ngram
listlengths
0
82k
[ "for i in range(len(self.points)): self.dists += [np.linalg.norm( self.points[i] - self.points[(i+1)", "self.points = points self.n = len(self.points) self.dists = [0] for", "- self.dists[idx])/np.linalg.norm(self.points[(idx+1)%self.n]-self.points[idx]) return self.points[idx] + \\ mult*(self.points[(idx+1)%self.n]-self.points[idx]) def interpolate_index(self,dist): def", "(self.dists[(cur+1)%self.n] >= dist)) # binary search step_size=int(self.n / 4) cur=int(self.n", "else: cur += step_size step_size = max(int(step_size/2), 1) return cur", "step_size=int(self.n / 4) cur=int(self.n / 2) while not is_solution(cur): if", "dist: cur -= step_size else: cur += step_size step_size =", "self.n = len(self.points) self.dists = [0] for i in range(len(self.points)):", "return ((self.dists[cur] <= dist) and (self.dists[(cur+1)%self.n] >= dist)) # binary", "import bezier import numpy as np class VectorInterpolator: def __init__(self,points):", "idx == self.n-1: return self.dists[idx] <= dist else: return ((self.dists[cur]", "self.points[(i+1) % self.n] )+self.dists[i]] def interpolate(self,alpha): dist = alpha*self.dists[-1] idx", "= len(self.points) self.dists = [0] for i in range(len(self.points)): self.dists", "idx = self.interpolate_index(dist) mult = (dist - self.dists[idx])/np.linalg.norm(self.points[(idx+1)%self.n]-self.points[idx]) return self.points[idx]", "interpolate(self,alpha): dist = alpha*self.dists[-1] idx = self.interpolate_index(dist) mult = (dist", "<= dist) and (self.dists[(cur+1)%self.n] >= dist)) # binary search step_size=int(self.n", "# binary search step_size=int(self.n / 4) cur=int(self.n / 2) while", "[np.linalg.norm( self.points[i] - self.points[(i+1) % self.n] )+self.dists[i]] def interpolate(self,alpha): dist", "-= step_size else: cur += step_size step_size = max(int(step_size/2), 1)", "- self.points[(i+1) % self.n] )+self.dists[i]] def interpolate(self,alpha): dist = alpha*self.dists[-1]", "self.n] )+self.dists[i]] def interpolate(self,alpha): dist = alpha*self.dists[-1] idx = self.interpolate_index(dist)", "as np class VectorInterpolator: def __init__(self,points): self.points = points self.n", "<= dist else: return ((self.dists[cur] <= dist) and (self.dists[(cur+1)%self.n] >=", "interpolate_index(self,dist): def is_solution(idx): if idx == self.n-1: return self.dists[idx] <=", "self.dists = [0] for i in range(len(self.points)): self.dists += [np.linalg.norm(", "> dist: cur -= step_size else: cur += step_size step_size", "bezier import numpy as np class VectorInterpolator: def __init__(self,points): self.points", "def interpolate(self,alpha): dist = alpha*self.dists[-1] idx = self.interpolate_index(dist) mult =", "self.dists[idx] <= dist else: return ((self.dists[cur] <= dist) and (self.dists[(cur+1)%self.n]", "in range(len(self.points)): self.dists += [np.linalg.norm( self.points[i] - self.points[(i+1) % self.n]", "mult*(self.points[(idx+1)%self.n]-self.points[idx]) def interpolate_index(self,dist): def is_solution(idx): if idx == self.n-1: return", "dist) and (self.dists[(cur+1)%self.n] >= dist)) # binary search step_size=int(self.n /", "4) cur=int(self.n / 2) while not is_solution(cur): if self.dists[cur] >", "self.n-1: return self.dists[idx] <= dist else: return ((self.dists[cur] <= dist)", "/ 4) cur=int(self.n / 2) while not is_solution(cur): if self.dists[cur]", ")+self.dists[i]] def interpolate(self,alpha): dist = alpha*self.dists[-1] idx = self.interpolate_index(dist) mult", "\\ mult*(self.points[(idx+1)%self.n]-self.points[idx]) def interpolate_index(self,dist): def is_solution(idx): if idx == self.n-1:", "mult = (dist - self.dists[idx])/np.linalg.norm(self.points[(idx+1)%self.n]-self.points[idx]) return self.points[idx] + \\ mult*(self.points[(idx+1)%self.n]-self.points[idx])", "is_solution(idx): if idx == self.n-1: return self.dists[idx] <= dist else:", "while not is_solution(cur): if self.dists[cur] > dist: cur -= step_size", "class VectorInterpolator: def __init__(self,points): self.points = points self.n = len(self.points)", "__init__(self,points): self.points = points self.n = len(self.points) self.dists = [0]", "len(self.points) self.dists = [0] for i in range(len(self.points)): self.dists +=", "VectorInterpolator: def __init__(self,points): self.points = points self.n = len(self.points) self.dists", "self.dists += [np.linalg.norm( self.points[i] - self.points[(i+1) % self.n] )+self.dists[i]] def", "step_size else: cur += step_size step_size = max(int(step_size/2), 1) return", "not is_solution(cur): if self.dists[cur] > dist: cur -= step_size else:", "cur=int(self.n / 2) while not is_solution(cur): if self.dists[cur] > dist:", "is_solution(cur): if self.dists[cur] > dist: cur -= step_size else: cur", ">= dist)) # binary search step_size=int(self.n / 4) cur=int(self.n /", "points self.n = len(self.points) self.dists = [0] for i in", "search step_size=int(self.n / 4) cur=int(self.n / 2) while not is_solution(cur):", "2) while not is_solution(cur): if self.dists[cur] > dist: cur -=", "= self.interpolate_index(dist) mult = (dist - self.dists[idx])/np.linalg.norm(self.points[(idx+1)%self.n]-self.points[idx]) return self.points[idx] +", "manimlib.imports import * from manimlib.utils import bezier import numpy as", "alpha*self.dists[-1] idx = self.interpolate_index(dist) mult = (dist - self.dists[idx])/np.linalg.norm(self.points[(idx+1)%self.n]-self.points[idx]) return", "dist = alpha*self.dists[-1] idx = self.interpolate_index(dist) mult = (dist -", "(dist - self.dists[idx])/np.linalg.norm(self.points[(idx+1)%self.n]-self.points[idx]) return self.points[idx] + \\ mult*(self.points[(idx+1)%self.n]-self.points[idx]) def interpolate_index(self,dist):", "def interpolate_index(self,dist): def is_solution(idx): if idx == self.n-1: return self.dists[idx]", "= points self.n = len(self.points) self.dists = [0] for i", "np class VectorInterpolator: def __init__(self,points): self.points = points self.n =", "if idx == self.n-1: return self.dists[idx] <= dist else: return", "else: return ((self.dists[cur] <= dist) and (self.dists[(cur+1)%self.n] >= dist)) #", "self.points[i] - self.points[(i+1) % self.n] )+self.dists[i]] def interpolate(self,alpha): dist =", "% self.n] )+self.dists[i]] def interpolate(self,alpha): dist = alpha*self.dists[-1] idx =", "self.dists[idx])/np.linalg.norm(self.points[(idx+1)%self.n]-self.points[idx]) return self.points[idx] + \\ mult*(self.points[(idx+1)%self.n]-self.points[idx]) def interpolate_index(self,dist): def is_solution(idx):", "from manimlib.imports import * from manimlib.utils import bezier import numpy", "self.points[idx] + \\ mult*(self.points[(idx+1)%self.n]-self.points[idx]) def interpolate_index(self,dist): def is_solution(idx): if idx", "dist)) # binary search step_size=int(self.n / 4) cur=int(self.n / 2)", "def is_solution(idx): if idx == self.n-1: return self.dists[idx] <= dist", "manimlib.utils import bezier import numpy as np class VectorInterpolator: def", "return self.points[idx] + \\ mult*(self.points[(idx+1)%self.n]-self.points[idx]) def interpolate_index(self,dist): def is_solution(idx): if", "def __init__(self,points): self.points = points self.n = len(self.points) self.dists =", "and (self.dists[(cur+1)%self.n] >= dist)) # binary search step_size=int(self.n / 4)", "== self.n-1: return self.dists[idx] <= dist else: return ((self.dists[cur] <=", "range(len(self.points)): self.dists += [np.linalg.norm( self.points[i] - self.points[(i+1) % self.n] )+self.dists[i]]", "if self.dists[cur] > dist: cur -= step_size else: cur +=", "self.dists[cur] > dist: cur -= step_size else: cur += step_size", "((self.dists[cur] <= dist) and (self.dists[(cur+1)%self.n] >= dist)) # binary search", "/ 2) while not is_solution(cur): if self.dists[cur] > dist: cur", "return self.dists[idx] <= dist else: return ((self.dists[cur] <= dist) and", "from manimlib.utils import bezier import numpy as np class VectorInterpolator:", "+ \\ mult*(self.points[(idx+1)%self.n]-self.points[idx]) def interpolate_index(self,dist): def is_solution(idx): if idx ==", "= (dist - self.dists[idx])/np.linalg.norm(self.points[(idx+1)%self.n]-self.points[idx]) return self.points[idx] + \\ mult*(self.points[(idx+1)%self.n]-self.points[idx]) def", "= [0] for i in range(len(self.points)): self.dists += [np.linalg.norm( self.points[i]", "import * from manimlib.utils import bezier import numpy as np", "import numpy as np class VectorInterpolator: def __init__(self,points): self.points =", "cur -= step_size else: cur += step_size step_size = max(int(step_size/2),", "= alpha*self.dists[-1] idx = self.interpolate_index(dist) mult = (dist - self.dists[idx])/np.linalg.norm(self.points[(idx+1)%self.n]-self.points[idx])", "self.interpolate_index(dist) mult = (dist - self.dists[idx])/np.linalg.norm(self.points[(idx+1)%self.n]-self.points[idx]) return self.points[idx] + \\", "numpy as np class VectorInterpolator: def __init__(self,points): self.points = points", "binary search step_size=int(self.n / 4) cur=int(self.n / 2) while not", "+= [np.linalg.norm( self.points[i] - self.points[(i+1) % self.n] )+self.dists[i]] def interpolate(self,alpha):", "dist else: return ((self.dists[cur] <= dist) and (self.dists[(cur+1)%self.n] >= dist))", "* from manimlib.utils import bezier import numpy as np class", "i in range(len(self.points)): self.dists += [np.linalg.norm( self.points[i] - self.points[(i+1) %", "[0] for i in range(len(self.points)): self.dists += [np.linalg.norm( self.points[i] -" ]
[ "from setuptools import setup setup(name='rapid_plotly', version='0.1', description='Convenience functions to rapidly", "setuptools import setup setup(name='rapid_plotly', version='0.1', description='Convenience functions to rapidly create", "setup(name='rapid_plotly', version='0.1', description='Convenience functions to rapidly create beautiful Plotly graphs',", "functions to rapidly create beautiful Plotly graphs', author='<NAME>', author_email='<EMAIL>', packages=['rapid_plotly'],", "import setup setup(name='rapid_plotly', version='0.1', description='Convenience functions to rapidly create beautiful", "to rapidly create beautiful Plotly graphs', author='<NAME>', author_email='<EMAIL>', packages=['rapid_plotly'], zip_safe=False)", "version='0.1', description='Convenience functions to rapidly create beautiful Plotly graphs', author='<NAME>',", "setup setup(name='rapid_plotly', version='0.1', description='Convenience functions to rapidly create beautiful Plotly", "description='Convenience functions to rapidly create beautiful Plotly graphs', author='<NAME>', author_email='<EMAIL>'," ]
[ "in this file to have the include cache updated #", "line.strip() if line.startswith(\"#INCLUDE\"): include_directive_tokens = line.split(maxsplit=1) if len(include_directive_tokens) > 1:", "file # and we are using a single cache file", "Path) -> Optional[List[Path]]: if not exists(bml_includes_cache_file): return None with open(bml_includes_cache_file,", "OS neutral compared to running a shell command copyfile(src_css_file, css_basename)", "\".html\") for bml_path in input_bml_file_paths: bml_deps = read_bml_includes_cache(bml_path) if bml_deps", "html_output_path(bml_path: Path) -> Path: return Path(splitext(bml_path)[0] + \".html\") for bml_path", "None: copyfile(dependencies[0], targets[0]) for src, dst in [(src_file, dst_file), (css_file,", "bml file # for new include directives every time a", "Path, bml_deps: List[Path]): existing_deps = {} if exists(bml_includes_cache_file): with open(bml_includes_cache_file,", "update_bml_includes_cache(bml_path, bml_deps) for bml_path in input_bml_file_paths: # We don't use", "(css_file, dst_css)]: yield { 'name': basename(src), 'actions': [copy_file], 'file_dep': [src],", "else: return None # Manually edited perhaps (assuming we got", "-> Iterator[Path]: for line in file_handle.readlines(): line = line.strip() if", "are using the order of the tasks in this file", "with open(bml_path, encoding='utf-8') as f: unique_deps = {include for include", "= Path(join(bml_tools_dir, css_basename)) def copy_file() -> None: # OS neutral", "`pip install [--user] doit` adds `doit.exe` to the PATH #", "= \"bml.css\" src_css_file = Path(join(bml_tools_dir, css_basename)) def copy_file() -> None:", "tasks in this file to have the include cache updated", "got the task order correct) def update_bml_includes_cache(bml_path: Path, bml_deps: List[Path]):", "{ 'name': basename(src), 'actions': [copy_file], 'file_dep': [src], 'targets': [dst], 'title':", "def bml_include_dependencies(bml_path: Path) -> List[Path]: # bml files can include", "We don't use a target as doit cannot deal with", "in [(src_file, dst_file), (css_file, dst_css)]: yield { 'name': basename(src), 'actions':", "doit file_dep dependency as it is being updated # by", "Exception: pass existing_deps[bml_path] = bml_deps with open(bml_includes_cache_file, \"w\", encoding='utf-8') as", "= bml_include_dependencies(bml_path) update_bml_includes_cache(bml_path, bml_deps) yield { 'name': basename(bml_path), 'actions': [f\"python", "# Manually edited messed up json perhaps return None if", "html file from bridge bidding markup language file.\"\"\" bml2html_path =", "/usr/bin/doit -f # https://pydoit.org # `pip install [--user] doit` adds", "a single cache file instead of one cache file per", "\"\"\"Create html file from bridge bidding markup language file.\"\"\" bml2html_path", "Path(join(bml_tools_dir, css_basename)) def copy_file() -> None: # OS neutral compared", "task_publish_main_bidding(): \"\"\"Copy the main bidding html and css document to", "bml_deps with open(bml_includes_cache_file, \"w\", encoding='utf-8') as f: json.dump(existing_deps, f, indent=4)", "bml_path in existing_deps: return existing_deps[bml_path] else: return None # Manually", "return existing_deps[bml_path] else: return None # Manually edited perhaps (assuming", "free form path string included_file = include_directive_tokens[1].strip() yield Path(included_file) with", "the PATH # - Note `doit auto`, the file watcher", "edited perhaps (assuming we got the task order correct) def", "# before the html task reads the include cache as", "as f: try: existing_deps = json.load(f) except Exception: pass existing_deps[bml_path]", "Linux/Mac # - All commands are relative to dodo.py (doit", "enough. yield { 'name': basename(bml_path), 'actions': [(calc_include_deps_and_cache, [bml_path])], 'file_dep': [bml_path],", "if not exists(bml_includes_cache_file): return None with open(bml_includes_cache_file, encoding='utf-8') as f:", "the file name is not quoted, just a free form", "the tasks in this file to have the include cache", "css_file = \"bml.css\" dst_css = f\"W:/{css_file}\" def copy_file(dependencies, targets) ->", "changing file dependencies # The html task itself cannot use", "title_with_actions } def task_publish_main_bidding(): \"\"\"Copy the main bidding html and", "same output file # and we are using a single", "bml_include_dependencies(bml_path: Path) -> List[Path]: # bml files can include others,", "return None # Manually edited perhaps (assuming we got the", "{bml2html_path} {bml_path}\"], 'file_dep': [bml_path] + bml_deps, 'targets': [html_output_path(bml_path)], 'title': title_with_actions", "and css document to the web server root.\"\"\" src_file =", "cache.\"\"\" input_bml_file_paths = glob(\"*.bml\") def calc_include_deps_and_cache(file_dep) -> None: bml_path =", "\"bml.css\" src_css_file = Path(join(bml_tools_dir, css_basename)) def copy_file() -> None: #", "os import environ from os.path import abspath, basename, dirname, exists,", "only works on Linux/Mac # - All commands are relative", "https://pydoit.org # `pip install [--user] doit` adds `doit.exe` to the", "the include cache updated # before the html task reads", "import abspath, basename, dirname, exists, expanduser, join, splitext from shutil", "# This does mean that we are using the order", "style sheet to this directory.\"\"\" css_basename = \"bml.css\" src_css_file =", "Path(file_dep) bml_deps = bml_include_dependencies(bml_path) update_bml_includes_cache(bml_path, bml_deps) for bml_path in input_bml_file_paths:", "and we are using a single cache file instead of", "with more than one input file affecting the same output", "open(bml_path, encoding='utf-8') as f: unique_deps = {include for include in", "include in includes(f) if include != bml_path} return list(unique_deps) def", "Iterator, List, NewType, Optional from doit.tools import title_with_actions Path =", "different notion of an update (not just tracking file modifications)", "[bml_path] + bml_deps, 'targets': [html_output_path(bml_path)], 'title': title_with_actions } def task_bmlcss():", "file changes. # Actually, using a different notion of an", "of dodo.py # even if ran from a different directory", "are using a single cache file instead of one cache", "[css_basename], 'title': title_with_actions } def task_publish_main_bidding(): \"\"\"Copy the main bidding", "shell command copyfile(src_css_file, css_basename) return { 'actions': [copy_file], 'file_dep': [src_css_file],", "This does mean that we are using the order of", "# We assume the file name is not quoted, just", "src, dst in [(src_file, dst_file), (css_file, dst_css)]: yield { 'name':", "we got the task order correct) def update_bml_includes_cache(bml_path: Path, bml_deps:", "cache as part of determining changing file dependencies # The", "the bml CSS style sheet to this directory.\"\"\" css_basename =", "name is not quoted, just a free form path string", "= line.split(maxsplit=1) if len(include_directive_tokens) > 1: # We assume the", "a doit file_dep dependency as it is being updated #", "if line.startswith(\"#INCLUDE\"): include_directive_tokens = line.split(maxsplit=1) if len(include_directive_tokens) > 1: #", "# - All commands are relative to dodo.py (doit runs", "1: # We assume the file name is not quoted,", "input_bml_file_paths = glob(\"*.bml\") def calc_include_deps_and_cache(file_dep) -> None: bml_path = Path(file_dep)", "title_with_actions } def task_bmlcss(): \"\"\"Copy the bml CSS style sheet", "using a single cache file instead of one cache file", "compared to running a shell command copyfile(src_css_file, css_basename) return {", "different directory `doit -f path/to/dodo.py`) from glob import glob import", "include_directive_tokens = line.split(maxsplit=1) if len(include_directive_tokens) > 1: # We assume", "(not just tracking file modifications) if another feature of #", "as part of determining changing file dependencies # The html", "{} if exists(bml_includes_cache_file): with open(bml_includes_cache_file, encoding='utf-8') as f: try: existing_deps", "json.load(f) except Exception: pass existing_deps[bml_path] = bml_deps with open(bml_includes_cache_file, \"w\",", "document to the web server root.\"\"\" src_file = \"bidding-system.html\" dst_file", "\"\"\"Populate the bml include cache.\"\"\" input_bml_file_paths = glob(\"*.bml\") def calc_include_deps_and_cache(file_dep)", "json.load(f) except Exception: # Manually edited messed up json perhaps", "file to have the include cache updated # before the", "task_bmlcss(): \"\"\"Copy the bml CSS style sheet to this directory.\"\"\"", "per input file. # This does mean that we are", "to the PATH # - Note `doit auto`, the file", "path/to/dodo.py`) from glob import glob import json from os import", "= {} if exists(bml_includes_cache_file): with open(bml_includes_cache_file, encoding='utf-8') as f: try:", "} def task_bml2html(): \"\"\"Create html file from bridge bidding markup", "= f\"W:/{css_file}\" def copy_file(dependencies, targets) -> None: copyfile(dependencies[0], targets[0]) for", "not quoted, just a free form path string included_file =", "= Path(join(bml_tools_dir, \"bml2html.py\")) input_bml_file_paths = glob(\"*.bml\") def html_output_path(bml_path: Path) ->", "bml CSS style sheet to this directory.\"\"\" css_basename = \"bml.css\"", "# `pip install [--user] doit` adds `doit.exe` to the PATH", "join, splitext from shutil import copyfile from typing import Iterator,", "bml files can include others, so spend time scanning every", "glob(\"*.bml\") def html_output_path(bml_path: Path) -> Path: return Path(splitext(bml_path)[0] + \".html\")", "read_bml_includes_cache(bml_path: Path) -> Optional[List[Path]]: if not exists(bml_includes_cache_file): return None with", "input file affecting the same output file # and we", "glob import glob import json from os import environ from", "file.\"\"\" bml2html_path = Path(join(bml_tools_dir, \"bml2html.py\")) input_bml_file_paths = glob(\"*.bml\") def html_output_path(bml_path:", "changes. # Actually, using a different notion of an update", "file is saved def includes(file_handle) -> Iterator[Path]: for line in", "as a doit file_dep dependency as it is being updated", "an update (not just tracking file modifications) if another feature", "# OS neutral compared to running a shell command copyfile(src_css_file,", "file as a doit file_dep dependency as it is being", "feature of # doit that could be applied if interested", "of an update (not just tracking file modifications) if another", "def copy_file() -> None: # OS neutral compared to running", "just tracking file modifications) if another feature of # doit", "None # Manually edited perhaps (assuming we got the task", "that could be applied if interested enough. yield { 'name':", "{ 'name': basename(bml_path), 'actions': [f\"python {bml2html_path} {bml_path}\"], 'file_dep': [bml_path] +", "unique_deps = {include for include in includes(f) if include !=", "f: try: existing_deps = json.load(f) except Exception: pass existing_deps[bml_path] =", "def task_bmlcss(): \"\"\"Copy the bml CSS style sheet to this", "basename(src), 'actions': [copy_file], 'file_dep': [src], 'targets': [dst], 'title': title_with_actions }", "server root.\"\"\" src_file = \"bidding-system.html\" dst_file = f\"W:/{src_file}\" css_file =", "edited messed up json perhaps return None if bml_path in", "single cache file instead of one cache file per input", "Manually edited messed up json perhaps return None if bml_path", "[(calc_include_deps_and_cache, [bml_path])], 'file_dep': [bml_path], 'title': title_with_actions } def task_bml2html(): \"\"\"Create", "return Path(splitext(bml_path)[0] + \".html\") for bml_path in input_bml_file_paths: bml_deps =", "def read_bml_includes_cache(bml_path: Path) -> Optional[List[Path]]: if not exists(bml_includes_cache_file): return None", "\".include-deps.json\" def bml_include_dependencies(bml_path: Path) -> List[Path]: # bml files can", "commands are relative to dodo.py (doit runs in the working", "basename, dirname, exists, expanduser, join, splitext from shutil import copyfile", "cannot use the include cache file as a doit file_dep", "if another feature of # doit that could be applied", "from bridge bidding markup language file.\"\"\" bml2html_path = Path(join(bml_tools_dir, \"bml2html.py\"))", "- All commands are relative to dodo.py (doit runs in", "install [--user] doit` adds `doit.exe` to the PATH # -", "for bml_path in input_bml_file_paths: bml_deps = read_bml_includes_cache(bml_path) if bml_deps is", "task_bml_include_cache(): \"\"\"Populate the bml include cache.\"\"\" input_bml_file_paths = glob(\"*.bml\") def", "doit that could be applied if interested enough. yield {", "NewType(\"Path\", str) home = Path(expanduser(\"~\")) bml_tools_dir = Path(environ.get(\"BML_TOOLS_DIRECTORY\", join(home, \"dev/bml\")))", "cache file per input file. # This does mean that", "command copyfile(src_css_file, css_basename) return { 'actions': [copy_file], 'file_dep': [src_css_file], 'targets':", "quoted, just a free form path string included_file = include_directive_tokens[1].strip()", "Path) -> List[Path]: # bml files can include others, so", "the html task reads the include cache as part of", "doit cannot deal with more than one input file affecting", "tracking file modifications) if another feature of # doit that", "directory.\"\"\" css_basename = \"bml.css\" src_css_file = Path(join(bml_tools_dir, css_basename)) def copy_file()", "the same output file # and we are using a", "bml_deps = bml_include_dependencies(bml_path) update_bml_includes_cache(bml_path, bml_deps) yield { 'name': basename(bml_path), 'actions':", "'targets': [html_output_path(bml_path)], 'title': title_with_actions } def task_bmlcss(): \"\"\"Copy the bml", "up json perhaps return None if bml_path in existing_deps: return", "basename(bml_path), 'actions': [(calc_include_deps_and_cache, [bml_path])], 'file_dep': [bml_path], 'title': title_with_actions } def", "we are using the order of the tasks in this", "basename(bml_path), 'actions': [f\"python {bml2html_path} {bml_path}\"], 'file_dep': [bml_path] + bml_deps, 'targets':", "= Path(environ.get(\"BML_TOOLS_DIRECTORY\", join(home, \"dev/bml\"))) bml_includes_cache_file = \".include-deps.json\" def bml_include_dependencies(bml_path: Path)", "= \"bidding-system.html\" dst_file = f\"W:/{src_file}\" css_file = \"bml.css\" dst_css =", "open(bml_includes_cache_file, encoding='utf-8') as f: try: existing_deps = json.load(f) except Exception:", "time a bml file is saved def includes(file_handle) -> Iterator[Path]:", "cannot deal with more than one input file affecting the", "Path: return Path(splitext(bml_path)[0] + \".html\") for bml_path in input_bml_file_paths: bml_deps", "perhaps (assuming we got the task order correct) def update_bml_includes_cache(bml_path:", "PATH # - Note `doit auto`, the file watcher only", "existing_deps = json.load(f) except Exception: # Manually edited messed up", "Actually, using a different notion of an update (not just", "'title': title_with_actions } def task_bml2html(): \"\"\"Create html file from bridge", "'name': basename(bml_path), 'actions': [f\"python {bml2html_path} {bml_path}\"], 'file_dep': [bml_path] + bml_deps,", "include cache file as a doit file_dep dependency as it", "{bml_path}\"], 'file_dep': [bml_path] + bml_deps, 'targets': [html_output_path(bml_path)], 'title': title_with_actions }", "yield Path(included_file) with open(bml_path, encoding='utf-8') as f: unique_deps = {include", "is saved def includes(file_handle) -> Iterator[Path]: for line in file_handle.readlines():", "every bml file # for new include directives every time", "deal with more than one input file affecting the same", "string included_file = include_directive_tokens[1].strip() yield Path(included_file) with open(bml_path, encoding='utf-8') as", "task itself cannot use the include cache file as a", "title_with_actions } def task_bml2html(): \"\"\"Create html file from bridge bidding", "from shutil import copyfile from typing import Iterator, List, NewType,", "`doit -f path/to/dodo.py`) from glob import glob import json from", "input_bml_file_paths = glob(\"*.bml\") def html_output_path(bml_path: Path) -> Path: return Path(splitext(bml_path)[0]", "the working dir of dodo.py # even if ran from", "-> List[Path]: # bml files can include others, so spend", "= f\"W:/{src_file}\" css_file = \"bml.css\" dst_css = f\"W:/{css_file}\" def copy_file(dependencies,", "List[Path]): existing_deps = {} if exists(bml_includes_cache_file): with open(bml_includes_cache_file, encoding='utf-8') as", "task order correct) def update_bml_includes_cache(bml_path: Path, bml_deps: List[Path]): existing_deps =", "bml_deps = bml_include_dependencies(bml_path) update_bml_includes_cache(bml_path, bml_deps) for bml_path in input_bml_file_paths: #", "[bml_path])], 'file_dep': [bml_path], 'title': title_with_actions } def task_bml2html(): \"\"\"Create html", "being updated # by other unrelated bml file changes. #", "glob(\"*.bml\") def calc_include_deps_and_cache(file_dep) -> None: bml_path = Path(file_dep) bml_deps =", "\"dev/bml\"))) bml_includes_cache_file = \".include-deps.json\" def bml_include_dependencies(bml_path: Path) -> List[Path]: #", "main bidding html and css document to the web server", "dst_css = f\"W:/{css_file}\" def copy_file(dependencies, targets) -> None: copyfile(dependencies[0], targets[0])", "copyfile(dependencies[0], targets[0]) for src, dst in [(src_file, dst_file), (css_file, dst_css)]:", "src_css_file = Path(join(bml_tools_dir, css_basename)) def copy_file() -> None: # OS", "f\"W:/{css_file}\" def copy_file(dependencies, targets) -> None: copyfile(dependencies[0], targets[0]) for src,", "-f # https://pydoit.org # `pip install [--user] doit` adds `doit.exe`", "indent=4) def task_bml_include_cache(): \"\"\"Populate the bml include cache.\"\"\" input_bml_file_paths =", "of one cache file per input file. # This does", "cache updated # before the html task reads the include", "as f: unique_deps = {include for include in includes(f) if", "# doit that could be applied if interested enough. yield", "update_bml_includes_cache(bml_path: Path, bml_deps: List[Path]): existing_deps = {} if exists(bml_includes_cache_file): with", "affecting the same output file # and we are using", "this file to have the include cache updated # before", "src_file = \"bidding-system.html\" dst_file = f\"W:/{src_file}\" css_file = \"bml.css\" dst_css", "unrelated bml file changes. # Actually, using a different notion", "+ bml_deps, 'targets': [html_output_path(bml_path)], 'title': title_with_actions } def task_bmlcss(): \"\"\"Copy", "includes(file_handle) -> Iterator[Path]: for line in file_handle.readlines(): line = line.strip()", "don't use a target as doit cannot deal with more", "exists(bml_includes_cache_file): with open(bml_includes_cache_file, encoding='utf-8') as f: try: existing_deps = json.load(f)", "use a target as doit cannot deal with more than", "environ from os.path import abspath, basename, dirname, exists, expanduser, join,", "as it is being updated # by other unrelated bml", "\"\"\"Copy the bml CSS style sheet to this directory.\"\"\" css_basename", "return { 'actions': [copy_file], 'file_dep': [src_css_file], 'targets': [css_basename], 'title': title_with_actions", "def copy_file(dependencies, targets) -> None: copyfile(dependencies[0], targets[0]) for src, dst", "{ 'actions': [copy_file], 'file_dep': [src_css_file], 'targets': [css_basename], 'title': title_with_actions }", "auto`, the file watcher only works on Linux/Mac # -", "= \"bml.css\" dst_css = f\"W:/{css_file}\" def copy_file(dependencies, targets) -> None:", "import environ from os.path import abspath, basename, dirname, exists, expanduser,", "\"w\", encoding='utf-8') as f: json.dump(existing_deps, f, indent=4) def task_bml_include_cache(): \"\"\"Populate", "path string included_file = include_directive_tokens[1].strip() yield Path(included_file) with open(bml_path, encoding='utf-8')", "= include_directive_tokens[1].strip() yield Path(included_file) with open(bml_path, encoding='utf-8') as f: unique_deps", "if interested enough. yield { 'name': basename(bml_path), 'actions': [(calc_include_deps_and_cache, [bml_path])],", "include cache.\"\"\" input_bml_file_paths = glob(\"*.bml\") def calc_include_deps_and_cache(file_dep) -> None: bml_path", "copyfile from typing import Iterator, List, NewType, Optional from doit.tools", "have the include cache updated # before the html task", "in existing_deps: return existing_deps[bml_path] else: return None # Manually edited", "= bml_deps with open(bml_includes_cache_file, \"w\", encoding='utf-8') as f: json.dump(existing_deps, f,", "All commands are relative to dodo.py (doit runs in the", "if len(include_directive_tokens) > 1: # We assume the file name", "def calc_include_deps_and_cache(file_dep) -> None: bml_path = Path(file_dep) bml_deps = bml_include_dependencies(bml_path)", "dependency as it is being updated # by other unrelated", "= line.strip() if line.startswith(\"#INCLUDE\"): include_directive_tokens = line.split(maxsplit=1) if len(include_directive_tokens) >", "f: unique_deps = {include for include in includes(f) if include", "'title': title_with_actions } def task_bmlcss(): \"\"\"Copy the bml CSS style", "import json from os import environ from os.path import abspath,", "on Linux/Mac # - All commands are relative to dodo.py", "language file.\"\"\" bml2html_path = Path(join(bml_tools_dir, \"bml2html.py\")) input_bml_file_paths = glob(\"*.bml\") def", "does mean that we are using the order of the", "can include others, so spend time scanning every bml file", "from typing import Iterator, List, NewType, Optional from doit.tools import", "> 1: # We assume the file name is not", "home = Path(expanduser(\"~\")) bml_tools_dir = Path(environ.get(\"BML_TOOLS_DIRECTORY\", join(home, \"dev/bml\"))) bml_includes_cache_file =", "'title': title_with_actions } def task_publish_main_bidding(): \"\"\"Copy the main bidding html", "'name': basename(bml_path), 'actions': [(calc_include_deps_and_cache, [bml_path])], 'file_dep': [bml_path], 'title': title_with_actions }", "html task reads the include cache as part of determining", "just a free form path string included_file = include_directive_tokens[1].strip() yield", "line = line.strip() if line.startswith(\"#INCLUDE\"): include_directive_tokens = line.split(maxsplit=1) if len(include_directive_tokens)", "bml2html_path = Path(join(bml_tools_dir, \"bml2html.py\")) input_bml_file_paths = glob(\"*.bml\") def html_output_path(bml_path: Path)", "# and we are using a single cache file instead", "assume the file name is not quoted, just a free", "html and css document to the web server root.\"\"\" src_file", "[--user] doit` adds `doit.exe` to the PATH # - Note", "bml_deps) for bml_path in input_bml_file_paths: # We don't use a", "dependencies # The html task itself cannot use the include", "update (not just tracking file modifications) if another feature of", "from doit.tools import title_with_actions Path = NewType(\"Path\", str) home =", "yield { 'name': basename(bml_path), 'actions': [f\"python {bml2html_path} {bml_path}\"], 'file_dep': [bml_path]", "from os import environ from os.path import abspath, basename, dirname,", "from a different directory `doit -f path/to/dodo.py`) from glob import", "directory `doit -f path/to/dodo.py`) from glob import glob import json", "the bml include cache.\"\"\" input_bml_file_paths = glob(\"*.bml\") def calc_include_deps_and_cache(file_dep) ->", "encoding='utf-8') as f: try: existing_deps = json.load(f) except Exception: #", "a different directory `doit -f path/to/dodo.py`) from glob import glob", "Optional from doit.tools import title_with_actions Path = NewType(\"Path\", str) home", "glob import json from os import environ from os.path import", "it is being updated # by other unrelated bml file", "use the include cache file as a doit file_dep dependency", "'file_dep': [bml_path] + bml_deps, 'targets': [html_output_path(bml_path)], 'title': title_with_actions } def", "= bml_include_dependencies(bml_path) update_bml_includes_cache(bml_path, bml_deps) for bml_path in input_bml_file_paths: # We", "# Manually edited perhaps (assuming we got the task order", "existing_deps[bml_path] else: return None # Manually edited perhaps (assuming we", "f: json.dump(existing_deps, f, indent=4) def task_bml_include_cache(): \"\"\"Populate the bml include", "def includes(file_handle) -> Iterator[Path]: for line in file_handle.readlines(): line =", "one cache file per input file. # This does mean", "'file_dep': [bml_path], 'title': title_with_actions } def task_bml2html(): \"\"\"Create html file", "bml_deps) yield { 'name': basename(bml_path), 'actions': [f\"python {bml2html_path} {bml_path}\"], 'file_dep':", "dirname, exists, expanduser, join, splitext from shutil import copyfile from", "= {include for include in includes(f) if include != bml_path}", "order of the tasks in this file to have the", "bml_path in input_bml_file_paths: # We don't use a target as", "of determining changing file dependencies # The html task itself", "with open(bml_includes_cache_file, encoding='utf-8') as f: try: existing_deps = json.load(f) except", "input_bml_file_paths: bml_deps = read_bml_includes_cache(bml_path) if bml_deps is None: bml_deps =", "= read_bml_includes_cache(bml_path) if bml_deps is None: bml_deps = bml_include_dependencies(bml_path) update_bml_includes_cache(bml_path,", "bml_path in input_bml_file_paths: bml_deps = read_bml_includes_cache(bml_path) if bml_deps is None:", "title_with_actions Path = NewType(\"Path\", str) home = Path(expanduser(\"~\")) bml_tools_dir =", "bml include cache.\"\"\" input_bml_file_paths = glob(\"*.bml\") def calc_include_deps_and_cache(file_dep) -> None:", "import title_with_actions Path = NewType(\"Path\", str) home = Path(expanduser(\"~\")) bml_tools_dir", "if exists(bml_includes_cache_file): with open(bml_includes_cache_file, encoding='utf-8') as f: try: existing_deps =", "We assume the file name is not quoted, just a", "mean that we are using the order of the tasks", "another feature of # doit that could be applied if", "file_handle.readlines(): line = line.strip() if line.startswith(\"#INCLUDE\"): include_directive_tokens = line.split(maxsplit=1) if", "} def task_bmlcss(): \"\"\"Copy the bml CSS style sheet to", "from glob import glob import json from os import environ", "input file. # This does mean that we are using", "file dependencies # The html task itself cannot use the", "bml_path} return list(unique_deps) def read_bml_includes_cache(bml_path: Path) -> Optional[List[Path]]: if not", "task_bml2html(): \"\"\"Create html file from bridge bidding markup language file.\"\"\"", "'actions': [copy_file], 'file_dep': [src_css_file], 'targets': [css_basename], 'title': title_with_actions } def", "using the order of the tasks in this file to", "file per input file. # This does mean that we", "shutil import copyfile from typing import Iterator, List, NewType, Optional", "json perhaps return None if bml_path in existing_deps: return existing_deps[bml_path]", "update_bml_includes_cache(bml_path, bml_deps) yield { 'name': basename(bml_path), 'actions': [f\"python {bml2html_path} {bml_path}\"],", "targets) -> None: copyfile(dependencies[0], targets[0]) for src, dst in [(src_file,", "as f: try: existing_deps = json.load(f) except Exception: # Manually", "- Note `doit auto`, the file watcher only works on", "css_basename) return { 'actions': [copy_file], 'file_dep': [src_css_file], 'targets': [css_basename], 'title':", "included_file = include_directive_tokens[1].strip() yield Path(included_file) with open(bml_path, encoding='utf-8') as f:", "include cache updated # before the html task reads the", "dst in [(src_file, dst_file), (css_file, dst_css)]: yield { 'name': basename(src),", "= json.load(f) except Exception: pass existing_deps[bml_path] = bml_deps with open(bml_includes_cache_file,", "the include cache file as a doit file_dep dependency as", "target as doit cannot deal with more than one input", "is being updated # by other unrelated bml file changes.", "file name is not quoted, just a free form path", "\"bml.css\" dst_css = f\"W:/{css_file}\" def copy_file(dependencies, targets) -> None: copyfile(dependencies[0],", "css document to the web server root.\"\"\" src_file = \"bidding-system.html\"", "file from bridge bidding markup language file.\"\"\" bml2html_path = Path(join(bml_tools_dir,", "doit.tools import title_with_actions Path = NewType(\"Path\", str) home = Path(expanduser(\"~\"))", "exists, expanduser, join, splitext from shutil import copyfile from typing", "-> Optional[List[Path]]: if not exists(bml_includes_cache_file): return None with open(bml_includes_cache_file, encoding='utf-8')", "Note `doit auto`, the file watcher only works on Linux/Mac", "dodo.py # even if ran from a different directory `doit", "to running a shell command copyfile(src_css_file, css_basename) return { 'actions':", "modifications) if another feature of # doit that could be", "root.\"\"\" src_file = \"bidding-system.html\" dst_file = f\"W:/{src_file}\" css_file = \"bml.css\"", "doit` adds `doit.exe` to the PATH # - Note `doit", "{include for include in includes(f) if include != bml_path} return", "existing_deps = json.load(f) except Exception: pass existing_deps[bml_path] = bml_deps with", "cache file instead of one cache file per input file.", "that we are using the order of the tasks in", "line in file_handle.readlines(): line = line.strip() if line.startswith(\"#INCLUDE\"): include_directive_tokens =", "a target as doit cannot deal with more than one", "relative to dodo.py (doit runs in the working dir of", "time scanning every bml file # for new include directives", "encoding='utf-8') as f: json.dump(existing_deps, f, indent=4) def task_bml_include_cache(): \"\"\"Populate the", "#! /usr/bin/doit -f # https://pydoit.org # `pip install [--user] doit`", "# bml files can include others, so spend time scanning", "spend time scanning every bml file # for new include", "Path(included_file) with open(bml_path, encoding='utf-8') as f: unique_deps = {include for", "scanning every bml file # for new include directives every", "in the working dir of dodo.py # even if ran", "for src, dst in [(src_file, dst_file), (css_file, dst_css)]: yield {", "in file_handle.readlines(): line = line.strip() if line.startswith(\"#INCLUDE\"): include_directive_tokens = line.split(maxsplit=1)", "form path string included_file = include_directive_tokens[1].strip() yield Path(included_file) with open(bml_path,", "`doit auto`, the file watcher only works on Linux/Mac #", "to the web server root.\"\"\" src_file = \"bidding-system.html\" dst_file =", "expanduser, join, splitext from shutil import copyfile from typing import", "-f path/to/dodo.py`) from glob import glob import json from os", "splitext from shutil import copyfile from typing import Iterator, List,", "List, NewType, Optional from doit.tools import title_with_actions Path = NewType(\"Path\",", "if ran from a different directory `doit -f path/to/dodo.py`) from", "f, indent=4) def task_bml_include_cache(): \"\"\"Populate the bml include cache.\"\"\" input_bml_file_paths", "open(bml_includes_cache_file, \"w\", encoding='utf-8') as f: json.dump(existing_deps, f, indent=4) def task_bml_include_cache():", "includes(f) if include != bml_path} return list(unique_deps) def read_bml_includes_cache(bml_path: Path)", "of the tasks in this file to have the include", "\"bml2html.py\")) input_bml_file_paths = glob(\"*.bml\") def html_output_path(bml_path: Path) -> Path: return", "css_basename)) def copy_file() -> None: # OS neutral compared to", "we are using a single cache file instead of one", "(doit runs in the working dir of dodo.py # even", "input_bml_file_paths: # We don't use a target as doit cannot", "others, so spend time scanning every bml file # for", "file affecting the same output file # and we are", "# Actually, using a different notion of an update (not", "bml_includes_cache_file = \".include-deps.json\" def bml_include_dependencies(bml_path: Path) -> List[Path]: # bml", "is None: bml_deps = bml_include_dependencies(bml_path) update_bml_includes_cache(bml_path, bml_deps) yield { 'name':", "existing_deps: return existing_deps[bml_path] else: return None # Manually edited perhaps", "yield { 'name': basename(bml_path), 'actions': [(calc_include_deps_and_cache, [bml_path])], 'file_dep': [bml_path], 'title':", "except Exception: # Manually edited messed up json perhaps return", "the main bidding html and css document to the web", "-> None: bml_path = Path(file_dep) bml_deps = bml_include_dependencies(bml_path) update_bml_includes_cache(bml_path, bml_deps)", "`doit.exe` to the PATH # - Note `doit auto`, the", "bridge bidding markup language file.\"\"\" bml2html_path = Path(join(bml_tools_dir, \"bml2html.py\")) input_bml_file_paths", "bml_deps: List[Path]): existing_deps = {} if exists(bml_includes_cache_file): with open(bml_includes_cache_file, encoding='utf-8')", "encoding='utf-8') as f: unique_deps = {include for include in includes(f)", "more than one input file affecting the same output file", "so spend time scanning every bml file # for new", "correct) def update_bml_includes_cache(bml_path: Path, bml_deps: List[Path]): existing_deps = {} if", "updated # by other unrelated bml file changes. # Actually,", "bml_include_dependencies(bml_path) update_bml_includes_cache(bml_path, bml_deps) yield { 'name': basename(bml_path), 'actions': [f\"python {bml2html_path}", "output file # and we are using a single cache", "using a different notion of an update (not just tracking", "dst_file = f\"W:/{src_file}\" css_file = \"bml.css\" dst_css = f\"W:/{css_file}\" def", "runs in the working dir of dodo.py # even if", "include others, so spend time scanning every bml file #", "instead of one cache file per input file. # This", "bidding markup language file.\"\"\" bml2html_path = Path(join(bml_tools_dir, \"bml2html.py\")) input_bml_file_paths =", "in input_bml_file_paths: bml_deps = read_bml_includes_cache(bml_path) if bml_deps is None: bml_deps", "in input_bml_file_paths: # We don't use a target as doit", "-> None: # OS neutral compared to running a shell", "\"\"\"Copy the main bidding html and css document to the", "the order of the tasks in this file to have", "messed up json perhaps return None if bml_path in existing_deps:", "= glob(\"*.bml\") def calc_include_deps_and_cache(file_dep) -> None: bml_path = Path(file_dep) bml_deps", "saved def includes(file_handle) -> Iterator[Path]: for line in file_handle.readlines(): line", "with open(bml_includes_cache_file, \"w\", encoding='utf-8') as f: json.dump(existing_deps, f, indent=4) def", "def task_bml2html(): \"\"\"Create html file from bridge bidding markup language", "Path(join(bml_tools_dir, \"bml2html.py\")) input_bml_file_paths = glob(\"*.bml\") def html_output_path(bml_path: Path) -> Path:", "# even if ran from a different directory `doit -f", "running a shell command copyfile(src_css_file, css_basename) return { 'actions': [copy_file],", "[html_output_path(bml_path)], 'title': title_with_actions } def task_bmlcss(): \"\"\"Copy the bml CSS", "len(include_directive_tokens) > 1: # We assume the file name is", "order correct) def update_bml_includes_cache(bml_path: Path, bml_deps: List[Path]): existing_deps = {}", "[bml_path], 'title': title_with_actions } def task_bml2html(): \"\"\"Create html file from", "to this directory.\"\"\" css_basename = \"bml.css\" src_css_file = Path(join(bml_tools_dir, css_basename))", "applied if interested enough. yield { 'name': basename(bml_path), 'actions': [(calc_include_deps_and_cache,", "Manually edited perhaps (assuming we got the task order correct)", "dst_css)]: yield { 'name': basename(src), 'actions': [copy_file], 'file_dep': [src], 'targets':", "abspath, basename, dirname, exists, expanduser, join, splitext from shutil import", "None with open(bml_includes_cache_file, encoding='utf-8') as f: try: existing_deps = json.load(f)", "!= bml_path} return list(unique_deps) def read_bml_includes_cache(bml_path: Path) -> Optional[List[Path]]: if", "# We don't use a target as doit cannot deal", "NewType, Optional from doit.tools import title_with_actions Path = NewType(\"Path\", str)", "reads the include cache as part of determining changing file", "are relative to dodo.py (doit runs in the working dir", "web server root.\"\"\" src_file = \"bidding-system.html\" dst_file = f\"W:/{src_file}\" css_file", "= json.load(f) except Exception: # Manually edited messed up json", "the task order correct) def update_bml_includes_cache(bml_path: Path, bml_deps: List[Path]): existing_deps", "of # doit that could be applied if interested enough.", "calc_include_deps_and_cache(file_dep) -> None: bml_path = Path(file_dep) bml_deps = bml_include_dependencies(bml_path) update_bml_includes_cache(bml_path,", "None if bml_path in existing_deps: return existing_deps[bml_path] else: return None", "file # for new include directives every time a bml", "targets[0]) for src, dst in [(src_file, dst_file), (css_file, dst_css)]: yield", "return list(unique_deps) def read_bml_includes_cache(bml_path: Path) -> Optional[List[Path]]: if not exists(bml_includes_cache_file):", "file watcher only works on Linux/Mac # - All commands", "a different notion of an update (not just tracking file", "css_basename = \"bml.css\" src_css_file = Path(join(bml_tools_dir, css_basename)) def copy_file() ->", "None: bml_deps = bml_include_dependencies(bml_path) update_bml_includes_cache(bml_path, bml_deps) yield { 'name': basename(bml_path),", "part of determining changing file dependencies # The html task", "perhaps return None if bml_path in existing_deps: return existing_deps[bml_path] else:", "try: existing_deps = json.load(f) except Exception: pass existing_deps[bml_path] = bml_deps", "file instead of one cache file per input file. #", "typing import Iterator, List, NewType, Optional from doit.tools import title_with_actions", "json from os import environ from os.path import abspath, basename,", "import Iterator, List, NewType, Optional from doit.tools import title_with_actions Path", "determining changing file dependencies # The html task itself cannot", "pass existing_deps[bml_path] = bml_deps with open(bml_includes_cache_file, \"w\", encoding='utf-8') as f:", "json.dump(existing_deps, f, indent=4) def task_bml_include_cache(): \"\"\"Populate the bml include cache.\"\"\"", "<filename>dodo.py #! /usr/bin/doit -f # https://pydoit.org # `pip install [--user]", "cache file as a doit file_dep dependency as it is", "updated # before the html task reads the include cache", "os.path import abspath, basename, dirname, exists, expanduser, join, splitext from", "is not quoted, just a free form path string included_file", "file. # This does mean that we are using the", "itself cannot use the include cache file as a doit", "None: # OS neutral compared to running a shell command", "} def task_publish_main_bidding(): \"\"\"Copy the main bidding html and css", "file_dep dependency as it is being updated # by other", "Path) -> Path: return Path(splitext(bml_path)[0] + \".html\") for bml_path in", "bml file is saved def includes(file_handle) -> Iterator[Path]: for line", "def task_bml_include_cache(): \"\"\"Populate the bml include cache.\"\"\" input_bml_file_paths = glob(\"*.bml\")", "html task itself cannot use the include cache file as", "'name': basename(src), 'actions': [copy_file], 'file_dep': [src], 'targets': [dst], 'title': title_with_actions", "Path(environ.get(\"BML_TOOLS_DIRECTORY\", join(home, \"dev/bml\"))) bml_includes_cache_file = \".include-deps.json\" def bml_include_dependencies(bml_path: Path) ->", "import copyfile from typing import Iterator, List, NewType, Optional from", "# for new include directives every time a bml file", "= \".include-deps.json\" def bml_include_dependencies(bml_path: Path) -> List[Path]: # bml files", "(assuming we got the task order correct) def update_bml_includes_cache(bml_path: Path,", "for line in file_handle.readlines(): line = line.strip() if line.startswith(\"#INCLUDE\"): include_directive_tokens", "= glob(\"*.bml\") def html_output_path(bml_path: Path) -> Path: return Path(splitext(bml_path)[0] +", "by other unrelated bml file changes. # Actually, using a", "Path(splitext(bml_path)[0] + \".html\") for bml_path in input_bml_file_paths: bml_deps = read_bml_includes_cache(bml_path)", "before the html task reads the include cache as part", "f\"W:/{src_file}\" css_file = \"bml.css\" dst_css = f\"W:/{css_file}\" def copy_file(dependencies, targets)", "list(unique_deps) def read_bml_includes_cache(bml_path: Path) -> Optional[List[Path]]: if not exists(bml_includes_cache_file): return", "'actions': [(calc_include_deps_and_cache, [bml_path])], 'file_dep': [bml_path], 'title': title_with_actions } def task_bml2html():", "task reads the include cache as part of determining changing", "Optional[List[Path]]: if not exists(bml_includes_cache_file): return None with open(bml_includes_cache_file, encoding='utf-8') as", "read_bml_includes_cache(bml_path) if bml_deps is None: bml_deps = bml_include_dependencies(bml_path) update_bml_includes_cache(bml_path, bml_deps)", "in includes(f) if include != bml_path} return list(unique_deps) def read_bml_includes_cache(bml_path:", "if bml_path in existing_deps: return existing_deps[bml_path] else: return None #", "to dodo.py (doit runs in the working dir of dodo.py", "new include directives every time a bml file is saved", "bml_include_dependencies(bml_path) update_bml_includes_cache(bml_path, bml_deps) for bml_path in input_bml_file_paths: # We don't", "include_directive_tokens[1].strip() yield Path(included_file) with open(bml_path, encoding='utf-8') as f: unique_deps =", "other unrelated bml file changes. # Actually, using a different", "= Path(file_dep) bml_deps = bml_include_dependencies(bml_path) update_bml_includes_cache(bml_path, bml_deps) for bml_path in", "working dir of dodo.py # even if ran from a", "as doit cannot deal with more than one input file", "ran from a different directory `doit -f path/to/dodo.py`) from glob", "if bml_deps is None: bml_deps = bml_include_dependencies(bml_path) update_bml_includes_cache(bml_path, bml_deps) yield", "[f\"python {bml2html_path} {bml_path}\"], 'file_dep': [bml_path] + bml_deps, 'targets': [html_output_path(bml_path)], 'title':", "return None if bml_path in existing_deps: return existing_deps[bml_path] else: return", "line.split(maxsplit=1) if len(include_directive_tokens) > 1: # We assume the file", "f: try: existing_deps = json.load(f) except Exception: # Manually edited", "'actions': [f\"python {bml2html_path} {bml_path}\"], 'file_dep': [bml_path] + bml_deps, 'targets': [html_output_path(bml_path)],", "a shell command copyfile(src_css_file, css_basename) return { 'actions': [copy_file], 'file_dep':", "str) home = Path(expanduser(\"~\")) bml_tools_dir = Path(environ.get(\"BML_TOOLS_DIRECTORY\", join(home, \"dev/bml\"))) bml_includes_cache_file", "[copy_file], 'file_dep': [src_css_file], 'targets': [css_basename], 'title': title_with_actions } def task_publish_main_bidding():", "yield { 'name': basename(src), 'actions': [copy_file], 'file_dep': [src], 'targets': [dst],", "# The html task itself cannot use the include cache", "the include cache as part of determining changing file dependencies", "copy_file(dependencies, targets) -> None: copyfile(dependencies[0], targets[0]) for src, dst in", "bml_tools_dir = Path(environ.get(\"BML_TOOLS_DIRECTORY\", join(home, \"dev/bml\"))) bml_includes_cache_file = \".include-deps.json\" def bml_include_dependencies(bml_path:", "bml_deps = read_bml_includes_cache(bml_path) if bml_deps is None: bml_deps = bml_include_dependencies(bml_path)", "def html_output_path(bml_path: Path) -> Path: return Path(splitext(bml_path)[0] + \".html\") for", "line.startswith(\"#INCLUDE\"): include_directive_tokens = line.split(maxsplit=1) if len(include_directive_tokens) > 1: # We", "# - Note `doit auto`, the file watcher only works", "directives every time a bml file is saved def includes(file_handle)", "List[Path]: # bml files can include others, so spend time", "this directory.\"\"\" css_basename = \"bml.css\" src_css_file = Path(join(bml_tools_dir, css_basename)) def", "for bml_path in input_bml_file_paths: # We don't use a target", "could be applied if interested enough. yield { 'name': basename(bml_path),", "bml file changes. # Actually, using a different notion of", "def task_publish_main_bidding(): \"\"\"Copy the main bidding html and css document", "try: existing_deps = json.load(f) except Exception: # Manually edited messed", "\"bidding-system.html\" dst_file = f\"W:/{src_file}\" css_file = \"bml.css\" dst_css = f\"W:/{css_file}\"", "existing_deps[bml_path] = bml_deps with open(bml_includes_cache_file, \"w\", encoding='utf-8') as f: json.dump(existing_deps,", "existing_deps = {} if exists(bml_includes_cache_file): with open(bml_includes_cache_file, encoding='utf-8') as f:", "than one input file affecting the same output file #", "include cache as part of determining changing file dependencies #", "not exists(bml_includes_cache_file): return None with open(bml_includes_cache_file, encoding='utf-8') as f: try:", "every time a bml file is saved def includes(file_handle) ->", "Path(expanduser(\"~\")) bml_tools_dir = Path(environ.get(\"BML_TOOLS_DIRECTORY\", join(home, \"dev/bml\"))) bml_includes_cache_file = \".include-deps.json\" def", "for new include directives every time a bml file is", "if include != bml_path} return list(unique_deps) def read_bml_includes_cache(bml_path: Path) ->", "as f: json.dump(existing_deps, f, indent=4) def task_bml_include_cache(): \"\"\"Populate the bml", "bml_path = Path(file_dep) bml_deps = bml_include_dependencies(bml_path) update_bml_includes_cache(bml_path, bml_deps) for bml_path", "neutral compared to running a shell command copyfile(src_css_file, css_basename) return", "notion of an update (not just tracking file modifications) if", "a free form path string included_file = include_directive_tokens[1].strip() yield Path(included_file)", "be applied if interested enough. yield { 'name': basename(bml_path), 'actions':", "import glob import json from os import environ from os.path", "dst_file), (css_file, dst_css)]: yield { 'name': basename(src), 'actions': [copy_file], 'file_dep':", "works on Linux/Mac # - All commands are relative to", "= NewType(\"Path\", str) home = Path(expanduser(\"~\")) bml_tools_dir = Path(environ.get(\"BML_TOOLS_DIRECTORY\", join(home,", "interested enough. yield { 'name': basename(bml_path), 'actions': [(calc_include_deps_and_cache, [bml_path])], 'file_dep':", "watcher only works on Linux/Mac # - All commands are", "include != bml_path} return list(unique_deps) def read_bml_includes_cache(bml_path: Path) -> Optional[List[Path]]:", "include directives every time a bml file is saved def", "bml_deps is None: bml_deps = bml_include_dependencies(bml_path) update_bml_includes_cache(bml_path, bml_deps) yield {", "copyfile(src_css_file, css_basename) return { 'actions': [copy_file], 'file_dep': [src_css_file], 'targets': [css_basename],", "'targets': [css_basename], 'title': title_with_actions } def task_publish_main_bidding(): \"\"\"Copy the main", "except Exception: pass existing_deps[bml_path] = bml_deps with open(bml_includes_cache_file, \"w\", encoding='utf-8')", "dir of dodo.py # even if ran from a different", "# by other unrelated bml file changes. # Actually, using", "adds `doit.exe` to the PATH # - Note `doit auto`,", "dodo.py (doit runs in the working dir of dodo.py #", "the web server root.\"\"\" src_file = \"bidding-system.html\" dst_file = f\"W:/{src_file}\"", "even if ran from a different directory `doit -f path/to/dodo.py`)", "= Path(expanduser(\"~\")) bml_tools_dir = Path(environ.get(\"BML_TOOLS_DIRECTORY\", join(home, \"dev/bml\"))) bml_includes_cache_file = \".include-deps.json\"", "Exception: # Manually edited messed up json perhaps return None", "-> None: copyfile(dependencies[0], targets[0]) for src, dst in [(src_file, dst_file),", "file modifications) if another feature of # doit that could", "'file_dep': [src_css_file], 'targets': [css_basename], 'title': title_with_actions } def task_publish_main_bidding(): \"\"\"Copy", "def update_bml_includes_cache(bml_path: Path, bml_deps: List[Path]): existing_deps = {} if exists(bml_includes_cache_file):", "Path = NewType(\"Path\", str) home = Path(expanduser(\"~\")) bml_tools_dir = Path(environ.get(\"BML_TOOLS_DIRECTORY\",", "sheet to this directory.\"\"\" css_basename = \"bml.css\" src_css_file = Path(join(bml_tools_dir,", "one input file affecting the same output file # and", "return None with open(bml_includes_cache_file, encoding='utf-8') as f: try: existing_deps =", "copy_file() -> None: # OS neutral compared to running a", "The html task itself cannot use the include cache file", "-> Path: return Path(splitext(bml_path)[0] + \".html\") for bml_path in input_bml_file_paths:", "Iterator[Path]: for line in file_handle.readlines(): line = line.strip() if line.startswith(\"#INCLUDE\"):", "None: bml_path = Path(file_dep) bml_deps = bml_include_dependencies(bml_path) update_bml_includes_cache(bml_path, bml_deps) for", "for include in includes(f) if include != bml_path} return list(unique_deps)", "a bml file is saved def includes(file_handle) -> Iterator[Path]: for", "encoding='utf-8') as f: try: existing_deps = json.load(f) except Exception: pass", "markup language file.\"\"\" bml2html_path = Path(join(bml_tools_dir, \"bml2html.py\")) input_bml_file_paths = glob(\"*.bml\")", "bml_deps, 'targets': [html_output_path(bml_path)], 'title': title_with_actions } def task_bmlcss(): \"\"\"Copy the", "bidding html and css document to the web server root.\"\"\"", "files can include others, so spend time scanning every bml", "to have the include cache updated # before the html", "[src_css_file], 'targets': [css_basename], 'title': title_with_actions } def task_publish_main_bidding(): \"\"\"Copy the", "# https://pydoit.org # `pip install [--user] doit` adds `doit.exe` to", "CSS style sheet to this directory.\"\"\" css_basename = \"bml.css\" src_css_file", "exists(bml_includes_cache_file): return None with open(bml_includes_cache_file, encoding='utf-8') as f: try: existing_deps", "+ \".html\") for bml_path in input_bml_file_paths: bml_deps = read_bml_includes_cache(bml_path) if", "{ 'name': basename(bml_path), 'actions': [(calc_include_deps_and_cache, [bml_path])], 'file_dep': [bml_path], 'title': title_with_actions", "the file watcher only works on Linux/Mac # - All", "join(home, \"dev/bml\"))) bml_includes_cache_file = \".include-deps.json\" def bml_include_dependencies(bml_path: Path) -> List[Path]:", "from os.path import abspath, basename, dirname, exists, expanduser, join, splitext", "[(src_file, dst_file), (css_file, dst_css)]: yield { 'name': basename(src), 'actions': [copy_file]," ]
[ "'r') line = f.readline() if line == \"\": f.close() raise", "% file) # except IOError as error: # print(\"%s: could", "(file, error.strerror) ## except EmptyFileError as error: # print(error) #", "print(error) # else: # print(\"%s: %s\" % (file, f.readline())) #", "= open(file, 'r') line = f.readline() if line == \"\":", "\"\": f.close() raise EmptyFileError(\"%s: is empty\" % file) # except", "pass filenames = [\"myfile1\", \"nonExistent\", \"emptyFile\", \"myfile2\"] for file in", "empty\" % file) # except IOError as error: # print(\"%s:", "# else: # print(\"%s: %s\" % (file, f.readline())) # finally:", "f.readline() if line == \"\": f.close() raise EmptyFileError(\"%s: is empty\"", "filenames: try: f = open(file, 'r') line = f.readline() if", "else: # print(\"%s: %s\" % (file, f.readline())) # finally: #", "f.close() raise EmptyFileError(\"%s: is empty\" % file) # except IOError", "except IOError as error: # print(\"%s: could not be opened:", "open(file, 'r') line = f.readline() if line == \"\": f.close()", "class EmptyFileError(Exception): pass filenames = [\"myfile1\", \"nonExistent\", \"emptyFile\", \"myfile2\"] for", "= [\"myfile1\", \"nonExistent\", \"emptyFile\", \"myfile2\"] for file in filenames: try:", "in filenames: try: f = open(file, 'r') line = f.readline()", "EmptyFileError as error: # print(error) # else: # print(\"%s: %s\"", "for file in filenames: try: f = open(file, 'r') line", "print(\"%s: %s\" % (file, f.readline())) # finally: # print(\"Done processing\",", "not be opened: %s\" % (file, error.strerror) ## except EmptyFileError", "be opened: %s\" % (file, error.strerror) ## except EmptyFileError as", "== \"\": f.close() raise EmptyFileError(\"%s: is empty\" % file) #", "%s\" % (file, f.readline())) # finally: # print(\"Done processing\", file)", "error: # print(\"%s: could not be opened: %s\" % (file,", "print(\"%s: could not be opened: %s\" % (file, error.strerror) ##", "could not be opened: %s\" % (file, error.strerror) ## except", "# except IOError as error: # print(\"%s: could not be", "line = f.readline() if line == \"\": f.close() raise EmptyFileError(\"%s:", "f = open(file, 'r') line = f.readline() if line ==", "error.strerror) ## except EmptyFileError as error: # print(error) # else:", "filenames = [\"myfile1\", \"nonExistent\", \"emptyFile\", \"myfile2\"] for file in filenames:", "## except EmptyFileError as error: # print(error) # else: #", "\"nonExistent\", \"emptyFile\", \"myfile2\"] for file in filenames: try: f =", "try: f = open(file, 'r') line = f.readline() if line", "= f.readline() if line == \"\": f.close() raise EmptyFileError(\"%s: is", "raise EmptyFileError(\"%s: is empty\" % file) # except IOError as", "# print(error) # else: # print(\"%s: %s\" % (file, f.readline()))", "error: # print(error) # else: # print(\"%s: %s\" % (file,", "file in filenames: try: f = open(file, 'r') line =", "as error: # print(\"%s: could not be opened: %s\" %", "# print(\"%s: %s\" % (file, f.readline())) # finally: # print(\"Done", "EmptyFileError(\"%s: is empty\" % file) # except IOError as error:", "[\"myfile1\", \"nonExistent\", \"emptyFile\", \"myfile2\"] for file in filenames: try: f", "if line == \"\": f.close() raise EmptyFileError(\"%s: is empty\" %", "\"emptyFile\", \"myfile2\"] for file in filenames: try: f = open(file,", "except EmptyFileError as error: # print(error) # else: # print(\"%s:", "# print(\"%s: could not be opened: %s\" % (file, error.strerror)", "\"myfile2\"] for file in filenames: try: f = open(file, 'r')", "opened: %s\" % (file, error.strerror) ## except EmptyFileError as error:", "IOError as error: # print(\"%s: could not be opened: %s\"", "% (file, error.strerror) ## except EmptyFileError as error: # print(error)", "is empty\" % file) # except IOError as error: #", "EmptyFileError(Exception): pass filenames = [\"myfile1\", \"nonExistent\", \"emptyFile\", \"myfile2\"] for file", "file) # except IOError as error: # print(\"%s: could not", "line == \"\": f.close() raise EmptyFileError(\"%s: is empty\" % file)", "as error: # print(error) # else: # print(\"%s: %s\" %", "%s\" % (file, error.strerror) ## except EmptyFileError as error: #" ]
[ "datastore.LED_COUNT self.pos = 0 self.direction=0 self.cols = [ \\ [255,0,0,0],", "<reponame>jimconner/digital_sky<filename>plugins/crumbling_in.py # Crumbling In # Like randomised coloured dots and", "self.pos >= self.max_led/2: self.direction=1 if self.pos <= 0: self.direction=0 col=self.cols[random.randint(0,7)]", "class animation(): def __init__(self,datastore): self.max_led = datastore.LED_COUNT self.pos = 0", "[0,0,255,64], \\ ] self.row=full((self.max_led,4),0) def emit_row(self): try: if self.pos >=", "dots and then they # increase on both sides getting", "self.row[self.pos]=col self.row[(self.max_led-1)-self.pos]=col if self.direction==0: self.pos+=1 else: self.pos-=1 return self.row except", "Crumbling In # Like randomised coloured dots and then they", "if self.direction==0: self.pos+=1 else: self.pos-=1 return self.row except Exception as", "import array,full class animation(): def __init__(self,datastore): self.max_led = datastore.LED_COUNT self.pos", "\\ [0,255,255,0], \\ [0,0,255,64], \\ ] self.row=full((self.max_led,4),0) def emit_row(self): try:", "[ \\ [255,0,0,0], \\ [0,255,0,0], \\ [0,0,255,0], \\ [0,0,0,255], \\", "\\ [255,0,0,0], \\ [0,255,0,0], \\ [0,0,255,0], \\ [0,0,0,255], \\ [255,255,0,0],", "\\ [255,0,255,0], \\ [0,255,255,0], \\ [0,0,255,64], \\ ] self.row=full((self.max_led,4),0) def", "and then they # increase on both sides getting closer", "[255,0,0,0], \\ [0,255,0,0], \\ [0,0,255,0], \\ [0,0,0,255], \\ [255,255,0,0], \\", "closer into the middle. import sys, traceback, random from numpy", "random from numpy import array,full class animation(): def __init__(self,datastore): self.max_led", "self.cols = [ \\ [255,0,0,0], \\ [0,255,0,0], \\ [0,0,255,0], \\", "\\ [0,0,255,0], \\ [0,0,0,255], \\ [255,255,0,0], \\ [255,0,255,0], \\ [0,255,255,0],", "getting closer and closer into the middle. import sys, traceback,", "0: self.direction=0 col=self.cols[random.randint(0,7)] if self.direction==1: col=[0,0,0,0] self.row[self.pos]=col self.row[(self.max_led-1)-self.pos]=col if self.direction==0:", "self.pos+=1 else: self.pos-=1 return self.row except Exception as err: print(err)", "self.direction=1 if self.pos <= 0: self.direction=0 col=self.cols[random.randint(0,7)] if self.direction==1: col=[0,0,0,0]", "self.row=full((self.max_led,4),0) def emit_row(self): try: if self.pos >= self.max_led/2: self.direction=1 if", "def emit_row(self): try: if self.pos >= self.max_led/2: self.direction=1 if self.pos", "[0,255,255,0], \\ [0,0,255,64], \\ ] self.row=full((self.max_led,4),0) def emit_row(self): try: if", ">= self.max_led/2: self.direction=1 if self.pos <= 0: self.direction=0 col=self.cols[random.randint(0,7)] if", "\\ [0,255,0,0], \\ [0,0,255,0], \\ [0,0,0,255], \\ [255,255,0,0], \\ [255,0,255,0],", "[0,0,255,0], \\ [0,0,0,255], \\ [255,255,0,0], \\ [255,0,255,0], \\ [0,255,255,0], \\", "[255,0,255,0], \\ [0,255,255,0], \\ [0,0,255,64], \\ ] self.row=full((self.max_led,4),0) def emit_row(self):", "if self.pos >= self.max_led/2: self.direction=1 if self.pos <= 0: self.direction=0", "from numpy import array,full class animation(): def __init__(self,datastore): self.max_led =", "if self.pos <= 0: self.direction=0 col=self.cols[random.randint(0,7)] if self.direction==1: col=[0,0,0,0] self.row[self.pos]=col", "] self.row=full((self.max_led,4),0) def emit_row(self): try: if self.pos >= self.max_led/2: self.direction=1", "self.pos = 0 self.direction=0 self.cols = [ \\ [255,0,0,0], \\", "= datastore.LED_COUNT self.pos = 0 self.direction=0 self.cols = [ \\", "[0,0,0,255], \\ [255,255,0,0], \\ [255,0,255,0], \\ [0,255,255,0], \\ [0,0,255,64], \\", "they # increase on both sides getting closer and closer", "\\ [255,255,0,0], \\ [255,0,255,0], \\ [0,255,255,0], \\ [0,0,255,64], \\ ]", "col=self.cols[random.randint(0,7)] if self.direction==1: col=[0,0,0,0] self.row[self.pos]=col self.row[(self.max_led-1)-self.pos]=col if self.direction==0: self.pos+=1 else:", "self.row[(self.max_led-1)-self.pos]=col if self.direction==0: self.pos+=1 else: self.pos-=1 return self.row except Exception", "if self.direction==1: col=[0,0,0,0] self.row[self.pos]=col self.row[(self.max_led-1)-self.pos]=col if self.direction==0: self.pos+=1 else: self.pos-=1", "numpy import array,full class animation(): def __init__(self,datastore): self.max_led = datastore.LED_COUNT", "self.pos <= 0: self.direction=0 col=self.cols[random.randint(0,7)] if self.direction==1: col=[0,0,0,0] self.row[self.pos]=col self.row[(self.max_led-1)-self.pos]=col", "0 self.direction=0 self.cols = [ \\ [255,0,0,0], \\ [0,255,0,0], \\", "sides getting closer and closer into the middle. import sys,", "on both sides getting closer and closer into the middle.", "\\ [0,0,0,255], \\ [255,255,0,0], \\ [255,0,255,0], \\ [0,255,255,0], \\ [0,0,255,64],", "[255,255,0,0], \\ [255,0,255,0], \\ [0,255,255,0], \\ [0,0,255,64], \\ ] self.row=full((self.max_led,4),0)", "array,full class animation(): def __init__(self,datastore): self.max_led = datastore.LED_COUNT self.pos =", "self.direction=0 self.cols = [ \\ [255,0,0,0], \\ [0,255,0,0], \\ [0,0,255,0],", "and closer into the middle. import sys, traceback, random from", "= 0 self.direction=0 self.cols = [ \\ [255,0,0,0], \\ [0,255,0,0],", "the middle. import sys, traceback, random from numpy import array,full", "self.direction==1: col=[0,0,0,0] self.row[self.pos]=col self.row[(self.max_led-1)-self.pos]=col if self.direction==0: self.pos+=1 else: self.pos-=1 return", "import sys, traceback, random from numpy import array,full class animation():", "Like randomised coloured dots and then they # increase on", "then they # increase on both sides getting closer and", "else: self.pos-=1 return self.row except Exception as err: print(err) traceback.print_exc(file=sys.stdout)", "__init__(self,datastore): self.max_led = datastore.LED_COUNT self.pos = 0 self.direction=0 self.cols =", "= [ \\ [255,0,0,0], \\ [0,255,0,0], \\ [0,0,255,0], \\ [0,0,0,255],", "self.max_led/2: self.direction=1 if self.pos <= 0: self.direction=0 col=self.cols[random.randint(0,7)] if self.direction==1:", "# Crumbling In # Like randomised coloured dots and then", "def __init__(self,datastore): self.max_led = datastore.LED_COUNT self.pos = 0 self.direction=0 self.cols", "randomised coloured dots and then they # increase on both", "self.direction==0: self.pos+=1 else: self.pos-=1 return self.row except Exception as err:", "middle. import sys, traceback, random from numpy import array,full class", "# Like randomised coloured dots and then they # increase", "# increase on both sides getting closer and closer into", "self.direction=0 col=self.cols[random.randint(0,7)] if self.direction==1: col=[0,0,0,0] self.row[self.pos]=col self.row[(self.max_led-1)-self.pos]=col if self.direction==0: self.pos+=1", "<= 0: self.direction=0 col=self.cols[random.randint(0,7)] if self.direction==1: col=[0,0,0,0] self.row[self.pos]=col self.row[(self.max_led-1)-self.pos]=col if", "try: if self.pos >= self.max_led/2: self.direction=1 if self.pos <= 0:", "traceback, random from numpy import array,full class animation(): def __init__(self,datastore):", "into the middle. import sys, traceback, random from numpy import", "self.max_led = datastore.LED_COUNT self.pos = 0 self.direction=0 self.cols = [", "closer and closer into the middle. import sys, traceback, random", "emit_row(self): try: if self.pos >= self.max_led/2: self.direction=1 if self.pos <=", "both sides getting closer and closer into the middle. import", "col=[0,0,0,0] self.row[self.pos]=col self.row[(self.max_led-1)-self.pos]=col if self.direction==0: self.pos+=1 else: self.pos-=1 return self.row", "animation(): def __init__(self,datastore): self.max_led = datastore.LED_COUNT self.pos = 0 self.direction=0", "\\ ] self.row=full((self.max_led,4),0) def emit_row(self): try: if self.pos >= self.max_led/2:", "sys, traceback, random from numpy import array,full class animation(): def", "[0,255,0,0], \\ [0,0,255,0], \\ [0,0,0,255], \\ [255,255,0,0], \\ [255,0,255,0], \\", "increase on both sides getting closer and closer into the", "\\ [0,0,255,64], \\ ] self.row=full((self.max_led,4),0) def emit_row(self): try: if self.pos", "coloured dots and then they # increase on both sides", "In # Like randomised coloured dots and then they #" ]
[ "3, 3, 3, 4, 4, 4, 4], \"c\": [1, 2,", "editor_options: if col != \"index\": self.assertIn(TEST_DF[col].dtype, (np.int64, np.float64)) else: self.assertEqual(set(editor_options),", "4, 1, 2, 3, 4], \"b\": [1, 1, 1, 1,", "# Pulling the x_arr forces a reset of the x_col_name", "BaseXYPlotConfig): def setUp(self): self.configurator = LinePlotConfigurator self.basic_type = LINE_PLOT_TYPE self.numerical_cols_only", "y_col_name=\"b\", z_col_name=\"d\") self.assertFalse(config.plot_style.colorize_by_float) # Color by a float: config.z_col_name =", "z_col_name=\"NON-EXISTENT\") with self.assertRaises(KeyError): config.to_dict() def test_data_choices(self): \"\"\" Make sure different", "* (LEN // 2), dtype=bool), }) class BasePlotConfig(object): def test_creation_fails_if_no_df(self):", "# Tests ------------------------------------------------------------------- def test_plot_basic(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\") self.assertEqual(config.plot_type,", "5, 6, 4, 4, 5, 6], \"d\": list(\"ababcabcdabcdeab\"), \"e\": np.random.randn(LEN),", "from pandas import DataFrame import numpy as np from numpy.testing", "}) class BasePlotConfig(object): def test_creation_fails_if_no_df(self): with self.assertRaises(ValueError): config = self.configurator()", "config = self.configurator(data_source=TEST_DF, x_col_name=\"a\") self.assertEqual(config.plot_type, self.basic_type) config_dict = config.to_dict() self.assertIsInstance(config_dict,", "pandas import DataFrame import numpy as np from numpy.testing import", "y_col_name=\"b\", z_col_name=\"e\") self.assertEqual(config.plot_type, CMAP_SCATTER_PLOT_TYPE) config_dict = config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\",", "x_values) self.assertIn(\"y_arr\", config_dict) self.assertEqual(len(config_dict[\"y_arr\"]), 2 * LEN) def test_melt_mode_with_melted_columns_and_str_color(self): config", "* (LEN // 2) + [\"f\"] * (LEN // 2))", "BACKEND_AVAILABLE, \"No UI backend available\") class TestLinePlotConfig(TestCase, BaseXYPlotConfig): def setUp(self):", "import os from pandas import DataFrame import numpy as np", "= self.configurator() config.to_dict() def test_bring_up(self): obj = self.configurator(data_source=TEST_DF) assert_obj_gui_works(obj) #", "config_dict) self.assertIsInstance(config_dict[\"z_arr\"], np.ndarray) def test_style_colorize_by_float_changes_on_color_column_change(self): \"\"\" The dtype of the", "x_values) self.assertIn(\"y_arr\", config_dict) for key in hue_values: self.assertEqual(len(config_dict[\"y_arr\"][key]), LEN) @skipIf(not", "if self.numerical_cols_only: for col in editor_options: if col != \"index\":", "(LEN // 2) + [\"f\"] * (LEN // 2)) self.assertEqual(set(config.x_arr.keys()),", "x_col_name=\"a\") self.assertEqual(config.plot_type, self.basic_type) config_dict = config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict)", "y_editor = view_items[1].content[0].editor self.assert_editor_options(y_editor) def test_plot_colored_by_str_col(self): # Color by a", "class BasePlotConfig(object): def test_creation_fails_if_no_df(self): with self.assertRaises(ValueError): config = self.configurator() config.to_dict()", "division from unittest import skipIf, TestCase import os from pandas", "class BaseXYPlotConfig(BasePlotConfig): def test_plot_basic(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\") self.assertEqual(config.plot_type,", "UI backend available\") class TestBarPlotConfig(TestCase, BaseXYPlotConfig): def setUp(self): self.configurator =", "config_dict) for key in hue_values: self.assertEqual(len(config_dict[\"y_arr\"][key]), LEN) def test_melt_mode_with_melted_columns_and_bool_color(self): config", "config_dict = config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict) assert_array_equal(config_dict[\"x_arr\"], TEST_DF[\"a\"].values) def", "float: config.z_col_name = \"e\" self.assertTrue(config.plot_style.colorize_by_float) def test_scatter_data_selection_columns(self): config = self.configurator(data_source=TEST_DF,", "BarPlotConfigurator self.basic_type = BAR_PLOT_TYPE self.numerical_cols_only = False def test_data_choices(self): \"\"\"", "@skipIf(not BACKEND_AVAILABLE, \"No UI backend available\") class TestScatterPlotConfig(TestCase, BaseXYPlotConfig): def", "2 * LEN) self.assertEqual(config.y_col_name, \"value\") config_dict = config.to_dict() self.assertIsInstance(config_dict, dict)", "config_dict[\"y_arr\"].values(): self.assertIsInstance(arr, np.ndarray) # For example: assert_array_equal(config_dict[\"y_arr\"][\"c\"], np.array([2, 2, 3]))", "config._data_selection_items() x_editor = view_items[0].content[3].content[0].content[0].editor self.assert_editor_options(x_editor) def test_melt_mode_no_effect(self): config = self.configurator(data_source=TEST_DF,", "= self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"e\") self.assertEqual(config.plot_type, self.basic_type) config_dict = config.to_dict()", "y_col_name=\"b\") view_items = config._data_selection_items() x_editor = view_items[0].content[0].editor self.assert_editor_options(x_editor) y_editor =", "\"g\": np.array([\"0\", \"1\"] * (LEN // 2)), \"h\": np.array([0, 1]", "= self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"NON-EXISTENT\") with self.assertRaises(KeyError): config.to_dict() @skipIf(not BACKEND_AVAILABLE,", "in config_dict[\"x_arr\"].values(): self.assertIsInstance(arr, np.ndarray) # For example: assert_array_equal(config_dict[\"x_arr\"][\"c\"], np.array([1, 4,", "self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"c\") self.assertEqual(config.plot_type, CMAP_SCATTER_PLOT_TYPE) config_dict = config.to_dict() self.assertIsInstance(config_dict,", "\"No UI backend available\") class TestScatterPlotConfig(TestCase, BaseXYPlotConfig): def setUp(self): self.configurator", "config_dict) self.assertIsInstance(config_dict[\"y_arr\"], dict) self.assertEqual(set(config_dict[\"y_arr\"].keys()), set(d_values)) for arr in config_dict[\"y_arr\"].values(): self.assertIsInstance(arr,", "ScatterPlotConfigurator, \\ SCATTER_PLOT_TYPE, CMAP_SCATTER_PLOT_TYPE, LINE_PLOT_TYPE, \\ BAR_PLOT_TYPE LEN = 16", "[\"\"] + config._available_columns self.assertCountEqual(columns, expected) @skipIf(not BACKEND_AVAILABLE, \"No UI backend", "= config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict) self.assertEqual(set(config_dict[\"x_arr\"].keys()), set(hue_values)) for key", "editor): editor_options = editor.values if self.numerical_cols_only: for col in editor_options:", "backend available\") class TestLinePlotConfig(TestCase, BaseXYPlotConfig): def setUp(self): self.configurator = LinePlotConfigurator", "config._color_selection_columns() expected = [\"\"] + config._available_columns self.assertCountEqual(columns, expected) @skipIf(not BACKEND_AVAILABLE,", "non-numerical \"\"\" config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"e\") view_items =", "self.assertIn(\"y_arr\", config_dict) self.assertIsInstance(config_dict[\"y_arr\"], np.ndarray) self.assertIn(\"z_arr\", config_dict) self.assertIsInstance(config_dict[\"z_arr\"], np.ndarray) def test_plot_scatter_colored_by_float_col(self):", "of the x_col_name x_values = np.array([\"e\"] * (LEN // 2)", "into 2 \"g\": np.array([\"0\", \"1\"] * (LEN // 2)), \"h\":", "= config._data_selection_items() x_editor = view_items[0].content[3].content[0].content[0].editor self.assert_editor_options(x_editor) def test_melt_mode_no_effect(self): config =", "available\") class TestHistogramPlotConfig(BasePlotConfig, TestCase): def setUp(self): self.configurator = HistogramPlotConfigurator self.basic_type", "config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"d\") self.assertFalse(config.plot_style.colorize_by_float) # Color by", "Tests ------------------------------------------------------------------- def test_plot_basic(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"e\")", "config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"e\") self.assertEqual(config.plot_type, CMAP_SCATTER_PLOT_TYPE) config_dict =", "TestCase): def setUp(self): self.configurator = HistogramPlotConfigurator self.basic_type = HIST_PLOT_TYPE self.numerical_cols_only", "= [\"\"] + config._available_columns self.assertCountEqual(columns, expected) @skipIf(not BACKEND_AVAILABLE, \"No UI", "in hue_values: assert_array_equal(config_dict[\"x_arr\"][key], x_values) self.assertIn(\"y_arr\", config_dict) for key in hue_values:", "config_dict) self.assertIsInstance(config_dict[\"y_arr\"], dict) self.assertEqual(set(config_dict[\"y_arr\"].keys()), hue_values) assert_array_equal(config_dict[\"y_arr\"][False], TEST_DF[\"b\"][::2]) assert_array_equal(config_dict[\"y_arr\"][True], TEST_DF[\"b\"][1::2]) def", "y_col_name=\"b\", z_col_name=\"d\") self.assertIn(config.plot_type, self.basic_type) config_dict = config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\",", "hue_values: self.assertEqual(len(config_dict[\"y_arr\"][key]), LEN) @skipIf(not BACKEND_AVAILABLE, \"No UI backend available\") class", "provide the right data choices. Passing non-numerical \"\"\" config =", "The dtype of the column to colorize controls colorize_by_float. \"\"\"", "key in hue_values: self.assertEqual(len(config.y_arr[key]), LEN) self.assertEqual(config.y_col_name, \"value\") self.assertIn(\"g\", config.transformed_data.columns) config_dict", "# Color by a string: config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\",", "\"value\") self.assertIn(\"h\", config.transformed_data.columns) config_dict = config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict)", "with self.assertRaises(KeyError): config.to_dict() @skipIf(not BACKEND_AVAILABLE, \"No UI backend available\") class", "assert_array_equal(config_dict[\"x_arr\"], x_values) self.assertIn(\"y_arr\", config_dict) self.assertEqual(len(config_dict[\"y_arr\"]), 2 * LEN) def test_melt_mode_with_melted_columns_and_str_color(self):", "self.assertIsNot(config.transformed_data, TEST_DF) self.assertIs(config.data_source, TEST_DF) hue_values = TEST_DF[\"g\"].unique() # Pulling the", "BasePlotConfig(object): def test_creation_fails_if_no_df(self): with self.assertRaises(ValueError): config = self.configurator() config.to_dict() def", "= view_items[0].content[0].editor self.assert_editor_options(x_editor) y_editor = view_items[1].content[0].editor self.assert_editor_options(y_editor) def test_plot_colored_by_str_col(self): #", "DataFrame({\"a\": [1, 2, 3, 4, 1, 2, 3, 4, 1,", "numpy.testing import assert_array_equal BACKEND_AVAILABLE = os.environ.get(\"ETS_TOOLKIT\", \"qt4\") != \"null\" if", "view_items[1].content[0].editor self.assert_editor_options(y_editor) def test_plot_colored_by_str_col(self): # Color by a column filled", "config_dict = config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict) self.assertIsInstance(config_dict[\"x_arr\"], np.ndarray) self.assertIn(\"y_arr\",", "1, 4, 4, 5, 6, 4, 4, 5, 6], \"d\":", "\"variable\") self.assertEqual(len(config.y_arr), 2 * LEN) self.assertEqual(config.y_col_name, \"value\") config_dict = config.to_dict()", "= True def test_plot_scatter_colored_by_int_col(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"c\")", "test_plot_basic(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\") self.assertEqual(config.plot_type, self.basic_type) config_dict = config.to_dict()", "self.assertEqual(len(config.y_arr), 2 * LEN) self.assertEqual(config.y_col_name, \"value\") config_dict = config.to_dict() self.assertIsInstance(config_dict,", "np.array([\"e\"] * (LEN // 2) + [\"f\"] * (LEN //", "BaseXYPlotConfig(BasePlotConfig): def test_plot_basic(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\") self.assertEqual(config.plot_type, self.basic_type)", "import numpy as np from numpy.testing import assert_array_equal BACKEND_AVAILABLE =", "np.ndarray) # For example: assert_array_equal(config_dict[\"x_arr\"][\"c\"], np.array([1, 4, 4])) self.assertIn(\"y_arr\", config_dict)", "True # Tests ------------------------------------------------------------------- def test_plot_basic(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\",", "self.assertIn(\"h\", config.transformed_data.columns) config_dict = config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict) self.assertEqual(set(config_dict[\"x_arr\"].keys()),", "view_items = config._data_selection_items() x_editor = view_items[0].content[0].editor self.assert_editor_options(x_editor) y_editor = view_items[1].content[0].editor", "test_plot_colored_by_bool_col(self): # Color by a column filled with boolean values", "data choices. \"\"\" config = self.configurator(data_source=TEST_DF, x_col_name=\"a\") view_items = config._data_selection_items()", "2 \"g\": np.array([\"0\", \"1\"] * (LEN // 2)), \"h\": np.array([0,", "= LinePlotConfigurator self.basic_type = LINE_PLOT_TYPE self.numerical_cols_only = True def test_line_data_selection_columns(self):", "y_col_name=\"b\", z_col_name=\"e\") view_items = config._data_selection_items() x_editor = view_items[0].content[0].editor self.assert_editor_options(x_editor) y_editor", "expected = config._numerical_columns self.assertCountEqual(columns, expected) def test_scatter_color_selection_columns(self): config = self.configurator(data_source=TEST_DF,", "x_col_name x_values = np.array([\"e\"] * (LEN // 2) + [\"f\"]", "boolean values config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"d\") self.assertIn(config.plot_type, self.basic_type)", "// 2)) self.assertEqual(set(config.x_arr.keys()), set(hue_values)) for key in hue_values: assert_array_equal(config.x_arr[key], x_values)", "4], \"c\": [1, 2, 3, 4, 2, 3, 1, 1,", "dict) self.assertIn(\"x_arr\", config_dict) self.assertIsInstance(config_dict[\"x_arr\"], dict) hue_values = set(TEST_DF[\"h\"]) self.assertEqual(set(config_dict[\"x_arr\"].keys()), hue_values)", "\"c\": [1, 2, 3, 4, 2, 3, 1, 1, 4,", "the right data choices. \"\"\" config = self.configurator(data_source=TEST_DF, x_col_name=\"a\") view_items", "config.transformed_data.columns) config_dict = config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict) self.assertEqual(set(config_dict[\"x_arr\"].keys()), set(hue_values))", "= self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\") view_items = config._data_selection_items() x_editor = view_items[0].content[0].editor", "np.array([1, 4, 4])) self.assertIn(\"y_arr\", config_dict) self.assertIsInstance(config_dict[\"y_arr\"], dict) self.assertEqual(set(config_dict[\"y_arr\"].keys()), set(d_values)) for", "self.assertEqual(config.y_col_name, \"value\") self.assertIn(\"h\", config.transformed_data.columns) config_dict = config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\",", "LEN) @skipIf(not BACKEND_AVAILABLE, \"No UI backend available\") class TestHistogramPlotConfig(BasePlotConfig, TestCase):", "= BAR_PLOT_TYPE self.numerical_cols_only = False def test_data_choices(self): \"\"\" Make sure", "set(hue_values)) for key in hue_values: assert_array_equal(config.x_arr[key], x_values) self.assertEqual(config.x_col_name, \"variable\") for", "4, 4, 5, 6, 4, 4, 5, 6], \"d\": list(\"ababcabcdabcdeab\"),", "self.assertEqual(config.plot_type, self.basic_type) config_dict = config.to_dict() self.assertIsInstance(config_dict, dict) def test_plot_colored_by_NON_EXISTENT_col(self): config", "True def test_plot_scatter_colored_by_int_col(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"c\") self.assertEqual(config.plot_type,", "HIST_PLOT_TYPE self.numerical_cols_only = True # Tests ------------------------------------------------------------------- def test_plot_basic(self): config", "config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"h\") self.assertIn(config.plot_type, self.basic_type) config_dict =", "\\ SCATTER_PLOT_TYPE, CMAP_SCATTER_PLOT_TYPE, LINE_PLOT_TYPE, \\ BAR_PLOT_TYPE LEN = 16 TEST_DF", "test_melt_mode_no_effect(self): config = self.configurator(data_source=TEST_DF, melt_source_data=True) self.assertEqual(config.plot_type, self.basic_type) # No columns", "TEST_DF[\"a\"][1::2]) self.assertIn(\"y_arr\", config_dict) self.assertIsInstance(config_dict[\"y_arr\"], dict) self.assertEqual(set(config_dict[\"y_arr\"].keys()), hue_values) assert_array_equal(config_dict[\"y_arr\"][False], TEST_DF[\"b\"][::2]) assert_array_equal(config_dict[\"y_arr\"][True],", "with self.assertRaises(KeyError): config.to_dict() def test_data_choices(self): \"\"\" Make sure different configurators", "config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict) self.assertEqual(set(config_dict[\"x_arr\"].keys()), set(hue_values)) for key in", "[1, 2, 3, 4, 2, 3, 1, 1, 4, 4,", "config = self.configurator(data_source=TEST_DF, melt_source_data=True) self.assertEqual(config.plot_type, self.basic_type) # No columns to", "test_scatter_data_selection_columns(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"d\") columns = config._data_selection_columns()", "3, 4, 2, 3, 1, 1, 4, 4, 5, 6,", "BACKEND_AVAILABLE, \"No UI backend available\") class TestBarPlotConfig(TestCase, BaseXYPlotConfig): def setUp(self):", "x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"d\") columns = config._color_selection_columns() expected = [\"\"] +", "view_items[0].content[3].content[0].content[0].editor self.assert_editor_options(x_editor) def test_melt_mode_no_effect(self): config = self.configurator(data_source=TEST_DF, melt_source_data=True) self.assertEqual(config.plot_type, self.basic_type)", "boolean values config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"h\") self.assertIn(config.plot_type, self.basic_type)", "x_arr forces a reset of the x_col_name x_values = np.array([\"e\"]*LEN+[\"f\"]*LEN)", "self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"d\") self.assertIn(config.plot_type, self.basic_type) config_dict = config.to_dict() self.assertIsInstance(config_dict,", "TestCase import os from pandas import DataFrame import numpy as", "TEST_DF) self.assertIs(config.data_source, TEST_DF) # Pulling the x_arr forces a reset", "2, 3, 4], \"b\": [1, 1, 1, 1, 2, 2,", "def test_plot_basic(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"e\") self.assertEqual(config.plot_type, self.basic_type)", "self.assertIn(\"x_arr\", config_dict) assert_array_equal(config_dict[\"x_arr\"], TEST_DF[\"a\"].values) def test_plot_NON_EXISTENT_col(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"NON-EXISTENT\")", "def assert_editor_options(self, editor): editor_options = editor.values if self.numerical_cols_only: for col", "# Tests ------------------------------------------------------------------- def test_plot_basic(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\",", "\"\"\" config = self.configurator(data_source=TEST_DF, x_col_name=\"a\") view_items = config._data_selection_items() x_editor =", "assert_array_equal(config_dict[\"x_arr\"][\"c\"], np.array([1, 4, 4])) self.assertIn(\"y_arr\", config_dict) self.assertIsInstance(config_dict[\"y_arr\"], dict) self.assertEqual(set(config_dict[\"y_arr\"].keys()), set(d_values))", "\"\"\" config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"e\") view_items = config._data_selection_items()", "data into 2 \"g\": np.array([\"0\", \"1\"] * (LEN // 2)),", "\"null\" if BACKEND_AVAILABLE: from app_common.apptools.testing_utils import assert_obj_gui_works from pybleau.app.plotting.plot_config import", "expected = [\"\"] + config._available_columns self.assertCountEqual(columns, expected) @skipIf(not BACKEND_AVAILABLE, \"No", "x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"e\") self.assertEqual(config.plot_type, self.basic_type) config_dict = config.to_dict() self.assertIsInstance(config_dict, dict)", "self.assertEqual(set(config_dict[\"y_arr\"].keys()), hue_values) assert_array_equal(config_dict[\"y_arr\"][False], TEST_DF[\"b\"][::2]) assert_array_equal(config_dict[\"y_arr\"][True], TEST_DF[\"b\"][1::2]) def test_plot_colored_by_NON_EXISTENT_col(self): config =", "config._numerical_columns self.assertCountEqual(columns, expected) def test_scatter_color_selection_columns(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\",", "LINE_PLOT_TYPE self.numerical_cols_only = True def test_line_data_selection_columns(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\",", "\"No UI backend available\") class TestLinePlotConfig(TestCase, BaseXYPlotConfig): def setUp(self): self.configurator", "self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict) self.assertEqual(set(config_dict[\"x_arr\"].keys()), set(hue_values)) for key in hue_values:", "!= \"null\" if BACKEND_AVAILABLE: from app_common.apptools.testing_utils import assert_obj_gui_works from pybleau.app.plotting.plot_config", "self.assertCountEqual(columns, expected) @skipIf(not BACKEND_AVAILABLE, \"No UI backend available\") class TestBarPlotConfig(TestCase,", "\"No UI backend available\") class TestBarPlotConfig(TestCase, BaseXYPlotConfig): def setUp(self): self.configurator", "TEST_DF) self.assertIs(config.data_source, TEST_DF) hue_values = TEST_DF[\"h\"].unique() # Pulling the x_arr", "\"No UI backend available\") class TestHistogramPlotConfig(BasePlotConfig, TestCase): def setUp(self): self.configurator", "test_scatter_color_selection_columns(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"d\") columns = config._color_selection_columns()", "True def test_line_data_selection_columns(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"d\") columns", "utilities ----------------------------------------------------- def assert_editor_options(self, editor): editor_options = editor.values if self.numerical_cols_only:", "= np.array([\"e\"] * (LEN // 2) + [\"f\"] * (LEN", "config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict) self.assertIsInstance(config_dict[\"x_arr\"], dict) hue_values = set(TEST_DF[\"h\"])", "= \"e\" self.assertTrue(config.plot_style.colorize_by_float) def test_scatter_data_selection_columns(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\",", "from unittest import skipIf, TestCase import os from pandas import", "self.assertCountEqual(columns, expected) def test_scatter_color_selection_columns(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"d\")", "self.assertIn(\"z_arr\", config_dict) self.assertIsInstance(config_dict[\"z_arr\"], np.ndarray) def test_plot_scatter_colored_by_float_col(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\",", "\"b\": [1, 1, 1, 1, 2, 2, 2, 2, 3,", "@skipIf(not BACKEND_AVAILABLE, \"No UI backend available\") class TestHistogramPlotConfig(BasePlotConfig, TestCase): def", "LinePlotConfigurator self.basic_type = LINE_PLOT_TYPE self.numerical_cols_only = True def test_line_data_selection_columns(self): config", "\"value\") self.assertIn(\"g\", config.transformed_data.columns) config_dict = config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict)", "np.float64)) else: self.assertEqual(set(editor_options), set(TEST_DF.columns) | {\"index\"}) class BaseXYPlotConfig(BasePlotConfig): def test_plot_basic(self):", "self.assertEqual(len(config.y_arr[key]), LEN) self.assertEqual(config.y_col_name, \"value\") self.assertIn(\"g\", config.transformed_data.columns) config_dict = config.to_dict() self.assertIsInstance(config_dict,", "config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"e\") self.assertEqual(config.plot_type, self.basic_type) config_dict =", "to split the entire data into 2 \"g\": np.array([\"0\", \"1\"]", "config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict) assert_array_equal(config_dict[\"x_arr\"], TEST_DF[\"a\"].values) def test_plot_NON_EXISTENT_col(self): config", "4], \"b\": [1, 1, 1, 1, 2, 2, 2, 2,", "2, 2, 3, 3, 3, 3, 4, 4, 4, 4],", "def test_style_colorize_by_float_changes_on_color_column_change(self): \"\"\" The dtype of the column to colorize", "self.configurator(data_source=TEST_DF, melt_source_data=True) self.assertEqual(config.plot_type, self.basic_type) # No columns to melt, so", "self.configurator(data_source=TEST_DF, x_col_name=\"NON-EXISTENT\") with self.assertRaises(KeyError): config.to_dict() def test_data_choices(self): \"\"\" Make sure", "= self.configurator(data_source=TEST_DF, x_col_name=\"a\") self.assertEqual(config.plot_type, self.basic_type) config_dict = config.to_dict() self.assertIsInstance(config_dict, dict)", "self.assertRaises(ValueError): config = self.configurator() config.to_dict() def test_bring_up(self): obj = self.configurator(data_source=TEST_DF)", "Make sure different configurators provide the right data choices. Passing", "__future__ import division from unittest import skipIf, TestCase import os", "to colorize controls colorize_by_float. \"\"\" # Color by a string:", "config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"d\") columns = config._color_selection_columns() expected", "self.assertIsNot(config.transformed_data, TEST_DF) self.assertIs(config.data_source, TEST_DF) hue_values = TEST_DF[\"h\"].unique() # Pulling the", "self.assertIsInstance(config_dict[\"z_arr\"], np.ndarray) def test_plot_scatter_colored_by_float_col(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"e\")", "2, 3, 4, 1, 2, 3, 4], \"b\": [1, 1,", "a string: config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"d\") self.assertFalse(config.plot_style.colorize_by_float) #", "------------------------------------------------------------------- def test_plot_basic(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\") self.assertEqual(config.plot_type, self.basic_type) config_dict", "melt_source_data=True, columns_to_melt=[\"e\", \"f\"]) self.assertIsNot(config.transformed_data, TEST_DF) self.assertIs(config.data_source, TEST_DF) # Pulling the", "in hue_values: self.assertEqual(len(config_dict[\"y_arr\"][key]), LEN) @skipIf(not BACKEND_AVAILABLE, \"No UI backend available\")", "= self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"d\") self.assertFalse(config.plot_style.colorize_by_float) # Color by a", "dict) hue_values = set(TEST_DF[\"h\"]) self.assertEqual(set(config_dict[\"x_arr\"].keys()), hue_values) assert_array_equal(config_dict[\"x_arr\"][False], TEST_DF[\"a\"][::2]) assert_array_equal(config_dict[\"x_arr\"][True], TEST_DF[\"a\"][1::2])", "CMAP_SCATTER_PLOT_TYPE, LINE_PLOT_TYPE, \\ BAR_PLOT_TYPE LEN = 16 TEST_DF = DataFrame({\"a\":", "different configurators provide the right data choices. Passing non-numerical \"\"\"", "LINE_PLOT_TYPE, \\ BAR_PLOT_TYPE LEN = 16 TEST_DF = DataFrame({\"a\": [1,", "a column filled with boolean values config = self.configurator(data_source=TEST_DF, x_col_name=\"a\",", "# Color by a float: config.z_col_name = \"e\" self.assertTrue(config.plot_style.colorize_by_float) def", "column to colorize controls colorize_by_float. \"\"\" # Color by a", "\"No UI backend available\") class TestHeatmapPlotConfig(BasePlotConfig, TestCase): def setUp(self): self.configurator", "np.array([\"0\", \"1\"] * (LEN // 2)), \"h\": np.array([0, 1] *", "# No columns to melt, so no transformation: self.assertIs(config.data_source, TEST_DF)", "test_melt_mode_with_melted_columns(self): config = self.configurator(data_source=TEST_DF, melt_source_data=True, columns_to_melt=[\"e\", \"f\"]) self.assertIsNot(config.transformed_data, TEST_DF) self.assertIs(config.data_source,", "self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\") self.assertEqual(config.plot_type, self.basic_type) config_dict = config.to_dict() self.assertIsInstance(config_dict, dict)", "Assertion utilities ----------------------------------------------------- def assert_editor_options(self, editor): editor_options = editor.values if", "def test_plot_colored_by_bool_col(self): # Color by a column filled with boolean", "self.basic_type = BAR_PLOT_TYPE self.numerical_cols_only = False def test_data_choices(self): \"\"\" Make", "def setUp(self): self.configurator = HistogramPlotConfigurator self.basic_type = HIST_PLOT_TYPE self.numerical_cols_only =", "config = self.configurator(data_source=TEST_DF, melt_source_data=True, columns_to_melt=[\"e\", \"f\"], z_col_name=\"h\") self.assertIsNot(config.transformed_data, TEST_DF) self.assertIs(config.data_source,", "config._data_selection_columns() expected = config._numerical_columns self.assertCountEqual(columns, expected) def test_line_color_selection_columns(self): config =", "reset of the x_col_name x_values = np.array([\"e\"]*LEN+[\"f\"]*LEN) assert_array_equal(config.x_arr, x_values) self.assertEqual(config.x_col_name,", "5, 6], \"d\": list(\"ababcabcdabcdeab\"), \"e\": np.random.randn(LEN), \"f\": range(LEN), # Highly", "BACKEND_AVAILABLE = os.environ.get(\"ETS_TOOLKIT\", \"qt4\") != \"null\" if BACKEND_AVAILABLE: from app_common.apptools.testing_utils", "self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict) self.assertIsInstance(config_dict[\"x_arr\"], dict) hue_values = set(TEST_DF[\"h\"]) self.assertEqual(set(config_dict[\"x_arr\"].keys()),", "# Color by a column filled with boolean values config", "[1, 2, 3, 4, 1, 2, 3, 4, 1, 2,", "a reset of the x_col_name x_values = np.array([\"e\"]*LEN+[\"f\"]*LEN) assert_array_equal(config.x_arr, x_values)", "self.assertTrue(config.plot_style.colorize_by_float) def test_scatter_data_selection_columns(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"d\") columns", "self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict) assert_array_equal(config_dict[\"x_arr\"], x_values) self.assertIn(\"y_arr\", config_dict) self.assertEqual(len(config_dict[\"y_arr\"]), 2", "+ [\"f\"] * (LEN // 2)) self.assertEqual(set(config.x_arr.keys()), set(hue_values)) for key", "1, 2, 3, 4], \"b\": [1, 1, 1, 1, 2,", "configurators provide the right data choices. Passing non-numerical \"\"\" config", "6], \"d\": list(\"ababcabcdabcdeab\"), \"e\": np.random.randn(LEN), \"f\": range(LEN), # Highly repetitive", "self.numerical_cols_only = True def test_plot_scatter_colored_by_int_col(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\",", "self.assertIs(config.data_source, TEST_DF) # Pulling the x_arr forces a reset of", "self.assertEqual(config.plot_type, self.basic_type) # No columns to melt, so no transformation:", "a reset of the x_col_name x_values = np.array([\"e\"] * (LEN", "x_col_name=\"a\", y_col_name=\"b\") view_items = config._data_selection_items() x_editor = view_items[0].content[0].editor self.assert_editor_options(x_editor) y_editor", "------------------------------------------------------------------- def test_plot_basic(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"e\") self.assertEqual(config.plot_type,", "x_col_name=\"a\") view_items = config._data_selection_items() x_editor = view_items[0].content[0].editor self.assert_editor_options(x_editor) @skipIf(not BACKEND_AVAILABLE,", "setUp(self): self.configurator = HeatmapPlotConfigurator self.basic_type = HEATMAP_PLOT_TYPE self.numerical_cols_only = True", "self.assertIs(config.transformed_data, TEST_DF) def test_melt_mode_with_melted_columns(self): config = self.configurator(data_source=TEST_DF, melt_source_data=True, columns_to_melt=[\"e\", \"f\"])", "@skipIf(not BACKEND_AVAILABLE, \"No UI backend available\") class TestLinePlotConfig(TestCase, BaseXYPlotConfig): def", "config_dict = config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict) assert_array_equal(config_dict[\"x_arr\"], TEST_DF[\"a\"].values) self.assertIn(\"y_arr\",", "self.configurator = ScatterPlotConfigurator self.basic_type = SCATTER_PLOT_TYPE self.numerical_cols_only = True def", "self.basic_type = LINE_PLOT_TYPE self.numerical_cols_only = True def test_line_data_selection_columns(self): config =", "self.assertIsInstance(arr, np.ndarray) # For example: assert_array_equal(config_dict[\"x_arr\"][\"c\"], np.array([1, 4, 4])) self.assertIn(\"y_arr\",", "self.basic_type) config_dict = config.to_dict() self.assertIsInstance(config_dict, dict) def test_plot_colored_by_NON_EXISTENT_col(self): config =", "\"index\": self.assertIn(TEST_DF[col].dtype, (np.int64, np.float64)) else: self.assertEqual(set(editor_options), set(TEST_DF.columns) | {\"index\"}) class", "= self.configurator(data_source=TEST_DF, melt_source_data=True, columns_to_melt=[\"e\", \"f\"], z_col_name=\"h\") self.assertIsNot(config.transformed_data, TEST_DF) self.assertIs(config.data_source, TEST_DF)", "True # Tests ------------------------------------------------------------------- def test_plot_basic(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\")", "config._data_selection_items() x_editor = view_items[0].content[0].editor self.assert_editor_options(x_editor) y_editor = view_items[1].content[0].editor self.assert_editor_options(y_editor) def", "LEN) self.assertEqual(config.y_col_name, \"value\") self.assertIn(\"g\", config.transformed_data.columns) config_dict = config.to_dict() self.assertIsInstance(config_dict, dict)", "self.assertIsNot(config.transformed_data, TEST_DF) self.assertIs(config.data_source, TEST_DF) # Pulling the x_arr forces a", "choices. Passing non-numerical \"\"\" config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"e\")", "(LEN // 2)), \"h\": np.array([0, 1] * (LEN // 2),", "self.basic_type = HEATMAP_PLOT_TYPE self.numerical_cols_only = True # Tests ------------------------------------------------------------------- def", "view_items[0].content[0].editor self.assert_editor_options(x_editor) @skipIf(not BACKEND_AVAILABLE, \"No UI backend available\") class TestHeatmapPlotConfig(BasePlotConfig,", "test_line_color_selection_columns(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"d\") columns = config._color_selection_columns()", "test_melt_mode_with_melted_columns_and_str_color(self): config = self.configurator(data_source=TEST_DF, melt_source_data=True, columns_to_melt=[\"e\", \"f\"], z_col_name=\"g\") self.assertIsNot(config.transformed_data, TEST_DF)", "obj = self.configurator(data_source=TEST_DF) assert_obj_gui_works(obj) # Assertion utilities ----------------------------------------------------- def assert_editor_options(self,", "\"variable\") for key in hue_values: self.assertEqual(len(config.y_arr[key]), LEN) self.assertEqual(config.y_col_name, \"value\") self.assertIn(\"g\",", "x_col_name=\"a\", y_col_name=\"b\") view_items = config._data_selection_items() x_editor = view_items[0].content[3].content[0].content[0].editor self.assert_editor_options(x_editor) def", "x_values) self.assertEqual(config.x_col_name, \"variable\") for key in hue_values: self.assertEqual(len(config.y_arr[key]), LEN) self.assertEqual(config.y_col_name,", "= config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict) assert_array_equal(config_dict[\"x_arr\"], TEST_DF[\"a\"].values) self.assertIn(\"y_arr\", config_dict)", "colorize_by_float. \"\"\" # Color by a string: config = self.configurator(data_source=TEST_DF,", "3, 3, 4, 4, 4, 4], \"c\": [1, 2, 3,", "\\ HEATMAP_PLOT_TYPE, HistogramPlotConfigurator, HIST_PLOT_TYPE, \\ LinePlotConfigurator, BarPlotConfigurator, ScatterPlotConfigurator, \\ SCATTER_PLOT_TYPE,", "config_dict = config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict) self.assertIsInstance(config_dict[\"x_arr\"], dict) d_values", "self.assertIn(\"x_arr\", config_dict) self.assertIsInstance(config_dict[\"x_arr\"], dict) d_values = TEST_DF[\"d\"].unique() self.assertEqual(set(config_dict[\"x_arr\"].keys()), set(d_values)) for", "4])) self.assertIn(\"y_arr\", config_dict) self.assertIsInstance(config_dict[\"y_arr\"], dict) self.assertEqual(set(config_dict[\"y_arr\"].keys()), set(d_values)) for arr in", "np.ndarray) self.assertIn(\"z_arr\", config_dict) self.assertIsInstance(config_dict[\"z_arr\"], np.ndarray) def test_style_colorize_by_float_changes_on_color_column_change(self): \"\"\" The dtype", "config_dict[\"x_arr\"].values(): self.assertIsInstance(arr, np.ndarray) # For example: assert_array_equal(config_dict[\"x_arr\"][\"c\"], np.array([1, 4, 4]))", "with self.assertRaises(ValueError): config = self.configurator() config.to_dict() def test_bring_up(self): obj =", "y_col_name=\"b\", z_col_name=\"d\") columns = config._color_selection_columns() expected = [\"\"] + config._available_columns", "import assert_array_equal BACKEND_AVAILABLE = os.environ.get(\"ETS_TOOLKIT\", \"qt4\") != \"null\" if BACKEND_AVAILABLE:", "assert_array_equal(config.x_arr, x_values) self.assertEqual(config.x_col_name, \"variable\") self.assertEqual(len(config.y_arr), 2 * LEN) self.assertEqual(config.y_col_name, \"value\")", "----------------------------------------------------- def assert_editor_options(self, editor): editor_options = editor.values if self.numerical_cols_only: for", "\"qt4\") != \"null\" if BACKEND_AVAILABLE: from app_common.apptools.testing_utils import assert_obj_gui_works from", "config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict) self.assertIsInstance(config_dict[\"x_arr\"], np.ndarray) self.assertIn(\"y_arr\", config_dict) self.assertIsInstance(config_dict[\"y_arr\"],", "self.configurator = BarPlotConfigurator self.basic_type = BAR_PLOT_TYPE self.numerical_cols_only = False def", "dict) self.assertIn(\"x_arr\", config_dict) self.assertEqual(set(config_dict[\"x_arr\"].keys()), set(hue_values)) for key in hue_values: assert_array_equal(config_dict[\"x_arr\"][key],", "3, 4], \"b\": [1, 1, 1, 1, 2, 2, 2,", "# Highly repetitive column to split the entire data into", "# For example: assert_array_equal(config_dict[\"x_arr\"][\"c\"], np.array([1, 4, 4])) self.assertIn(\"y_arr\", config_dict) self.assertIsInstance(config_dict[\"y_arr\"],", "= True # Tests ------------------------------------------------------------------- def test_plot_basic(self): config = self.configurator(data_source=TEST_DF,", "config_dict = config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict) self.assertIsInstance(config_dict[\"x_arr\"], dict) hue_values", "dict) d_values = TEST_DF[\"d\"].unique() self.assertEqual(set(config_dict[\"x_arr\"].keys()), set(d_values)) for arr in config_dict[\"x_arr\"].values():", "config_dict = config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict) assert_array_equal(config_dict[\"x_arr\"], x_values) self.assertIn(\"y_arr\",", "for col in editor_options: if col != \"index\": self.assertIn(TEST_DF[col].dtype, (np.int64,", "self.configurator(data_source=TEST_DF, melt_source_data=True, columns_to_melt=[\"e\", \"f\"], z_col_name=\"g\") self.assertIsNot(config.transformed_data, TEST_DF) self.assertIs(config.data_source, TEST_DF) hue_values", "HeatmapPlotConfigurator self.basic_type = HEATMAP_PLOT_TYPE self.numerical_cols_only = True # Tests -------------------------------------------------------------------", "z_col_name=\"e\") self.assertEqual(config.plot_type, CMAP_SCATTER_PLOT_TYPE) config_dict = config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict)", "data choices. Passing non-numerical \"\"\" config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\",", "import skipIf, TestCase import os from pandas import DataFrame import", "assert_array_equal(config_dict[\"y_arr\"], TEST_DF[\"b\"].values) def test_data_choices(self): \"\"\" Make sure different configurators provide", "controls colorize_by_float. \"\"\" # Color by a string: config =", "= set(TEST_DF[\"h\"]) self.assertEqual(set(config_dict[\"x_arr\"].keys()), hue_values) assert_array_equal(config_dict[\"x_arr\"][False], TEST_DF[\"a\"][::2]) assert_array_equal(config_dict[\"x_arr\"][True], TEST_DF[\"a\"][1::2]) self.assertIn(\"y_arr\", config_dict)", "= self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\") view_items = config._data_selection_items() x_editor = view_items[0].content[3].content[0].content[0].editor", "self.assertRaises(KeyError): config.to_dict() @skipIf(not BACKEND_AVAILABLE, \"No UI backend available\") class TestScatterPlotConfig(TestCase,", "[1, 1, 1, 1, 2, 2, 2, 2, 3, 3,", "z_col_name=\"d\") columns = config._color_selection_columns() expected = [\"\"] + config._available_columns self.assertCountEqual(columns,", "to melt, so no transformation: self.assertIs(config.data_source, TEST_DF) self.assertIs(config.transformed_data, TEST_DF) def", "= config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict) self.assertIsInstance(config_dict[\"x_arr\"], dict) hue_values =", "set(hue_values)) for key in hue_values: assert_array_equal(config_dict[\"x_arr\"][key], x_values) self.assertIn(\"y_arr\", config_dict) for", "\"d\": list(\"ababcabcdabcdeab\"), \"e\": np.random.randn(LEN), \"f\": range(LEN), # Highly repetitive column", "= config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict) self.assertIsInstance(config_dict[\"x_arr\"], np.ndarray) self.assertIn(\"y_arr\", config_dict)", "2, 3, 4, 2, 3, 1, 1, 4, 4, 5,", "No columns to melt, so no transformation: self.assertIs(config.data_source, TEST_DF) self.assertIs(config.transformed_data,", "= self.configurator(data_source=TEST_DF, x_col_name=\"NON-EXISTENT\") with self.assertRaises(KeyError): config.to_dict() def test_data_choices(self): \"\"\" Make", "from pybleau.app.plotting.plot_config import HeatmapPlotConfigurator, \\ HEATMAP_PLOT_TYPE, HistogramPlotConfigurator, HIST_PLOT_TYPE, \\ LinePlotConfigurator,", "x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"d\") self.assertFalse(config.plot_style.colorize_by_float) # Color by a float: config.z_col_name", "available\") class TestBarPlotConfig(TestCase, BaseXYPlotConfig): def setUp(self): self.configurator = BarPlotConfigurator self.basic_type", "LinePlotConfigurator, BarPlotConfigurator, ScatterPlotConfigurator, \\ SCATTER_PLOT_TYPE, CMAP_SCATTER_PLOT_TYPE, LINE_PLOT_TYPE, \\ BAR_PLOT_TYPE LEN", "assert_editor_options(self, editor): editor_options = editor.values if self.numerical_cols_only: for col in", "the x_arr forces a reset of the x_col_name x_values =", "= HistogramPlotConfigurator self.basic_type = HIST_PLOT_TYPE self.numerical_cols_only = True # Tests", "2) + [\"f\"] * (LEN // 2)) self.assertEqual(set(config.x_arr.keys()), set(hue_values)) for", "key in hue_values: assert_array_equal(config_dict[\"x_arr\"][key], x_values) self.assertIn(\"y_arr\", config_dict) for key in", "2, 3])) def test_plot_colored_by_bool_col(self): # Color by a column filled", "= BarPlotConfigurator self.basic_type = BAR_PLOT_TYPE self.numerical_cols_only = False def test_data_choices(self):", "\"value\") config_dict = config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict) assert_array_equal(config_dict[\"x_arr\"], x_values)", "2)) self.assertEqual(set(config.x_arr.keys()), set(hue_values)) for key in hue_values: assert_array_equal(config.x_arr[key], x_values) self.assertEqual(config.x_col_name,", "config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\") view_items = config._data_selection_items() x_editor =", "self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"h\") self.assertIn(config.plot_type, self.basic_type) config_dict = config.to_dict() self.assertIsInstance(config_dict,", "self.assertIn(\"y_arr\", config_dict) self.assertIsInstance(config_dict[\"y_arr\"], dict) self.assertEqual(set(config_dict[\"y_arr\"].keys()), set(d_values)) for arr in config_dict[\"y_arr\"].values():", "list(\"ababcabcdabcdeab\"), \"e\": np.random.randn(LEN), \"f\": range(LEN), # Highly repetitive column to", "= self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"d\") columns = config._color_selection_columns() expected =", "TestBarPlotConfig(TestCase, BaseXYPlotConfig): def setUp(self): self.configurator = BarPlotConfigurator self.basic_type = BAR_PLOT_TYPE", "self.assertIn(\"y_arr\", config_dict) for key in hue_values: self.assertEqual(len(config_dict[\"y_arr\"][key]), LEN) @skipIf(not BACKEND_AVAILABLE,", "hue_values = set(TEST_DF[\"h\"]) self.assertEqual(set(config_dict[\"x_arr\"].keys()), hue_values) assert_array_equal(config_dict[\"x_arr\"][False], TEST_DF[\"a\"][::2]) assert_array_equal(config_dict[\"x_arr\"][True], TEST_DF[\"a\"][1::2]) self.assertIn(\"y_arr\",", "self.assertCountEqual(columns, expected) @skipIf(not BACKEND_AVAILABLE, \"No UI backend available\") class TestLinePlotConfig(TestCase,", "test_plot_NON_EXISTENT_col(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"NON-EXISTENT\") with self.assertRaises(KeyError): config.to_dict() def test_data_choices(self):", "TEST_DF[\"b\"].values) def test_data_choices(self): \"\"\" Make sure different configurators provide the", "z_col_name=\"NON-EXISTENT\") with self.assertRaises(KeyError): config.to_dict() @skipIf(not BACKEND_AVAILABLE, \"No UI backend available\")", "def test_plot_scatter_colored_by_int_col(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"c\") self.assertEqual(config.plot_type, CMAP_SCATTER_PLOT_TYPE)", "2, 3, 3, 3, 3, 4, 4, 4, 4], \"c\":", "key in hue_values: self.assertEqual(len(config_dict[\"y_arr\"][key]), LEN) @skipIf(not BACKEND_AVAILABLE, \"No UI backend", "right data choices. Passing non-numerical \"\"\" config = self.configurator(data_source=TEST_DF, x_col_name=\"a\",", "self.assertEqual(len(config_dict[\"y_arr\"]), 2 * LEN) def test_melt_mode_with_melted_columns_and_str_color(self): config = self.configurator(data_source=TEST_DF, melt_source_data=True,", "assert_array_equal(config_dict[\"y_arr\"][False], TEST_DF[\"b\"][::2]) assert_array_equal(config_dict[\"y_arr\"][True], TEST_DF[\"b\"][1::2]) def test_plot_colored_by_NON_EXISTENT_col(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\",", "\"f\": range(LEN), # Highly repetitive column to split the entire", "view_items = config._data_selection_items() x_editor = view_items[0].content[0].editor self.assert_editor_options(x_editor) @skipIf(not BACKEND_AVAILABLE, \"No", "config.to_dict() def test_bring_up(self): obj = self.configurator(data_source=TEST_DF) assert_obj_gui_works(obj) # Assertion utilities", "assert_array_equal(config.x_arr[key], x_values) self.assertEqual(config.x_col_name, \"variable\") for key in hue_values: self.assertEqual(len(config.y_arr[key]), LEN)", "= config._data_selection_columns() expected = config._numerical_columns self.assertCountEqual(columns, expected) def test_scatter_color_selection_columns(self): config", "unittest import skipIf, TestCase import os from pandas import DataFrame", "= DataFrame({\"a\": [1, 2, 3, 4, 1, 2, 3, 4,", "in hue_values: assert_array_equal(config.x_arr[key], x_values) self.assertEqual(config.x_col_name, \"variable\") for key in hue_values:", "self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"e\") self.assertEqual(config.plot_type, CMAP_SCATTER_PLOT_TYPE) config_dict = config.to_dict() self.assertIsInstance(config_dict,", "config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"e\") view_items = config._data_selection_items() x_editor", "self.assertIsInstance(config_dict[\"y_arr\"], np.ndarray) self.assertIn(\"z_arr\", config_dict) self.assertIsInstance(config_dict[\"z_arr\"], np.ndarray) def test_style_colorize_by_float_changes_on_color_column_change(self): \"\"\" The", "self.assertIn(\"x_arr\", config_dict) assert_array_equal(config_dict[\"x_arr\"], x_values) self.assertIn(\"y_arr\", config_dict) self.assertEqual(len(config_dict[\"y_arr\"]), 2 * LEN)", "\"f\"], z_col_name=\"g\") self.assertIsNot(config.transformed_data, TEST_DF) self.assertIs(config.data_source, TEST_DF) hue_values = TEST_DF[\"g\"].unique() #", "2)), \"h\": np.array([0, 1] * (LEN // 2), dtype=bool), })", "colorize controls colorize_by_float. \"\"\" # Color by a string: config", "3, 3, 3, 3, 4, 4, 4, 4], \"c\": [1,", "provide the right data choices. \"\"\" config = self.configurator(data_source=TEST_DF, x_col_name=\"a\",", "so no transformation: self.assertIs(config.data_source, TEST_DF) self.assertIs(config.transformed_data, TEST_DF) def test_melt_mode_with_melted_columns(self): config", "assert_array_equal(config_dict[\"x_arr\"], TEST_DF[\"a\"].values) def test_plot_NON_EXISTENT_col(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"NON-EXISTENT\") with self.assertRaises(KeyError):", "config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"c\") self.assertEqual(config.plot_type, CMAP_SCATTER_PLOT_TYPE) config_dict =", "self.assertIn(config.plot_type, self.basic_type) config_dict = config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict) self.assertIsInstance(config_dict[\"x_arr\"],", "self.configurator(data_source=TEST_DF, melt_source_data=True, columns_to_melt=[\"e\", \"f\"]) self.assertIsNot(config.transformed_data, TEST_DF) self.assertIs(config.data_source, TEST_DF) # Pulling", "= HeatmapPlotConfigurator self.basic_type = HEATMAP_PLOT_TYPE self.numerical_cols_only = True # Tests", "assert_array_equal(config_dict[\"y_arr\"][True], TEST_DF[\"b\"][1::2]) def test_plot_colored_by_NON_EXISTENT_col(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"NON-EXISTENT\")", "self.assertEqual(set(config_dict[\"x_arr\"].keys()), set(hue_values)) for key in hue_values: assert_array_equal(config_dict[\"x_arr\"][key], x_values) self.assertIn(\"y_arr\", config_dict)", "= self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"d\") columns = config._data_selection_columns() expected =", "test_melt_mode_with_melted_columns_and_bool_color(self): config = self.configurator(data_source=TEST_DF, melt_source_data=True, columns_to_melt=[\"e\", \"f\"], z_col_name=\"h\") self.assertIsNot(config.transformed_data, TEST_DF)", "z_col_name=\"h\") self.assertIn(config.plot_type, self.basic_type) config_dict = config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict)", "4, 4])) self.assertIn(\"y_arr\", config_dict) self.assertIsInstance(config_dict[\"y_arr\"], dict) self.assertEqual(set(config_dict[\"y_arr\"].keys()), set(d_values)) for arr", "UI backend available\") class TestScatterPlotConfig(TestCase, BaseXYPlotConfig): def setUp(self): self.configurator =", "np from numpy.testing import assert_array_equal BACKEND_AVAILABLE = os.environ.get(\"ETS_TOOLKIT\", \"qt4\") !=", "in editor_options: if col != \"index\": self.assertIn(TEST_DF[col].dtype, (np.int64, np.float64)) else:", "columns_to_melt=[\"e\", \"f\"], z_col_name=\"g\") self.assertIsNot(config.transformed_data, TEST_DF) self.assertIs(config.data_source, TEST_DF) hue_values = TEST_DF[\"g\"].unique()", "config_dict) self.assertEqual(len(config_dict[\"y_arr\"]), 2 * LEN) def test_melt_mode_with_melted_columns_and_str_color(self): config = self.configurator(data_source=TEST_DF,", "Color by a string: config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"d\")", "self.assertEqual(config.y_col_name, \"value\") config_dict = config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict) assert_array_equal(config_dict[\"x_arr\"],", "self.assertIs(config.data_source, TEST_DF) hue_values = TEST_DF[\"h\"].unique() # Pulling the x_arr forces", "= os.environ.get(\"ETS_TOOLKIT\", \"qt4\") != \"null\" if BACKEND_AVAILABLE: from app_common.apptools.testing_utils import", "@skipIf(not BACKEND_AVAILABLE, \"No UI backend available\") class TestHeatmapPlotConfig(BasePlotConfig, TestCase): def", "| {\"index\"}) class BaseXYPlotConfig(BasePlotConfig): def test_plot_basic(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\",", "else: self.assertEqual(set(editor_options), set(TEST_DF.columns) | {\"index\"}) class BaseXYPlotConfig(BasePlotConfig): def test_plot_basic(self): config", "self.assertEqual(set(editor_options), set(TEST_DF.columns) | {\"index\"}) class BaseXYPlotConfig(BasePlotConfig): def test_plot_basic(self): config =", "self.assertIsInstance(config_dict[\"y_arr\"], dict) self.assertEqual(set(config_dict[\"y_arr\"].keys()), set(d_values)) for arr in config_dict[\"y_arr\"].values(): self.assertIsInstance(arr, np.ndarray)", "setUp(self): self.configurator = HistogramPlotConfigurator self.basic_type = HIST_PLOT_TYPE self.numerical_cols_only = True", "range(LEN), # Highly repetitive column to split the entire data", "= config._numerical_columns self.assertCountEqual(columns, expected) def test_line_color_selection_columns(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\",", "setUp(self): self.configurator = BarPlotConfigurator self.basic_type = BAR_PLOT_TYPE self.numerical_cols_only = False", "melt, so no transformation: self.assertIs(config.data_source, TEST_DF) self.assertIs(config.transformed_data, TEST_DF) def test_melt_mode_with_melted_columns(self):", "= LINE_PLOT_TYPE self.numerical_cols_only = True def test_line_data_selection_columns(self): config = self.configurator(data_source=TEST_DF,", "x_editor = view_items[0].content[3].content[0].content[0].editor self.assert_editor_options(x_editor) def test_melt_mode_no_effect(self): config = self.configurator(data_source=TEST_DF, melt_source_data=True)", "TEST_DF) hue_values = TEST_DF[\"h\"].unique() # Pulling the x_arr forces a", "editor.values if self.numerical_cols_only: for col in editor_options: if col !=", "self.assertIsInstance(config_dict[\"y_arr\"], dict) self.assertEqual(set(config_dict[\"y_arr\"].keys()), hue_values) assert_array_equal(config_dict[\"y_arr\"][False], TEST_DF[\"b\"][::2]) assert_array_equal(config_dict[\"y_arr\"][True], TEST_DF[\"b\"][1::2]) def test_plot_colored_by_NON_EXISTENT_col(self):", "LEN) self.assertEqual(config.y_col_name, \"value\") self.assertIn(\"h\", config.transformed_data.columns) config_dict = config.to_dict() self.assertIsInstance(config_dict, dict)", "key in hue_values: assert_array_equal(config.x_arr[key], x_values) self.assertEqual(config.x_col_name, \"variable\") for key in", "for arr in config_dict[\"y_arr\"].values(): self.assertIsInstance(arr, np.ndarray) # For example: assert_array_equal(config_dict[\"y_arr\"][\"c\"],", "= self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\") self.assertEqual(config.plot_type, self.basic_type) config_dict = config.to_dict() self.assertIsInstance(config_dict,", "np.ndarray) # For example: assert_array_equal(config_dict[\"y_arr\"][\"c\"], np.array([2, 2, 3])) def test_plot_colored_by_bool_col(self):", "with boolean values config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"h\") self.assertIn(config.plot_type,", "skipIf, TestCase import os from pandas import DataFrame import numpy", "config_dict) assert_array_equal(config_dict[\"x_arr\"], TEST_DF[\"a\"].values) def test_plot_NON_EXISTENT_col(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"NON-EXISTENT\") with", "UI backend available\") class TestHeatmapPlotConfig(BasePlotConfig, TestCase): def setUp(self): self.configurator =", "self.numerical_cols_only = False def test_data_choices(self): \"\"\" Make sure different configurators", "3, 4, 1, 2, 3, 4], \"b\": [1, 1, 1,", "x_values) self.assertIn(\"y_arr\", config_dict) for key in hue_values: self.assertEqual(len(config_dict[\"y_arr\"][key]), LEN) def", "{\"index\"}) class BaseXYPlotConfig(BasePlotConfig): def test_plot_basic(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\")", "test_plot_basic(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"e\") self.assertEqual(config.plot_type, self.basic_type) config_dict", "1, 2, 3, 4, 1, 2, 3, 4, 1, 2,", "BACKEND_AVAILABLE, \"No UI backend available\") class TestScatterPlotConfig(TestCase, BaseXYPlotConfig): def setUp(self):", "the column to colorize controls colorize_by_float. \"\"\" # Color by", "with boolean values config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"d\") self.assertIn(config.plot_type,", "dtype of the column to colorize controls colorize_by_float. \"\"\" #", "from numpy.testing import assert_array_equal BACKEND_AVAILABLE = os.environ.get(\"ETS_TOOLKIT\", \"qt4\") != \"null\"", "a float: config.z_col_name = \"e\" self.assertTrue(config.plot_style.colorize_by_float) def test_scatter_data_selection_columns(self): config =", "= SCATTER_PLOT_TYPE self.numerical_cols_only = True def test_plot_scatter_colored_by_int_col(self): config = self.configurator(data_source=TEST_DF,", "self.numerical_cols_only = True def test_line_data_selection_columns(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\",", "def test_bring_up(self): obj = self.configurator(data_source=TEST_DF) assert_obj_gui_works(obj) # Assertion utilities -----------------------------------------------------", "arr in config_dict[\"x_arr\"].values(): self.assertIsInstance(arr, np.ndarray) # For example: assert_array_equal(config_dict[\"x_arr\"][\"c\"], np.array([1,", "* (LEN // 2)) self.assertEqual(set(config.x_arr.keys()), set(hue_values)) for key in hue_values:", "the entire data into 2 \"g\": np.array([\"0\", \"1\"] * (LEN", "string: config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"d\") self.assertFalse(config.plot_style.colorize_by_float) # Color", "TEST_DF[\"a\"][::2]) assert_array_equal(config_dict[\"x_arr\"][True], TEST_DF[\"a\"][1::2]) self.assertIn(\"y_arr\", config_dict) self.assertIsInstance(config_dict[\"y_arr\"], dict) self.assertEqual(set(config_dict[\"y_arr\"].keys()), hue_values) assert_array_equal(config_dict[\"y_arr\"][False],", "y_col_name=\"b\", z_col_name=\"NON-EXISTENT\") with self.assertRaises(KeyError): config.to_dict() @skipIf(not BACKEND_AVAILABLE, \"No UI backend", "repetitive column to split the entire data into 2 \"g\":", "= False def test_data_choices(self): \"\"\" Make sure different configurators provide", "entire data into 2 \"g\": np.array([\"0\", \"1\"] * (LEN //", "self.configurator(data_source=TEST_DF, melt_source_data=True, columns_to_melt=[\"e\", \"f\"], z_col_name=\"h\") self.assertIsNot(config.transformed_data, TEST_DF) self.assertIs(config.data_source, TEST_DF) hue_values", "HEATMAP_PLOT_TYPE self.numerical_cols_only = True # Tests ------------------------------------------------------------------- def test_plot_basic(self): config", "test_style_colorize_by_float_changes_on_color_column_change(self): \"\"\" The dtype of the column to colorize controls", "TEST_DF[\"b\"][::2]) assert_array_equal(config_dict[\"y_arr\"][True], TEST_DF[\"b\"][1::2]) def test_plot_colored_by_NON_EXISTENT_col(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\",", "config = self.configurator(data_source=TEST_DF, x_col_name=\"NON-EXISTENT\") with self.assertRaises(KeyError): config.to_dict() def test_data_choices(self): \"\"\"", "= self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"e\") view_items = config._data_selection_items() x_editor =", "test_plot_scatter_colored_by_int_col(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"c\") self.assertEqual(config.plot_type, CMAP_SCATTER_PLOT_TYPE) config_dict", "self.numerical_cols_only: for col in editor_options: if col != \"index\": self.assertIn(TEST_DF[col].dtype,", "self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"e\") self.assertEqual(config.plot_type, self.basic_type) config_dict = config.to_dict() self.assertIsInstance(config_dict,", "sure different configurators provide the right data choices. Passing non-numerical", "hue_values: self.assertEqual(len(config_dict[\"y_arr\"][key]), LEN) def test_melt_mode_with_melted_columns_and_bool_color(self): config = self.configurator(data_source=TEST_DF, melt_source_data=True, columns_to_melt=[\"e\",", "self.assertIsInstance(config_dict[\"x_arr\"], dict) hue_values = set(TEST_DF[\"h\"]) self.assertEqual(set(config_dict[\"x_arr\"].keys()), hue_values) assert_array_equal(config_dict[\"x_arr\"][False], TEST_DF[\"a\"][::2]) assert_array_equal(config_dict[\"x_arr\"][True],", "columns_to_melt=[\"e\", \"f\"], z_col_name=\"h\") self.assertIsNot(config.transformed_data, TEST_DF) self.assertIs(config.data_source, TEST_DF) hue_values = TEST_DF[\"h\"].unique()", "np.array([\"e\"]*LEN+[\"f\"]*LEN) assert_array_equal(config.x_arr, x_values) self.assertEqual(config.x_col_name, \"variable\") self.assertEqual(len(config.y_arr), 2 * LEN) self.assertEqual(config.y_col_name,", "for key in hue_values: self.assertEqual(len(config.y_arr[key]), LEN) self.assertEqual(config.y_col_name, \"value\") self.assertIn(\"g\", config.transformed_data.columns)", "view_items[0].content[0].editor self.assert_editor_options(x_editor) y_editor = view_items[1].content[0].editor self.assert_editor_options(y_editor) def test_plot_colored_by_str_col(self): # Color", "class TestHistogramPlotConfig(BasePlotConfig, TestCase): def setUp(self): self.configurator = HistogramPlotConfigurator self.basic_type =", "config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"d\") self.assertIn(config.plot_type, self.basic_type) config_dict =", "self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"NON-EXISTENT\") with self.assertRaises(KeyError): config.to_dict() def test_data_choices(self): \"\"\"", "self.assertIn(\"y_arr\", config_dict) self.assertIsInstance(config_dict[\"y_arr\"], np.ndarray) self.assertIn(\"z_arr\", config_dict) self.assertIsInstance(config_dict[\"z_arr\"], np.ndarray) def test_style_colorize_by_float_changes_on_color_column_change(self):", "x_col_name x_values = np.array([\"e\"]*LEN+[\"f\"]*LEN) assert_array_equal(config.x_arr, x_values) self.assertEqual(config.x_col_name, \"variable\") self.assertEqual(len(config.y_arr), 2", "3])) def test_plot_colored_by_bool_col(self): # Color by a column filled with", "= TEST_DF[\"g\"].unique() # Pulling the x_arr forces a reset of", "class TestHeatmapPlotConfig(BasePlotConfig, TestCase): def setUp(self): self.configurator = HeatmapPlotConfigurator self.basic_type =", "assert_array_equal(config_dict[\"x_arr\"], TEST_DF[\"a\"].values) self.assertIn(\"y_arr\", config_dict) assert_array_equal(config_dict[\"y_arr\"], TEST_DF[\"b\"].values) def test_data_choices(self): \"\"\" Make", "self.assertIs(config.data_source, TEST_DF) hue_values = TEST_DF[\"g\"].unique() # Pulling the x_arr forces", "1, 1, 1, 2, 2, 2, 2, 3, 3, 3,", "y_col_name=\"b\", z_col_name=\"c\") self.assertEqual(config.plot_type, CMAP_SCATTER_PLOT_TYPE) config_dict = config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\",", "= view_items[0].content[3].content[0].content[0].editor self.assert_editor_options(x_editor) def test_melt_mode_no_effect(self): config = self.configurator(data_source=TEST_DF, melt_source_data=True) self.assertEqual(config.plot_type,", "available\") class TestHeatmapPlotConfig(BasePlotConfig, TestCase): def setUp(self): self.configurator = HeatmapPlotConfigurator self.basic_type", "config_dict) self.assertIsInstance(config_dict[\"x_arr\"], np.ndarray) self.assertIn(\"y_arr\", config_dict) self.assertIsInstance(config_dict[\"y_arr\"], np.ndarray) self.assertIn(\"z_arr\", config_dict) self.assertIsInstance(config_dict[\"z_arr\"],", "reset of the x_col_name x_values = np.array([\"e\"] * (LEN //", "choices. \"\"\" config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\") view_items = config._data_selection_items()", "self.basic_type = HIST_PLOT_TYPE self.numerical_cols_only = True # Tests ------------------------------------------------------------------- def", "self.assertIsInstance(config_dict[\"z_arr\"], np.ndarray) def test_style_colorize_by_float_changes_on_color_column_change(self): \"\"\" The dtype of the column", "TEST_DF) hue_values = TEST_DF[\"g\"].unique() # Pulling the x_arr forces a", "For example: assert_array_equal(config_dict[\"x_arr\"][\"c\"], np.array([1, 4, 4])) self.assertIn(\"y_arr\", config_dict) self.assertIsInstance(config_dict[\"y_arr\"], dict)", "def test_line_color_selection_columns(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"d\") columns =", "as np from numpy.testing import assert_array_equal BACKEND_AVAILABLE = os.environ.get(\"ETS_TOOLKIT\", \"qt4\")", "right data choices. \"\"\" config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\") view_items", "4, 1, 2, 3, 4, 1, 2, 3, 4], \"b\":", "2, 2, 2, 2, 3, 3, 3, 3, 4, 4,", "config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\") self.assertEqual(config.plot_type, self.basic_type) config_dict = config.to_dict()", "def setUp(self): self.configurator = LinePlotConfigurator self.basic_type = LINE_PLOT_TYPE self.numerical_cols_only =", "* LEN) self.assertEqual(config.y_col_name, \"value\") config_dict = config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\",", "self.assert_editor_options(x_editor) @skipIf(not BACKEND_AVAILABLE, \"No UI backend available\") class TestHeatmapPlotConfig(BasePlotConfig, TestCase):", "split the entire data into 2 \"g\": np.array([\"0\", \"1\"] *", "set(TEST_DF.columns) | {\"index\"}) class BaseXYPlotConfig(BasePlotConfig): def test_plot_basic(self): config = self.configurator(data_source=TEST_DF,", "= config._color_selection_columns() expected = [\"\"] + config._available_columns self.assertCountEqual(columns, expected) @skipIf(not", "test_plot_scatter_colored_by_float_col(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"e\") self.assertEqual(config.plot_type, CMAP_SCATTER_PLOT_TYPE) config_dict", "hue_values) assert_array_equal(config_dict[\"y_arr\"][False], TEST_DF[\"b\"][::2]) assert_array_equal(config_dict[\"y_arr\"][True], TEST_DF[\"b\"][1::2]) def test_plot_colored_by_NON_EXISTENT_col(self): config = self.configurator(data_source=TEST_DF,", "= config._numerical_columns self.assertCountEqual(columns, expected) def test_scatter_color_selection_columns(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\",", "\"\"\" The dtype of the column to colorize controls colorize_by_float.", "BAR_PLOT_TYPE self.numerical_cols_only = False def test_data_choices(self): \"\"\" Make sure different", "* (LEN // 2)), \"h\": np.array([0, 1] * (LEN //", "choices. \"\"\" config = self.configurator(data_source=TEST_DF, x_col_name=\"a\") view_items = config._data_selection_items() x_editor", "pybleau.app.plotting.plot_config import HeatmapPlotConfigurator, \\ HEATMAP_PLOT_TYPE, HistogramPlotConfigurator, HIST_PLOT_TYPE, \\ LinePlotConfigurator, BarPlotConfigurator,", "BAR_PLOT_TYPE LEN = 16 TEST_DF = DataFrame({\"a\": [1, 2, 3,", "self.assertIn(\"x_arr\", config_dict) self.assertEqual(set(config_dict[\"x_arr\"].keys()), set(hue_values)) for key in hue_values: assert_array_equal(config_dict[\"x_arr\"][key], x_values)", "np.ndarray) def test_style_colorize_by_float_changes_on_color_column_change(self): \"\"\" The dtype of the column to", "of the column to colorize controls colorize_by_float. \"\"\" # Color", "# Assertion utilities ----------------------------------------------------- def assert_editor_options(self, editor): editor_options = editor.values", "different configurators provide the right data choices. \"\"\" config =", "HIST_PLOT_TYPE, \\ LinePlotConfigurator, BarPlotConfigurator, ScatterPlotConfigurator, \\ SCATTER_PLOT_TYPE, CMAP_SCATTER_PLOT_TYPE, LINE_PLOT_TYPE, \\", "4, 4], \"c\": [1, 2, 3, 4, 2, 3, 1,", "key in hue_values: self.assertEqual(len(config_dict[\"y_arr\"][key]), LEN) def test_melt_mode_with_melted_columns_and_bool_color(self): config = self.configurator(data_source=TEST_DF,", "TestHeatmapPlotConfig(BasePlotConfig, TestCase): def setUp(self): self.configurator = HeatmapPlotConfigurator self.basic_type = HEATMAP_PLOT_TYPE", "BarPlotConfigurator, ScatterPlotConfigurator, \\ SCATTER_PLOT_TYPE, CMAP_SCATTER_PLOT_TYPE, LINE_PLOT_TYPE, \\ BAR_PLOT_TYPE LEN =", "if col != \"index\": self.assertIn(TEST_DF[col].dtype, (np.int64, np.float64)) else: self.assertEqual(set(editor_options), set(TEST_DF.columns)", "= True def test_line_data_selection_columns(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"d\")", "class TestBarPlotConfig(TestCase, BaseXYPlotConfig): def setUp(self): self.configurator = BarPlotConfigurator self.basic_type =", "def test_scatter_data_selection_columns(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"d\") columns =", "config.to_dict() self.assertIsInstance(config_dict, dict) def test_plot_colored_by_NON_EXISTENT_col(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\",", "os from pandas import DataFrame import numpy as np from", "config._numerical_columns self.assertCountEqual(columns, expected) def test_line_color_selection_columns(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\",", "columns = config._data_selection_columns() expected = config._numerical_columns self.assertCountEqual(columns, expected) def test_line_color_selection_columns(self):", "ScatterPlotConfigurator self.basic_type = SCATTER_PLOT_TYPE self.numerical_cols_only = True def test_plot_scatter_colored_by_int_col(self): config", "z_col_name=\"d\") self.assertFalse(config.plot_style.colorize_by_float) # Color by a float: config.z_col_name = \"e\"", "config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"NON-EXISTENT\") with self.assertRaises(KeyError): config.to_dict() @skipIf(not", "config = self.configurator(data_source=TEST_DF, melt_source_data=True, columns_to_melt=[\"e\", \"f\"]) self.assertIsNot(config.transformed_data, TEST_DF) self.assertIs(config.data_source, TEST_DF)", "hue_values: self.assertEqual(len(config.y_arr[key]), LEN) self.assertEqual(config.y_col_name, \"value\") self.assertIn(\"h\", config.transformed_data.columns) config_dict = config.to_dict()", "for key in hue_values: assert_array_equal(config_dict[\"x_arr\"][key], x_values) self.assertIn(\"y_arr\", config_dict) for key", "the right data choices. \"\"\" config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\")", "// 2) + [\"f\"] * (LEN // 2)) self.assertEqual(set(config.x_arr.keys()), set(hue_values))", "TEST_DF) self.assertIs(config.transformed_data, TEST_DF) def test_melt_mode_with_melted_columns(self): config = self.configurator(data_source=TEST_DF, melt_source_data=True, columns_to_melt=[\"e\",", "def setUp(self): self.configurator = ScatterPlotConfigurator self.basic_type = SCATTER_PLOT_TYPE self.numerical_cols_only =", "hue_values) assert_array_equal(config_dict[\"x_arr\"][False], TEST_DF[\"a\"][::2]) assert_array_equal(config_dict[\"x_arr\"][True], TEST_DF[\"a\"][1::2]) self.assertIn(\"y_arr\", config_dict) self.assertIsInstance(config_dict[\"y_arr\"], dict) self.assertEqual(set(config_dict[\"y_arr\"].keys()),", "test_plot_colored_by_NON_EXISTENT_col(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"NON-EXISTENT\") with self.assertRaises(KeyError): config.to_dict()", "= self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"d\") self.assertIn(config.plot_type, self.basic_type) config_dict = config.to_dict()", "view_items = config._data_selection_items() x_editor = view_items[0].content[3].content[0].content[0].editor self.assert_editor_options(x_editor) def test_melt_mode_no_effect(self): config", "3, 4, 1, 2, 3, 4, 1, 2, 3, 4],", "self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\") view_items = config._data_selection_items() x_editor = view_items[0].content[3].content[0].content[0].editor self.assert_editor_options(x_editor)", "\"\"\" # Color by a string: config = self.configurator(data_source=TEST_DF, x_col_name=\"a\",", "x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"c\") self.assertEqual(config.plot_type, CMAP_SCATTER_PLOT_TYPE) config_dict = config.to_dict() self.assertIsInstance(config_dict, dict)", "self.configurator = LinePlotConfigurator self.basic_type = LINE_PLOT_TYPE self.numerical_cols_only = True def", "config._data_selection_items() x_editor = view_items[0].content[0].editor self.assert_editor_options(x_editor) @skipIf(not BACKEND_AVAILABLE, \"No UI backend", "def test_melt_mode_no_effect(self): config = self.configurator(data_source=TEST_DF, melt_source_data=True) self.assertEqual(config.plot_type, self.basic_type) # No", "of the x_col_name x_values = np.array([\"e\"]*LEN+[\"f\"]*LEN) assert_array_equal(config.x_arr, x_values) self.assertEqual(config.x_col_name, \"variable\")", "x_arr forces a reset of the x_col_name x_values = np.array([\"e\"]", "assert_array_equal(config_dict[\"x_arr\"][False], TEST_DF[\"a\"][::2]) assert_array_equal(config_dict[\"x_arr\"][True], TEST_DF[\"a\"][1::2]) self.assertIn(\"y_arr\", config_dict) self.assertIsInstance(config_dict[\"y_arr\"], dict) self.assertEqual(set(config_dict[\"y_arr\"].keys()), hue_values)", "TEST_DF = DataFrame({\"a\": [1, 2, 3, 4, 1, 2, 3,", "def test_creation_fails_if_no_df(self): with self.assertRaises(ValueError): config = self.configurator() config.to_dict() def test_bring_up(self):", "by a float: config.z_col_name = \"e\" self.assertTrue(config.plot_style.colorize_by_float) def test_scatter_data_selection_columns(self): config", "right data choices. \"\"\" config = self.configurator(data_source=TEST_DF, x_col_name=\"a\") view_items =", "z_col_name=\"h\") self.assertIsNot(config.transformed_data, TEST_DF) self.assertIs(config.data_source, TEST_DF) hue_values = TEST_DF[\"h\"].unique() # Pulling", "def test_line_data_selection_columns(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"d\") columns =", "config_dict) assert_array_equal(config_dict[\"x_arr\"], TEST_DF[\"a\"].values) self.assertIn(\"y_arr\", config_dict) assert_array_equal(config_dict[\"y_arr\"], TEST_DF[\"b\"].values) def test_data_choices(self): \"\"\"", "\"h\": np.array([0, 1] * (LEN // 2), dtype=bool), }) class", "dict) self.assertIn(\"x_arr\", config_dict) self.assertIsInstance(config_dict[\"x_arr\"], dict) d_values = TEST_DF[\"d\"].unique() self.assertEqual(set(config_dict[\"x_arr\"].keys()), set(d_values))", "+ config._available_columns self.assertCountEqual(columns, expected) @skipIf(not BACKEND_AVAILABLE, \"No UI backend available\")", "self.assertIsInstance(config_dict[\"x_arr\"], dict) d_values = TEST_DF[\"d\"].unique() self.assertEqual(set(config_dict[\"x_arr\"].keys()), set(d_values)) for arr in", "4, 1, 2, 3, 4, 1, 2, 3, 4, 1,", "self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"NON-EXISTENT\") with self.assertRaises(KeyError): config.to_dict() @skipIf(not BACKEND_AVAILABLE, \"No", "config_dict) self.assertEqual(set(config_dict[\"x_arr\"].keys()), set(hue_values)) for key in hue_values: assert_array_equal(config_dict[\"x_arr\"][key], x_values) self.assertIn(\"y_arr\",", "HEATMAP_PLOT_TYPE, HistogramPlotConfigurator, HIST_PLOT_TYPE, \\ LinePlotConfigurator, BarPlotConfigurator, ScatterPlotConfigurator, \\ SCATTER_PLOT_TYPE, CMAP_SCATTER_PLOT_TYPE,", "in hue_values: self.assertEqual(len(config_dict[\"y_arr\"][key]), LEN) def test_melt_mode_with_melted_columns_and_bool_color(self): config = self.configurator(data_source=TEST_DF, melt_source_data=True,", "\"f\"], z_col_name=\"h\") self.assertIsNot(config.transformed_data, TEST_DF) self.assertIs(config.data_source, TEST_DF) hue_values = TEST_DF[\"h\"].unique() #", "def test_melt_mode_with_melted_columns_and_bool_color(self): config = self.configurator(data_source=TEST_DF, melt_source_data=True, columns_to_melt=[\"e\", \"f\"], z_col_name=\"h\") self.assertIsNot(config.transformed_data,", "Passing non-numerical \"\"\" config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"e\") view_items", "dtype=bool), }) class BasePlotConfig(object): def test_creation_fails_if_no_df(self): with self.assertRaises(ValueError): config =", "False def test_data_choices(self): \"\"\" Make sure different configurators provide the", "= TEST_DF[\"d\"].unique() self.assertEqual(set(config_dict[\"x_arr\"].keys()), set(d_values)) for arr in config_dict[\"x_arr\"].values(): self.assertIsInstance(arr, np.ndarray)", "SCATTER_PLOT_TYPE self.numerical_cols_only = True def test_plot_scatter_colored_by_int_col(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\",", "dict) self.assertIn(\"x_arr\", config_dict) assert_array_equal(config_dict[\"x_arr\"], TEST_DF[\"a\"].values) self.assertIn(\"y_arr\", config_dict) assert_array_equal(config_dict[\"y_arr\"], TEST_DF[\"b\"].values) def", "def test_scatter_color_selection_columns(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"d\") columns =", "\"variable\") for key in hue_values: self.assertEqual(len(config.y_arr[key]), LEN) self.assertEqual(config.y_col_name, \"value\") self.assertIn(\"h\",", "dict) def test_plot_colored_by_NON_EXISTENT_col(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"NON-EXISTENT\") with", "BaseXYPlotConfig): def setUp(self): self.configurator = ScatterPlotConfigurator self.basic_type = SCATTER_PLOT_TYPE self.numerical_cols_only", "np.array([0, 1] * (LEN // 2), dtype=bool), }) class BasePlotConfig(object):", "assert_obj_gui_works(obj) # Assertion utilities ----------------------------------------------------- def assert_editor_options(self, editor): editor_options =", "def setUp(self): self.configurator = BarPlotConfigurator self.basic_type = BAR_PLOT_TYPE self.numerical_cols_only =", "transformation: self.assertIs(config.data_source, TEST_DF) self.assertIs(config.transformed_data, TEST_DF) def test_melt_mode_with_melted_columns(self): config = self.configurator(data_source=TEST_DF,", "\\ LinePlotConfigurator, BarPlotConfigurator, ScatterPlotConfigurator, \\ SCATTER_PLOT_TYPE, CMAP_SCATTER_PLOT_TYPE, LINE_PLOT_TYPE, \\ BAR_PLOT_TYPE", "def test_plot_basic(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\") self.assertEqual(config.plot_type, self.basic_type) config_dict", "self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"e\") view_items = config._data_selection_items() x_editor = view_items[0].content[0].editor", "BACKEND_AVAILABLE: from app_common.apptools.testing_utils import assert_obj_gui_works from pybleau.app.plotting.plot_config import HeatmapPlotConfigurator, \\", "self.assertIn(\"z_arr\", config_dict) self.assertIsInstance(config_dict[\"z_arr\"], np.ndarray) def test_style_colorize_by_float_changes_on_color_column_change(self): \"\"\" The dtype of", "config_dict = config.to_dict() self.assertIsInstance(config_dict, dict) def test_plot_colored_by_NON_EXISTENT_col(self): config = self.configurator(data_source=TEST_DF,", "x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"e\") self.assertEqual(config.plot_type, CMAP_SCATTER_PLOT_TYPE) config_dict = config.to_dict() self.assertIsInstance(config_dict, dict)", "LEN = 16 TEST_DF = DataFrame({\"a\": [1, 2, 3, 4,", "1] * (LEN // 2), dtype=bool), }) class BasePlotConfig(object): def", "for key in hue_values: assert_array_equal(config.x_arr[key], x_values) self.assertEqual(config.x_col_name, \"variable\") for key", "assert_array_equal(config_dict[\"x_arr\"][True], TEST_DF[\"a\"][1::2]) self.assertIn(\"y_arr\", config_dict) self.assertIsInstance(config_dict[\"y_arr\"], dict) self.assertEqual(set(config_dict[\"y_arr\"].keys()), hue_values) assert_array_equal(config_dict[\"y_arr\"][False], TEST_DF[\"b\"][::2])", "x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"e\") view_items = config._data_selection_items() x_editor = view_items[0].content[0].editor self.assert_editor_options(x_editor)", "// 2), dtype=bool), }) class BasePlotConfig(object): def test_creation_fails_if_no_df(self): with self.assertRaises(ValueError):", "test_line_data_selection_columns(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"d\") columns = config._data_selection_columns()", "UI backend available\") class TestLinePlotConfig(TestCase, BaseXYPlotConfig): def setUp(self): self.configurator =", "config_dict) for key in hue_values: self.assertEqual(len(config_dict[\"y_arr\"][key]), LEN) @skipIf(not BACKEND_AVAILABLE, \"No", "y_col_name=\"b\") self.assertEqual(config.plot_type, self.basic_type) config_dict = config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict)", "Color by a float: config.z_col_name = \"e\" self.assertTrue(config.plot_style.colorize_by_float) def test_scatter_data_selection_columns(self):", "def test_plot_scatter_colored_by_float_col(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"e\") self.assertEqual(config.plot_type, CMAP_SCATTER_PLOT_TYPE)", "3, 4, 4, 4, 4], \"c\": [1, 2, 3, 4,", "self.assertIsInstance(config_dict[\"x_arr\"], np.ndarray) self.assertIn(\"y_arr\", config_dict) self.assertIsInstance(config_dict[\"y_arr\"], np.ndarray) self.assertIn(\"z_arr\", config_dict) self.assertIsInstance(config_dict[\"z_arr\"], np.ndarray)", "= self.configurator(data_source=TEST_DF, x_col_name=\"a\") view_items = config._data_selection_items() x_editor = view_items[0].content[0].editor self.assert_editor_options(x_editor)", "os.environ.get(\"ETS_TOOLKIT\", \"qt4\") != \"null\" if BACKEND_AVAILABLE: from app_common.apptools.testing_utils import assert_obj_gui_works", "app_common.apptools.testing_utils import assert_obj_gui_works from pybleau.app.plotting.plot_config import HeatmapPlotConfigurator, \\ HEATMAP_PLOT_TYPE, HistogramPlotConfigurator,", "self.assertRaises(KeyError): config.to_dict() def test_data_choices(self): \"\"\" Make sure different configurators provide", "from app_common.apptools.testing_utils import assert_obj_gui_works from pybleau.app.plotting.plot_config import HeatmapPlotConfigurator, \\ HEATMAP_PLOT_TYPE,", "x_editor = view_items[0].content[0].editor self.assert_editor_options(x_editor) @skipIf(not BACKEND_AVAILABLE, \"No UI backend available\")", "dict) self.assertIn(\"x_arr\", config_dict) assert_array_equal(config_dict[\"x_arr\"], TEST_DF[\"a\"].values) def test_plot_NON_EXISTENT_col(self): config = self.configurator(data_source=TEST_DF,", "self.assertCountEqual(columns, expected) def test_line_color_selection_columns(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"d\")", "test_data_choices(self): \"\"\" Make sure different configurators provide the right data", "no transformation: self.assertIs(config.data_source, TEST_DF) self.assertIs(config.transformed_data, TEST_DF) def test_melt_mode_with_melted_columns(self): config =", "config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"d\") columns = config._data_selection_columns() expected", "class TestScatterPlotConfig(TestCase, BaseXYPlotConfig): def setUp(self): self.configurator = ScatterPlotConfigurator self.basic_type =", "columns = config._data_selection_columns() expected = config._numerical_columns self.assertCountEqual(columns, expected) def test_scatter_color_selection_columns(self):", "2), dtype=bool), }) class BasePlotConfig(object): def test_creation_fails_if_no_df(self): with self.assertRaises(ValueError): config", "self.assertIs(config.data_source, TEST_DF) self.assertIs(config.transformed_data, TEST_DF) def test_melt_mode_with_melted_columns(self): config = self.configurator(data_source=TEST_DF, melt_source_data=True,", "np.ndarray) self.assertIn(\"z_arr\", config_dict) self.assertIsInstance(config_dict[\"z_arr\"], np.ndarray) def test_plot_scatter_colored_by_float_col(self): config = self.configurator(data_source=TEST_DF,", "hue_values = TEST_DF[\"g\"].unique() # Pulling the x_arr forces a reset", "config = self.configurator(data_source=TEST_DF, melt_source_data=True, columns_to_melt=[\"e\", \"f\"], z_col_name=\"g\") self.assertIsNot(config.transformed_data, TEST_DF) self.assertIs(config.data_source,", "= config._data_selection_items() x_editor = view_items[0].content[0].editor self.assert_editor_options(x_editor) @skipIf(not BACKEND_AVAILABLE, \"No UI", "for arr in config_dict[\"x_arr\"].values(): self.assertIsInstance(arr, np.ndarray) # For example: assert_array_equal(config_dict[\"x_arr\"][\"c\"],", "self.assertEqual(set(config.x_arr.keys()), set(hue_values)) for key in hue_values: assert_array_equal(config.x_arr[key], x_values) self.assertEqual(config.x_col_name, \"variable\")", "editor_options = editor.values if self.numerical_cols_only: for col in editor_options: if", "= 16 TEST_DF = DataFrame({\"a\": [1, 2, 3, 4, 1,", "np.ndarray) self.assertIn(\"y_arr\", config_dict) self.assertIsInstance(config_dict[\"y_arr\"], np.ndarray) self.assertIn(\"z_arr\", config_dict) self.assertIsInstance(config_dict[\"z_arr\"], np.ndarray) def", "Tests ------------------------------------------------------------------- def test_plot_basic(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\") self.assertEqual(config.plot_type, self.basic_type)", "x_values) self.assertEqual(config.x_col_name, \"variable\") self.assertEqual(len(config.y_arr), 2 * LEN) self.assertEqual(config.y_col_name, \"value\") config_dict", "self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"d\") self.assertFalse(config.plot_style.colorize_by_float) # Color by a float:", "= self.configurator(data_source=TEST_DF, melt_source_data=True) self.assertEqual(config.plot_type, self.basic_type) # No columns to melt,", "def setUp(self): self.configurator = HeatmapPlotConfigurator self.basic_type = HEATMAP_PLOT_TYPE self.numerical_cols_only =", "np.random.randn(LEN), \"f\": range(LEN), # Highly repetitive column to split the", "BACKEND_AVAILABLE, \"No UI backend available\") class TestHeatmapPlotConfig(BasePlotConfig, TestCase): def setUp(self):", "HistogramPlotConfigurator self.basic_type = HIST_PLOT_TYPE self.numerical_cols_only = True # Tests -------------------------------------------------------------------", "(LEN // 2), dtype=bool), }) class BasePlotConfig(object): def test_creation_fails_if_no_df(self): with", "self.basic_type) # No columns to melt, so no transformation: self.assertIs(config.data_source,", "= TEST_DF[\"h\"].unique() # Pulling the x_arr forces a reset of", "TEST_DF[\"a\"].values) def test_plot_NON_EXISTENT_col(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"NON-EXISTENT\") with self.assertRaises(KeyError): config.to_dict()", "import DataFrame import numpy as np from numpy.testing import assert_array_equal", "z_col_name=\"g\") self.assertIsNot(config.transformed_data, TEST_DF) self.assertIs(config.data_source, TEST_DF) hue_values = TEST_DF[\"g\"].unique() # Pulling", "self.configurator = HeatmapPlotConfigurator self.basic_type = HEATMAP_PLOT_TYPE self.numerical_cols_only = True #", "hue_values: assert_array_equal(config.x_arr[key], x_values) self.assertEqual(config.x_col_name, \"variable\") for key in hue_values: self.assertEqual(len(config.y_arr[key]),", "in config_dict[\"y_arr\"].values(): self.assertIsInstance(arr, np.ndarray) # For example: assert_array_equal(config_dict[\"y_arr\"][\"c\"], np.array([2, 2,", "\"f\"]) self.assertIsNot(config.transformed_data, TEST_DF) self.assertIs(config.data_source, TEST_DF) # Pulling the x_arr forces", "BaseXYPlotConfig): def setUp(self): self.configurator = BarPlotConfigurator self.basic_type = BAR_PLOT_TYPE self.numerical_cols_only", "melt_source_data=True, columns_to_melt=[\"e\", \"f\"], z_col_name=\"h\") self.assertIsNot(config.transformed_data, TEST_DF) self.assertIs(config.data_source, TEST_DF) hue_values =", "example: assert_array_equal(config_dict[\"y_arr\"][\"c\"], np.array([2, 2, 3])) def test_plot_colored_by_bool_col(self): # Color by", "for key in hue_values: self.assertEqual(len(config_dict[\"y_arr\"][key]), LEN) def test_melt_mode_with_melted_columns_and_bool_color(self): config =", "= editor.values if self.numerical_cols_only: for col in editor_options: if col", "= self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"c\") self.assertEqual(config.plot_type, CMAP_SCATTER_PLOT_TYPE) config_dict = config.to_dict()", "TEST_DF) # Pulling the x_arr forces a reset of the", "self.assertEqual(len(config.y_arr[key]), LEN) self.assertEqual(config.y_col_name, \"value\") self.assertIn(\"h\", config.transformed_data.columns) config_dict = config.to_dict() self.assertIsInstance(config_dict,", "config = self.configurator(data_source=TEST_DF, x_col_name=\"a\") view_items = config._data_selection_items() x_editor = view_items[0].content[0].editor", "self.assert_editor_options(y_editor) def test_plot_colored_by_str_col(self): # Color by a column filled with", "by a column filled with boolean values config = self.configurator(data_source=TEST_DF,", "backend available\") class TestBarPlotConfig(TestCase, BaseXYPlotConfig): def setUp(self): self.configurator = BarPlotConfigurator", "self.configurator(data_source=TEST_DF) assert_obj_gui_works(obj) # Assertion utilities ----------------------------------------------------- def assert_editor_options(self, editor): editor_options", "DataFrame import numpy as np from numpy.testing import assert_array_equal BACKEND_AVAILABLE", "self.assertEqual(len(config_dict[\"y_arr\"][key]), LEN) @skipIf(not BACKEND_AVAILABLE, \"No UI backend available\") class TestHistogramPlotConfig(BasePlotConfig,", "= config._data_selection_columns() expected = config._numerical_columns self.assertCountEqual(columns, expected) def test_line_color_selection_columns(self): config", "self.assertIn(\"x_arr\", config_dict) assert_array_equal(config_dict[\"x_arr\"], TEST_DF[\"a\"].values) self.assertIn(\"y_arr\", config_dict) assert_array_equal(config_dict[\"y_arr\"], TEST_DF[\"b\"].values) def test_data_choices(self):", "= config.to_dict() self.assertIsInstance(config_dict, dict) def test_plot_colored_by_NON_EXISTENT_col(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\",", "3, 4, 1, 2, 3, 4, 1, 2, 3, 4,", "x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"h\") self.assertIn(config.plot_type, self.basic_type) config_dict = config.to_dict() self.assertIsInstance(config_dict, dict)", "1, 1, 4, 4, 5, 6, 4, 4, 5, 6],", "Pulling the x_arr forces a reset of the x_col_name x_values", "d_values = TEST_DF[\"d\"].unique() self.assertEqual(set(config_dict[\"x_arr\"].keys()), set(d_values)) for arr in config_dict[\"x_arr\"].values(): self.assertIsInstance(arr,", "data choices. \"\"\" config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\") view_items =", "self.assert_editor_options(x_editor) y_editor = view_items[1].content[0].editor self.assert_editor_options(y_editor) def test_plot_colored_by_str_col(self): # Color by", "TEST_DF[\"g\"].unique() # Pulling the x_arr forces a reset of the", "hue_values: self.assertEqual(len(config.y_arr[key]), LEN) self.assertEqual(config.y_col_name, \"value\") self.assertIn(\"g\", config.transformed_data.columns) config_dict = config.to_dict()", "backend available\") class TestHistogramPlotConfig(BasePlotConfig, TestCase): def setUp(self): self.configurator = HistogramPlotConfigurator", "z_col_name=\"e\") self.assertEqual(config.plot_type, self.basic_type) config_dict = config.to_dict() self.assertIsInstance(config_dict, dict) def test_plot_colored_by_NON_EXISTENT_col(self):", "available\") class TestScatterPlotConfig(TestCase, BaseXYPlotConfig): def setUp(self): self.configurator = ScatterPlotConfigurator self.basic_type", "x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"d\") columns = config._data_selection_columns() expected = config._numerical_columns self.assertCountEqual(columns,", "assert_obj_gui_works from pybleau.app.plotting.plot_config import HeatmapPlotConfigurator, \\ HEATMAP_PLOT_TYPE, HistogramPlotConfigurator, HIST_PLOT_TYPE, \\", "col in editor_options: if col != \"index\": self.assertIn(TEST_DF[col].dtype, (np.int64, np.float64))", "self.assertEqual(set(config_dict[\"x_arr\"].keys()), set(d_values)) for arr in config_dict[\"x_arr\"].values(): self.assertIsInstance(arr, np.ndarray) # For", "1, 2, 3, 4, 1, 2, 3, 4], \"b\": [1,", "self.configurator() config.to_dict() def test_bring_up(self): obj = self.configurator(data_source=TEST_DF) assert_obj_gui_works(obj) # Assertion", "assert_array_equal BACKEND_AVAILABLE = os.environ.get(\"ETS_TOOLKIT\", \"qt4\") != \"null\" if BACKEND_AVAILABLE: from", "config_dict) self.assertIsInstance(config_dict[\"y_arr\"], np.ndarray) self.assertIn(\"z_arr\", config_dict) self.assertIsInstance(config_dict[\"z_arr\"], np.ndarray) def test_style_colorize_by_float_changes_on_color_column_change(self): \"\"\"", "= config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict) assert_array_equal(config_dict[\"x_arr\"], x_values) self.assertIn(\"y_arr\", config_dict)", "filled with boolean values config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"h\")", "x_editor = view_items[0].content[0].editor self.assert_editor_options(x_editor) y_editor = view_items[1].content[0].editor self.assert_editor_options(y_editor) def test_plot_colored_by_str_col(self):", "self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"d\") columns = config._color_selection_columns() expected = [\"\"]", "4, 5, 6, 4, 4, 5, 6], \"d\": list(\"ababcabcdabcdeab\"), \"e\":", "z_col_name=\"d\") self.assertIn(config.plot_type, self.basic_type) config_dict = config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict)", "test_plot_colored_by_str_col(self): # Color by a column filled with boolean values", "self.assertIn(\"x_arr\", config_dict) self.assertIsInstance(config_dict[\"x_arr\"], np.ndarray) self.assertIn(\"y_arr\", config_dict) self.assertIsInstance(config_dict[\"y_arr\"], np.ndarray) self.assertIn(\"z_arr\", config_dict)", "self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict) assert_array_equal(config_dict[\"x_arr\"], TEST_DF[\"a\"].values) self.assertIn(\"y_arr\", config_dict) assert_array_equal(config_dict[\"y_arr\"], TEST_DF[\"b\"].values)", "BACKEND_AVAILABLE, \"No UI backend available\") class TestHistogramPlotConfig(BasePlotConfig, TestCase): def setUp(self):", "self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict) assert_array_equal(config_dict[\"x_arr\"], TEST_DF[\"a\"].values) def test_plot_NON_EXISTENT_col(self): config =", "= config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict) self.assertIsInstance(config_dict[\"x_arr\"], dict) d_values =", "TestHistogramPlotConfig(BasePlotConfig, TestCase): def setUp(self): self.configurator = HistogramPlotConfigurator self.basic_type = HIST_PLOT_TYPE", "x_col_name=\"NON-EXISTENT\") with self.assertRaises(KeyError): config.to_dict() def test_data_choices(self): \"\"\" Make sure different", "backend available\") class TestScatterPlotConfig(TestCase, BaseXYPlotConfig): def setUp(self): self.configurator = ScatterPlotConfigurator", "col != \"index\": self.assertIn(TEST_DF[col].dtype, (np.int64, np.float64)) else: self.assertEqual(set(editor_options), set(TEST_DF.columns) |", "self.assertEqual(len(config_dict[\"y_arr\"][key]), LEN) def test_melt_mode_with_melted_columns_and_bool_color(self): config = self.configurator(data_source=TEST_DF, melt_source_data=True, columns_to_melt=[\"e\", \"f\"],", "column to split the entire data into 2 \"g\": np.array([\"0\",", "4, 4, 4], \"c\": [1, 2, 3, 4, 2, 3,", "= self.configurator(data_source=TEST_DF) assert_obj_gui_works(obj) # Assertion utilities ----------------------------------------------------- def assert_editor_options(self, editor):", "x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"NON-EXISTENT\") with self.assertRaises(KeyError): config.to_dict() def test_data_choices(self): \"\"\" Make", "column filled with boolean values config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\",", "import assert_obj_gui_works from pybleau.app.plotting.plot_config import HeatmapPlotConfigurator, \\ HEATMAP_PLOT_TYPE, HistogramPlotConfigurator, HIST_PLOT_TYPE,", "sure different configurators provide the right data choices. \"\"\" config", "CMAP_SCATTER_PLOT_TYPE) config_dict = config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict) self.assertIsInstance(config_dict[\"x_arr\"], np.ndarray)", "config_dict) self.assertIsInstance(config_dict[\"x_arr\"], dict) d_values = TEST_DF[\"d\"].unique() self.assertEqual(set(config_dict[\"x_arr\"].keys()), set(d_values)) for arr", "LEN) self.assertEqual(config.y_col_name, \"value\") config_dict = config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict)", "LEN) def test_melt_mode_with_melted_columns_and_bool_color(self): config = self.configurator(data_source=TEST_DF, melt_source_data=True, columns_to_melt=[\"e\", \"f\"], z_col_name=\"h\")", "def test_plot_basic(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\") self.assertEqual(config.plot_type, self.basic_type) config_dict =", "@skipIf(not BACKEND_AVAILABLE, \"No UI backend available\") class TestBarPlotConfig(TestCase, BaseXYPlotConfig): def", "test_creation_fails_if_no_df(self): with self.assertRaises(ValueError): config = self.configurator() config.to_dict() def test_bring_up(self): obj", "expected = config._numerical_columns self.assertCountEqual(columns, expected) def test_line_color_selection_columns(self): config = self.configurator(data_source=TEST_DF,", "self.configurator(data_source=TEST_DF, x_col_name=\"a\") self.assertEqual(config.plot_type, self.basic_type) config_dict = config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\",", "set(d_values)) for arr in config_dict[\"y_arr\"].values(): self.assertIsInstance(arr, np.ndarray) # For example:", "def test_melt_mode_with_melted_columns(self): config = self.configurator(data_source=TEST_DF, melt_source_data=True, columns_to_melt=[\"e\", \"f\"]) self.assertIsNot(config.transformed_data, TEST_DF)", "2, 3, 1, 1, 4, 4, 5, 6, 4, 4,", "setUp(self): self.configurator = ScatterPlotConfigurator self.basic_type = SCATTER_PLOT_TYPE self.numerical_cols_only = True", "self.assertEqual(config.x_col_name, \"variable\") for key in hue_values: self.assertEqual(len(config.y_arr[key]), LEN) self.assertEqual(config.y_col_name, \"value\")", "= config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict) assert_array_equal(config_dict[\"x_arr\"], TEST_DF[\"a\"].values) def test_plot_NON_EXISTENT_col(self):", "dict) self.assertEqual(set(config_dict[\"y_arr\"].keys()), set(d_values)) for arr in config_dict[\"y_arr\"].values(): self.assertIsInstance(arr, np.ndarray) #", "self.assertIn(\"y_arr\", config_dict) self.assertEqual(len(config_dict[\"y_arr\"]), 2 * LEN) def test_melt_mode_with_melted_columns_and_str_color(self): config =", "def test_data_choices(self): \"\"\" Make sure different configurators provide the right", "self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\") view_items = config._data_selection_items() x_editor = view_items[0].content[0].editor self.assert_editor_options(x_editor)", "expected) def test_line_color_selection_columns(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"d\") columns", "self.assertIsInstance(arr, np.ndarray) # For example: assert_array_equal(config_dict[\"y_arr\"][\"c\"], np.array([2, 2, 3])) def", "= HEATMAP_PLOT_TYPE self.numerical_cols_only = True # Tests ------------------------------------------------------------------- def test_plot_basic(self):", "y_col_name=\"b\", z_col_name=\"e\") self.assertEqual(config.plot_type, self.basic_type) config_dict = config.to_dict() self.assertIsInstance(config_dict, dict) def", "(np.int64, np.float64)) else: self.assertEqual(set(editor_options), set(TEST_DF.columns) | {\"index\"}) class BaseXYPlotConfig(BasePlotConfig): def", "\"\"\" Make sure different configurators provide the right data choices.", "def test_plot_colored_by_str_col(self): # Color by a column filled with boolean", "assert_array_equal(config_dict[\"y_arr\"][\"c\"], np.array([2, 2, 3])) def test_plot_colored_by_bool_col(self): # Color by a", "values config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"h\") self.assertIn(config.plot_type, self.basic_type) config_dict", "test_bring_up(self): obj = self.configurator(data_source=TEST_DF) assert_obj_gui_works(obj) # Assertion utilities ----------------------------------------------------- def", "config_dict) self.assertIsInstance(config_dict[\"x_arr\"], dict) hue_values = set(TEST_DF[\"h\"]) self.assertEqual(set(config_dict[\"x_arr\"].keys()), hue_values) assert_array_equal(config_dict[\"x_arr\"][False], TEST_DF[\"a\"][::2])", "= ScatterPlotConfigurator self.basic_type = SCATTER_PLOT_TYPE self.numerical_cols_only = True def test_plot_scatter_colored_by_int_col(self):", "dict) self.assertIn(\"x_arr\", config_dict) assert_array_equal(config_dict[\"x_arr\"], x_values) self.assertIn(\"y_arr\", config_dict) self.assertEqual(len(config_dict[\"y_arr\"]), 2 *", "the right data choices. Passing non-numerical \"\"\" config = self.configurator(data_source=TEST_DF,", "in hue_values: self.assertEqual(len(config.y_arr[key]), LEN) self.assertEqual(config.y_col_name, \"value\") self.assertIn(\"g\", config.transformed_data.columns) config_dict =", "self.assertEqual(config.x_col_name, \"variable\") self.assertEqual(len(config.y_arr), 2 * LEN) self.assertEqual(config.y_col_name, \"value\") config_dict =", "def test_plot_NON_EXISTENT_col(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"NON-EXISTENT\") with self.assertRaises(KeyError): config.to_dict() def", "// 2)), \"h\": np.array([0, 1] * (LEN // 2), dtype=bool),", "self.configurator(data_source=TEST_DF, x_col_name=\"a\") view_items = config._data_selection_items() x_editor = view_items[0].content[0].editor self.assert_editor_options(x_editor) @skipIf(not", "test_plot_basic(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\") self.assertEqual(config.plot_type, self.basic_type) config_dict =", "self.assertIn(\"y_arr\", config_dict) self.assertIsInstance(config_dict[\"y_arr\"], dict) self.assertEqual(set(config_dict[\"y_arr\"].keys()), hue_values) assert_array_equal(config_dict[\"y_arr\"][False], TEST_DF[\"b\"][::2]) assert_array_equal(config_dict[\"y_arr\"][True], TEST_DF[\"b\"][1::2])", "forces a reset of the x_col_name x_values = np.array([\"e\"]*LEN+[\"f\"]*LEN) assert_array_equal(config.x_arr,", "4, 5, 6], \"d\": list(\"ababcabcdabcdeab\"), \"e\": np.random.randn(LEN), \"f\": range(LEN), #", "self.assertIn(\"y_arr\", config_dict) assert_array_equal(config_dict[\"y_arr\"], TEST_DF[\"b\"].values) def test_data_choices(self): \"\"\" Make sure different", "values config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"d\") self.assertIn(config.plot_type, self.basic_type) config_dict", "y_col_name=\"b\", z_col_name=\"NON-EXISTENT\") with self.assertRaises(KeyError): config.to_dict() def test_data_choices(self): \"\"\" Make sure", "\\ BAR_PLOT_TYPE LEN = 16 TEST_DF = DataFrame({\"a\": [1, 2,", "6, 4, 4, 5, 6], \"d\": list(\"ababcabcdabcdeab\"), \"e\": np.random.randn(LEN), \"f\":", "= self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"h\") self.assertIn(config.plot_type, self.basic_type) config_dict = config.to_dict()", "self.assertIn(\"x_arr\", config_dict) self.assertIsInstance(config_dict[\"x_arr\"], dict) hue_values = set(TEST_DF[\"h\"]) self.assertEqual(set(config_dict[\"x_arr\"].keys()), hue_values) assert_array_equal(config_dict[\"x_arr\"][False],", "1, 1, 2, 2, 2, 2, 3, 3, 3, 3,", "self.assertIn(\"g\", config.transformed_data.columns) config_dict = config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict) self.assertEqual(set(config_dict[\"x_arr\"].keys()),", "columns to melt, so no transformation: self.assertIs(config.data_source, TEST_DF) self.assertIs(config.transformed_data, TEST_DF)", "self.numerical_cols_only = True # Tests ------------------------------------------------------------------- def test_plot_basic(self): config =", "HeatmapPlotConfigurator, \\ HEATMAP_PLOT_TYPE, HistogramPlotConfigurator, HIST_PLOT_TYPE, \\ LinePlotConfigurator, BarPlotConfigurator, ScatterPlotConfigurator, \\", "self.basic_type) config_dict = config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict) assert_array_equal(config_dict[\"x_arr\"], TEST_DF[\"a\"].values)", "config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict) self.assertIsInstance(config_dict[\"x_arr\"], dict) d_values = TEST_DF[\"d\"].unique()", "* LEN) def test_melt_mode_with_melted_columns_and_str_color(self): config = self.configurator(data_source=TEST_DF, melt_source_data=True, columns_to_melt=[\"e\", \"f\"],", "2, 2, 2, 3, 3, 3, 3, 4, 4, 4,", "forces a reset of the x_col_name x_values = np.array([\"e\"] *", "= view_items[0].content[0].editor self.assert_editor_options(x_editor) @skipIf(not BACKEND_AVAILABLE, \"No UI backend available\") class", "y_col_name=\"b\", z_col_name=\"h\") self.assertIn(config.plot_type, self.basic_type) config_dict = config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\",", "TEST_DF) self.assertIs(config.data_source, TEST_DF) hue_values = TEST_DF[\"g\"].unique() # Pulling the x_arr", "example: assert_array_equal(config_dict[\"x_arr\"][\"c\"], np.array([1, 4, 4])) self.assertIn(\"y_arr\", config_dict) self.assertIsInstance(config_dict[\"y_arr\"], dict) self.assertEqual(set(config_dict[\"y_arr\"].keys()),", "SCATTER_PLOT_TYPE, CMAP_SCATTER_PLOT_TYPE, LINE_PLOT_TYPE, \\ BAR_PLOT_TYPE LEN = 16 TEST_DF =", "config.to_dict() @skipIf(not BACKEND_AVAILABLE, \"No UI backend available\") class TestScatterPlotConfig(TestCase, BaseXYPlotConfig):", "TestCase): def setUp(self): self.configurator = HeatmapPlotConfigurator self.basic_type = HEATMAP_PLOT_TYPE self.numerical_cols_only", "= view_items[1].content[0].editor self.assert_editor_options(y_editor) def test_plot_colored_by_str_col(self): # Color by a column", "hue_values: assert_array_equal(config_dict[\"x_arr\"][key], x_values) self.assertIn(\"y_arr\", config_dict) for key in hue_values: self.assertEqual(len(config_dict[\"y_arr\"][key]),", "\"\"\" config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\") view_items = config._data_selection_items() x_editor", "def test_plot_colored_by_NON_EXISTENT_col(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"NON-EXISTENT\") with self.assertRaises(KeyError):", "self.assertIn(\"y_arr\", config_dict) for key in hue_values: self.assertEqual(len(config_dict[\"y_arr\"][key]), LEN) def test_melt_mode_with_melted_columns_and_bool_color(self):", "z_col_name=\"d\") columns = config._data_selection_columns() expected = config._numerical_columns self.assertCountEqual(columns, expected) def", "Highly repetitive column to split the entire data into 2", "config_dict) self.assertIsInstance(config_dict[\"y_arr\"], np.ndarray) self.assertIn(\"z_arr\", config_dict) self.assertIsInstance(config_dict[\"z_arr\"], np.ndarray) def test_plot_scatter_colored_by_float_col(self): config", "\"e\" self.assertTrue(config.plot_style.colorize_by_float) def test_scatter_data_selection_columns(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"d\")", "config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict) assert_array_equal(config_dict[\"x_arr\"], x_values) self.assertIn(\"y_arr\", config_dict) self.assertEqual(len(config_dict[\"y_arr\"]),", "TestScatterPlotConfig(TestCase, BaseXYPlotConfig): def setUp(self): self.configurator = ScatterPlotConfigurator self.basic_type = SCATTER_PLOT_TYPE", "= config._data_selection_items() x_editor = view_items[0].content[0].editor self.assert_editor_options(x_editor) y_editor = view_items[1].content[0].editor self.assert_editor_options(y_editor)", "TestLinePlotConfig(TestCase, BaseXYPlotConfig): def setUp(self): self.configurator = LinePlotConfigurator self.basic_type = LINE_PLOT_TYPE", "TEST_DF[\"h\"].unique() # Pulling the x_arr forces a reset of the", "if BACKEND_AVAILABLE: from app_common.apptools.testing_utils import assert_obj_gui_works from pybleau.app.plotting.plot_config import HeatmapPlotConfigurator,", "from __future__ import division from unittest import skipIf, TestCase import", "self.basic_type = SCATTER_PLOT_TYPE self.numerical_cols_only = True def test_plot_scatter_colored_by_int_col(self): config =", "available\") class TestLinePlotConfig(TestCase, BaseXYPlotConfig): def setUp(self): self.configurator = LinePlotConfigurator self.basic_type", "configurators provide the right data choices. \"\"\" config = self.configurator(data_source=TEST_DF,", "self.assertIsInstance(config_dict, dict) def test_plot_colored_by_NON_EXISTENT_col(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"NON-EXISTENT\")", "(LEN // 2)) self.assertEqual(set(config.x_arr.keys()), set(hue_values)) for key in hue_values: assert_array_equal(config.x_arr[key],", "self.basic_type) config_dict = config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict) self.assertIsInstance(config_dict[\"x_arr\"], dict)", "self.assert_editor_options(x_editor) def test_melt_mode_no_effect(self): config = self.configurator(data_source=TEST_DF, melt_source_data=True) self.assertEqual(config.plot_type, self.basic_type) #", "= self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"e\") self.assertEqual(config.plot_type, CMAP_SCATTER_PLOT_TYPE) config_dict = config.to_dict()", "y_col_name=\"b\", z_col_name=\"d\") columns = config._data_selection_columns() expected = config._numerical_columns self.assertCountEqual(columns, expected)", "expected) def test_scatter_color_selection_columns(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"d\") columns", "x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"d\") self.assertIn(config.plot_type, self.basic_type) config_dict = config.to_dict() self.assertIsInstance(config_dict, dict)", "TEST_DF[\"d\"].unique() self.assertEqual(set(config_dict[\"x_arr\"].keys()), set(d_values)) for arr in config_dict[\"x_arr\"].values(): self.assertIsInstance(arr, np.ndarray) #", "# For example: assert_array_equal(config_dict[\"y_arr\"][\"c\"], np.array([2, 2, 3])) def test_plot_colored_by_bool_col(self): #", "2, 3, 4, 1, 2, 3, 4, 1, 2, 3,", "np.array([2, 2, 3])) def test_plot_colored_by_bool_col(self): # Color by a column", "1, 2, 2, 2, 2, 3, 3, 3, 3, 4,", "self.assertFalse(config.plot_style.colorize_by_float) # Color by a float: config.z_col_name = \"e\" self.assertTrue(config.plot_style.colorize_by_float)", "columns = config._color_selection_columns() expected = [\"\"] + config._available_columns self.assertCountEqual(columns, expected)", "Color by a column filled with boolean values config =", "config_dict) self.assertIsInstance(config_dict[\"z_arr\"], np.ndarray) def test_plot_scatter_colored_by_float_col(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\",", "self.assertEqual(config.plot_type, CMAP_SCATTER_PLOT_TYPE) config_dict = config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict) self.assertIsInstance(config_dict[\"x_arr\"],", "x_values = np.array([\"e\"]*LEN+[\"f\"]*LEN) assert_array_equal(config.x_arr, x_values) self.assertEqual(config.x_col_name, \"variable\") self.assertEqual(len(config.y_arr), 2 *", "TEST_DF[\"b\"][1::2]) def test_plot_colored_by_NON_EXISTENT_col(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"NON-EXISTENT\") with", "self.assertIn(TEST_DF[col].dtype, (np.int64, np.float64)) else: self.assertEqual(set(editor_options), set(TEST_DF.columns) | {\"index\"}) class BaseXYPlotConfig(BasePlotConfig):", "melt_source_data=True, columns_to_melt=[\"e\", \"f\"], z_col_name=\"g\") self.assertIsNot(config.transformed_data, TEST_DF) self.assertIs(config.data_source, TEST_DF) hue_values =", "the x_col_name x_values = np.array([\"e\"] * (LEN // 2) +", "set(d_values)) for arr in config_dict[\"x_arr\"].values(): self.assertIsInstance(arr, np.ndarray) # For example:", "config = self.configurator() config.to_dict() def test_bring_up(self): obj = self.configurator(data_source=TEST_DF) assert_obj_gui_works(obj)", "2 * LEN) def test_melt_mode_with_melted_columns_and_str_color(self): config = self.configurator(data_source=TEST_DF, melt_source_data=True, columns_to_melt=[\"e\",", "z_col_name=\"c\") self.assertEqual(config.plot_type, CMAP_SCATTER_PLOT_TYPE) config_dict = config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict)", "numpy as np from numpy.testing import assert_array_equal BACKEND_AVAILABLE = os.environ.get(\"ETS_TOOLKIT\",", "4, 4, 5, 6], \"d\": list(\"ababcabcdabcdeab\"), \"e\": np.random.randn(LEN), \"f\": range(LEN),", "self.assertEqual(set(config_dict[\"x_arr\"].keys()), hue_values) assert_array_equal(config_dict[\"x_arr\"][False], TEST_DF[\"a\"][::2]) assert_array_equal(config_dict[\"x_arr\"][True], TEST_DF[\"a\"][1::2]) self.assertIn(\"y_arr\", config_dict) self.assertIsInstance(config_dict[\"y_arr\"], dict)", "config._available_columns self.assertCountEqual(columns, expected) @skipIf(not BACKEND_AVAILABLE, \"No UI backend available\") class", "for key in hue_values: self.assertEqual(len(config_dict[\"y_arr\"][key]), LEN) @skipIf(not BACKEND_AVAILABLE, \"No UI", "UI backend available\") class TestHistogramPlotConfig(BasePlotConfig, TestCase): def setUp(self): self.configurator =", "x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"NON-EXISTENT\") with self.assertRaises(KeyError): config.to_dict() @skipIf(not BACKEND_AVAILABLE, \"No UI", "self.assertEqual(set(config_dict[\"y_arr\"].keys()), set(d_values)) for arr in config_dict[\"y_arr\"].values(): self.assertIsInstance(arr, np.ndarray) # For", "dict) self.assertIn(\"x_arr\", config_dict) self.assertIsInstance(config_dict[\"x_arr\"], np.ndarray) self.assertIn(\"y_arr\", config_dict) self.assertIsInstance(config_dict[\"y_arr\"], np.ndarray) self.assertIn(\"z_arr\",", "4, 4, 4, 4], \"c\": [1, 2, 3, 4, 2,", "config.z_col_name = \"e\" self.assertTrue(config.plot_style.colorize_by_float) def test_scatter_data_selection_columns(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\",", "def test_melt_mode_with_melted_columns_and_str_color(self): config = self.configurator(data_source=TEST_DF, melt_source_data=True, columns_to_melt=[\"e\", \"f\"], z_col_name=\"g\") self.assertIsNot(config.transformed_data,", "assert_array_equal(config_dict[\"x_arr\"][key], x_values) self.assertIn(\"y_arr\", config_dict) for key in hue_values: self.assertEqual(len(config_dict[\"y_arr\"][key]), LEN)", "arr in config_dict[\"y_arr\"].values(): self.assertIsInstance(arr, np.ndarray) # For example: assert_array_equal(config_dict[\"y_arr\"][\"c\"], np.array([2,", "np.ndarray) def test_plot_scatter_colored_by_float_col(self): config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"e\") self.assertEqual(config.plot_type,", "!= \"index\": self.assertIn(TEST_DF[col].dtype, (np.int64, np.float64)) else: self.assertEqual(set(editor_options), set(TEST_DF.columns) | {\"index\"})", "HistogramPlotConfigurator, HIST_PLOT_TYPE, \\ LinePlotConfigurator, BarPlotConfigurator, ScatterPlotConfigurator, \\ SCATTER_PLOT_TYPE, CMAP_SCATTER_PLOT_TYPE, LINE_PLOT_TYPE,", "x_values = np.array([\"e\"] * (LEN // 2) + [\"f\"] *", "provide the right data choices. \"\"\" config = self.configurator(data_source=TEST_DF, x_col_name=\"a\")", "self.configurator = HistogramPlotConfigurator self.basic_type = HIST_PLOT_TYPE self.numerical_cols_only = True #", "config.to_dict() def test_data_choices(self): \"\"\" Make sure different configurators provide the", "= self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"NON-EXISTENT\") with self.assertRaises(KeyError): config.to_dict() def test_data_choices(self):", "hue_values = TEST_DF[\"h\"].unique() # Pulling the x_arr forces a reset", "TEST_DF[\"a\"].values) self.assertIn(\"y_arr\", config_dict) assert_array_equal(config_dict[\"y_arr\"], TEST_DF[\"b\"].values) def test_data_choices(self): \"\"\" Make sure", "filled with boolean values config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"d\")", "config_dict) assert_array_equal(config_dict[\"x_arr\"], x_values) self.assertIn(\"y_arr\", config_dict) self.assertEqual(len(config_dict[\"y_arr\"]), 2 * LEN) def", "LEN) def test_melt_mode_with_melted_columns_and_str_color(self): config = self.configurator(data_source=TEST_DF, melt_source_data=True, columns_to_melt=[\"e\", \"f\"], z_col_name=\"g\")", "self.assertEqual(config.y_col_name, \"value\") self.assertIn(\"g\", config.transformed_data.columns) config_dict = config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\",", "= self.configurator(data_source=TEST_DF, melt_source_data=True, columns_to_melt=[\"e\", \"f\"]) self.assertIsNot(config.transformed_data, TEST_DF) self.assertIs(config.data_source, TEST_DF) #", "the x_col_name x_values = np.array([\"e\"]*LEN+[\"f\"]*LEN) assert_array_equal(config.x_arr, x_values) self.assertEqual(config.x_col_name, \"variable\") self.assertEqual(len(config.y_arr),", "3, 1, 1, 4, 4, 5, 6, 4, 4, 5,", "z_col_name=\"e\") view_items = config._data_selection_items() x_editor = view_items[0].content[0].editor self.assert_editor_options(x_editor) y_editor =", "4, 2, 3, 1, 1, 4, 4, 5, 6, 4,", "self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict) self.assertIsInstance(config_dict[\"x_arr\"], np.ndarray) self.assertIn(\"y_arr\", config_dict) self.assertIsInstance(config_dict[\"y_arr\"], np.ndarray)", "config._data_selection_columns() expected = config._numerical_columns self.assertCountEqual(columns, expected) def test_scatter_color_selection_columns(self): config =", "self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"d\") columns = config._data_selection_columns() expected = config._numerical_columns", "melt_source_data=True) self.assertEqual(config.plot_type, self.basic_type) # No columns to melt, so no", "config_dict) assert_array_equal(config_dict[\"y_arr\"], TEST_DF[\"b\"].values) def test_data_choices(self): \"\"\" Make sure different configurators", "setUp(self): self.configurator = LinePlotConfigurator self.basic_type = LINE_PLOT_TYPE self.numerical_cols_only = True", "y_col_name=\"b\") view_items = config._data_selection_items() x_editor = view_items[0].content[3].content[0].content[0].editor self.assert_editor_options(x_editor) def test_melt_mode_no_effect(self):", "= HIST_PLOT_TYPE self.numerical_cols_only = True # Tests ------------------------------------------------------------------- def test_plot_basic(self):", "key in hue_values: self.assertEqual(len(config.y_arr[key]), LEN) self.assertEqual(config.y_col_name, \"value\") self.assertIn(\"h\", config.transformed_data.columns) config_dict", "expected) @skipIf(not BACKEND_AVAILABLE, \"No UI backend available\") class TestBarPlotConfig(TestCase, BaseXYPlotConfig):", "expected) @skipIf(not BACKEND_AVAILABLE, \"No UI backend available\") class TestLinePlotConfig(TestCase, BaseXYPlotConfig):", "for key in hue_values: self.assertEqual(len(config.y_arr[key]), LEN) self.assertEqual(config.y_col_name, \"value\") self.assertIn(\"h\", config.transformed_data.columns)", "self.assertIsInstance(config_dict[\"y_arr\"], np.ndarray) self.assertIn(\"z_arr\", config_dict) self.assertIsInstance(config_dict[\"z_arr\"], np.ndarray) def test_plot_scatter_colored_by_float_col(self): config =", "in hue_values: self.assertEqual(len(config.y_arr[key]), LEN) self.assertEqual(config.y_col_name, \"value\") self.assertIn(\"h\", config.transformed_data.columns) config_dict =", "x_col_name=\"a\", y_col_name=\"b\") self.assertEqual(config.plot_type, self.basic_type) config_dict = config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\",", "config_dict = config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict) self.assertEqual(set(config_dict[\"x_arr\"].keys()), set(hue_values)) for", "backend available\") class TestHeatmapPlotConfig(BasePlotConfig, TestCase): def setUp(self): self.configurator = HeatmapPlotConfigurator", "\"1\"] * (LEN // 2)), \"h\": np.array([0, 1] * (LEN", "set(TEST_DF[\"h\"]) self.assertEqual(set(config_dict[\"x_arr\"].keys()), hue_values) assert_array_equal(config_dict[\"x_arr\"][False], TEST_DF[\"a\"][::2]) assert_array_equal(config_dict[\"x_arr\"][True], TEST_DF[\"a\"][1::2]) self.assertIn(\"y_arr\", config_dict) self.assertIsInstance(config_dict[\"y_arr\"],", "columns_to_melt=[\"e\", \"f\"]) self.assertIsNot(config.transformed_data, TEST_DF) self.assertIs(config.data_source, TEST_DF) # Pulling the x_arr", "dict) self.assertEqual(set(config_dict[\"y_arr\"].keys()), hue_values) assert_array_equal(config_dict[\"y_arr\"][False], TEST_DF[\"b\"][::2]) assert_array_equal(config_dict[\"y_arr\"][True], TEST_DF[\"b\"][1::2]) def test_plot_colored_by_NON_EXISTENT_col(self): config", "class TestLinePlotConfig(TestCase, BaseXYPlotConfig): def setUp(self): self.configurator = LinePlotConfigurator self.basic_type =", "TEST_DF) def test_melt_mode_with_melted_columns(self): config = self.configurator(data_source=TEST_DF, melt_source_data=True, columns_to_melt=[\"e\", \"f\"]) self.assertIsNot(config.transformed_data,", "import HeatmapPlotConfigurator, \\ HEATMAP_PLOT_TYPE, HistogramPlotConfigurator, HIST_PLOT_TYPE, \\ LinePlotConfigurator, BarPlotConfigurator, ScatterPlotConfigurator,", "= self.configurator(data_source=TEST_DF, melt_source_data=True, columns_to_melt=[\"e\", \"f\"], z_col_name=\"g\") self.assertIsNot(config.transformed_data, TEST_DF) self.assertIs(config.data_source, TEST_DF)", "config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"NON-EXISTENT\") with self.assertRaises(KeyError): config.to_dict() def", "Make sure different configurators provide the right data choices. \"\"\"", "[\"f\"] * (LEN // 2)) self.assertEqual(set(config.x_arr.keys()), set(hue_values)) for key in", "by a string: config = self.configurator(data_source=TEST_DF, x_col_name=\"a\", y_col_name=\"b\", z_col_name=\"d\") self.assertFalse(config.plot_style.colorize_by_float)", "import division from unittest import skipIf, TestCase import os from", "self.assertEqual(config.plot_type, self.basic_type) config_dict = config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict) assert_array_equal(config_dict[\"x_arr\"],", "config.to_dict() self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict) assert_array_equal(config_dict[\"x_arr\"], TEST_DF[\"a\"].values) self.assertIn(\"y_arr\", config_dict) assert_array_equal(config_dict[\"y_arr\"],", "= np.array([\"e\"]*LEN+[\"f\"]*LEN) assert_array_equal(config.x_arr, x_values) self.assertEqual(config.x_col_name, \"variable\") self.assertEqual(len(config.y_arr), 2 * LEN)", "\"e\": np.random.randn(LEN), \"f\": range(LEN), # Highly repetitive column to split", "self.assertIsInstance(config_dict, dict) self.assertIn(\"x_arr\", config_dict) self.assertIsInstance(config_dict[\"x_arr\"], dict) d_values = TEST_DF[\"d\"].unique() self.assertEqual(set(config_dict[\"x_arr\"].keys()),", "16 TEST_DF = DataFrame({\"a\": [1, 2, 3, 4, 1, 2,", "For example: assert_array_equal(config_dict[\"y_arr\"][\"c\"], np.array([2, 2, 3])) def test_plot_colored_by_bool_col(self): # Color" ]
[ "TestMixed(IntegrationTest): def __init__(self, *args, **kwargs): super().__init__(os.path.join('languages', 'mixed'), *args, **kwargs) def", "'mixed_library'), *args, **kwargs) def test_build(self): self.build(executable('program')) self.assertOutput([executable('program')], 'hello, library!\\n') @skip_if('fortran'", "**kwargs): super().__init__(os.path.join('languages', 'mixed_fortran'), *args, **kwargs) def test_build(self): self.build(executable('program')) self.assertOutput([executable('program')], 'hello", "mismatch somewhere. @skip_if(env.host_platform.genus == 'darwin', 'fortran on os x is", "somewhere. @skip_if(env.host_platform.genus == 'darwin', 'fortran on os x is weird')", "# XXX: This fails on macOS, probably because of a", "**kwargs): super().__init__(os.path.join('languages', 'mixed_library'), *args, **kwargs) def test_build(self): self.build(executable('program')) self.assertOutput([executable('program')], 'hello,", "def __init__(self, *args, **kwargs): super().__init__(os.path.join('languages', 'mixed'), *args, **kwargs) def test_build(self):", "*args, **kwargs): super().__init__(os.path.join('languages', 'mixed_fortran'), *args, **kwargs) def test_build(self): self.build(executable('program')) self.assertOutput([executable('program')],", "test_build(self): self.build(executable('program')) self.assertOutput([executable('program')], 'hello from c++!\\n') class TestMixedLibrary(IntegrationTest): def __init__(self,", "__init__(self, *args, **kwargs): super().__init__(os.path.join('languages', 'mixed'), *args, **kwargs) def test_build(self): self.build(executable('program'))", "class TestMixed(IntegrationTest): def __init__(self, *args, **kwargs): super().__init__(os.path.join('languages', 'mixed'), *args, **kwargs)", "os x is weird') class TestMixedFortran(IntegrationTest): def __init__(self, *args, **kwargs):", "is weird') class TestMixedFortran(IntegrationTest): def __init__(self, *args, **kwargs): super().__init__(os.path.join('languages', 'mixed_fortran'),", "self.build(executable('program')) self.assertOutput([executable('program')], 'hello, library!\\n') @skip_if('fortran' not in test_features, 'skipping fortran", "a version mismatch somewhere. @skip_if(env.host_platform.genus == 'darwin', 'fortran on os", "import os.path from .. import * class TestMixed(IntegrationTest): def __init__(self,", "os.path from .. import * class TestMixed(IntegrationTest): def __init__(self, *args,", "test_build(self): self.build(executable('program')) self.assertOutput([executable('program')], 'hello, library!\\n') @skip_if('fortran' not in test_features, 'skipping", "tests') # XXX: This fails on macOS, probably because of", "because of a version mismatch somewhere. @skip_if(env.host_platform.genus == 'darwin', 'fortran", "__init__(self, *args, **kwargs): super().__init__(os.path.join('languages', 'mixed_library'), *args, **kwargs) def test_build(self): self.build(executable('program'))", "class TestMixedLibrary(IntegrationTest): def __init__(self, *args, **kwargs): super().__init__(os.path.join('languages', 'mixed_library'), *args, **kwargs)", "**kwargs) def test_build(self): self.build(executable('program')) self.assertOutput([executable('program')], 'hello, library!\\n') @skip_if('fortran' not in", "'fortran on os x is weird') class TestMixedFortran(IntegrationTest): def __init__(self,", "'hello, library!\\n') @skip_if('fortran' not in test_features, 'skipping fortran tests') #", "def test_build(self): self.build(executable('program')) self.assertOutput([executable('program')], 'hello, library!\\n') @skip_if('fortran' not in test_features,", "super().__init__(os.path.join('languages', 'mixed_library'), *args, **kwargs) def test_build(self): self.build(executable('program')) self.assertOutput([executable('program')], 'hello, library!\\n')", "weird') class TestMixedFortran(IntegrationTest): def __init__(self, *args, **kwargs): super().__init__(os.path.join('languages', 'mixed_fortran'), *args,", "not in test_features, 'skipping fortran tests') # XXX: This fails", "TestMixedLibrary(IntegrationTest): def __init__(self, *args, **kwargs): super().__init__(os.path.join('languages', 'mixed_library'), *args, **kwargs) def", "def __init__(self, *args, **kwargs): super().__init__(os.path.join('languages', 'mixed_fortran'), *args, **kwargs) def test_build(self):", "fails on macOS, probably because of a version mismatch somewhere.", "'mixed_fortran'), *args, **kwargs) def test_build(self): self.build(executable('program')) self.assertOutput([executable('program')], 'hello from f77!\\n')", "* class TestMixed(IntegrationTest): def __init__(self, *args, **kwargs): super().__init__(os.path.join('languages', 'mixed'), *args,", "@skip_if('fortran' not in test_features, 'skipping fortran tests') # XXX: This", "**kwargs): super().__init__(os.path.join('languages', 'mixed'), *args, **kwargs) def test_build(self): self.build(executable('program')) self.assertOutput([executable('program')], 'hello", "on macOS, probably because of a version mismatch somewhere. @skip_if(env.host_platform.genus", "__init__(self, *args, **kwargs): super().__init__(os.path.join('languages', 'mixed_fortran'), *args, **kwargs) def test_build(self): self.build(executable('program'))", "@skip_if(env.host_platform.genus == 'darwin', 'fortran on os x is weird') class", "*args, **kwargs): super().__init__(os.path.join('languages', 'mixed_library'), *args, **kwargs) def test_build(self): self.build(executable('program')) self.assertOutput([executable('program')],", "class TestMixedFortran(IntegrationTest): def __init__(self, *args, **kwargs): super().__init__(os.path.join('languages', 'mixed_fortran'), *args, **kwargs)", "import * class TestMixed(IntegrationTest): def __init__(self, *args, **kwargs): super().__init__(os.path.join('languages', 'mixed'),", "self.assertOutput([executable('program')], 'hello from c++!\\n') class TestMixedLibrary(IntegrationTest): def __init__(self, *args, **kwargs):", "This fails on macOS, probably because of a version mismatch", "fortran tests') # XXX: This fails on macOS, probably because", "def __init__(self, *args, **kwargs): super().__init__(os.path.join('languages', 'mixed_library'), *args, **kwargs) def test_build(self):", "x is weird') class TestMixedFortran(IntegrationTest): def __init__(self, *args, **kwargs): super().__init__(os.path.join('languages',", "of a version mismatch somewhere. @skip_if(env.host_platform.genus == 'darwin', 'fortran on", "*args, **kwargs): super().__init__(os.path.join('languages', 'mixed'), *args, **kwargs) def test_build(self): self.build(executable('program')) self.assertOutput([executable('program')],", "'mixed'), *args, **kwargs) def test_build(self): self.build(executable('program')) self.assertOutput([executable('program')], 'hello from c++!\\n')", "self.assertOutput([executable('program')], 'hello, library!\\n') @skip_if('fortran' not in test_features, 'skipping fortran tests')", "library!\\n') @skip_if('fortran' not in test_features, 'skipping fortran tests') # XXX:", "'darwin', 'fortran on os x is weird') class TestMixedFortran(IntegrationTest): def", "from .. import * class TestMixed(IntegrationTest): def __init__(self, *args, **kwargs):", ".. import * class TestMixed(IntegrationTest): def __init__(self, *args, **kwargs): super().__init__(os.path.join('languages',", "super().__init__(os.path.join('languages', 'mixed'), *args, **kwargs) def test_build(self): self.build(executable('program')) self.assertOutput([executable('program')], 'hello from", "'hello from c++!\\n') class TestMixedLibrary(IntegrationTest): def __init__(self, *args, **kwargs): super().__init__(os.path.join('languages',", "== 'darwin', 'fortran on os x is weird') class TestMixedFortran(IntegrationTest):", "version mismatch somewhere. @skip_if(env.host_platform.genus == 'darwin', 'fortran on os x", "macOS, probably because of a version mismatch somewhere. @skip_if(env.host_platform.genus ==", "def test_build(self): self.build(executable('program')) self.assertOutput([executable('program')], 'hello from c++!\\n') class TestMixedLibrary(IntegrationTest): def", "TestMixedFortran(IntegrationTest): def __init__(self, *args, **kwargs): super().__init__(os.path.join('languages', 'mixed_fortran'), *args, **kwargs) def", "in test_features, 'skipping fortran tests') # XXX: This fails on", "'skipping fortran tests') # XXX: This fails on macOS, probably", "XXX: This fails on macOS, probably because of a version", "*args, **kwargs) def test_build(self): self.build(executable('program')) self.assertOutput([executable('program')], 'hello, library!\\n') @skip_if('fortran' not", "probably because of a version mismatch somewhere. @skip_if(env.host_platform.genus == 'darwin',", "c++!\\n') class TestMixedLibrary(IntegrationTest): def __init__(self, *args, **kwargs): super().__init__(os.path.join('languages', 'mixed_library'), *args,", "on os x is weird') class TestMixedFortran(IntegrationTest): def __init__(self, *args,", "from c++!\\n') class TestMixedLibrary(IntegrationTest): def __init__(self, *args, **kwargs): super().__init__(os.path.join('languages', 'mixed_library'),", "*args, **kwargs) def test_build(self): self.build(executable('program')) self.assertOutput([executable('program')], 'hello from c++!\\n') class", "super().__init__(os.path.join('languages', 'mixed_fortran'), *args, **kwargs) def test_build(self): self.build(executable('program')) self.assertOutput([executable('program')], 'hello from", "**kwargs) def test_build(self): self.build(executable('program')) self.assertOutput([executable('program')], 'hello from c++!\\n') class TestMixedLibrary(IntegrationTest):", "test_features, 'skipping fortran tests') # XXX: This fails on macOS,", "self.build(executable('program')) self.assertOutput([executable('program')], 'hello from c++!\\n') class TestMixedLibrary(IntegrationTest): def __init__(self, *args," ]
[ "reader: student_list.append(row) print(row) print(student_list) columns = [\"user_id\", \"integration_id\", \"login_id\", \"password\",", "from collections import namedtuple # Basic example Point = namedtuple('Point',", "+ p.y) print(Point(x=11, y=22)) from collections import namedtuple import csv", "student_namedtupe_list = [] for row in student_list: student = Student(*row)", "y) print(p.x + p.y) print(Point(x=11, y=22)) from collections import namedtuple", "= namedtuple('Student', columns) student_namedtupe_list = [] for row in student_list:", "p[1]) x, y = p print(x, y) print(p.x + p.y)", "\"last_name\", \"full_name\", \"sortable_name\", \"short_name\", \"email\", \"status\"] Student = namedtuple('Student', columns)", "= [] for row in reader: student_list.append(row) print(row) print(student_list) columns", "namedtuple # Basic example Point = namedtuple('Point', ['x', 'y']) p", "print(Point(x=11, y=22)) from collections import namedtuple import csv f =", "Student = namedtuple('Student', columns) student_namedtupe_list = [] for row in", "= open(\"users.csv\", \"r\") next(f) reader = csv.reader(f) student_list = []", "p print(x, y) print(p.x + p.y) print(Point(x=11, y=22)) from collections", "= Point(11, y=22) print(p[0] + p[1]) x, y = p", "x, y = p print(x, y) print(p.x + p.y) print(Point(x=11,", "row in reader: student_list.append(row) print(row) print(student_list) columns = [\"user_id\", \"integration_id\",", "for row in student_list: student = Student(*row) student_namedtupe_list.append(student) print(student_namedtupe_list[0]) print(student_namedtupe_list[0].full_name)", "p.y) print(Point(x=11, y=22)) from collections import namedtuple import csv f", "= p print(x, y) print(p.x + p.y) print(Point(x=11, y=22)) from", "namedtuple import csv f = open(\"users.csv\", \"r\") next(f) reader =", "y=22)) from collections import namedtuple import csv f = open(\"users.csv\",", "student_list.append(row) print(row) print(student_list) columns = [\"user_id\", \"integration_id\", \"login_id\", \"password\", \"first_name\",", "in reader: student_list.append(row) print(row) print(student_list) columns = [\"user_id\", \"integration_id\", \"login_id\",", "Point = namedtuple('Point', ['x', 'y']) p = Point(11, y=22) print(p[0]", "+ p[1]) x, y = p print(x, y) print(p.x +", "\"sortable_name\", \"short_name\", \"email\", \"status\"] Student = namedtuple('Student', columns) student_namedtupe_list =", "namedtuple('Student', columns) student_namedtupe_list = [] for row in student_list: student", "[\"user_id\", \"integration_id\", \"login_id\", \"password\", \"first_name\", \"last_name\", \"full_name\", \"sortable_name\", \"short_name\", \"email\",", "= namedtuple('Point', ['x', 'y']) p = Point(11, y=22) print(p[0] +", "\"login_id\", \"password\", \"first_name\", \"last_name\", \"full_name\", \"sortable_name\", \"short_name\", \"email\", \"status\"] Student", "[] for row in student_list: student = Student(*row) student_namedtupe_list.append(student) print(student_namedtupe_list[0])", "['x', 'y']) p = Point(11, y=22) print(p[0] + p[1]) x,", "\"short_name\", \"email\", \"status\"] Student = namedtuple('Student', columns) student_namedtupe_list = []", "Basic example Point = namedtuple('Point', ['x', 'y']) p = Point(11,", "collections import namedtuple import csv f = open(\"users.csv\", \"r\") next(f)", "print(x, y) print(p.x + p.y) print(Point(x=11, y=22)) from collections import", "student_list = [] for row in reader: student_list.append(row) print(row) print(student_list)", "columns = [\"user_id\", \"integration_id\", \"login_id\", \"password\", \"first_name\", \"last_name\", \"full_name\", \"sortable_name\",", "reader = csv.reader(f) student_list = [] for row in reader:", "columns) student_namedtupe_list = [] for row in student_list: student =", "\"r\") next(f) reader = csv.reader(f) student_list = [] for row", "# Basic example Point = namedtuple('Point', ['x', 'y']) p =", "\"password\", \"first_name\", \"last_name\", \"full_name\", \"sortable_name\", \"short_name\", \"email\", \"status\"] Student =", "y=22) print(p[0] + p[1]) x, y = p print(x, y)", "\"email\", \"status\"] Student = namedtuple('Student', columns) student_namedtupe_list = [] for", "'y']) p = Point(11, y=22) print(p[0] + p[1]) x, y", "f = open(\"users.csv\", \"r\") next(f) reader = csv.reader(f) student_list =", "csv.reader(f) student_list = [] for row in reader: student_list.append(row) print(row)", "for row in reader: student_list.append(row) print(row) print(student_list) columns = [\"user_id\",", "open(\"users.csv\", \"r\") next(f) reader = csv.reader(f) student_list = [] for", "= csv.reader(f) student_list = [] for row in reader: student_list.append(row)", "= [] for row in student_list: student = Student(*row) student_namedtupe_list.append(student)", "import namedtuple import csv f = open(\"users.csv\", \"r\") next(f) reader", "print(student_list) columns = [\"user_id\", \"integration_id\", \"login_id\", \"password\", \"first_name\", \"last_name\", \"full_name\",", "\"status\"] Student = namedtuple('Student', columns) student_namedtupe_list = [] for row", "import csv f = open(\"users.csv\", \"r\") next(f) reader = csv.reader(f)", "import namedtuple # Basic example Point = namedtuple('Point', ['x', 'y'])", "namedtuple('Point', ['x', 'y']) p = Point(11, y=22) print(p[0] + p[1])", "Point(11, y=22) print(p[0] + p[1]) x, y = p print(x,", "example Point = namedtuple('Point', ['x', 'y']) p = Point(11, y=22)", "y = p print(x, y) print(p.x + p.y) print(Point(x=11, y=22))", "csv f = open(\"users.csv\", \"r\") next(f) reader = csv.reader(f) student_list", "print(row) print(student_list) columns = [\"user_id\", \"integration_id\", \"login_id\", \"password\", \"first_name\", \"last_name\",", "\"first_name\", \"last_name\", \"full_name\", \"sortable_name\", \"short_name\", \"email\", \"status\"] Student = namedtuple('Student',", "\"full_name\", \"sortable_name\", \"short_name\", \"email\", \"status\"] Student = namedtuple('Student', columns) student_namedtupe_list", "print(p[0] + p[1]) x, y = p print(x, y) print(p.x", "[] for row in reader: student_list.append(row) print(row) print(student_list) columns =", "\"integration_id\", \"login_id\", \"password\", \"first_name\", \"last_name\", \"full_name\", \"sortable_name\", \"short_name\", \"email\", \"status\"]", "print(p.x + p.y) print(Point(x=11, y=22)) from collections import namedtuple import", "from collections import namedtuple import csv f = open(\"users.csv\", \"r\")", "= [\"user_id\", \"integration_id\", \"login_id\", \"password\", \"first_name\", \"last_name\", \"full_name\", \"sortable_name\", \"short_name\",", "next(f) reader = csv.reader(f) student_list = [] for row in", "p = Point(11, y=22) print(p[0] + p[1]) x, y =", "collections import namedtuple # Basic example Point = namedtuple('Point', ['x'," ]
[ "yappi.set_clock_type(clock_type) yappi.start(addons=True) print(\"Start mitmdump...\") mitmdump([\"-k\", \"-q\", \"-S\", \"1024example\"]) print(\"mitmdump stopped.\")", "a = ApacheBenchThread(concurrency) a.start() if profiler == \"yappi\": yappi.set_clock_type(clock_type) yappi.start(addons=True)", "{} -X 127.0.0.1:8080 http://example.com/\".format(self.concurrency)) @click.command() @click.option('--profiler', default=\"none\", type=click.Choice(['none', 'yappi'])) @click.option('--clock-type',", "mitmdump from os import system from threading import Thread import", "clock_type, concurrency): outfile = \"callgrind.mitmdump-{}-c{}\".format(clock_type, concurrency) a = ApacheBenchThread(concurrency) a.start()", "\"1024example\"]) print(\"mitmdump stopped.\") print(\"Save profile information...\") if profiler == \"yappi\":", "import click class ApacheBenchThread(Thread): def __init__(self, concurrency): self.concurrency = concurrency", "yappi.stop() stats = yappi.get_func_stats() stats.save(outfile, type='callgrind') print(\"Done.\") if __name__ ==", "install click yappi from mitmproxy.main import mitmdump from os import", "<reponame>dotnes/mitmproxy # Profile mitmdump with apachebench and # yappi (https://code.google.com/p/yappi/)", "click class ApacheBenchThread(Thread): def __init__(self, concurrency): self.concurrency = concurrency super().__init__()", "@click.option('--profiler', default=\"none\", type=click.Choice(['none', 'yappi'])) @click.option('--clock-type', default=\"cpu\", type=click.Choice(['wall', 'cpu'])) @click.option('--concurrency', default=1,", "\"yappi\": yappi.set_clock_type(clock_type) yappi.start(addons=True) print(\"Start mitmdump...\") mitmdump([\"-k\", \"-q\", \"-S\", \"1024example\"]) print(\"mitmdump", "type=click.INT) def main(profiler, clock_type, concurrency): outfile = \"callgrind.mitmdump-{}-c{}\".format(clock_type, concurrency) a", "main(profiler, clock_type, concurrency): outfile = \"callgrind.mitmdump-{}-c{}\".format(clock_type, concurrency) a = ApacheBenchThread(concurrency)", "yappi import click class ApacheBenchThread(Thread): def __init__(self, concurrency): self.concurrency =", "class ApacheBenchThread(Thread): def __init__(self, concurrency): self.concurrency = concurrency super().__init__() def", "= ApacheBenchThread(concurrency) a.start() if profiler == \"yappi\": yappi.set_clock_type(clock_type) yappi.start(addons=True) print(\"Start", "1024 -c {} -X 127.0.0.1:8080 http://example.com/\".format(self.concurrency)) @click.command() @click.option('--profiler', default=\"none\", type=click.Choice(['none',", "- pip install click yappi from mitmproxy.main import mitmdump from", "__init__(self, concurrency): self.concurrency = concurrency super().__init__() def run(self): time.sleep(2) system(", "(https://code.google.com/p/yappi/) # # Requirements: # - Apache Bench \"ab\" binary", "os import system from threading import Thread import time import", "concurrency): outfile = \"callgrind.mitmdump-{}-c{}\".format(clock_type, concurrency) a = ApacheBenchThread(concurrency) a.start() if", "= concurrency super().__init__() def run(self): time.sleep(2) system( \"ab -n 1024", "mitmdump([\"-k\", \"-q\", \"-S\", \"1024example\"]) print(\"mitmdump stopped.\") print(\"Save profile information...\") if", "super().__init__() def run(self): time.sleep(2) system( \"ab -n 1024 -c {}", "== \"yappi\": yappi.set_clock_type(clock_type) yappi.start(addons=True) print(\"Start mitmdump...\") mitmdump([\"-k\", \"-q\", \"-S\", \"1024example\"])", "if profiler == \"yappi\": yappi.stop() stats = yappi.get_func_stats() stats.save(outfile, type='callgrind')", "Profile mitmdump with apachebench and # yappi (https://code.google.com/p/yappi/) # #", "yappi.start(addons=True) print(\"Start mitmdump...\") mitmdump([\"-k\", \"-q\", \"-S\", \"1024example\"]) print(\"mitmdump stopped.\") print(\"Save", "def main(profiler, clock_type, concurrency): outfile = \"callgrind.mitmdump-{}-c{}\".format(clock_type, concurrency) a =", "profiler == \"yappi\": yappi.stop() stats = yappi.get_func_stats() stats.save(outfile, type='callgrind') print(\"Done.\")", "with apachebench and # yappi (https://code.google.com/p/yappi/) # # Requirements: #", "default=1, type=click.INT) def main(profiler, clock_type, concurrency): outfile = \"callgrind.mitmdump-{}-c{}\".format(clock_type, concurrency)", "Bench \"ab\" binary # - pip install click yappi from", "Apache Bench \"ab\" binary # - pip install click yappi", "from mitmproxy.main import mitmdump from os import system from threading", "time.sleep(2) system( \"ab -n 1024 -c {} -X 127.0.0.1:8080 http://example.com/\".format(self.concurrency))", "click yappi from mitmproxy.main import mitmdump from os import system", "self.concurrency = concurrency super().__init__() def run(self): time.sleep(2) system( \"ab -n", "concurrency) a = ApacheBenchThread(concurrency) a.start() if profiler == \"yappi\": yappi.set_clock_type(clock_type)", "\"yappi\": yappi.stop() stats = yappi.get_func_stats() stats.save(outfile, type='callgrind') print(\"Done.\") if __name__", "time import yappi import click class ApacheBenchThread(Thread): def __init__(self, concurrency):", "@click.command() @click.option('--profiler', default=\"none\", type=click.Choice(['none', 'yappi'])) @click.option('--clock-type', default=\"cpu\", type=click.Choice(['wall', 'cpu'])) @click.option('--concurrency',", "system( \"ab -n 1024 -c {} -X 127.0.0.1:8080 http://example.com/\".format(self.concurrency)) @click.command()", "default=\"none\", type=click.Choice(['none', 'yappi'])) @click.option('--clock-type', default=\"cpu\", type=click.Choice(['wall', 'cpu'])) @click.option('--concurrency', default=1, type=click.INT)", "ApacheBenchThread(Thread): def __init__(self, concurrency): self.concurrency = concurrency super().__init__() def run(self):", "import Thread import time import yappi import click class ApacheBenchThread(Thread):", "stopped.\") print(\"Save profile information...\") if profiler == \"yappi\": yappi.stop() stats", "print(\"Start mitmdump...\") mitmdump([\"-k\", \"-q\", \"-S\", \"1024example\"]) print(\"mitmdump stopped.\") print(\"Save profile", "pip install click yappi from mitmproxy.main import mitmdump from os", "== \"yappi\": yappi.stop() stats = yappi.get_func_stats() stats.save(outfile, type='callgrind') print(\"Done.\") if", "yappi from mitmproxy.main import mitmdump from os import system from", "profile information...\") if profiler == \"yappi\": yappi.stop() stats = yappi.get_func_stats()", "http://example.com/\".format(self.concurrency)) @click.command() @click.option('--profiler', default=\"none\", type=click.Choice(['none', 'yappi'])) @click.option('--clock-type', default=\"cpu\", type=click.Choice(['wall', 'cpu']))", "'yappi'])) @click.option('--clock-type', default=\"cpu\", type=click.Choice(['wall', 'cpu'])) @click.option('--concurrency', default=1, type=click.INT) def main(profiler,", "import mitmdump from os import system from threading import Thread", "# yappi (https://code.google.com/p/yappi/) # # Requirements: # - Apache Bench", "import time import yappi import click class ApacheBenchThread(Thread): def __init__(self,", "= yappi.get_func_stats() stats.save(outfile, type='callgrind') print(\"Done.\") if __name__ == '__main__': main()", "-X 127.0.0.1:8080 http://example.com/\".format(self.concurrency)) @click.command() @click.option('--profiler', default=\"none\", type=click.Choice(['none', 'yappi'])) @click.option('--clock-type', default=\"cpu\",", "# Requirements: # - Apache Bench \"ab\" binary # -", "'cpu'])) @click.option('--concurrency', default=1, type=click.INT) def main(profiler, clock_type, concurrency): outfile =", "a.start() if profiler == \"yappi\": yappi.set_clock_type(clock_type) yappi.start(addons=True) print(\"Start mitmdump...\") mitmdump([\"-k\",", "concurrency super().__init__() def run(self): time.sleep(2) system( \"ab -n 1024 -c", "Thread import time import yappi import click class ApacheBenchThread(Thread): def", "# - pip install click yappi from mitmproxy.main import mitmdump", "\"ab\" binary # - pip install click yappi from mitmproxy.main", "Requirements: # - Apache Bench \"ab\" binary # - pip", "print(\"mitmdump stopped.\") print(\"Save profile information...\") if profiler == \"yappi\": yappi.stop()", "profiler == \"yappi\": yappi.set_clock_type(clock_type) yappi.start(addons=True) print(\"Start mitmdump...\") mitmdump([\"-k\", \"-q\", \"-S\",", "yappi (https://code.google.com/p/yappi/) # # Requirements: # - Apache Bench \"ab\"", "# # Requirements: # - Apache Bench \"ab\" binary #", "def run(self): time.sleep(2) system( \"ab -n 1024 -c {} -X", "type=click.Choice(['wall', 'cpu'])) @click.option('--concurrency', default=1, type=click.INT) def main(profiler, clock_type, concurrency): outfile", "print(\"Save profile information...\") if profiler == \"yappi\": yappi.stop() stats =", "from threading import Thread import time import yappi import click", "def __init__(self, concurrency): self.concurrency = concurrency super().__init__() def run(self): time.sleep(2)", "\"callgrind.mitmdump-{}-c{}\".format(clock_type, concurrency) a = ApacheBenchThread(concurrency) a.start() if profiler == \"yappi\":", "127.0.0.1:8080 http://example.com/\".format(self.concurrency)) @click.command() @click.option('--profiler', default=\"none\", type=click.Choice(['none', 'yappi'])) @click.option('--clock-type', default=\"cpu\", type=click.Choice(['wall',", "= \"callgrind.mitmdump-{}-c{}\".format(clock_type, concurrency) a = ApacheBenchThread(concurrency) a.start() if profiler ==", "import yappi import click class ApacheBenchThread(Thread): def __init__(self, concurrency): self.concurrency", "binary # - pip install click yappi from mitmproxy.main import", "@click.option('--clock-type', default=\"cpu\", type=click.Choice(['wall', 'cpu'])) @click.option('--concurrency', default=1, type=click.INT) def main(profiler, clock_type,", "from os import system from threading import Thread import time", "if profiler == \"yappi\": yappi.set_clock_type(clock_type) yappi.start(addons=True) print(\"Start mitmdump...\") mitmdump([\"-k\", \"-q\",", "mitmdump with apachebench and # yappi (https://code.google.com/p/yappi/) # # Requirements:", "stats = yappi.get_func_stats() stats.save(outfile, type='callgrind') print(\"Done.\") if __name__ == '__main__':", "concurrency): self.concurrency = concurrency super().__init__() def run(self): time.sleep(2) system( \"ab", "mitmdump...\") mitmdump([\"-k\", \"-q\", \"-S\", \"1024example\"]) print(\"mitmdump stopped.\") print(\"Save profile information...\")", "information...\") if profiler == \"yappi\": yappi.stop() stats = yappi.get_func_stats() stats.save(outfile,", "outfile = \"callgrind.mitmdump-{}-c{}\".format(clock_type, concurrency) a = ApacheBenchThread(concurrency) a.start() if profiler", "-n 1024 -c {} -X 127.0.0.1:8080 http://example.com/\".format(self.concurrency)) @click.command() @click.option('--profiler', default=\"none\",", "@click.option('--concurrency', default=1, type=click.INT) def main(profiler, clock_type, concurrency): outfile = \"callgrind.mitmdump-{}-c{}\".format(clock_type,", "import system from threading import Thread import time import yappi", "\"ab -n 1024 -c {} -X 127.0.0.1:8080 http://example.com/\".format(self.concurrency)) @click.command() @click.option('--profiler',", "run(self): time.sleep(2) system( \"ab -n 1024 -c {} -X 127.0.0.1:8080", "apachebench and # yappi (https://code.google.com/p/yappi/) # # Requirements: # -", "ApacheBenchThread(concurrency) a.start() if profiler == \"yappi\": yappi.set_clock_type(clock_type) yappi.start(addons=True) print(\"Start mitmdump...\")", "# - Apache Bench \"ab\" binary # - pip install", "type=click.Choice(['none', 'yappi'])) @click.option('--clock-type', default=\"cpu\", type=click.Choice(['wall', 'cpu'])) @click.option('--concurrency', default=1, type=click.INT) def", "\"-q\", \"-S\", \"1024example\"]) print(\"mitmdump stopped.\") print(\"Save profile information...\") if profiler", "# Profile mitmdump with apachebench and # yappi (https://code.google.com/p/yappi/) #", "-c {} -X 127.0.0.1:8080 http://example.com/\".format(self.concurrency)) @click.command() @click.option('--profiler', default=\"none\", type=click.Choice(['none', 'yappi']))", "threading import Thread import time import yappi import click class", "- Apache Bench \"ab\" binary # - pip install click", "and # yappi (https://code.google.com/p/yappi/) # # Requirements: # - Apache", "mitmproxy.main import mitmdump from os import system from threading import", "default=\"cpu\", type=click.Choice(['wall', 'cpu'])) @click.option('--concurrency', default=1, type=click.INT) def main(profiler, clock_type, concurrency):", "system from threading import Thread import time import yappi import", "\"-S\", \"1024example\"]) print(\"mitmdump stopped.\") print(\"Save profile information...\") if profiler ==" ]
[ "logscale = False, aspectratio='equal', colbar_orient = 'vertical', units = None):", "contour levels up to max of S else: levels =", "boolean (True is default) create in linear/log scale aspectration :", ": a threshold value, default is None (no data clipping)", "fig,ax def histogram(data, normed = False): \"\"\" this function will", "= plt.colorbar(c) cbar.set_label(r'$\\omega$ [s$^{-1}$]') ax.set_aspect(aspectration) return f,ax def showf(data, variables=None,", "c = ax.contourf(data.x,data.y,data['w'], levels=levels, cmap = plt.get_cmap('RdYlBu')) plt.xlabel('x [' +", "plt.tight_layout() return f, ax def contour_plot(data, threshold = None, contourLevels", "def contour_plot(data, threshold = None, contourLevels = None, colbar =", "(no data clipping) contourLevels : number of contour levels, default", "or equal for the plot's apearence colbar_orient - 'horizontal' or", "dataset_to_array(data) x = data.x y = data.y u = data.u", "None, colbar = True, logscale = False, aspectration='equal', units=None): \"\"\"", "'vertical' orientation of the colorbar (if colbar is True) Outputs:", "= np.linspace(0, np.max(S.flatten()), 30) # default contour levels up to", "integer, default is 1 savepath : [optional] path to save", "xr.where(data['u']>threshold, threshold, data['u']) data['v'] = xr.where(data['v']>threshold, threshold, data['v']) S =", "to present normalized histogram \"\"\" u = np.asarray(data.u).flatten() v =", "plt.show() def showscal(data, property='ken'): \"\"\" showf(data, var, units) Arguments: data", "= data.x y = data.y u = data.u v =", "= True, logscale = False, aspectratio='equal', colbar_orient = 'vertical', units", "for the plot's apearence colbar_orient - 'horizontal' or 'vertical' orientation", "to array \"\"\" if 't' in data.dims: print('Warning: function for", "None else units[1])+']' data = data.piv.vec2scal(property=property) contour_plot(data) def animate(data, arrowscale=1,", "= plt.colors.LogNorm()) else: c = ax.contourf(x,y,S,alpha=0.8, cmap = plt.get_cmap(\"Blues\"), levels=levels)", "levels=levels, cmap = plt.get_cmap('RdYlBu')) plt.xlabel('x [' + lUnits + ']')", "= ax.contourf(x,y,S,alpha=0.8, cmap = plt.get_cmap(\"Blues\"), levels=levels) if colbar: cbar =", "colbar: cbar = plt.colorbar(c, orientation=colbar_orient) cbar.set_label(r'$\\left| \\, V \\, \\right|$", "None: data['w'] = xr.where(data['w']>threshold, threshold, data['w']) m = np.amax(abs(data['w'])) if", "['m' 'm' 'mm/s' 'mm/s'] velUnits = units[2] tUnits = velUnits.split('/')[1]", "# -*- coding: utf-8 -*- \"\"\" Various plots \"\"\" import", "threshold arrScale - use to change arrow scales nthArr -", "contour_plot(data) def animate(data, arrowscale=1, savepath=None): \"\"\" animates the quiver plot", "that contains dimensions of t,x,y and variables u,v and maybe", "a normalized histogram of the velocity data. Input: data :", "= np.amax(abs(data['w'])) if contourLevels == None: levels = np.linspace(-m, m,", "named im.mp4 is saved \"\"\" X, Y = data.x, data.y", "v**2)) fig = plt.get_fignums() if len(fig) == 0: # if", "to generate a colorbar or not logscale - if true", "units[0] ylabel += ' ' + units[1] fig = plt.figure(None", "= dataset_to_array(data) x = data.x y = data.y u =", "= False, aspectration='equal', units=None): \"\"\" contourf ajusted for the xarray", "mywriter = FFMpegWriter() if savepath: p = os.getcwd() os.chdir(savepath) anim.save('im.mp4',", "contourLevels = None, colbar = True, logscale = False, aspectratio='equal',", "units) Arguments: data : xarray.DataSet that contains dimensions of t,x,y", "(scalar) \"\"\" if variables is None: xlabel = ' '", "the dataset (multiple frames) Input: data : xarray PIV type", "def showscal(data, property='ken'): \"\"\" showf(data, var, units) Arguments: data :", "levels = levels, norm = plt.colors.LogNorm()) else: c = ax.contourf(x,y,S,alpha=0.8,", "+ ' [' + (None if units is None else", "be set equal to threshold arrScale - use to change", "aspectration='equal', units=None): \"\"\" contourf ajusted for the xarray PIV dataset,", "plt.get_cmap('RdYlBu'), norm=plt.colors.LogNorm()) else: c = ax.contourf(data.x,data.y,data['w'], levels=levels, cmap = plt.get_cmap('RdYlBu'))", "number of contour levels, default is None colbar : boolean", "data.x y = data.y u = data.u v = data.v", "len(fig) == 0: # if no figure is open fig,", "30) else: levels = np.linspace(-contourLevels, contourLevels, 30) if logscale: c", "plt.colorbar(Q) units = data.attrs['units'] cb.ax.set_ylabel('velocity (' + units[2] + ')')", "None): \"\"\" Generates a quiver plot of a 'data' xarray", "pivpy, one of the frames in the Dataset selected by", "None, nthArr = 1, contourLevels = None, colbar = True,", "' else: xlabel = variables[0] ylabel = variables[1] if units", "None, contourLevels = None, colbar = True, logscale = False,", "np.max(S.flatten()), 30) # default contour levels up to max of", "from matplotlib.animation import FuncAnimation, FFMpegWriter import xarray as xr import", "threshold - values above the threshold will be set equal", "in data.dims: print('Warning: function for a single frame, using first", "Various plots \"\"\" import numpy as np import matplotlib.pyplot as", "the frames in the Dataset selected by default using .isel(t=0)", "np.linspace(-contourLevels, contourLevels, 30) if logscale: c = ax.contourf(data.x,data.y,np.abs(data['w']), levels=levels, cmap", "Input: data : xarray PIV DataArray, converted automatically using .isel(t=0)", "data.x, data.y U, V = data.u[:,:,0], data.v[:,:,0] # first frame", "'t' in data.dims: print('Warning: function for a single frame, using", "= xr.where(data['w']>threshold, threshold, data['w']) m = np.amax(abs(data['w'])) if contourLevels ==", "']') plt.ylabel('y [' + lUnits + ']') if colbar: cbar", "set auto or equal for the plot's apearence colbar_orient -", "scale aspectration : string, 'equal' is the default \"\"\" data", "'mm/s' 'mm/s'] # velUnits = units[2] # tUnits = velUnits.split('/')[1]", "else var[1]) + ' [' + (None if units is", "to max of S else: levels = np.linspace(0, contourLevels, 30)", "or 'dt' else: lUnits, velUnits, tUnits = '', '', ''", "(True is default) create in linear/log scale aspectration : string,", "orientation of the colorbar (if colbar is True) Outputs: none", "ax = plt.gca() if contourLevels is None: levels = np.linspace(0,", "['+ lUnits +' $\\cdot$ '+ tUnits +'$^{-1}$]') ax.quiver(x[::nthArr],y[::nthArr], u[::nthArr,::nthArr],v[::nthArr,::nthArr],units='width', scale", "logscale = False, aspectration='equal', units=None): \"\"\" contourf ajusted for the", "im.mp4 is saved \"\"\" X, Y = data.x, data.y U,", "to save the MP4 animation, default is None Output: if", "arrow from the array contourLevels - use to specify the", "'s' or 'dt' else: lUnits, velUnits, tUnits = '', '',", "import pdb; pdb.set_trace() # xlabel = (None if var is", "= plt.subplot2grid((2,1),(1,0)) ax[1].hist(v,bins=np.int(np.sqrt(len(v)*0.5)),density=normed) ax[1].set_xlabel('v ['+units[2]+']') plt.tight_layout() return f, ax def", "Q = ax.quiver(X[::3,::3], Y[::3,::3], U[::3,::3], V[::3,::3], M[::3,::3], units='inches', scale=arrowscale) cb", "aspectratio='equal', colbar_orient = 'vertical', units = None): \"\"\" Generates a", "contourLevels - use to specify the maximum value (abs) of", "= None, contourLevels = None, colbar = True, logscale =", "'mm/s'] # velUnits = units[2] # tUnits = velUnits.split('/')[1] #", "plt.colors.LogNorm()) else: c = ax.contourf(x,y,S,alpha=0.8, cmap = plt.get_cmap(\"Blues\"), levels=levels) if", "aspectration : string, 'equal' is the default \"\"\" data =", "default using .isel(t=0) threshold - values above the threshold will", "units is not None: xlabel += ' ' + units[0]", "Inputs: data - xarray DataArray of the type defined in", "of DataSet arrowscale : [optional] integer, default is 1 savepath", "plt.colorbar(c, orientation=colbar_orient) cbar.set_label(r'$\\left| \\, V \\, \\right|$ ['+ lUnits +'", "data. Input: data : xarray DataSet with ['u','v'] attrs['units'] normed", "converted automatically using .isel(t=0) threshold : a threshold value, default", "plt.get_cmap(\"Blues\"), levels=levels) if colbar: cbar = plt.colorbar(c, orientation=colbar_orient) cbar.set_label(r'$\\left| \\,", "lUnits + ')') ax.set_aspect(aspectratio) return fig,ax def histogram(data, normed =", "single frame, using first frame, supply data.isel(t=N)') data = data.isel(t=N)", "if fig is None else fig.number) # import pdb; pdb.set_trace()", "'horizontal' or 'vertical' orientation of the colorbar (if colbar is", "ax.text(0.2,1.05, '1/'+str(len(data.t)), ha='center', va='center', transform=ax.transAxes) def update_quiver(num,Q,data,text): U,V = data.u[:,:,num],data.v[:,:,num]", "log scale aspectratio - set auto or equal for the", "if units is not None: xlabel += ' ' +", "is open fig, ax = plt.subplots() # open a new", "tUnits +'$^{-1}$]') ax.quiver(x[::nthArr],y[::nthArr], u[::nthArr,::nthArr],v[::nthArr,::nthArr],units='width', scale = np.max(S*arrScale),headwidth=2) ax.set_xlabel('x (' +", "30) if logscale: c = ax.contourf(data.x,data.y,np.abs(data['w']), levels=levels, cmap = plt.get_cmap('RdYlBu'),", "an image display of the animation if savepath is an", "frames = len(data.t), blit=False) mywriter = FFMpegWriter() if savepath: p", "= Inf, n) \"\"\" data = dataset_to_array(data) x = data.x", "fig is None else fig.number) for t in data['t']: d", "'+ tUnits +'$^{-1}$]') ax.quiver(x[::nthArr],y[::nthArr], u[::nthArr,::nthArr],v[::nthArr,::nthArr],units='width', scale = np.max(S*arrScale),headwidth=2) ax.set_xlabel('x ('", "np.asarray(data.u).flatten() v = np.asarray(data.v).flatten() units = data.attrs['units'] f,ax = plt.subplots(2)", "ylabel = variables[1] if units is not None: xlabel +=", "def animate(data, arrowscale=1, savepath=None): \"\"\" animates the quiver plot for", "else var[0]) + ' [' + (None if units is", "units = data.attrs['units'] f,ax = plt.subplots(2) ax[0].hist(u,bins=np.int(np.sqrt(len(u))*0.5),density=normed) ax[0].set_xlabel('u ['+units[2]+']') ax[1]", "return f, ax def contour_plot(data, threshold = None, contourLevels =", "None: data['u'] = xr.where(data['u']>threshold, threshold, data['u']) data['v'] = xr.where(data['v']>threshold, threshold,", "os.chdir(savepath) anim.save('im.mp4', writer=mywriter) os.chdir(p) else: anim.save('im.mp4', writer=mywriter) def dataset_to_array(data,N=0): \"\"\"", "30) # default contour levels up to max of S", "# default contour levels up to max of S else:", "save the MP4 animation, default is None Output: if savepath", "+ ')') ax.set_aspect(aspectratio) return fig,ax def histogram(data, normed = False):", "is the default \"\"\" data = dataset_to_array(data) if units is", "data.u[:,:,num],data.v[:,:,num] M = np.sqrt(U[::3,::3]**2 + V[::3,::3]**2) Q.set_UVC(U,V,M) text.set_text(str(num+1)+'/'+str(len(data.t))) return Q", "= None, colbar = True, logscale = False, aspectratio='equal', colbar_orient", "if var is None else var[0]) + ' [' +", "the animation if savepath is an existing path, a file", "Arguments: data : xarray.DataSet that contains dimensions of t,x,y and", "None, then only an image display of the animation if", "if contourLevels == None: levels = np.linspace(-m, m, 30) else:", "if fig is None else fig.number) for t in data['t']:", "is None else fig.number) for t in data['t']: d =", "nthArr = 1, contourLevels = None, colbar = True, logscale", "the MP4 animation, default is None Output: if savepath is", "= None): \"\"\" Generates a quiver plot of a 'data'", "plt.pause(0.1) plt.show() def showscal(data, property='ken'): \"\"\" showf(data, var, units) Arguments:", "the threshold will be set equal to threshold arrScale -", "plt.quiver(d['x'],d['y'],d['u'],d['v'],d['u']**2 + d['v']**2) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.draw() plt.pause(0.1) plt.show() def showscal(data,", "# xlabel = (None if var is None else var[0])", "= np.linspace(0, contourLevels, 30) if logscale: c = ax.contourf(x,y,S,alpha=0.8, cmap", "ax.set_aspect(aspectration) return f,ax def showf(data, variables=None, units=None, fig=None): \"\"\" showf(data,", "(default is True) show/hide colorbar logscale : boolean (True is", "['u','v'] attrs['units'] normed : (optional) default is False to present", "Q.set_UVC(U,V,M) text.set_text(str(num+1)+'/'+str(len(data.t))) return Q anim = FuncAnimation(fig, update_quiver, fargs=(Q,data,text), frames", "else units[0])+']' # ylabel = (None if var is None", "M[::3,::3], units='inches', scale=arrowscale) cb = plt.colorbar(Q) units = data.attrs['units'] cb.ax.set_ylabel('velocity", "units = data.attrs['units'] cb.ax.set_ylabel('velocity (' + units[2] + ')') text", "if variables is None: xlabel = ' ' ylabel =", "blit=False) mywriter = FFMpegWriter() if savepath: p = os.getcwd() os.chdir(savepath)", "data.y u = data.u v = data.v if units is", "if contourLevels is None: levels = np.linspace(0, np.max(S.flatten()), 30) #", "units=None, fig=None): \"\"\" showf(data, var, units) Arguments: data : xarray.DataSet", "- use to specify the maximum value (abs) of contour", "data['u'] = xr.where(data['u']>threshold, threshold, data['u']) data['v'] = xr.where(data['v']>threshold, threshold, data['v'])", "data : xarray.DataSet that contains dimensions of t,x,y and a", "arrowscale=1, savepath=None): \"\"\" animates the quiver plot for the dataset", "plt.subplot2grid((2,1),(1,0)) ax[1].hist(v,bins=np.int(np.sqrt(len(v)*0.5)),density=normed) ax[1].set_xlabel('v ['+units[2]+']') plt.tight_layout() return f, ax def contour_plot(data,", "Dataset to array \"\"\" if 't' in data.dims: print('Warning: function", "'' lUnits = '' f,ax = plt.subplots() if threshold is", "of t,x,y and a variable w (scalar) \"\"\" # fig", "['+units[2]+']') ax[1] = plt.subplot2grid((2,1),(1,0)) ax[1].hist(v,bins=np.int(np.sqrt(len(v)*0.5)),density=normed) ax[1].set_xlabel('v ['+units[2]+']') plt.tight_layout() return f,", "False, aspectration='equal', units=None): \"\"\" contourf ajusted for the xarray PIV", "ajusted for the xarray PIV dataset, creates a contour map", "type of DataSet arrowscale : [optional] integer, default is 1", "open fig, ax = plt.subplots() # open a new figure", "# ylabel = (None if var is None else var[1])", "every nth arrow from the array contourLevels - use to", "it 's' or 'dt' else: lUnits, velUnits, tUnits = '',", "data['u']) data['v'] = xr.where(data['v']>threshold, threshold, data['v']) S = np.array(np.sqrt(u**2 +", "no figure is open fig, ax = plt.subplots() # open", "of contour plots colbar - True/False wether to generate a", "0: # if no figure is open fig, ax =", "= velUnits.split('/')[1] # make it 's' or 'dt' else: #", "object (single frame from a dataset) Inputs: data - xarray", "units=None): \"\"\" contourf ajusted for the xarray PIV dataset, creates", "velUnits = '', '' lUnits = '' f,ax = plt.subplots()", "= plt.get_fignums() if len(fig) == 0: # if no figure", "arrow scales nthArr - use to plot only every nth", "data['w'] property. Input: data : xarray PIV DataArray, converted automatically", "= plt.get_cmap(\"Blues\"), levels = levels, norm = plt.colors.LogNorm()) else: c", "ax = plt.subplots() # open a new figure else: ax", "colbar - True/False wether to generate a colorbar or not", "xr import os def quiver(data, arrScale = 25.0, threshold =", "of the animation if savepath is an existing path, a", "True, logscale = False, aspectration='equal', units=None): \"\"\" contourf ajusted for", "that contains dimensions of t,x,y and a variable w (scalar)", "data.dims: print('Warning: function for a single frame, using first frame,", "U[::3,::3], V[::3,::3], M[::3,::3], units='inches', scale=arrowscale) cb = plt.colorbar(Q) units =", "xarray DataArray object (single frame from a dataset) Inputs: data", "' ' else: xlabel = variables[0] ylabel = variables[1] if", "= data.piv.vec2scal(property=property) contour_plot(data) def animate(data, arrowscale=1, savepath=None): \"\"\" animates the", "quiver plot for the dataset (multiple frames) Input: data :", "np.linspace(-m, m, 30) else: levels = np.linspace(-contourLevels, contourLevels, 30) if", "'', '', '' if threshold is not None: data['u'] =", "ax def contour_plot(data, threshold = None, contourLevels = None, colbar", "FuncAnimation, FFMpegWriter import xarray as xr import os def quiver(data,", "import os def quiver(data, arrScale = 25.0, threshold = None,", "True) Outputs: none Usage: graphics.quiver(data, arrScale = 0.2, threshold =", "cmap = plt.get_cmap('RdYlBu')) plt.xlabel('x [' + lUnits + ']') plt.ylabel('y", "ax[1] = plt.subplot2grid((2,1),(1,0)) ax[1].hist(v,bins=np.int(np.sqrt(len(v)*0.5)),density=normed) ax[1].set_xlabel('v ['+units[2]+']') plt.tight_layout() return f, ax", "lUnits + ']') plt.ylabel('y [' + lUnits + ']') if", "of t,x,y and variables u,v and maybe w (scalar) \"\"\"", "arrowscale : [optional] integer, default is 1 savepath : [optional]", "a quiver plot of a 'data' xarray DataArray object (single", "(scalar) \"\"\" # fig = plt.figure(None if fig is None", "True, logscale = False, aspectratio='equal', colbar_orient = 'vertical', units =", "data.u[:,:,0], data.v[:,:,0] # first frame fig, ax = plt.subplots(1,1) M", "and variables u,v and maybe w (scalar) \"\"\" if variables", "equal for the plot's apearence colbar_orient - 'horizontal' or 'vertical'", "+ units[2] + ')') text = ax.text(0.2,1.05, '1/'+str(len(data.t)), ha='center', va='center',", "- set auto or equal for the plot's apearence colbar_orient", "u = np.asarray(data.u).flatten() v = np.asarray(data.v).flatten() units = data.attrs['units'] f,ax", "= units[2] # tUnits = velUnits.split('/')[1] # make it 's'", "levels = np.linspace(-m, m, 30) else: levels = np.linspace(-contourLevels, contourLevels,", "Inf, n) \"\"\" data = dataset_to_array(data) x = data.x y", "xarray.DataSet that contains dimensions of t,x,y and variables u,v and", "= ax.contourf(data.x,data.y,data['w'], levels=levels, cmap = plt.get_cmap('RdYlBu')) plt.xlabel('x [' + lUnits", "'', '' lUnits = '' f,ax = plt.subplots() if threshold", "savepath is None, then only an image display of the", "image display of the animation if savepath is an existing", "wether to generate a colorbar or not logscale - if", "np.max(S*arrScale),headwidth=2) ax.set_xlabel('x (' + lUnits + ')') ax.set_ylabel('y (' +", "for a single frame, using first frame, supply data.isel(t=N)') data", "if threshold is not None: data['w'] = xr.where(data['w']>threshold, threshold, data['w'])", "V \\, \\right|$ ['+ lUnits +' $\\cdot$ '+ tUnits +'$^{-1}$]')", "= None, colbar = True, logscale = False, aspectration='equal', units=None):", "of the colorbar (if colbar is True) Outputs: none Usage:", "y = data.y u = data.u v = data.v if", "(if colbar is True) Outputs: none Usage: graphics.quiver(data, arrScale =", "$\\cdot$ '+ tUnits +'$^{-1}$]') ax.quiver(x[::nthArr],y[::nthArr], u[::nthArr,::nthArr],v[::nthArr,::nthArr],units='width', scale = np.max(S*arrScale),headwidth=2) ax.set_xlabel('x", "threshold : a threshold value, default is None (no data", "plt.figure(None if fig is None else fig.number) for t in", "if savepath is an existing path, a file named im.mp4", "use to change arrow scales nthArr - use to plot", "plot for the dataset (multiple frames) Input: data : xarray", "+ units[1] fig = plt.figure(None if fig is None else", "contourf ajusted for the xarray PIV dataset, creates a contour", "if var is None else var[1]) + ' [' +", "variables is None: xlabel = ' ' ylabel = '", "contains dimensions of t,x,y and variables u,v and maybe w", "automatically using .isel(t=0) threshold : a threshold value, default is", "contains dimensions of t,x,y and a variable w (scalar) \"\"\"", "pdb; pdb.set_trace() # xlabel = (None if var is None", "'' if threshold is not None: data['u'] = xr.where(data['u']>threshold, threshold,", "histogram \"\"\" u = np.asarray(data.u).flatten() v = np.asarray(data.v).flatten() units =", "(None if var is None else var[1]) + ' ['", "velUnits, tUnits = '', '', '' if threshold is not", "ax[1].set_xlabel('v ['+units[2]+']') plt.tight_layout() return f, ax def contour_plot(data, threshold =", "PIV DataArray, converted automatically using .isel(t=0) threshold : a threshold", "print('Warning: function for a single frame, using first frame, supply", "ylabel = (None if var is None else var[1]) +", "levels = np.linspace(0, np.max(S.flatten()), 30) # default contour levels up", "a 'data' xarray DataArray object (single frame from a dataset)", "plt.get_cmap('RdYlBu')) plt.xlabel('x [' + lUnits + ']') plt.ylabel('y [' +", "(None if units is None else units[1])+']' data = data.piv.vec2scal(property=property)", "= np.linspace(-m, m, 30) else: levels = np.linspace(-contourLevels, contourLevels, 30)", "t in data['t']: d = data.isel(t=t) plt.quiver(d['x'],d['y'],d['u'],d['v'],d['u']**2 + d['v']**2) plt.xlabel(xlabel)", "+ ')') text = ax.text(0.2,1.05, '1/'+str(len(data.t)), ha='center', va='center', transform=ax.transAxes) def", "[' + lUnits + ']') if colbar: cbar = plt.colorbar(c)", "path, a file named im.mp4 is saved \"\"\" X, Y", "xlabel = ' ' ylabel = ' ' else: xlabel", "u = data.u v = data.v if units is not", "units='inches', scale=arrowscale) cb = plt.colorbar(Q) units = data.attrs['units'] cb.ax.set_ylabel('velocity ('", "= velUnits.split('/')[1] # make it 's' or 'dt' else: lUnits,", "values above the threshold will be set equal to threshold", "fig = plt.get_fignums() if len(fig) == 0: # if no", "# tUnits = velUnits.split('/')[1] # make it 's' or 'dt'", "animate(data, arrowscale=1, savepath=None): \"\"\" animates the quiver plot for the", "fig=None): \"\"\" showf(data, var, units) Arguments: data : xarray.DataSet that", "xr.where(data['v']>threshold, threshold, data['v']) S = np.array(np.sqrt(u**2 + v**2)) fig =", "cbar = plt.colorbar(c, orientation=colbar_orient) cbar.set_label(r'$\\left| \\, V \\, \\right|$ ['+", "type defined in pivpy, one of the frames in the", "lUnits +' $\\cdot$ '+ tUnits +'$^{-1}$]') ax.quiver(x[::nthArr],y[::nthArr], u[::nthArr,::nthArr],v[::nthArr,::nthArr],units='width', scale =", "xarray PIV dataset, creates a contour map for the data['w']", "display of the animation if savepath is an existing path,", "# make it 's' or 'dt' else: lUnits, velUnits, tUnits", "import FuncAnimation, FFMpegWriter import xarray as xr import os def", "specify the maximum value (abs) of contour plots colbar -", "only every nth arrow from the array contourLevels - use", "(multiple frames) Input: data : xarray PIV type of DataSet", "the xarray PIV dataset, creates a contour map for the", ": [optional] path to save the MP4 animation, default is", "data : xarray DataSet with ['u','v'] attrs['units'] normed : (optional)", "data.piv.vec2scal(property=property) contour_plot(data) def animate(data, arrowscale=1, savepath=None): \"\"\" animates the quiver", "DataArray, converted automatically using .isel(t=0) threshold : a threshold value,", "v = data.v if units is not None: lUnits =", "and a variable w (scalar) \"\"\" # fig = plt.figure(None", "= dataset_to_array(data) if units is not None: lUnits = units[0]", "'m' 'mm/s' 'mm/s'] # velUnits = units[2] # tUnits =", "auto or equal for the plot's apearence colbar_orient - 'horizontal'", "+ units[0] ylabel += ' ' + units[1] fig =", "is None else units[1])+']' data = data.piv.vec2scal(property=property) contour_plot(data) def animate(data,", "savepath: p = os.getcwd() os.chdir(savepath) anim.save('im.mp4', writer=mywriter) os.chdir(p) else: anim.save('im.mp4',", "orientation=colbar_orient) cbar.set_label(r'$\\left| \\, V \\, \\right|$ ['+ lUnits +' $\\cdot$", "MP4 animation, default is None Output: if savepath is None,", "xlabel = variables[0] ylabel = variables[1] if units is not", "new figure else: ax = plt.gca() if contourLevels is None:", "\"\"\" this function will plot a normalized histogram of the", "contourLevels == None: levels = np.linspace(-m, m, 30) else: levels", "ax.quiver(x[::nthArr],y[::nthArr], u[::nthArr,::nthArr],v[::nthArr,::nthArr],units='width', scale = np.max(S*arrScale),headwidth=2) ax.set_xlabel('x (' + lUnits +", "# make it 's' or 'dt' else: # lUnits, velUnits", "not logscale - if true then colorbar is on log", "plt.colorbar(c) cbar.set_label(r'$\\omega$ [s$^{-1}$]') ax.set_aspect(aspectration) return f,ax def showf(data, variables=None, units=None,", "array contourLevels - use to specify the maximum value (abs)", "equal to threshold arrScale - use to change arrow scales", "= data.v if units is not None: lUnits = units[0]", "else: levels = np.linspace(0, contourLevels, 30) if logscale: c =", "path to save the MP4 animation, default is None Output:", "lUnits + ')') ax.set_ylabel('y (' + lUnits + ')') ax.set_aspect(aspectratio)", "[s$^{-1}$]') ax.set_aspect(aspectration) return f,ax def showf(data, variables=None, units=None, fig=None): \"\"\"", "' + units[0] ylabel += ' ' + units[1] fig", "')') ax.set_ylabel('y (' + lUnits + ')') ax.set_aspect(aspectratio) return fig,ax", "fig = plt.figure(None if fig is None else fig.number) for", "# import pdb; pdb.set_trace() # xlabel = (None if var", "+= ' ' + units[0] ylabel += ' ' +", "import numpy as np import matplotlib.pyplot as plt from matplotlib.animation", "- use to change arrow scales nthArr - use to", "']') if colbar: cbar = plt.colorbar(c) cbar.set_label(r'$\\omega$ [s$^{-1}$]') ax.set_aspect(aspectration) return", "generate a colorbar or not logscale - if true then", "norm=plt.colors.LogNorm()) else: c = ax.contourf(data.x,data.y,data['w'], levels=levels, cmap = plt.get_cmap('RdYlBu')) plt.xlabel('x", "xarray PIV DataArray, converted automatically using .isel(t=0) threshold : a", "+ ']') plt.ylabel('y [' + lUnits + ']') if colbar:", "= data.y u = data.u v = data.v if units", "variables=None, units=None, fig=None): \"\"\" showf(data, var, units) Arguments: data :", "default is None (no data clipping) contourLevels : number of", "dataset_to_array(data) if units is not None: lUnits = units[0] #", "= plt.get_cmap(\"Blues\"), levels=levels) if colbar: cbar = plt.colorbar(c, orientation=colbar_orient) cbar.set_label(r'$\\left|", "= np.sqrt(U**2 + V**2) Q = ax.quiver(X[::3,::3], Y[::3,::3], U[::3,::3], V[::3,::3],", "lUnits = units[0] # ['m' 'm' 'mm/s' 'mm/s'] # velUnits", "quiver plot of a 'data' xarray DataArray object (single frame", "= np.max(S*arrScale),headwidth=2) ax.set_xlabel('x (' + lUnits + ')') ax.set_ylabel('y ('", "= ax.quiver(X[::3,::3], Y[::3,::3], U[::3,::3], V[::3,::3], M[::3,::3], units='inches', scale=arrowscale) cb =", "p = os.getcwd() os.chdir(savepath) anim.save('im.mp4', writer=mywriter) os.chdir(p) else: anim.save('im.mp4', writer=mywriter)", "if true then colorbar is on log scale aspectratio -", "xarray PIV type of DataSet arrowscale : [optional] integer, default", "# velUnits = units[2] # tUnits = velUnits.split('/')[1] # make", "animation, default is None Output: if savepath is None, then", "= '', '' lUnits = '' f,ax = plt.subplots() if", "+ (None if units is None else units[0])+']' # ylabel", "var[0]) + ' [' + (None if units is None", "lUnits = '' f,ax = plt.subplots() if threshold is not", "None else var[0]) + ' [' + (None if units", "arrScale = 25.0, threshold = None, nthArr = 1, contourLevels", "U, V = data.u[:,:,0], data.v[:,:,0] # first frame fig, ax", "ax[1].hist(v,bins=np.int(np.sqrt(len(v)*0.5)),density=normed) ax[1].set_xlabel('v ['+units[2]+']') plt.tight_layout() return f, ax def contour_plot(data, threshold", "1 savepath : [optional] path to save the MP4 animation,", "for the data['w'] property. Input: data : xarray PIV DataArray,", "cmap = plt.get_cmap('RdYlBu'), norm=plt.colors.LogNorm()) else: c = ax.contourf(data.x,data.y,data['w'], levels=levels, cmap", "\\, \\right|$ ['+ lUnits +' $\\cdot$ '+ tUnits +'$^{-1}$]') ax.quiver(x[::nthArr],y[::nthArr],", "not None: xlabel += ' ' + units[0] ylabel +=", "None else fig.number) # import pdb; pdb.set_trace() # xlabel =", "ha='center', va='center', transform=ax.transAxes) def update_quiver(num,Q,data,text): U,V = data.u[:,:,num],data.v[:,:,num] M =", "contourLevels, 30) if logscale: c = ax.contourf(x,y,S,alpha=0.8, cmap = plt.get_cmap(\"Blues\"),", "= plt.subplots(2) ax[0].hist(u,bins=np.int(np.sqrt(len(u))*0.5),density=normed) ax[0].set_xlabel('u ['+units[2]+']') ax[1] = plt.subplot2grid((2,1),(1,0)) ax[1].hist(v,bins=np.int(np.sqrt(len(v)*0.5)),density=normed) ax[1].set_xlabel('v", "x = data.x y = data.y u = data.u v", "c = ax.contourf(x,y,S,alpha=0.8, cmap = plt.get_cmap(\"Blues\"), levels = levels, norm", "units[1] fig = plt.figure(None if fig is None else fig.number)", "colbar : boolean (default is True) show/hide colorbar logscale :", "not None: data['u'] = xr.where(data['u']>threshold, threshold, data['u']) data['v'] = xr.where(data['v']>threshold,", "f,ax = plt.subplots(2) ax[0].hist(u,bins=np.int(np.sqrt(len(u))*0.5),density=normed) ax[0].set_xlabel('u ['+units[2]+']') ax[1] = plt.subplot2grid((2,1),(1,0)) ax[1].hist(v,bins=np.int(np.sqrt(len(v)*0.5)),density=normed)", "as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation,", "data.v if units is not None: lUnits = units[0] #", "None: lUnits = units[0] # ['m' 'm' 'mm/s' 'mm/s'] velUnits", "frames in the Dataset selected by default using .isel(t=0) threshold", "fargs=(Q,data,text), frames = len(data.t), blit=False) mywriter = FFMpegWriter() if savepath:", "+'$^{-1}$]') ax.quiver(x[::nthArr],y[::nthArr], u[::nthArr,::nthArr],v[::nthArr,::nthArr],units='width', scale = np.max(S*arrScale),headwidth=2) ax.set_xlabel('x (' + lUnits", "\"\"\" showf(data, var, units) Arguments: data : xarray.DataSet that contains", "or 'vertical' orientation of the colorbar (if colbar is True)", "fig, ax = plt.subplots() # open a new figure else:", "ylabel = ' ' else: xlabel = variables[0] ylabel =", "else fig.number) # import pdb; pdb.set_trace() # xlabel = (None", "data.attrs['units'] f,ax = plt.subplots(2) ax[0].hist(u,bins=np.int(np.sqrt(len(u))*0.5),density=normed) ax[0].set_xlabel('u ['+units[2]+']') ax[1] = plt.subplot2grid((2,1),(1,0))", "contourLevels : number of contour levels, default is None colbar", "= 'vertical', units = None): \"\"\" Generates a quiver plot", "None: levels = np.linspace(0, np.max(S.flatten()), 30) # default contour levels", "= np.linspace(-contourLevels, contourLevels, 30) if logscale: c = ax.contourf(data.x,data.y,np.abs(data['w']), levels=levels,", "' ' + units[0] ylabel += ' ' + units[1]", "(None if var is None else var[0]) + ' ['", "<filename>pivpy/graphics.py<gh_stars>1-10 # -*- coding: utf-8 -*- \"\"\" Various plots \"\"\"", "writer=mywriter) def dataset_to_array(data,N=0): \"\"\" converts xarray Dataset to array \"\"\"", "contourLevels = None, colbar = True, logscale = False, aspectration='equal',", "dataset_to_array(data,N=0): \"\"\" converts xarray Dataset to array \"\"\" if 't'", "open a new figure else: ax = plt.gca() if contourLevels", "False, aspectratio='equal', colbar_orient = 'vertical', units = None): \"\"\" Generates", "savepath is an existing path, a file named im.mp4 is", "threshold value, default is None (no data clipping) contourLevels :", "default) create in linear/log scale aspectration : string, 'equal' is", "'m' 'mm/s' 'mm/s'] velUnits = units[2] tUnits = velUnits.split('/')[1] #", "n) \"\"\" data = dataset_to_array(data) x = data.x y =", "ax.set_xlabel('x (' + lUnits + ')') ax.set_ylabel('y (' + lUnits", ": xarray PIV DataArray, converted automatically using .isel(t=0) threshold :", "None: xlabel += ' ' + units[0] ylabel += '", "c = ax.contourf(x,y,S,alpha=0.8, cmap = plt.get_cmap(\"Blues\"), levels=levels) if colbar: cbar", "= plt.get_cmap('RdYlBu')) plt.xlabel('x [' + lUnits + ']') plt.ylabel('y ['", "False to present normalized histogram \"\"\" u = np.asarray(data.u).flatten() v", "xarray DataSet with ['u','v'] attrs['units'] normed : (optional) default is", "only an image display of the animation if savepath is", "attrs['units'] normed : (optional) default is False to present normalized", "None: xlabel = ' ' ylabel = ' ' else:", "matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation, FFMpegWriter import xarray", "is True) Outputs: none Usage: graphics.quiver(data, arrScale = 0.2, threshold", "cbar = plt.colorbar(c) cbar.set_label(r'$\\omega$ [s$^{-1}$]') ax.set_aspect(aspectration) return f,ax def showf(data,", "f,ax def showf(data, variables=None, units=None, fig=None): \"\"\" showf(data, var, units)", "make it 's' or 'dt' else: # lUnits, velUnits =", "' ylabel = ' ' else: xlabel = variables[0] ylabel", "threshold will be set equal to threshold arrScale - use", "contour levels, default is None colbar : boolean (default is", "colbar is True) Outputs: none Usage: graphics.quiver(data, arrScale = 0.2,", "+ lUnits + ']') plt.ylabel('y [' + lUnits + ']')", "= variables[0] ylabel = variables[1] if units is not None:", "os.getcwd() os.chdir(savepath) anim.save('im.mp4', writer=mywriter) os.chdir(p) else: anim.save('im.mp4', writer=mywriter) def dataset_to_array(data,N=0):", "normed : (optional) default is False to present normalized histogram", "- 'horizontal' or 'vertical' orientation of the colorbar (if colbar", "is None: xlabel = ' ' ylabel = ' '", "savepath=None): \"\"\" animates the quiver plot for the dataset (multiple", "pdb.set_trace() # xlabel = (None if var is None else", "nth arrow from the array contourLevels - use to specify", "if units is None else units[0])+']' # ylabel = (None", "coding: utf-8 -*- \"\"\" Various plots \"\"\" import numpy as", "data['v']) S = np.array(np.sqrt(u**2 + v**2)) fig = plt.get_fignums() if", "the quiver plot for the dataset (multiple frames) Input: data", "converts xarray Dataset to array \"\"\" if 't' in data.dims:", "matplotlib.animation import FuncAnimation, FFMpegWriter import xarray as xr import os", "scale=arrowscale) cb = plt.colorbar(Q) units = data.attrs['units'] cb.ax.set_ylabel('velocity (' +", "creates a contour map for the data['w'] property. Input: data", "\"\"\" u = np.asarray(data.u).flatten() v = np.asarray(data.v).flatten() units = data.attrs['units']", "\"\"\" # fig = plt.figure(None if fig is None else", "S else: levels = np.linspace(0, contourLevels, 30) if logscale: c", "value (abs) of contour plots colbar - True/False wether to", "ax.contourf(x,y,S,alpha=0.8, cmap = plt.get_cmap(\"Blues\"), levels=levels) if colbar: cbar = plt.colorbar(c,", "default is None Output: if savepath is None, then only", "np.sqrt(U[::3,::3]**2 + V[::3,::3]**2) Q.set_UVC(U,V,M) text.set_text(str(num+1)+'/'+str(len(data.t))) return Q anim = FuncAnimation(fig,", "scale = np.max(S*arrScale),headwidth=2) ax.set_xlabel('x (' + lUnits + ')') ax.set_ylabel('y", "ax.contourf(data.x,data.y,data['w'], levels=levels, cmap = plt.get_cmap('RdYlBu')) plt.xlabel('x [' + lUnits +", "lUnits, velUnits, tUnits = '', '', '' if threshold is", "plt from matplotlib.animation import FuncAnimation, FFMpegWriter import xarray as xr", "to change arrow scales nthArr - use to plot only", ": boolean (True is default) create in linear/log scale aspectration", "\"\"\" Various plots \"\"\" import numpy as np import matplotlib.pyplot", "None, colbar = True, logscale = False, aspectratio='equal', colbar_orient =", "histogram of the velocity data. Input: data : xarray DataSet", "then only an image display of the animation if savepath", "ax = plt.subplots(1,1) M = np.sqrt(U**2 + V**2) Q =", "or 'dt' else: # lUnits, velUnits = '', '' lUnits", "plot only every nth arrow from the array contourLevels -", "= data.attrs['units'] f,ax = plt.subplots(2) ax[0].hist(u,bins=np.int(np.sqrt(len(u))*0.5),density=normed) ax[0].set_xlabel('u ['+units[2]+']') ax[1] =", "plt.xlabel('x [' + lUnits + ']') plt.ylabel('y [' + lUnits", "['m' 'm' 'mm/s' 'mm/s'] # velUnits = units[2] # tUnits", "\"\"\" data = dataset_to_array(data) x = data.x y = data.y", "fig.number) # import pdb; pdb.set_trace() # xlabel = (None if", "plt.gca() if contourLevels is None: levels = np.linspace(0, np.max(S.flatten()), 30)", "colbar: cbar = plt.colorbar(c) cbar.set_label(r'$\\omega$ [s$^{-1}$]') ax.set_aspect(aspectration) return f,ax def", "in data['t']: d = data.isel(t=t) plt.quiver(d['x'],d['y'],d['u'],d['v'],d['u']**2 + d['v']**2) plt.xlabel(xlabel) plt.ylabel(ylabel)", "' ' + units[1] fig = plt.figure(None if fig is", "ylabel += ' ' + units[1] fig = plt.figure(None if", "PIV dataset, creates a contour map for the data['w'] property.", "threshold, data['u']) data['v'] = xr.where(data['v']>threshold, threshold, data['v']) S = np.array(np.sqrt(u**2", "True) show/hide colorbar logscale : boolean (True is default) create", "# lUnits, velUnits = '', '' lUnits = '' f,ax", "Outputs: none Usage: graphics.quiver(data, arrScale = 0.2, threshold = Inf,", "else fig.number) for t in data['t']: d = data.isel(t=t) plt.quiver(d['x'],d['y'],d['u'],d['v'],d['u']**2", "= plt.gca() if contourLevels is None: levels = np.linspace(0, np.max(S.flatten()),", "is on log scale aspectratio - set auto or equal", "= np.sqrt(U[::3,::3]**2 + V[::3,::3]**2) Q.set_UVC(U,V,M) text.set_text(str(num+1)+'/'+str(len(data.t))) return Q anim =", "ax.set_aspect(aspectratio) return fig,ax def histogram(data, normed = False): \"\"\" this", "levels = np.linspace(0, contourLevels, 30) if logscale: c = ax.contourf(x,y,S,alpha=0.8,", "data : xarray PIV DataArray, converted automatically using .isel(t=0) threshold", "'s' or 'dt' else: # lUnits, velUnits = '', ''", "def showf(data, variables=None, units=None, fig=None): \"\"\" showf(data, var, units) Arguments:", "Output: if savepath is None, then only an image display", "- True/False wether to generate a colorbar or not logscale", "import xarray as xr import os def quiver(data, arrScale =", "the Dataset selected by default using .isel(t=0) threshold - values", "'equal' is the default \"\"\" data = dataset_to_array(data) if units", "levels, default is None colbar : boolean (default is True)", "Generates a quiver plot of a 'data' xarray DataArray object", "+ V**2) Q = ax.quiver(X[::3,::3], Y[::3,::3], U[::3,::3], V[::3,::3], M[::3,::3], units='inches',", "')') text = ax.text(0.2,1.05, '1/'+str(len(data.t)), ha='center', va='center', transform=ax.transAxes) def update_quiver(num,Q,data,text):", "contourLevels, 30) if logscale: c = ax.contourf(data.x,data.y,np.abs(data['w']), levels=levels, cmap =", "(single frame from a dataset) Inputs: data - xarray DataArray", "the type defined in pivpy, one of the frames in", "is None else fig.number) # import pdb; pdb.set_trace() # xlabel", "using first frame, supply data.isel(t=N)') data = data.isel(t=N) return data", "Usage: graphics.quiver(data, arrScale = 0.2, threshold = Inf, n) \"\"\"", "velocity data. Input: data : xarray DataSet with ['u','v'] attrs['units']", "threshold = None, nthArr = 1, contourLevels = None, colbar", "None Output: if savepath is None, then only an image", ": xarray.DataSet that contains dimensions of t,x,y and variables u,v", "if colbar: cbar = plt.colorbar(c) cbar.set_label(r'$\\omega$ [s$^{-1}$]') ax.set_aspect(aspectration) return f,ax", "cb.ax.set_ylabel('velocity (' + units[2] + ')') text = ax.text(0.2,1.05, '1/'+str(len(data.t)),", "plots \"\"\" import numpy as np import matplotlib.pyplot as plt", "scale aspectratio - set auto or equal for the plot's", "frame fig, ax = plt.subplots(1,1) M = np.sqrt(U**2 + V**2)", "colbar = True, logscale = False, aspectration='equal', units=None): \"\"\" contourf", "transform=ax.transAxes) def update_quiver(num,Q,data,text): U,V = data.u[:,:,num],data.v[:,:,num] M = np.sqrt(U[::3,::3]**2 +", "is None else var[0]) + ' [' + (None if", "np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation, FFMpegWriter", "'1/'+str(len(data.t)), ha='center', va='center', transform=ax.transAxes) def update_quiver(num,Q,data,text): U,V = data.u[:,:,num],data.v[:,:,num] M", "'data' xarray DataArray object (single frame from a dataset) Inputs:", "+ v**2)) fig = plt.get_fignums() if len(fig) == 0: #", "units[1])+']' data = data.piv.vec2scal(property=property) contour_plot(data) def animate(data, arrowscale=1, savepath=None): \"\"\"", "len(data.t), blit=False) mywriter = FFMpegWriter() if savepath: p = os.getcwd()", "= True, logscale = False, aspectration='equal', units=None): \"\"\" contourf ajusted", "logscale : boolean (True is default) create in linear/log scale", "variables[1] if units is not None: xlabel += ' '", "ax.contourf(x,y,S,alpha=0.8, cmap = plt.get_cmap(\"Blues\"), levels = levels, norm = plt.colors.LogNorm())", "= np.array(np.sqrt(u**2 + v**2)) fig = plt.get_fignums() if len(fig) ==", "variable w (scalar) \"\"\" # fig = plt.figure(None if fig", "velUnits.split('/')[1] # make it 's' or 'dt' else: # lUnits,", "and maybe w (scalar) \"\"\" if variables is None: xlabel", "file named im.mp4 is saved \"\"\" X, Y = data.x,", ": xarray PIV type of DataSet arrowscale : [optional] integer,", "lUnits, velUnits = '', '' lUnits = '' f,ax =", "= ' ' ylabel = ' ' else: xlabel =", "\"\"\" if variables is None: xlabel = ' ' ylabel", "= data.u v = data.v if units is not None:", "# if no figure is open fig, ax = plt.subplots()", "Input: data : xarray DataSet with ['u','v'] attrs['units'] normed :", "V[::3,::3], M[::3,::3], units='inches', scale=arrowscale) cb = plt.colorbar(Q) units = data.attrs['units']", "V**2) Q = ax.quiver(X[::3,::3], Y[::3,::3], U[::3,::3], V[::3,::3], M[::3,::3], units='inches', scale=arrowscale)", "= False, aspectratio='equal', colbar_orient = 'vertical', units = None): \"\"\"", "plt.xlabel(xlabel) plt.ylabel(ylabel) plt.draw() plt.pause(0.1) plt.show() def showscal(data, property='ken'): \"\"\" showf(data,", "= (None if var is None else var[0]) + '", "data.v[:,:,0] # first frame fig, ax = plt.subplots(1,1) M =", "if no figure is open fig, ax = plt.subplots() #", "= np.asarray(data.v).flatten() units = data.attrs['units'] f,ax = plt.subplots(2) ax[0].hist(u,bins=np.int(np.sqrt(len(u))*0.5),density=normed) ax[0].set_xlabel('u", "Dataset selected by default using .isel(t=0) threshold - values above", "to specify the maximum value (abs) of contour plots colbar", "the default \"\"\" data = dataset_to_array(data) if units is not", "colorbar (if colbar is True) Outputs: none Usage: graphics.quiver(data, arrScale", "data['t']: d = data.isel(t=t) plt.quiver(d['x'],d['y'],d['u'],d['v'],d['u']**2 + d['v']**2) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.draw()", "else: ax = plt.gca() if contourLevels is None: levels =", "xarray.DataSet that contains dimensions of t,x,y and a variable w", "'dt' else: # lUnits, velUnits = '', '' lUnits =", "the maximum value (abs) of contour plots colbar - True/False", "= FFMpegWriter() if savepath: p = os.getcwd() os.chdir(savepath) anim.save('im.mp4', writer=mywriter)", "(optional) default is False to present normalized histogram \"\"\" u", "np.array(np.sqrt(u**2 + v**2)) fig = plt.get_fignums() if len(fig) == 0:", "\"\"\" data = dataset_to_array(data) if units is not None: lUnits", "tUnits = velUnits.split('/')[1] # make it 's' or 'dt' else:", "is not None: data['u'] = xr.where(data['u']>threshold, threshold, data['u']) data['v'] =", "lUnits + ']') if colbar: cbar = plt.colorbar(c) cbar.set_label(r'$\\omega$ [s$^{-1}$]')", "in pivpy, one of the frames in the Dataset selected", "os def quiver(data, arrScale = 25.0, threshold = None, nthArr", "xlabel = (None if var is None else var[0]) +", "of the type defined in pivpy, one of the frames", "default is 1 savepath : [optional] path to save the", "data.y U, V = data.u[:,:,0], data.v[:,:,0] # first frame fig,", "a threshold value, default is None (no data clipping) contourLevels", "plt.get_fignums() if len(fig) == 0: # if no figure is", "+ ']') if colbar: cbar = plt.colorbar(c) cbar.set_label(r'$\\omega$ [s$^{-1}$]') ax.set_aspect(aspectration)", "units[0] # ['m' 'm' 'mm/s' 'mm/s'] velUnits = units[2] tUnits", "d['v']**2) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.draw() plt.pause(0.1) plt.show() def showscal(data, property='ken'): \"\"\"", "V[::3,::3]**2) Q.set_UVC(U,V,M) text.set_text(str(num+1)+'/'+str(len(data.t))) return Q anim = FuncAnimation(fig, update_quiver, fargs=(Q,data,text),", "FuncAnimation(fig, update_quiver, fargs=(Q,data,text), frames = len(data.t), blit=False) mywriter = FFMpegWriter()", "var, units) Arguments: data : xarray.DataSet that contains dimensions of", "None (no data clipping) contourLevels : number of contour levels,", "tUnits = '', '', '' if threshold is not None:", "w (scalar) \"\"\" if variables is None: xlabel = '", "colbar_orient - 'horizontal' or 'vertical' orientation of the colorbar (if", "' [' + (None if units is None else units[1])+']'", "a dataset) Inputs: data - xarray DataArray of the type", "threshold is not None: data['u'] = xr.where(data['u']>threshold, threshold, data['u']) data['v']", "contourLevels is None: levels = np.linspace(0, np.max(S.flatten()), 30) # default", ": string, 'equal' is the default \"\"\" data = dataset_to_array(data)", "Y[::3,::3], U[::3,::3], V[::3,::3], M[::3,::3], units='inches', scale=arrowscale) cb = plt.colorbar(Q) units", "\\right|$ ['+ lUnits +' $\\cdot$ '+ tUnits +'$^{-1}$]') ax.quiver(x[::nthArr],y[::nthArr], u[::nthArr,::nthArr],v[::nthArr,::nthArr],units='width',", "' [' + (None if units is None else units[0])+']'", "' + units[1] fig = plt.figure(None if fig is None", "if logscale: c = ax.contourf(data.x,data.y,np.abs(data['w']), levels=levels, cmap = plt.get_cmap('RdYlBu'), norm=plt.colors.LogNorm())", "a new figure else: ax = plt.gca() if contourLevels is", "plot a normalized histogram of the velocity data. Input: data", "\"\"\" contourf ajusted for the xarray PIV dataset, creates a", "c = ax.contourf(data.x,data.y,np.abs(data['w']), levels=levels, cmap = plt.get_cmap('RdYlBu'), norm=plt.colors.LogNorm()) else: c", "set equal to threshold arrScale - use to change arrow", ": xarray DataSet with ['u','v'] attrs['units'] normed : (optional) default", "True/False wether to generate a colorbar or not logscale -", "figure else: ax = plt.gca() if contourLevels is None: levels", "for the xarray PIV dataset, creates a contour map for", "using .isel(t=0) threshold - values above the threshold will be", "= levels, norm = plt.colors.LogNorm()) else: c = ax.contourf(x,y,S,alpha=0.8, cmap", "in linear/log scale aspectration : string, 'equal' is the default", "[' + lUnits + ']') plt.ylabel('y [' + lUnits +", "'mm/s'] velUnits = units[2] tUnits = velUnits.split('/')[1] # make it", "arrScale = 0.2, threshold = Inf, n) \"\"\" data =", "'' f,ax = plt.subplots() if threshold is not None: data['w']", "# fig = plt.figure(None if fig is None else fig.number)", "animation if savepath is an existing path, a file named", "os.chdir(p) else: anim.save('im.mp4', writer=mywriter) def dataset_to_array(data,N=0): \"\"\" converts xarray Dataset", "+ lUnits + ')') ax.set_aspect(aspectratio) return fig,ax def histogram(data, normed", "fig.number) for t in data['t']: d = data.isel(t=t) plt.quiver(d['x'],d['y'],d['u'],d['v'],d['u']**2 +", "= '', '', '' if threshold is not None: data['u']", "'vertical', units = None): \"\"\" Generates a quiver plot of", "None: levels = np.linspace(-m, m, 30) else: levels = np.linspace(-contourLevels,", "ax.set_ylabel('y (' + lUnits + ')') ax.set_aspect(aspectratio) return fig,ax def", "plt.draw() plt.pause(0.1) plt.show() def showscal(data, property='ken'): \"\"\" showf(data, var, units)", "apearence colbar_orient - 'horizontal' or 'vertical' orientation of the colorbar", "to threshold arrScale - use to change arrow scales nthArr", "graphics.quiver(data, arrScale = 0.2, threshold = Inf, n) \"\"\" data", "threshold, data['v']) S = np.array(np.sqrt(u**2 + v**2)) fig = plt.get_fignums()", ".isel(t=0) threshold : a threshold value, default is None (no", "text = ax.text(0.2,1.05, '1/'+str(len(data.t)), ha='center', va='center', transform=ax.transAxes) def update_quiver(num,Q,data,text): U,V", "dataset) Inputs: data - xarray DataArray of the type defined", "is not None: xlabel += ' ' + units[0] ylabel", "nthArr - use to plot only every nth arrow from", "data : xarray.DataSet that contains dimensions of t,x,y and variables", "colorbar or not logscale - if true then colorbar is", "in the Dataset selected by default using .isel(t=0) threshold -", "ax[0].hist(u,bins=np.int(np.sqrt(len(u))*0.5),density=normed) ax[0].set_xlabel('u ['+units[2]+']') ax[1] = plt.subplot2grid((2,1),(1,0)) ax[1].hist(v,bins=np.int(np.sqrt(len(v)*0.5)),density=normed) ax[1].set_xlabel('v ['+units[2]+']') plt.tight_layout()", "units = None): \"\"\" Generates a quiver plot of a", "will plot a normalized histogram of the velocity data. Input:", "levels=levels) if colbar: cbar = plt.colorbar(c, orientation=colbar_orient) cbar.set_label(r'$\\left| \\, V", "showf(data, variables=None, units=None, fig=None): \"\"\" showf(data, var, units) Arguments: data", "= data.attrs['units'] cb.ax.set_ylabel('velocity (' + units[2] + ')') text =", "va='center', transform=ax.transAxes) def update_quiver(num,Q,data,text): U,V = data.u[:,:,num],data.v[:,:,num] M = np.sqrt(U[::3,::3]**2", "showscal(data, property='ken'): \"\"\" showf(data, var, units) Arguments: data : xarray.DataSet", "arrScale - use to change arrow scales nthArr - use", ".isel(t=0) threshold - values above the threshold will be set", "plot's apearence colbar_orient - 'horizontal' or 'vertical' orientation of the", "default \"\"\" data = dataset_to_array(data) if units is not None:", "else units[1])+']' data = data.piv.vec2scal(property=property) contour_plot(data) def animate(data, arrowscale=1, savepath=None):", "t,x,y and variables u,v and maybe w (scalar) \"\"\" if", "is None: levels = np.linspace(0, np.max(S.flatten()), 30) # default contour", "normalized histogram \"\"\" u = np.asarray(data.u).flatten() v = np.asarray(data.v).flatten() units", "string, 'equal' is the default \"\"\" data = dataset_to_array(data) if", "d = data.isel(t=t) plt.quiver(d['x'],d['y'],d['u'],d['v'],d['u']**2 + d['v']**2) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.draw() plt.pause(0.1)", "= plt.subplots() # open a new figure else: ax =", "= data.u[:,:,num],data.v[:,:,num] M = np.sqrt(U[::3,::3]**2 + V[::3,::3]**2) Q.set_UVC(U,V,M) text.set_text(str(num+1)+'/'+str(len(data.t))) return", "as plt from matplotlib.animation import FuncAnimation, FFMpegWriter import xarray as", "none Usage: graphics.quiver(data, arrScale = 0.2, threshold = Inf, n)", "\"\"\" import numpy as np import matplotlib.pyplot as plt from", "= 1, contourLevels = None, colbar = True, logscale =", "data.isel(t=t) plt.quiver(d['x'],d['y'],d['u'],d['v'],d['u']**2 + d['v']**2) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.draw() plt.pause(0.1) plt.show() def", "logscale: c = ax.contourf(x,y,S,alpha=0.8, cmap = plt.get_cmap(\"Blues\"), levels = levels,", "update_quiver, fargs=(Q,data,text), frames = len(data.t), blit=False) mywriter = FFMpegWriter() if", "function for a single frame, using first frame, supply data.isel(t=N)')", "is not None: lUnits = units[0] # ['m' 'm' 'mm/s'", "(' + lUnits + ')') ax.set_aspect(aspectratio) return fig,ax def histogram(data,", "X, Y = data.x, data.y U, V = data.u[:,:,0], data.v[:,:,0]", "units[2] + ')') text = ax.text(0.2,1.05, '1/'+str(len(data.t)), ha='center', va='center', transform=ax.transAxes)", "is None colbar : boolean (default is True) show/hide colorbar", "from the array contourLevels - use to specify the maximum", "utf-8 -*- \"\"\" Various plots \"\"\" import numpy as np", "update_quiver(num,Q,data,text): U,V = data.u[:,:,num],data.v[:,:,num] M = np.sqrt(U[::3,::3]**2 + V[::3,::3]**2) Q.set_UVC(U,V,M)", "-*- \"\"\" Various plots \"\"\" import numpy as np import", "of S else: levels = np.linspace(0, contourLevels, 30) if logscale:", "a colorbar or not logscale - if true then colorbar", "frame, using first frame, supply data.isel(t=N)') data = data.isel(t=N) return", "units is None else units[0])+']' # ylabel = (None if", "as xr import os def quiver(data, arrScale = 25.0, threshold", "change arrow scales nthArr - use to plot only every", "property='ken'): \"\"\" showf(data, var, units) Arguments: data : xarray.DataSet that", "will be set equal to threshold arrScale - use to", "plt.subplots() # open a new figure else: ax = plt.gca()", "= units[2] tUnits = velUnits.split('/')[1] # make it 's' or", "= False): \"\"\" this function will plot a normalized histogram", "\"\"\" Generates a quiver plot of a 'data' xarray DataArray", "data['w']) m = np.amax(abs(data['w'])) if contourLevels == None: levels =", "30) if logscale: c = ax.contourf(x,y,S,alpha=0.8, cmap = plt.get_cmap(\"Blues\"), levels", "animates the quiver plot for the dataset (multiple frames) Input:", "+ lUnits + ']') if colbar: cbar = plt.colorbar(c) cbar.set_label(r'$\\omega$", "the velocity data. Input: data : xarray DataSet with ['u','v']", "if threshold is not None: data['u'] = xr.where(data['u']>threshold, threshold, data['u'])", "units[0] # ['m' 'm' 'mm/s' 'mm/s'] # velUnits = units[2]", "default is None colbar : boolean (default is True) show/hide", "= data.x, data.y U, V = data.u[:,:,0], data.v[:,:,0] # first", "v = np.asarray(data.v).flatten() units = data.attrs['units'] f,ax = plt.subplots(2) ax[0].hist(u,bins=np.int(np.sqrt(len(u))*0.5),density=normed)", "# ['m' 'm' 'mm/s' 'mm/s'] # velUnits = units[2] #", ": [optional] integer, default is 1 savepath : [optional] path", "data = dataset_to_array(data) if units is not None: lUnits =", "histogram(data, normed = False): \"\"\" this function will plot a", "None colbar : boolean (default is True) show/hide colorbar logscale", "data.attrs['units'] cb.ax.set_ylabel('velocity (' + units[2] + ')') text = ax.text(0.2,1.05,", "= plt.colorbar(Q) units = data.attrs['units'] cb.ax.set_ylabel('velocity (' + units[2] +", "to plot only every nth arrow from the array contourLevels", "+ lUnits + ')') ax.set_ylabel('y (' + lUnits + ')')", "value, default is None (no data clipping) contourLevels : number", "create in linear/log scale aspectration : string, 'equal' is the", "threshold is not None: data['w'] = xr.where(data['w']>threshold, threshold, data['w']) m", "= plt.get_cmap('RdYlBu'), norm=plt.colors.LogNorm()) else: c = ax.contourf(data.x,data.y,data['w'], levels=levels, cmap =", "units is None else units[1])+']' data = data.piv.vec2scal(property=property) contour_plot(data) def", "' ' ylabel = ' ' else: xlabel = variables[0]", "logscale: c = ax.contourf(data.x,data.y,np.abs(data['w']), levels=levels, cmap = plt.get_cmap('RdYlBu'), norm=plt.colors.LogNorm()) else:", "DataSet arrowscale : [optional] integer, default is 1 savepath :", "from a dataset) Inputs: data - xarray DataArray of the", "if 't' in data.dims: print('Warning: function for a single frame,", "\"\"\" animates the quiver plot for the dataset (multiple frames)", "= plt.figure(None if fig is None else fig.number) # import", "= 25.0, threshold = None, nthArr = 1, contourLevels =", "numpy as np import matplotlib.pyplot as plt from matplotlib.animation import", "None else units[0])+']' # ylabel = (None if var is", "V = data.u[:,:,0], data.v[:,:,0] # first frame fig, ax =", "one of the frames in the Dataset selected by default", "[optional] path to save the MP4 animation, default is None", "text.set_text(str(num+1)+'/'+str(len(data.t))) return Q anim = FuncAnimation(fig, update_quiver, fargs=(Q,data,text), frames =", "use to plot only every nth arrow from the array", "scales nthArr - use to plot only every nth arrow", "u[::nthArr,::nthArr],v[::nthArr,::nthArr],units='width', scale = np.max(S*arrScale),headwidth=2) ax.set_xlabel('x (' + lUnits + ')')", "levels up to max of S else: levels = np.linspace(0,", "dataset (multiple frames) Input: data : xarray PIV type of", "frames) Input: data : xarray PIV type of DataSet arrowscale", "= plt.subplots() if threshold is not None: data['w'] = xr.where(data['w']>threshold,", "the plot's apearence colbar_orient - 'horizontal' or 'vertical' orientation of", "is None (no data clipping) contourLevels : number of contour", "1, contourLevels = None, colbar = True, logscale = False,", "(' + lUnits + ')') ax.set_ylabel('y (' + lUnits +", "= ax.contourf(x,y,S,alpha=0.8, cmap = plt.get_cmap(\"Blues\"), levels = levels, norm =", "not None: data['w'] = xr.where(data['w']>threshold, threshold, data['w']) m = np.amax(abs(data['w']))", "is None else units[0])+']' # ylabel = (None if var", "the colorbar (if colbar is True) Outputs: none Usage: graphics.quiver(data,", "return Q anim = FuncAnimation(fig, update_quiver, fargs=(Q,data,text), frames = len(data.t),", "anim.save('im.mp4', writer=mywriter) def dataset_to_array(data,N=0): \"\"\" converts xarray Dataset to array", "colorbar is on log scale aspectratio - set auto or", "None: lUnits = units[0] # ['m' 'm' 'mm/s' 'mm/s'] #", "fig, ax = plt.subplots(1,1) M = np.sqrt(U**2 + V**2) Q", "xarray as xr import os def quiver(data, arrScale = 25.0,", "[' + (None if units is None else units[0])+']' #", "var is None else var[1]) + ' [' + (None", "existing path, a file named im.mp4 is saved \"\"\" X,", "w (scalar) \"\"\" # fig = plt.figure(None if fig is", "(None if units is None else units[0])+']' # ylabel =", "array \"\"\" if 't' in data.dims: print('Warning: function for a", "is default) create in linear/log scale aspectration : string, 'equal'", "is None, then only an image display of the animation", "property. Input: data : xarray PIV DataArray, converted automatically using", "saved \"\"\" X, Y = data.x, data.y U, V =", "\"\"\" if 't' in data.dims: print('Warning: function for a single", "np.linspace(0, contourLevels, 30) if logscale: c = ax.contourf(x,y,S,alpha=0.8, cmap =", "fig is None else fig.number) # import pdb; pdb.set_trace() #", "norm = plt.colors.LogNorm()) else: c = ax.contourf(x,y,S,alpha=0.8, cmap = plt.get_cmap(\"Blues\"),", "var is None else var[0]) + ' [' + (None", "xarray Dataset to array \"\"\" if 't' in data.dims: print('Warning:", "data clipping) contourLevels : number of contour levels, default is", "= ax.text(0.2,1.05, '1/'+str(len(data.t)), ha='center', va='center', transform=ax.transAxes) def update_quiver(num,Q,data,text): U,V =", "default contour levels up to max of S else: levels", "'dt' else: lUnits, velUnits, tUnits = '', '', '' if", "m = np.amax(abs(data['w'])) if contourLevels == None: levels = np.linspace(-m,", "ax.quiver(X[::3,::3], Y[::3,::3], U[::3,::3], V[::3,::3], M[::3,::3], units='inches', scale=arrowscale) cb = plt.colorbar(Q)", "= units[0] # ['m' 'm' 'mm/s' 'mm/s'] # velUnits =", "plots colbar - True/False wether to generate a colorbar or", "+ ')') ax.set_ylabel('y (' + lUnits + ')') ax.set_aspect(aspectratio) return", "- values above the threshold will be set equal to", "= plt.figure(None if fig is None else fig.number) for t", "lUnits = units[0] # ['m' 'm' 'mm/s' 'mm/s'] velUnits =", "== 0: # if no figure is open fig, ax", "function will plot a normalized histogram of the velocity data.", "then colorbar is on log scale aspectratio - set auto", "+= ' ' + units[1] fig = plt.figure(None if fig", "anim.save('im.mp4', writer=mywriter) os.chdir(p) else: anim.save('im.mp4', writer=mywriter) def dataset_to_array(data,N=0): \"\"\" converts", "def histogram(data, normed = False): \"\"\" this function will plot", "above the threshold will be set equal to threshold arrScale", "- xarray DataArray of the type defined in pivpy, one", "plt.subplots(2) ax[0].hist(u,bins=np.int(np.sqrt(len(u))*0.5),density=normed) ax[0].set_xlabel('u ['+units[2]+']') ax[1] = plt.subplot2grid((2,1),(1,0)) ax[1].hist(v,bins=np.int(np.sqrt(len(v)*0.5)),density=normed) ax[1].set_xlabel('v ['+units[2]+']')", ": boolean (default is True) show/hide colorbar logscale : boolean", "plt.ylabel('y [' + lUnits + ']') if colbar: cbar =", "Input: data : xarray PIV type of DataSet arrowscale :", "data - xarray DataArray of the type defined in pivpy,", "return f,ax def showf(data, variables=None, units=None, fig=None): \"\"\" showf(data, var,", "-*- coding: utf-8 -*- \"\"\" Various plots \"\"\" import numpy", "first frame fig, ax = plt.subplots(1,1) M = np.sqrt(U**2 +", "colbar = True, logscale = False, aspectratio='equal', colbar_orient = 'vertical',", "by default using .isel(t=0) threshold - values above the threshold", "FFMpegWriter import xarray as xr import os def quiver(data, arrScale", "Q anim = FuncAnimation(fig, update_quiver, fargs=(Q,data,text), frames = len(data.t), blit=False)", ": xarray.DataSet that contains dimensions of t,x,y and a variable", "np.asarray(data.v).flatten() units = data.attrs['units'] f,ax = plt.subplots(2) ax[0].hist(u,bins=np.int(np.sqrt(len(u))*0.5),density=normed) ax[0].set_xlabel('u ['+units[2]+']')", "= np.asarray(data.u).flatten() v = np.asarray(data.v).flatten() units = data.attrs['units'] f,ax =", "ax.contourf(data.x,data.y,np.abs(data['w']), levels=levels, cmap = plt.get_cmap('RdYlBu'), norm=plt.colors.LogNorm()) else: c = ax.contourf(data.x,data.y,data['w'],", "normalized histogram of the velocity data. Input: data : xarray", "aspectratio - set auto or equal for the plot's apearence", "map for the data['w'] property. Input: data : xarray PIV", "= xr.where(data['u']>threshold, threshold, data['u']) data['v'] = xr.where(data['v']>threshold, threshold, data['v']) S", "if units is None else units[1])+']' data = data.piv.vec2scal(property=property) contour_plot(data)", "defined in pivpy, one of the frames in the Dataset", "+ V[::3,::3]**2) Q.set_UVC(U,V,M) text.set_text(str(num+1)+'/'+str(len(data.t))) return Q anim = FuncAnimation(fig, update_quiver,", "= os.getcwd() os.chdir(savepath) anim.save('im.mp4', writer=mywriter) os.chdir(p) else: anim.save('im.mp4', writer=mywriter) def", "contour plots colbar - True/False wether to generate a colorbar", "u,v and maybe w (scalar) \"\"\" if variables is None:", "for t in data['t']: d = data.isel(t=t) plt.quiver(d['x'],d['y'],d['u'],d['v'],d['u']**2 + d['v']**2)", "None else fig.number) for t in data['t']: d = data.isel(t=t)", "a single frame, using first frame, supply data.isel(t=N)') data =", "FFMpegWriter() if savepath: p = os.getcwd() os.chdir(savepath) anim.save('im.mp4', writer=mywriter) os.chdir(p)", "units[2] tUnits = velUnits.split('/')[1] # make it 's' or 'dt'", ": (optional) default is False to present normalized histogram \"\"\"", "0.2, threshold = Inf, n) \"\"\" data = dataset_to_array(data) x", "plt.figure(None if fig is None else fig.number) # import pdb;", "anim = FuncAnimation(fig, update_quiver, fargs=(Q,data,text), frames = len(data.t), blit=False) mywriter", "if savepath: p = os.getcwd() os.chdir(savepath) anim.save('im.mp4', writer=mywriter) os.chdir(p) else:", "boolean (default is True) show/hide colorbar logscale : boolean (True", "else: anim.save('im.mp4', writer=mywriter) def dataset_to_array(data,N=0): \"\"\" converts xarray Dataset to", "fig = plt.figure(None if fig is None else fig.number) #", "if logscale: c = ax.contourf(x,y,S,alpha=0.8, cmap = plt.get_cmap(\"Blues\"), levels =", "an existing path, a file named im.mp4 is saved \"\"\"", "= len(data.t), blit=False) mywriter = FFMpegWriter() if savepath: p =", "it 's' or 'dt' else: # lUnits, velUnits = '',", "[' + (None if units is None else units[1])+']' data", "False): \"\"\" this function will plot a normalized histogram of", "xr.where(data['w']>threshold, threshold, data['w']) m = np.amax(abs(data['w'])) if contourLevels == None:", "np.linspace(0, np.max(S.flatten()), 30) # default contour levels up to max", ": number of contour levels, default is None colbar :", "logscale - if true then colorbar is on log scale", "== None: levels = np.linspace(-m, m, 30) else: levels =", "= plt.subplots(1,1) M = np.sqrt(U**2 + V**2) Q = ax.quiver(X[::3,::3],", "= units[0] # ['m' 'm' 'mm/s' 'mm/s'] velUnits = units[2]", "xlabel += ' ' + units[0] ylabel += ' '", "plot of a 'data' xarray DataArray object (single frame from", "\\, V \\, \\right|$ ['+ lUnits +' $\\cdot$ '+ tUnits", "= (None if var is None else var[1]) + '", "plt.subplots(1,1) M = np.sqrt(U**2 + V**2) Q = ax.quiver(X[::3,::3], Y[::3,::3],", "data = data.piv.vec2scal(property=property) contour_plot(data) def animate(data, arrowscale=1, savepath=None): \"\"\" animates", "data.u v = data.v if units is not None: lUnits", "t,x,y and a variable w (scalar) \"\"\" # fig =", "DataArray object (single frame from a dataset) Inputs: data -", "writer=mywriter) os.chdir(p) else: anim.save('im.mp4', writer=mywriter) def dataset_to_array(data,N=0): \"\"\" converts xarray", "on log scale aspectratio - set auto or equal for", "cbar.set_label(r'$\\left| \\, V \\, \\right|$ ['+ lUnits +' $\\cdot$ '+", "quiver(data, arrScale = 25.0, threshold = None, nthArr = 1,", "variables u,v and maybe w (scalar) \"\"\" if variables is", "selected by default using .isel(t=0) threshold - values above the", "if savepath is None, then only an image display of", "the array contourLevels - use to specify the maximum value", "max of S else: levels = np.linspace(0, contourLevels, 30) if", "present normalized histogram \"\"\" u = np.asarray(data.u).flatten() v = np.asarray(data.v).flatten()", "= FuncAnimation(fig, update_quiver, fargs=(Q,data,text), frames = len(data.t), blit=False) mywriter =", "PIV type of DataSet arrowscale : [optional] integer, default is", "units[2] # tUnits = velUnits.split('/')[1] # make it 's' or", "return fig,ax def histogram(data, normed = False): \"\"\" this function", "else: xlabel = variables[0] ylabel = variables[1] if units is", "= variables[1] if units is not None: xlabel += '", "linear/log scale aspectration : string, 'equal' is the default \"\"\"", "if units is not None: lUnits = units[0] # ['m'", "up to max of S else: levels = np.linspace(0, contourLevels,", "else: # lUnits, velUnits = '', '' lUnits = ''", "frame from a dataset) Inputs: data - xarray DataArray of", "contour map for the data['w'] property. Input: data : xarray", "or not logscale - if true then colorbar is on", "- if true then colorbar is on log scale aspectratio", "cmap = plt.get_cmap(\"Blues\"), levels = levels, norm = plt.colors.LogNorm()) else:", "DataSet with ['u','v'] attrs['units'] normed : (optional) default is False", "f, ax def contour_plot(data, threshold = None, contourLevels = None,", "\"\"\" converts xarray Dataset to array \"\"\" if 't' in", "is not None: data['w'] = xr.where(data['w']>threshold, threshold, data['w']) m =", "data : xarray PIV type of DataSet arrowscale : [optional]", "dataset, creates a contour map for the data['w'] property. Input:", "dimensions of t,x,y and variables u,v and maybe w (scalar)", "else: c = ax.contourf(x,y,S,alpha=0.8, cmap = plt.get_cmap(\"Blues\"), levels=levels) if colbar:", "= data.u[:,:,0], data.v[:,:,0] # first frame fig, ax = plt.subplots(1,1)", "')') ax.set_aspect(aspectratio) return fig,ax def histogram(data, normed = False): \"\"\"", "# first frame fig, ax = plt.subplots(1,1) M = np.sqrt(U**2", "if colbar: cbar = plt.colorbar(c, orientation=colbar_orient) cbar.set_label(r'$\\left| \\, V \\,", "plt.subplots() if threshold is not None: data['w'] = xr.where(data['w']>threshold, threshold,", "S = np.array(np.sqrt(u**2 + v**2)) fig = plt.get_fignums() if len(fig)", "cb = plt.colorbar(Q) units = data.attrs['units'] cb.ax.set_ylabel('velocity (' + units[2]", "levels = np.linspace(-contourLevels, contourLevels, 30) if logscale: c = ax.contourf(data.x,data.y,np.abs(data['w']),", "is False to present normalized histogram \"\"\" u = np.asarray(data.u).flatten()", "\"\"\" X, Y = data.x, data.y U, V = data.u[:,:,0],", "def quiver(data, arrScale = 25.0, threshold = None, nthArr =", "np.sqrt(U**2 + V**2) Q = ax.quiver(X[::3,::3], Y[::3,::3], U[::3,::3], V[::3,::3], M[::3,::3],", "figure is open fig, ax = plt.subplots() # open a", "true then colorbar is on log scale aspectratio - set", "None else var[1]) + ' [' + (None if units", "else: levels = np.linspace(-contourLevels, contourLevels, 30) if logscale: c =", "is saved \"\"\" X, Y = data.x, data.y U, V", "variables[0] ylabel = variables[1] if units is not None: xlabel", "f,ax = plt.subplots() if threshold is not None: data['w'] =", "(abs) of contour plots colbar - True/False wether to generate", "a contour map for the data['w'] property. Input: data :", "make it 's' or 'dt' else: lUnits, velUnits, tUnits =", "levels=levels, cmap = plt.get_cmap('RdYlBu'), norm=plt.colors.LogNorm()) else: c = ax.contourf(data.x,data.y,data['w'], levels=levels,", "of contour levels, default is None colbar : boolean (default", "= '' f,ax = plt.subplots() if threshold is not None:", "np.amax(abs(data['w'])) if contourLevels == None: levels = np.linspace(-m, m, 30)", "is an existing path, a file named im.mp4 is saved", "is None else var[1]) + ' [' + (None if", "def dataset_to_array(data,N=0): \"\"\" converts xarray Dataset to array \"\"\" if", "of the frames in the Dataset selected by default using", "plt.get_cmap(\"Blues\"), levels = levels, norm = plt.colors.LogNorm()) else: c =", "with ['u','v'] attrs['units'] normed : (optional) default is False to", "the data['w'] property. Input: data : xarray PIV DataArray, converted", "plt.ylabel(ylabel) plt.draw() plt.pause(0.1) plt.show() def showscal(data, property='ken'): \"\"\" showf(data, var,", "use to specify the maximum value (abs) of contour plots", "is None Output: if savepath is None, then only an", "clipping) contourLevels : number of contour levels, default is None", "default is False to present normalized histogram \"\"\" u =", "xarray DataArray of the type defined in pivpy, one of", "show/hide colorbar logscale : boolean (True is default) create in", "dimensions of t,x,y and a variable w (scalar) \"\"\" #", "= ' ' else: xlabel = variables[0] ylabel = variables[1]", "'', '' if threshold is not None: data['u'] = xr.where(data['u']>threshold,", "savepath : [optional] path to save the MP4 animation, default", "var[1]) + ' [' + (None if units is None", "M = np.sqrt(U**2 + V**2) Q = ax.quiver(X[::3,::3], Y[::3,::3], U[::3,::3],", "showf(data, var, units) Arguments: data : xarray.DataSet that contains dimensions", "= data.isel(t=t) plt.quiver(d['x'],d['y'],d['u'],d['v'],d['u']**2 + d['v']**2) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.draw() plt.pause(0.1) plt.show()", "def update_quiver(num,Q,data,text): U,V = data.u[:,:,num],data.v[:,:,num] M = np.sqrt(U[::3,::3]**2 + V[::3,::3]**2)", "threshold, data['w']) m = np.amax(abs(data['w'])) if contourLevels == None: levels", "cbar.set_label(r'$\\omega$ [s$^{-1}$]') ax.set_aspect(aspectration) return f,ax def showf(data, variables=None, units=None, fig=None):", "is True) show/hide colorbar logscale : boolean (True is default)", "25.0, threshold = None, nthArr = 1, contourLevels = None,", "levels, norm = plt.colors.LogNorm()) else: c = ax.contourf(x,y,S,alpha=0.8, cmap =", "+ d['v']**2) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.draw() plt.pause(0.1) plt.show() def showscal(data, property='ken'):", "for the dataset (multiple frames) Input: data : xarray PIV", "= None, nthArr = 1, contourLevels = None, colbar =", "a file named im.mp4 is saved \"\"\" X, Y =", "cmap = plt.get_cmap(\"Blues\"), levels=levels) if colbar: cbar = plt.colorbar(c, orientation=colbar_orient)", "using .isel(t=0) threshold : a threshold value, default is None", "DataArray of the type defined in pivpy, one of the", "data = dataset_to_array(data) x = data.x y = data.y u", "if len(fig) == 0: # if no figure is open", "else: lUnits, velUnits, tUnits = '', '', '' if threshold", "= 0.2, threshold = Inf, n) \"\"\" data = dataset_to_array(data)", "this function will plot a normalized histogram of the velocity", "# ['m' 'm' 'mm/s' 'mm/s'] velUnits = units[2] tUnits =", "not None: lUnits = units[0] # ['m' 'm' 'mm/s' 'mm/s']", "a variable w (scalar) \"\"\" # fig = plt.figure(None if", "units[0])+']' # ylabel = (None if var is None else", "import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation, FFMpegWriter import", "['+units[2]+']') plt.tight_layout() return f, ax def contour_plot(data, threshold = None,", "ax[0].set_xlabel('u ['+units[2]+']') ax[1] = plt.subplot2grid((2,1),(1,0)) ax[1].hist(v,bins=np.int(np.sqrt(len(v)*0.5)),density=normed) ax[1].set_xlabel('v ['+units[2]+']') plt.tight_layout() return", "colorbar logscale : boolean (True is default) create in linear/log", "- use to plot only every nth arrow from the", "data['w'] = xr.where(data['w']>threshold, threshold, data['w']) m = np.amax(abs(data['w'])) if contourLevels", "[optional] integer, default is 1 savepath : [optional] path to", "velUnits = units[2] # tUnits = velUnits.split('/')[1] # make it", "maximum value (abs) of contour plots colbar - True/False wether", "of a 'data' xarray DataArray object (single frame from a", "of the velocity data. Input: data : xarray DataSet with", "velUnits = units[2] tUnits = velUnits.split('/')[1] # make it 's'", "(' + units[2] + ')') text = ax.text(0.2,1.05, '1/'+str(len(data.t)), ha='center',", "threshold = Inf, n) \"\"\" data = dataset_to_array(data) x =", "velUnits.split('/')[1] # make it 's' or 'dt' else: lUnits, velUnits,", "contour_plot(data, threshold = None, contourLevels = None, colbar = True,", "normed = False): \"\"\" this function will plot a normalized", "else: c = ax.contourf(data.x,data.y,data['w'], levels=levels, cmap = plt.get_cmap('RdYlBu')) plt.xlabel('x ['", "maybe w (scalar) \"\"\" if variables is None: xlabel =", "M = np.sqrt(U[::3,::3]**2 + V[::3,::3]**2) Q.set_UVC(U,V,M) text.set_text(str(num+1)+'/'+str(len(data.t))) return Q anim", "+ (None if units is None else units[1])+']' data =", "m, 30) else: levels = np.linspace(-contourLevels, contourLevels, 30) if logscale:", "# open a new figure else: ax = plt.gca() if", "= ax.contourf(data.x,data.y,np.abs(data['w']), levels=levels, cmap = plt.get_cmap('RdYlBu'), norm=plt.colors.LogNorm()) else: c =", "is 1 savepath : [optional] path to save the MP4", "Y = data.x, data.y U, V = data.u[:,:,0], data.v[:,:,0] #", "+' $\\cdot$ '+ tUnits +'$^{-1}$]') ax.quiver(x[::nthArr],y[::nthArr], u[::nthArr,::nthArr],v[::nthArr,::nthArr],units='width', scale = np.max(S*arrScale),headwidth=2)", "colbar_orient = 'vertical', units = None): \"\"\" Generates a quiver", "U,V = data.u[:,:,num],data.v[:,:,num] M = np.sqrt(U[::3,::3]**2 + V[::3,::3]**2) Q.set_UVC(U,V,M) text.set_text(str(num+1)+'/'+str(len(data.t)))", "= xr.where(data['v']>threshold, threshold, data['v']) S = np.array(np.sqrt(u**2 + v**2)) fig", "units is not None: lUnits = units[0] # ['m' 'm'", "'mm/s' 'mm/s'] velUnits = units[2] tUnits = velUnits.split('/')[1] # make", "data['v'] = xr.where(data['v']>threshold, threshold, data['v']) S = np.array(np.sqrt(u**2 + v**2))", "threshold = None, contourLevels = None, colbar = True, logscale", "= plt.colorbar(c, orientation=colbar_orient) cbar.set_label(r'$\\left| \\, V \\, \\right|$ ['+ lUnits" ]
[ "dilations=(1, 6, 12, 18), dropout_ratio=0.1, num_classes=21, contrast=True, norm_cfg=norm_cfg, align_corners=False, loss_decode=dict(", "norm_eval=False, interpolate_mode='bicubic'), neck=None, decode_head=dict( type='ASPPHead', in_channels=768, # in_index=3, channels=512, dilations=(1,", "model = dict( type='EncoderDecoder', pretrained='pretrain/vit_base_patch16_224.pth', backbone=dict( type='VisionTransformer', img_size=(224, 224), patch_size=16,", "norm_cfg=dict(type='LN', eps=1e-6), act_cfg=dict(type='GELU'), norm_eval=False, interpolate_mode='bicubic'), neck=None, decode_head=dict( type='ASPPHead', in_channels=768, #", "18), dropout_ratio=0.1, num_classes=21, contrast=True, norm_cfg=norm_cfg, align_corners=False, loss_decode=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)),", "8, 11), qkv_bias=True, drop_rate=0.0, attn_drop_rate=0.0, drop_path_rate=0.0, with_cls_token=True, norm_cfg=dict(type='LN', eps=1e-6), act_cfg=dict(type='GELU'),", "mlp_ratio=4, # out_indices=(2, 5, 8, 11), qkv_bias=True, drop_rate=0.0, attn_drop_rate=0.0, drop_path_rate=0.0,", "channels=512, dilations=(1, 6, 12, 18), dropout_ratio=0.1, num_classes=21, contrast=True, norm_cfg=norm_cfg, align_corners=False,", "# out_indices=(2, 5, 8, 11), qkv_bias=True, drop_rate=0.0, attn_drop_rate=0.0, drop_path_rate=0.0, with_cls_token=True,", "model training and testing settings train_cfg=dict(), test_cfg=dict(mode='whole')) # yapf: disable", "contrast=True, norm_cfg=norm_cfg, align_corners=False, loss_decode=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)), auxiliary_head=None, # model", "num_classes=21, contrast=True, norm_cfg=norm_cfg, align_corners=False, loss_decode=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)), auxiliary_head=None, #", "dict(type='BN', requires_grad=True) model = dict( type='EncoderDecoder', pretrained='pretrain/vit_base_patch16_224.pth', backbone=dict( type='VisionTransformer', img_size=(224,", "norm_cfg = dict(type='BN', requires_grad=True) model = dict( type='EncoderDecoder', pretrained='pretrain/vit_base_patch16_224.pth', backbone=dict(", "= dict(type='BN', requires_grad=True) model = dict( type='EncoderDecoder', pretrained='pretrain/vit_base_patch16_224.pth', backbone=dict( type='VisionTransformer',", "6, 12, 18), dropout_ratio=0.1, num_classes=21, contrast=True, norm_cfg=norm_cfg, align_corners=False, loss_decode=dict( type='CrossEntropyLoss',", "embed_dim=768, depth=12, num_heads=12, mlp_ratio=4, # out_indices=(2, 5, 8, 11), qkv_bias=True,", "img_size=(224, 224), patch_size=16, in_channels=3, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4, # out_indices=(2,", "settings norm_cfg = dict(type='BN', requires_grad=True) model = dict( type='EncoderDecoder', pretrained='pretrain/vit_base_patch16_224.pth',", "# model training and testing settings train_cfg=dict(), test_cfg=dict(mode='whole')) # yapf:", "align_corners=False, loss_decode=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)), auxiliary_head=None, # model training and", "loss_weight=1.0)), auxiliary_head=None, # model training and testing settings train_cfg=dict(), test_cfg=dict(mode='whole'))", "out_indices=(2, 5, 8, 11), qkv_bias=True, drop_rate=0.0, attn_drop_rate=0.0, drop_path_rate=0.0, with_cls_token=True, norm_cfg=dict(type='LN',", "norm_cfg=norm_cfg, align_corners=False, loss_decode=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)), auxiliary_head=None, # model training", "= dict( type='EncoderDecoder', pretrained='pretrain/vit_base_patch16_224.pth', backbone=dict( type='VisionTransformer', img_size=(224, 224), patch_size=16, in_channels=3,", "loss_decode=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)), auxiliary_head=None, # model training and testing", "type='EncoderDecoder', pretrained='pretrain/vit_base_patch16_224.pth', backbone=dict( type='VisionTransformer', img_size=(224, 224), patch_size=16, in_channels=3, embed_dim=768, depth=12,", "in_index=3, channels=512, dilations=(1, 6, 12, 18), dropout_ratio=0.1, num_classes=21, contrast=True, norm_cfg=norm_cfg,", "# in_index=3, channels=512, dilations=(1, 6, 12, 18), dropout_ratio=0.1, num_classes=21, contrast=True,", "dropout_ratio=0.1, num_classes=21, contrast=True, norm_cfg=norm_cfg, align_corners=False, loss_decode=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)), auxiliary_head=None,", "use_sigmoid=False, loss_weight=1.0)), auxiliary_head=None, # model training and testing settings train_cfg=dict(),", "interpolate_mode='bicubic'), neck=None, decode_head=dict( type='ASPPHead', in_channels=768, # in_index=3, channels=512, dilations=(1, 6,", "5, 8, 11), qkv_bias=True, drop_rate=0.0, attn_drop_rate=0.0, drop_path_rate=0.0, with_cls_token=True, norm_cfg=dict(type='LN', eps=1e-6),", "eps=1e-6), act_cfg=dict(type='GELU'), norm_eval=False, interpolate_mode='bicubic'), neck=None, decode_head=dict( type='ASPPHead', in_channels=768, # in_index=3,", "neck=None, decode_head=dict( type='ASPPHead', in_channels=768, # in_index=3, channels=512, dilations=(1, 6, 12,", "patch_size=16, in_channels=3, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4, # out_indices=(2, 5, 8,", "224), patch_size=16, in_channels=3, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4, # out_indices=(2, 5,", "decode_head=dict( type='ASPPHead', in_channels=768, # in_index=3, channels=512, dilations=(1, 6, 12, 18),", "type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)), auxiliary_head=None, # model training and testing settings", "drop_rate=0.0, attn_drop_rate=0.0, drop_path_rate=0.0, with_cls_token=True, norm_cfg=dict(type='LN', eps=1e-6), act_cfg=dict(type='GELU'), norm_eval=False, interpolate_mode='bicubic'), neck=None,", "depth=12, num_heads=12, mlp_ratio=4, # out_indices=(2, 5, 8, 11), qkv_bias=True, drop_rate=0.0,", "model settings norm_cfg = dict(type='BN', requires_grad=True) model = dict( type='EncoderDecoder',", "attn_drop_rate=0.0, drop_path_rate=0.0, with_cls_token=True, norm_cfg=dict(type='LN', eps=1e-6), act_cfg=dict(type='GELU'), norm_eval=False, interpolate_mode='bicubic'), neck=None, decode_head=dict(", "with_cls_token=True, norm_cfg=dict(type='LN', eps=1e-6), act_cfg=dict(type='GELU'), norm_eval=False, interpolate_mode='bicubic'), neck=None, decode_head=dict( type='ASPPHead', in_channels=768,", "12, 18), dropout_ratio=0.1, num_classes=21, contrast=True, norm_cfg=norm_cfg, align_corners=False, loss_decode=dict( type='CrossEntropyLoss', use_sigmoid=False,", "auxiliary_head=None, # model training and testing settings train_cfg=dict(), test_cfg=dict(mode='whole')) #", "type='VisionTransformer', img_size=(224, 224), patch_size=16, in_channels=3, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4, #", "dict( type='EncoderDecoder', pretrained='pretrain/vit_base_patch16_224.pth', backbone=dict( type='VisionTransformer', img_size=(224, 224), patch_size=16, in_channels=3, embed_dim=768,", "in_channels=768, # in_index=3, channels=512, dilations=(1, 6, 12, 18), dropout_ratio=0.1, num_classes=21,", "drop_path_rate=0.0, with_cls_token=True, norm_cfg=dict(type='LN', eps=1e-6), act_cfg=dict(type='GELU'), norm_eval=False, interpolate_mode='bicubic'), neck=None, decode_head=dict( type='ASPPHead',", "in_channels=3, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4, # out_indices=(2, 5, 8, 11),", "backbone=dict( type='VisionTransformer', img_size=(224, 224), patch_size=16, in_channels=3, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4,", "num_heads=12, mlp_ratio=4, # out_indices=(2, 5, 8, 11), qkv_bias=True, drop_rate=0.0, attn_drop_rate=0.0,", "11), qkv_bias=True, drop_rate=0.0, attn_drop_rate=0.0, drop_path_rate=0.0, with_cls_token=True, norm_cfg=dict(type='LN', eps=1e-6), act_cfg=dict(type='GELU'), norm_eval=False,", "act_cfg=dict(type='GELU'), norm_eval=False, interpolate_mode='bicubic'), neck=None, decode_head=dict( type='ASPPHead', in_channels=768, # in_index=3, channels=512,", "pretrained='pretrain/vit_base_patch16_224.pth', backbone=dict( type='VisionTransformer', img_size=(224, 224), patch_size=16, in_channels=3, embed_dim=768, depth=12, num_heads=12,", "# model settings norm_cfg = dict(type='BN', requires_grad=True) model = dict(", "requires_grad=True) model = dict( type='EncoderDecoder', pretrained='pretrain/vit_base_patch16_224.pth', backbone=dict( type='VisionTransformer', img_size=(224, 224),", "type='ASPPHead', in_channels=768, # in_index=3, channels=512, dilations=(1, 6, 12, 18), dropout_ratio=0.1,", "qkv_bias=True, drop_rate=0.0, attn_drop_rate=0.0, drop_path_rate=0.0, with_cls_token=True, norm_cfg=dict(type='LN', eps=1e-6), act_cfg=dict(type='GELU'), norm_eval=False, interpolate_mode='bicubic')," ]
[ "the container. The format is <device-on-host>[:<device-on-container>][:<permissions>] (e.g. device /dev/sdc:/dev/xvdc:rwm) type:", "self.params['network'] == ['none']: after = True return self._diff_update_and_compare('no_hosts', before, after)", "include http_proxy, https_proxy, ftp_proxy, no_proxy, and also the upper case", "self.params['device_write_iops'] or [] before, after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('device_write_iops',", "['--network', \",\".join(self.params['network'])] def addparam_no_hosts(self, c): return c + ['--no-hosts=%s' %", "example '10.88.64.128'. Can only be used if no additional CNI", "\"\"\"Return True if container is running now.\"\"\" return self.exists and", "c + ['--no-hosts=%s' % self.params['no_hosts']] def addparam_oom_kill_disable(self, c): return c", "container will be created. type: str cgroups: description: - Determines", "thus conflicts with CGroup options cgroupns and cgroup-parent. type: str", "% self.params['publish_all']] def addparam_read_only(self, c): return c + ['--read-only=%s' %", "else: params_with_defaults[p] = self.module.params[p] return params_with_defaults def _diff_update_and_compare(self, param_name, before,", "c): return c + ['--oom-kill-disable=%s' % self.params['oom_kill_disable']] def addparam_oom_score_adj(self, c):", "one is the actual healthcheck command. before = self.info['config']['healthcheck']['test'][1] else:", "2m3s. The default value is 0s type: str healthcheck_timeout: description:", "true. type: bool tmpfs: description: - Create a tmpfs mount.", "import yaml from ansible.module_utils.basic import AnsibleModule from ansible.module_utils._text import to_bytes,", "self.container.name) self.update_container_result() elif self.container.running and not self.container.different: if self.restart: self.container.restart()", "bootstrap. The value can be expressed in time format like", "c): return c + ['--stop-timeout', self.params['stop_timeout']] def addparam_subgidname(self, c): return", "% self.params['systemd']] def addparam_tmpfs(self, c): for tmpfs in self.params['tmpfs'].items(): c", "CPU real-time period in microseconds. Limit the container's Real Time", "return c + ['--uts', self.params['uts']] def addparam_volume(self, c): for vol", "\"\", \"NetworkSettings\": { \"Bridge\": \"\", ... }, \"Path\": \"sh\", \"ProcessLabel\":", "empty value means user namespaces are disabled. type: str uts:", "provided configuration does not match, the container will be updated,", "the Network mode for the container * bridge create a", "be expressed in time format like 2m3s. The default value", "or before return self._diff_update_and_compare('hostname', before, after) def diffparam_image(self): # TODO(sshnaidm):", "pseudo-TTY. The default is false. type: bool uidmap: description: -", "before, after) def diffparam_memory_reservation(self): before = str(self.info['hostconfig']['memoryreservation']) after = self.params['memory_reservation']", "accepts a weight value between 10 and 1000 type: int", "LooseVersion( self.podman_version): self.module.fail_json(msg=\"Parameter %s is supported till podman \" \"version", "label: description: - Add metadata to a container, pass dictionary", "be available locally. type: str annotation: description: - Add an", "to allow execution (0-3, 0,1). Only effective on NUMA systems.", "and self.module.params['blkio_weight_device'] is None: after = [] else: after =", "not self.container.exists: self.results.update({'changed': False}) elif self.container.exists: self.container.delete() self.results['actions'].append('deleted %s' %", "pass dictionary of label names and values type: dict label_file:", "process. Cgroups will be created if they do not already", "= str(self.info['hostconfig']['memoryswap']) after = self.params['memory_swap'] if (self.module.params['memory_swap'] is None and", "an interval is considered failed. Like start-period, the value can", "g) Note - idempotency is supported for integers only. type:", "real-time period in microseconds type: int cpu_rt_period: description: - Limit", "10. type: int subgidname: description: - Run the container in", "within the default CNI network's pool (default 10.88.0.0/16). type: str", "with_sequence: count=4 - name: remove container podman_container: name: ohno state:", "before, after) def diffparam_network(self): before = [self.info['hostconfig']['networkmode']] after = self.params['network']", "= \" \".join([self.module.params['executable']] + [to_native(i) for i in b_command]) self.module.log(\"PODMAN-CONTAINER-DEBUG:", "the CPU real-time period in microseconds type: int cpu_rt_period: description:", "path blkio_weight: description: - Block IO weight (relative weight) accepts", "\"\"\"Perform container tasks. Manages podman container, inspects it and checks", "def update_container_result(self, changed=True): \"\"\"Inspect the current container, update results with", "self._diff_update_and_compare('cgroup_parent', before, after) def diffparam_cgroups(self): # Cgroups output is not", "1000000000 after = self.params['cpus'] return self._diff_update_and_compare('cpus', before, after) def diffparam_cpuset_cpus(self):", "bool default: True debug: description: - Return additional information which", "{}} self.non_idempotent = { 'env_file', 'env_host', \"ulimit\", # Defaults depend", "- I(present) - Asserts the existence of a container matching", "default value is 0s type: str healthcheck_timeout: description: - The", "hostname is random generated, this parameter has partial idempotency only.", "a container will be created. If a container matches the", "= [i.lower() for i in after.split()] elif isinstance(after, list): after", "else: after = self.params['blkio_weight_device'] return self._diff_update_and_compare('blkio_weight_device', before, after) def diffparam_cap_add(self):", "for dev in self.params['device_write_iops']: c += ['--device-write-iops', dev] return c", "cgroupns and cgroup-parent. type: str choices: - default - disabled", "addparam_env(self, c): for env_value in self.params['env'].items(): c += ['--env', b\"=\".join([to_bytes(k,", "uts: description: - Set the UTS mode for the container", "will force the container to not create CGroups, and thus", "diff_func_list = [func for func in dir(self) if callable(getattr(self, func))", "to_native ANSIBLE_METADATA = { 'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'", "ip:hostPort:containerPort | ip::containerPort | hostPort:containerPort | containerPort type: list elements:", "else: after = self.params['user'] return self._diff_update_and_compare('user', before, after) def diffparam_uts(self):", "_diff_update_and_compare(self, param_name, before, after): if before != after: self.diff['before'].update({param_name: before})", "case, the image is assumed to be available locally. type:", "- 'ignore' image_strict: description: - Whether to compare images in", "return image_actions rc, out, err = module.run_command([module_exec, 'image', 'pull', image])", "a network namespace to join * slirp4netns use slirp4netns to", "default is false. When set to true, keep stdin open", "bool security_opt: description: - Security Options. For example security_opt \"seccomp=unconfined\"", "%s\" % (k, v) for k, v in sorted( diffs['before'].items())])", "Apache License, Version 2.0 (the \"License\"); you may # not", "= self.info['hostconfig']['cpusetcpus'] after = self.params['cpuset_cpus'] return self._diff_update_and_compare('cpuset_cpus', before, after) def", "description: - Tune the host's OOM preferences for containers (accepts", "All Rights Reserved. # # Licensed under the Apache License,", "env_value in self.params['env'].items(): c += ['--env', b\"=\".join([to_bytes(k, errors='surrogate_or_strict') for k", "integers only. type: str memory_swappiness: description: - Tune a container's", "additional CNI networks to join were specified via 'network:', and", "is false. type: bool security_opt: description: - Security Options. For", "path to the container log file. For example log_opt \"path=/var/log/container/mycontainer.json\"", "list of image actions - if it pulled or nothing", "volumes option for idempotency after = [\":\".join(v.split(\":\")[:2]) for v in", "- name: remove container podman_container: name: ohno state: absent -", "[] @property def exists(self): \"\"\"Check if container exists.\"\"\" return bool(self.info", "def diffparam_oom_score_adj(self): before = self.info['hostconfig']['oomscoreadj'] after = self.params['oom_score_adj'] return self._diff_update_and_compare('oom_score_adj',", "flake8: noqa: E501 from __future__ import absolute_import, division, print_function __metaclass__", "not use this file except in compliance with the License.", "to cgroups under which the cgroup for the container will", "interval is considered failed. Like start-period, the value can be", "is 'stopped'.\"\"\" if not self.container.exists and not self.image: self.module.fail_json(msg='Cannot create", "and namespaces. type: bool default: False init: description: - Run", "Copyright (c) 2019 OpenStack Foundation # All Rights Reserved. #", "memory_reservation: description: - Memory soft limit (format 100m, where unit", "absent - present - stopped - started image: description: -", "in out: self.module.fail_json(msg=\"%s run failed!\" % self.module.params['executable']) return out.split(\"version\")[1].strip() def", "self.info['config']['hostname'] after = self.params['hostname'] or before return self._diff_update_and_compare('hostname', before, after)", "the container to not create CGroups, and thus conflicts with", "now.\"\"\" return self.exists and not self.info['State']['Running'] def get_info(self): \"\"\"Inspect container", "self.stop() self.run() class PodmanManager: \"\"\"Module manager class. Defines according to", "def _diff_update_and_compare(self, param_name, before, after): if before != after: self.diff['before'].update({param_name:", "[], '']: different = True return different def ensure_image_exists(module, image):", "of a container matching the name and any provided configuration", "a new user namespace using the supplied mapping. type: str", "container type: str volume: description: - Create a bind mount.", "i in self.params['device']] before, after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('devices',", "to parameters what actions should be applied to container \"\"\"", "CPU real-time runtime in microseconds. This flag tells the kernel", "if self.action == 'delete': cmd = ['rm', '-f', self.params['name']] return", "\"License\"); you may # not use this file except in", "requirements: - \"Podman installed on host\" options: name: description: -", "['--memory-swappiness', self.params['memory_swappiness']] def addparam_mount(self, c): return c + ['--mount', self.params['mount']]", "['--userns', self.params['userns']] def addparam_uts(self, c): return c + ['--uts', self.params['uts']]", "addparam_label_file(self, c): return c + ['--label-file', self.params['label_file']] def addparam_log_driver(self, c):", "self.image) self.results['actions'] += image_actions self.state = self.module.params['state'] self.restart = self.module.params['force_restart']", "image_actions rc, out, err = module.run_command([module_exec, 'image', 'pull', image]) if", "type: int stop_timeout: description: - Timeout (in seconds) to stop", "was configured; otherwise the config key isn't part of the", "considered failed. Like start-period, the value can be expressed in", "/dev/sda:1000) type: list dns: description: - Set custom DNS servers", "+= self.params['command'].split() return [to_bytes(i, errors='surrogate_or_strict') for i in cmd] def", "self.defaults related to podman version return self.defaults class PodmanContainerDiff: def", "- CPU shares (relative weight) type: int cpus: description: -", "addparam_label(self, c): for label in self.params['label'].items(): c += ['--label', b'='.join([to_bytes(l,", "after) def diffparam_uts(self): before = self.info['hostconfig']['utsmode'] after = self.params['uts'] return", "self.params['name']] all_param_methods = [func for func in dir(self) if callable(getattr(self,", "errors='surrogate_or_strict') for i in cmd] def check_version(self, param, minv=None, maxv=None):", "cmd += self.params['command'].split() return [to_bytes(i, errors='surrogate_or_strict') for i in cmd]", "% self.params['restart_policy']] def addparam_rm(self, c): if self.params['rm']: c += ['--rm']", "description: - Path to the container-init binary. type: str interactive:", "description: - Memory soft limit (format 100m, where unit =", "= { \"blkio_weight\": 0, \"cgroups\": \"default\", \"cgroup_parent\": \"\", \"cidfile\": \"\",", "in self.params['sysctl'].items(): c += ['--sysctl', b\"=\".join([to_bytes(k, errors='surrogate_or_strict') for k in", "}' \"\"\" class PodmanModuleParams: \"\"\"Creates list of arguments for podman", "type: raw cpu_period: description: - Limit the CPU real-time period", "return c + ['--healthcheck-command', self.params['healthcheck']] def addparam_healthcheck_interval(self, c): return c", "description: - The maximum time allowed to complete the healthcheck", "the first one is # \"CMD-SHELL\" and the second one", "c): for cap_add in self.params['cap_add']: c += ['--cap-add', cap_add] return", "tasks. Manages podman container, inspects it and checks its current", "runtime in microseconds. This flag tells the kernel to limit", "+ ['--memory-swappiness', self.params['memory_swappiness']] def addparam_mount(self, c): return c + ['--mount',", "c): for dev in self.params['device_write_bps']: c += ['--device-write-bps', dev] return", "is passed, ensure it exists, if not - pull it", "before = self.info['hostconfig']['logconfig']['type'] after = self.params['log_driver'] return self._diff_update_and_compare('log_driver', before, after)", "self.container.running: self.container.stop() self.results['actions'].append('stopped %s' % self.container.name) self.update_container_result() def make_absent(self): \"\"\"Run", "for param in params_set: func_name = \"_\".join([\"addparam\", param]) if func_name", "default is false. type: bool publish: description: - Publish a", "namespaced kernel parameters at runtime type: dict systemd: description: -", "\"container{{ item }}\" recreate: yes image: someuser/anotherappimage command: sleep 1d", "return is_different @property def running(self): \"\"\"Return True if container is", "http_proxy: description: - By default proxy environment variables are passed", "-m (--memory) flag. The swap LIMIT should always be larger", "load-balanced containers podman_container: name: \"container{{ item }}\" recreate: yes image:", "# make here any changes to self.defaults related to podman", "an exploded container on the file system. The dafault is", "image' ' is not specified!') if not self.container.exists: self.container.create() self.results['actions'].append('created", "container's network namespace via 'network container:<name|id>'. The address must be", "self.params['command'].split() return [to_bytes(i, errors='surrogate_or_strict') for i in cmd] def start_stop_delete(self):", "ansible module object image {str} -- name of image Returns:", "else: cmd += self.params['command'].split() return [to_bytes(i, errors='surrogate_or_strict') for i in", "} def default_dict(self): # make here any changes to self.defaults", "container. type: bool default: False restart_policy: description: - Restart policy", "{}, 'after': {}} self.non_idempotent = { 'env_file', 'env_host', \"ulimit\", #", "(MEMs) in which to allow execution (0-3, 0,1). Only effective", "self._perform_action('run') def delete(self): \"\"\"Delete the container.\"\"\" self._perform_action('delete') def stop(self): \"\"\"Stop", "self.stdout, self.stderr = '', '' self.info = self.get_info() self.version =", "or UID used and optionally the groupname or GID for", "addparam_healthcheck_interval(self, c): return c + ['--healthcheck-interval', self.params['healthcheck_interval']] def addparam_healthcheck_retries(self, c):", "description: - Limit the CPU real-time period in microseconds type:", "container. type: list elements: str aliases: - volumes volumes_from: description:", "\"StartedAt\": \"2019-06-17T19:13:10.152479729+03:00\", \"Status\": \"exited\" }, \"StaticDir\": \"...\" ... }' \"\"\"", "image volumes. The options are bind, tmpfs, or ignore (default", "str(v).lower() for k, v in self.params['env'].items() }) return self._diff_update_and_compare('env', before,", "(format 10k, where unit = b, k, m or g)", "get from inspest, recreate it if not default before =", "self.non_idempotent = { 'env_file', 'env_host', \"ulimit\", # Defaults depend on", "container. Arguments: action {str} -- action to perform - start,", "journald - json-file log_opt: description: - Logging driver specific options.", "params_with_defaults = {} self.default_dict = PodmanDefaults( self.module, self.version).default_dict() for p", "exp] return c def addparam_gidmap(self, c): return c + ['--gidmap',", "``export REGISTRY_AUTH_FILE=path`` type: path blkio_weight: description: - Block IO weight", "namespaces. type: bool default: False init: description: - Run an", "% self.params['read_only_tmpfs']] def addparam_restart_policy(self, c): return c + ['--restart=%s' %", "0,1). Only effective on NUMA systems. type: str detach: description:", "self._diff_update_and_compare('cgroups', before, after) return False def diffparam_cidfile(self): before = self.info['hostconfig']['containeridfile']", "image will be pulled from the registry. If no tag", "description: - Create a bind mount. If you specify, volume", "dns_search: description: - Set custom DNS search domains (Use dns_search", "or [] return self._diff_update_and_compare('volumes_from', before, after) def diffparam_workdir(self): before =", "= self.params['volumes_from'] or [] return self._diff_update_and_compare('volumes_from', before, after) def diffparam_workdir(self):", "Configure namespaced kernel parameters at runtime type: dict systemd: description:", "[\"%s - %s\" % (k, v) for k, v in", "line delimited file of labels type: str log_driver: description: -", "the container's ``/etc/hosts`` file. type: dict aliases: - add_hosts expose:", "before = [\":\".join([i['pathonhost'], i['pathincontainer']]) for i in self.info['hostconfig']['devices']] after =", "in cmd] def start_stop_delete(self): if self.action in ['stop', 'start']: cmd", "container. type: str healthcheck_interval: description: - Set an interval for", "to follow when containers exit. Restart policy will not take", "for the container. It defaults to the PODMAN_USERNS environment variable.", "the default for rootless containers type: list elements: str aliases:", "type: bool etc_hosts: description: - Dict of host-to-IP mappings, where", "the container's root filesystem as read only. Default is false", "after = after.replace(\":latest\", \"\") before = before.split(\"/\")[-1] after = after.split(\"/\")[-1]", "c + ['--hostname', self.params['hostname']] def addparam_http_proxy(self, c): return c +", "is 10. type: int subgidname: description: - Run the container", "of the authentication file by setting the ``REGISTRY_AUTH_FILE`` environment variable.", "type: str memory_swappiness: description: - Tune a container's memory swappiness", "Time CPU usage to the period you specify. type: int", "[], \"env_host\": False, \"etc_hosts\": {}, \"group_add\": [], \"healthcheck\": \"\", \"ipc\":", "['--env-host=%s' % self.params['env_host']] def addparam_etc_hosts(self, c): for host_ip in self.params['etc_hosts'].items():", "\"0\", # \"memory_swappiness\": -1, \"no_hosts\": False, # libpod issue with", "not None) for param in params_set: func_name = \"_\".join([\"addparam\", param])", "i in before] after = self.params['device_write_iops'] or [] before, after", "redis command: redis-server --appendonly yes state: present recreate: yes expose:", "self.info = yaml.safe_load(json.dumps(info).lower()) self.params = self.defaultize() self.diff = {'before': {},", "before a healthcheck is considered to be unhealthy. The default", "c + ['--http-proxy=%s' % self.params['http_proxy']] def addparam_image_volume(self, c): return c", "to limit the amount of time in a given CPU", "type: list elements: str aliases: - exposed - exposed_ports force_restart:", "a container. Format is a single character or ctrl-value type:", "self.params['cgroup_parent']] def addparam_cidfile(self, c): return c + ['--cidfile', self.params['cidfile']] def", "c + ['--healthcheck-start-period', self.params['healthcheck_start_period']] def addparam_healthcheck_timeout(self, c): return c +", "addparam_rootfs(self, c): return c + ['--rootfs=%s' % self.params['rootfs']] def addparam_security_opt(self,", "mydata - name: Restart a container podman_container: name: myapplication image:", "image: someuser/anotherappimage command: sleep 1d with_sequence: count=4 - name: remove", "Stop a container podman_container: name: mycontainer state: stopped - name:", "return self._diff_update_and_compare('tty', before, after) def diffparam_user(self): before = self.info['config']['user'] if", "included, C(latest) will be used. - Can also be an", "a new user namespace using the supplied mapping. type: list", "considered to be relative to the cgroups path of the", "The default is false. type: bool uidmap: description: - Run", "= sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('security_opt', before, after) def diffparam_stop_signal(self): before", "is not absolute, the path is considered to be relative", "another container's network stack * host use the podman host", "etc_hosts: description: - Dict of host-to-IP mappings, where each host", "The initialization time needed for a container to bootstrap. The", "false, \"OciVersion\": \"1.0.1-dev\", \"Paused\": false, \"Pid\": 4083, \"Restarting\": false, \"Running\":", "if C(state) is I(absent). returned: always type: dict sample: '{", "command for a container. type: str healthcheck_interval: description: - Set", "module.params['state'] in ['started', 'present'] and \\ not module.params['image']: module.fail_json(msg=\"State '%s'", "what actions should be applied to container \"\"\" def __init__(self,", "= self.params['etc_hosts'] return self._diff_update_and_compare('etc_hosts', before, after) def diffparam_group_add(self): before =", "handle the builtin image volumes. The options are bind, tmpfs,", "for the container type: str volume: description: - Create a", "the system uses bytes. If you omit the size entirely,", "= module def construct_command_from_params(self): \"\"\"Create a podman command from given", "type: str uts: description: - Set the UTS mode for", "for the container will be created. type: str cgroups: description:", "Proxy signals sent to the podman run command to the", "in self.params['device_write_iops']: c += ['--device-write-iops', dev] return c def addparam_dns(self,", "[ \"PATH=/usr/sbin:/usr/bin:/sbin:/bin\", \"TERM=xterm\", \"HOSTNAME=\", \"container=podman\" ], \"Hostname\": \"\", \"Image\": \"docker.io/library/busybox:latest\",", "self.params['memory'] != 0 and self.params['memory'].isdigit()): after = str(int(self.params['memory']) * 2)", "b'container', b'inspect', self.name]) return json.loads(out)[0] if rc == 0 else", "for k in sysctl])] return c def addparam_systemd(self, c): return", "Logging driver. Used to set the log driver for the", "the container's pids limit. Set -1 to have unlimited pids", "type: int cpus: description: - Number of CPUs. The default", "disabled option will force the container to not create CGroups,", "after) # Parameter has limited idempotency, unable to guess the", "actions - if it pulled or nothing was done \"\"\"", "cgroups path of the init process. Cgroups will be created", "in before] after = self.params['device_read_iops'] or [] before, after =", "will create CGroups. Valid values are enabled and disabled, which", "is 30s type: str hostname: description: - Container host name.", "'-f', self.params['name']] return [to_bytes(i, errors='surrogate_or_strict') for i in cmd] def", "i['rate']) for i in before] after = self.params['device_write_bps'] or []", "may obtain # a copy of the License at #", "- Set environment variables. This option allows you to specify", "type: bool security_opt: description: - Security Options. For example security_opt", "self.params['oom_kill_disable']] def addparam_oom_score_adj(self, c): return c + ['--oom-score-adj', self.params['oom_score_adj']] def", "- Ulimit options type: list user: description: - Sets the", "= self.info['effectivecaps'] or [] after = [] if self.module.params['cap_add'] is", "new user namespace using the supplied mapping. type: list ulimit:", "* ns:<path> path to a network namespace to join *", "(e.g. device /dev/sdc:/dev/xvdc:rwm) type: list elements: str device_read_bps: description: -", "if not self.container.exists: self.results.update({'changed': False}) elif self.container.exists: self.container.delete() self.results['actions'].append('deleted %s'", "description: - Read in a line delimited file of environment", "self.params['env']: after.update({ str(k).lower(): str(v).lower() for k, v in self.params['env'].items() })", "k, v in self.params['env'].items() }) return self._diff_update_and_compare('env', before, after) def", "twice memory parameter before = str(self.info['hostconfig']['memoryswap']) after = self.params['memory_swap'] if", "will be created if they do not already exist. type:", "container.\"\"\" self._perform_action('run') def delete(self): \"\"\"Delete the container.\"\"\" self._perform_action('delete') def stop(self):", "@property def stopped(self): \"\"\"Return True if container exists and is", "description: - Add additional groups to run as type: list", "self.module.log(\"PODMAN-CONTAINER-DEBUG: %s\" % full_cmd) self.actions.append(full_cmd) if not self.module.check_mode: rc, out,", "podman process. This can be disabled by setting the http_proxy", "addparam_device_write_iops(self, c): for dev in self.params['device_write_iops']: c += ['--device-write-iops', dev]", "ensure_image_exists(self.module, self.image) self.results['actions'] += image_actions self.state = self.module.params['state'] self.restart =", "+ ['--entrypoint', self.params['entrypoint']] def addparam_env(self, c): for env_value in self.params['env'].items():", "'%s' required image to be configured!\" % module.params['state']) PodmanManager(module).execute() if", "addparam_cmd_args(self, c): return c + self.params['cmd_args'] class PodmanDefaults: def __init__(self,", "name: mycontainer state: present image: ubuntu:14.04 command: \"sleep 1d\" -", "self.module.params['state'] self.restart = self.module.params['force_restart'] self.recreate = self.module.params['recreate'] self.container = PodmanContainer(self.module,", "the file system. The dafault is false. type: bool security_opt:", "and restarted. - I(stopped) - Asserts that the container is", "TODO(sshnaidm): for strict image compare mode use SHAs before =", "may # not use this file except in compliance with", "dict([i.split(\":\") for i in self.info['hostconfig']['extrahosts']]) else: before = {} after", "str): after = [i.lower() for i in after.split()] elif isinstance(after,", "to compare images in idempotency by taking into account a", "in before] after = self.params['device_read_bps'] or [] before, after =", "before.copy() if self.params['env']: after.update({ str(k).lower(): str(v).lower() for k, v in", "pid of the conmon process to a file. conmon runs", "a key in the dictionary. Each host name will be", "host device to the container. The format is <device-on-host>[:<device-on-container>][:<permissions>] (e.g.", "before, after) # Because of hostname is random generated, this", "'image', 'exists', image]) if rc == 0: return image_actions rc,", "available locally. type: str annotation: description: - Add an annotation", "Add a host device to the container. The format is", "for dev in self.params['device_read_iops']: c += ['--device-read-iops', dev] return c", "actions & states.\"\"\" states_map = { 'present': self.make_started, 'started': self.make_started,", "type: str group_add: description: - Add additional groups to run", "matching container. - I(started) - Asserts there is a running", "for host_ip in self.params['etc_hosts'].items(): c += ['--add-host', ':'.join(host_ip)] return c", "\" \"version %s only! Current version is %s\" % (", "__init__(self, module, name): \"\"\"Initialize PodmanContainer class. Arguments: module {obj} --", "name: Stop a container podman_container: name: mycontainer state: stopped -", "if rc != 0: self.module.fail_json( msg=\"Can't %s container %s\" %", "= (i for i in self.params if self.params[i] is not", "- Override the key sequence for detaching a container. Format", "read-write tmpfs on /run, /tmp, and /var/tmp. The default is", "after = self.params['group_add'] return self._diff_update_and_compare('group_add', before, after) # Healthcheck is", "default proxy environment variables are passed into the container if", "c): for u in self.params['ulimit']: c += ['--ulimit', u] return", "diffcheck.diff if self.module._diff and is_different and diffs['before'] and diffs['after']: self.diff['before']", "':'.join(blkio)] return c def addparam_cap_add(self, c): for cap_add in self.params['cap_add']:", "diffparam_log_driver(self): before = self.info['hostconfig']['logconfig']['type'] after = self.params['log_driver'] return self._diff_update_and_compare('log_driver', before,", "flag. The swap LIMIT should always be larger than -m", "+ ['--shm-size', self.params['shm_size']] def addparam_sig_proxy(self, c): return c + ['--sig-proxy=%s'", "\"Hostname\": \"\", \"Image\": \"docker.io/library/busybox:latest\", \"Labels\": null, \"OpenStdin\": false, \"StdinOnce\": false,", "c + ['--cpu-period', self.params['cpu_period']] def addparam_cpu_rt_period(self, c): return c +", "is included, C(latest) will be used. - Can also be", "name: myservice image: busybox log_options: path=/var/log/container/mycontainer.json log_driver: k8s-file \"\"\" RETURN", "- Override command of container. Can be a string or", "\"\", \"Image\": \"docker.io/library/busybox:latest\", \"Labels\": null, \"OpenStdin\": false, \"StdinOnce\": false, \"StopSignal\":", "- stopped - started image: description: - Repository path (or", "policy to follow when containers exit. Restart policy will not", "from inspest, recreate it if not default before = False", "maintainers ASAP!\") def main(): module = AnsibleModule( argument_spec=yaml.safe_load(DOCUMENTATION)['options'], mutually_exclusive=( ['no_hosts',", "is not in the C($PATH) on the machine running C(podman)", "in label])] return c def addparam_label_file(self, c): return c +", "is different.\"\"\" diffcheck = PodmanContainerDiff(self.module, self.info, self.version) is_different = diffcheck.is_different()", "+ ['--conmon-pidfile', self.params['conmon_pidfile']] def addparam_cpu_period(self, c): return c + ['--cpu-period',", "The dafault is false. type: bool security_opt: description: - Security", "choices: - absent - present - stopped - started image:", "self.params = self.defaultize() self.diff = {'before': {}, 'after': {}} self.non_idempotent", "self.diff['before'].update({param_name: before}) self.diff['after'].update({param_name: after}) return True return False def diffparam_annotation(self):", "after) def diffparam_cgroup_parent(self): before = self.info['hostconfig']['cgroupparent'] after = self.params['cgroup_parent'] return", "configuration does not match, the container will be updated, if", "podman to make the pod for you, preference the pod", "- idempotency is supported for integers only. type: str memory_swappiness:", "sysctl])] return c def addparam_systemd(self, c): return c + ['--systemd=%s'", "container podman_container: name: container image: quay.io/bitnami/wildfly state: started - name:", "must be greater than 0. Unit is optional and can", "c + ['--conmon-pidfile', self.params['conmon_pidfile']] def addparam_cpu_period(self, c): return c +", "c + ['--label-file', self.params['label_file']] def addparam_log_driver(self, c): return c +", "after: self.diff['before'].update({param_name: before}) self.diff['after'].update({param_name: after}) return True return False def", "re-creation of the matching container. - I(started) - Asserts there", "in self.params['uidmap']: c += ['--uidmap', uidmap] return c def addparam_ulimit(self,", "str memory_swappiness: description: - Tune a container's memory swappiness behavior.", "str cpuset_mems: description: - Memory nodes (MEMs) in which to", "behavior. Accepts an integer between 0 and 100. type: int", "impossible to get from inspest, recreate it if not default", "a separate process than Podman, so this is necessary when", "upper case versions of those. Defaults to true type: bool", "description: - Container host name. Sets the container host name", "% self.params['cgroups']] def addparam_cgroupns(self, c): self.check_version('--cgroupns', minv='1.6.2') return c +", "= sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('device_read_bps', before, after) def diffparam_device_read_iops(self): before", "after = self.params['tty'] return self._diff_update_and_compare('tty', before, after) def diffparam_user(self): before", "extended privileges to this container. The default is false. type:", "size entirely, the system uses 64m type: str sig_proxy: description:", "Real Time CPU usage. This flag tell the kernel to", "volumes.append([m['name'], m['destination']]) else: volumes.append([m['source'], m['destination']]) before = [\":\".join(v) for v", "in self.non_idempotent: if self.module.params[p] is not None and self.module.params[p] not", "self.params['stop_signal']] def addparam_stop_timeout(self, c): return c + ['--stop-timeout', self.params['stop_timeout']] def", "% self.container.name) self.update_container_result() elif self.container.stopped and not self.container.different: self.container.start() self.results['actions'].append('started", "podman_container: name: container image: quay.io/bitnami/wildfly state: started - name: Create", "return c def addparam_rootfs(self, c): return c + ['--rootfs=%s' %", "self._diff_update_and_compare('cpu_rt_runtime', before, after) def diffparam_cpu_shares(self): before = self.info['hostconfig']['cpushares'] after =", "\"cpuset_mems\": \"\", \"detach\": True, \"device\": [], \"env_host\": False, \"etc_hosts\": {},", "default: False detach_keys: description: - Override the key sequence for", "\"\"\"Initialize PodmanManager class. Arguments: module {obj} -- ansible module object", "or GID for the specified command. type: str userns: description:", "search domains (Use dns_search with '' if you don't wish", "addparam_cgroups(self, c): self.check_version('--cgroups', minv='1.6.0') return c + ['--cgroups=%s' % self.params['cgroups']]", "a container's port, or range of ports, to the host.", "port redirection on the host system. type: list elements: str", "compatibility reasons, the facts are also accessible directly as C(podman_container).", "running container matching the name and any provided configuration. If", "__init__(self, module, info, podman_version): self.module = module self.version = podman_version", "and values type: dict label_file: description: - Read in a", "minv=None, maxv=None): if minv and LooseVersion(minv) > LooseVersion( self.podman_version): self.module.fail_json(msg=\"Parameter", "Mount the container's root filesystem as read only. Default is", "attached. The default is false. When set to true, keep", "str pids_limit: description: - Tune the container's pids limit. Set", "= podman_version self.defaults = { \"blkio_weight\": 0, \"cgroups\": \"default\", \"cgroup_parent\":", "self.module.fail_json(msg='Cannot create container when image' ' is not specified!') if", "\"--root\", ... ], \"GraphDriver\": { ... }, \"HostConfig\": { ...", "if self.module.params['log_opt'] in [None, '']: after = before else: after", "in a new user namespace using the map with 'name'", "+ ['--label-file', self.params['label_file']] def addparam_log_driver(self, c): return c + ['--log-driver',", "for the container Default is false. type: bool oom_kill_disable: description:", "description: - Publish a container's port, or range of ports,", "def diffparam_cpu_rt_runtime(self): before = self.info['hostconfig']['cpurealtimeruntime'] after = self.params['cpu_rt_runtime'] return self._diff_update_and_compare('cpu_rt_runtime',", "'tmpfs' - 'ignore' image_strict: description: - Whether to compare images", "a pseudo-TTY. The default is false. type: bool uidmap: description:", "if 'cgroups' in self.info['hostconfig']: before = self.info['hostconfig']['cgroups'] after = self.params['cgroups']", "name that is available inside the container. type: str http_proxy:", "type import json from distutils.version import LooseVersion import yaml from", "list elements: str aliases: - ports - published - published_ports", "(i['path'], i['rate']) for i in before] after = self.params['device_read_bps'] or", "sequence for detaching a container. Format is a single character", "{}, \"group_add\": [], \"healthcheck\": \"\", \"ipc\": \"\", \"kernelmemory\": \"0\", \"log_driver\":", "to a device (e.g. device-write-iops /dev/sda:1000) type: list dns: description:", "existing container. type: bool default: False restart_policy: description: - Restart", "'volume': volumes.append([m['name'], m['destination']]) else: volumes.append([m['source'], m['destination']]) before = [\":\".join(v) for", "before = self.info['config']['hostname'] after = self.params['hostname'] or before return self._diff_update_and_compare('hostname',", "the specific language governing permissions and limitations # under the", "or not. Default is false. type: bool oom_score_adj: description: -", "container is running moves it to a stopped state. type:", "= module.run_command([module_exec, 'image', 'exists', image]) if rc == 0: return", "if c in after: after.remove(c) before, after = sorted(list(set(before))), sorted(list(set(after)))", "argument_spec=yaml.safe_load(DOCUMENTATION)['options'], mutually_exclusive=( ['no_hosts', 'etc_hosts'], ), supports_check_mode=True, ) # work on", "before = self.info['config']['tty'] after = self.params['tty'] return self._diff_update_and_compare('tty', before, after)", "always be larger than -m (--memory) value. By default, the", "I(started) - Asserts there is a running container matching the", "self.params['detach']] def addparam_detach_keys(self, c): return c + ['--detach-keys', self.params['detach_keys']] def", "different registries are the same before = before.replace(\":latest\", \"\") after", "True debug: description: - Return additional information which can be", "before, after) def diffparam_cgroup_parent(self): before = self.info['hostconfig']['cgroupparent'] after = self.params['cgroup_parent']", "self.params['log_opt'].split(\"=\")[1] return self._diff_update_and_compare('log_opt', before, after) def diffparam_memory(self): before = str(self.info['hostconfig']['memory'])", "real-time period in microseconds. Limit the container's Real Time CPU", "variables type: path env_host: description: - Use all current host", "the groupname or GID for the specified command. type: str", "[\":\".join(i.split(\":\")[:2]) for i in self.params['device']] before, after = sorted(list(set(before))), sorted(list(set(after)))", "example security_opt \"seccomp=unconfined\" type: list elements: str shm_size: description: -", "if it is not in the C($PATH) on the machine", "c): return c + ['--privileged=%s' % self.params['privileged']] def addparam_publish(self, c):", "installed on host\" options: name: description: - Name of the", "image is passed, ensure it exists, if not - pull", "a user-defined network * ns:<path> path to a network namespace", "False for func_name in diff_func_list: dff_func = getattr(self, func_name) if", "- Can also be an image ID. If this is", "self.params['security_opt'] before, after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('security_opt', before, after)", "execution (0-3, 0,1) type: str cpuset_mems: description: - Memory nodes", "and limitations # under the License. # flake8: noqa: E501", "' is not specified!') if not self.container.exists: self.container.create() self.results['actions'].append('created %s'", "container to be stopped and restarted. - I(stopped) - Asserts", "if not self.container.exists and not self.image: self.module.fail_json(msg='Cannot create container when", "states_map = { 'present': self.make_started, 'started': self.make_started, 'absent': self.make_absent, 'stopped':", "type: list device_write_iops: description: - Limit write rate (IO per", "def recreate(self): \"\"\"Recreate the container.\"\"\" self.delete() self.run() def restart(self): \"\"\"Restart", "= {} after = self.params['etc_hosts'] return self._diff_update_and_compare('etc_hosts', before, after) def", "@property def different(self): \"\"\"Check if container is different.\"\"\" diffcheck =", "changed, 'container': facts, 'podman_actions': self.container.actions}, stdout=out, stderr=err) if self.container.diff: self.results.update({'diff':", "container podman_container: name: mydata image: busybox volume: - /tmp/data -", "c += ['--device-read-bps', dev] return c def addparam_device_read_iops(self, c): for", "CONDITIONS OF ANY KIND, either express or implied. See the", "before, after) def diffparam_cpu_period(self): before = self.info['hostconfig']['cpuperiod'] after = self.params['cpu_period']", "container, pass dictionary of label names and values type: dict", "failed. Like start-period, the value can be expressed in a", "def addparam_read_only_tmpfs(self, c): return c + ['--read-only-tmpfs=%s' % self.params['read_only_tmpfs']] def", "is not None: after.update(self.params['annotation']) return self._diff_update_and_compare('annotation', before, after) def diffparam_env_host(self):", "+= self.params['command'] else: cmd += self.params['command'].split() return [to_bytes(i, errors='surrogate_or_strict') for", "return c + ['--blkio-weight', self.params['blkio_weight']] def addparam_blkio_weight_device(self, c): for blkio", "= module self.results = { 'changed': False, 'actions': [], 'container':", "'delete', 'start' params {dict} -- dictionary of module parameters \"\"\"", "= True # Check non idempotent parameters for p in", "input vars if module.params['state'] in ['started', 'present'] and \\ not", "self.info['hostconfig']['cpurealtimeperiod'] after = self.params['cpu_rt_period'] return self._diff_update_and_compare('cpu_rt_period', before, after) def diffparam_cpu_rt_runtime(self):", "- 6379 volumes_from: - mydata - name: Restart a container", "podman stop commands. Valid values are * no - Do", "\"\"\"Stop the container.\"\"\" self._perform_action('stop') def start(self): \"\"\"Start the container.\"\"\" self._perform_action('start')", "description: - Limit read rate (bytes per second) from a", "sorted(list(set(after))) return self._diff_update_and_compare('cap_add', before, after) def diffparam_cap_drop(self): before = self.info['effectivecaps']", "return self._diff_update_and_compare('devices', before, after) def diffparam_device_read_bps(self): before = self.info['hostconfig']['blkiodevicereadbps'] or", "self.non_idempotent: if self.module.params[p] is not None and self.module.params[p] not in", "and gather info about it.\"\"\" rc, out, err = self.module.run_command(", "name: Re-create a redis container podman_container: name: myredis image: redis", "c + ['--cgroupns=%s' % self.params['cgroupns']] def addparam_cgroup_parent(self, c): return c", "mount to the container. bind or tmpfs For example mount", "self.container.stopped: self.update_container_result(changed=False) elif self.container.running: self.container.stop() self.results['actions'].append('stopped %s' % self.container.name) self.update_container_result()", "line delimited file of environment variables type: path env_host: description:", "['--healthcheck-retries', self.params['healthcheck_retries']] def addparam_healthcheck_start_period(self, c): return c + ['--healthcheck-start-period', self.params['healthcheck_start_period']]", "the search domain) type: str entrypoint: description: - Overwrite the", "host interfaces. The default is false. type: bool read_only: description:", "the /etc/subuid file. type: str sysctl: description: - Configure namespaced", "container, update results with last info, exit. Keyword Arguments: changed", "self.stderr = err if rc != 0: self.module.fail_json( msg=\"Can't %s", "IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND,", "c def addparam_device_write_iops(self, c): for dev in self.params['device_write_iops']: c +=", "container is different.\"\"\" diffcheck = PodmanContainerDiff(self.module, self.info, self.version) is_different =", "you omit the size entirely, the system uses 64m type:", "self.module.params['cap_add']] after += before before, after = sorted(list(set(before))), sorted(list(set(after))) return", "the container. type: dict env_file: description: - Read in a", "= self.params['memory_swap'] if (self.module.params['memory_swap'] is None and self.params['memory'] != 0", "= not bool(self.info['hostspath']) after = self.params['no_hosts'] if self.params['network'] == ['none']:", "c): return c + ['--read-only-tmpfs=%s' % self.params['read_only_tmpfs']] def addparam_restart_policy(self, c):", "self.module.params['conmon_pidfile'] is None: after = before else: after = self.params['conmon_pidfile']", "elements: str aliases: - volumes volumes_from: description: - Mount volumes", "action, params, podman_version, module): self.params = params self.action = action", "self._diff_update_and_compare('cpu_rt_period', before, after) def diffparam_cpu_rt_runtime(self): before = self.info['hostconfig']['cpurealtimeruntime'] after =", "- disabled cidfile: description: - Write the container ID to", "- Memory nodes (MEMs) in which to allow execution (0-3,", "a healthcheck command for a container. type: str healthcheck_interval: description:", "idempotency by taking into account a full name with registry", "default: started choices: - absent - present - stopped -", "Limit the container's Real Time CPU usage. This flag tell", "-1000 to 1000) type: int pid: description: - Set the", "performed (default: {True}) \"\"\" facts = self.container.get_info() if changed else", "( param, minv, self.podman_version)) if maxv and LooseVersion(maxv) < LooseVersion(", "expand_user_and_vars=False) self.stdout = out self.stderr = err if rc !=", "def addparam_cpuset_cpus(self, c): return c + ['--cpuset-cpus', self.params['cpuset_cpus']] def addparam_cpuset_mems(self,", "], \"GraphDriver\": { ... }, \"HostConfig\": { ... }, \"HostnamePath\":", "\"User\": { \"gid\": 0, \"uid\": 0 }, \"Volumes\": null, \"WorkingDir\":", "self.params['cpuset_mems'] return self._diff_update_and_compare('cpuset_mems', before, after) def diffparam_device(self): before = [\":\".join([i['pathonhost'],", "the container type: str volume: description: - Create a bind", "removed in Ansible 2.12. - Empty if C(state) is I(absent).", "restarted. - I(stopped) - Asserts that the container is first", "return c + ['--ip', self.params['ip']] def addparam_ipc(self, c): return c", "[func for func in dir(self) if callable(getattr(self, func)) and func.startswith(\"addparam\")]", "self.params['cgroupns']] def addparam_cgroup_parent(self, c): return c + ['--cgroup-parent', self.params['cgroup_parent']] def", "[None, '']: after = before else: after = self.params['log_opt'].split(\"=\")[1] return", "def addparam_blkio_weight(self, c): return c + ['--blkio-weight', self.params['blkio_weight']] def addparam_blkio_weight_device(self,", "from the specified container(s). type: list elements: str workdir: description:", "file. type: str sysctl: description: - Configure namespaced kernel parameters", "'image', 'pull', image]) if rc != 0: module.fail_json(msg=\"Can't pull image", "all_param_methods: cmd = getattr(self, func_name)(cmd) cmd.append(self.params['image']) if self.params['command']: if isinstance(self.params['command'],", "= { 'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community' } DOCUMENTATION", "str network: description: - Set the Network mode for the", "elements: str conmon_pidfile: description: - Write the pid of the", "description: - Sets the username or UID used and optionally", "if not attached. The default is false. When set to", "of module parameters \"\"\" def __init__(self, action, params, podman_version, module):", "a container. Default is 10. type: int subgidname: description: -", "out, err = self.module.run_command( [self.module.params['executable'], b'container', b'inspect', self.name]) return json.loads(out)[0]", "- Limit write rate (IO per second) to a device", "the name but the provided configuration does not match, the", "or [] before, after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('device_read_bps', before,", "self._diff_update_and_compare('device_write_bps', before, after) def diffparam_device_write_iops(self): before = self.info['hostconfig']['blkiodevicewriteiops'] or []", "- Set custom DNS options type: str dns_search: description: -", "<network-name>|<network-id> connect to a user-defined network * ns:<path> path to", "if not self.module.check_mode: rc, out, err = self.module.run_command( [self.module.params['executable'], b'container']", "self.results.update({'podman_version': self.container.version}) self.module.exit_json(**self.results) def make_started(self): \"\"\"Run actions if desired state", "guess the default log_path def diffparam_log_opt(self): before = self.info['logpath'] if", "= self.params['network'] return self._diff_update_and_compare('network', before, after) def diffparam_no_hosts(self): before =", "type: str init_path: description: - Path to the container-init binary.", "type: str state: description: - I(absent) - A container matching", "number of retries allowed before a healthcheck is considered to", "is false. type: bool oom_kill_disable: description: - Whether to disable", "+= ['--cap-add', cap_add] return c def addparam_cap_drop(self, c): for cap_drop", "variables passed in include http_proxy, https_proxy, ftp_proxy, no_proxy, and also", "... }, \"HostnamePath\": \"...\", \"HostsPath\": \"...\", \"ID\": \"...\", \"Image\": \"...\",", "image {str} -- name of image Returns: list -- list", "update results with last info, exit. Keyword Arguments: changed {bool}", "when comparing configuration. Use the recreate option to force the", "default value is 3. type: int healthcheck_start_period: description: - The", "it or fail. Arguments: module {obj} -- ansible module object", "c): return c + ['--cpus', self.params['cpus']] def addparam_cpuset_cpus(self, c): return", "sorted( diffs['after'].items())]) + \"\\n\" return is_different @property def running(self): \"\"\"Return", "}, \"HostnamePath\": \"...\", \"HostsPath\": \"...\", \"ID\": \"...\", \"Image\": \"...\", \"ImageName\":", "return c + ['--healthcheck-timeout', self.params['healthcheck_timeout']] def addparam_hostname(self, c): return c", "\"memory_swappiness\": -1, \"no_hosts\": False, # libpod issue with networks in", "self._diff_update_and_compare('label', before, after) def diffparam_log_driver(self): before = self.info['hostconfig']['logconfig']['type'] after =", "CPU period Real Time tasks may consume. type: int cpu_shares:", "the upper case versions of those. Defaults to true type:", "image compare mode use SHAs before = self.info['config']['image'] after =", "before = self.info['hostconfig']['securityopt'] after = self.params['security_opt'] before, after = sorted(list(set(before))),", "cap_drop: description: - List of capabilities to drop from the", "\"myservice\", \"Namespace\": \"\", \"NetworkSettings\": { \"Bridge\": \"\", ... }, \"Path\":", "after) return False def diffparam_conmon_pidfile(self): before = self.info['conmonpidfile'] if self.module.params['conmon_pidfile']", "self.params['subuidname']] def addparam_sysctl(self, c): for sysctl in self.params['sysctl'].items(): c +=", "= [i.lower() for i in after] return self._diff_update_and_compare('command', before, after)", "restart containers on exit * on-failure[:max_retries] - Restart containers when", "return c + ['--healthcheck-retries', self.params['healthcheck_retries']] def addparam_healthcheck_start_period(self, c): return c", "else: different = True # Check non idempotent parameters for", "For example mount \"type=bind,source=/path/on/host,destination=/path/in/container\" type: str network: description: - Set", "podman_version): self.module = module self.version = podman_version self.defaults = {", "for uidmap in self.params['uidmap']: c += ['--uidmap', uidmap] return c", "stack * host use the podman host network stack. *", "(i for i in self.params if self.params[i] is not None)", "if dff_func(): if fail_fast: return True else: different = True", "Security Options. For example security_opt \"seccomp=unconfined\" type: list elements: str", "be created. If a container matches the name but the", "i in self.module.params['cap_add']] after += before before, after = sorted(list(set(before))),", "\"ipc\": \"\", \"kernelmemory\": \"0\", \"log_driver\": \"k8s-file\", \"memory\": \"0\", \"memory_swap\": \"0\",", "to create the container. If an image is not found,", "be created. type: str cgroups: description: - Determines whether the", "in sorted( diffs['after'].items())]) + \"\\n\" return is_different @property def running(self):", "to set the search domain) type: str entrypoint: description: -", "'healthcheck' in self.info['config']: # the \"test\" key is a list", "in self.module.params['cap_add']] after += before before, after = sorted(list(set(before))), sorted(list(set(after)))", "before != after: self.diff['before'].update({param_name: before}) self.diff['after'].update({param_name: after}) return True return", "sysctl: description: - Configure namespaced kernel parameters at runtime type:", "image: busybox volume: - /tmp/data - name: Re-create a redis", "return c + ['--log-opt', self.params['log_opt']] def addparam_memory(self, c): return c", "Container host name. Sets the container host name that is", "c def addparam_publish_all(self, c): return c + ['--publish-all=%s' % self.params['publish_all']]", "key value, multiple times. type: dict authfile: description: - Path", "connect to a user-defined network * ns:<path> path to a", "return c + ['--detach=%s' % self.params['detach']] def addparam_detach_keys(self, c): return", "elements: str dns_option: description: - Set custom DNS options type:", "all_param_methods = [func for func in dir(self) if callable(getattr(self, func))", "str state: description: - I(absent) - A container matching the", "false, \"LogPath\": \"/tmp/container/mycontainer.json\", \"MountLabel\": \"system_u:object_r:container_file_t:s0:c282,c782\", \"Mounts\": [ ... ], \"Name\":", "return c def addparam_cgroups(self, c): self.check_version('--cgroups', minv='1.6.0') return c +", "after = self.params['no_hosts'] if self.params['network'] == ['none']: after = True", "\"\"\" def __init__(self, action, params, podman_version, module): self.params = params", "addparam_env_host(self, c): self.check_version('--env-host', minv='1.5.0') return c + ['--env-host=%s' % self.params['env_host']]", "= self.params['log_opt'].split(\"=\")[1] return self._diff_update_and_compare('log_opt', before, after) def diffparam_memory(self): before =", "published_ports publish_all: description: - Publish all exposed ports to random", "{str} -- action to perform - start, create, stop, run,", "podman command def addparam_cmd_args(self, c): return c + self.params['cmd_args'] class", "``REGISTRY_AUTH_FILE`` environment variable. ``export REGISTRY_AUTH_FILE=path`` type: path blkio_weight: description: -", "\"...\", \"ImageName\": \"docker.io/library/busybox:latest\", \"IsInfra\": false, \"LogPath\": \"/tmp/container/mycontainer.json\", \"MountLabel\": \"system_u:object_r:container_file_t:s0:c282,c782\", \"Mounts\":", "sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('device_write_bps', before, after) def diffparam_device_write_iops(self): before =", "c): return c + ['--healthcheck-start-period', self.params['healthcheck_start_period']] def addparam_healthcheck_timeout(self, c): return", "value can be expressed in a time format such as", "device (e.g. device-write-iops /dev/sda:1000) type: list dns: description: - Set", "if it is running. Use force_restart to force a matching", "isinstance(self.params['command'], list): cmd += self.params['command'] else: cmd += self.params['command'].split() return", "self.info['State']['Running'] @property def stopped(self): \"\"\"Return True if container exists and", "data container podman_container: name: mydata image: busybox volume: - /tmp/data", "- Run container in detach mode type: bool default: True", "+= ['--label', b'='.join([to_bytes(l, errors='surrogate_or_strict') for l in label])] return c", "will be updated, if it can be. If it cannot", "if vol: c += ['--volume', vol] return c def addparam_volumes_from(self,", "+= ['--expose', exp] return c def addparam_gidmap(self, c): return c", "the container. type: str pod: description: - Run container in", "description: - Add an annotation to the container. The format", "str cgroups: description: - Determines whether the container will create", "self.params['blkio_weight_device'].items(): c += ['--blkio-weight-device', ':'.join(blkio)] return c def addparam_cap_add(self, c):", "c): return c + ['--userns', self.params['userns']] def addparam_uts(self, c): return", "c + ['--dns-search', self.params['dns_search']] def addparam_entrypoint(self, c): return c +", "C(podman_container). Note that the returned fact will be removed in", "default is true type: bool recreate: description: - Use with", "namespace using the supplied mapping. type: str group_add: description: -", "the -m (--memory) flag. The swap LIMIT should always be", "i.split(\"=\")[1] for i in env_before} after = before.copy() if self.params['env']:", "init: description: - Run an init inside the container that", "self.info['hostconfig']['extrahosts']]) else: before = {} after = self.params['etc_hosts'] return self._diff_update_and_compare('etc_hosts',", "self.module.params[p] not in [{}, [], '']: different = True return", "def diffparam_device_write_iops(self): before = self.info['hostconfig']['blkiodevicewriteiops'] or [] before = [\"%s:%s\"", "cmd] def check_version(self, param, minv=None, maxv=None): if minv and LooseVersion(minv)", "stopped(self): \"\"\"Return True if container exists and is not running", "before = self.info['hostconfig']['cpushares'] after = self.params['cpu_shares'] return self._diff_update_and_compare('cpu_shares', before, after)", "addparam_gidmap(self, c): return c + ['--gidmap', self.params['gidmap']] def addparam_group_add(self, c):", "after) def diffparam_device_write_bps(self): before = self.info['hostconfig']['blkiodevicewritebps'] or [] before =", "omit the unit, the system uses bytes. If you omit", "dev in self.params['device_read_bps']: c += ['--device-read-bps', dev] return c def", "[self.info['hostconfig']['networkmode']] after = self.params['network'] return self._diff_update_and_compare('network', before, after) def diffparam_no_hosts(self):", "sorted(list(set(after))) return self._diff_update_and_compare('device_write_iops', before, after) # Limited idempotency, it can't", "of capabilities to add to the container. type: list elements:", "restart of container. type: bool default: False aliases: - restart", "c): for exp in self.params['expose']: c += ['--expose', exp] return", "The format is key value, multiple times. type: dict authfile:", "kernel to restrict the container's Real Time CPU usage to", "self.info['hostconfig']['pidmode'] after = self.params['pid'] return self._diff_update_and_compare('pid', before, after) def diffparam_rm(self):", "workdir: description: - Working directory inside the container. The default", "True # Check non idempotent parameters for p in self.non_idempotent:", "(or image name) and tag used to create the container.", "after = self.params['workdir'] return self._diff_update_and_compare('workdir', before, after) def is_different(self): diff_func_list", "), supports_check_mode=True, ) # work on input vars if module.params['state']", "any provided configuration parameters. If no container matches the name,", "\" \"please contact maintainers ASAP!\") def main(): module = AnsibleModule(", "\"8080:9000\" - \"127.0.0.1:8081:9001/udp\" env: SECRET_KEY: \"ssssh\" BOOLEAN_KEY: \"yes\" - name:", "def diffparam_cap_drop(self): before = self.info['effectivecaps'] or [] after = before[:]", "description: - Mount the container's root filesystem as read only.", "new user namespace using the map with 'name' in the", "\"IsInfra\": false, \"LogPath\": \"/tmp/container/mycontainer.json\", \"MountLabel\": \"system_u:object_r:container_file_t:s0:c282,c782\", \"Mounts\": [ ... ],", "variables in container. Defaults to false. type: bool etc_hosts: description:", "before = [\"%s:%s\" % (i['path'], i['rate']) for i in before]", "self.container.stop() self.results['actions'].append('stopped %s' % self.container.name) self.update_container_result() def make_absent(self): \"\"\"Run actions", "['--cpu-rt-runtime', self.params['cpu_rt_runtime']] def addparam_cpu_shares(self, c): return c + ['--cpu-shares', self.params['cpu_shares']]", "microseconds. This flag tells the kernel to limit the amount", "['--subuidname', self.params['subuidname']] def addparam_sysctl(self, c): for sysctl in self.params['sysctl'].items(): c", "addparam_uts(self, c): return c + ['--uts', self.params['uts']] def addparam_volume(self, c):", "return c + ['--mount', self.params['mount']] def addparam_network(self, c): return c", "\"BoundingCaps\": [ \"CAP_CHOWN\", ... ], \"Config\": { \"Annotations\": { \"io.kubernetes.cri-o.ContainerType\":", "true, the first argument refers to an exploded container on", "self.params['cidfile']] def addparam_conmon_pidfile(self, c): return c + ['--conmon-pidfile', self.params['conmon_pidfile']] def", "per second) to a device (e.g. device-write-iops /dev/sda:1000) type: list", "+ ['--cgroupns=%s' % self.params['cgroupns']] def addparam_cgroup_parent(self, c): return c +", "0, \"cpu_rt_period\": 0, \"cpuset_cpus\": \"\", \"cpuset_mems\": \"\", \"detach\": True, \"device\":", "type: dict tty: description: - Allocate a pseudo-TTY. The default", "after.update(self.params['annotation']) return self._diff_update_and_compare('annotation', before, after) def diffparam_env_host(self): # It's impossible", "path is not absolute, the path is considered to be", "description: - CPUs in which to allow execution (0-3, 0,1)", "false, \"Error\": \"\", \"ExitCode\": 0, \"FinishedAt\": \"2019-06-17T19:13:10.157518963+03:00\", \"Healthcheck\": { \"FailingStreak\":", "Set the PID mode for the container type: str pids_limit:", "= self.params['cpuset_cpus'] return self._diff_update_and_compare('cpuset_cpus', before, after) def diffparam_cpuset_mems(self): before =", "\"\", \"cpuset_mems\": \"\", \"detach\": True, \"device\": [], \"env_host\": False, \"etc_hosts\":", "i.lower() for i in self.module.params['cap_drop']]: if c in after: after.remove(c)", "def main(): module = AnsibleModule( argument_spec=yaml.safe_load(DOCUMENTATION)['options'], mutually_exclusive=( ['no_hosts', 'etc_hosts'], ),", "= self.info['hostconfig']['volumesfrom'] or [] after = self.params['volumes_from'] or [] return", "C(podman) default: 'podman' type: str state: description: - I(absent) -", "self.params['device']: c += ['--device', dev] return c def addparam_device_read_bps(self, c):", "is <number><unit>. number must be greater than 0. Unit is", "type: str memory_reservation: description: - Memory soft limit (format 100m,", "key is a list of 2 items where the first", "inside the container. type: str http_proxy: description: - By default", "if not attached. The default is false. type: bool ip:", "the container is not joining another container's network namespace via", "def addparam_detach(self, c): return c + ['--detach=%s' % self.params['detach']] def", "sorted(list(set(after))) return self._diff_update_and_compare('security_opt', before, after) def diffparam_stop_signal(self): before = self.info['config']['stopsignal']", "def addparam_device_read_iops(self, c): for dev in self.params['device_read_iops']: c += ['--device-read-iops',", "(--memory) flag. The swap LIMIT should always be larger than", "except in compliance with the License. You may obtain #", "are part of the registered vars since Ansible 2.8. For", "self._diff_update_and_compare('user', before, after) def diffparam_uts(self): before = self.info['hostconfig']['utsmode'] after =", "its current state \"\"\" def __init__(self, module, name): \"\"\"Initialize PodmanContainer", "True return self._diff_update_and_compare('no_hosts', before, after) def diffparam_oom_score_adj(self): before = self.info['hostconfig']['oomscoreadj']", "file. Default is ``${XDG_RUNTIME_DIR}/containers/auth.json`` (Not available for remote commands) You", "guess } def defaultize(self): params_with_defaults = {} self.default_dict = PodmanDefaults(", "parameters at runtime type: dict systemd: description: - Run container", "self.params['volume']: if vol: c += ['--volume', vol] return c def", "If you omit the size entirely, the system uses 64m", "CPUs in which to allow execution (0-3, 0,1) type: str", "int pid: description: - Set the PID mode for the", "before = before.split(\"/\")[-1] after = after.split(\"/\")[-1] return self._diff_update_and_compare('image', before, after)", "TODO(sshnaidm): to inspect image to get the default command if", "[\":\".join(v.split(\":\")[:2]) for v in self.params['volume']] before, after = sorted(list(set(before))), sorted(list(set(after)))", "limit (format 100m, where unit = b, k, m or", "= sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('cap_add', before, after) def diffparam_cap_drop(self): before", "map with 'name' in the /etc/subgid file. type: str subuidname:", "even if not attached. The default is false. When set", "+ ['--read-only=%s' % self.params['read_only']] def addparam_read_only_tmpfs(self, c): return c +", "c + ['--cgroup-parent', self.params['cgroup_parent']] def addparam_cidfile(self, c): return c +", "done \"\"\" image_actions = [] module_exec = module.params['executable'] if not", "and \\ not module.params['image']: module.fail_json(msg=\"State '%s' required image to be", "def addparam_image_volume(self, c): return c + ['--image-volume', self.params['image_volume']] def addparam_init(self,", "stderr=err) def run(self): \"\"\"Run the container.\"\"\" self._perform_action('run') def delete(self): \"\"\"Delete", "case versions of those. Defaults to true type: bool image_volume:", "\"new:\" type: str privileged: description: - Give extended privileges to", "= self.info['logpath'] if self.module.params['log_opt'] in [None, '']: after = before", "running binaries within a container is the root directory (/).", "elements: str shm_size: description: - Size of /dev/shm. The format", "return c + ['--cgroup-parent', self.params['cgroup_parent']] def addparam_cidfile(self, c): return c", "def addparam_detach_keys(self, c): return c + ['--detach-keys', self.params['detach_keys']] def addparam_device(self,", "+ \"\\n\" self.diff['after'] = \"\\n\".join( [\"%s - %s\" % (k,", "provided configuration parameters. If no container matches the name, a", "the host interfaces. The default is false. type: bool read_only:", "The format is <number><unit>. number must be greater than 0.", "is ``${XDG_RUNTIME_DIR}/containers/auth.json`` (Not available for remote commands) You can also", "container will be created. If a container matches the name", "self.info['config']['cmd'] after = self.params['command'] if isinstance(after, str): after = [i.lower()", "self.info['logpath'] if self.module.params['log_opt'] in [None, '']: after = before else:", "specific language governing permissions and limitations # under the License.", "cpus: description: - Number of CPUs. The default is 0.0", "# not use this file except in compliance with the", "addparam_init_path(self, c): return c + ['--init-path', self.params['init_path']] def addparam_interactive(self, c):", "when containers exit. Restart policy will not take effect if", "no_proxy, and also the upper case versions of those. Defaults", "in self.info['hostconfig']: before = self.info['hostconfig']['cgroups'] after = self.params['cgroups'] return self._diff_update_and_compare('cgroups',", "- name: Stop a container podman_container: name: mycontainer state: stopped", "bool aliases: - remove rootfs: description: - If true, the", "before = self.info['hostconfig']['oomscoreadj'] after = self.params['oom_score_adj'] return self._diff_update_and_compare('oom_score_adj', before, after)", "effective on NUMA systems. type: str detach: description: - Run", "['--conmon-pidfile', self.params['conmon_pidfile']] def addparam_cpu_period(self, c): return c + ['--cpu-period', self.params['cpu_period']]", "= self.info['config']['healthcheck']['test'][1] else: before = '' after = self.params['healthcheck'] or", "2) return self._diff_update_and_compare('memory_swap', before, after) def diffparam_memory_reservation(self): before = str(self.info['hostconfig']['memoryreservation'])", "Note - idempotency is supported for integers only. type: str", "diffparam_device_read_bps(self): before = self.info['hostconfig']['blkiodevicereadbps'] or [] before = [\"%s:%s\" %", "it to a stopped state. type: str default: started choices:", "str cap_drop: description: - List of capabilities to drop from", "- Return additional information which can be helpful for investigations.", "= self.params['blkio_weight_device'] return self._diff_update_and_compare('blkio_weight_device', before, after) def diffparam_cap_add(self): before =", "\".join([self.module.params['executable']] + [to_native(i) for i in b_command]) self.module.log(\"PODMAN-CONTAINER-DEBUG: %s\" %", "str cpuset_cpus: description: - CPUs in which to allow execution", "elements: str cap_drop: description: - List of capabilities to drop", "the PODMAN_USERNS environment variable. An empty value means user namespaces", "def diffparam_cpuset_cpus(self): before = self.info['hostconfig']['cpusetcpus'] after = self.params['cpuset_cpus'] return self._diff_update_and_compare('cpuset_cpus',", "\"yes\" - name: Container present podman_container: name: mycontainer state: present", "\"\"\" b_command = PodmanModuleParams(action, self.module.params, self.version, self.module, ).construct_command_from_params() full_cmd =", "- Set custom DNS servers type: list elements: str dns_option:", "the optional max_retries count is hit * always - Restart", "name: mydata image: busybox volume: - /tmp/data - name: Re-create", "+ ['--sig-proxy=%s' % self.params['sig_proxy']] def addparam_stop_signal(self, c): return c +", "Keyword Arguments: changed {bool} -- whether any action was performed", "type: bool default: False aliases: - restart gidmap: description: -", "cap_add in self.params['cap_add']: c += ['--cap-add', cap_add] return c def", "== 'delete': cmd = ['rm', '-f', self.params['name']] return [to_bytes(i, errors='surrogate_or_strict')", "def addparam_annotation(self, c): for annotate in self.params['annotation'].items(): c += ['--annotation',", "matches the name, a container will be created and started.", "period in microseconds type: int cpu_rt_period: description: - Limit the", "\",\".join(self.params['network'])] def addparam_no_hosts(self, c): return c + ['--no-hosts=%s' % self.params['no_hosts']]", "= self.info['hostconfig']['blkioweight'] after = self.params['blkio_weight'] return self._diff_update_and_compare('blkio_weight', before, after) def", "logic error happened, \" \"please contact maintainers ASAP!\") def main():", "container. type: dict env_file: description: - Read in a line", "\"workdir\": \"/\", } def default_dict(self): # make here any changes", "the second one is the actual healthcheck command. before =", "systemd: description: - Run container in systemd mode. The default", "= self.params['env_host'] return self._diff_update_and_compare('env_host', before, after) def diffparam_blkio_weight(self): before =", "# It's impossible to get from inspest, recreate it if", "count=4 - name: remove container podman_container: name: ohno state: absent", "elements: str workdir: description: - Working directory inside the container.", "not self.module.check_mode: rc, out, err = self.module.run_command( [self.module.params['executable'], b'container'] +", "volume /HOST-DIR:/CONTAINER-DIR, podman bind mounts /HOST-DIR in the host to", "of the container. type: dict env_file: description: - Read in", "forwards signals and reaps processes. type: str init_path: description: -", "'' self.info = self.get_info() self.version = self._get_podman_version() self.diff = {}", "return c + ['--read-only=%s' % self.params['read_only']] def addparam_read_only_tmpfs(self, c): return", "description: - Any additionl command options you want to pass", "REGISTRY_AUTH_FILE=path`` type: path blkio_weight: description: - Block IO weight (relative", "description: - Run an init inside the container that forwards", "fact will be removed in Ansible 2.12. - Empty if", "it is not in the C($PATH) on the machine running", "is not found, the image will be pulled from the", "+ ['--cpu-rt-period', self.params['cpu_rt_period']] def addparam_cpu_rt_runtime(self, c): return c + ['--cpu-rt-runtime',", "before, after) def diffparam_cpu_shares(self): before = self.info['hostconfig']['cpushares'] after = self.params['cpu_shares']", "the container.\"\"\" self._perform_action('delete') def stop(self): \"\"\"Stop the container.\"\"\" self._perform_action('stop') def", "self._diff_update_and_compare('annotation', before, after) def diffparam_env_host(self): # It's impossible to get", "c def addparam_volumes_from(self, c): for vol in self.params['volumes_from']: c +=", "c): if self.params['rm']: c += ['--rm'] return c def addparam_rootfs(self,", "so this is necessary when using systemd to restart Podman", "return self._diff_update_and_compare('device_read_iops', before, after) def diffparam_device_write_bps(self): before = self.info['hostconfig']['blkiodevicewritebps'] or", "= b, k, m or g) Note - idempotency is", "or not mode: # In a idempotency 'lite mode' assume", "['--blkio-weight', self.params['blkio_weight']] def addparam_blkio_weight_device(self, c): for blkio in self.params['blkio_weight_device'].items(): c", "% full_cmd) self.actions.append(full_cmd) if not self.module.check_mode: rc, out, err =", "file of environment variables type: path env_host: description: - Use", "false, \"StartedAt\": \"2019-06-17T19:13:10.152479729+03:00\", \"Status\": \"exited\" }, \"StaticDir\": \"...\" ... }'", "the container required: True type: str executable: description: - Path", "before = dict([i.split(\":\") for i in self.info['hostconfig']['extrahosts']]) else: before =", "before, after) def is_different(self): diff_func_list = [func for func in", "description: - Ulimit options type: list user: description: - Sets", "+ ['--oom-kill-disable=%s' % self.params['oom_kill_disable']] def addparam_oom_score_adj(self, c): return c +", "keep stdin open even if not attached. The default is", "elif self.container.exists: self.container.delete() self.results['actions'].append('deleted %s' % self.container.name) self.results.update({'changed': True}) self.results.update({'container':", "unhealthy. The default value is 3. type: int healthcheck_start_period: description:", "container on the file system. The dafault is false. type:", "self._diff_update_and_compare('conmon_pidfile', before, after) def diffparam_cpu_period(self): before = self.info['hostconfig']['cpuperiod'] after =", "- Read in a line delimited file of labels type:", "type: int cpu_shares: description: - CPU shares (relative weight) type:", "no - Do not restart containers on exit * on-failure[:max_retries]", "after = self.params['privileged'] return self._diff_update_and_compare('privileged', before, after) def diffparam_pid(self): before", "for the process that will be launched inside of the", "self.info['config']['stopsignal'] after = self.params['stop_signal'] return self._diff_update_and_compare('stop_signal', before, after) def diffparam_tty(self):", "before = self.info['hostconfig']['cpusetcpus'] after = self.params['cpuset_cpus'] return self._diff_update_and_compare('cpuset_cpus', before, after)", "sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('device_read_iops', before, after) def diffparam_device_write_bps(self): before =", "all images from different registries are the same before =", "\"Tty\": false, \"User\": { \"gid\": 0, \"uid\": 0 }, \"Volumes\":", "after) def diffparam_group_add(self): before = self.info['hostconfig']['groupadd'] after = self.params['group_add'] return", "true type: bool image_volume: description: - Tells podman how to", "\"ExitCommand\": [ \"/usr/bin/podman\", \"--root\", ... ], \"GraphDriver\": { ... },", "['--memory-swap', self.params['memory_swap']] def addparam_memory_swappiness(self, c): return c + ['--memory-swappiness', self.params['memory_swappiness']]", "default is false. type: bool read_only: description: - Mount the", "key sequence for detaching a container. Format is a single", "allowed to complete the healthcheck before an interval is considered", "[\"cap_\" + i.lower() for i in self.module.params['cap_drop']]: if c in", "{ 'present': self.make_started, 'started': self.make_started, 'absent': self.make_absent, 'stopped': self.make_stopped }", "specify arbitrary environment variables that are available for the process", "for the specified command. type: str userns: description: - Set", "writing, software # distributed under the License is distributed on", "\"Name\": \"myservice\", \"Namespace\": \"\", \"NetworkSettings\": { \"Bridge\": \"\", ... },", "and before: after = before else: after = self.params['user'] return", "container if set for the podman process. This can be", "%s\" % image) return image_actions class PodmanContainer: \"\"\"Perform container tasks.", "before, after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('cap_add', before, after) def", "= self.params['cpu_rt_runtime'] return self._diff_update_and_compare('cpu_rt_runtime', before, after) def diffparam_cpu_shares(self): before =", "self.default_dict: params_with_defaults[p] = self.default_dict[p] else: params_with_defaults[p] = self.module.params[p] return params_with_defaults", "self.params['cidfile'] return self._diff_update_and_compare('cidfile', before, after) def diffparam_command(self): # TODO(sshnaidm): to", "{i.split(\"=\")[0]: i.split(\"=\")[1] for i in env_before} after = before.copy() if", "% self.params['cgroupns']] def addparam_cgroup_parent(self, c): return c + ['--cgroup-parent', self.params['cgroup_parent']]", "of labels type: str log_driver: description: - Logging driver. Used", "to set the log driver for the container. For example", "For example log_driver \"k8s-file\". type: str choices: - k8s-file -", "str(self.info['hostconfig']['memoryswap']) after = self.params['memory_swap'] if (self.module.params['memory_swap'] is None and self.params['memory']", "b_command = PodmanModuleParams(action, self.module.params, self.version, self.module, ).construct_command_from_params() full_cmd = \"", "restart_policy: \"no\" device: \"/dev/sda:/dev/xvda:rwm\" ports: - \"8080:9000\" - \"127.0.0.1:8081:9001/udp\" env:", "info about it.\"\"\" rc, out, err = self.module.run_command( [self.module.params['executable'], b'container',", "Force restart of container. type: bool default: False aliases: -", "should always be larger than -m (--memory) value. By default,", "to run as type: list healthcheck: description: - Set or", "noqa: E501 from __future__ import absolute_import, division, print_function __metaclass__ =", "list elements: str workdir: description: - Working directory inside the", "def diffparam_volumes_from(self): before = self.info['hostconfig']['volumesfrom'] or [] after = self.params['volumes_from']", "be expressed in a time format such as 1m22s. The", "containers podman_container: name: \"container{{ item }}\" recreate: yes image: someuser/anotherappimage", "exits. The default is false. type: bool aliases: - remove", "refers to an exploded container on the file system. The", "versions of those. Defaults to true type: bool image_volume: description:", "supplied mapping. type: str group_add: description: - Add additional groups", "str sysctl: description: - Configure namespaced kernel parameters at runtime", "container will create CGroups. Valid values are enabled and disabled,", "def running(self): \"\"\"Return True if container is running now.\"\"\" return", "addparam_rm(self, c): if self.params['rm']: c += ['--rm'] return c def", "delete(self): \"\"\"Delete the container.\"\"\" self._perform_action('delete') def stop(self): \"\"\"Stop the container.\"\"\"", "%s' % self.container.name) self.results.update({'changed': True}) self.results.update({'container': {}, 'podman_actions': self.container.actions}) self.module.exit_json(**self.results)", "before = self.info['config']['stopsignal'] after = self.params['stop_signal'] return self._diff_update_and_compare('stop_signal', before, after)", "parameter before = str(self.info['hostconfig']['memoryswap']) after = self.params['memory_swap'] if (self.module.params['memory_swap'] is", "+ ['--pod', self.params['pod']] def addparam_privileged(self, c): return c + ['--privileged=%s'", "v in sorted( diffs['after'].items())]) + \"\\n\" return is_different @property def", "- Add an annotation to the container. The format is", "variables. This option allows you to specify arbitrary environment variables", "+= ['--device-read-iops', dev] return c def addparam_device_write_bps(self, c): for dev", "{obj} -- ansible module object image {str} -- name of", "matching the name and any provided configuration. If no container", "diffparam_cap_drop(self): before = self.info['effectivecaps'] or [] after = before[:] if", "out, err = self.module.run_command( [self.module.params['executable'], b'--version']) if rc != 0", "before, after) def diffparam_device_read_iops(self): before = self.info['hostconfig']['blkiodevicereadiops'] or [] before", "bool default: False detach_keys: description: - Override the key sequence", "disable results in no automatic timer setup) (default \"30s\") type:", "mapping. type: list ulimit: description: - Ulimit options type: list", "for remote commands) You can also override the default path", "before, after) def diffparam_pid(self): before = self.info['hostconfig']['pidmode'] after = self.params['pid']", "interactive: description: - Keep STDIN open even if not attached.", "k, v in sorted( diffs['after'].items())]) + \"\\n\" return is_different @property", "addparam_cap_drop(self, c): for cap_drop in self.params['cap_drop']: c += ['--cap-drop', cap_drop]", "callable(getattr(self, func)) and func.startswith(\"addparam\")] params_set = (i for i in", "stdout=out, stderr=err) if self.container.diff: self.results.update({'diff': self.container.diff}) if self.module.params['debug']: self.results.update({'podman_version': self.container.version})", "* on-failure[:max_retries] - Restart containers when they exit with a", "as C(podman_container). Note that the returned fact will be removed", "assume all images from different registries are the same before", "self.container.different: if self.restart: self.container.restart() self.results['actions'].append('restarted %s' % self.container.name) self.update_container_result() self.update_container_result(changed=False)", "can be expressed in time format like 2m3s. The default", "+ ['--log-driver', self.params['log_driver']] def addparam_log_opt(self, c): return c + ['--log-opt',", "running in --read-only mode, then mount a read-write tmpfs on", "def addparam_pid(self, c): return c + ['--pid', self.params['pid']] def addparam_pids_limit(self,", "diffparam_user(self): before = self.info['config']['user'] if self.module.params['user'] is None and before:", "out or \"version\" not in out: self.module.fail_json(msg=\"%s run failed!\" %", "Limited idempotency, it can't guess default values def diffparam_env(self): env_before", "container. It defaults to the PODMAN_USERNS environment variable. An empty", "self.name) def update_container_result(self, changed=True): \"\"\"Inspect the current container, update results", "container's ``/etc/hosts`` file. type: dict aliases: - add_hosts expose: description:", "taken into account when comparing configuration. Use the recreate option", "if self.container.running and \\ (self.container.different or self.recreate): self.container.recreate() self.results['actions'].append('recreated %s'", "def execute(self): \"\"\"Execute the desired action according to map of", "container's Real Time CPU usage. This flag tell the kernel", "\"sandbox\", \"io.kubernetes.cri-o.TTY\": \"false\" }, \"AttachStderr\": false, \"AttachStdin\": false, \"AttachStdout\": false,", "\"Labels\": null, \"OpenStdin\": false, \"StdinOnce\": false, \"StopSignal\": 15, \"Tty\": false,", "list healthcheck: description: - Set or alter a healthcheck command", "# Because of hostname is random generated, this parameter has", "module.fail_json(msg=\"State '%s' required image to be configured!\" % module.params['state']) PodmanManager(module).execute()", "c): return c + ['--memory-reservation', self.params['memory_reservation']] def addparam_memory_swap(self, c): return", "till podman \" \"version %s only! Current version is %s\"", "[] return self._diff_update_and_compare('volumes_from', before, after) def diffparam_workdir(self): before = self.info['config']['workingdir']", "self._diff_update_and_compare('uts', before, after) def diffparam_volume(self): before = self.info['mounts'] if before:", "create a network stack on the default bridge * none", "str conmon_pidfile: description: - Write the pid of the conmon", "c + ['--cpuset-cpus', self.params['cpuset_cpus']] def addparam_cpuset_mems(self, c): return c +", "Set an interval for the healthchecks (a value of disable", "\"system_u:object_r:container_file_t:s0:c282,c782\", \"Mounts\": [ ... ], \"Name\": \"myservice\", \"Namespace\": \"\", \"NetworkSettings\":", "err = self.module.run_command( [self.module.params['executable'], b'--version']) if rc != 0 or", "self.update_container_result() self.update_container_result(changed=False) elif not self.container.exists: self.container.run() self.results['actions'].append('started %s' % self.container.name)", "the default ENTRYPOINT of the image type: str env: description:", "diffparam_ipc(self): before = self.info['hostconfig']['ipcmode'] after = self.params['ipc'] return self._diff_update_and_compare('ipc', before,", "before = self.info['hostconfig']['blkioweightdevice'] if before == [] and self.module.params['blkio_weight_device'] is", "created. If the path is not absolute, the path is", "return self._diff_update_and_compare('cap_drop', before, after) def diffparam_cgroup_parent(self): before = self.info['hostconfig']['cgroupparent'] after", "gidmap: description: - Run the container in a new user", "can be expressed in a time format such as 1m22s.", "nodes (MEMs) in which to allow execution (0-3, 0,1). Only", "default for rootless containers type: list elements: str aliases: -", "with the -m (--memory) flag. The swap LIMIT should always", "If it cannot be updated, it will be removed and", "the registered vars since Ansible 2.8. For compatibility reasons, the", "Rights Reserved. # # Licensed under the Apache License, Version", "return self._diff_update_and_compare('cpuset_mems', before, after) def diffparam_device(self): before = [\":\".join([i['pathonhost'], i['pathincontainer']])", "different(self): \"\"\"Check if container is different.\"\"\" diffcheck = PodmanContainerDiff(self.module, self.info,", "path of the authentication file by setting the ``REGISTRY_AUTH_FILE`` environment", "supported for integers only. type: str memory_reservation: description: - Memory", "type: str ipc: description: - Default is to create a", "\"2019-06-17T19:13:09.873858307+03:00\", \"Dependencies\": [], \"Driver\": \"overlay\", \"EffectiveCaps\": [ \"CAP_CHOWN\", ... ],", "return self._diff_update_and_compare('cpu_period', before, after) def diffparam_cpu_rt_period(self): before = self.info['hostconfig']['cpurealtimeperiod'] after", "return c def addparam_env_file(self, c): return c + ['--env-file', self.params['env_file']]", "mutually_exclusive=( ['no_hosts', 'etc_hosts'], ), supports_check_mode=True, ) # work on input", "volume: - /tmp/data - name: Re-create a redis container podman_container:", "log_opt \"path=/var/log/container/mycontainer.json\" type: str aliases: - log_options memory: description: -", "ports to random ports on the host interfaces. The default", "kernel_memory: description: - Kernel memory limit (format <number>[<unit>], where unit", "Defaults depend on user and platform, impossible to guess }", "within a container is the root directory (/). type: str", "PodmanManager: \"\"\"Module manager class. Defines according to parameters what actions", "if desired state is 'stopped'.\"\"\" if not self.container.exists and not", "before, after) def diffparam_no_hosts(self): before = not bool(self.info['hostspath']) after =", "path cmd_args: description: - Any additionl command options you want", "choices: - 'bind' - 'tmpfs' - 'ignore' image_strict: description: -", "/ 1000000000 after = self.params['cpus'] return self._diff_update_and_compare('cpus', before, after) def", "cpu_rt_period: description: - Limit the CPU real-time period in microseconds.", "(e.g. device-write-iops /dev/sda:1000) type: list dns: description: - Set custom", "diffparam_cpuset_cpus(self): before = self.info['hostconfig']['cpusetcpus'] after = self.params['cpuset_cpus'] return self._diff_update_and_compare('cpuset_cpus', before,", "c + ['--restart=%s' % self.params['restart_policy']] def addparam_rm(self, c): if self.params['rm']:", "don't wish to set the search domain) type: str entrypoint:", "an integer between 0 and 100. type: int mount: description:", "diffparam_blkio_weight_device(self): before = self.info['hostconfig']['blkioweightdevice'] if before == [] and self.module.params['blkio_weight_device']", "Podman, so this is necessary when using systemd to restart", "self.start_stop_delete() if self.action in ['create', 'run']: cmd = [self.action, '--name',", "module object \"\"\" super(PodmanManager, self).__init__() self.module = module self.results =", "str aliases: - volumes volumes_from: description: - Mount volumes from", "def diffparam_user(self): before = self.info['config']['user'] if self.module.params['user'] is None and", "pids for the container. type: str pod: description: - Run", "list elements: str aliases: - net no_hosts: description: - Do", "c): return c + ['--rootfs=%s' % self.params['rootfs']] def addparam_security_opt(self, c):", "k8s-file - journald - json-file log_opt: description: - Logging driver", "rm: description: - Automatically remove the container when it exits.", "the pid of the conmon process to a file. conmon", "% self.container.name) self.update_container_result() def make_stopped(self): \"\"\"Run actions if desired state", "self._diff_update_and_compare('env_host', before, after) def diffparam_blkio_weight(self): before = self.info['hostconfig']['blkioweight'] after =", "container.\"\"\" self.delete() self.run() def restart(self): \"\"\"Restart the container.\"\"\" self.stop() self.run()", "k in sysctl])] return c def addparam_systemd(self, c): return c", "{ \"io.kubernetes.cri-o.ContainerType\": \"sandbox\", \"io.kubernetes.cri-o.TTY\": \"false\" }, \"AttachStderr\": false, \"AttachStdin\": false,", "2.12. - Empty if C(state) is I(absent). returned: always type:", "def __init__(self, module, info, podman_version): self.module = module self.version =", "driver specific options. Used to set the path to the", "self.module.params['cap_drop'] is not None: for c in [\"cap_\" + i.lower()", "is not None: before = self.info['config']['cmd'] after = self.params['command'] if", "to handle the builtin image volumes. The options are bind,", "/var/tmp. The default is true type: bool recreate: description: -", "before return self._diff_update_and_compare('hostname', before, after) def diffparam_image(self): # TODO(sshnaidm): for", "= self.params['oom_score_adj'] return self._diff_update_and_compare('oom_score_adj', before, after) def diffparam_privileged(self): before =", "description: - Name of the container required: True type: str", "containers on exit * on-failure[:max_retries] - Restart containers when they", "via 'network container:<name|id>'. The address must be within the default", "start-period, the value can be expressed in a time format", "option to false. The environment variables passed in include http_proxy,", "read only. Default is false type: bool read_only_tmpfs: description: -", "= '' after = self.params['healthcheck'] or before return self._diff_update_and_compare('healthcheck', before,", "\"Running\": false, \"StartedAt\": \"2019-06-17T19:13:10.152479729+03:00\", \"Status\": \"exited\" }, \"StaticDir\": \"...\" ...", "description: - Allocate a pseudo-TTY. The default is false. type:", "containerPort type: list elements: str aliases: - ports - published", "= [\":\".join([i['pathonhost'], i['pathincontainer']]) for i in self.info['hostconfig']['devices']] after = [\":\".join(i.split(\":\")[:2])", "to bootstrap. The value can be expressed in time format", "in all_param_methods: cmd = getattr(self, func_name)(cmd) cmd.append(self.params['image']) if self.params['command']: if", "weight (relative weight) accepts a weight value between 10 and", "do not already exist. type: path cgroupns: description: - Path", "configuration parameters. If no container matches the name, a container", "\"\"\" image_actions = [] module_exec = module.params['executable'] if not image:", "to pass to podman command, cmd_args - ['--other-param', 'value'] Be", "then if the container is running moves it to a", "c + ['--healthcheck-interval', self.params['healthcheck_interval']] def addparam_healthcheck_retries(self, c): return c +", "self.info['hostconfig']['cgroups'] after = self.params['cgroups'] return self._diff_update_and_compare('cgroups', before, after) return False", "Be aware module doesn't support idempotency if this is set.", "+ ['--memory', self.params['memory']] def addparam_memory_reservation(self, c): return c + ['--memory-reservation',", "\"sh\" ], \"BoundingCaps\": [ \"CAP_CHOWN\", ... ], \"Config\": { \"Annotations\":", "action according to map of actions & states.\"\"\" states_map =", "facts, 'podman_actions': self.container.actions}, stdout=out, stderr=err) if self.container.diff: self.results.update({'diff': self.container.diff}) if", "Do not restart containers on exit * on-failure[:max_retries] - Restart", "label])] return c def addparam_label_file(self, c): return c + ['--label-file',", "self.params['conmon_pidfile'] return self._diff_update_and_compare('conmon_pidfile', before, after) def diffparam_cpu_period(self): before = self.info['hostconfig']['cpuperiod']", "- Do not create /etc/hosts for the container Default is", "If the path is not absolute, the path is considered", "value is 0s type: str healthcheck_timeout: description: - The maximum", "['none']: after = True return self._diff_update_and_compare('no_hosts', before, after) def diffparam_oom_score_adj(self):", "self.params['tmpfs'].items(): c += ['--tmpfs', ':'.join(tmpfs)] return c def addparam_tty(self, c):", "['--blkio-weight-device', ':'.join(blkio)] return c def addparam_cap_add(self, c): for cap_add in", "The default is true. type: bool tmpfs: description: - Create", "return self._diff_update_and_compare('stop_signal', before, after) def diffparam_tty(self): before = self.info['config']['tty'] after", "def diffparam_cgroup_parent(self): before = self.info['hostconfig']['cgroupparent'] after = self.params['cgroup_parent'] return self._diff_update_and_compare('cgroup_parent',", "tmpfs \"/tmp\" \"rw,size=787448k,mode=1777\" type: dict tty: description: - Allocate a", "choices: - default - disabled cidfile: description: - Write the", "pool (default 10.88.0.0/16). type: str ipc: description: - Default is", "to stop a container. Default is SIGTERM. type: int stop_timeout:", "after.replace(\":latest\", \"\") before = before.split(\"/\")[-1] after = after.split(\"/\")[-1] return self._diff_update_and_compare('image',", "c + ['--detach-keys', self.params['detach_keys']] def addparam_device(self, c): for dev in", "\"127.0.0.1:8081:9001/udp\" env: SECRET_KEY: \"ssssh\" BOOLEAN_KEY: \"yes\" - name: Container present", "self.podman_version): self.module.fail_json(msg=\"Parameter %s is supported from podman \" \"version %s", "Asserts that the container is first I(present), and then if", "\"...\" ... }' \"\"\" class PodmanModuleParams: \"\"\"Creates list of arguments", "diffparam_privileged(self): before = self.info['hostconfig']['privileged'] after = self.params['privileged'] return self._diff_update_and_compare('privileged', before,", "is false type: bool read_only_tmpfs: description: - If container is", "- Keep STDIN open even if not attached. The default", "description: - Configure namespaced kernel parameters at runtime type: dict", "directory inside the container. The default working directory for running", "not. Default is false. type: bool oom_score_adj: description: - Tune", "An empty value means user namespaces are disabled. type: str", "is true. type: bool tmpfs: description: - Create a tmpfs", "self.restart = self.module.params['force_restart'] self.recreate = self.module.params['recreate'] self.container = PodmanContainer(self.module, self.name)", "def addparam_healthcheck_interval(self, c): return c + ['--healthcheck-interval', self.params['healthcheck_interval']] def addparam_healthcheck_retries(self,", "- default - disabled cidfile: description: - Write the container", "retrying indefinitely type: str rm: description: - Automatically remove the", "Used to set the path to the container log file.", "rc == 0 else {} def _get_podman_version(self): rc, out, err", "to C(podman) executable if it is not in the C($PATH)", "commands. Valid values are * no - Do not restart", "elif isinstance(after, list): after = [i.lower() for i in after]", "diffcheck.is_different() diffs = diffcheck.diff if self.module._diff and is_different and diffs['before']", "secopt in self.params['security_opt']: c += ['--security-opt', secopt] return c def", "and started states to force the re-creation of an existing", "0s type: str healthcheck_timeout: description: - The maximum time allowed", "greater than 0. Unit is optional and can be b", "type: path env_host: description: - Use all current host environment", "container's port, or range of ports, to the host. Format", "+ ['--restart=%s' % self.params['restart_policy']] def addparam_rm(self, c): if self.params['rm']: c", "null, \"OpenStdin\": false, \"StdinOnce\": false, \"StopSignal\": 15, \"Tty\": false, \"User\":", "= self.module.params['state'] self.restart = self.module.params['force_restart'] self.recreate = self.module.params['recreate'] self.container =", "not bool(self.info['hostspath']) after = self.params['no_hosts'] if self.params['network'] == ['none']: after", "list device_read_iops: description: - Limit read rate (IO per second)", "namespace mode for the container. It defaults to the PODMAN_USERNS", "image_actions = ensure_image_exists(self.module, self.image) self.results['actions'] += image_actions self.state = self.module.params['state']", "[] for m in before: if m['type'] == 'volume': volumes.append([m['name'],", "= sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('devices', before, after) def diffparam_device_read_bps(self): before", "Restart a container podman_container: name: myapplication image: redis state: started", "Current version is %s\" % ( param, minv, self.podman_version)) def", "the container. If an image is not found, the image", "return self._diff_update_and_compare('device_write_bps', before, after) def diffparam_device_write_iops(self): before = self.info['hostconfig']['blkiodevicewriteiops'] or", "c): return c + ['--memory-swap', self.params['memory_swap']] def addparam_memory_swappiness(self, c): return", "in env_before} after = before.copy() if self.params['env']: after.update({ str(k).lower(): str(v).lower()", "not supported in all versions if 'cgroups' in self.info['hostconfig']: before", "class. Defines according to parameters what actions should be applied", "in self.params['cap_add']: c += ['--cap-add', cap_add] return c def addparam_cap_drop(self,", "before, after) def diffparam_etc_hosts(self): if self.info['hostconfig']['extrahosts']: before = dict([i.split(\":\") for", "return c def addparam_systemd(self, c): return c + ['--systemd=%s' %", "- /tmp/data - name: Re-create a redis container podman_container: name:", "c def addparam_healthcheck(self, c): return c + ['--healthcheck-command', self.params['healthcheck']] def", "self.params['ulimit']: c += ['--ulimit', u] return c def addparam_user(self, c):", "self.params['env_file']] def addparam_env_host(self, c): self.check_version('--env-host', minv='1.5.0') return c + ['--env-host=%s'", "is random generated, this parameter has partial idempotency only. def", "ID to the file type: path cmd_args: description: - Any", "... ], \"Name\": \"myservice\", \"Namespace\": \"\", \"NetworkSettings\": { \"Bridge\": \"\",", "['--detach=%s' % self.params['detach']] def addparam_detach_keys(self, c): return c + ['--detach-keys',", "different = True # Check non idempotent parameters for p", "a container matches the name but the provided configuration does", "i in cmd] if self.action == 'delete': cmd = ['rm',", "[ \"CAP_CHOWN\", ... ], \"Config\": { \"Annotations\": { \"io.kubernetes.cri-o.ContainerType\": \"sandbox\",", "the C($PATH) on the machine running C(podman) default: 'podman' type:", "['--cgroups=%s' % self.params['cgroups']] def addparam_cgroupns(self, c): self.check_version('--cgroupns', minv='1.6.2') return c", "the podman run command to the container process. SIGCHLD, SIGSTOP,", "root directory (/). type: str \"\"\" EXAMPLES = \"\"\" -", "... }, \"Path\": \"sh\", \"ProcessLabel\": \"system_u:system_r:container_t:s0:c282,c782\", \"ResolvConfPath\": \"...\", \"RestartCount\": 0,", "__metaclass__ = type import json from distutils.version import LooseVersion import", "c + self.params['cmd_args'] class PodmanDefaults: def __init__(self, module, podman_version): self.module", "container type: str kernel_memory: description: - Kernel memory limit (format", "be removed and re-created with the requested config. Image version", "debug: description: - Return additional information which can be helpful", "self.params['pids_limit']] def addparam_pod(self, c): return c + ['--pod', self.params['pod']] def", "mydata image: busybox volume: - /tmp/data - name: Re-create a", "diffparam_rm(self): before = self.info['hostconfig']['autoremove'] after = self.params['rm'] return self._diff_update_and_compare('rm', before,", "not attached. The default is false. type: bool ip: description:", "detach_keys: description: - Override the key sequence for detaching a", "self.params['uts']] def addparam_volume(self, c): for vol in self.params['volume']: if vol:", "specified command. type: str userns: description: - Set the user", "Check non idempotent parameters for p in self.non_idempotent: if self.module.params[p]", "You may obtain # a copy of the License at", "not self.info['State']['Running'] def get_info(self): \"\"\"Inspect container and gather info about", "path env_host: description: - Use all current host environment variables", "matches the name but the provided configuration does not match,", "\"\"\" def __init__(self, module): \"\"\"Initialize PodmanManager class. Arguments: module {obj}", "elements: str aliases: - ports - published - published_ports publish_all:", "device-read-bps /dev/sda:1mb) type: list device_read_iops: description: - Limit read rate", "any changes to self.defaults related to podman version return self.defaults", "SIGSTOP, and SIGKILL are not proxied. The default is true.", "self.params['dns_search']] def addparam_entrypoint(self, c): return c + ['--entrypoint', self.params['entrypoint']] def", "self.results = { 'changed': False, 'actions': [], 'container': {}, }", "in env_value])] return c def addparam_env_file(self, c): return c +", "addparam_cpuset_mems(self, c): return c + ['--cpuset-mems', self.params['cpuset_mems']] def addparam_detach(self, c):", "the podman inspection output. - Note that facts are part", "'cgroups' in self.info['hostconfig']: before = self.info['hostconfig']['cgroups'] after = self.params['cgroups'] return", "CGroups. Valid values are enabled and disabled, which the default", "after = self.params['cidfile'] return self._diff_update_and_compare('cidfile', before, after) def diffparam_command(self): #", "in the podman container. type: list elements: str aliases: -", "the conmon process to a file. conmon runs in a", "\"Entrypoint\": \"\", \"Env\": [ \"PATH=/usr/sbin:/usr/bin:/sbin:/bin\", \"TERM=xterm\", \"HOSTNAME=\", \"container=podman\" ], \"Hostname\":", "return c def addparam_cap_drop(self, c): for cap_drop in self.params['cap_drop']: c", "exit, regardless of status, retrying indefinitely type: str rm: description:", "GID for the specified command. type: str userns: description: -", "self._diff_update_and_compare('rm', before, after) def diffparam_security_opt(self): before = self.info['hostconfig']['securityopt'] after =", "for i in self.info['hostconfig']['devices']] after = [\":\".join(i.split(\":\")[:2]) for i in", "after) def diffparam_cpu_rt_runtime(self): before = self.info['hostconfig']['cpurealtimeruntime'] after = self.params['cpu_rt_runtime'] return", "command def addparam_cmd_args(self, c): return c + self.params['cmd_args'] class PodmanDefaults:", "\"diffparam\")] fail_fast = not bool(self.module._diff) different = False for func_name", "type: str aliases: - log_options memory: description: - Memory limit", "after) def diffparam_ipc(self): before = self.info['hostconfig']['ipcmode'] after = self.params['ipc'] return", "blkio_weight: description: - Block IO weight (relative weight) accepts a", "create CGroups. Valid values are enabled and disabled, which the", "is None and self.params['memory'] != 0 and self.params['memory'].isdigit()): after =", "b'container'] + b_command, expand_user_and_vars=False) self.stdout = out self.stderr = err", "c def addparam_expose(self, c): for exp in self.params['expose']: c +=", "it.\"\"\" rc, out, err = self.module.run_command( [self.module.params['executable'], b'container', b'inspect', self.name])", "bool recreate: description: - Use with present and started states", "pulled or nothing was done \"\"\" image_actions = [] module_exec", "variable. An empty value means user namespaces are disabled. type:", "action type from 'run', 'stop', 'create', 'delete', 'start' params {dict}", "c + ['--cpu-rt-runtime', self.params['cpu_rt_runtime']] def addparam_cpu_shares(self, c): return c +", "elements: str aliases: - net no_hosts: description: - Do not", "to allow execution (0-3, 0,1) type: str cpuset_mems: description: -", "}}\" recreate: yes image: someuser/anotherappimage command: sleep 1d with_sequence: count=4", "values are * no - Do not restart containers on", "of an existing container. type: bool default: False restart_policy: description:", "def diffparam_command(self): # TODO(sshnaidm): to inspect image to get the", "+ self.params['cmd_args'] class PodmanDefaults: def __init__(self, module, podman_version): self.module =", "default is false. type: bool ip: description: - Specify a", "\"/\" }, \"ConmonPidFile\": \"...\", \"Created\": \"2019-06-17T19:13:09.873858307+03:00\", \"Dependencies\": [], \"Driver\": \"overlay\",", "param]) if func_name in all_param_methods: cmd = getattr(self, func_name)(cmd) cmd.append(self.params['image'])", "container %s\" % (action, self.name), stdout=out, stderr=err) def run(self): \"\"\"Run", "in self.params['device_read_bps']: c += ['--device-read-bps', dev] return c def addparam_device_read_iops(self,", "module {obj} -- ansible module object name {str} -- name", "present image: ubuntu:14.04 command: \"sleep 1d\" - name: Stop a", "name with \"new:\" type: str privileged: description: - Give extended", "if a healthcheck # was configured; otherwise the config key", "want to pass to podman command, cmd_args - ['--other-param', 'value']", "absolute, the path is considered to be relative to the", "facts are part of the registered vars since Ansible 2.8.", "before = self.info['hostconfig']['blkiodevicewritebps'] or [] before = [\"%s:%s\" % (i['path'],", "['--sig-proxy=%s' % self.params['sig_proxy']] def addparam_stop_signal(self, c): return c + ['--stop-signal',", "c += ['--cap-drop', cap_drop] return c def addparam_cgroups(self, c): self.check_version('--cgroups',", "diffparam_cgroups(self): # Cgroups output is not supported in all versions", "self.module.params['name'] self.executable = \\ self.module.get_bin_path(self.module.params['executable'], required=True) self.image = self.module.params['image'] image_actions", "regardless of status, retrying indefinitely type: str rm: description: -", "volumes_from: description: - Mount volumes from the specified container(s). type:", "module.run_command([module_exec, 'image', 'pull', image]) if rc != 0: module.fail_json(msg=\"Can't pull", "exploded container on the file system. The dafault is false.", "(e.g. expose \"3300-3310\") to set up port redirection on the", "bind mount. If you specify, volume /HOST-DIR:/CONTAINER-DIR, podman bind mounts", "addparam_stop_timeout(self, c): return c + ['--stop-timeout', self.params['stop_timeout']] def addparam_subgidname(self, c):", "per second) to a device (e.g. device-write-bps /dev/sda:1mb) type: list", "else: after = self.params['log_opt'].split(\"=\")[1] return self._diff_update_and_compare('log_opt', before, after) def diffparam_memory(self):", "cmd += self.params['command'] else: cmd += self.params['command'].split() return [to_bytes(i, errors='surrogate_or_strict')", "only. Default is false type: bool read_only_tmpfs: description: - If", "started states to force the re-creation of an existing container.", "after = before else: after = self.params['conmon_pidfile'] return self._diff_update_and_compare('conmon_pidfile', before,", "c): return c + ['--gidmap', self.params['gidmap']] def addparam_group_add(self, c): for", "= err if rc != 0: self.module.fail_json( msg=\"Can't %s container", "c += ['--volume', vol] return c def addparam_volumes_from(self, c): for", "raw cpu_period: description: - Limit the CPU real-time period in", "'name' in the /etc/subgid file. type: str subuidname: description: -", "same before = before.replace(\":latest\", \"\") after = after.replace(\":latest\", \"\") before", "and re-created with the requested config. Image version will be", "= module.run_command([module_exec, 'image', 'pull', image]) if rc != 0: module.fail_json(msg=\"Can't", "not self.image: self.module.fail_json(msg='Cannot create container when image' ' is not", "in microseconds. This flag tells the kernel to limit the", "stopped state. type: str default: started choices: - absent -", "self.version = self._get_podman_version() self.diff = {} self.actions = [] @property", "'start' params {dict} -- dictionary of module parameters \"\"\" def", "before = self.info['mounts'] if before: volumes = [] for m", "state \"\"\" def __init__(self, module, name): \"\"\"Initialize PodmanContainer class. Arguments:", "self.container.name) self.update_container_result() def make_absent(self): \"\"\"Run actions if desired state is", "groupname or GID for the specified command. type: str userns:", "type: str default: started choices: - absent - present -", "err = self.container.stdout, self.container.stderr self.results.update({'changed': changed, 'container': facts, 'podman_actions': self.container.actions},", "podman_container: name: mydata image: busybox volume: - /tmp/data - name:", "json.loads(out)[0] if rc == 0 else {} def _get_podman_version(self): rc,", "CNI network's pool (default 10.88.0.0/16). type: str ipc: description: -", "Block IO weight (relative weight) accepts a weight value between", "[\"default\"], \"oom_score_adj\": 0, \"pid\": \"\", \"privileged\": False, \"rm\": False, \"security_opt\":", "Run container in detach mode type: bool default: True debug:", "- k8s-file - journald - json-file log_opt: description: - Logging", "self.params['cgroups'] return self._diff_update_and_compare('cgroups', before, after) return False def diffparam_cidfile(self): before", "['--cpuset-mems', self.params['cpuset_mems']] def addparam_detach(self, c): return c + ['--detach=%s' %", "an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF", "+ ['--cpu-rt-runtime', self.params['cpu_rt_runtime']] def addparam_cpu_shares(self, c): return c + ['--cpu-shares',", "you to specify arbitrary environment variables that are available for", "= module self.version = podman_version self.defaults = { \"blkio_weight\": 0,", "dictionary of module parameters \"\"\" def __init__(self, action, params, podman_version,", "on the host interfaces. The default is false. type: bool", "container's Real Time CPU usage to the period you specify.", "description: - Give extended privileges to this container. The default", "- Memory limit (format 10k, where unit = b, k,", "representing the current state of the container. Matches the podman", "the container ID to the file type: path cmd_args: description:", "on exit * on-failure[:max_retries] - Restart containers when they exit", "cgroup-parent. type: str choices: - default - disabled cidfile: description:", "def addparam_stop_timeout(self, c): return c + ['--stop-timeout', self.params['stop_timeout']] def addparam_subgidname(self,", "c + ['--uts', self.params['uts']] def addparam_volume(self, c): for vol in", "action to perform - start, create, stop, run, delete \"\"\"", "Add metadata to a container, pass dictionary of label names", "the container, for example '10.88.64.128'. Can only be used if", "self.diff = {} self.actions = [] @property def exists(self): \"\"\"Check", "- Automatically remove the container when it exits. The default", "before, after) # Healthcheck is only defined in container config", "c): return c + ['--detach-keys', self.params['detach_keys']] def addparam_device(self, c): for", "not absolute, the path is considered to be relative to", "'changed': False, 'actions': [], 'container': {}, } self.name = self.module.params['name']", "addparam_pod(self, c): return c + ['--pod', self.params['pod']] def addparam_privileged(self, c):", "list): cmd += self.params['command'] else: cmd += self.params['command'].split() return [to_bytes(i,", "Like start-period, the value can be expressed in a time", "for the container will be created. If the path is", "according to map of actions & states.\"\"\" states_map = {", "option to force the re-creation of the matching container. -", "podman command, cmd_args - ['--other-param', 'value'] Be aware module doesn't", "description: - Add metadata to a container, pass dictionary of", "- Whether to compare images in idempotency by taking into", "def addparam_expose(self, c): for exp in self.params['expose']: c += ['--expose',", "before, after) def diffparam_cpuset_mems(self): before = self.info['hostconfig']['cpusetmems'] after = self.params['cpuset_mems']", "after = self.params['cgroup_parent'] return self._diff_update_and_compare('cgroup_parent', before, after) def diffparam_cgroups(self): #", "in self.module.params: if self.module.params[p] is None and p in self.default_dict:", "self.params['group_add'] return self._diff_update_and_compare('group_add', before, after) # Healthcheck is only defined", "name: Run container podman_container: name: container image: quay.io/bitnami/wildfly state: started", "return c + ['--kernel-memory', self.params['kernel_memory']] def addparam_label(self, c): for label", "the first argument refers to an exploded container on the", "# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "= [self.action, self.params['name']] return [to_bytes(i, errors='surrogate_or_strict') for i in cmd]", "- Limit read rate (IO per second) from a device", "self.results.update({'container': {}, 'podman_actions': self.container.actions}) self.module.exit_json(**self.results) def execute(self): \"\"\"Execute the desired", "self.info['hostconfig']['securityopt'] after = self.params['security_opt'] before, after = sorted(list(set(before))), sorted(list(set(after))) return", "addparam_pids_limit(self, c): return c + ['--pids-limit', self.params['pids_limit']] def addparam_pod(self, c):", "diffparam_cpu_period(self): before = self.info['hostconfig']['cpuperiod'] after = self.params['cpu_period'] return self._diff_update_and_compare('cpu_period', before,", "c def addparam_rootfs(self, c): return c + ['--rootfs=%s' % self.params['rootfs']]", "exit. Restart policy will not take effect if a container", "args for podman command def addparam_cmd_args(self, c): return c +", "false, \"StdinOnce\": false, \"StopSignal\": 15, \"Tty\": false, \"User\": { \"gid\":", "return c + ['--init', self.params['init']] def addparam_init_path(self, c): return c", "implied. See the # License for the specific language governing", "the container. The format is key value, multiple times. type:", "def addparam_init_path(self, c): return c + ['--init-path', self.params['init_path']] def addparam_interactive(self,", "before = self.info['config']['labels'] or {} after = before.copy() if self.params['label']:", "label_file: description: - Read in a line delimited file of", "volumes from the specified container(s). type: list elements: str workdir:", "(e.g. device-write-bps /dev/sda:1mb) type: list device_write_iops: description: - Limit write", "{str} -- name of container \"\"\" super(PodmanContainer, self).__init__() self.module =", "available for the process that will be launched inside of", "an existing pod. If you want podman to make the", "blkio_weight_device: description: - Block IO weight (relative device weight, format", "self.update_container_result() elif self.container.running and not self.container.different: if self.restart: self.container.restart() self.results['actions'].append('restarted", "CLI command. Arguments: action {str} -- action type from 'run',", "a matching container, even if it is running. Use force_restart", "\"no\" device: \"/dev/sda:/dev/xvda:rwm\" ports: - \"8080:9000\" - \"127.0.0.1:8081:9001/udp\" env: SECRET_KEY:", "after) # Limited idempotency, it can't guess default values def", "+ [to_native(i) for i in b_command]) self.module.log(\"PODMAN-CONTAINER-DEBUG: %s\" % full_cmd)", "- Asserts that the container is first I(present), and then", "self.container.different: self.container.recreate() self.results['actions'].append('recreated %s' % self.container.name) self.update_container_result() elif self.container.stopped and", "image type: str env: description: - Set environment variables. This", "cgroup for the container will be created. type: str cgroups:", "def addparam_workdir(self, c): return c + ['--workdir', self.params['workdir']] # Add", "(i['path'], i['rate']) for i in before] after = self.params['device_write_bps'] or", "- Logging driver specific options. Used to set the path", "of disable results in no automatic timer setup) (default \"30s\")", "container. type: str http_proxy: description: - By default proxy environment", "\"\", \"privileged\": False, \"rm\": False, \"security_opt\": [], \"stop_signal\": 15, \"tty\":", "return c + ['--env-host=%s' % self.params['env_host']] def addparam_etc_hosts(self, c): for", "before = {i.split(\"=\")[0]: i.split(\"=\")[1] for i in env_before} after =", "namespace to join * slirp4netns use slirp4netns to create a", "bytes. If you omit the size entirely, the system uses", "self.info['hostconfig']['oomscoreadj'] after = self.params['oom_score_adj'] return self._diff_update_and_compare('oom_score_adj', before, after) def diffparam_privileged(self):", "description: - Path of the authentication file. Default is ``${XDG_RUNTIME_DIR}/containers/auth.json``", "created and started. Use recreate to always re-create a matching", "even if not attached. The default is false. type: bool", "int subgidname: description: - Run the container in a new", "else: volumes.append([m['source'], m['destination']]) before = [\":\".join(v) for v in volumes]", "self.container.create() self.results['actions'].append('created %s' % self.container.name) self.update_container_result() if self.container.stopped: self.update_container_result(changed=False) elif", "is set. type: list elements: str conmon_pidfile: description: - Write", "cannot be updated, it will be removed and re-created with", "in which to allow execution (0-3, 0,1). Only effective on", "\"2019-06-17T19:13:10.152479729+03:00\", \"Status\": \"exited\" }, \"StaticDir\": \"...\" ... }' \"\"\" class", "it cannot be updated, it will be removed and re-created", "\"\"\"Inspect the current container, update results with last info, exit.", "addparam_oom_kill_disable(self, c): return c + ['--oom-kill-disable=%s' % self.params['oom_kill_disable']] def addparam_oom_score_adj(self,", "\"cgroup_parent\": \"\", \"cidfile\": \"\", \"cpus\": 0.0, \"cpu_shares\": 0, \"cpu_quota\": 0,", "+ ['--dns', ','.join(self.params['dns'])] def addparam_dns_option(self, c): return c + ['--dns-option',", "def delete(self): \"\"\"Delete the container.\"\"\" self._perform_action('delete') def stop(self): \"\"\"Stop the", "the default bridge * none no networking * container:<name|id> reuse", "to true type: bool image_volume: description: - Tells podman how", "I(absent). returned: always type: dict sample: '{ \"AppArmorProfile\": \"\", \"Args\":", "description: - Write the pid of the conmon process to", "(bytes per second) to a device (e.g. device-write-bps /dev/sda:1mb) type:", "addparam_cpu_rt_runtime(self, c): return c + ['--cpu-rt-runtime', self.params['cpu_rt_runtime']] def addparam_cpu_shares(self, c):", "return self._diff_update_and_compare('privileged', before, after) def diffparam_pid(self): before = self.info['hostconfig']['pidmode'] after", "The options are bind, tmpfs, or ignore (default bind) type:", "Note that the returned fact will be removed in Ansible", "- remove rootfs: description: - If true, the first argument", "= AnsibleModule( argument_spec=yaml.safe_load(DOCUMENTATION)['options'], mutually_exclusive=( ['no_hosts', 'etc_hosts'], ), supports_check_mode=True, ) #", "import to_bytes, to_native ANSIBLE_METADATA = { 'metadata_version': '1.0', 'status': ['preview'],", "type: bool oom_kill_disable: description: - Whether to disable OOM Killer", "self.params['log_driver']] def addparam_log_opt(self, c): return c + ['--log-opt', self.params['log_opt']] def", "each host name is a key in the dictionary. Each", "['--pid', self.params['pid']] def addparam_pids_limit(self, c): return c + ['--pids-limit', self.params['pids_limit']]", "is not supported in all versions if 'cgroups' in self.info['hostconfig']:", "self.update_container_result() def make_stopped(self): \"\"\"Run actions if desired state is 'stopped'.\"\"\"", "c + ['--rootfs=%s' % self.params['rootfs']] def addparam_security_opt(self, c): for secopt", "description: - Limit write rate (IO per second) to a", "are * no - Do not restart containers on exit", "self._diff_update_and_compare('oom_score_adj', before, after) def diffparam_privileged(self): before = self.info['hostconfig']['privileged'] after =", "container when it exits. The default is false. type: bool", "= self.module.params['recreate'] self.container = PodmanContainer(self.module, self.name) def update_container_result(self, changed=True): \"\"\"Inspect", "log_driver \"k8s-file\". type: str choices: - k8s-file - journald -", "self.params['publish']: c += ['--publish', pub] return c def addparam_publish_all(self, c):", "\"\\n\" self.diff['after'] = \"\\n\".join( [\"%s - %s\" % (k, v)", "self.container.version}) self.module.exit_json(**self.results) def make_started(self): \"\"\"Run actions if desired state is", "for v in volumes] # Ignore volumes option for idempotency", "false. type: bool read_only: description: - Mount the container's root", "c): return c + ['--publish-all=%s' % self.params['publish_all']] def addparam_read_only(self, c):", "after) def diffparam_volumes_from(self): before = self.info['hostconfig']['volumesfrom'] or [] after =", "self.container.exists and not self.image: self.module.fail_json(msg='Cannot create container when image' '", "host name is a key in the dictionary. Each host", "mode = self.params['image_strict'] if mode is None or not mode:", "2.0 (the \"License\"); you may # not use this file", "def __init__(self, module, name): \"\"\"Initialize PodmanContainer class. Arguments: module {obj}", "servers type: list elements: str dns_option: description: - Set custom", "return c + ['--detach-keys', self.params['detach_keys']] def addparam_device(self, c): for dev", "ctrl-value type: str device: description: - Add a host device", "self.info, self.version) is_different = diffcheck.is_different() diffs = diffcheck.diff if self.module._diff", "example mount \"type=bind,source=/path/on/host,destination=/path/in/container\" type: str network: description: - Set the", "container is the root directory (/). type: str \"\"\" EXAMPLES", "% (action, self.name), stdout=out, stderr=err) def run(self): \"\"\"Run the container.\"\"\"", "g (gigabytes). If you omit the unit, the system uses", "\"FinishedAt\": \"2019-06-17T19:13:10.157518963+03:00\", \"Healthcheck\": { \"FailingStreak\": 0, \"Log\": null, \"Status\": \"\"", "supported for integers only. type: str memory_swap: description: - A", "running now.\"\"\" return self.exists and self.info['State']['Running'] @property def stopped(self): \"\"\"Return", "passed into the container if set for the podman process.", "authfile: description: - Path of the authentication file. Default is", "This flag tells the kernel to limit the amount of", "you specify, volume /HOST-DIR:/CONTAINER-DIR, podman bind mounts /HOST-DIR in the", "volumes = [] for m in before: if m['type'] ==", "user namespace using the map with 'name' in the /etc/subuid", "error happened, \" \"please contact maintainers ASAP!\") def main(): module", "self.params['group_add']: c += ['--group-add', g] return c def addparam_healthcheck(self, c):", "def diffparam_no_hosts(self): before = not bool(self.info['hostspath']) after = self.params['no_hosts'] if", "before] after = self.params['device_write_bps'] or [] before, after = sorted(list(set(before))),", "self.params['workdir'] return self._diff_update_and_compare('workdir', before, after) def is_different(self): diff_func_list = [func", "and func.startswith( \"diffparam\")] fail_fast = not bool(self.module._diff) different = False", "after) def diffparam_privileged(self): before = self.info['hostconfig']['privileged'] after = self.params['privileged'] return", "%s\" % full_cmd) self.actions.append(full_cmd) if not self.module.check_mode: rc, out, err", "def diffparam_uts(self): before = self.info['hostconfig']['utsmode'] after = self.params['uts'] return self._diff_update_and_compare('uts',", "# All Rights Reserved. # # Licensed under the Apache", "podman_version self.default_dict = None self.info = yaml.safe_load(json.dumps(info).lower()) self.params = self.defaultize()", "stopped - name: Start 4 load-balanced containers podman_container: name: \"container{{", "Set environment variables. This option allows you to specify arbitrary", "c): return c + ['--subuidname', self.params['subuidname']] def addparam_sysctl(self, c): for", "to drop from the container. type: list elements: str cgroup_parent:", "Write the pid of the conmon process to a file.", "None: after = [] else: after = self.params['blkio_weight_device'] return self._diff_update_and_compare('blkio_weight_device',", "Must be used with the -m (--memory) flag. The swap", "Tune the host's OOM preferences for containers (accepts -1000 to", "self._diff_update_and_compare('hostname', before, after) def diffparam_image(self): # TODO(sshnaidm): for strict image", "after = self.params['device_read_iops'] or [] before, after = sorted(list(set(before))), sorted(list(set(after)))", "self.container.running and not self.container.different: if self.restart: self.container.restart() self.results['actions'].append('restarted %s' %", "\"path=/var/log/container/mycontainer.json\" type: str aliases: - log_options memory: description: - Memory", "after = after.split(\"/\")[-1] return self._diff_update_and_compare('image', before, after) def diffparam_ipc(self): before", "minv='1.6.0') return c + ['--cgroups=%s' % self.params['cgroups']] def addparam_cgroupns(self, c):", "def addparam_label(self, c): for label in self.params['label'].items(): c += ['--label',", "defaultize(self): params_with_defaults = {} self.default_dict = PodmanDefaults( self.module, self.version).default_dict() for", "want podman to make the pod for you, preference the", "bind, tmpfs, or ignore (default bind) type: str choices: -", "podman container. type: list elements: str aliases: - volumes volumes_from:", "preferences for containers (accepts -1000 to 1000) type: int pid:", "you omit the unit, the system uses bytes. If you", "'stop', 'delete']: return self.start_stop_delete() if self.action in ['create', 'run']: cmd", "after) def diffparam_pid(self): before = self.info['hostconfig']['pidmode'] after = self.params['pid'] return", "for strict image compare mode use SHAs before = self.info['config']['image']", "example tmpfs \"/tmp\" \"rw,size=787448k,mode=1777\" type: dict tty: description: - Allocate", "the container. type: list elements: str cap_drop: description: - List", "self.update_container_result(changed=False) elif self.container.running: self.container.stop() self.results['actions'].append('stopped %s' % self.container.name) self.update_container_result() def", "integers only. type: str label: description: - Add metadata to", "def diffparam_annotation(self): before = self.info['config']['annotations'] or {} after = before.copy()", "Format - ip:hostPort:containerPort | ip::containerPort | hostPort:containerPort | containerPort type:", "format such as 1m22s. The default value is 30s type:", "\"cpu_shares\": 0, \"cpu_quota\": 0, \"cpu_period\": 0, \"cpu_rt_runtime\": 0, \"cpu_rt_period\": 0,", "addparam_volume(self, c): for vol in self.params['volume']: if vol: c +=", "is 0.0 which means no limit. type: str cpuset_cpus: description:", "def addparam_volumes_from(self, c): for vol in self.params['volumes_from']: c += ['--volumes-from',", "type: dict env_file: description: - Read in a line delimited", "after = self.params['security_opt'] before, after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('security_opt',", "Default is to create a private IPC namespace (POSIX SysV", "return True return False def diffparam_annotation(self): before = self.info['config']['annotations'] or", "# License for the specific language governing permissions and limitations", "return c + ['--sig-proxy=%s' % self.params['sig_proxy']] def addparam_stop_signal(self, c): return", "self._perform_action('stop') def start(self): \"\"\"Start the container.\"\"\" self._perform_action('start') def create(self): \"\"\"Create", "podman_version, module): self.params = params self.action = action self.podman_version =", "diffparam_blkio_weight(self): before = self.info['hostconfig']['blkioweight'] after = self.params['blkio_weight'] return self._diff_update_and_compare('blkio_weight', before,", "return self._diff_update_and_compare('memory_reservation', before, after) def diffparam_network(self): before = [self.info['hostconfig']['networkmode']] after", "self.params['rm'] return self._diff_update_and_compare('rm', before, after) def diffparam_security_opt(self): before = self.info['hostconfig']['securityopt']", "['--systemd=%s' % self.params['systemd']] def addparam_tmpfs(self, c): for tmpfs in self.params['tmpfs'].items():", "before, after) def diffparam_user(self): before = self.info['config']['user'] if self.module.params['user'] is", "is I(absent). returned: always type: dict sample: '{ \"AppArmorProfile\": \"\",", "'actions': [], 'container': {}, } self.name = self.module.params['name'] self.executable =", "diffparam_stop_signal(self): before = self.info['config']['stopsignal'] after = self.params['stop_signal'] return self._diff_update_and_compare('stop_signal', before,", "addparam_shm_size(self, c): return c + ['--shm-size', self.params['shm_size']] def addparam_sig_proxy(self, c):", "namespace using the map with 'name' in the /etc/subuid file.", "Network mode for the container * bridge create a network", "= self.params['uts'] return self._diff_update_and_compare('uts', before, after) def diffparam_volume(self): before =", "with a non-0 exit code, retrying indefinitely or until the", "from different registries are the same before = before.replace(\":latest\", \"\")", "self.module.fail_json(msg=\"%s run failed!\" % self.module.params['executable']) return out.split(\"version\")[1].strip() def _perform_action(self, action):", "self.info['hostconfig']['cgroupparent'] after = self.params['cgroup_parent'] return self._diff_update_and_compare('cgroup_parent', before, after) def diffparam_cgroups(self):", "list elements: str cap_drop: description: - List of capabilities to", "\"memory\": \"0\", \"memory_swap\": \"0\", \"memory_reservation\": \"0\", # \"memory_swappiness\": -1, \"no_hosts\":", "capabilities to drop from the container. type: list elements: str", "[], \"Driver\": \"overlay\", \"EffectiveCaps\": [ \"CAP_CHOWN\", ... ], \"ExecIDs\": [],", "int healthcheck_start_period: description: - The initialization time needed for a", "(default bind) type: str choices: - 'bind' - 'tmpfs' -", "after = self.params['blkio_weight_device'] return self._diff_update_and_compare('blkio_weight_device', before, after) def diffparam_cap_add(self): before", "the container. type: str http_proxy: description: - By default proxy", "strings for Popen command \"\"\" if self.action in ['start', 'stop',", "self.params['annotation'].items(): c += ['--annotation', '='.join(annotate)] return c def addparam_authfile(self, c):", "the builtin image volumes. The options are bind, tmpfs, or", "before, after) def diffparam_blkio_weight_device(self): before = self.info['hostconfig']['blkioweightdevice'] if before ==", "not None: after += [\"cap_\" + i.lower() for i in", "name: container image: quay.io/bitnami/wildfly state: started - name: Create a", "before] after = self.params['device_write_iops'] or [] before, after = sorted(list(set(before))),", "Logging driver specific options. Used to set the path to", "description: - Use with present and started states to force", "\"...\", \"Created\": \"2019-06-17T19:13:09.873858307+03:00\", \"Dependencies\": [], \"Driver\": \"overlay\", \"EffectiveCaps\": [ \"CAP_CHOWN\",", "= before.copy() if self.params['label']: after.update({ str(k).lower(): str(v).lower() for k, v", "return c + ['--shm-size', self.params['shm_size']] def addparam_sig_proxy(self, c): return c", "return self._diff_update_and_compare('blkio_weight', before, after) def diffparam_blkio_weight_device(self): before = self.info['hostconfig']['blkioweightdevice'] if", "%s\" % ( param, minv, self.podman_version)) def addparam_annotation(self, c): for", "addparam_conmon_pidfile(self, c): return c + ['--conmon-pidfile', self.params['conmon_pidfile']] def addparam_cpu_period(self, c):", "type: bool stop_signal: description: - Signal to stop a container.", "self.info['config']['env'] or {} before = {i.split(\"=\")[0]: i.split(\"=\")[1] for i in", "'create', 'delete', 'start' params {dict} -- dictionary of module parameters", "which means no limit. type: str cpuset_cpus: description: - CPUs", "before = self.info['effectivecaps'] or [] after = [] if self.module.params['cap_add']", "= before.copy() if self.module.params['annotation'] is not None: after.update(self.params['annotation']) return self._diff_update_and_compare('annotation',", "type: list ulimit: description: - Ulimit options type: list user:", "diffparam_device_write_iops(self): before = self.info['hostconfig']['blkiodevicewriteiops'] or [] before = [\"%s:%s\" %", "bool uidmap: description: - Run the container in a new", "str device_read_bps: description: - Limit read rate (bytes per second)", "Matches the podman inspection output. - Note that facts are", "self.actions.append(full_cmd) if not self.module.check_mode: rc, out, err = self.module.run_command( [self.module.params['executable'],", "created. If a container matches the name but the provided", "container.\"\"\" self._perform_action('delete') def stop(self): \"\"\"Stop the container.\"\"\" self._perform_action('stop') def start(self):", "[ \"sh\" ], \"BoundingCaps\": [ \"CAP_CHOWN\", ... ], \"Config\": {", "is first I(present), and then if the container is running", "self.update_container_result() elif self.container.stopped and not self.container.different: self.container.start() self.results['actions'].append('started %s' %", "self.podman_version)) if maxv and LooseVersion(maxv) < LooseVersion( self.podman_version): self.module.fail_json(msg=\"Parameter %s", "15, \"tty\": False, \"user\": \"\", \"uts\": \"\", \"volume\": [], \"workdir\":", "the podman container. type: list elements: str aliases: - volumes", "c + ['--env-file', self.params['env_file']] def addparam_env_host(self, c): self.check_version('--env-host', minv='1.5.0') return", "for integers only. type: str label: description: - Add metadata", "memory: description: - Memory limit (format 10k, where unit =", "b_command, expand_user_and_vars=False) self.stdout = out self.stderr = err if rc", "memory limit (format <number>[<unit>], where unit = b, k, m", "for detaching a container. Format is a single character or", "- Do not restart containers on exit * on-failure[:max_retries] -", "in compliance with the License. You may obtain # a", "= self.params['command'] if isinstance(after, str): after = [i.lower() for i", "after) def diffparam_security_opt(self): before = self.info['hostconfig']['securityopt'] after = self.params['security_opt'] before,", "state of the container. Matches the podman inspection output. -", "module self.results = { 'changed': False, 'actions': [], 'container': {},", "before, after) # Parameter has limited idempotency, unable to guess", "- name: Run container podman_container: name: container image: quay.io/bitnami/wildfly state:", "'--name', self.params['name']] all_param_methods = [func for func in dir(self) if", "'after': {}} self.non_idempotent = { 'env_file', 'env_host', \"ulimit\", # Defaults", "the same before = before.replace(\":latest\", \"\") after = after.replace(\":latest\", \"\")", "- started image: description: - Repository path (or image name)", "The value can be expressed in time format like 2m3s.", "description: - I(absent) - A container matching the specified name", "<device-on-host>[:<device-on-container>][:<permissions>] (e.g. device /dev/sdc:/dev/xvdc:rwm) type: list elements: str device_read_bps: description:", "self.params['pid'] return self._diff_update_and_compare('pid', before, after) def diffparam_rm(self): before = self.info['hostconfig']['autoremove']", "port, or range of ports, to the host. Format -", "to the podman run command to the container process. SIGCHLD,", "self.params['mount']] def addparam_network(self, c): return c + ['--network', \",\".join(self.params['network'])] def", "to the container's ``/etc/hosts`` file. type: dict aliases: - add_hosts", "before, after) def diffparam_stop_signal(self): before = self.info['config']['stopsignal'] after = self.params['stop_signal']", "self.info['hostconfig']['logconfig']['type'] after = self.params['log_driver'] return self._diff_update_and_compare('log_driver', before, after) # Parameter", "DNS options type: str dns_search: description: - Set custom DNS", "self.params['device_read_bps']: c += ['--device-read-bps', dev] return c def addparam_device_read_iops(self, c):", "def diffparam_healthcheck(self): if 'healthcheck' in self.info['config']: # the \"test\" key", "the container's Real Time CPU usage. This flag tell the", "= module self.version = podman_version self.default_dict = None self.info =", "None: after += [\"cap_\" + i.lower() for i in self.module.params['cap_add']]", "{} after = self.params['etc_hosts'] return self._diff_update_and_compare('etc_hosts', before, after) def diffparam_group_add(self):", "if self.module.params['conmon_pidfile'] is None: after = before else: after =", "# was configured; otherwise the config key isn't part of", "0.0 which means no limit. type: str cpuset_cpus: description: -", "+= ['--rm'] return c def addparam_rootfs(self, c): return c +", "-- action to perform - start, create, stop, run, delete", "This option allows you to specify arbitrary environment variables that", "to the container process. SIGCHLD, SIGSTOP, and SIGKILL are not", "\"cpu_period\": 0, \"cpu_rt_runtime\": 0, \"cpu_rt_period\": 0, \"cpuset_cpus\": \"\", \"cpuset_mems\": \"\",", "def addparam_ulimit(self, c): for u in self.params['ulimit']: c += ['--ulimit',", "second) to a device (e.g. device-write-iops /dev/sda:1000) type: list dns:", "\"\"\"Creates list of arguments for podman CLI command. Arguments: action", "init inside the container that forwards signals and reaps processes.", "import LooseVersion import yaml from ansible.module_utils.basic import AnsibleModule from ansible.module_utils._text", "before = self.info['hostconfig']['cpurealtimeruntime'] after = self.params['cpu_rt_runtime'] return self._diff_update_and_compare('cpu_rt_runtime', before, after)", "format is <number><unit>. number must be greater than 0. Unit", "* 2) return self._diff_update_and_compare('memory_swap', before, after) def diffparam_memory_reservation(self): before =", "where unit = b, k, m or g) Note -", "actual healthcheck command. before = self.info['config']['healthcheck']['test'][1] else: before = ''", "& states.\"\"\" states_map = { 'present': self.make_started, 'started': self.make_started, 'absent':", "= self.params['memory'] return self._diff_update_and_compare('memory', before, after) def diffparam_memory_swap(self): # By", "str privileged: description: - Give extended privileges to this container.", "self.params['cpu_rt_runtime']] def addparam_cpu_shares(self, c): return c + ['--cpu-shares', self.params['cpu_shares']] def", "def diffparam_memory_swap(self): # By default it's twice memory parameter before", "['--detach-keys', self.params['detach_keys']] def addparam_device(self, c): for dev in self.params['device']: c", "yes image: someuser/anotherappimage command: sleep 1d with_sequence: count=4 - name:", "\"EffectiveCaps\": [ \"CAP_CHOWN\", ... ], \"ExecIDs\": [], \"ExitCommand\": [ \"/usr/bin/podman\",", "is key value, multiple times. type: dict authfile: description: -", "['--volumes-from', vol] return c def addparam_workdir(self, c): return c +", "(c) 2019 OpenStack Foundation # All Rights Reserved. # #", "= after.split(\"/\")[-1] return self._diff_update_and_compare('image', before, after) def diffparam_ipc(self): before =", "before = self.info['hostconfig']['blkiodevicereadiops'] or [] before = [\"%s:%s\" % (i['path'],", "description: - By default proxy environment variables are passed into", "disabled by setting the http_proxy option to false. The environment", "False def diffparam_conmon_pidfile(self): before = self.info['conmonpidfile'] if self.module.params['conmon_pidfile'] is None:", "via 'network:', and if the container is not joining another", "c + ['--cpu-shares', self.params['cpu_shares']] def addparam_cpus(self, c): return c +", "return c + ['--cpu-rt-runtime', self.params['cpu_rt_runtime']] def addparam_cpu_shares(self, c): return c", "and not self.container.different: self.container.start() self.results['actions'].append('started %s' % self.container.name) self.update_container_result() def", "['--rootfs=%s' % self.params['rootfs']] def addparam_security_opt(self, c): for secopt in self.params['security_opt']:", "-- list of image actions - if it pulled or", "ansible module object name {str} -- name of container \"\"\"", "podman_container: name: myservice image: busybox log_options: path=/var/log/container/mycontainer.json log_driver: k8s-file \"\"\"", "# Copyright (c) 2019 OpenStack Foundation # All Rights Reserved.", "such as 1m22s. The default value is 30s type: str", "host name will be added to the container's ``/etc/hosts`` file.", "self.diff['after'] = \"\\n\".join( [\"%s - %s\" % (k, v) for", "= self.info['hostconfig']['cpushares'] after = self.params['cpu_shares'] return self._diff_update_and_compare('cpu_shares', before, after) def", "Tune the container's pids limit. Set -1 to have unlimited", "to in writing, software # distributed under the License is", "mounts /HOST-DIR in the host to /CONTAINER-DIR in the podman", "diffs['before'] and diffs['after']: self.diff['before'] = \"\\n\".join( [\"%s - %s\" %", "to get from inspest, recreate it if not default before", "path is considered to be relative to the cgroups path", "by setting the ``REGISTRY_AUTH_FILE`` environment variable. ``export REGISTRY_AUTH_FILE=path`` type: path", "type: bool default: False init: description: - Run an init", "not create /etc/hosts for the container Default is false. type:", "Sets the container host name that is available inside the", "__init__(self, module, podman_version): self.module = module self.version = podman_version self.defaults", "[to_bytes(i, errors='surrogate_or_strict') for i in cmd] if self.action == 'delete':", "pids limit. Set -1 to have unlimited pids for the", "self.module.exit_json(**self.results) def make_started(self): \"\"\"Run actions if desired state is 'started'.\"\"\"", "self.check_version('--cgroups', minv='1.6.0') return c + ['--cgroups=%s' % self.params['cgroups']] def addparam_cgroupns(self,", "[] after = [] if self.module.params['cap_add'] is not None: after", "- Facts representing the current state of the container. Matches", "- Limit the CPU real-time runtime in microseconds. This flag", "class PodmanContainerDiff: def __init__(self, module, info, podman_version): self.module = module", "\"StdinOnce\": false, \"StopSignal\": 15, \"Tty\": false, \"User\": { \"gid\": 0,", "run command to the container process. SIGCHLD, SIGSTOP, and SIGKILL", "image Returns: list -- list of image actions - if", "self.diff['before'] = \"\\n\".join( [\"%s - %s\" % (k, v) for", "sig_proxy: description: - Proxy signals sent to the podman run", "License, Version 2.0 (the \"License\"); you may # not use", "dev] return c def addparam_device_write_bps(self, c): for dev in self.params['device_write_bps']:", "self.params['memory_swappiness']] def addparam_mount(self, c): return c + ['--mount', self.params['mount']] def", "after = self.params['cpus'] return self._diff_update_and_compare('cpus', before, after) def diffparam_cpuset_cpus(self): before", "group_add: description: - Add additional groups to run as type:", "self.container.name) self.results.update({'changed': True}) self.results.update({'container': {}, 'podman_actions': self.container.actions}) self.module.exit_json(**self.results) def execute(self):", "detaching a container. Format is a single character or ctrl-value", "microseconds. Limit the container's Real Time CPU usage. This flag", "container * bridge create a network stack on the default", "True}) self.results.update({'container': {}, 'podman_actions': self.container.actions}) self.module.exit_json(**self.results) def execute(self): \"\"\"Execute the", "\"Env\": [ \"PATH=/usr/sbin:/usr/bin:/sbin:/bin\", \"TERM=xterm\", \"HOSTNAME=\", \"container=podman\" ], \"Hostname\": \"\", \"Image\":", "key in the dictionary. Each host name will be added", "format like 2m3s. The default value is 0s type: str", "sorted(list(set(after))) return self._diff_update_and_compare('devices', before, after) def diffparam_device_read_bps(self): before = self.info['hostconfig']['blkiodevicereadbps']", "- Signal to stop a container. Default is SIGTERM. type:", "before.copy() if self.module.params['annotation'] is not None: after.update(self.params['annotation']) return self._diff_update_and_compare('annotation', before,", "with registry and namespaces. type: bool default: False init: description:", "return c + ['--oom-score-adj', self.params['oom_score_adj']] def addparam_pid(self, c): return c", "updated, if it can be. If it cannot be updated,", "\"sh\" ], \"Domainname\": \"\", \"Entrypoint\": \"\", \"Env\": [ \"PATH=/usr/sbin:/usr/bin:/sbin:/bin\", \"TERM=xterm\",", "c += ['--tmpfs', ':'.join(tmpfs)] return c def addparam_tty(self, c): return", "is assumed to be available locally. type: str annotation: description:", "after.split(\"/\")[-1] return self._diff_update_and_compare('image', before, after) def diffparam_ipc(self): before = self.info['hostconfig']['ipcmode']", "to the PODMAN_USERNS environment variable. An empty value means user", "= self.module.run_command( [self.module.params['executable'], b'--version']) if rc != 0 or not", "def __init__(self, module, podman_version): self.module = module self.version = podman_version", "if not default before = False after = self.params['env_host'] return", "self.params['network'] return self._diff_update_and_compare('network', before, after) def diffparam_no_hosts(self): before = not", "self.module.params['command'] is not None: before = self.info['config']['cmd'] after = self.params['command']", "value can be expressed in time format like 2m3s. The", "I(present), and then if the container is running moves it", "they do not already exist. type: path cgroupns: description: -", "idempotency is supported for integers only. type: str memory_swap: description:", "c): self.check_version('--cgroups', minv='1.6.0') return c + ['--cgroups=%s' % self.params['cgroups']] def", "License is distributed on an \"AS IS\" BASIS, WITHOUT #", "a device (e.g. device-write-iops /dev/sda:1000) type: list dns: description: -", "arguments for podman CLI command. Arguments: action {str} -- action", "after = self.params['blkio_weight'] return self._diff_update_and_compare('blkio_weight', before, after) def diffparam_blkio_weight_device(self): before", "false. When set to true, keep stdin open even if", "before, after) def diffparam_device(self): before = [\":\".join([i['pathonhost'], i['pathincontainer']]) for i", "return self._diff_update_and_compare('oom_score_adj', before, after) def diffparam_privileged(self): before = self.info['hostconfig']['privileged'] after", "[] before, after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('device_read_bps', before, after)", "= self.info['hostconfig']['utsmode'] after = self.params['uts'] return self._diff_update_and_compare('uts', before, after) def", "if self.module.params['debug']: self.results.update({'podman_version': self.container.version}) self.module.exit_json(**self.results) def make_started(self): \"\"\"Run actions if", "in self.module.params['cap_drop']]: if c in after: after.remove(c) before, after =", "Block IO weight (relative device weight, format DEVICE_NAME[:]WEIGHT). type: dict", "% self.params['env_host']] def addparam_etc_hosts(self, c): for host_ip in self.params['etc_hosts'].items(): c", "rate (bytes per second) to a device (e.g. device-write-bps /dev/sda:1mb)", "return params_with_defaults def _diff_update_and_compare(self, param_name, before, after): if before !=", "description: - Return additional information which can be helpful for", "with \"new:\" type: str privileged: description: - Give extended privileges", "podman containers notes: [] description: - Start, stop, restart and", "class. Arguments: module {obj} -- ansible module object name {str}", "+ ['--init-path', self.params['init_path']] def addparam_interactive(self, c): return c + ['--interactive=%s'", "Override command of container. Can be a string or a", "is_different and diffs['before'] and diffs['after']: self.diff['before'] = \"\\n\".join( [\"%s -", "mapping. type: str group_add: description: - Add additional groups to", "not match, the container will be updated, if it can", "description: - Facts representing the current state of the container.", "- Path of the authentication file. Default is ``${XDG_RUNTIME_DIR}/containers/auth.json`` (Not", "mappings, where each host name is a key in the", "def diffparam_workdir(self): before = self.info['config']['workingdir'] after = self.params['workdir'] return self._diff_update_and_compare('workdir',", "def addparam_blkio_weight_device(self, c): for blkio in self.params['blkio_weight_device'].items(): c += ['--blkio-weight-device',", "are not proxied. The default is true. type: bool stop_signal:", "# Check non idempotent parameters for p in self.non_idempotent: if", "= PodmanContainerDiff(self.module, self.info, self.version) is_different = diffcheck.is_different() diffs = diffcheck.diff", "# flake8: noqa: E501 from __future__ import absolute_import, division, print_function", "'podman' type: str state: description: - I(absent) - A container", "is 'absent'.\"\"\" if not self.container.exists: self.results.update({'changed': False}) elif self.container.exists: self.container.delete()", "\"/dev/sda:/dev/xvda:rwm\" ports: - \"8080:9000\" - \"127.0.0.1:8081:9001/udp\" env: SECRET_KEY: \"ssssh\" BOOLEAN_KEY:", "c): return c + ['--ip', self.params['ip']] def addparam_ipc(self, c): return", "uses 64m type: str sig_proxy: description: - Proxy signals sent", "device: \"/dev/sda:/dev/xvda:rwm\" ports: - \"8080:9000\" - \"127.0.0.1:8081:9001/udp\" env: SECRET_KEY: \"ssssh\"", "- Add metadata to a container, pass dictionary of label", "type: str pids_limit: description: - Tune the container's pids limit.", "str interactive: description: - Keep STDIN open even if not", "\"/tmp\" \"rw,size=787448k,mode=1777\" type: dict tty: description: - Allocate a pseudo-TTY.", "swappiness behavior. Accepts an integer between 0 and 100. type:", "process_action() self.module.fail_json(msg=\"Unexpected logic error happened, \" \"please contact maintainers ASAP!\")", "after = self.params['user'] return self._diff_update_and_compare('user', before, after) def diffparam_uts(self): before", "output is not supported in all versions if 'cgroups' in", "RETURN = \"\"\" container: description: - Facts representing the current", "- mydata - name: Restart a container podman_container: name: myapplication", "the container if set for the podman process. This can", "description: - Set custom DNS servers type: list elements: str", "account a full name with registry and namespaces. type: bool", "str aliases: - net no_hosts: description: - Do not create", "func_name in diff_func_list: dff_func = getattr(self, func_name) if dff_func(): if", "True if container is running now.\"\"\" return self.exists and self.info['State']['Running']", "- ['--other-param', 'value'] Be aware module doesn't support idempotency if", "return self._diff_update_and_compare('env', before, after) def diffparam_etc_hosts(self): if self.info['hostconfig']['extrahosts']: before =", "ANSIBLE_METADATA = { 'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community' }", "distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR", "diffparam_volumes_from(self): before = self.info['hostconfig']['volumesfrom'] or [] after = self.params['volumes_from'] or", "\"TERM=xterm\", \"HOSTNAME=\", \"container=podman\" ], \"Hostname\": \"\", \"Image\": \"docker.io/library/busybox:latest\", \"Labels\": null,", ") # work on input vars if module.params['state'] in ['started',", "c): for tmpfs in self.params['tmpfs'].items(): c += ['--tmpfs', ':'.join(tmpfs)] return", "- Determines whether the container will create CGroups. Valid values", "be b (bytes), k (kilobytes), m(megabytes), or g (gigabytes). If", "%s\" % ( param, minv, self.podman_version)) if maxv and LooseVersion(maxv)", "but the provided configuration does not match, the container will", "self.info['hostconfig']['devices']] after = [\":\".join(i.split(\":\")[:2]) for i in self.params['device']] before, after", "matching container to be stopped and restarted. - I(stopped) -", "for k, v in self.params['env'].items() }) return self._diff_update_and_compare('env', before, after)", "- Block IO weight (relative weight) accepts a weight value", "of byte strings for Popen command \"\"\" if self.action in", "for k, v in sorted( diffs['before'].items())]) + \"\\n\" self.diff['after'] =", "containers notes: [] description: - Start, stop, restart and manage", "str aliases: - ports - published - published_ports publish_all: description:", "If true, the first argument refers to an exploded container", "If you want podman to make the pod for you,", "sorted(list(set(after))) return self._diff_update_and_compare('volume', before, after) def diffparam_volumes_from(self): before = self.info['hostconfig']['volumesfrom']", "['--kernel-memory', self.params['kernel_memory']] def addparam_label(self, c): for label in self.params['label'].items(): c", "bool default: False aliases: - restart gidmap: description: - Run", "- The maximum time allowed to complete the healthcheck before", "or tmpfs For example mount \"type=bind,source=/path/on/host,destination=/path/in/container\" type: str network: description:", "dff_func = getattr(self, func_name) if dff_func(): if fail_fast: return True", "value. By default, the swap LIMIT will be set to", "output podman_container: name: myservice image: busybox log_options: path=/var/log/container/mycontainer.json log_driver: k8s-file", "before = self.info['config']['annotations'] or {} after = before.copy() if self.module.params['annotation']", "def __init__(self, action, params, podman_version, module): self.params = params self.action", "= \"\"\" - name: Run container podman_container: name: container image:", "addparam_subuidname(self, c): return c + ['--subuidname', self.params['subuidname']] def addparam_sysctl(self, c):", "\"\", \"cidfile\": \"\", \"cpus\": 0.0, \"cpu_shares\": 0, \"cpu_quota\": 0, \"cpu_period\":", "return c + ['--network', \",\".join(self.params['network'])] def addparam_no_hosts(self, c): return c", "self.default_dict = PodmanDefaults( self.module, self.version).default_dict() for p in self.module.params: if", "json from distutils.version import LooseVersion import yaml from ansible.module_utils.basic import", "description: - Whether to compare images in idempotency by taking", "name: Start 4 load-balanced containers podman_container: name: \"container{{ item }}\"", "= out self.stderr = err if rc != 0: self.module.fail_json(", "- Limit the CPU real-time period in microseconds. Limit the", "rootfs: description: - If true, the first argument refers to", "healthcheck command for a container. type: str healthcheck_interval: description: -", "for the container, for example '10.88.64.128'. Can only be used", "container process. SIGCHLD, SIGSTOP, and SIGKILL are not proxied. The", "after.update({ str(k).lower(): str(v).lower() for k, v in self.params['env'].items() }) return", "% self.params['tty']] def addparam_uidmap(self, c): for uidmap in self.params['uidmap']: c", "hit * always - Restart containers when they exit, regardless", "%s' % self.container.name) self.update_container_result() elif self.container.stopped and not self.container.different: self.container.start()", "compliance with the License. You may obtain # a copy", "Path to cgroups under which the cgroup for the container", "self.params['conmon_pidfile']] def addparam_cpu_period(self, c): return c + ['--cpu-period', self.params['cpu_period']] def", "def diffparam_device_read_bps(self): before = self.info['hostconfig']['blkiodevicereadbps'] or [] before = [\"%s:%s\"", "under the License. # flake8: noqa: E501 from __future__ import", "module doesn't support idempotency if this is set. type: list", "or alter a healthcheck command for a container. type: str", "set to double the value of --memory Note - idempotency", "user and platform, impossible to guess } def defaultize(self): params_with_defaults", "self.stderr = '', '' self.info = self.get_info() self.version = self._get_podman_version()", "container exists.\"\"\" return bool(self.info != {}) @property def different(self): \"\"\"Check", "i in cmd] def start_stop_delete(self): if self.action in ['stop', 'start']:", "# # Unless required by applicable law or agreed to", "c + ['--env-host=%s' % self.params['env_host']] def addparam_etc_hosts(self, c): for host_ip", "0: module.fail_json(msg=\"Can't pull image %s\" % image, stdout=out, stderr=err) image_actions.append(\"pulled", "func.startswith( \"diffparam\")] fail_fast = not bool(self.module._diff) different = False for", "c): return c + ['--uts', self.params['uts']] def addparam_volume(self, c): for", "self.container.name) self.update_container_result() elif self.container.stopped and not self.container.different: self.container.start() self.results['actions'].append('started %s'", "def stop(self): \"\"\"Stop the container.\"\"\" self._perform_action('stop') def start(self): \"\"\"Start the", "specify, volume /HOST-DIR:/CONTAINER-DIR, podman bind mounts /HOST-DIR in the host", "after = self.params['cpu_period'] return self._diff_update_and_compare('cpu_period', before, after) def diffparam_cpu_rt_period(self): before", "['--log-opt', self.params['log_opt']] def addparam_memory(self, c): return c + ['--memory', self.params['memory']]", "impossible to guess } def defaultize(self): params_with_defaults = {} self.default_dict", "to this container. The default is false. type: bool publish:", "!= after: self.diff['before'].update({param_name: before}) self.diff['after'].update({param_name: after}) return True return False", "g in self.params['group_add']: c += ['--group-add', g] return c def", "{obj} -- ansible module object name {str} -- name of", "return self._diff_update_and_compare('volumes_from', before, after) def diffparam_workdir(self): before = self.info['config']['workingdir'] after", "Read in a line delimited file of labels type: str", "0,1) type: str cpuset_mems: description: - Memory nodes (MEMs) in", "\"\", \"Entrypoint\": \"\", \"Env\": [ \"PATH=/usr/sbin:/usr/bin:/sbin:/bin\", \"TERM=xterm\", \"HOSTNAME=\", \"container=podman\" ],", "Asserts the existence of a container matching the name and", "default: False aliases: - restart gidmap: description: - Run the", "self.module.run_command( [self.module.params['executable'], b'container', b'inspect', self.name]) return json.loads(out)[0] if rc ==", "description: - Path to cgroups under which the cgroup for", "read rate (IO per second) from a device (e.g. device-read-iops", "def create(self): \"\"\"Create the container.\"\"\" self._perform_action('create') def recreate(self): \"\"\"Recreate the", "/dev/shm. The format is <number><unit>. number must be greater than", "\"1.0.1-dev\", \"Paused\": false, \"Pid\": 4083, \"Restarting\": false, \"Running\": false, \"StartedAt\":", "BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either", "after = self.params['cgroups'] return self._diff_update_and_compare('cgroups', before, after) return False def", "bool(self.module._diff) different = False for func_name in diff_func_list: dff_func =", "type: str cpuset_mems: description: - Memory nodes (MEMs) in which", "= {i.split(\"=\")[0]: i.split(\"=\")[1] for i in env_before} after = before.copy()", "PodmanModuleParams(action, self.module.params, self.version, self.module, ).construct_command_from_params() full_cmd = \" \".join([self.module.params['executable']] +", "to restart Podman containers. type: path command: description: - Override", "name and any provided configuration parameters. If no container matches", "['--stop-signal', self.params['stop_signal']] def addparam_stop_timeout(self, c): return c + ['--stop-timeout', self.params['stop_timeout']]", "Allocate a pseudo-TTY. The default is false. type: bool uidmap:", "is considered to be unhealthy. The default value is 3.", "def addparam_publish(self, c): for pub in self.params['publish']: c += ['--publish',", "used with the -m (--memory) flag. The swap LIMIT should", "aliases: - remove rootfs: description: - If true, the first", "false, \"AttachStdout\": false, \"Cmd\": [ \"sh\" ], \"Domainname\": \"\", \"Entrypoint\":", "description: - Set the UTS mode for the container type:", "from __future__ import absolute_import, division, print_function __metaclass__ = type import", "etc_hosts: other: \"127.0.0.1\" restart_policy: \"no\" device: \"/dev/sda:/dev/xvda:rwm\" ports: - \"8080:9000\"", "c + ['--mount', self.params['mount']] def addparam_network(self, c): return c +", "volumes. The options are bind, tmpfs, or ignore (default bind)", "self.params['cpu_period'] return self._diff_update_and_compare('cpu_period', before, after) def diffparam_cpu_rt_period(self): before = self.info['hostconfig']['cpurealtimeperiod']", "addparam_cgroupns(self, c): self.check_version('--cgroupns', minv='1.6.2') return c + ['--cgroupns=%s' % self.params['cgroupns']]", "['--user', self.params['user']] def addparam_userns(self, c): return c + ['--userns', self.params['userns']]", "return c + ['--http-proxy=%s' % self.params['http_proxy']] def addparam_image_volume(self, c): return", "after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('cap_add', before, after) def diffparam_cap_drop(self):", "func_name = \"_\".join([\"addparam\", param]) if func_name in all_param_methods: cmd =", "image actions - if it pulled or nothing was done", "a weight value between 10 and 1000 type: int blkio_weight_device:", "\"\", \"uts\": \"\", \"volume\": [], \"workdir\": \"/\", } def default_dict(self):", "name): \"\"\"Initialize PodmanContainer class. Arguments: module {obj} -- ansible module", "= before else: after = self.params['user'] return self._diff_update_and_compare('user', before, after)", "return c + ['--healthcheck-interval', self.params['healthcheck_interval']] def addparam_healthcheck_retries(self, c): return c", "self._diff_update_and_compare('cpu_shares', before, after) def diffparam_cpus(self): before = int(self.info['hostconfig']['nanocpus']) / 1000000000", "return out.split(\"version\")[1].strip() def _perform_action(self, action): \"\"\"Perform action with container. Arguments:", "subgidname: description: - Run the container in a new user", "to an exploded container on the file system. The dafault", "name: remove container podman_container: name: ohno state: absent - name:", "before: if m['type'] == 'volume': volumes.append([m['name'], m['destination']]) else: volumes.append([m['source'], m['destination']])", "def addparam_dns_option(self, c): return c + ['--dns-option', self.params['dns_option']] def addparam_dns_search(self,", "\"group_add\": [], \"healthcheck\": \"\", \"ipc\": \"\", \"kernelmemory\": \"0\", \"log_driver\": \"k8s-file\",", "map with 'name' in the /etc/subuid file. type: str sysctl:", "def addparam_publish_all(self, c): return c + ['--publish-all=%s' % self.params['publish_all']] def", "[\"cap_\" + i.lower() for i in self.module.params['cap_add']] after += before", "the process that will be launched inside of the container.", "and self.container.different: self.container.recreate() self.results['actions'].append('recreated %s' % self.container.name) self.update_container_result() elif self.container.stopped", "Restart policy will not take effect if a container is", "'='.join(annotate)] return c def addparam_authfile(self, c): return c + ['--authfile',", "[ \"CAP_CHOWN\", ... ], \"ExecIDs\": [], \"ExitCommand\": [ \"/usr/bin/podman\", \"--root\",", "func in dir(self) if callable(getattr(self, func)) and func.startswith(\"addparam\")] params_set =", "interval for the healthchecks (a value of disable results in", "addparam_image_volume(self, c): return c + ['--image-volume', self.params['image_volume']] def addparam_init(self, c):", "value, multiple times. type: dict authfile: description: - Path of", "for the container. type: str pod: description: - Run container", "http_proxy, https_proxy, ftp_proxy, no_proxy, and also the upper case versions", "if self.module.params['cap_drop'] is not None: for c in [\"cap_\" +", "state: started - name: Create a data container podman_container: name:", "\"127.0.0.1\" restart_policy: \"no\" device: \"/dev/sda:/dev/xvda:rwm\" ports: - \"8080:9000\" - \"127.0.0.1:8081:9001/udp\"", "to create a user network stack. This is the default", "command: \"sleep 1d\" - name: Stop a container podman_container: name:", "in dir(self) if callable(getattr(self, func)) and func.startswith(\"addparam\")] params_set = (i", "the License is distributed on an \"AS IS\" BASIS, WITHOUT", "... ], \"ExecIDs\": [], \"ExitCommand\": [ \"/usr/bin/podman\", \"--root\", ... ],", "up port redirection on the host system. type: list elements:", "Memory limit (format 10k, where unit = b, k, m", "and optionally the groupname or GID for the specified command.", "\"Restarting\": false, \"Running\": false, \"StartedAt\": \"2019-06-17T19:13:10.152479729+03:00\", \"Status\": \"exited\" }, \"StaticDir\":", "allows you to specify arbitrary environment variables that are available", "\"no_hosts\": False, # libpod issue with networks in inspection \"network\":", "container config if a healthcheck # was configured; otherwise the", "proxied. The default is true. type: bool stop_signal: description: -", "IO weight (relative weight) accepts a weight value between 10", "after = before.copy() if self.params['env']: after.update({ str(k).lower(): str(v).lower() for k,", "relative to the cgroups path of the init process. Cgroups", "return c + ['--systemd=%s' % self.params['systemd']] def addparam_tmpfs(self, c): for", "if self.params[i] is not None) for param in params_set: func_name", "['--env', b\"=\".join([to_bytes(k, errors='surrogate_or_strict') for k in env_value])] return c def", "\"...\", \"RestartCount\": 0, \"Rootfs\": \"\", \"State\": { \"Dead\": false, \"Error\":", "the host to /CONTAINER-DIR in the podman container. type: list", "addparam_user(self, c): return c + ['--user', self.params['user']] def addparam_userns(self, c):", "which the cgroup for the container will be created. If", "user-defined network * ns:<path> path to a network namespace to", "which the cgroup for the container will be created. type:", "before, after) def diffparam_privileged(self): before = self.info['hostconfig']['privileged'] after = self.params['privileged']", "= [] for m in before: if m['type'] == 'volume':", "type: str privileged: description: - Give extended privileges to this", "c): return c + ['--cpu-rt-period', self.params['cpu_rt_period']] def addparam_cpu_rt_runtime(self, c): return", "if no additional CNI networks to join were specified via", "example log_opt \"path=/var/log/container/mycontainer.json\" type: str aliases: - log_options memory: description:", "after = self.params['oom_score_adj'] return self._diff_update_and_compare('oom_score_adj', before, after) def diffparam_privileged(self): before", "cgroups under which the cgroup for the container will be", "[], \"stop_signal\": 15, \"tty\": False, \"user\": \"\", \"uts\": \"\", \"volume\":", "\"\"\"Check if container is different.\"\"\" diffcheck = PodmanContainerDiff(self.module, self.info, self.version)", "be used if no additional CNI networks to join were", "and the second one is the actual healthcheck command. before", "be a string or a list. type: raw cpu_period: description:", "also the upper case versions of those. Defaults to true", "container Default is false. type: bool oom_kill_disable: description: - Whether", "for pub in self.params['publish']: c += ['--publish', pub] return c", "before, after) def diffparam_security_opt(self): before = self.info['hostconfig']['securityopt'] after = self.params['security_opt']", "microseconds type: int cpu_rt_period: description: - Limit the CPU real-time", "- Set custom DNS search domains (Use dns_search with ''", "in self.default_dict: params_with_defaults[p] = self.default_dict[p] else: params_with_defaults[p] = self.module.params[p] return", "diff_func_list: dff_func = getattr(self, func_name) if dff_func(): if fail_fast: return", "cap_add: description: - List of capabilities to add to the", "may consume. type: int cpu_shares: description: - CPU shares (relative", "this parameter has partial idempotency only. def diffparam_hostname(self): before =", "1d with_sequence: count=4 - name: remove container podman_container: name: ohno", "- name: Start 4 load-balanced containers podman_container: name: \"container{{ item", "['--cpus', self.params['cpus']] def addparam_cpuset_cpus(self, c): return c + ['--cpuset-cpus', self.params['cpuset_cpus']]", "not already exist. type: path cgroupns: description: - Path to", "in a line delimited file of environment variables type: path", "def start_stop_delete(self): if self.action in ['stop', 'start']: cmd = [self.action,", "weight) type: int cpus: description: - Number of CPUs. The", "Manage podman containers notes: [] description: - Start, stop, restart", "c + ['--ipc', self.params['ipc']] def addparam_kernel_memory(self, c): return c +", "proxy environment variables are passed into the container if set", "def addparam_device_write_iops(self, c): for dev in self.params['device_write_iops']: c += ['--device-write-iops',", "version_added: '2.9' short_description: Manage podman containers notes: [] description: -", "ansible module object \"\"\" super(PodmanManager, self).__init__() self.module = module self.results", "diffparam_annotation(self): before = self.info['config']['annotations'] or {} after = before.copy() if", "- Mount the container's root filesystem as read only. Default", "c += ['--device', dev] return c def addparam_device_read_bps(self, c): for", "return self._diff_update_and_compare('log_opt', before, after) def diffparam_memory(self): before = str(self.info['hostconfig']['memory']) after", "needed for a container to bootstrap. The value can be", "cmd] def start_stop_delete(self): if self.action in ['stop', 'start']: cmd =", "... ], \"Config\": { \"Annotations\": { \"io.kubernetes.cri-o.ContainerType\": \"sandbox\", \"io.kubernetes.cri-o.TTY\": \"false\"", "integers only. type: str memory_reservation: description: - Memory soft limit", "sorted( diffs['before'].items())]) + \"\\n\" self.diff['after'] = \"\\n\".join( [\"%s - %s\"", "= [self.info['hostconfig']['networkmode']] after = self.params['network'] return self._diff_update_and_compare('network', before, after) def", "an annotation to the container. The format is key value,", "self.name]) return json.loads(out)[0] if rc == 0 else {} def", "@property def exists(self): \"\"\"Check if container exists.\"\"\" return bool(self.info !=", "diffparam_env_host(self): # It's impossible to get from inspest, recreate it", "return self._diff_update_and_compare('group_add', before, after) # Healthcheck is only defined in", "effect if a container is stopped via the podman kill", "+= [\"cap_\" + i.lower() for i in self.module.params['cap_add']] after +=", "the default path of the authentication file by setting the", "Default is SIGTERM. type: int stop_timeout: description: - Timeout (in", "in self.params if self.params[i] is not None) for param in", "to the host. Format - ip:hostPort:containerPort | ip::containerPort | hostPort:containerPort", "self.results.update({'changed': False}) elif self.container.exists: self.container.delete() self.results['actions'].append('deleted %s' % self.container.name) self.results.update({'changed':", "['--rm'] return c def addparam_rootfs(self, c): return c + ['--rootfs=%s'", "\"tty\": False, \"user\": \"\", \"uts\": \"\", \"volume\": [], \"workdir\": \"/\",", "def addparam_label_file(self, c): return c + ['--label-file', self.params['label_file']] def addparam_log_driver(self,", "stderr=err) if self.container.diff: self.results.update({'diff': self.container.diff}) if self.module.params['debug']: self.results.update({'podman_version': self.container.version}) self.module.exit_json(**self.results)", "bool publish: description: - Publish a container's port, or range", "type: bool read_only_tmpfs: description: - If container is running in", "after = self.params['memory_reservation'] return self._diff_update_and_compare('memory_reservation', before, after) def diffparam_network(self): before", "{} def _get_podman_version(self): rc, out, err = self.module.run_command( [self.module.params['executable'], b'--version'])", "CPU usage. This flag tell the kernel to restrict the", "0 and self.params['memory'].isdigit()): after = str(int(self.params['memory']) * 2) return self._diff_update_and_compare('memory_swap',", "= not bool(self.module._diff) different = False for func_name in diff_func_list:", "self.params['env'].items(): c += ['--env', b\"=\".join([to_bytes(k, errors='surrogate_or_strict') for k in env_value])]", "be within the default CNI network's pool (default 10.88.0.0/16). type:", "container and gather info about it.\"\"\" rc, out, err =", "from given module parameters. Returns: list -- list of byte", "use the podman host network stack. * <network-name>|<network-id> connect to", "return c def addparam_volumes_from(self, c): for vol in self.params['volumes_from']: c", "running(self): \"\"\"Return True if container is running now.\"\"\" return self.exists", "after) def diffparam_memory_reservation(self): before = str(self.info['hostconfig']['memoryreservation']) after = self.params['memory_reservation'] return", "supported in all versions if 'cgroups' in self.info['hostconfig']: before =", "in self.info['config']: # the \"test\" key is a list of", "= self.info['hostconfig']['containeridfile'] after = self.params['cidfile'] return self._diff_update_and_compare('cidfile', before, after) def", "description: - Proxy signals sent to the podman run command", "the host's OOM preferences for containers (accepts -1000 to 1000)", "a data container podman_container: name: mydata image: busybox volume: -", "before: after = before else: after = self.params['user'] return self._diff_update_and_compare('user',", "that the returned fact will be removed in Ansible 2.12.", "if maxv and LooseVersion(maxv) < LooseVersion( self.podman_version): self.module.fail_json(msg=\"Parameter %s is", "self.params['device_write_bps']: c += ['--device-write-bps', dev] return c def addparam_device_write_iops(self, c):", "LooseVersion import yaml from ansible.module_utils.basic import AnsibleModule from ansible.module_utils._text import", "l in label])] return c def addparam_label_file(self, c): return c", "'status': ['preview'], 'supported_by': 'community' } DOCUMENTATION = \"\"\" module: podman_container", "the supplied mapping. type: str group_add: description: - Add additional", "+= ['--device-write-iops', dev] return c def addparam_dns(self, c): return c", "that will be launched inside of the container. type: dict", "c + ['--tty=%s' % self.params['tty']] def addparam_uidmap(self, c): for uidmap", "list dns: description: - Set custom DNS servers type: list", "self.container.stderr self.results.update({'changed': changed, 'container': facts, 'podman_actions': self.container.actions}, stdout=out, stderr=err) if", "addparam_no_hosts(self, c): return c + ['--no-hosts=%s' % self.params['no_hosts']] def addparam_oom_kill_disable(self,", "registry. If no tag is included, C(latest) will be used.", "def addparam_device(self, c): for dev in self.params['device']: c += ['--device',", "preference the pod name with \"new:\" type: str privileged: description:", "if it can be. If it cannot be updated, it", "c): return c + ['--dns-search', self.params['dns_search']] def addparam_entrypoint(self, c): return", "ipc: description: - Default is to create a private IPC", "idempotency after = [\":\".join(v.split(\":\")[:2]) for v in self.params['volume']] before, after", "- \"Podman installed on host\" options: name: description: - Name", "limit. Set -1 to have unlimited pids for the container.", "params_set = (i for i in self.params if self.params[i] is", "weight value between 10 and 1000 type: int blkio_weight_device: description:", "- Tune the container's pids limit. Set -1 to have", "0 and 100. type: int mount: description: - Attach a", "Limit write rate (IO per second) to a device (e.g.", "self.info['hostconfig']['blkiodevicewriteiops'] or [] before = [\"%s:%s\" % (i['path'], i['rate']) for", "cpu_period: description: - Limit the CPU real-time period in microseconds", "path (or image name) and tag used to create the", "c): return c + ['--cgroup-parent', self.params['cgroup_parent']] def addparam_cidfile(self, c): return", "- %s\" % (k, v) for k, v in sorted(", "return c + ['--image-volume', self.params['image_volume']] def addparam_init(self, c): return c", "time allowed to complete the healthcheck before an interval is", "= self.params['group_add'] return self._diff_update_and_compare('group_add', before, after) # Healthcheck is only", "in the /etc/subuid file. type: str sysctl: description: - Configure", "supports_check_mode=True, ) # work on input vars if module.params['state'] in", "vars since Ansible 2.8. For compatibility reasons, the facts are", "c + ['--subgidname', self.params['subgidname']] def addparam_subuidname(self, c): return c +", "\"<NAME> (@sshnaidm)\" version_added: '2.9' short_description: Manage podman containers notes: []", "def diffparam_env_host(self): # It's impossible to get from inspest, recreate", "after) def diffparam_cpuset_mems(self): before = self.info['hostconfig']['cpusetmems'] after = self.params['cpuset_mems'] return", "\"rw,size=787448k,mode=1777\" type: dict tty: description: - Allocate a pseudo-TTY. The", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "- Timeout (in seconds) to stop a container. Default is", "c + ['--blkio-weight', self.params['blkio_weight']] def addparam_blkio_weight_device(self, c): for blkio in", "accessible directly as C(podman_container). Note that the returned fact will", "[], \"workdir\": \"/\", } def default_dict(self): # make here any", "after) def diffparam_memory(self): before = str(self.info['hostconfig']['memory']) after = self.params['memory'] return", "Name of the container required: True type: str executable: description:", "after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('volume', before, after) def diffparam_volumes_from(self):", "set the path to the container log file. For example", "self.module = module def construct_command_from_params(self): \"\"\"Create a podman command from", "has limited idempotency, unable to guess the default log_path def", "elif self.container.running and not self.container.different: if self.restart: self.container.restart() self.results['actions'].append('restarted %s'", "swap. Must be used with the -m (--memory) flag. The", "+ ['--healthcheck-command', self.params['healthcheck']] def addparam_healthcheck_interval(self, c): return c + ['--healthcheck-interval',", "return self._diff_update_and_compare('memory_swap', before, after) def diffparam_memory_reservation(self): before = str(self.info['hostconfig']['memoryreservation']) after", "fail_fast = not bool(self.module._diff) different = False for func_name in", "podman_container: name: mycontainer state: stopped - name: Start 4 load-balanced", "[\":\".join(v) for v in volumes] # Ignore volumes option for", "c): return c + ['--interactive=%s' % self.params['interactive']] def addparam_ip(self, c):", "changed=True): \"\"\"Inspect the current container, update results with last info,", "podman container, inspects it and checks its current state \"\"\"", "description: - Logging driver. Used to set the log driver", "container. The default is false. type: bool publish: description: -", "how to handle the builtin image volumes. The options are", "stop a container. Default is SIGTERM. type: int stop_timeout: description:", "oom_kill_disable: description: - Whether to disable OOM Killer for the", "def addparam_sysctl(self, c): for sysctl in self.params['sysctl'].items(): c += ['--sysctl',", "before = str(self.info['hostconfig']['memory']) after = self.params['memory'] return self._diff_update_and_compare('memory', before, after)", "after] return self._diff_update_and_compare('command', before, after) return False def diffparam_conmon_pidfile(self): before", "for dev in self.params['device_read_bps']: c += ['--device-read-bps', dev] return c", "= name self.stdout, self.stderr = '', '' self.info = self.get_info()", "CPU real-time period in microseconds type: int cpu_rt_period: description: -", "if self.info['hostconfig']['extrahosts']: before = dict([i.split(\":\") for i in self.info['hostconfig']['extrahosts']]) else:", "the requested config. Image version will be taken into account", "return self.defaults class PodmanContainerDiff: def __init__(self, module, info, podman_version): self.module", "return c + ['--interactive=%s' % self.params['interactive']] def addparam_ip(self, c): return", "addparam_device_read_bps(self, c): for dev in self.params['device_read_bps']: c += ['--device-read-bps', dev]", "https_proxy, ftp_proxy, no_proxy, and also the upper case versions of", "description: - Number of CPUs. The default is 0.0 which", "+= ['--group-add', g] return c def addparam_healthcheck(self, c): return c", "'env_host', \"ulimit\", # Defaults depend on user and platform, impossible", "is only defined in container config if a healthcheck #", "restart(self): \"\"\"Restart the container.\"\"\" self.stop() self.run() class PodmanManager: \"\"\"Module manager", "{ \"Dead\": false, \"Error\": \"\", \"ExitCode\": 0, \"FinishedAt\": \"2019-06-17T19:13:10.157518963+03:00\", \"Healthcheck\":", "module.run_command([module_exec, 'image', 'exists', image]) if rc == 0: return image_actions", "description: - List of capabilities to drop from the container.", "and any provided configuration parameters. If no container matches the", "c + ['--cpuset-mems', self.params['cpuset_mems']] def addparam_detach(self, c): return c +", "['create', 'run']: cmd = [self.action, '--name', self.params['name']] all_param_methods = [func", "is a single character or ctrl-value type: str device: description:", "of host-to-IP mappings, where each host name is a key", "- Force restart of container. type: bool default: False aliases:", "it exits. The default is false. type: bool aliases: -", "in [{}, [], '']: different = True return different def", "command from given module parameters. Returns: list -- list of", "c + ['--log-opt', self.params['log_opt']] def addparam_memory(self, c): return c +", "name: Restart a container podman_container: name: myapplication image: redis state:", "self.module.run_command( [self.module.params['executable'], b'container'] + b_command, expand_user_and_vars=False) self.stdout = out self.stderr", "[{}, [], '']: different = True return different def ensure_image_exists(module,", "myredis image: redis command: redis-server --appendonly yes state: present recreate:", "the container. type: list elements: str cgroup_parent: description: - Path", "= [] module_exec = module.params['executable'] if not image: return image_actions", "def addparam_cgroup_parent(self, c): return c + ['--cgroup-parent', self.params['cgroup_parent']] def addparam_cidfile(self,", "user namespace mode for the container. It defaults to the", "configuration. If no container matches the name, a container will", "For compatibility reasons, the facts are also accessible directly as", "law or agreed to in writing, software # distributed under", "[], \"healthcheck\": \"\", \"ipc\": \"\", \"kernelmemory\": \"0\", \"log_driver\": \"k8s-file\", \"memory\":", "\"\"\"Recreate the container.\"\"\" self.delete() self.run() def restart(self): \"\"\"Restart the container.\"\"\"", "CGroups, and thus conflicts with CGroup options cgroupns and cgroup-parent.", "self.module.params[p] is not None and self.module.params[p] not in [{}, [],", "def diffparam_cpuset_mems(self): before = self.info['hostconfig']['cpusetmems'] after = self.params['cpuset_mems'] return self._diff_update_and_compare('cpuset_mems',", "before, after) return False def diffparam_conmon_pidfile(self): before = self.info['conmonpidfile'] if", "return self._diff_update_and_compare('volume', before, after) def diffparam_volumes_from(self): before = self.info['hostconfig']['volumesfrom'] or", "specify. type: int cpu_rt_runtime: description: - Limit the CPU real-time", "= self._get_podman_version() self.diff = {} self.actions = [] @property def", "of image Returns: list -- list of image actions -", "or [] after = [] if self.module.params['cap_add'] is not None:", "def addparam_tmpfs(self, c): for tmpfs in self.params['tmpfs'].items(): c += ['--tmpfs',", "state: absent - name: Writing output podman_container: name: myservice image:", "c + ['--cpus', self.params['cpus']] def addparam_cpuset_cpus(self, c): return c +", "sorted(list(set(after))) return self._diff_update_and_compare('device_read_bps', before, after) def diffparam_device_read_iops(self): before = self.info['hostconfig']['blkiodevicereadiops']", "Attach a filesystem mount to the container. bind or tmpfs", "to specify arbitrary environment variables that are available for the", "inspest, recreate it if not default before = False after", "'supported_by': 'community' } DOCUMENTATION = \"\"\" module: podman_container author: -", "or {} after = before.copy() if self.params['label']: after.update({ str(k).lower(): str(v).lower()", "before = not bool(self.info['hostspath']) after = self.params['no_hosts'] if self.params['network'] ==", "self._diff_update_and_compare('no_hosts', before, after) def diffparam_oom_score_adj(self): before = self.info['hostconfig']['oomscoreadj'] after =", "type: str device: description: - Add a host device to", "str aliases: - exposed - exposed_ports force_restart: description: - Force", "self.params['ip']] def addparam_ipc(self, c): return c + ['--ipc', self.params['ipc']] def", "self.params['cap_drop']: c += ['--cap-drop', cap_drop] return c def addparam_cgroups(self, c):", "not specified!') if not self.container.exists: self.container.create() self.results['actions'].append('created %s' % self.container.name)", "return c + ['--stop-signal', self.params['stop_signal']] def addparam_stop_timeout(self, c): return c", "- published_ports publish_all: description: - Publish all exposed ports to", "(in seconds) to stop a container. Default is 10. type:", "maxv and LooseVersion(maxv) < LooseVersion( self.podman_version): self.module.fail_json(msg=\"Parameter %s is supported", "to force a matching container to be stopped and restarted.", "Create a tmpfs mount. For example tmpfs \"/tmp\" \"rw,size=787448k,mode=1777\" type:", "[\":\".join([i['pathonhost'], i['pathincontainer']]) for i in self.info['hostconfig']['devices']] after = [\":\".join(i.split(\":\")[:2]) for", "systemd mode. The default is true. type: bool tmpfs: description:", "c def addparam_gidmap(self, c): return c + ['--gidmap', self.params['gidmap']] def", "return c + ['--rootfs=%s' % self.params['rootfs']] def addparam_security_opt(self, c): for", "in the host to /CONTAINER-DIR in the podman container. type:", "for i in after] return self._diff_update_and_compare('command', before, after) return False", "description: - Determines whether the container will create CGroups. Valid", "\"sh\", \"ProcessLabel\": \"system_u:system_r:container_t:s0:c282,c782\", \"ResolvConfPath\": \"...\", \"RestartCount\": 0, \"Rootfs\": \"\", \"State\":", "['--label-file', self.params['label_file']] def addparam_log_driver(self, c): return c + ['--log-driver', self.params['log_driver']]", "self.info['conmonpidfile'] if self.module.params['conmon_pidfile'] is None: after = before else: after", "are enabled and disabled, which the default being enabled. The", "memory plus swap. Must be used with the -m (--memory)", "} DOCUMENTATION = \"\"\" module: podman_container author: - \"<NAME> (@sshnaidm)\"", "can be disabled by setting the http_proxy option to false.", "and manage Podman containers requirements: - \"Podman installed on host\"", "(bytes per second) from a device (e.g. device-read-bps /dev/sda:1mb) type:", "\"docker.io/library/busybox:latest\", \"IsInfra\": false, \"LogPath\": \"/tmp/container/mycontainer.json\", \"MountLabel\": \"system_u:object_r:container_file_t:s0:c282,c782\", \"Mounts\": [ ...", "namespace via 'network container:<name|id>'. The address must be within the", "self.params['volume']] before, after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('volume', before, after)", "on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS", "Each host name will be added to the container's ``/etc/hosts``", "the CPU real-time period in microseconds. Limit the container's Real", "self.update_container_result() elif self.container.stopped and self.container.different: self.container.recreate() self.results['actions'].append('recreated %s' % self.container.name)", "type: bool tmpfs: description: - Create a tmpfs mount. For", "supported for integers only. type: str memory_swappiness: description: - Tune", "before = self.info['config']['image'] after = self.params['image'] mode = self.params['image_strict'] if", "'container': {}, } self.name = self.module.params['name'] self.executable = \\ self.module.get_bin_path(self.module.params['executable'],", "will not take effect if a container is stopped via", "- volumes volumes_from: description: - Mount volumes from the specified", "container in a new user namespace using the supplied mapping.", "directory (/). type: str \"\"\" EXAMPLES = \"\"\" - name:", "Publish a container's port, or range of ports, to the", "- published - published_ports publish_all: description: - Publish all exposed", "self.run() def restart(self): \"\"\"Restart the container.\"\"\" self.stop() self.run() class PodmanManager:", "name of container \"\"\" super(PodmanContainer, self).__init__() self.module = module self.name", "states_map[self.state] process_action() self.module.fail_json(msg=\"Unexpected logic error happened, \" \"please contact maintainers", "be used with the -m (--memory) flag. The swap LIMIT", "be created. If the path is not absolute, the path", "- 'tmpfs' - 'ignore' image_strict: description: - Whether to compare", "reuse another container's network stack * host use the podman", "[] if self.module.params['cap_add'] is not None: after += [\"cap_\" +", "def diffparam_ipc(self): before = self.info['hostconfig']['ipcmode'] after = self.params['ipc'] return self._diff_update_and_compare('ipc',", "+= ['--sysctl', b\"=\".join([to_bytes(k, errors='surrogate_or_strict') for k in sysctl])] return c", "self.results['actions'].append('started %s' % self.container.name) self.update_container_result() def make_stopped(self): \"\"\"Run actions if", "['--entrypoint', self.params['entrypoint']] def addparam_env(self, c): for env_value in self.params['env'].items(): c", "self.params['cpuset_cpus'] return self._diff_update_and_compare('cpuset_cpus', before, after) def diffparam_cpuset_mems(self): before = self.info['hostconfig']['cpusetmems']", "diffparam_device_read_iops(self): before = self.info['hostconfig']['blkiodevicereadiops'] or [] before = [\"%s:%s\" %", "used to create the container. If an image is not", "def diffparam_cpu_shares(self): before = self.info['hostconfig']['cpushares'] after = self.params['cpu_shares'] return self._diff_update_and_compare('cpu_shares',", "weight) accepts a weight value between 10 and 1000 type:", "= ensure_image_exists(self.module, self.image) self.results['actions'] += image_actions self.state = self.module.params['state'] self.restart", "after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('device_write_bps', before, after) def diffparam_device_write_iops(self):", "}, \"OOMKilled\": false, \"OciVersion\": \"1.0.1-dev\", \"Paused\": false, \"Pid\": 4083, \"Restarting\":", "distutils.version import LooseVersion import yaml from ansible.module_utils.basic import AnsibleModule from", "self.action = action self.podman_version = podman_version self.module = module def", "inspects it and checks its current state \"\"\" def __init__(self,", "addparam_healthcheck(self, c): return c + ['--healthcheck-command', self.params['healthcheck']] def addparam_healthcheck_interval(self, c):", "c in after: after.remove(c) before, after = sorted(list(set(before))), sorted(list(set(after))) return", "not default before = False after = self.params['env_host'] return self._diff_update_and_compare('env_host',", "after = self.params['etc_hosts'] return self._diff_update_and_compare('etc_hosts', before, after) def diffparam_group_add(self): before", "[\"%s:%s\" % (i['path'], i['rate']) for i in before] after =", "rate (IO per second) to a device (e.g. device-write-iops /dev/sda:1000)", "container.\"\"\" self.stop() self.run() class PodmanManager: \"\"\"Module manager class. Defines according", "c + ['--privileged=%s' % self.params['privileged']] def addparam_publish(self, c): for pub", "and func.startswith(\"addparam\")] params_set = (i for i in self.params if", "self.params['command'] else: cmd += self.params['command'].split() return [to_bytes(i, errors='surrogate_or_strict') for i", "'run', 'stop', 'create', 'delete', 'start' params {dict} -- dictionary of", "= self.params['tty'] return self._diff_update_and_compare('tty', before, after) def diffparam_user(self): before =", "self.params['command'] if isinstance(after, str): after = [i.lower() for i in", "container. type: str pod: description: - Run container in an", "addparam_cpu_period(self, c): return c + ['--cpu-period', self.params['cpu_period']] def addparam_cpu_rt_period(self, c):", "Limit the CPU real-time period in microseconds type: int cpu_rt_period:", "self.params['cpus'] return self._diff_update_and_compare('cpus', before, after) def diffparam_cpuset_cpus(self): before = self.info['hostconfig']['cpusetcpus']", "before, after) def diffparam_device_read_bps(self): before = self.info['hostconfig']['blkiodevicereadbps'] or [] before", "type: str rm: description: - Automatically remove the container when", "about it.\"\"\" rc, out, err = self.module.run_command( [self.module.params['executable'], b'container', b'inspect',", "bool read_only_tmpfs: description: - If container is running in --read-only", "\"cpu_rt_runtime\": 0, \"cpu_rt_period\": 0, \"cpuset_cpus\": \"\", \"cpuset_mems\": \"\", \"detach\": True,", "type: list elements: str cgroup_parent: description: - Path to cgroups", "str log_driver: description: - Logging driver. Used to set the", "is supported from podman \" \"version %s only! Current version", "for i in before] after = self.params['device_read_bps'] or [] before,", "busybox volume: - /tmp/data - name: Re-create a redis container", "false. type: bool ip: description: - Specify a static IP", "recreate: yes expose: - 6379 volumes_from: - mydata - name:", "self.module.params, self.version, self.module, ).construct_command_from_params() full_cmd = \" \".join([self.module.params['executable']] + [to_native(i)", "disabled, which the default being enabled. The disabled option will", "is necessary when using systemd to restart Podman containers. type:", "desired state is 'absent'.\"\"\" if not self.container.exists: self.results.update({'changed': False}) elif", "}, \"Volumes\": null, \"WorkingDir\": \"/\" }, \"ConmonPidFile\": \"...\", \"Created\": \"2019-06-17T19:13:09.873858307+03:00\",", "self.params['cpuset_cpus']] def addparam_cpuset_mems(self, c): return c + ['--cpuset-mems', self.params['cpuset_mems']] def", "errors='surrogate_or_strict') for i in cmd] def start_stop_delete(self): if self.action in", "The default is true type: bool recreate: description: - Use", "description: - Set custom DNS search domains (Use dns_search with", "<number>[<unit>], where unit = b, k, m or g) Note", "self.container.run() self.results['actions'].append('started %s' % self.container.name) self.update_container_result() elif self.container.stopped and self.container.different:", "and SIGKILL are not proxied. The default is true. type:", "networking * container:<name|id> reuse another container's network stack * host", "item }}\" recreate: yes image: someuser/anotherappimage command: sleep 1d with_sequence:", "{} after = before.copy() if self.params['label']: after.update({ str(k).lower(): str(v).lower() for", "= self.params['no_hosts'] if self.params['network'] == ['none']: after = True return", "return self._diff_update_and_compare('device_read_bps', before, after) def diffparam_device_read_iops(self): before = self.info['hostconfig']['blkiodevicereadiops'] or", "def addparam_authfile(self, c): return c + ['--authfile', self.params['authfile']] def addparam_blkio_weight(self,", "allow execution (0-3, 0,1) type: str cpuset_mems: description: - Memory", "k, v in self.params['label'].items() }) return self._diff_update_and_compare('label', before, after) def", "be larger than -m (--memory) value. By default, the swap", "is not joining another container's network namespace via 'network container:<name|id>'.", "'network container:<name|id>'. The address must be within the default CNI", "By default, the swap LIMIT will be set to double", "container will be updated, if it can be. If it", "}, \"Path\": \"sh\", \"ProcessLabel\": \"system_u:system_r:container_t:s0:c282,c782\", \"ResolvConfPath\": \"...\", \"RestartCount\": 0, \"Rootfs\":", "= [] else: after = self.params['blkio_weight_device'] return self._diff_update_and_compare('blkio_weight_device', before, after)", "in container config if a healthcheck # was configured; otherwise", "description: - Set or alter a healthcheck command for a", "is_different = diffcheck.is_different() diffs = diffcheck.diff if self.module._diff and is_different", "is the root directory (/). type: str \"\"\" EXAMPLES =", "c += ['--volumes-from', vol] return c def addparam_workdir(self, c): return", "libpod issue with networks in inspection \"network\": [\"default\"], \"oom_score_adj\": 0,", "force the re-creation of an existing container. type: bool default:", "the path to the container log file. For example log_opt", "a running container matching the name and any provided configuration.", "before, after) def diffparam_env_host(self): # It's impossible to get from", "self.params['cpu_rt_runtime'] return self._diff_update_and_compare('cpu_rt_runtime', before, after) def diffparam_cpu_shares(self): before = self.info['hostconfig']['cpushares']", "Time tasks may consume. type: int cpu_shares: description: - CPU", "def addparam_healthcheck_retries(self, c): return c + ['--healthcheck-retries', self.params['healthcheck_retries']] def addparam_healthcheck_start_period(self,", "dev] return c def addparam_device_write_iops(self, c): for dev in self.params['device_write_iops']:", "\" \".join([self.module.params['executable']] + [to_native(i) for i in b_command]) self.module.log(\"PODMAN-CONTAINER-DEBUG: %s\"", "{ \"blkio_weight\": 0, \"cgroups\": \"default\", \"cgroup_parent\": \"\", \"cidfile\": \"\", \"cpus\":", "return c + ['--read-only-tmpfs=%s' % self.params['read_only_tmpfs']] def addparam_restart_policy(self, c): return", "format is <device-on-host>[:<device-on-container>][:<permissions>] (e.g. device /dev/sdc:/dev/xvdc:rwm) type: list elements: str", "Restart policy to follow when containers exit. Restart policy will", "self.params['dns_option']] def addparam_dns_search(self, c): return c + ['--dns-search', self.params['dns_search']] def", "in self.params['security_opt']: c += ['--security-opt', secopt] return c def addparam_shm_size(self,", "after) def diffparam_blkio_weight_device(self): before = self.info['hostconfig']['blkioweightdevice'] if before == []", "addparam_pid(self, c): return c + ['--pid', self.params['pid']] def addparam_pids_limit(self, c):", "mode, then mount a read-write tmpfs on /run, /tmp, and", "process_action = states_map[self.state] process_action() self.module.fail_json(msg=\"Unexpected logic error happened, \" \"please", "with 'name' in the /etc/subgid file. type: str subuidname: description:", "to the container-init binary. type: str interactive: description: - Keep", "\"detach\": True, \"device\": [], \"env_host\": False, \"etc_hosts\": {}, \"group_add\": [],", "account when comparing configuration. Use the recreate option to force", "Defines according to parameters what actions should be applied to", "= self.info['config']['tty'] after = self.params['tty'] return self._diff_update_and_compare('tty', before, after) def", "def addparam_dns_search(self, c): return c + ['--dns-search', self.params['dns_search']] def addparam_entrypoint(self,", "option will force the container to not create CGroups, and", "= diffcheck.diff if self.module._diff and is_different and diffs['before'] and diffs['after']:", "between 10 and 1000 type: int blkio_weight_device: description: - Block", "not image: return image_actions rc, out, err = module.run_command([module_exec, 'image',", "after = self.params['uts'] return self._diff_update_and_compare('uts', before, after) def diffparam_volume(self): before", "b'--version']) if rc != 0 or not out or \"version\"", "will be taken into account when comparing configuration. Use the", "description: - Specify a static IP address for the container,", "being enabled. The disabled option will force the container to", "after) def diffparam_image(self): # TODO(sshnaidm): for strict image compare mode", "redis state: started restart: yes etc_hosts: other: \"127.0.0.1\" restart_policy: \"no\"", "Any additionl command options you want to pass to podman", "be launched inside of the container. type: dict env_file: description:", "executable: description: - Path to C(podman) executable if it is", "self._diff_update_and_compare('healthcheck', before, after) # Because of hostname is random generated,", "addparam_cpuset_cpus(self, c): return c + ['--cpuset-cpus', self.params['cpuset_cpus']] def addparam_cpuset_mems(self, c):", "- A limit value equal to memory plus swap. Must", "changes to self.defaults related to podman version return self.defaults class", "detach: description: - Run container in detach mode type: bool", "integer between 0 and 100. type: int mount: description: -", "command. type: str userns: description: - Set the user namespace", "OOM preferences for containers (accepts -1000 to 1000) type: int", "* always - Restart containers when they exit, regardless of", "def diffparam_device(self): before = [\":\".join([i['pathonhost'], i['pathincontainer']]) for i in self.info['hostconfig']['devices']]", "of the registered vars since Ansible 2.8. For compatibility reasons,", "idempotent parameters for p in self.non_idempotent: if self.module.params[p] is not", "indefinitely type: str rm: description: - Automatically remove the container", "2 items where the first one is # \"CMD-SHELL\" and", "c): return c + ['--cidfile', self.params['cidfile']] def addparam_conmon_pidfile(self, c): return", "generated, this parameter has partial idempotency only. def diffparam_hostname(self): before", "- Configure namespaced kernel parameters at runtime type: dict systemd:", "# distributed under the License is distributed on an \"AS", "environment variables type: path env_host: description: - Use all current", "return c def addparam_expose(self, c): for exp in self.params['expose']: c", "process. This can be disabled by setting the http_proxy option", "c + ['--healthcheck-retries', self.params['healthcheck_retries']] def addparam_healthcheck_start_period(self, c): return c +", "image %s\" % image, stdout=out, stderr=err) image_actions.append(\"pulled image %s\" %", "in ['stop', 'start']: cmd = [self.action, self.params['name']] return [to_bytes(i, errors='surrogate_or_strict')", "after = [i.lower() for i in after] return self._diff_update_and_compare('command', before,", "False def diffparam_annotation(self): before = self.info['config']['annotations'] or {} after =", "self._diff_update_and_compare('env', before, after) def diffparam_etc_hosts(self): if self.info['hostconfig']['extrahosts']: before = dict([i.split(\":\")", "(Use dns_search with '' if you don't wish to set", "Podman containers. type: path command: description: - Override command of", "at runtime type: dict systemd: description: - Run container in", "container. type: bool default: False aliases: - restart gidmap: description:", "minv, self.podman_version)) def addparam_annotation(self, c): for annotate in self.params['annotation'].items(): c", "name is a key in the dictionary. Each host name", "If a container matches the name but the provided configuration", "def addparam_device_read_bps(self, c): for dev in self.params['device_read_bps']: c += ['--device-read-bps',", "or a range of ports (e.g. expose \"3300-3310\") to set", "self.params['healthcheck_start_period']] def addparam_healthcheck_timeout(self, c): return c + ['--healthcheck-timeout', self.params['healthcheck_timeout']] def", "is not running now.\"\"\" return self.exists and not self.info['State']['Running'] def", "... }, \"HostConfig\": { ... }, \"HostnamePath\": \"...\", \"HostsPath\": \"...\",", "+ ['--cpu-shares', self.params['cpu_shares']] def addparam_cpus(self, c): return c + ['--cpus',", "diffs = diffcheck.diff if self.module._diff and is_different and diffs['before'] and", "allow execution (0-3, 0,1). Only effective on NUMA systems. type:", "def diffparam_cidfile(self): before = self.info['hostconfig']['containeridfile'] after = self.params['cidfile'] return self._diff_update_and_compare('cidfile',", "minv='1.5.0') return c + ['--env-host=%s' % self.params['env_host']] def addparam_etc_hosts(self, c):", "all versions if 'cgroups' in self.info['hostconfig']: before = self.info['hostconfig']['cgroups'] after", "diffparam_pid(self): before = self.info['hostconfig']['pidmode'] after = self.params['pid'] return self._diff_update_and_compare('pid', before,", "for integers only. type: str memory_swappiness: description: - Tune a", "podman inspection output. - Note that facts are part of", "in a new user namespace using the supplied mapping. type:", "custom DNS options type: str dns_search: description: - Set custom", "an image ID. If this is the case, the image", "image: ubuntu:14.04 command: \"sleep 1d\" - name: Stop a container", "runs in a separate process than Podman, so this is", "device (e.g. device-read-iops /dev/sda:1000) type: list device_write_bps: description: - Limit", "def diffparam_log_driver(self): before = self.info['hostconfig']['logconfig']['type'] after = self.params['log_driver'] return self._diff_update_and_compare('log_driver',", "def addparam_dns(self, c): return c + ['--dns', ','.join(self.params['dns'])] def addparam_dns_option(self,", "before.split(\"/\")[-1] after = after.split(\"/\")[-1] return self._diff_update_and_compare('image', before, after) def diffparam_ipc(self):", "The number of retries allowed before a healthcheck is considered", "str default: started choices: - absent - present - stopped", "= self.params['log_driver'] return self._diff_update_and_compare('log_driver', before, after) # Parameter has limited", "is # \"CMD-SHELL\" and the second one is the actual", "tag used to create the container. If an image is", "after) # Because of hostname is random generated, this parameter", "after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('security_opt', before, after) def diffparam_stop_signal(self):", "false, \"Pid\": 4083, \"Restarting\": false, \"Running\": false, \"StartedAt\": \"2019-06-17T19:13:10.152479729+03:00\", \"Status\":", "str \"\"\" EXAMPLES = \"\"\" - name: Run container podman_container:", "the init process. Cgroups will be created if they do", "directly as C(podman_container). Note that the returned fact will be", "['--cpu-shares', self.params['cpu_shares']] def addparam_cpus(self, c): return c + ['--cpus', self.params['cpus']]", "in volumes] # Ignore volumes option for idempotency after =", "the podman host network stack. * <network-name>|<network-id> connect to a", "under the License is distributed on an \"AS IS\" BASIS,", "self.version) is_different = diffcheck.is_different() diffs = diffcheck.diff if self.module._diff and", "bool default: False init: description: - Run an init inside", "device-write-iops /dev/sda:1000) type: list dns: description: - Set custom DNS", "- if it pulled or nothing was done \"\"\" image_actions", "def addparam_subuidname(self, c): return c + ['--subuidname', self.params['subuidname']] def addparam_sysctl(self,", "addparam_tmpfs(self, c): for tmpfs in self.params['tmpfs'].items(): c += ['--tmpfs', ':'.join(tmpfs)]", "null, \"WorkingDir\": \"/\" }, \"ConmonPidFile\": \"...\", \"Created\": \"2019-06-17T19:13:09.873858307+03:00\", \"Dependencies\": [],", "this file except in compliance with the License. You may", "of capabilities to drop from the container. type: list elements:", "\"uts\": \"\", \"volume\": [], \"workdir\": \"/\", } def default_dict(self): #", "are disabled. type: str uts: description: - Set the UTS", "dir(self) if callable(getattr(self, func)) and func.startswith( \"diffparam\")] fail_fast = not", "not self.container.exists: self.container.create() self.results['actions'].append('created %s' % self.container.name) self.update_container_result() if self.container.stopped:", "log driver for the container. For example log_driver \"k8s-file\". type:", "for a container to bootstrap. The value can be expressed", "10.88.0.0/16). type: str ipc: description: - Default is to create", "def addparam_healthcheck_timeout(self, c): return c + ['--healthcheck-timeout', self.params['healthcheck_timeout']] def addparam_hostname(self,", "tell the kernel to restrict the container's Real Time CPU", "limit (format <number>[<unit>], where unit = b, k, m or", "This flag tell the kernel to restrict the container's Real", "type: int cpu_rt_runtime: description: - Limit the CPU real-time runtime", "['--healthcheck-interval', self.params['healthcheck_interval']] def addparam_healthcheck_retries(self, c): return c + ['--healthcheck-retries', self.params['healthcheck_retries']]", "0, \"cpu_period\": 0, \"cpu_rt_runtime\": 0, \"cpu_rt_period\": 0, \"cpuset_cpus\": \"\", \"cpuset_mems\":", "self.container.recreate() self.results['actions'].append('recreated %s' % self.container.name) self.update_container_result() elif self.container.running and not", "if changed else self.container.info out, err = self.container.stdout, self.container.stderr self.results.update({'changed':", "file except in compliance with the License. You may obtain", "- Write the container ID to the file type: path", "the http_proxy option to false. The environment variables passed in", "reaps processes. type: str init_path: description: - Path to the", "(self.container.different or self.recreate): self.container.recreate() self.results['actions'].append('recreated %s' % self.container.name) self.update_container_result() elif", "volume: description: - Create a bind mount. If you specify,", "OR CONDITIONS OF ANY KIND, either express or implied. See", "\"HostConfig\": { ... }, \"HostnamePath\": \"...\", \"HostsPath\": \"...\", \"ID\": \"...\",", "type: list device_write_bps: description: - Limit write rate (bytes per", "+ ['--tty=%s' % self.params['tty']] def addparam_uidmap(self, c): for uidmap in", "rate (IO per second) from a device (e.g. device-read-iops /dev/sda:1000)", "of time in a given CPU period Real Time tasks", "= self.module.params[p] return params_with_defaults def _diff_update_and_compare(self, param_name, before, after): if", "before = self.info['effectivecaps'] or [] after = before[:] if self.module.params['cap_drop']", "If no tag is included, C(latest) will be used. -", "where each host name is a key in the dictionary.", "['--oom-kill-disable=%s' % self.params['oom_kill_disable']] def addparam_oom_score_adj(self, c): return c + ['--oom-score-adj',", "always - Restart containers when they exit, regardless of status,", "- Add additional groups to run as type: list healthcheck:", "== [] and self.module.params['blkio_weight_device'] is None: after = [] else:", "after = self.params['hostname'] or before return self._diff_update_and_compare('hostname', before, after) def", "def addparam_security_opt(self, c): for secopt in self.params['security_opt']: c += ['--security-opt',", "def addparam_subgidname(self, c): return c + ['--subgidname', self.params['subgidname']] def addparam_subuidname(self,", "value is 30s type: str hostname: description: - Container host", "When set to true, keep stdin open even if not", "tmpfs For example mount \"type=bind,source=/path/on/host,destination=/path/in/container\" type: str network: description: -", "for i in cmd] if self.action == 'delete': cmd =", "class PodmanManager: \"\"\"Module manager class. Defines according to parameters what", "after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('device_read_iops', before, after) def diffparam_device_write_bps(self):", "for env_value in self.params['env'].items(): c += ['--env', b\"=\".join([to_bytes(k, errors='surrogate_or_strict') for", "['--image-volume', self.params['image_volume']] def addparam_init(self, c): return c + ['--init', self.params['init']]", "self._perform_action('create') def recreate(self): \"\"\"Recreate the container.\"\"\" self.delete() self.run() def restart(self):", "return [to_bytes(i, errors='surrogate_or_strict') for i in cmd] def check_version(self, param,", "the key sequence for detaching a container. Format is a", "the host. Format - ip:hostPort:containerPort | ip::containerPort | hostPort:containerPort |", "self.results['actions'].append('recreated %s' % self.container.name) self.update_container_result() elif self.container.running and not self.container.different:", "container's network stack * host use the podman host network", "root filesystem as read only. Default is false type: bool", "sample: '{ \"AppArmorProfile\": \"\", \"Args\": [ \"sh\" ], \"BoundingCaps\": [", "is false. type: bool read_only: description: - Mount the container's", "% (k, v) for k, v in sorted( diffs['after'].items())]) +", "for i in self.module.params['cap_add']] after += before before, after =", "c): return c + ['--mount', self.params['mount']] def addparam_network(self, c): return", "inside the container that forwards signals and reaps processes. type:", "before, after) def diffparam_uts(self): before = self.info['hostconfig']['utsmode'] after = self.params['uts']", "self.container.info out, err = self.container.stdout, self.container.stderr self.results.update({'changed': changed, 'container': facts,", "matches the name, a container will be created. If a", "specific options. Used to set the path to the container", "self.delete() self.run() def restart(self): \"\"\"Restart the container.\"\"\" self.stop() self.run() class", "return image_actions rc, out, err = module.run_command([module_exec, 'image', 'exists', image])", "started image: description: - Repository path (or image name) and", "If you omit the unit, the system uses bytes. If", "when using systemd to restart Podman containers. type: path command:", "return c + ['--subgidname', self.params['subgidname']] def addparam_subuidname(self, c): return c", "self.make_stopped } process_action = states_map[self.state] process_action() self.module.fail_json(msg=\"Unexpected logic error happened,", "the default CNI network's pool (default 10.88.0.0/16). type: str ipc:", "in an existing pod. If you want podman to make", "to have unlimited pids for the container. type: str pod:", "using the map with 'name' in the /etc/subuid file. type:", "k in env_value])] return c def addparam_env_file(self, c): return c", "to double the value of --memory Note - idempotency is", "[], \"ExitCommand\": [ \"/usr/bin/podman\", \"--root\", ... ], \"GraphDriver\": { ...", "\"uid\": 0 }, \"Volumes\": null, \"WorkingDir\": \"/\" }, \"ConmonPidFile\": \"...\",", "container:<name|id>'. The address must be within the default CNI network's", "use this file except in compliance with the License. You", "def addparam_user(self, c): return c + ['--user', self.params['user']] def addparam_userns(self,", "\"\", \"State\": { \"Dead\": false, \"Error\": \"\", \"ExitCode\": 0, \"FinishedAt\":", "return bool(self.info != {}) @property def different(self): \"\"\"Check if container", "], \"BoundingCaps\": [ \"CAP_CHOWN\", ... ], \"Config\": { \"Annotations\": {", "# Add your own args for podman command def addparam_cmd_args(self,", "c += ['--security-opt', secopt] return c def addparam_shm_size(self, c): return", "pull image %s\" % image, stdout=out, stderr=err) image_actions.append(\"pulled image %s\"", "- journald - json-file log_opt: description: - Logging driver specific", "to a user-defined network * ns:<path> path to a network", "pull it or fail. Arguments: module {obj} -- ansible module", "when they exit with a non-0 exit code, retrying indefinitely", "\"log_driver\": \"k8s-file\", \"memory\": \"0\", \"memory_swap\": \"0\", \"memory_reservation\": \"0\", # \"memory_swappiness\":", "path to a network namespace to join * slirp4netns use", "class PodmanDefaults: def __init__(self, module, podman_version): self.module = module self.version", "before, after) def diffparam_workdir(self): before = self.info['config']['workingdir'] after = self.params['workdir']", "%s only! Current version is %s\" % ( param, minv,", "0.0, \"cpu_shares\": 0, \"cpu_quota\": 0, \"cpu_period\": 0, \"cpu_rt_runtime\": 0, \"cpu_rt_period\":", "params_set: func_name = \"_\".join([\"addparam\", param]) if func_name in all_param_methods: cmd", "rc, out, err = self.module.run_command( [self.module.params['executable'], b'container', b'inspect', self.name]) return", "addparam_env_file(self, c): return c + ['--env-file', self.params['env_file']] def addparam_env_host(self, c):", "default before = False after = self.params['env_host'] return self._diff_update_and_compare('env_host', before,", "before = self.info['hostconfig']['autoremove'] after = self.params['rm'] return self._diff_update_and_compare('rm', before, after)", "before = self.info['config']['healthcheck']['test'][1] else: before = '' after = self.params['healthcheck']", "c += ['--publish', pub] return c def addparam_publish_all(self, c): return", "%s is supported till podman \" \"version %s only! Current", "integers only. type: str memory_swap: description: - A limit value", "= self.module.run_command( [self.module.params['executable'], b'container', b'inspect', self.name]) return json.loads(out)[0] if rc", "config. Image version will be taken into account when comparing", "diffparam_command(self): # TODO(sshnaidm): to inspect image to get the default", "the Apache License, Version 2.0 (the \"License\"); you may #", "options type: str dns_search: description: - Set custom DNS search", "action {str} -- action to perform - start, create, stop,", "available for remote commands) You can also override the default", "a matching container to be stopped and restarted. - I(stopped)", "\"\") before = before.split(\"/\")[-1] after = after.split(\"/\")[-1] return self._diff_update_and_compare('image', before,", "self.params['healthcheck']] def addparam_healthcheck_interval(self, c): return c + ['--healthcheck-interval', self.params['healthcheck_interval']] def", "def diffparam_cgroups(self): # Cgroups output is not supported in all", "I(absent) - A container matching the specified name will be", "healthcheck_interval: description: - Set an interval for the healthchecks (a", "redis-server --appendonly yes state: present recreate: yes expose: - 6379", "description: - Block IO weight (relative device weight, format DEVICE_NAME[:]WEIGHT).", "name self.stdout, self.stderr = '', '' self.info = self.get_info() self.version", "description: - Set the user namespace mode for the container.", "memory_swap: description: - A limit value equal to memory plus", "image]) if rc != 0: module.fail_json(msg=\"Can't pull image %s\" %", "container tasks. Manages podman container, inspects it and checks its", "%s' % self.container.name) self.update_container_result() elif self.container.running and not self.container.different: if", "for exp in self.params['expose']: c += ['--expose', exp] return c", "user: description: - Sets the username or UID used and", "containers exit. Restart policy will not take effect if a", "options type: list user: description: - Sets the username or", "before, after) def diffparam_image(self): # TODO(sshnaidm): for strict image compare", "before, after) def diffparam_memory(self): before = str(self.info['hostconfig']['memory']) after = self.params['memory']", "c): return c + ['--pids-limit', self.params['pids_limit']] def addparam_pod(self, c): return", "is supported for integers only. type: str memory_swappiness: description: -", "(default 10.88.0.0/16). type: str ipc: description: - Default is to", "and not self.image: self.module.fail_json(msg='Cannot create container when image' ' is", "'']: after = before else: after = self.params['log_opt'].split(\"=\")[1] return self._diff_update_and_compare('log_opt',", "type: str pod: description: - Run container in an existing", "self.info['config']: # the \"test\" key is a list of 2", "self.params['healthcheck'] or before return self._diff_update_and_compare('healthcheck', before, after) # Because of", "None and p in self.default_dict: params_with_defaults[p] = self.default_dict[p] else: params_with_defaults[p]", "diffparam_hostname(self): before = self.info['config']['hostname'] after = self.params['hostname'] or before return", "is false. type: bool publish: description: - Publish a container's", "memory_swappiness: description: - Tune a container's memory swappiness behavior. Accepts", "self.info['hostconfig']['autoremove'] after = self.params['rm'] return self._diff_update_and_compare('rm', before, after) def diffparam_security_opt(self):", "= before[:] if self.module.params['cap_drop'] is not None: for c in", "to the container log file. For example log_opt \"path=/var/log/container/mycontainer.json\" type:", "the config. def diffparam_healthcheck(self): if 'healthcheck' in self.info['config']: # the", "additionl command options you want to pass to podman command,", "'community' } DOCUMENTATION = \"\"\" module: podman_container author: - \"<NAME>", "Limit write rate (bytes per second) to a device (e.g.", "addparam_dns_option(self, c): return c + ['--dns-option', self.params['dns_option']] def addparam_dns_search(self, c):", "c): return c + ['--healthcheck-command', self.params['healthcheck']] def addparam_healthcheck_interval(self, c): return", "after = self.params['cpuset_cpus'] return self._diff_update_and_compare('cpuset_cpus', before, after) def diffparam_cpuset_mems(self): before", "exists and is not running now.\"\"\" return self.exists and not", "module def construct_command_from_params(self): \"\"\"Create a podman command from given module", "where the first one is # \"CMD-SHELL\" and the second", "return c + ['--dns-option', self.params['dns_option']] def addparam_dns_search(self, c): return c", "def is_different(self): diff_func_list = [func for func in dir(self) if", "self.container.recreate() self.results['actions'].append('recreated %s' % self.container.name) self.update_container_result() elif self.container.stopped and not", "a list of 2 items where the first one is", "% image, stdout=out, stderr=err) image_actions.append(\"pulled image %s\" % image) return", "will be pulled from the registry. If no tag is", "if isinstance(self.params['command'], list): cmd += self.params['command'] else: cmd += self.params['command'].split()", "type: path command: description: - Override command of container. Can", "err = module.run_command([module_exec, 'image', 'exists', image]) if rc == 0:", "can't guess default values def diffparam_env(self): env_before = self.info['config']['env'] or", "conmon_pidfile: description: - Write the pid of the conmon process", "the image is assumed to be available locally. type: str", "self.params['device_write_bps'] or [] before, after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('device_write_bps',", "m['destination']]) before = [\":\".join(v) for v in volumes] # Ignore", "conmon process to a file. conmon runs in a separate", "c): return c + ['--cpu-rt-runtime', self.params['cpu_rt_runtime']] def addparam_cpu_shares(self, c): return", "network namespace to join * slirp4netns use slirp4netns to create", "c += ['--rm'] return c def addparam_rootfs(self, c): return c", "= {} self.actions = [] @property def exists(self): \"\"\"Check if", "+ ['--stop-timeout', self.params['stop_timeout']] def addparam_subgidname(self, c): return c + ['--subgidname',", "The maximum time allowed to complete the healthcheck before an", "\"user\": \"\", \"uts\": \"\", \"volume\": [], \"workdir\": \"/\", } def", "self.module.run_command( [self.module.params['executable'], b'--version']) if rc != 0 or not out", "str dns_search: description: - Set custom DNS search domains (Use", "def diffparam_cpus(self): before = int(self.info['hostconfig']['nanocpus']) / 1000000000 after = self.params['cpus']", "self.info['hostconfig']['ipcmode'] after = self.params['ipc'] return self._diff_update_and_compare('ipc', before, after) def diffparam_label(self):", "description: - Run container in an existing pod. If you", "self.params['interactive']] def addparam_ip(self, c): return c + ['--ip', self.params['ip']] def", "add_hosts expose: description: - Expose a port, or a range", "self.params['memory'].isdigit()): after = str(int(self.params['memory']) * 2) return self._diff_update_and_compare('memory_swap', before, after)", "= sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('device_read_iops', before, after) def diffparam_device_write_bps(self): before", "mount: description: - Attach a filesystem mount to the container.", "is running in --read-only mode, then mount a read-write tmpfs", "module = AnsibleModule( argument_spec=yaml.safe_load(DOCUMENTATION)['options'], mutually_exclusive=( ['no_hosts', 'etc_hosts'], ), supports_check_mode=True, )", "def addparam_cgroupns(self, c): self.check_version('--cgroupns', minv='1.6.2') return c + ['--cgroupns=%s' %", "image_volume: description: - Tells podman how to handle the builtin", "= \\ self.module.get_bin_path(self.module.params['executable'], required=True) self.image = self.module.params['image'] image_actions = ensure_image_exists(self.module,", "cmd = getattr(self, func_name)(cmd) cmd.append(self.params['image']) if self.params['command']: if isinstance(self.params['command'], list):", "it exists, if not - pull it or fail. Arguments:", "description: - Set the Network mode for the container *", "= self.params['device_read_bps'] or [] before, after = sorted(list(set(before))), sorted(list(set(after))) return", "- List of capabilities to drop from the container. type:", "\"State\": { \"Dead\": false, \"Error\": \"\", \"ExitCode\": 0, \"FinishedAt\": \"2019-06-17T19:13:10.157518963+03:00\",", "def addparam_hostname(self, c): return c + ['--hostname', self.params['hostname']] def addparam_http_proxy(self,", "c): return c + ['--cpu-shares', self.params['cpu_shares']] def addparam_cpus(self, c): return", "before, after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('cap_drop', before, after) def", "will be launched inside of the container. type: dict env_file:", "a healthcheck # was configured; otherwise the config key isn't", "str http_proxy: description: - By default proxy environment variables are", "def diffparam_blkio_weight_device(self): before = self.info['hostconfig']['blkioweightdevice'] if before == [] and", "Options. For example security_opt \"seccomp=unconfined\" type: list elements: str shm_size:", "on host\" options: name: description: - Name of the container", "for the container type: str pids_limit: description: - Tune the", "tmpfs in self.params['tmpfs'].items(): c += ['--tmpfs', ':'.join(tmpfs)] return c def", "the # License for the specific language governing permissions and", "self._diff_update_and_compare('device_read_iops', before, after) def diffparam_device_write_bps(self): before = self.info['hostconfig']['blkiodevicewritebps'] or []", "random ports on the host interfaces. The default is false.", "\"Mounts\": [ ... ], \"Name\": \"myservice\", \"Namespace\": \"\", \"NetworkSettings\": {", "def addparam_pod(self, c): return c + ['--pod', self.params['pod']] def addparam_privileged(self,", "type: str userns: description: - Set the user namespace mode", "is false. type: bool ip: description: - Specify a static", "the dictionary. Each host name will be added to the", "time format such as 1m22s. The default value is 30s", "default CNI network's pool (default 10.88.0.0/16). type: str ipc: description:", "construct_command_from_params(self): \"\"\"Create a podman command from given module parameters. Returns:", "= self.info['hostconfig']['blkiodevicewritebps'] or [] before = [\"%s:%s\" % (i['path'], i['rate'])", "str healthcheck_timeout: description: - The maximum time allowed to complete", "sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('cap_add', before, after) def diffparam_cap_drop(self): before =", "for i in before] after = self.params['device_read_iops'] or [] before,", "self.module.params['image'] image_actions = ensure_image_exists(self.module, self.image) self.results['actions'] += image_actions self.state =", "of the image type: str env: description: - Set environment", "__init__(self, module): \"\"\"Initialize PodmanManager class. Arguments: module {obj} -- ansible", "detach mode type: bool default: True debug: description: - Return", "= getattr(self, func_name) if dff_func(): if fail_fast: return True else:", "+ ['--env-host=%s' % self.params['env_host']] def addparam_etc_hosts(self, c): for host_ip in", "status, retrying indefinitely type: str rm: description: - Automatically remove", "+ ['--memory-swap', self.params['memory_swap']] def addparam_memory_swappiness(self, c): return c + ['--memory-swappiness',", "healthcheck command. before = self.info['config']['healthcheck']['test'][1] else: before = '' after", "addparam_oom_score_adj(self, c): return c + ['--oom-score-adj', self.params['oom_score_adj']] def addparam_pid(self, c):", "\"ResolvConfPath\": \"...\", \"RestartCount\": 0, \"Rootfs\": \"\", \"State\": { \"Dead\": false,", "also accessible directly as C(podman_container). Note that the returned fact", "'started'.\"\"\" if self.container.running and \\ (self.container.different or self.recreate): self.container.recreate() self.results['actions'].append('recreated", "-- whether any action was performed (default: {True}) \"\"\" facts", "log_opt: description: - Logging driver specific options. Used to set", "def diffparam_privileged(self): before = self.info['hostconfig']['privileged'] after = self.params['privileged'] return self._diff_update_and_compare('privileged',", "image_actions self.state = self.module.params['state'] self.restart = self.module.params['force_restart'] self.recreate = self.module.params['recreate']", "value between 10 and 1000 type: int blkio_weight_device: description: -", "are bind, tmpfs, or ignore (default bind) type: str choices:", "mycontainer state: present image: ubuntu:14.04 command: \"sleep 1d\" - name:", "Path to the container-init binary. type: str interactive: description: -", "- Restart policy to follow when containers exit. Restart policy", "- Limit the CPU real-time period in microseconds type: int", "False init: description: - Run an init inside the container", "self.params['user']] def addparam_userns(self, c): return c + ['--userns', self.params['userns']] def", "self._diff_update_and_compare('log_opt', before, after) def diffparam_memory(self): before = str(self.info['hostconfig']['memory']) after =", "self.make_started, 'started': self.make_started, 'absent': self.make_absent, 'stopped': self.make_stopped } process_action =", "Run container podman_container: name: container image: quay.io/bitnami/wildfly state: started -", "func_name)(cmd) cmd.append(self.params['image']) if self.params['command']: if isinstance(self.params['command'], list): cmd += self.params['command']", "container: description: - Facts representing the current state of the", "before return self._diff_update_and_compare('healthcheck', before, after) # Because of hostname is", "Arguments: module {obj} -- ansible module object \"\"\" super(PodmanManager, self).__init__()", "(relative weight) type: int cpus: description: - Number of CPUs.", "larger than -m (--memory) value. By default, the swap LIMIT", "full name with registry and namespaces. type: bool default: False", "= self.params['healthcheck'] or before return self._diff_update_and_compare('healthcheck', before, after) # Because", "self.info['config']['annotations'] or {} after = before.copy() if self.module.params['annotation'] is not", "addparam_log_opt(self, c): return c + ['--log-opt', self.params['log_opt']] def addparam_memory(self, c):", "image %s\" % image) return image_actions class PodmanContainer: \"\"\"Perform container", "= False after = self.params['env_host'] return self._diff_update_and_compare('env_host', before, after) def", "{ \"Bridge\": \"\", ... }, \"Path\": \"sh\", \"ProcessLabel\": \"system_u:system_r:container_t:s0:c282,c782\", \"ResolvConfPath\":", "in ['started', 'present'] and \\ not module.params['image']: module.fail_json(msg=\"State '%s' required", "file. type: str subuidname: description: - Run the container in", "true. type: bool stop_signal: description: - Signal to stop a", "before = self.info['logpath'] if self.module.params['log_opt'] in [None, '']: after =", "def addparam_conmon_pidfile(self, c): return c + ['--conmon-pidfile', self.params['conmon_pidfile']] def addparam_cpu_period(self,", "\"\", \"detach\": True, \"device\": [], \"env_host\": False, \"etc_hosts\": {}, \"group_add\":", "'' if you don't wish to set the search domain)", "description: - List of capabilities to add to the container.", "state is 'started'.\"\"\" if self.container.running and \\ (self.container.different or self.recreate):", "b'inspect', self.name]) return json.loads(out)[0] if rc == 0 else {}", "policy will not take effect if a container is stopped", "Popen command \"\"\" if self.action in ['start', 'stop', 'delete']: return", "the recreate option to force the re-creation of the matching", "\"memory_swap\": \"0\", \"memory_reservation\": \"0\", # \"memory_swappiness\": -1, \"no_hosts\": False, #", "a new user namespace using the map with 'name' in", "\"\"\" - name: Run container podman_container: name: container image: quay.io/bitnami/wildfly", "} process_action = states_map[self.state] process_action() self.module.fail_json(msg=\"Unexpected logic error happened, \"", "and is not running now.\"\"\" return self.exists and not self.info['State']['Running']", "+ ['--pids-limit', self.params['pids_limit']] def addparam_pod(self, c): return c + ['--pod',", "join were specified via 'network:', and if the container is", "return c def addparam_ulimit(self, c): for u in self.params['ulimit']: c", "you want to pass to podman command, cmd_args - ['--other-param',", "you may # not use this file except in compliance", "return c + ['--cpu-rt-period', self.params['cpu_rt_period']] def addparam_cpu_rt_runtime(self, c): return c", "= yaml.safe_load(json.dumps(info).lower()) self.params = self.defaultize() self.diff = {'before': {}, 'after':", "podman_container: name: mycontainer state: present image: ubuntu:14.04 command: \"sleep 1d\"", "= self.info['hostconfig']['pidmode'] after = self.params['pid'] return self._diff_update_and_compare('pid', before, after) def", "before, after) def diffparam_ipc(self): before = self.info['hostconfig']['ipcmode'] after = self.params['ipc']", "return self._diff_update_and_compare('workdir', before, after) def is_different(self): diff_func_list = [func for", "self.params['subgidname']] def addparam_subuidname(self, c): return c + ['--subuidname', self.params['subuidname']] def", "super(PodmanContainer, self).__init__() self.module = module self.name = name self.stdout, self.stderr", "Image version will be taken into account when comparing configuration.", "language governing permissions and limitations # under the License. #", "description: - Restart policy to follow when containers exit. Restart", "container is stopped via the podman kill or podman stop", "force_restart to force a matching container to be stopped and", "+ ['--dns-option', self.params['dns_option']] def addparam_dns_search(self, c): return c + ['--dns-search',", "value equal to memory plus swap. Must be used with", "addparam_hostname(self, c): return c + ['--hostname', self.params['hostname']] def addparam_http_proxy(self, c):", "unit, the system uses bytes. If you omit the size", "before = self.info['hostconfig']['ipcmode'] after = self.params['ipc'] return self._diff_update_and_compare('ipc', before, after)", "= self.info['hostconfig']['groupadd'] after = self.params['group_add'] return self._diff_update_and_compare('group_add', before, after) #", "log_driver: k8s-file \"\"\" RETURN = \"\"\" container: description: - Facts", "type: list elements: str shm_size: description: - Size of /dev/shm.", "\"docker.io/library/busybox:latest\", \"Labels\": null, \"OpenStdin\": false, \"StdinOnce\": false, \"StopSignal\": 15, \"Tty\":", "\"StopSignal\": 15, \"Tty\": false, \"User\": { \"gid\": 0, \"uid\": 0", "after += before before, after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('cap_add',", "'stop', 'create', 'delete', 'start' params {dict} -- dictionary of module", "self.params if self.params[i] is not None) for param in params_set:", "\"\", \"cpus\": 0.0, \"cpu_shares\": 0, \"cpu_quota\": 0, \"cpu_period\": 0, \"cpu_rt_runtime\":", "as type: list healthcheck: description: - Set or alter a", "\"/tmp/container/mycontainer.json\", \"MountLabel\": \"system_u:object_r:container_file_t:s0:c282,c782\", \"Mounts\": [ ... ], \"Name\": \"myservice\", \"Namespace\":", "self.params[i] is not None) for param in params_set: func_name =", "out.split(\"version\")[1].strip() def _perform_action(self, action): \"\"\"Perform action with container. Arguments: action", "= self.module.params['force_restart'] self.recreate = self.module.params['recreate'] self.container = PodmanContainer(self.module, self.name) def", "if self.container.stopped: self.update_container_result(changed=False) elif self.container.running: self.container.stop() self.results['actions'].append('stopped %s' % self.container.name)", "diffparam_env(self): env_before = self.info['config']['env'] or {} before = {i.split(\"=\")[0]: i.split(\"=\")[1]", "parameters for p in self.non_idempotent: if self.module.params[p] is not None", "description: - Set environment variables. This option allows you to", "Tells podman how to handle the builtin image volumes. The", "Set the UTS mode for the container type: str volume:", "is not None: after += [\"cap_\" + i.lower() for i", "after) # Healthcheck is only defined in container config if", "dict sample: '{ \"AppArmorProfile\": \"\", \"Args\": [ \"sh\" ], \"BoundingCaps\":", "- Empty if C(state) is I(absent). returned: always type: dict", "c in [\"cap_\" + i.lower() for i in self.module.params['cap_drop']]: if", "since Ansible 2.8. For compatibility reasons, the facts are also", "c += ['--blkio-weight-device', ':'.join(blkio)] return c def addparam_cap_add(self, c): for", "volumes] # Ignore volumes option for idempotency after = [\":\".join(v.split(\":\")[:2])", "description: - Limit read rate (IO per second) from a", "use SHAs before = self.info['config']['image'] after = self.params['image'] mode =", "self._diff_update_and_compare('network', before, after) def diffparam_no_hosts(self): before = not bool(self.info['hostspath']) after", "Killer for the container or not. Default is false. type:", "values def diffparam_env(self): env_before = self.info['config']['env'] or {} before =", "= dict([i.split(\":\") for i in self.info['hostconfig']['extrahosts']]) else: before = {}", "an image is not found, the image will be pulled", "match, the container will be updated, if it can be.", "\"Log\": null, \"Status\": \"\" }, \"OOMKilled\": false, \"OciVersion\": \"1.0.1-dev\", \"Paused\":", "def addparam_memory_reservation(self, c): return c + ['--memory-reservation', self.params['memory_reservation']] def addparam_memory_swap(self,", "write rate (IO per second) to a device (e.g. device-write-iops", "it is running. Use force_restart to force a matching container", "container. - I(started) - Asserts there is a running container", "Valid values are enabled and disabled, which the default being", "take effect if a container is stopped via the podman", "return self.exists and self.info['State']['Running'] @property def stopped(self): \"\"\"Return True if", "default command if self.module.params['command'] is not None: before = self.info['config']['cmd']", "the container process. SIGCHLD, SIGSTOP, and SIGKILL are not proxied.", "if you don't wish to set the search domain) type:", "bool stop_signal: description: - Signal to stop a container. Default", "any provided configuration. If no container matches the name, a", "to a network namespace to join * slirp4netns use slirp4netns", "to set the path to the container log file. For", "description: - Run container in detach mode type: bool default:", "- Specify a static IP address for the container, for", "exposed - exposed_ports force_restart: description: - Force restart of container.", "False, \"security_opt\": [], \"stop_signal\": 15, \"tty\": False, \"user\": \"\", \"uts\":", "before: volumes = [] for m in before: if m['type']", "after = self.params['log_driver'] return self._diff_update_and_compare('log_driver', before, after) # Parameter has", "\"network\": [\"default\"], \"oom_score_adj\": 0, \"pid\": \"\", \"privileged\": False, \"rm\": False,", "key isn't part of the config. def diffparam_healthcheck(self): if 'healthcheck'", "after) def diffparam_log_driver(self): before = self.info['hostconfig']['logconfig']['type'] after = self.params['log_driver'] return", "['--tmpfs', ':'.join(tmpfs)] return c def addparam_tty(self, c): return c +", "for vol in self.params['volume']: if vol: c += ['--volume', vol]", "before = self.info['hostconfig']['cpusetmems'] after = self.params['cpuset_mems'] return self._diff_update_and_compare('cpuset_mems', before, after)", "if self.action in ['start', 'stop', 'delete']: return self.start_stop_delete() if self.action", "execution (0-3, 0,1). Only effective on NUMA systems. type: str", "str device: description: - Add a host device to the", "recreate: yes image: someuser/anotherappimage command: sleep 1d with_sequence: count=4 -", "and self.info['State']['Running'] @property def stopped(self): \"\"\"Return True if container exists", "be. If it cannot be updated, it will be removed", "after) def diffparam_no_hosts(self): before = not bool(self.info['hostspath']) after = self.params['no_hosts']", "= self.info['effectivecaps'] or [] after = before[:] if self.module.params['cap_drop'] is", "after = self.params['ipc'] return self._diff_update_and_compare('ipc', before, after) def diffparam_label(self): before", "self.params['memory'] return self._diff_update_and_compare('memory', before, after) def diffparam_memory_swap(self): # By default", "def diffparam_log_opt(self): before = self.info['logpath'] if self.module.params['log_opt'] in [None, '']:", "C(state) is I(absent). returned: always type: dict sample: '{ \"AppArmorProfile\":", "pod name with \"new:\" type: str privileged: description: - Give", "(a value of disable results in no automatic timer setup)", "diffparam_cidfile(self): before = self.info['hostconfig']['containeridfile'] after = self.params['cidfile'] return self._diff_update_and_compare('cidfile', before,", "be stopped and restarted. - I(stopped) - Asserts that the", "c): self.check_version('--cgroupns', minv='1.6.2') return c + ['--cgroupns=%s' % self.params['cgroupns']] def", "c += ['--add-host', ':'.join(host_ip)] return c def addparam_expose(self, c): for", "['--dns-search', self.params['dns_search']] def addparam_entrypoint(self, c): return c + ['--entrypoint', self.params['entrypoint']]", "myservice image: busybox log_options: path=/var/log/container/mycontainer.json log_driver: k8s-file \"\"\" RETURN =", "should be applied to container \"\"\" def __init__(self, module): \"\"\"Initialize", "+= ['--cap-drop', cap_drop] return c def addparam_cgroups(self, c): self.check_version('--cgroups', minv='1.6.0')", "is running. Use force_restart to force a matching container to", "will be added to the container's ``/etc/hosts`` file. type: dict", "it pulled or nothing was done \"\"\" image_actions = []", "and diffs['after']: self.diff['before'] = \"\\n\".join( [\"%s - %s\" % (k,", "create a private IPC namespace (POSIX SysV IPC) for the", "* no - Do not restart containers on exit *", "false. type: bool uidmap: description: - Run the container in", "c def addparam_device_write_bps(self, c): for dev in self.params['device_write_bps']: c +=", "+ ['--systemd=%s' % self.params['systemd']] def addparam_tmpfs(self, c): for tmpfs in", "+= ['--ulimit', u] return c def addparam_user(self, c): return c", "Arguments: changed {bool} -- whether any action was performed (default:", "minv, self.podman_version)) if maxv and LooseVersion(maxv) < LooseVersion( self.podman_version): self.module.fail_json(msg=\"Parameter", "['--device-read-iops', dev] return c def addparam_device_write_bps(self, c): for dev in", "container is first I(present), and then if the container is", "software # distributed under the License is distributed on an", "diffparam_oom_score_adj(self): before = self.info['hostconfig']['oomscoreadj'] after = self.params['oom_score_adj'] return self._diff_update_and_compare('oom_score_adj', before,", "env_file: description: - Read in a line delimited file of", "[func for func in dir(self) if callable(getattr(self, func)) and func.startswith(", "return c + ['--cpu-shares', self.params['cpu_shares']] def addparam_cpus(self, c): return c", "a user network stack. This is the default for rootless", "def addparam_cpu_shares(self, c): return c + ['--cpu-shares', self.params['cpu_shares']] def addparam_cpus(self,", "containers. type: path command: description: - Override command of container.", "not None: for c in [\"cap_\" + i.lower() for i", "c + ['--log-driver', self.params['log_driver']] def addparam_log_opt(self, c): return c +", "i['rate']) for i in before] after = self.params['device_read_bps'] or []", "value of disable results in no automatic timer setup) (default", "['--cpu-rt-period', self.params['cpu_rt_period']] def addparam_cpu_rt_runtime(self, c): return c + ['--cpu-rt-runtime', self.params['cpu_rt_runtime']]", "can also override the default path of the authentication file", "host's OOM preferences for containers (accepts -1000 to 1000) type:", "# TODO(sshnaidm): for strict image compare mode use SHAs before", "+ ['--dns-search', self.params['dns_search']] def addparam_entrypoint(self, c): return c + ['--entrypoint',", "'pull', image]) if rc != 0: module.fail_json(msg=\"Can't pull image %s\"", "self.module = module self.version = podman_version self.defaults = { \"blkio_weight\":", "container. The default working directory for running binaries within a", "self.info['hostconfig']['extrahosts']: before = dict([i.split(\":\") for i in self.info['hostconfig']['extrahosts']]) else: before", "as 1m22s. The default value is 30s type: str hostname:", "container is running in --read-only mode, then mount a read-write", "one is # \"CMD-SHELL\" and the second one is the", "to container \"\"\" def __init__(self, module): \"\"\"Initialize PodmanManager class. Arguments:", "description: - Tells podman how to handle the builtin image", "the kernel to restrict the container's Real Time CPU usage", "], \"Config\": { \"Annotations\": { \"io.kubernetes.cri-o.ContainerType\": \"sandbox\", \"io.kubernetes.cri-o.TTY\": \"false\" },", "is supported for integers only. type: str memory_reservation: description: -", "c): return c + ['--init', self.params['init']] def addparam_init_path(self, c): return", "before = self.info['config']['user'] if self.module.params['user'] is None and before: after", "they exit, regardless of status, retrying indefinitely type: str rm:", "def addparam_restart_policy(self, c): return c + ['--restart=%s' % self.params['restart_policy']] def", "- Size of /dev/shm. The format is <number><unit>. number must", "def addparam_volume(self, c): for vol in self.params['volume']: if vol: c", "diffcheck = PodmanContainerDiff(self.module, self.info, self.version) is_different = diffcheck.is_different() diffs =", "return c + ['--workdir', self.params['workdir']] # Add your own args", "the map with 'name' in the /etc/subuid file. type: str", "- present - stopped - started image: description: - Repository", "4 load-balanced containers podman_container: name: \"container{{ item }}\" recreate: yes", "after) def diffparam_oom_score_adj(self): before = self.info['hostconfig']['oomscoreadj'] after = self.params['oom_score_adj'] return", "self.module.fail_json(msg=\"Parameter %s is supported till podman \" \"version %s only!", "description: - Working directory inside the container. The default working", "is 0s type: str healthcheck_timeout: description: - The maximum time", "Dict of host-to-IP mappings, where each host name is a", "self.params['pid']] def addparam_pids_limit(self, c): return c + ['--pids-limit', self.params['pids_limit']] def", "\"security_opt\": [], \"stop_signal\": 15, \"tty\": False, \"user\": \"\", \"uts\": \"\",", "it and checks its current state \"\"\" def __init__(self, module,", "healthcheck_retries: description: - The number of retries allowed before a", "for sysctl in self.params['sysctl'].items(): c += ['--sysctl', b\"=\".join([to_bytes(k, errors='surrogate_or_strict') for", "after.split()] elif isinstance(after, list): after = [i.lower() for i in", "myapplication image: redis state: started restart: yes etc_hosts: other: \"127.0.0.1\"", "return self._diff_update_and_compare('user', before, after) def diffparam_uts(self): before = self.info['hostconfig']['utsmode'] after", "and 1000 type: int blkio_weight_device: description: - Block IO weight", "func_name in all_param_methods: cmd = getattr(self, func_name)(cmd) cmd.append(self.params['image']) if self.params['command']:", "after = before.copy() if self.module.params['annotation'] is not None: after.update(self.params['annotation']) return", "\"test\" key is a list of 2 items where the", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "and checks its current state \"\"\" def __init__(self, module, name):", "state: description: - I(absent) - A container matching the specified", "Set the Network mode for the container * bridge create", "addparam_dns(self, c): return c + ['--dns', ','.join(self.params['dns'])] def addparam_dns_option(self, c):", "+ ['--gidmap', self.params['gidmap']] def addparam_group_add(self, c): for g in self.params['group_add']:", "is the actual healthcheck command. before = self.info['config']['healthcheck']['test'][1] else: before", "cpuset_cpus: description: - CPUs in which to allow execution (0-3,", "and \\ (self.container.different or self.recreate): self.container.recreate() self.results['actions'].append('recreated %s' % self.container.name)", "str(v).lower() for k, v in self.params['label'].items() }) return self._diff_update_and_compare('label', before,", "minv and LooseVersion(minv) > LooseVersion( self.podman_version): self.module.fail_json(msg=\"Parameter %s is supported", "E501 from __future__ import absolute_import, division, print_function __metaclass__ = type", "type: str annotation: description: - Add an annotation to the", "return c def addparam_gidmap(self, c): return c + ['--gidmap', self.params['gidmap']]", "def addparam_uts(self, c): return c + ['--uts', self.params['uts']] def addparam_volume(self,", "before, after) def diffparam_cpus(self): before = int(self.info['hostconfig']['nanocpus']) / 1000000000 after", "run as type: list healthcheck: description: - Set or alter", "self.params['publish_all']] def addparam_read_only(self, c): return c + ['--read-only=%s' % self.params['read_only']]", "create /etc/hosts for the container Default is false. type: bool", "of image actions - if it pulled or nothing was", "type: str memory_swap: description: - A limit value equal to", "a container will be created and started. Use recreate to", "['preview'], 'supported_by': 'community' } DOCUMENTATION = \"\"\" module: podman_container author:", "remove container podman_container: name: ohno state: absent - name: Writing", "['--oom-score-adj', self.params['oom_score_adj']] def addparam_pid(self, c): return c + ['--pid', self.params['pid']]", "KIND, either express or implied. See the # License for", "self.params['blkio_weight']] def addparam_blkio_weight_device(self, c): for blkio in self.params['blkio_weight_device'].items(): c +=", "false, \"Running\": false, \"StartedAt\": \"2019-06-17T19:13:10.152479729+03:00\", \"Status\": \"exited\" }, \"StaticDir\": \"...\"", "before = self.info['hostconfig']['utsmode'] after = self.params['uts'] return self._diff_update_and_compare('uts', before, after)", "diffs['before'].items())]) + \"\\n\" self.diff['after'] = \"\\n\".join( [\"%s - %s\" %", "(0-3, 0,1) type: str cpuset_mems: description: - Memory nodes (MEMs)", "tmpfs mount. For example tmpfs \"/tmp\" \"rw,size=787448k,mode=1777\" type: dict tty:", "type: int cpu_rt_period: description: - Limit the CPU real-time period", "device weight, format DEVICE_NAME[:]WEIGHT). type: dict cap_add: description: - List", "for i in cmd] def start_stop_delete(self): if self.action in ['stop',", "use slirp4netns to create a user network stack. This is", "is hit * always - Restart containers when they exit,", "number must be greater than 0. Unit is optional and", "\"\"\"Run the container.\"\"\" self._perform_action('run') def delete(self): \"\"\"Delete the container.\"\"\" self._perform_action('delete')", "c def addparam_user(self, c): return c + ['--user', self.params['user']] def", "return c def addparam_dns(self, c): return c + ['--dns', ','.join(self.params['dns'])]", "c += ['--uidmap', uidmap] return c def addparam_ulimit(self, c): for", "before = self.info['hostconfig']['pidmode'] after = self.params['pid'] return self._diff_update_and_compare('pid', before, after)", "i['rate']) for i in before] after = self.params['device_read_iops'] or []", "stdout=out, stderr=err) image_actions.append(\"pulled image %s\" % image) return image_actions class", "# Defaults depend on user and platform, impossible to guess", "\"Domainname\": \"\", \"Entrypoint\": \"\", \"Env\": [ \"PATH=/usr/sbin:/usr/bin:/sbin:/bin\", \"TERM=xterm\", \"HOSTNAME=\", \"container=podman\"", "self.module._diff and is_different and diffs['before'] and diffs['after']: self.diff['before'] = \"\\n\".join(", "{ 'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community' } DOCUMENTATION =", "return self._diff_update_and_compare('command', before, after) return False def diffparam_conmon_pidfile(self): before =", "return self._diff_update_and_compare('image', before, after) def diffparam_ipc(self): before = self.info['hostconfig']['ipcmode'] after", "is false. type: bool oom_score_adj: description: - Tune the host's", "+ ['--subgidname', self.params['subgidname']] def addparam_subuidname(self, c): return c + ['--subuidname',", "def diffparam_cpu_rt_period(self): before = self.info['hostconfig']['cpurealtimeperiod'] after = self.params['cpu_rt_period'] return self._diff_update_and_compare('cpu_rt_period',", "= self.info['config']['stopsignal'] after = self.params['stop_signal'] return self._diff_update_and_compare('stop_signal', before, after) def", "List of capabilities to drop from the container. type: list", "start_stop_delete(self): if self.action in ['stop', 'start']: cmd = [self.action, self.params['name']]", "= before else: after = self.params['conmon_pidfile'] return self._diff_update_and_compare('conmon_pidfile', before, after)", "and LooseVersion(maxv) < LooseVersion( self.podman_version): self.module.fail_json(msg=\"Parameter %s is supported till", "v in self.params['label'].items() }) return self._diff_update_and_compare('label', before, after) def diffparam_log_driver(self):", "of actions & states.\"\"\" states_map = { 'present': self.make_started, 'started':", "[] before, after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('device_write_bps', before, after)", "support idempotency if this is set. type: list elements: str", "def diffparam_cap_add(self): before = self.info['effectivecaps'] or [] after = []", "addparam_read_only_tmpfs(self, c): return c + ['--read-only-tmpfs=%s' % self.params['read_only_tmpfs']] def addparam_restart_policy(self,", "self.actions = [] @property def exists(self): \"\"\"Check if container exists.\"\"\"", "interfaces. The default is false. type: bool read_only: description: -", "state: present recreate: yes expose: - 6379 volumes_from: - mydata", "/CONTAINER-DIR in the podman container. type: list elements: str aliases:", "isn't part of the config. def diffparam_healthcheck(self): if 'healthcheck' in", "annotate in self.params['annotation'].items(): c += ['--annotation', '='.join(annotate)] return c def", "container to bootstrap. The value can be expressed in time", "cap_add] return c def addparam_cap_drop(self, c): for cap_drop in self.params['cap_drop']:", "existing pod. If you want podman to make the pod", "+ ['--healthcheck-retries', self.params['healthcheck_retries']] def addparam_healthcheck_start_period(self, c): return c + ['--healthcheck-start-period',", "- By default proxy environment variables are passed into the", "= podman_version self.module = module def construct_command_from_params(self): \"\"\"Create a podman", "diffparam_device_write_bps(self): before = self.info['hostconfig']['blkiodevicewritebps'] or [] before = [\"%s:%s\" %", "container matches the name, a container will be created and", "host to /CONTAINER-DIR in the podman container. type: list elements:", "out, err = module.run_command([module_exec, 'image', 'exists', image]) if rc ==", "= self.info['mounts'] if before: volumes = [] for m in", "addparam_subgidname(self, c): return c + ['--subgidname', self.params['subgidname']] def addparam_subuidname(self, c):", "elements: str aliases: - exposed - exposed_ports force_restart: description: -", "= [\":\".join(v.split(\":\")[:2]) for v in self.params['volume']] before, after = sorted(list(set(before))),", "For example security_opt \"seccomp=unconfined\" type: list elements: str shm_size: description:", "``/etc/hosts`` file. type: dict aliases: - add_hosts expose: description: -", "or podman stop commands. Valid values are * no -", "after) def diffparam_cpus(self): before = int(self.info['hostconfig']['nanocpus']) / 1000000000 after =", "to be relative to the cgroups path of the init", "for example '10.88.64.128'. Can only be used if no additional", "(relative device weight, format DEVICE_NAME[:]WEIGHT). type: dict cap_add: description: -", "if self.action in ['stop', 'start']: cmd = [self.action, self.params['name']] return", "2019 OpenStack Foundation # All Rights Reserved. # # Licensed", "self.params['etc_hosts'] return self._diff_update_and_compare('etc_hosts', before, after) def diffparam_group_add(self): before = self.info['hostconfig']['groupadd']", "self.params['systemd']] def addparam_tmpfs(self, c): for tmpfs in self.params['tmpfs'].items(): c +=", "\"MountLabel\": \"system_u:object_r:container_file_t:s0:c282,c782\", \"Mounts\": [ ... ], \"Name\": \"myservice\", \"Namespace\": \"\",", "or {} before = {i.split(\"=\")[0]: i.split(\"=\")[1] for i in env_before}", "self.params['user'] return self._diff_update_and_compare('user', before, after) def diffparam_uts(self): before = self.info['hostconfig']['utsmode']", "CPU shares (relative weight) type: int cpus: description: - Number", "Run the container in a new user namespace using the", "c): return c + ['--tty=%s' % self.params['tty']] def addparam_uidmap(self, c):", "defined in container config if a healthcheck # was configured;", "type: str hostname: description: - Container host name. Sets the", "obtain # a copy of the License at # #", "systemd to restart Podman containers. type: path command: description: -", "privileges to this container. The default is false. type: bool", "cpu_rt_runtime: description: - Limit the CPU real-time runtime in microseconds.", "c): return c + ['--systemd=%s' % self.params['systemd']] def addparam_tmpfs(self, c):", "passed, ensure it exists, if not - pull it or", "to set up port redirection on the host system. type:", "volumes.append([m['source'], m['destination']]) before = [\":\".join(v) for v in volumes] #", "after) def diffparam_device_read_iops(self): before = self.info['hostconfig']['blkiodevicereadiops'] or [] before =", "type: str env: description: - Set environment variables. This option", "c + ['--dns', ','.join(self.params['dns'])] def addparam_dns_option(self, c): return c +", "the container in a new user namespace using the map", "- Run container in systemd mode. The default is true.", "SECRET_KEY: \"ssssh\" BOOLEAN_KEY: \"yes\" - name: Container present podman_container: name:", "c): return c + self.params['cmd_args'] class PodmanDefaults: def __init__(self, module,", "actions should be applied to container \"\"\" def __init__(self, module):", "always type: dict sample: '{ \"AppArmorProfile\": \"\", \"Args\": [ \"sh\"", "self.params['cpus']] def addparam_cpuset_cpus(self, c): return c + ['--cpuset-cpus', self.params['cpuset_cpus']] def", "[] else: after = self.params['blkio_weight_device'] return self._diff_update_and_compare('blkio_weight_device', before, after) def", "str hostname: description: - Container host name. Sets the container", "DNS search domains (Use dns_search with '' if you don't", "'absent': self.make_absent, 'stopped': self.make_stopped } process_action = states_map[self.state] process_action() self.module.fail_json(msg=\"Unexpected", "for k, v in sorted( diffs['after'].items())]) + \"\\n\" return is_different", "any action was performed (default: {True}) \"\"\" facts = self.container.get_info()", "I(stopped) - Asserts that the container is first I(present), and", "type: list healthcheck: description: - Set or alter a healthcheck", "False}) elif self.container.exists: self.container.delete() self.results['actions'].append('deleted %s' % self.container.name) self.results.update({'changed': True})", "image to be configured!\" % module.params['state']) PodmanManager(module).execute() if __name__ ==", "is None and p in self.default_dict: params_with_defaults[p] = self.default_dict[p] else:", "registry and namespaces. type: bool default: False init: description: -", "type: bool default: False detach_keys: description: - Override the key", "+ ['--cgroups=%s' % self.params['cgroups']] def addparam_cgroupns(self, c): self.check_version('--cgroupns', minv='1.6.2') return", "diffparam_workdir(self): before = self.info['config']['workingdir'] after = self.params['workdir'] return self._diff_update_and_compare('workdir', before,", "device (e.g. device-write-bps /dev/sda:1mb) type: list device_write_iops: description: - Limit", "ensure it exists, if not - pull it or fail.", "a healthcheck is considered to be unhealthy. The default value", "The environment variables passed in include http_proxy, https_proxy, ftp_proxy, no_proxy,", "after = [] if self.module.params['cap_add'] is not None: after +=", "= self.info['config']['labels'] or {} after = before.copy() if self.params['label']: after.update({", "a line delimited file of labels type: str log_driver: description:", "if self.action in ['create', 'run']: cmd = [self.action, '--name', self.params['name']]", "addparam_volumes_from(self, c): for vol in self.params['volumes_from']: c += ['--volumes-from', vol]", "changed else self.container.info out, err = self.container.stdout, self.container.stderr self.results.update({'changed': changed,", "inspect image to get the default command if self.module.params['command'] is", "first argument refers to an exploded container on the file", "addparam_memory_swap(self, c): return c + ['--memory-swap', self.params['memory_swap']] def addparam_memory_swappiness(self, c):", "- Expose a port, or a range of ports (e.g.", "in self.params['cap_drop']: c += ['--cap-drop', cap_drop] return c def addparam_cgroups(self,", "self.module.fail_json( msg=\"Can't %s container %s\" % (action, self.name), stdout=out, stderr=err)", "description: - Signal to stop a container. Default is SIGTERM.", "c + ['--stop-signal', self.params['stop_signal']] def addparam_stop_timeout(self, c): return c +", "to a stopped state. type: str default: started choices: -", "c def addparam_tty(self, c): return c + ['--tty=%s' % self.params['tty']]", "type: list elements: str device_read_bps: description: - Limit read rate", "{}) @property def different(self): \"\"\"Check if container is different.\"\"\" diffcheck", "self.name = self.module.params['name'] self.executable = \\ self.module.get_bin_path(self.module.params['executable'], required=True) self.image =", "\"\" }, \"OOMKilled\": false, \"OciVersion\": \"1.0.1-dev\", \"Paused\": false, \"Pid\": 4083,", "The default is false. type: bool aliases: - remove rootfs:", "LooseVersion(minv) > LooseVersion( self.podman_version): self.module.fail_json(msg=\"Parameter %s is supported from podman", "in params_set: func_name = \"_\".join([\"addparam\", param]) if func_name in all_param_methods:", "def _perform_action(self, action): \"\"\"Perform action with container. Arguments: action {str}", "\"cgroups\": \"default\", \"cgroup_parent\": \"\", \"cidfile\": \"\", \"cpus\": 0.0, \"cpu_shares\": 0,", "c): for pub in self.params['publish']: c += ['--publish', pub] return", "c + ['--read-only=%s' % self.params['read_only']] def addparam_read_only_tmpfs(self, c): return c", "- name: Restart a container podman_container: name: myapplication image: redis", "is None or not mode: # In a idempotency 'lite", "the period you specify. type: int cpu_rt_runtime: description: - Limit", "+= before before, after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('cap_add', before,", "* slirp4netns use slirp4netns to create a user network stack.", "description: - The number of retries allowed before a healthcheck", "the config key isn't part of the config. def diffparam_healthcheck(self):", "Arguments: module {obj} -- ansible module object image {str} --", "self.version, self.module, ).construct_command_from_params() full_cmd = \" \".join([self.module.params['executable']] + [to_native(i) for", "= before.copy() if self.params['env']: after.update({ str(k).lower(): str(v).lower() for k, v", "those. Defaults to true type: bool image_volume: description: - Tells", "joining another container's network namespace via 'network container:<name|id>'. The address", "mode type: bool default: True debug: description: - Return additional", "a time format such as 1m22s. The default value is", "['started', 'present'] and \\ not module.params['image']: module.fail_json(msg=\"State '%s' required image", "self.params['device_read_iops'] or [] before, after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('device_read_iops',", "def addparam_network(self, c): return c + ['--network', \",\".join(self.params['network'])] def addparam_no_hosts(self,", "cmd = [self.action, self.params['name']] return [to_bytes(i, errors='surrogate_or_strict') for i in", "The default value is 30s type: str hostname: description: -", "- Run an init inside the container that forwards signals", "def addparam_healthcheck_start_period(self, c): return c + ['--healthcheck-start-period', self.params['healthcheck_start_period']] def addparam_healthcheck_timeout(self,", "version is %s\" % ( param, minv, self.podman_version)) def addparam_annotation(self,", "tmpfs: description: - Create a tmpfs mount. For example tmpfs", "force a matching container to be stopped and restarted. -", "is stopped via the podman kill or podman stop commands.", "Can also be an image ID. If this is the", "a container. type: str healthcheck_interval: description: - Set an interval", "\"please contact maintainers ASAP!\") def main(): module = AnsibleModule( argument_spec=yaml.safe_load(DOCUMENTATION)['options'],", "custom DNS servers type: list elements: str dns_option: description: -", "c def addparam_authfile(self, c): return c + ['--authfile', self.params['authfile']] def", "stop_signal: description: - Signal to stop a container. Default is", "in [None, '']: after = before else: after = self.params['log_opt'].split(\"=\")[1]", "self.params['etc_hosts'].items(): c += ['--add-host', ':'.join(host_ip)] return c def addparam_expose(self, c):", "or until the optional max_retries count is hit * always", "after = True return self._diff_update_and_compare('no_hosts', before, after) def diffparam_oom_score_adj(self): before", "device_write_bps: description: - Limit write rate (bytes per second) to", "self.executable = \\ self.module.get_bin_path(self.module.params['executable'], required=True) self.image = self.module.params['image'] image_actions =", "return c + ['--oom-kill-disable=%s' % self.params['oom_kill_disable']] def addparam_oom_score_adj(self, c): return", "dev] return c def addparam_device_read_iops(self, c): for dev in self.params['device_read_iops']:", "= None self.info = yaml.safe_load(json.dumps(info).lower()) self.params = self.defaultize() self.diff =", "elif self.container.stopped and not self.container.different: self.container.start() self.results['actions'].append('started %s' % self.container.name)", "default is false. type: bool aliases: - remove rootfs: description:", "c + ['--pid', self.params['pid']] def addparam_pids_limit(self, c): return c +", "c += ['--device-write-iops', dev] return c def addparam_dns(self, c): return", "c): return c + ['--init-path', self.params['init_path']] def addparam_interactive(self, c): return", "+ b_command, expand_user_and_vars=False) self.stdout = out self.stderr = err if", "c): return c + ['--authfile', self.params['authfile']] def addparam_blkio_weight(self, c): return", "a container podman_container: name: myapplication image: redis state: started restart:", "to true, keep stdin open even if not attached. The", "in dir(self) if callable(getattr(self, func)) and func.startswith( \"diffparam\")] fail_fast =", "self.module.get_bin_path(self.module.params['executable'], required=True) self.image = self.module.params['image'] image_actions = ensure_image_exists(self.module, self.image) self.results['actions']", "cmd = ['rm', '-f', self.params['name']] return [to_bytes(i, errors='surrogate_or_strict') for i", "is true type: bool recreate: description: - Use with present", "description: - Write the container ID to the file type:", "WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express", "be unhealthy. The default value is 3. type: int healthcheck_start_period:", "self.get_info() self.version = self._get_podman_version() self.diff = {} self.actions = []", "['--hostname', self.params['hostname']] def addparam_http_proxy(self, c): return c + ['--http-proxy=%s' %", "\\ (self.container.different or self.recreate): self.container.recreate() self.results['actions'].append('recreated %s' % self.container.name) self.update_container_result()", "(POSIX SysV IPC) for the container type: str kernel_memory: description:", "list elements: str conmon_pidfile: description: - Write the pid of", "matching the specified name will be stopped and removed. -", "\"oom_score_adj\": 0, \"pid\": \"\", \"privileged\": False, \"rm\": False, \"security_opt\": [],", "compare mode use SHAs before = self.info['config']['image'] after = self.params['image']", "addparam_cpu_rt_period(self, c): return c + ['--cpu-rt-period', self.params['cpu_rt_period']] def addparam_cpu_rt_runtime(self, c):", "def addparam_sig_proxy(self, c): return c + ['--sig-proxy=%s' % self.params['sig_proxy']] def", "+ ['--init', self.params['init']] def addparam_init_path(self, c): return c + ['--init-path',", "# Parameter has limited idempotency, unable to guess the default", "/dev/sda:1mb) type: list device_write_iops: description: - Limit write rate (IO", "container-init binary. type: str interactive: description: - Keep STDIN open", "in idempotency by taking into account a full name with", "self._diff_update_and_compare('devices', before, after) def diffparam_device_read_bps(self): before = self.info['hostconfig']['blkiodevicereadbps'] or []", "self.check_version('--env-host', minv='1.5.0') return c + ['--env-host=%s' % self.params['env_host']] def addparam_etc_hosts(self,", "addparam_annotation(self, c): for annotate in self.params['annotation'].items(): c += ['--annotation', '='.join(annotate)]", "AnsibleModule( argument_spec=yaml.safe_load(DOCUMENTATION)['options'], mutually_exclusive=( ['no_hosts', 'etc_hosts'], ), supports_check_mode=True, ) # work", "and started. Use recreate to always re-create a matching container,", "\"AppArmorProfile\": \"\", \"Args\": [ \"sh\" ], \"BoundingCaps\": [ \"CAP_CHOWN\", ...", "self._diff_update_and_compare('workdir', before, after) def is_different(self): diff_func_list = [func for func", "container when image' ' is not specified!') if not self.container.exists:", "self.info['config']['user'] if self.module.params['user'] is None and before: after = before", "container or not. Default is false. type: bool oom_score_adj: description:", "if before != after: self.diff['before'].update({param_name: before}) self.diff['after'].update({param_name: after}) return True", "started. Use recreate to always re-create a matching container, even", "= [self.action, '--name', self.params['name']] all_param_methods = [func for func in", "def addparam_userns(self, c): return c + ['--userns', self.params['userns']] def addparam_uts(self,", "before = {} after = self.params['etc_hosts'] return self._diff_update_and_compare('etc_hosts', before, after)", "c + ['--shm-size', self.params['shm_size']] def addparam_sig_proxy(self, c): return c +", "a filesystem mount to the container. bind or tmpfs For", "read_only_tmpfs: description: - If container is running in --read-only mode,", "stop_timeout: description: - Timeout (in seconds) to stop a container.", "name: \"container{{ item }}\" recreate: yes image: someuser/anotherappimage command: sleep", "not create CGroups, and thus conflicts with CGroup options cgroupns", "namespaces are disabled. type: str uts: description: - Set the", "self.exists and not self.info['State']['Running'] def get_info(self): \"\"\"Inspect container and gather", "false type: bool read_only_tmpfs: description: - If container is running", "and can be b (bytes), k (kilobytes), m(megabytes), or g", "def addparam_device_write_bps(self, c): for dev in self.params['device_write_bps']: c += ['--device-write-bps',", "- Tune a container's memory swappiness behavior. Accepts an integer", "is available inside the container. type: str http_proxy: description: -", "if self.module.params[p] is None and p in self.default_dict: params_with_defaults[p] =", "list. type: raw cpu_period: description: - Limit the CPU real-time", "weight (relative device weight, format DEVICE_NAME[:]WEIGHT). type: dict cap_add: description:", "\"overlay\", \"EffectiveCaps\": [ \"CAP_CHOWN\", ... ], \"ExecIDs\": [], \"ExitCommand\": [", "before = '' after = self.params['healthcheck'] or before return self._diff_update_and_compare('healthcheck',", "force the container to not create CGroups, and thus conflicts", "available inside the container. type: str http_proxy: description: - By", "self.params['uts'] return self._diff_update_and_compare('uts', before, after) def diffparam_volume(self): before = self.info['mounts']", "-1 to have unlimited pids for the container. type: str", "(self.module.params['memory_swap'] is None and self.params['memory'] != 0 and self.params['memory'].isdigit()): after", "from ansible.module_utils.basic import AnsibleModule from ansible.module_utils._text import to_bytes, to_native ANSIBLE_METADATA", "rc != 0: module.fail_json(msg=\"Can't pull image %s\" % image, stdout=out,", "state: stopped - name: Start 4 load-balanced containers podman_container: name:", "description: - Block IO weight (relative weight) accepts a weight", "for the container type: str kernel_memory: description: - Kernel memory", "description: - Limit write rate (bytes per second) to a", "be added to the container's ``/etc/hosts`` file. type: dict aliases:", "return self._diff_update_and_compare('blkio_weight_device', before, after) def diffparam_cap_add(self): before = self.info['effectivecaps'] or", "required image to be configured!\" % module.params['state']) PodmanManager(module).execute() if __name__", "time needed for a container to bootstrap. The value can", "type: str kernel_memory: description: - Kernel memory limit (format <number>[<unit>],", "command to the container process. SIGCHLD, SIGSTOP, and SIGKILL are", "state: started restart: yes etc_hosts: other: \"127.0.0.1\" restart_policy: \"no\" device:", "+ ['--no-hosts=%s' % self.params['no_hosts']] def addparam_oom_kill_disable(self, c): return c +", "dict authfile: description: - Path of the authentication file. Default", "addparam_cap_add(self, c): for cap_add in self.params['cap_add']: c += ['--cap-add', cap_add]", "Determines whether the container will create CGroups. Valid values are", "for k in env_value])] return c def addparam_env_file(self, c): return", "and is_different and diffs['before'] and diffs['after']: self.diff['before'] = \"\\n\".join( [\"%s", "= type import json from distutils.version import LooseVersion import yaml", "image: redis command: redis-server --appendonly yes state: present recreate: yes", "DOCUMENTATION = \"\"\" module: podman_container author: - \"<NAME> (@sshnaidm)\" version_added:", "before, after) return False def diffparam_cidfile(self): before = self.info['hostconfig']['containeridfile'] after", "quay.io/bitnami/wildfly state: started - name: Create a data container podman_container:", "- \"127.0.0.1:8081:9001/udp\" env: SECRET_KEY: \"ssssh\" BOOLEAN_KEY: \"yes\" - name: Container", "c): return c + ['--cpu-period', self.params['cpu_period']] def addparam_cpu_rt_period(self, c): return", "+ ['--healthcheck-interval', self.params['healthcheck_interval']] def addparam_healthcheck_retries(self, c): return c + ['--healthcheck-retries',", "to the file type: path cmd_args: description: - Any additionl", "before = before.replace(\":latest\", \"\") after = after.replace(\":latest\", \"\") before =", "to inspect image to get the default command if self.module.params['command']", "type: bool oom_score_adj: description: - Tune the host's OOM preferences", "before}) self.diff['after'].update({param_name: after}) return True return False def diffparam_annotation(self): before", "3. type: int healthcheck_start_period: description: - The initialization time needed", "Ulimit options type: list user: description: - Sets the username", "with the requested config. Image version will be taken into", "of container. type: bool default: False aliases: - restart gidmap:", "| ip::containerPort | hostPort:containerPort | containerPort type: list elements: str", "\"\"\" def __init__(self, module, name): \"\"\"Initialize PodmanContainer class. Arguments: module", "* container:<name|id> reuse another container's network stack * host use", "or implied. See the # License for the specific language", "= before.split(\"/\")[-1] after = after.split(\"/\")[-1] return self._diff_update_and_compare('image', before, after) def", "have unlimited pids for the container. type: str pod: description:", "c): return c + ['--healthcheck-retries', self.params['healthcheck_retries']] def addparam_healthcheck_start_period(self, c): return", "after = before else: after = self.params['user'] return self._diff_update_and_compare('user', before,", "def different(self): \"\"\"Check if container is different.\"\"\" diffcheck = PodmanContainerDiff(self.module,", "delete \"\"\" b_command = PodmanModuleParams(action, self.module.params, self.version, self.module, ).construct_command_from_params() full_cmd", "the container will be created. If the path is not", "def diffparam_security_opt(self): before = self.info['hostconfig']['securityopt'] after = self.params['security_opt'] before, after", "Healthcheck is only defined in container config if a healthcheck", "\"StaticDir\": \"...\" ... }' \"\"\" class PodmanModuleParams: \"\"\"Creates list of", "< LooseVersion( self.podman_version): self.module.fail_json(msg=\"Parameter %s is supported till podman \"", "per second) from a device (e.g. device-read-iops /dev/sda:1000) type: list", "self.params['memory_swap'] if (self.module.params['memory_swap'] is None and self.params['memory'] != 0 and", "subuidname: description: - Run the container in a new user", "i['pathincontainer']]) for i in self.info['hostconfig']['devices']] after = [\":\".join(i.split(\":\")[:2]) for i", "before, after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('device_read_bps', before, after) def", "\"...\", \"ID\": \"...\", \"Image\": \"...\", \"ImageName\": \"docker.io/library/busybox:latest\", \"IsInfra\": false, \"LogPath\":", "self.params['hostname'] or before return self._diff_update_and_compare('hostname', before, after) def diffparam_image(self): #", "self.params['kernel_memory']] def addparam_label(self, c): for label in self.params['label'].items(): c +=", "> LooseVersion( self.podman_version): self.module.fail_json(msg=\"Parameter %s is supported from podman \"", "c + ['--image-volume', self.params['image_volume']] def addparam_init(self, c): return c +", "return self.exists and not self.info['State']['Running'] def get_info(self): \"\"\"Inspect container and", "of the init process. Cgroups will be created if they", "c + ['--user', self.params['user']] def addparam_userns(self, c): return c +", "type: str volume: description: - Create a bind mount. If", "\"ulimit\", # Defaults depend on user and platform, impossible to", "open even if not attached. The default is false. type:", "], \"ExecIDs\": [], \"ExitCommand\": [ \"/usr/bin/podman\", \"--root\", ... ], \"GraphDriver\":", "and not self.container.different: if self.restart: self.container.restart() self.results['actions'].append('restarted %s' % self.container.name)", "parameters \"\"\" def __init__(self, action, params, podman_version, module): self.params =", "pass to podman command, cmd_args - ['--other-param', 'value'] Be aware", "- Whether to disable OOM Killer for the container or", "self.module.params['blkio_weight_device'] is None: after = [] else: after = self.params['blkio_weight_device']", "recreate to always re-create a matching container, even if it", "+ ['--interactive=%s' % self.params['interactive']] def addparam_ip(self, c): return c +", "taking into account a full name with registry and namespaces.", "there is a running container matching the name and any", "before, after) def diffparam_group_add(self): before = self.info['hostconfig']['groupadd'] after = self.params['group_add']", ").construct_command_from_params() full_cmd = \" \".join([self.module.params['executable']] + [to_native(i) for i in", "the container type: str kernel_memory: description: - Kernel memory limit", "type: bool publish: description: - Publish a container's port, or", "addparam_expose(self, c): for exp in self.params['expose']: c += ['--expose', exp]", "{'before': {}, 'after': {}} self.non_idempotent = { 'env_file', 'env_host', \"ulimit\",", "the current state of the container. Matches the podman inspection", "sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('security_opt', before, after) def diffparam_stop_signal(self): before =", "Reserved. # # Licensed under the Apache License, Version 2.0", "type: bool ip: description: - Specify a static IP address", "self._diff_update_and_compare('volumes_from', before, after) def diffparam_workdir(self): before = self.info['config']['workingdir'] after =", "config. def diffparam_healthcheck(self): if 'healthcheck' in self.info['config']: # the \"test\"", "def addparam_oom_kill_disable(self, c): return c + ['--oom-kill-disable=%s' % self.params['oom_kill_disable']] def", "= self.info['config']['hostname'] after = self.params['hostname'] or before return self._diff_update_and_compare('hostname', before,", "if rc != 0 or not out or \"version\" not", "c): return c + ['--no-hosts=%s' % self.params['no_hosts']] def addparam_oom_kill_disable(self, c):", "or [] after = before[:] if self.module.params['cap_drop'] is not None:", "return c + ['--memory-swap', self.params['memory_swap']] def addparam_memory_swappiness(self, c): return c", "module self.version = podman_version self.defaults = { \"blkio_weight\": 0, \"cgroups\":", "before, after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('volume', before, after) def", "+ ['--stop-signal', self.params['stop_signal']] def addparam_stop_timeout(self, c): return c + ['--stop-timeout',", "on /run, /tmp, and /var/tmp. The default is true type:", "[] after = self.params['volumes_from'] or [] return self._diff_update_and_compare('volumes_from', before, after)", "type: str label: description: - Add metadata to a container,", "info, exit. Keyword Arguments: changed {bool} -- whether any action", "% self.params['rootfs']] def addparam_security_opt(self, c): for secopt in self.params['security_opt']: c", "not joining another container's network namespace via 'network container:<name|id>'. The", "Real Time CPU usage to the period you specify. type:", "a given CPU period Real Time tasks may consume. type:", "from 'run', 'stop', 'create', 'delete', 'start' params {dict} -- dictionary", "images from different registries are the same before = before.replace(\":latest\",", "= self.info['hostconfig']['blkiodevicereadbps'] or [] before = [\"%s:%s\" % (i['path'], i['rate'])", "UTS mode for the container type: str volume: description: -", "disable OOM Killer for the container or not. Default is", "b_command]) self.module.log(\"PODMAN-CONTAINER-DEBUG: %s\" % full_cmd) self.actions.append(full_cmd) if not self.module.check_mode: rc,", "the container when it exits. The default is false. type:", "dir(self) if callable(getattr(self, func)) and func.startswith(\"addparam\")] params_set = (i for", "It's impossible to get from inspest, recreate it if not", "self.params['memory_reservation'] return self._diff_update_and_compare('memory_reservation', before, after) def diffparam_network(self): before = [self.info['hostconfig']['networkmode']]", "exposed ports to random ports on the host interfaces. The", "container. Matches the podman inspection output. - Note that facts", "required: True type: str executable: description: - Path to C(podman)", "self.params['label']: after.update({ str(k).lower(): str(v).lower() for k, v in self.params['label'].items() })", "cmd.append(self.params['image']) if self.params['command']: if isinstance(self.params['command'], list): cmd += self.params['command'] else:", "= after.replace(\":latest\", \"\") before = before.split(\"/\")[-1] after = after.split(\"/\")[-1] return", "with networks in inspection \"network\": [\"default\"], \"oom_score_adj\": 0, \"pid\": \"\",", "- Add a host device to the container. The format", "of the matching container. - I(started) - Asserts there is", "only. type: str label: description: - Add metadata to a", "+= ['--security-opt', secopt] return c def addparam_shm_size(self, c): return c", "By default it's twice memory parameter before = str(self.info['hostconfig']['memoryswap']) after", "name, a container will be created. If a container matches", "returned: always type: dict sample: '{ \"AppArmorProfile\": \"\", \"Args\": [", "started restart: yes etc_hosts: other: \"127.0.0.1\" restart_policy: \"no\" device: \"/dev/sda:/dev/xvda:rwm\"", "['--device-read-bps', dev] return c def addparam_device_read_iops(self, c): for dev in", "name) and tag used to create the container. If an", "oom_score_adj: description: - Tune the host's OOM preferences for containers", "to get the default command if self.module.params['command'] is not None:", "bridge create a network stack on the default bridge *", "it can't guess default values def diffparam_env(self): env_before = self.info['config']['env']", "self._diff_update_and_compare('memory_reservation', before, after) def diffparam_network(self): before = [self.info['hostconfig']['networkmode']] after =", "file. For example log_opt \"path=/var/log/container/mycontainer.json\" type: str aliases: - log_options", "self.results.update({'diff': self.container.diff}) if self.module.params['debug']: self.results.update({'podman_version': self.container.version}) self.module.exit_json(**self.results) def make_started(self): \"\"\"Run", "container, for example '10.88.64.128'. Can only be used if no", "errors='surrogate_or_strict') for i in cmd] if self.action == 'delete': cmd", "hostname: description: - Container host name. Sets the container host", "after) def diffparam_cpuset_cpus(self): before = self.info['hostconfig']['cpusetcpus'] after = self.params['cpuset_cpus'] return", "or agreed to in writing, software # distributed under the", "['--add-host', ':'.join(host_ip)] return c def addparam_expose(self, c): for exp in", "None: before = self.info['config']['cmd'] after = self.params['command'] if isinstance(after, str):", "c def addparam_dns(self, c): return c + ['--dns', ','.join(self.params['dns'])] def", "self.stdout = out self.stderr = err if rc != 0:", "will be removed and re-created with the requested config. Image", "idempotency is supported for integers only. type: str memory_reservation: description:", "def addparam_cmd_args(self, c): return c + self.params['cmd_args'] class PodmanDefaults: def", "self.container.name) self.update_container_result() def make_stopped(self): \"\"\"Run actions if desired state is", "__future__ import absolute_import, division, print_function __metaclass__ = type import json", "cap_drop] return c def addparam_cgroups(self, c): self.check_version('--cgroups', minv='1.6.0') return c", "10k, where unit = b, k, m or g) Note", "in self.params['volume']: if vol: c += ['--volume', vol] return c", "% self.container.name) self.update_container_result() def make_absent(self): \"\"\"Run actions if desired state", "[ \"/usr/bin/podman\", \"--root\", ... ], \"GraphDriver\": { ... }, \"HostConfig\":", "userns: description: - Set the user namespace mode for the", "the path is not absolute, the path is considered to", "= before else: after = self.params['log_opt'].split(\"=\")[1] return self._diff_update_and_compare('log_opt', before, after)", "config if a healthcheck # was configured; otherwise the config", "image) return image_actions class PodmanContainer: \"\"\"Perform container tasks. Manages podman", "['--authfile', self.params['authfile']] def addparam_blkio_weight(self, c): return c + ['--blkio-weight', self.params['blkio_weight']]", "def get_info(self): \"\"\"Inspect container and gather info about it.\"\"\" rc,", "= self.params['cpuset_mems'] return self._diff_update_and_compare('cpuset_mems', before, after) def diffparam_device(self): before =", "- json-file log_opt: description: - Logging driver specific options. Used", "['--no-hosts=%s' % self.params['no_hosts']] def addparam_oom_kill_disable(self, c): return c + ['--oom-kill-disable=%s'", "action was performed (default: {True}) \"\"\" facts = self.container.get_info() if", "container's memory swappiness behavior. Accepts an integer between 0 and", "after) def diffparam_device(self): before = [\":\".join([i['pathonhost'], i['pathincontainer']]) for i in", "c): return c + ['--log-opt', self.params['log_opt']] def addparam_memory(self, c): return", "name {str} -- name of container \"\"\" super(PodmanContainer, self).__init__() self.module", "network namespace via 'network container:<name|id>'. The address must be within", "def addparam_healthcheck(self, c): return c + ['--healthcheck-command', self.params['healthcheck']] def addparam_healthcheck_interval(self,", "before = [self.info['hostconfig']['networkmode']] after = self.params['network'] return self._diff_update_and_compare('network', before, after)", "Asserts there is a running container matching the name and", "metadata to a container, pass dictionary of label names and", "processes. type: str init_path: description: - Path to the container-init", "the container host name that is available inside the container.", "['--http-proxy=%s' % self.params['http_proxy']] def addparam_image_volume(self, c): return c + ['--image-volume',", "information which can be helpful for investigations. type: bool default:", "different = True return different def ensure_image_exists(module, image): \"\"\"If image", "self.results['actions'].append('recreated %s' % self.container.name) self.update_container_result() elif self.container.stopped and not self.container.different:", "removed and re-created with the requested config. Image version will", "self.container.different: self.container.start() self.results['actions'].append('started %s' % self.container.name) self.update_container_result() def make_stopped(self): \"\"\"Run", "network * ns:<path> path to a network namespace to join", "{ 'env_file', 'env_host', \"ulimit\", # Defaults depend on user and", "[i.lower() for i in after.split()] elif isinstance(after, list): after =", "{ \"Annotations\": { \"io.kubernetes.cri-o.ContainerType\": \"sandbox\", \"io.kubernetes.cri-o.TTY\": \"false\" }, \"AttachStderr\": false,", "'podman_actions': self.container.actions}) self.module.exit_json(**self.results) def execute(self): \"\"\"Execute the desired action according", "\\ not module.params['image']: module.fail_json(msg=\"State '%s' required image to be configured!\"", "for m in before: if m['type'] == 'volume': volumes.append([m['name'], m['destination']])", "the container is first I(present), and then if the container", "\"ConmonPidFile\": \"...\", \"Created\": \"2019-06-17T19:13:09.873858307+03:00\", \"Dependencies\": [], \"Driver\": \"overlay\", \"EffectiveCaps\": [", "between 0 and 100. type: int mount: description: - Attach", "commands) You can also override the default path of the", "description: - The initialization time needed for a container to", "expose: - 6379 volumes_from: - mydata - name: Restart a", "under which the cgroup for the container will be created.", "str cgroup_parent: description: - Path to cgroups under which the", "Only effective on NUMA systems. type: str detach: description: -", "self.action in ['stop', 'start']: cmd = [self.action, self.params['name']] return [to_bytes(i,", "timer setup) (default \"30s\") type: str healthcheck_retries: description: - The", "= self.params['image_strict'] if mode is None or not mode: #", "the PID mode for the container type: str pids_limit: description:", "(action, self.name), stdout=out, stderr=err) def run(self): \"\"\"Run the container.\"\"\" self._perform_action('run')", "i in self.info['hostconfig']['extrahosts']]) else: before = {} after = self.params['etc_hosts']", "= self.params['security_opt'] before, after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('security_opt', before,", "inside the container. The default working directory for running binaries", "dns: description: - Set custom DNS servers type: list elements:", "name but the provided configuration does not match, the container", "be applied to container \"\"\" def __init__(self, module): \"\"\"Initialize PodmanManager", "return self._diff_update_and_compare('env_host', before, after) def diffparam_blkio_weight(self): before = self.info['hostconfig']['blkioweight'] after", "containers when they exit with a non-0 exit code, retrying", "self.container.exists: self.container.run() self.results['actions'].append('started %s' % self.container.name) self.update_container_result() elif self.container.stopped and", "self.module.params['recreate'] self.container = PodmanContainer(self.module, self.name) def update_container_result(self, changed=True): \"\"\"Inspect the", "self.container.running and \\ (self.container.different or self.recreate): self.container.recreate() self.results['actions'].append('recreated %s' %", "type: dict sample: '{ \"AppArmorProfile\": \"\", \"Args\": [ \"sh\" ],", "c + ['--publish-all=%s' % self.params['publish_all']] def addparam_read_only(self, c): return c", "to the container. bind or tmpfs For example mount \"type=bind,source=/path/on/host,destination=/path/in/container\"", "a full name with registry and namespaces. type: bool default:", "params {dict} -- dictionary of module parameters \"\"\" def __init__(self,", "\"seccomp=unconfined\" type: list elements: str shm_size: description: - Size of", "optionally the groupname or GID for the specified command. type:", "an existing container. type: bool default: False restart_policy: description: -", "- Tells podman how to handle the builtin image volumes.", "(@sshnaidm)\" version_added: '2.9' short_description: Manage podman containers notes: [] description:", "- Logging driver. Used to set the log driver for", "platform, impossible to guess } def defaultize(self): params_with_defaults = {}", "dictionary of label names and values type: dict label_file: description:", "container, inspects it and checks its current state \"\"\" def", "the log driver for the container. For example log_driver \"k8s-file\".", "self._diff_update_and_compare('security_opt', before, after) def diffparam_stop_signal(self): before = self.info['config']['stopsignal'] after =", "['--label', b'='.join([to_bytes(l, errors='surrogate_or_strict') for l in label])] return c def", "- Create a bind mount. If you specify, volume /HOST-DIR:/CONTAINER-DIR,", "restart_policy: description: - Restart policy to follow when containers exit.", "Can be a string or a list. type: raw cpu_period:", "- Kernel memory limit (format <number>[<unit>], where unit = b,", "... }' \"\"\" class PodmanModuleParams: \"\"\"Creates list of arguments for", "diffparam_log_opt(self): before = self.info['logpath'] if self.module.params['log_opt'] in [None, '']: after", "\"system_u:system_r:container_t:s0:c282,c782\", \"ResolvConfPath\": \"...\", \"RestartCount\": 0, \"Rootfs\": \"\", \"State\": { \"Dead\":", "self.info['hostconfig']['blkiodevicereadiops'] or [] before = [\"%s:%s\" % (i['path'], i['rate']) for", "self._diff_update_and_compare('volume', before, after) def diffparam_volumes_from(self): before = self.info['hostconfig']['volumesfrom'] or []", "the authentication file. Default is ``${XDG_RUNTIME_DIR}/containers/auth.json`` (Not available for remote", "name will be added to the container's ``/etc/hosts`` file. type:", "on NUMA systems. type: str detach: description: - Run container", "module, name): \"\"\"Initialize PodmanContainer class. Arguments: module {obj} -- ansible", "[self.action, self.params['name']] return [to_bytes(i, errors='surrogate_or_strict') for i in cmd] if", "elif not self.container.exists: self.container.run() self.results['actions'].append('started %s' % self.container.name) self.update_container_result() elif", "image, stdout=out, stderr=err) image_actions.append(\"pulled image %s\" % image) return image_actions", "bool oom_kill_disable: description: - Whether to disable OOM Killer for", "C(podman) executable if it is not in the C($PATH) on", "return c + ['--hostname', self.params['hostname']] def addparam_http_proxy(self, c): return c", "be relative to the cgroups path of the init process.", "self.name), stdout=out, stderr=err) def run(self): \"\"\"Run the container.\"\"\" self._perform_action('run') def", "after) return False def diffparam_cidfile(self): before = self.info['hostconfig']['containeridfile'] after =", "bool read_only: description: - Mount the container's root filesystem as", "\"Volumes\": null, \"WorkingDir\": \"/\" }, \"ConmonPidFile\": \"...\", \"Created\": \"2019-06-17T19:13:09.873858307+03:00\", \"Dependencies\":", "30s type: str hostname: description: - Container host name. Sets", "return c + ['--user', self.params['user']] def addparam_userns(self, c): return c", "= self.info['hostconfig']['cgroups'] after = self.params['cgroups'] return self._diff_update_and_compare('cgroups', before, after) return", "and any provided configuration. If no container matches the name,", "out, err = self.module.run_command( [self.module.params['executable'], b'container'] + b_command, expand_user_and_vars=False) self.stdout", "process that will be launched inside of the container. type:", "you, preference the pod name with \"new:\" type: str privileged:", "container matching the name and any provided configuration. If no", "Expose a port, or a range of ports (e.g. expose", "(format <number>[<unit>], where unit = b, k, m or g)", "Write the container ID to the file type: path cmd_args:", "c + ['--ip', self.params['ip']] def addparam_ipc(self, c): return c +", "out: self.module.fail_json(msg=\"%s run failed!\" % self.module.params['executable']) return out.split(\"version\")[1].strip() def _perform_action(self,", "- Path to cgroups under which the cgroup for the", "!= 0 or not out or \"version\" not in out:", "self._perform_action('delete') def stop(self): \"\"\"Stop the container.\"\"\" self._perform_action('stop') def start(self): \"\"\"Start", "return json.loads(out)[0] if rc == 0 else {} def _get_podman_version(self):", "'' after = self.params['healthcheck'] or before return self._diff_update_and_compare('healthcheck', before, after)", "is running moves it to a stopped state. type: str", "make here any changes to self.defaults related to podman version", "period Real Time tasks may consume. type: int cpu_shares: description:", "- name: Re-create a redis container podman_container: name: myredis image:", "bool tmpfs: description: - Create a tmpfs mount. For example", "env_host: description: - Use all current host environment variables in", "/dev/sda:1000) type: list device_write_bps: description: - Limit write rate (bytes", "podman_version self.defaults = { \"blkio_weight\": 0, \"cgroups\": \"default\", \"cgroup_parent\": \"\",", "- add_hosts expose: description: - Expose a port, or a", "c += ['--sysctl', b\"=\".join([to_bytes(k, errors='surrogate_or_strict') for k in sysctl])] return", "container. Format is a single character or ctrl-value type: str", "c): return c + ['--network', \",\".join(self.params['network'])] def addparam_no_hosts(self, c): return", "IO weight (relative device weight, format DEVICE_NAME[:]WEIGHT). type: dict cap_add:", "Set custom DNS search domains (Use dns_search with '' if", "- Set the PID mode for the container type: str", "c += ['--annotation', '='.join(annotate)] return c def addparam_authfile(self, c): return", "SIGKILL are not proxied. The default is true. type: bool", "self.container.stdout, self.container.stderr self.results.update({'changed': changed, 'container': facts, 'podman_actions': self.container.actions}, stdout=out, stderr=err)", "is not None and self.module.params[p] not in [{}, [], '']:", "addparam_http_proxy(self, c): return c + ['--http-proxy=%s' % self.params['http_proxy']] def addparam_image_volume(self,", "self.results['actions'].append('created %s' % self.container.name) self.update_container_result() if self.container.stopped: self.update_container_result(changed=False) elif self.container.running:", "already exist. type: path cgroupns: description: - Path to cgroups", "a container. Default is SIGTERM. type: int stop_timeout: description: -", "self.container.actions}, stdout=out, stderr=err) if self.container.diff: self.results.update({'diff': self.container.diff}) if self.module.params['debug']: self.results.update({'podman_version':", "def defaultize(self): params_with_defaults = {} self.default_dict = PodmanDefaults( self.module, self.version).default_dict()", "= PodmanModuleParams(action, self.module.params, self.version, self.module, ).construct_command_from_params() full_cmd = \" \".join([self.module.params['executable']]", "before = [\":\".join(v) for v in volumes] # Ignore volumes", "after = self.params['device_write_bps'] or [] before, after = sorted(list(set(before))), sorted(list(set(after)))", "\"device\": [], \"env_host\": False, \"etc_hosts\": {}, \"group_add\": [], \"healthcheck\": \"\",", "= PodmanContainer(self.module, self.name) def update_container_result(self, changed=True): \"\"\"Inspect the current container,", "\"_\".join([\"addparam\", param]) if func_name in all_param_methods: cmd = getattr(self, func_name)(cmd)", "last info, exit. Keyword Arguments: changed {bool} -- whether any", "If an image is not found, the image will be", "- Number of CPUs. The default is 0.0 which means", "publish_all: description: - Publish all exposed ports to random ports", "c): return c + ['--hostname', self.params['hostname']] def addparam_http_proxy(self, c): return", "i in env_before} after = before.copy() if self.params['env']: after.update({ str(k).lower():", "mount. If you specify, volume /HOST-DIR:/CONTAINER-DIR, podman bind mounts /HOST-DIR", "http_proxy option to false. The environment variables passed in include", "the actual healthcheck command. before = self.info['config']['healthcheck']['test'][1] else: before =", "dict systemd: description: - Run container in systemd mode. The", "to podman version return self.defaults class PodmanContainerDiff: def __init__(self, module,", "[to_native(i) for i in b_command]) self.module.log(\"PODMAN-CONTAINER-DEBUG: %s\" % full_cmd) self.actions.append(full_cmd)", "description: - Path to C(podman) executable if it is not", "+ ['--publish-all=%s' % self.params['publish_all']] def addparam_read_only(self, c): return c +", "bool default: False restart_policy: description: - Restart policy to follow", "PodmanManager class. Arguments: module {obj} -- ansible module object \"\"\"", "def addparam_interactive(self, c): return c + ['--interactive=%s' % self.params['interactive']] def", "be created if they do not already exist. type: path", "absolute_import, division, print_function __metaclass__ = type import json from distutils.version", "= self.info['hostconfig']['blkiodevicewriteiops'] or [] before = [\"%s:%s\" % (i['path'], i['rate'])", "update_container_result(self, changed=True): \"\"\"Inspect the current container, update results with last", "def make_started(self): \"\"\"Run actions if desired state is 'started'.\"\"\" if", "m['destination']]) else: volumes.append([m['source'], m['destination']]) before = [\":\".join(v) for v in", "+ ['--cpuset-cpus', self.params['cpuset_cpus']] def addparam_cpuset_mems(self, c): return c + ['--cpuset-mems',", "host\" options: name: description: - Name of the container required:", "c + ['--memory-swap', self.params['memory_swap']] def addparam_memory_swappiness(self, c): return c +", "(bytes), k (kilobytes), m(megabytes), or g (gigabytes). If you omit", "podman run command to the container process. SIGCHLD, SIGSTOP, and", "self.container.name) self.update_container_result() self.update_container_result(changed=False) elif not self.container.exists: self.container.run() self.results['actions'].append('started %s' %", "addparam_workdir(self, c): return c + ['--workdir', self.params['workdir']] # Add your", "read_only: description: - Mount the container's root filesystem as read", "for func_name in diff_func_list: dff_func = getattr(self, func_name) if dff_func():", "+= image_actions self.state = self.module.params['state'] self.restart = self.module.params['force_restart'] self.recreate =", "used if no additional CNI networks to join were specified", "and p in self.default_dict: params_with_defaults[p] = self.default_dict[p] else: params_with_defaults[p] =", "addparam_sig_proxy(self, c): return c + ['--sig-proxy=%s' % self.params['sig_proxy']] def addparam_stop_signal(self,", "def addparam_log_opt(self, c): return c + ['--log-opt', self.params['log_opt']] def addparam_memory(self,", "It defaults to the PODMAN_USERNS environment variable. An empty value", "stack on the default bridge * none no networking *", "option for idempotency after = [\":\".join(v.split(\":\")[:2]) for v in self.params['volume']]", "user network stack. This is the default for rootless containers", "- ports - published - published_ports publish_all: description: - Publish", "diffs['after'].items())]) + \"\\n\" return is_different @property def running(self): \"\"\"Return True", "False detach_keys: description: - Override the key sequence for detaching", "a device (e.g. device-read-iops /dev/sda:1000) type: list device_write_bps: description: -", "- Start, stop, restart and manage Podman containers requirements: -", "be removed in Ansible 2.12. - Empty if C(state) is", "i in before] after = self.params['device_read_iops'] or [] before, after", "of the container required: True type: str executable: description: -", "type: list device_read_iops: description: - Limit read rate (IO per", "file type: path cmd_args: description: - Any additionl command options", "c): for host_ip in self.params['etc_hosts'].items(): c += ['--add-host', ':'.join(host_ip)] return", "image: quay.io/bitnami/wildfly state: started - name: Create a data container", "environment variable. An empty value means user namespaces are disabled.", "list elements: str cgroup_parent: description: - Path to cgroups under", "podman \" \"version %s only! Current version is %s\" %", "\"version %s only! Current version is %s\" % ( param,", "Unless required by applicable law or agreed to in writing,", "10 and 1000 type: int blkio_weight_device: description: - Block IO", "command, cmd_args - ['--other-param', 'value'] Be aware module doesn't support", "The swap LIMIT should always be larger than -m (--memory)", "Mount volumes from the specified container(s). type: list elements: str", "in microseconds. Limit the container's Real Time CPU usage. This", "self.info['hostconfig']['blkioweightdevice'] if before == [] and self.module.params['blkio_weight_device'] is None: after", "to not create CGroups, and thus conflicts with CGroup options", "existence of a container matching the name and any provided", "no container matches the name, a container will be created", "mycontainer state: stopped - name: Start 4 load-balanced containers podman_container:", "list user: description: - Sets the username or UID used", "def addparam_read_only(self, c): return c + ['--read-only=%s' % self.params['read_only']] def", "options: name: description: - Name of the container required: True", "not self.container.different: if self.restart: self.container.restart() self.results['actions'].append('restarted %s' % self.container.name) self.update_container_result()", "type: int healthcheck_start_period: description: - The initialization time needed for", "desired state is 'stopped'.\"\"\" if not self.container.exists and not self.image:", "self.params['userns']] def addparam_uts(self, c): return c + ['--uts', self.params['uts']] def", "'{ \"AppArmorProfile\": \"\", \"Args\": [ \"sh\" ], \"BoundingCaps\": [ \"CAP_CHOWN\",", "idempotency if this is set. type: list elements: str conmon_pidfile:", "'value'] Be aware module doesn't support idempotency if this is", "int(self.info['hostconfig']['nanocpus']) / 1000000000 after = self.params['cpus'] return self._diff_update_and_compare('cpus', before, after)", "stopped and restarted. - I(stopped) - Asserts that the container", "stdin open even if not attached. The default is false.", "self.params['no_hosts'] if self.params['network'] == ['none']: after = True return self._diff_update_and_compare('no_hosts',", "/dev/sdc:/dev/xvdc:rwm) type: list elements: str device_read_bps: description: - Limit read", "- Restart containers when they exit, regardless of status, retrying", "self._diff_update_and_compare('cpuset_mems', before, after) def diffparam_device(self): before = [\":\".join([i['pathonhost'], i['pathincontainer']]) for", "either express or implied. See the # License for the", "to complete the healthcheck before an interval is considered failed.", "random generated, this parameter has partial idempotency only. def diffparam_hostname(self):", "signals sent to the podman run command to the container", "err = self.module.run_command( [self.module.params['executable'], b'container', b'inspect', self.name]) return json.loads(out)[0] if", "module self.version = podman_version self.default_dict = None self.info = yaml.safe_load(json.dumps(info).lower())", "return c + ['--memory-swappiness', self.params['memory_swappiness']] def addparam_mount(self, c): return c", "SysV IPC) for the container type: str kernel_memory: description: -", "self.module.params['cap_add'] is not None: after += [\"cap_\" + i.lower() for", "def _get_podman_version(self): rc, out, err = self.module.run_command( [self.module.params['executable'], b'--version']) if", "diffparam_volume(self): before = self.info['mounts'] if before: volumes = [] for", "of container \"\"\" super(PodmanContainer, self).__init__() self.module = module self.name =", "description: - Use all current host environment variables in container.", "the authentication file by setting the ``REGISTRY_AUTH_FILE`` environment variable. ``export", "PodmanDefaults: def __init__(self, module, podman_version): self.module = module self.version =", "* <network-name>|<network-id> connect to a user-defined network * ns:<path> path", "command: sleep 1d with_sequence: count=4 - name: remove container podman_container:", "['--cidfile', self.params['cidfile']] def addparam_conmon_pidfile(self, c): return c + ['--conmon-pidfile', self.params['conmon_pidfile']]", "not self.container.different: self.container.start() self.results['actions'].append('started %s' % self.container.name) self.update_container_result() def make_stopped(self):", "returned fact will be removed in Ansible 2.12. - Empty", "\"WorkingDir\": \"/\" }, \"ConmonPidFile\": \"...\", \"Created\": \"2019-06-17T19:13:09.873858307+03:00\", \"Dependencies\": [], \"Driver\":", "description: - Tune a container's memory swappiness behavior. Accepts an", "env_value])] return c def addparam_env_file(self, c): return c + ['--env-file',", "diffparam_device(self): before = [\":\".join([i['pathonhost'], i['pathincontainer']]) for i in self.info['hostconfig']['devices']] after", "optional max_retries count is hit * always - Restart containers", "self._diff_update_and_compare('memory', before, after) def diffparam_memory_swap(self): # By default it's twice", "to a device (e.g. device-write-bps /dev/sda:1mb) type: list device_write_iops: description:", "if self.module.params['cap_add'] is not None: after += [\"cap_\" + i.lower()", "Whether to disable OOM Killer for the container or not.", "'name' in the /etc/subuid file. type: str sysctl: description: -", "if mode is None or not mode: # In a", "part of the registered vars since Ansible 2.8. For compatibility", "(e.g. device-read-iops /dev/sda:1000) type: list device_write_bps: description: - Limit write", "self.module.params[p] is None and p in self.default_dict: params_with_defaults[p] = self.default_dict[p]", "% self.params['interactive']] def addparam_ip(self, c): return c + ['--ip', self.params['ip']]", "PODMAN_USERNS environment variable. An empty value means user namespaces are", "= self.defaultize() self.diff = {'before': {}, 'after': {}} self.non_idempotent =", "['--gidmap', self.params['gidmap']] def addparam_group_add(self, c): for g in self.params['group_add']: c", "exists(self): \"\"\"Check if container exists.\"\"\" return bool(self.info != {}) @property", "b, k, m or g) Note - idempotency is supported", "be stopped and removed. - I(present) - Asserts the existence", "super(PodmanManager, self).__init__() self.module = module self.results = { 'changed': False,", "command if self.module.params['command'] is not None: before = self.info['config']['cmd'] after", "diffparam_cpu_rt_period(self): before = self.info['hostconfig']['cpurealtimeperiod'] after = self.params['cpu_rt_period'] return self._diff_update_and_compare('cpu_rt_period', before,", "ENTRYPOINT of the image type: str env: description: - Set", "\"ProcessLabel\": \"system_u:system_r:container_t:s0:c282,c782\", \"ResolvConfPath\": \"...\", \"RestartCount\": 0, \"Rootfs\": \"\", \"State\": {", "False, \"etc_hosts\": {}, \"group_add\": [], \"healthcheck\": \"\", \"ipc\": \"\", \"kernelmemory\":", "= self.info['hostconfig']['oomscoreadj'] after = self.params['oom_score_adj'] return self._diff_update_and_compare('oom_score_adj', before, after) def", "ports on the host interfaces. The default is false. type:", "addparam_blkio_weight(self, c): return c + ['--blkio-weight', self.params['blkio_weight']] def addparam_blkio_weight_device(self, c):", "= before.replace(\":latest\", \"\") after = after.replace(\":latest\", \"\") before = before.split(\"/\")[-1]", "if the container is not joining another container's network namespace", "before, after) def diffparam_blkio_weight(self): before = self.info['hostconfig']['blkioweight'] after = self.params['blkio_weight']", "for the container or not. Default is false. type: bool", "{str} -- action type from 'run', 'stop', 'create', 'delete', 'start'", "\"\", \"ipc\": \"\", \"kernelmemory\": \"0\", \"log_driver\": \"k8s-file\", \"memory\": \"0\", \"memory_swap\":", "after = self.params['cpuset_mems'] return self._diff_update_and_compare('cpuset_mems', before, after) def diffparam_device(self): before", "self.params['name']] return [to_bytes(i, errors='surrogate_or_strict') for i in cmd] if self.action", "Returns: list -- list of image actions - if it", "- 'bind' - 'tmpfs' - 'ignore' image_strict: description: - Whether", "before, after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('device_write_bps', before, after) def", "default_dict(self): # make here any changes to self.defaults related to", "return [to_bytes(i, errors='surrogate_or_strict') for i in cmd] def start_stop_delete(self): if", "= self.info['hostconfig']['cpuperiod'] after = self.params['cpu_period'] return self._diff_update_and_compare('cpu_period', before, after) def", "\"\", \"Env\": [ \"PATH=/usr/sbin:/usr/bin:/sbin:/bin\", \"TERM=xterm\", \"HOSTNAME=\", \"container=podman\" ], \"Hostname\": \"\",", "the image type: str env: description: - Set environment variables.", "b (bytes), k (kilobytes), m(megabytes), or g (gigabytes). If you", "return self._diff_update_and_compare('cgroups', before, after) return False def diffparam_cidfile(self): before =", "+ ['--healthcheck-timeout', self.params['healthcheck_timeout']] def addparam_hostname(self, c): return c + ['--hostname',", "for u in self.params['ulimit']: c += ['--ulimit', u] return c", "self._diff_update_and_compare('blkio_weight_device', before, after) def diffparam_cap_add(self): before = self.info['effectivecaps'] or []", "the container. It defaults to the PODMAN_USERNS environment variable. An", "- Create a tmpfs mount. For example tmpfs \"/tmp\" \"rw,size=787448k,mode=1777\"", "create, stop, run, delete \"\"\" b_command = PodmanModuleParams(action, self.module.params, self.version,", "type: path cmd_args: description: - Any additionl command options you", "Size of /dev/shm. The format is <number><unit>. number must be", "0, \"uid\": 0 }, \"Volumes\": null, \"WorkingDir\": \"/\" }, \"ConmonPidFile\":", "- name: Writing output podman_container: name: myservice image: busybox log_options:", "[] before, after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('device_write_iops', before, after)", "started choices: - absent - present - stopped - started", "c + ['--read-only-tmpfs=%s' % self.params['read_only_tmpfs']] def addparam_restart_policy(self, c): return c", "names and values type: dict label_file: description: - Read in", "description: - Memory limit (format 10k, where unit = b,", "only. type: str memory_swappiness: description: - Tune a container's memory", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "c + ['--pids-limit', self.params['pids_limit']] def addparam_pod(self, c): return c +", "+ ['--user', self.params['user']] def addparam_userns(self, c): return c + ['--userns',", "self.container.exists: self.container.delete() self.results['actions'].append('deleted %s' % self.container.name) self.results.update({'changed': True}) self.results.update({'container': {},", "force the re-creation of the matching container. - I(started) -", "self.version = podman_version self.defaults = { \"blkio_weight\": 0, \"cgroups\": \"default\",", "of 2 items where the first one is # \"CMD-SHELL\"", "type: str entrypoint: description: - Overwrite the default ENTRYPOINT of", "for idempotency after = [\":\".join(v.split(\":\")[:2]) for v in self.params['volume']] before,", "License. # flake8: noqa: E501 from __future__ import absolute_import, division,", "\"\"\"Restart the container.\"\"\" self.stop() self.run() class PodmanManager: \"\"\"Module manager class.", "this container. The default is false. type: bool publish: description:", "set for the podman process. This can be disabled by", "self.params['entrypoint']] def addparam_env(self, c): for env_value in self.params['env'].items(): c +=", "to a file. conmon runs in a separate process than", "True, \"device\": [], \"env_host\": False, \"etc_hosts\": {}, \"group_add\": [], \"healthcheck\":", "flag tells the kernel to limit the amount of time", "the existence of a container matching the name and any", "self._diff_update_and_compare('image', before, after) def diffparam_ipc(self): before = self.info['hostconfig']['ipcmode'] after =", "self.defaults = { \"blkio_weight\": 0, \"cgroups\": \"default\", \"cgroup_parent\": \"\", \"cidfile\":", "network: description: - Set the Network mode for the container", "= self.info['hostconfig']['cpurealtimeruntime'] after = self.params['cpu_rt_runtime'] return self._diff_update_and_compare('cpu_rt_runtime', before, after) def", "for podman CLI command. Arguments: action {str} -- action type", "command: description: - Override command of container. Can be a", "\"HOSTNAME=\", \"container=podman\" ], \"Hostname\": \"\", \"Image\": \"docker.io/library/busybox:latest\", \"Labels\": null, \"OpenStdin\":", "if rc == 0: return image_actions rc, out, err =", "after) def is_different(self): diff_func_list = [func for func in dir(self)", "- Block IO weight (relative device weight, format DEVICE_NAME[:]WEIGHT). type:", "list -- list of image actions - if it pulled", "checks its current state \"\"\" def __init__(self, module, name): \"\"\"Initialize", "(default \"30s\") type: str healthcheck_retries: description: - The number of", "self.podman_version = podman_version self.module = module def construct_command_from_params(self): \"\"\"Create a", "self.params['volumes_from']: c += ['--volumes-from', vol] return c def addparam_workdir(self, c):", "description: - Attach a filesystem mount to the container. bind", "after) def diffparam_volume(self): before = self.info['mounts'] if before: volumes =", "['--expose', exp] return c def addparam_gidmap(self, c): return c +", "self._diff_update_and_compare('cpuset_cpus', before, after) def diffparam_cpuset_mems(self): before = self.info['hostconfig']['cpusetmems'] after =", "module, info, podman_version): self.module = module self.version = podman_version self.default_dict", "file by setting the ``REGISTRY_AUTH_FILE`` environment variable. ``export REGISTRY_AUTH_FILE=path`` type:", "port, or a range of ports (e.g. expose \"3300-3310\") to", "entirely, the system uses 64m type: str sig_proxy: description: -", "1000 type: int blkio_weight_device: description: - Block IO weight (relative", "list device_write_iops: description: - Limit write rate (IO per second)", "command: redis-server --appendonly yes state: present recreate: yes expose: -", "restrict the container's Real Time CPU usage to the period", "registries are the same before = before.replace(\":latest\", \"\") after =", "is supported till podman \" \"version %s only! Current version", "type from 'run', 'stop', 'create', 'delete', 'start' params {dict} --", "+= ['--volumes-from', vol] return c def addparam_workdir(self, c): return c", "(accepts -1000 to 1000) type: int pid: description: - Set", "name: myredis image: redis command: redis-server --appendonly yes state: present", "before, after) # Limited idempotency, it can't guess default values", "part of the config. def diffparam_healthcheck(self): if 'healthcheck' in self.info['config']:", "device to the container. The format is <device-on-host>[:<device-on-container>][:<permissions>] (e.g. device", "Use all current host environment variables in container. Defaults to", "if self.container.diff: self.results.update({'diff': self.container.diff}) if self.module.params['debug']: self.results.update({'podman_version': self.container.version}) self.module.exit_json(**self.results) def", "limit value equal to memory plus swap. Must be used", "device: description: - Add a host device to the container.", "self.results['actions'].append('deleted %s' % self.container.name) self.results.update({'changed': True}) self.results.update({'container': {}, 'podman_actions': self.container.actions})", "attached. The default is false. type: bool ip: description: -", "diffparam_cap_add(self): before = self.info['effectivecaps'] or [] after = [] if", "before = self.info['hostconfig']['privileged'] after = self.params['privileged'] return self._diff_update_and_compare('privileged', before, after)", "Note that facts are part of the registered vars since", "diffparam_security_opt(self): before = self.info['hostconfig']['securityopt'] after = self.params['security_opt'] before, after =", "is optional and can be b (bytes), k (kilobytes), m(megabytes),", "def addparam_cpu_rt_period(self, c): return c + ['--cpu-rt-period', self.params['cpu_rt_period']] def addparam_cpu_rt_runtime(self,", "= {} self.default_dict = PodmanDefaults( self.module, self.version).default_dict() for p in", "\"ExecIDs\": [], \"ExitCommand\": [ \"/usr/bin/podman\", \"--root\", ... ], \"GraphDriver\": {", "c + ['--interactive=%s' % self.params['interactive']] def addparam_ip(self, c): return c", "self.state = self.module.params['state'] self.restart = self.module.params['force_restart'] self.recreate = self.module.params['recreate'] self.container", "non idempotent parameters for p in self.non_idempotent: if self.module.params[p] is", "to guess the default log_path def diffparam_log_opt(self): before = self.info['logpath']", "allowed before a healthcheck is considered to be unhealthy. The", "= self.info['hostconfig']['blkioweightdevice'] if before == [] and self.module.params['blkio_weight_device'] is None:", "type: int subgidname: description: - Run the container in a", "i in after.split()] elif isinstance(after, list): after = [i.lower() for", "== 0: return image_actions rc, out, err = module.run_command([module_exec, 'image',", "+ ['--ipc', self.params['ipc']] def addparam_kernel_memory(self, c): return c + ['--kernel-memory',", "if the container is running moves it to a stopped", "= str(self.info['hostconfig']['memory']) after = self.params['memory'] return self._diff_update_and_compare('memory', before, after) def", "which can be helpful for investigations. type: bool default: False", "self.params['volumes_from'] or [] return self._diff_update_and_compare('volumes_from', before, after) def diffparam_workdir(self): before", "for func in dir(self) if callable(getattr(self, func)) and func.startswith(\"addparam\")] params_set", "For example tmpfs \"/tmp\" \"rw,size=787448k,mode=1777\" type: dict tty: description: -", "k, m or g) Note - idempotency is supported for", "from podman \" \"version %s only! Current version is %s\"", "cpuset_mems: description: - Memory nodes (MEMs) in which to allow", "or [] before = [\"%s:%s\" % (i['path'], i['rate']) for i", "container will be created and started. Use recreate to always", "str pod: description: - Run container in an existing pod.", "False after = self.params['env_host'] return self._diff_update_and_compare('env_host', before, after) def diffparam_blkio_weight(self):", "after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('device_write_iops', before, after) # Limited", "k8s-file \"\"\" RETURN = \"\"\" container: description: - Facts representing", "'2.9' short_description: Manage podman containers notes: [] description: - Start,", "(i['path'], i['rate']) for i in before] after = self.params['device_write_iops'] or", "kernel to limit the amount of time in a given", "container(s). type: list elements: str workdir: description: - Working directory", "self.params['image_volume']] def addparam_init(self, c): return c + ['--init', self.params['init']] def", "results in no automatic timer setup) (default \"30s\") type: str", "\"Pid\": 4083, \"Restarting\": false, \"Running\": false, \"StartedAt\": \"2019-06-17T19:13:10.152479729+03:00\", \"Status\": \"exited\"", "def addparam_log_driver(self, c): return c + ['--log-driver', self.params['log_driver']] def addparam_log_opt(self,", "'ignore' image_strict: description: - Whether to compare images in idempotency", "addparam_healthcheck_retries(self, c): return c + ['--healthcheck-retries', self.params['healthcheck_retries']] def addparam_healthcheck_start_period(self, c):", "a private IPC namespace (POSIX SysV IPC) for the container", "else: after = self.params['conmon_pidfile'] return self._diff_update_and_compare('conmon_pidfile', before, after) def diffparam_cpu_period(self):", "distributed under the License is distributed on an \"AS IS\"", "whether the container will create CGroups. Valid values are enabled", "= getattr(self, func_name)(cmd) cmd.append(self.params['image']) if self.params['command']: if isinstance(self.params['command'], list): cmd", "return self._diff_update_and_compare('cpu_rt_runtime', before, after) def diffparam_cpu_shares(self): before = self.info['hostconfig']['cpushares'] after", "the healthcheck before an interval is considered failed. Like start-period,", "in [\"cap_\" + i.lower() for i in self.module.params['cap_drop']]: if c", "','.join(self.params['dns'])] def addparam_dns_option(self, c): return c + ['--dns-option', self.params['dns_option']] def", "[self.action, '--name', self.params['name']] all_param_methods = [func for func in dir(self)", "- If container is running in --read-only mode, then mount", "self.module.exit_json(**self.results) def execute(self): \"\"\"Execute the desired action according to map", "(0-3, 0,1). Only effective on NUMA systems. type: str detach:", "def addparam_rootfs(self, c): return c + ['--rootfs=%s' % self.params['rootfs']] def", "ignore (default bind) type: str choices: - 'bind' - 'tmpfs'", "- Publish a container's port, or range of ports, to", "c += ['--env', b\"=\".join([to_bytes(k, errors='surrogate_or_strict') for k in env_value])] return", "def addparam_tty(self, c): return c + ['--tty=%s' % self.params['tty']] def", "on-failure[:max_retries] - Restart containers when they exit with a non-0", "ip::containerPort | hostPort:containerPort | containerPort type: list elements: str aliases:", "- name: Container present podman_container: name: mycontainer state: present image:", "exist. type: path cgroupns: description: - Path to cgroups under", "self.params['memory_swap']] def addparam_memory_swappiness(self, c): return c + ['--memory-swappiness', self.params['memory_swappiness']] def", "container. For example log_driver \"k8s-file\". type: str choices: - k8s-file", "str memory_swap: description: - A limit value equal to memory", "['--cap-drop', cap_drop] return c def addparam_cgroups(self, c): self.check_version('--cgroups', minv='1.6.0') return", "list elements: str shm_size: description: - Size of /dev/shm. The", "to map of actions & states.\"\"\" states_map = { 'present':", "ulimit: description: - Ulimit options type: list user: description: -", "{ ... }, \"HostConfig\": { ... }, \"HostnamePath\": \"...\", \"HostsPath\":", "None and self.module.params[p] not in [{}, [], '']: different =", "c + ['--pod', self.params['pod']] def addparam_privileged(self, c): return c +", "description: - Security Options. For example security_opt \"seccomp=unconfined\" type: list", "image is assumed to be available locally. type: str annotation:", "self.info['hostconfig']['blkiodevicewritebps'] or [] before = [\"%s:%s\" % (i['path'], i['rate']) for", "after = self.params['rm'] return self._diff_update_and_compare('rm', before, after) def diffparam_security_opt(self): before", "notes: [] description: - Start, stop, restart and manage Podman", "aliases: - volumes volumes_from: description: - Mount volumes from the", "self.results['actions'] += image_actions self.state = self.module.params['state'] self.restart = self.module.params['force_restart'] self.recreate", "def make_absent(self): \"\"\"Run actions if desired state is 'absent'.\"\"\" if", "PodmanModuleParams: \"\"\"Creates list of arguments for podman CLI command. Arguments:", "See the # License for the specific language governing permissions", "it's twice memory parameter before = str(self.info['hostconfig']['memoryswap']) after = self.params['memory_swap']", "'podman_actions': self.container.actions}, stdout=out, stderr=err) if self.container.diff: self.results.update({'diff': self.container.diff}) if self.module.params['debug']:", "and cgroup-parent. type: str choices: - default - disabled cidfile:", "conmon runs in a separate process than Podman, so this", "+= ['--publish', pub] return c def addparam_publish_all(self, c): return c", "config key isn't part of the config. def diffparam_healthcheck(self): if", "return c + ['--healthcheck-start-period', self.params['healthcheck_start_period']] def addparam_healthcheck_timeout(self, c): return c", "before, after) def diffparam_volume(self): before = self.info['mounts'] if before: volumes", "(e.g. device-read-bps /dev/sda:1mb) type: list device_read_iops: description: - Limit read", "= self.info['hostconfig']['cpurealtimeperiod'] after = self.params['cpu_rt_period'] return self._diff_update_and_compare('cpu_rt_period', before, after) def", "a range of ports (e.g. expose \"3300-3310\") to set up", "[] module_exec = module.params['executable'] if not image: return image_actions rc,", "create(self): \"\"\"Create the container.\"\"\" self._perform_action('create') def recreate(self): \"\"\"Recreate the container.\"\"\"", "in self.params['label'].items(): c += ['--label', b'='.join([to_bytes(l, errors='surrogate_or_strict') for l in", "elements: str device_read_bps: description: - Limit read rate (bytes per", "image name) and tag used to create the container. If", "The default is false. type: bool ip: description: - Specify", "[to_bytes(i, errors='surrogate_or_strict') for i in cmd] def start_stop_delete(self): if self.action", "def addparam_cap_add(self, c): for cap_add in self.params['cap_add']: c += ['--cap-add',", "name. Sets the container host name that is available inside", "user namespace using the supplied mapping. type: list ulimit: description:", "podman command from given module parameters. Returns: list -- list", "c): return c + ['--memory', self.params['memory']] def addparam_memory_reservation(self, c): return", "container:<name|id> reuse another container's network stack * host use the", "of container. Can be a string or a list. type:", "def run(self): \"\"\"Run the container.\"\"\" self._perform_action('run') def delete(self): \"\"\"Delete the", "additional groups to run as type: list healthcheck: description: -", "description: - Limit the CPU real-time runtime in microseconds. This", "0, \"Log\": null, \"Status\": \"\" }, \"OOMKilled\": false, \"OciVersion\": \"1.0.1-dev\",", "['--workdir', self.params['workdir']] # Add your own args for podman command", "states.\"\"\" states_map = { 'present': self.make_started, 'started': self.make_started, 'absent': self.make_absent,", "For example log_opt \"path=/var/log/container/mycontainer.json\" type: str aliases: - log_options memory:", "for rootless containers type: list elements: str aliases: - net", "return c + ['--cpuset-cpus', self.params['cpuset_cpus']] def addparam_cpuset_mems(self, c): return c", "(i['path'], i['rate']) for i in before] after = self.params['device_read_iops'] or", "of the container. Matches the podman inspection output. - Note", "mode is None or not mode: # In a idempotency", "environment variable. ``export REGISTRY_AUTH_FILE=path`` type: path blkio_weight: description: - Block", "ID. If this is the case, the image is assumed", "\"\"\" RETURN = \"\"\" container: description: - Facts representing the", "that is available inside the container. type: str http_proxy: description:", "= \"\"\" container: description: - Facts representing the current state", "def diffparam_device_write_bps(self): before = self.info['hostconfig']['blkiodevicewritebps'] or [] before = [\"%s:%s\"", "u in self.params['ulimit']: c += ['--ulimit', u] return c def", "container.\"\"\" self._perform_action('create') def recreate(self): \"\"\"Recreate the container.\"\"\" self.delete() self.run() def", "exit code, retrying indefinitely or until the optional max_retries count", "self._diff_update_and_compare('blkio_weight', before, after) def diffparam_blkio_weight_device(self): before = self.info['hostconfig']['blkioweightdevice'] if before", "image: busybox log_options: path=/var/log/container/mycontainer.json log_driver: k8s-file \"\"\" RETURN = \"\"\"", "the machine running C(podman) default: 'podman' type: str state: description:", "}, \"AttachStderr\": false, \"AttachStdin\": false, \"AttachStdout\": false, \"Cmd\": [ \"sh\"", "a device (e.g. device-write-bps /dev/sda:1mb) type: list device_write_iops: description: -", "self.container.restart() self.results['actions'].append('restarted %s' % self.container.name) self.update_container_result() self.update_container_result(changed=False) elif not self.container.exists:", "to the period you specify. type: int cpu_rt_runtime: description: -", "time in a given CPU period Real Time tasks may", "after) def diffparam_rm(self): before = self.info['hostconfig']['autoremove'] after = self.params['rm'] return", "of environment variables type: path env_host: description: - Use all", "pod for you, preference the pod name with \"new:\" type:", "description: - Set an interval for the healthchecks (a value", "= self.params['privileged'] return self._diff_update_and_compare('privileged', before, after) def diffparam_pid(self): before =", "c): return c + ['--kernel-memory', self.params['kernel_memory']] def addparam_label(self, c): for", "c + ['--dns-option', self.params['dns_option']] def addparam_dns_search(self, c): return c +", "module): self.params = params self.action = action self.podman_version = podman_version", "container. The format is <device-on-host>[:<device-on-container>][:<permissions>] (e.g. device /dev/sdc:/dev/xvdc:rwm) type: list", "container matching the name and any provided configuration parameters. If", "* host use the podman host network stack. * <network-name>|<network-id>", "be greater than 0. Unit is optional and can be", "c + ['--healthcheck-command', self.params['healthcheck']] def addparam_healthcheck_interval(self, c): return c +", "was performed (default: {True}) \"\"\" facts = self.container.get_info() if changed", "\"ID\": \"...\", \"Image\": \"...\", \"ImageName\": \"docker.io/library/busybox:latest\", \"IsInfra\": false, \"LogPath\": \"/tmp/container/mycontainer.json\",", "is a running container matching the name and any provided", "parameters what actions should be applied to container \"\"\" def", "the facts are also accessible directly as C(podman_container). Note that", "the container * bridge create a network stack on the", "image_actions class PodmanContainer: \"\"\"Perform container tasks. Manages podman container, inspects", "address must be within the default CNI network's pool (default", "description: - Size of /dev/shm. The format is <number><unit>. number", "not take effect if a container is stopped via the", "restart and manage Podman containers requirements: - \"Podman installed on", "the username or UID used and optionally the groupname or", "systems. type: str detach: description: - Run container in detach", "after: after.remove(c) before, after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('cap_drop', before,", "None and self.params['memory'] != 0 and self.params['memory'].isdigit()): after = str(int(self.params['memory'])", "stopped via the podman kill or podman stop commands. Valid", "rc != 0 or not out or \"version\" not in", "before[:] if self.module.params['cap_drop'] is not None: for c in [\"cap_\"", "+= ['--device-read-bps', dev] return c def addparam_device_read_iops(self, c): for dev", "recreate it if not default before = False after =", "self.info = self.get_info() self.version = self._get_podman_version() self.diff = {} self.actions", "after = self.params['cpu_shares'] return self._diff_update_and_compare('cpu_shares', before, after) def diffparam_cpus(self): before", "CPU usage to the period you specify. type: int cpu_rt_runtime:", "filesystem as read only. Default is false type: bool read_only_tmpfs:", "is_different @property def running(self): \"\"\"Return True if container is running", "self.info['mounts'] if before: volumes = [] for m in before:", "import json from distutils.version import LooseVersion import yaml from ansible.module_utils.basic", "get the default command if self.module.params['command'] is not None: before", "c def addparam_systemd(self, c): return c + ['--systemd=%s' % self.params['systemd']]", "'delete']: return self.start_stop_delete() if self.action in ['create', 'run']: cmd =", "+ ['--mount', self.params['mount']] def addparam_network(self, c): return c + ['--network',", "self.module.params[p] return params_with_defaults def _diff_update_and_compare(self, param_name, before, after): if before", "of CPUs. The default is 0.0 which means no limit.", "self.params['blkio_weight_device'] return self._diff_update_and_compare('blkio_weight_device', before, after) def diffparam_cap_add(self): before = self.info['effectivecaps']", "to false. type: bool etc_hosts: description: - Dict of host-to-IP", "\"type=bind,source=/path/on/host,destination=/path/in/container\" type: str network: description: - Set the Network mode", "addparam_publish_all(self, c): return c + ['--publish-all=%s' % self.params['publish_all']] def addparam_read_only(self,", "facts are also accessible directly as C(podman_container). Note that the", "return c + ['--authfile', self.params['authfile']] def addparam_blkio_weight(self, c): return c", "{ 'changed': False, 'actions': [], 'container': {}, } self.name =", "= action self.podman_version = podman_version self.module = module def construct_command_from_params(self):", "rc, out, err = self.module.run_command( [self.module.params['executable'], b'container'] + b_command, expand_user_and_vars=False)", "type: int mount: description: - Attach a filesystem mount to", "str dns_option: description: - Set custom DNS options type: str", "in a time format such as 1m22s. The default value", "int cpus: description: - Number of CPUs. The default is", "absent - name: Writing output podman_container: name: myservice image: busybox", "['--sysctl', b\"=\".join([to_bytes(k, errors='surrogate_or_strict') for k in sysctl])] return c def", "values type: dict label_file: description: - Read in a line", "self.params['image_strict'] if mode is None or not mode: # In", "['--annotation', '='.join(annotate)] return c def addparam_authfile(self, c): return c +", "created. type: str cgroups: description: - Determines whether the container", "complete the healthcheck before an interval is considered failed. Like", "type: str cgroups: description: - Determines whether the container will", "container. Can be a string or a list. type: raw", "container. Defaults to false. type: bool etc_hosts: description: - Dict", "false. type: bool aliases: - remove rootfs: description: - If", "return self._diff_update_and_compare('etc_hosts', before, after) def diffparam_group_add(self): before = self.info['hostconfig']['groupadd'] after", "of --memory Note - idempotency is supported for integers only.", "for i in cmd] def check_version(self, param, minv=None, maxv=None): if", "['--restart=%s' % self.params['restart_policy']] def addparam_rm(self, c): if self.params['rm']: c +=", "in self.params['env'].items(): c += ['--env', b\"=\".join([to_bytes(k, errors='surrogate_or_strict') for k in", "format is key value, multiple times. type: dict authfile: description:", "{ \"gid\": 0, \"uid\": 0 }, \"Volumes\": null, \"WorkingDir\": \"/\"", "c): return c + ['--cpuset-mems', self.params['cpuset_mems']] def addparam_detach(self, c): return", "or before return self._diff_update_and_compare('healthcheck', before, after) # Because of hostname", "not - pull it or fail. Arguments: module {obj} --", "Default is false. type: bool oom_score_adj: description: - Tune the", "\"Status\": \"\" }, \"OOMKilled\": false, \"OciVersion\": \"1.0.1-dev\", \"Paused\": false, \"Pid\":", "param, minv, self.podman_version)) if maxv and LooseVersion(maxv) < LooseVersion( self.podman_version):", "also be an image ID. If this is the case,", "[], 'container': {}, } self.name = self.module.params['name'] self.executable = \\", "from distutils.version import LooseVersion import yaml from ansible.module_utils.basic import AnsibleModule", "['--security-opt', secopt] return c def addparam_shm_size(self, c): return c +", "not attached. The default is false. When set to true,", "net no_hosts: description: - Do not create /etc/hosts for the", "| hostPort:containerPort | containerPort type: list elements: str aliases: -", "\"env_host\": False, \"etc_hosts\": {}, \"group_add\": [], \"healthcheck\": \"\", \"ipc\": \"\",", "be an image ID. If this is the case, the", "an interval for the healthchecks (a value of disable results", "guess default values def diffparam_env(self): env_before = self.info['config']['env'] or {}", "i in b_command]) self.module.log(\"PODMAN-CONTAINER-DEBUG: %s\" % full_cmd) self.actions.append(full_cmd) if not", "-1, \"no_hosts\": False, # libpod issue with networks in inspection", "created if they do not already exist. type: path cgroupns:", "str userns: description: - Set the user namespace mode for", "tasks may consume. type: int cpu_shares: description: - CPU shares", "create CGroups, and thus conflicts with CGroup options cgroupns and", "container \"\"\" def __init__(self, module): \"\"\"Initialize PodmanManager class. Arguments: module", "str(k).lower(): str(v).lower() for k, v in self.params['label'].items() }) return self._diff_update_and_compare('label',", "before, after) def diffparam_label(self): before = self.info['config']['labels'] or {} after", "% self.params['no_hosts']] def addparam_oom_kill_disable(self, c): return c + ['--oom-kill-disable=%s' %", "conflicts with CGroup options cgroupns and cgroup-parent. type: str choices:", "OF ANY KIND, either express or implied. See the #", "via the podman kill or podman stop commands. Valid values", "module parameters. Returns: list -- list of byte strings for", "1m22s. The default value is 30s type: str hostname: description:", "container \"\"\" super(PodmanContainer, self).__init__() self.module = module self.name = name", "applied to container \"\"\" def __init__(self, module): \"\"\"Initialize PodmanManager class.", "binaries within a container is the root directory (/). type:", "['--init', self.params['init']] def addparam_init_path(self, c): return c + ['--init-path', self.params['init_path']]", "['--device-write-bps', dev] return c def addparam_device_write_iops(self, c): for dev in", "podman version return self.defaults class PodmanContainerDiff: def __init__(self, module, info,", "for Popen command \"\"\" if self.action in ['start', 'stop', 'delete']:", "device-read-iops /dev/sda:1000) type: list device_write_bps: description: - Limit write rate", "false, \"AttachStdin\": false, \"AttachStdout\": false, \"Cmd\": [ \"sh\" ], \"Domainname\":", "name: Create a data container podman_container: name: mydata image: busybox", "], \"Domainname\": \"\", \"Entrypoint\": \"\", \"Env\": [ \"PATH=/usr/sbin:/usr/bin:/sbin:/bin\", \"TERM=xterm\", \"HOSTNAME=\",", "memory swappiness behavior. Accepts an integer between 0 and 100.", "\"container=podman\" ], \"Hostname\": \"\", \"Image\": \"docker.io/library/busybox:latest\", \"Labels\": null, \"OpenStdin\": false,", "+= ['--add-host', ':'.join(host_ip)] return c def addparam_expose(self, c): for exp", "+ i.lower() for i in self.module.params['cap_drop']]: if c in after:", "with the License. You may obtain # a copy of", "module.fail_json(msg=\"Can't pull image %s\" % image, stdout=out, stderr=err) image_actions.append(\"pulled image", "None and before: after = before else: after = self.params['user']", "self.params['authfile']] def addparam_blkio_weight(self, c): return c + ['--blkio-weight', self.params['blkio_weight']] def", "def exists(self): \"\"\"Check if container exists.\"\"\" return bool(self.info != {})", "'stopped': self.make_stopped } process_action = states_map[self.state] process_action() self.module.fail_json(msg=\"Unexpected logic error", "4083, \"Restarting\": false, \"Running\": false, \"StartedAt\": \"2019-06-17T19:13:10.152479729+03:00\", \"Status\": \"exited\" },", "or fail. Arguments: module {obj} -- ansible module object image", "[] and self.module.params['blkio_weight_device'] is None: after = [] else: after", "self.params['device_read_iops']: c += ['--device-read-iops', dev] return c def addparam_device_write_bps(self, c):", "def restart(self): \"\"\"Restart the container.\"\"\" self.stop() self.run() class PodmanManager: \"\"\"Module", "if self.module.params[p] is not None and self.module.params[p] not in [{},", "host_ip in self.params['etc_hosts'].items(): c += ['--add-host', ':'.join(host_ip)] return c def", "not None and self.module.params[p] not in [{}, [], '']: different", "for the container * bridge create a network stack on", "stopped - started image: description: - Repository path (or image", "before] after = self.params['device_read_bps'] or [] before, after = sorted(list(set(before))),", "self.params['cpu_rt_period']] def addparam_cpu_rt_runtime(self, c): return c + ['--cpu-rt-runtime', self.params['cpu_rt_runtime']] def", "after = self.params['cpu_rt_period'] return self._diff_update_and_compare('cpu_rt_period', before, after) def diffparam_cpu_rt_runtime(self): before", "[self.module.params['executable'], b'container'] + b_command, expand_user_and_vars=False) self.stdout = out self.stderr =", "self.version = podman_version self.default_dict = None self.info = yaml.safe_load(json.dumps(info).lower()) self.params", "diffparam_label(self): before = self.info['config']['labels'] or {} after = before.copy() if", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "before an interval is considered failed. Like start-period, the value", "<filename>tripleo_ansible/ansible_plugins/modules/podman_container.py #!/usr/bin/python # Copyright (c) 2019 OpenStack Foundation # All", "idempotency is supported for integers only. type: str memory_swappiness: description:", "% self.params['privileged']] def addparam_publish(self, c): for pub in self.params['publish']: c", "\"\"\"If image is passed, ensure it exists, if not -", "15, \"Tty\": false, \"User\": { \"gid\": 0, \"uid\": 0 },", "image: redis state: started restart: yes etc_hosts: other: \"127.0.0.1\" restart_policy:", "Set -1 to have unlimited pids for the container. type:", "in the dictionary. Each host name will be added to", "host network stack. * <network-name>|<network-id> connect to a user-defined network", "for a container. type: str healthcheck_interval: description: - Set an", "host system. type: list elements: str aliases: - exposed -", "a network stack on the default bridge * none no", "+= ['--tmpfs', ':'.join(tmpfs)] return c def addparam_tty(self, c): return c", "Ansible 2.8. For compatibility reasons, the facts are also accessible", "maximum time allowed to complete the healthcheck before an interval", "list of 2 items where the first one is #", "annotation: description: - Add an annotation to the container. The", "# Limited idempotency, it can't guess default values def diffparam_env(self):", "name: Writing output podman_container: name: myservice image: busybox log_options: path=/var/log/container/mycontainer.json", "is <device-on-host>[:<device-on-container>][:<permissions>] (e.g. device /dev/sdc:/dev/xvdc:rwm) type: list elements: str device_read_bps:", "now.\"\"\" return self.exists and self.info['State']['Running'] @property def stopped(self): \"\"\"Return True", "not self.container.exists and not self.image: self.module.fail_json(msg='Cannot create container when image'", "type: list elements: str dns_option: description: - Set custom DNS", "``${XDG_RUNTIME_DIR}/containers/auth.json`` (Not available for remote commands) You can also override", "self.default_dict = None self.info = yaml.safe_load(json.dumps(info).lower()) self.params = self.defaultize() self.diff", "type: dict authfile: description: - Path of the authentication file.", "another container's network namespace via 'network container:<name|id>'. The address must", "not in [{}, [], '']: different = True return different", "% self.container.name) self.update_container_result() self.update_container_result(changed=False) elif not self.container.exists: self.container.run() self.results['actions'].append('started %s'", "self._diff_update_and_compare('device_write_iops', before, after) # Limited idempotency, it can't guess default", "default: True debug: description: - Return additional information which can", "str env: description: - Set environment variables. This option allows", "in the /etc/subgid file. type: str subuidname: description: - Run", "def addparam_cgroups(self, c): self.check_version('--cgroups', minv='1.6.0') return c + ['--cgroups=%s' %", "Limit read rate (IO per second) from a device (e.g.", "type: str healthcheck_interval: description: - Set an interval for the", "recreate: description: - Use with present and started states to", "LooseVersion( self.podman_version): self.module.fail_json(msg=\"Parameter %s is supported from podman \" \"version", "in all versions if 'cgroups' in self.info['hostconfig']: before = self.info['hostconfig']['cgroups']", "the container.\"\"\" self._perform_action('start') def create(self): \"\"\"Create the container.\"\"\" self._perform_action('create') def", "default path of the authentication file by setting the ``REGISTRY_AUTH_FILE``", "path of the init process. Cgroups will be created if", "user namespace using the map with 'name' in the /etc/subgid", "container. The format is key value, multiple times. type: dict", "the name and any provided configuration. If no container matches", "in microseconds type: int cpu_rt_period: description: - Limit the CPU", "self._diff_update_and_compare('pid', before, after) def diffparam_rm(self): before = self.info['hostconfig']['autoremove'] after =", "self.restart: self.container.restart() self.results['actions'].append('restarted %s' % self.container.name) self.update_container_result() self.update_container_result(changed=False) elif not", "command options you want to pass to podman command, cmd_args", "Run container in an existing pod. If you want podman", "self.info['hostconfig']['containeridfile'] after = self.params['cidfile'] return self._diff_update_and_compare('cidfile', before, after) def diffparam_command(self):", "\"io.kubernetes.cri-o.TTY\": \"false\" }, \"AttachStderr\": false, \"AttachStdin\": false, \"AttachStdout\": false, \"Cmd\":", "for dev in self.params['device_write_bps']: c += ['--device-write-bps', dev] return c", "<number><unit>. number must be greater than 0. Unit is optional", "\"\"\"Initialize PodmanContainer class. Arguments: module {obj} -- ansible module object", "def addparam_uidmap(self, c): for uidmap in self.params['uidmap']: c += ['--uidmap',", "self.image: self.module.fail_json(msg='Cannot create container when image' ' is not specified!')", "on the file system. The dafault is false. type: bool", "in self.params['device_write_bps']: c += ['--device-write-bps', dev] return c def addparam_device_write_iops(self,", "write rate (bytes per second) to a device (e.g. device-write-bps", "% (k, v) for k, v in sorted( diffs['before'].items())]) +", "@property def running(self): \"\"\"Return True if container is running now.\"\"\"", "the desired action according to map of actions & states.\"\"\"", "+= ['--device', dev] return c def addparam_device_read_bps(self, c): for dev", "remove rootfs: description: - If true, the first argument refers", "dev in self.params['device_write_bps']: c += ['--device-write-bps', dev] return c def", "!= 0: module.fail_json(msg=\"Can't pull image %s\" % image, stdout=out, stderr=err)", "c + ['--init', self.params['init']] def addparam_init_path(self, c): return c +", "podman kill or podman stop commands. Valid values are *", "action): \"\"\"Perform action with container. Arguments: action {str} -- action", "times. type: dict authfile: description: - Path of the authentication", "image: return image_actions rc, out, err = module.run_command([module_exec, 'image', 'exists',", "mount a read-write tmpfs on /run, /tmp, and /var/tmp. The", "def diffparam_cpu_period(self): before = self.info['hostconfig']['cpuperiod'] after = self.params['cpu_period'] return self._diff_update_and_compare('cpu_period',", "c): for dev in self.params['device_read_iops']: c += ['--device-read-iops', dev] return", "return self._diff_update_and_compare('hostname', before, after) def diffparam_image(self): # TODO(sshnaidm): for strict", "self.params['ipc'] return self._diff_update_and_compare('ipc', before, after) def diffparam_label(self): before = self.info['config']['labels']", "\"\", \"ExitCode\": 0, \"FinishedAt\": \"2019-06-17T19:13:10.157518963+03:00\", \"Healthcheck\": { \"FailingStreak\": 0, \"Log\":", "self.action in ['create', 'run']: cmd = [self.action, '--name', self.params['name']] all_param_methods", "self.module.params['executable']) return out.split(\"version\")[1].strip() def _perform_action(self, action): \"\"\"Perform action with container.", "\"\"\"Delete the container.\"\"\" self._perform_action('delete') def stop(self): \"\"\"Stop the container.\"\"\" self._perform_action('stop')", "addparam_detach_keys(self, c): return c + ['--detach-keys', self.params['detach_keys']] def addparam_device(self, c):", "\"kernelmemory\": \"0\", \"log_driver\": \"k8s-file\", \"memory\": \"0\", \"memory_swap\": \"0\", \"memory_reservation\": \"0\",", "type: str choices: - k8s-file - journald - json-file log_opt:", "params_with_defaults def _diff_update_and_compare(self, param_name, before, after): if before != after:", "{}, 'podman_actions': self.container.actions}) self.module.exit_json(**self.results) def execute(self): \"\"\"Execute the desired action", "set the log driver for the container. For example log_driver", "actions if desired state is 'absent'.\"\"\" if not self.container.exists: self.results.update({'changed':", "podman host network stack. * <network-name>|<network-id> connect to a user-defined", "= self.info['config']['user'] if self.module.params['user'] is None and before: after =", "If no container matches the name, a container will be", "(/). type: str \"\"\" EXAMPLES = \"\"\" - name: Run", "\"AttachStdout\": false, \"Cmd\": [ \"sh\" ], \"Domainname\": \"\", \"Entrypoint\": \"\",", "before = self.info['hostconfig']['cgroupparent'] after = self.params['cgroup_parent'] return self._diff_update_and_compare('cgroup_parent', before, after)", "Format is a single character or ctrl-value type: str device:", "- Write the pid of the conmon process to a", "type: str healthcheck_timeout: description: - The maximum time allowed to", "not bool(self.module._diff) different = False for func_name in diff_func_list: dff_func", "for blkio in self.params['blkio_weight_device'].items(): c += ['--blkio-weight-device', ':'.join(blkio)] return c", "self.module.params: if self.module.params[p] is None and p in self.default_dict: params_with_defaults[p]", "container's root filesystem as read only. Default is false type:", "format DEVICE_NAME[:]WEIGHT). type: dict cap_add: description: - List of capabilities", "or \"version\" not in out: self.module.fail_json(msg=\"%s run failed!\" % self.module.params['executable'])", "Whether to compare images in idempotency by taking into account", "['--device-write-iops', dev] return c def addparam_dns(self, c): return c +", "self.action == 'delete': cmd = ['rm', '-f', self.params['name']] return [to_bytes(i,", "private IPC namespace (POSIX SysV IPC) for the container type:", "self._diff_update_and_compare('memory_swap', before, after) def diffparam_memory_reservation(self): before = str(self.info['hostconfig']['memoryreservation']) after =", "on input vars if module.params['state'] in ['started', 'present'] and \\", "\"\", \"volume\": [], \"workdir\": \"/\", } def default_dict(self): # make", "pod. If you want podman to make the pod for", "default: False restart_policy: description: - Restart policy to follow when", "= self.params['cpu_rt_period'] return self._diff_update_and_compare('cpu_rt_period', before, after) def diffparam_cpu_rt_runtime(self): before =", "command of container. Can be a string or a list.", "means no limit. type: str cpuset_cpus: description: - CPUs in", "type: dict label_file: description: - Read in a line delimited", "'etc_hosts'], ), supports_check_mode=True, ) # work on input vars if", "\"Dead\": false, \"Error\": \"\", \"ExitCode\": 0, \"FinishedAt\": \"2019-06-17T19:13:10.157518963+03:00\", \"Healthcheck\": {", "alter a healthcheck command for a container. type: str healthcheck_interval:", "period you specify. type: int cpu_rt_runtime: description: - Limit the", "in a line delimited file of labels type: str log_driver:", "c): return c + ['--entrypoint', self.params['entrypoint']] def addparam_env(self, c): for", "does not match, the container will be updated, if it", "container. bind or tmpfs For example mount \"type=bind,source=/path/on/host,destination=/path/in/container\" type: str", "optional and can be b (bytes), k (kilobytes), m(megabytes), or", "True else: different = True # Check non idempotent parameters", "device-write-bps /dev/sda:1mb) type: list device_write_iops: description: - Limit write rate", "or [] before, after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('device_write_bps', before,", "the specified container(s). type: list elements: str workdir: description: -", "description: - Set the PID mode for the container type:", "In a idempotency 'lite mode' assume all images from different", "separate process than Podman, so this is necessary when using", "value is 3. type: int healthcheck_start_period: description: - The initialization", "byte strings for Popen command \"\"\" if self.action in ['start',", "are the same before = before.replace(\":latest\", \"\") after = after.replace(\":latest\",", "unit = b, k, m or g) Note - idempotency", "automatic timer setup) (default \"30s\") type: str healthcheck_retries: description: -", "module, podman_version): self.module = module self.version = podman_version self.defaults =", "only! Current version is %s\" % ( param, minv, self.podman_version))", "['--dns-option', self.params['dns_option']] def addparam_dns_search(self, c): return c + ['--dns-search', self.params['dns_search']]", "container to not create CGroups, and thus conflicts with CGroup", "I(present) - Asserts the existence of a container matching the", "container. Default is 10. type: int subgidname: description: - Run", "self.container.name) self.update_container_result() if self.container.stopped: self.update_container_result(changed=False) elif self.container.running: self.container.stop() self.results['actions'].append('stopped %s'", "addparam_mount(self, c): return c + ['--mount', self.params['mount']] def addparam_network(self, c):", "other: \"127.0.0.1\" restart_policy: \"no\" device: \"/dev/sda:/dev/xvda:rwm\" ports: - \"8080:9000\" -", "for i in self.params['device']] before, after = sorted(list(set(before))), sorted(list(set(after))) return", "(relative weight) accepts a weight value between 10 and 1000", "['stop', 'start']: cmd = [self.action, self.params['name']] return [to_bytes(i, errors='surrogate_or_strict') for", "a stopped state. type: str default: started choices: - absent", "= self.params['image'] mode = self.params['image_strict'] if mode is None or", "return c + ['--cgroups=%s' % self.params['cgroups']] def addparam_cgroupns(self, c): self.check_version('--cgroupns',", "self._get_podman_version() self.diff = {} self.actions = [] @property def exists(self):", "on the machine running C(podman) default: 'podman' type: str state:", "ansible.module_utils.basic import AnsibleModule from ansible.module_utils._text import to_bytes, to_native ANSIBLE_METADATA =", "only defined in container config if a healthcheck # was", "annotation to the container. The format is key value, multiple", "after) def diffparam_cap_drop(self): before = self.info['effectivecaps'] or [] after =", "self.params['device']] before, after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('devices', before, after)", "host-to-IP mappings, where each host name is a key in", "process. SIGCHLD, SIGSTOP, and SIGKILL are not proxied. The default", "addparam_authfile(self, c): return c + ['--authfile', self.params['authfile']] def addparam_blkio_weight(self, c):", "}) return self._diff_update_and_compare('label', before, after) def diffparam_log_driver(self): before = self.info['hostconfig']['logconfig']['type']", "was done \"\"\" image_actions = [] module_exec = module.params['executable'] if", "can be. If it cannot be updated, it will be", "\"false\" }, \"AttachStderr\": false, \"AttachStdin\": false, \"AttachStdout\": false, \"Cmd\": [", "k (kilobytes), m(megabytes), or g (gigabytes). If you omit the", "c def addparam_device_read_bps(self, c): for dev in self.params['device_read_bps']: c +=", "of retries allowed before a healthcheck is considered to be", "c): return c + ['--user', self.params['user']] def addparam_userns(self, c): return", "str subuidname: description: - Run the container in a new", "default bridge * none no networking * container:<name|id> reuse another", "c): return c + ['--blkio-weight', self.params['blkio_weight']] def addparam_blkio_weight_device(self, c): for", "!= 0 and self.params['memory'].isdigit()): after = str(int(self.params['memory']) * 2) return", "= self.params['device_write_bps'] or [] before, after = sorted(list(set(before))), sorted(list(set(after))) return", "1d\" - name: Stop a container podman_container: name: mycontainer state:", "container. Default is SIGTERM. type: int stop_timeout: description: - Timeout", "if m['type'] == 'volume': volumes.append([m['name'], m['destination']]) else: volumes.append([m['source'], m['destination']]) before", "podman_container author: - \"<NAME> (@sshnaidm)\" version_added: '2.9' short_description: Manage podman", "C(latest) will be used. - Can also be an image", "express or implied. See the # License for the specific", "means user namespaces are disabled. type: str uts: description: -", "using the supplied mapping. type: list ulimit: description: - Ulimit", "--read-only mode, then mount a read-write tmpfs on /run, /tmp,", "return c def addparam_user(self, c): return c + ['--user', self.params['user']]", "division, print_function __metaclass__ = type import json from distutils.version import", "cidfile: description: - Write the container ID to the file", "null, \"Status\": \"\" }, \"OOMKilled\": false, \"OciVersion\": \"1.0.1-dev\", \"Paused\": false,", "not self.container.exists: self.container.run() self.results['actions'].append('started %s' % self.container.name) self.update_container_result() elif self.container.stopped", "+ ['--ip', self.params['ip']] def addparam_ipc(self, c): return c + ['--ipc',", "re-creation of an existing container. type: bool default: False restart_policy:", "addparam_memory(self, c): return c + ['--memory', self.params['memory']] def addparam_memory_reservation(self, c):", "- Use with present and started states to force the", "return c + ['--cidfile', self.params['cidfile']] def addparam_conmon_pidfile(self, c): return c", "from a device (e.g. device-read-iops /dev/sda:1000) type: list device_write_bps: description:", "self.params['stop_timeout']] def addparam_subgidname(self, c): return c + ['--subgidname', self.params['subgidname']] def", "self.params['env_host']] def addparam_etc_hosts(self, c): for host_ip in self.params['etc_hosts'].items(): c +=", "all exposed ports to random ports on the host interfaces.", "they exit with a non-0 exit code, retrying indefinitely or", "to make the pod for you, preference the pod name", "c + ['--systemd=%s' % self.params['systemd']] def addparam_tmpfs(self, c): for tmpfs", "a static IP address for the container, for example '10.88.64.128'.", "yaml from ansible.module_utils.basic import AnsibleModule from ansible.module_utils._text import to_bytes, to_native", "the container is running moves it to a stopped state.", "after) def diffparam_env_host(self): # It's impossible to get from inspest,", "This can be disabled by setting the http_proxy option to", "Cgroups output is not supported in all versions if 'cgroups'", "has partial idempotency only. def diffparam_hostname(self): before = self.info['config']['hostname'] after", "self._diff_update_and_compare('stop_signal', before, after) def diffparam_tty(self): before = self.info['config']['tty'] after =", "def make_stopped(self): \"\"\"Run actions if desired state is 'stopped'.\"\"\" if", "The address must be within the default CNI network's pool", "in self.params['expose']: c += ['--expose', exp] return c def addparam_gidmap(self,", "= sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('device_write_iops', before, after) # Limited idempotency,", "in a separate process than Podman, so this is necessary", "%s' % self.container.name) self.update_container_result() self.update_container_result(changed=False) elif not self.container.exists: self.container.run() self.results['actions'].append('started", "print_function __metaclass__ = type import json from distutils.version import LooseVersion", "self.params['healthcheck_interval']] def addparam_healthcheck_retries(self, c): return c + ['--healthcheck-retries', self.params['healthcheck_retries']] def", "present podman_container: name: mycontainer state: present image: ubuntu:14.04 command: \"sleep", "return c def addparam_label_file(self, c): return c + ['--label-file', self.params['label_file']]", "for the healthchecks (a value of disable results in no", "c): for annotate in self.params['annotation'].items(): c += ['--annotation', '='.join(annotate)] return", "0, \"cgroups\": \"default\", \"cgroup_parent\": \"\", \"cidfile\": \"\", \"cpus\": 0.0, \"cpu_shares\":", "idempotency, unable to guess the default log_path def diffparam_log_opt(self): before", "Limit the CPU real-time period in microseconds. Limit the container's", "you want podman to make the pod for you, preference", "addparam_systemd(self, c): return c + ['--systemd=%s' % self.params['systemd']] def addparam_tmpfs(self,", "runtime type: dict systemd: description: - Run container in systemd", "image): \"\"\"If image is passed, ensure it exists, if not", "-- action type from 'run', 'stop', 'create', 'delete', 'start' params", "name, a container will be created and started. Use recreate", "in self.params['annotation'].items(): c += ['--annotation', '='.join(annotate)] return c def addparam_authfile(self,", "changed {bool} -- whether any action was performed (default: {True})", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "it will be removed and re-created with the requested config.", "before, after) def diffparam_tty(self): before = self.info['config']['tty'] after = self.params['tty']", "override the default path of the authentication file by setting", "create the container. If an image is not found, the", "pulled from the registry. If no tag is included, C(latest)", "diffs['after']: self.diff['before'] = \"\\n\".join( [\"%s - %s\" % (k, v)", "\"stop_signal\": 15, \"tty\": False, \"user\": \"\", \"uts\": \"\", \"volume\": [],", "or range of ports, to the host. Format - ip:hostPort:containerPort", "an init inside the container that forwards signals and reaps", "def addparam_entrypoint(self, c): return c + ['--entrypoint', self.params['entrypoint']] def addparam_env(self,", "c + ['--entrypoint', self.params['entrypoint']] def addparam_env(self, c): for env_value in", "PodmanContainerDiff: def __init__(self, module, info, podman_version): self.module = module self.version", "None: after.update(self.params['annotation']) return self._diff_update_and_compare('annotation', before, after) def diffparam_env_host(self): # It's", "path command: description: - Override command of container. Can be", "self.params['stop_signal'] return self._diff_update_and_compare('stop_signal', before, after) def diffparam_tty(self): before = self.info['config']['tty']", "% (i['path'], i['rate']) for i in before] after = self.params['device_write_bps']", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "\"rm\": False, \"security_opt\": [], \"stop_signal\": 15, \"tty\": False, \"user\": \"\",", "and LooseVersion(minv) > LooseVersion( self.podman_version): self.module.fail_json(msg=\"Parameter %s is supported from", "type: str executable: description: - Path to C(podman) executable if", "the healthchecks (a value of disable results in no automatic", "module self.name = name self.stdout, self.stderr = '', '' self.info", "in cmd] if self.action == 'delete': cmd = ['rm', '-f',", "idempotency only. def diffparam_hostname(self): before = self.info['config']['hostname'] after = self.params['hostname']", "self.update_container_result() if self.container.stopped: self.update_container_result(changed=False) elif self.container.running: self.container.stop() self.results['actions'].append('stopped %s' %", "description: - Start, stop, restart and manage Podman containers requirements:", "\"\"\"Create a podman command from given module parameters. Returns: list", "container. type: list elements: str cgroup_parent: description: - Path to", "\"\"\"Run actions if desired state is 'stopped'.\"\"\" if not self.container.exists", "description: - If container is running in --read-only mode, then", "def diffparam_memory_reservation(self): before = str(self.info['hostconfig']['memoryreservation']) after = self.params['memory_reservation'] return self._diff_update_and_compare('memory_reservation',", "['--subgidname', self.params['subgidname']] def addparam_subuidname(self, c): return c + ['--subuidname', self.params['subuidname']]", "dns_option: description: - Set custom DNS options type: str dns_search:", "param, minv=None, maxv=None): if minv and LooseVersion(minv) > LooseVersion( self.podman_version):", "elements: str cgroup_parent: description: - Path to cgroups under which", "and /var/tmp. The default is true type: bool recreate: description:", "func_name) if dff_func(): if fail_fast: return True else: different =", "exit * on-failure[:max_retries] - Restart containers when they exit with", "in the C($PATH) on the machine running C(podman) default: 'podman'", "before, after) def diffparam_volumes_from(self): before = self.info['hostconfig']['volumesfrom'] or [] after", "network stack. * <network-name>|<network-id> connect to a user-defined network *", "name: description: - Name of the container required: True type:", "return c + ['--subuidname', self.params['subuidname']] def addparam_sysctl(self, c): for sysctl", "i in before] after = self.params['device_read_bps'] or [] before, after", "amount of time in a given CPU period Real Time", "return self.start_stop_delete() if self.action in ['create', 'run']: cmd = [self.action,", "def __init__(self, module): \"\"\"Initialize PodmanManager class. Arguments: module {obj} --", "v) for k, v in sorted( diffs['before'].items())]) + \"\\n\" self.diff['after']", "c): for sysctl in self.params['sysctl'].items(): c += ['--sysctl', b\"=\".join([to_bytes(k, errors='surrogate_or_strict')", "to be stopped and restarted. - I(stopped) - Asserts that", "image ID. If this is the case, the image is", "self.module.params['user'] is None and before: after = before else: after", "C($PATH) on the machine running C(podman) default: 'podman' type: str", "c += ['--cap-add', cap_add] return c def addparam_cap_drop(self, c): for", "The default value is 0s type: str healthcheck_timeout: description: -", "return c + ['--conmon-pidfile', self.params['conmon_pidfile']] def addparam_cpu_period(self, c): return c", "or ctrl-value type: str device: description: - Add a host", "Returns: list -- list of byte strings for Popen command", "period in microseconds. Limit the container's Real Time CPU usage.", "\"\", \"Args\": [ \"sh\" ], \"BoundingCaps\": [ \"CAP_CHOWN\", ... ],", "is None: after = [] else: after = self.params['blkio_weight_device'] return", "c + ['--cidfile', self.params['cidfile']] def addparam_conmon_pidfile(self, c): return c +", "be updated, it will be removed and re-created with the", "current host environment variables in container. Defaults to false. type:", "also override the default path of the authentication file by", "after) def diffparam_stop_signal(self): before = self.info['config']['stopsignal'] after = self.params['stop_signal'] return", "aliases: - add_hosts expose: description: - Expose a port, or", "label in self.params['label'].items(): c += ['--label', b'='.join([to_bytes(l, errors='surrogate_or_strict') for l", "before, after): if before != after: self.diff['before'].update({param_name: before}) self.diff['after'].update({param_name: after})", "static IP address for the container, for example '10.88.64.128'. Can", "search domain) type: str entrypoint: description: - Overwrite the default", "not proxied. The default is true. type: bool stop_signal: description:", "mode for the container type: str volume: description: - Create", "system. type: list elements: str aliases: - exposed - exposed_ports", "default is false. type: bool uidmap: description: - Run the", "= sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('volume', before, after) def diffparam_volumes_from(self): before", "from a device (e.g. device-read-bps /dev/sda:1mb) type: list device_read_iops: description:", "system uses 64m type: str sig_proxy: description: - Proxy signals", "self.info['hostconfig']['cpushares'] after = self.params['cpu_shares'] return self._diff_update_and_compare('cpu_shares', before, after) def diffparam_cpus(self):", "Start 4 load-balanced containers podman_container: name: \"container{{ item }}\" recreate:", "\"Image\": \"...\", \"ImageName\": \"docker.io/library/busybox:latest\", \"IsInfra\": false, \"LogPath\": \"/tmp/container/mycontainer.json\", \"MountLabel\": \"system_u:object_r:container_file_t:s0:c282,c782\",", "c): for uidmap in self.params['uidmap']: c += ['--uidmap', uidmap] return", "sorted(list(set(after))) return self._diff_update_and_compare('device_write_bps', before, after) def diffparam_device_write_iops(self): before = self.info['hostconfig']['blkiodevicewriteiops']", "sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('device_write_iops', before, after) # Limited idempotency, it", "description: - Run container in systemd mode. The default is", "= self.module.params['name'] self.executable = \\ self.module.get_bin_path(self.module.params['executable'], required=True) self.image = self.module.params['image']", "is supported for integers only. type: str memory_swap: description: -", "different = False for func_name in diff_func_list: dff_func = getattr(self,", "self.params['label_file']] def addparam_log_driver(self, c): return c + ['--log-driver', self.params['log_driver']] def", "\"OciVersion\": \"1.0.1-dev\", \"Paused\": false, \"Pid\": 4083, \"Restarting\": false, \"Running\": false,", "= self.params['cpus'] return self._diff_update_and_compare('cpus', before, after) def diffparam_cpuset_cpus(self): before =", "diffparam_memory_swap(self): # By default it's twice memory parameter before =", "func)) and func.startswith( \"diffparam\")] fail_fast = not bool(self.module._diff) different =", "env_before} after = before.copy() if self.params['env']: after.update({ str(k).lower(): str(v).lower() for", "addparam_restart_policy(self, c): return c + ['--restart=%s' % self.params['restart_policy']] def addparam_rm(self,", "def diffparam_env(self): env_before = self.info['config']['env'] or {} before = {i.split(\"=\")[0]:", "UID used and optionally the groupname or GID for the", "- net no_hosts: description: - Do not create /etc/hosts for", "description: - Kernel memory limit (format <number>[<unit>], where unit =", "in sysctl])] return c def addparam_systemd(self, c): return c +", "after) def diffparam_command(self): # TODO(sshnaidm): to inspect image to get", "return self._diff_update_and_compare('memory', before, after) def diffparam_memory_swap(self): # By default it's", "to create a private IPC namespace (POSIX SysV IPC) for", "create container when image' ' is not specified!') if not", "before.copy() if self.params['label']: after.update({ str(k).lower(): str(v).lower() for k, v in", "- ip:hostPort:containerPort | ip::containerPort | hostPort:containerPort | containerPort type: list", "self._diff_update_and_compare('cpu_period', before, after) def diffparam_cpu_rt_period(self): before = self.info['hostconfig']['cpurealtimeperiod'] after =", "necessary when using systemd to restart Podman containers. type: path", "log_options memory: description: - Memory limit (format 10k, where unit", "max_retries count is hit * always - Restart containers when", "before = self.info['hostconfig']['containeridfile'] after = self.params['cidfile'] return self._diff_update_and_compare('cidfile', before, after)", "addparam_etc_hosts(self, c): for host_ip in self.params['etc_hosts'].items(): c += ['--add-host', ':'.join(host_ip)]", "self.info['hostconfig']['cpurealtimeruntime'] after = self.params['cpu_rt_runtime'] return self._diff_update_and_compare('cpu_rt_runtime', before, after) def diffparam_cpu_shares(self):", "before = self.info['hostconfig']['volumesfrom'] or [] after = self.params['volumes_from'] or []", "to memory plus swap. Must be used with the -m", "Default is false. type: bool oom_kill_disable: description: - Whether to", "podman_container: name: \"container{{ item }}\" recreate: yes image: someuser/anotherappimage command:", "published - published_ports publish_all: description: - Publish all exposed ports", "def addparam_oom_score_adj(self, c): return c + ['--oom-score-adj', self.params['oom_score_adj']] def addparam_pid(self,", "addparam_privileged(self, c): return c + ['--privileged=%s' % self.params['privileged']] def addparam_publish(self,", "host environment variables in container. Defaults to false. type: bool", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "IP address for the container, for example '10.88.64.128'. Can only", "container type: str pids_limit: description: - Tune the container's pids", "(IO per second) from a device (e.g. device-read-iops /dev/sda:1000) type:", "from the registry. If no tag is included, C(latest) will", "errors='surrogate_or_strict') for l in label])] return c def addparam_label_file(self, c):", "int cpu_rt_period: description: - Limit the CPU real-time period in", "+ ['--read-only-tmpfs=%s' % self.params['read_only_tmpfs']] def addparam_restart_policy(self, c): return c +", "be created and started. Use recreate to always re-create a", "self.module, ).construct_command_from_params() full_cmd = \" \".join([self.module.params['executable']] + [to_native(i) for i", "to /CONTAINER-DIR in the podman container. type: list elements: str", "str(self.info['hostconfig']['memoryreservation']) after = self.params['memory_reservation'] return self._diff_update_and_compare('memory_reservation', before, after) def diffparam_network(self):", "reasons, the facts are also accessible directly as C(podman_container). Note", "soft limit (format 100m, where unit = b, k, m", "happened, \" \"please contact maintainers ASAP!\") def main(): module =", "c + ['--network', \",\".join(self.params['network'])] def addparam_no_hosts(self, c): return c +", "file of labels type: str log_driver: description: - Logging driver.", "is false. type: bool aliases: - remove rootfs: description: -", "Valid values are * no - Do not restart containers", "none no networking * container:<name|id> reuse another container's network stack", "m(megabytes), or g (gigabytes). If you omit the unit, the", "restart: yes etc_hosts: other: \"127.0.0.1\" restart_policy: \"no\" device: \"/dev/sda:/dev/xvda:rwm\" ports:", "type: str healthcheck_retries: description: - The number of retries allowed", "self.params['cgroups']] def addparam_cgroupns(self, c): self.check_version('--cgroupns', minv='1.6.2') return c + ['--cgroupns=%s'", "self.module.params['log_opt'] in [None, '']: after = before else: after =", "diffparam_tty(self): before = self.info['config']['tty'] after = self.params['tty'] return self._diff_update_and_compare('tty', before,", "addparam_cpu_shares(self, c): return c + ['--cpu-shares', self.params['cpu_shares']] def addparam_cpus(self, c):", "env: SECRET_KEY: \"ssssh\" BOOLEAN_KEY: \"yes\" - name: Container present podman_container:", "c += ['--device-write-bps', dev] return c def addparam_device_write_iops(self, c): for", "= [func for func in dir(self) if callable(getattr(self, func)) and", "container in detach mode type: bool default: True debug: description:", "is not None) for param in params_set: func_name = \"_\".join([\"addparam\",", "['--healthcheck-start-period', self.params['healthcheck_start_period']] def addparam_healthcheck_timeout(self, c): return c + ['--healthcheck-timeout', self.params['healthcheck_timeout']]", "shm_size: description: - Size of /dev/shm. The format is <number><unit>.", "- restart gidmap: description: - Run the container in a", "SHAs before = self.info['config']['image'] after = self.params['image'] mode = self.params['image_strict']", "for the specific language governing permissions and limitations # under", "return c + ['--entrypoint', self.params['entrypoint']] def addparam_env(self, c): for env_value", "type: dict systemd: description: - Run container in systemd mode.", "['--cpu-period', self.params['cpu_period']] def addparam_cpu_rt_period(self, c): return c + ['--cpu-rt-period', self.params['cpu_rt_period']]", "slirp4netns use slirp4netns to create a user network stack. This", "which the default being enabled. The disabled option will force", "user namespace using the supplied mapping. type: str group_add: description:", "of ports (e.g. expose \"3300-3310\") to set up port redirection", "i in self.params if self.params[i] is not None) for param", "{} self.actions = [] @property def exists(self): \"\"\"Check if container", "+= ['--volume', vol] return c def addparam_volumes_from(self, c): for vol", "}) return self._diff_update_and_compare('env', before, after) def diffparam_etc_hosts(self): if self.info['hostconfig']['extrahosts']: before", "self.default_dict[p] else: params_with_defaults[p] = self.module.params[p] return params_with_defaults def _diff_update_and_compare(self, param_name,", "c def addparam_label_file(self, c): return c + ['--label-file', self.params['label_file']] def", "self.podman_version): self.module.fail_json(msg=\"Parameter %s is supported till podman \" \"version %s", "\"/\", } def default_dict(self): # make here any changes to", "str group_add: description: - Add additional groups to run as", "before, after) def diffparam_memory_swap(self): # By default it's twice memory", "a host device to the container. The format is <device-on-host>[:<device-on-container>][:<permissions>]", "a container's memory swappiness behavior. Accepts an integer between 0", "if a container is stopped via the podman kill or", "kill or podman stop commands. Valid values are * no", "['--dns', ','.join(self.params['dns'])] def addparam_dns_option(self, c): return c + ['--dns-option', self.params['dns_option']]", "else self.container.info out, err = self.container.stdout, self.container.stderr self.results.update({'changed': changed, 'container':", "json-file log_opt: description: - Logging driver specific options. Used to", "addparam_read_only(self, c): return c + ['--read-only=%s' % self.params['read_only']] def addparam_read_only_tmpfs(self,", "a single character or ctrl-value type: str device: description: -", "to be available locally. type: str annotation: description: - Add", "c + ['--gidmap', self.params['gidmap']] def addparam_group_add(self, c): for g in", "b'='.join([to_bytes(l, errors='surrogate_or_strict') for l in label])] return c def addparam_label_file(self,", "c): return c + ['--pod', self.params['pod']] def addparam_privileged(self, c): return", "int blkio_weight_device: description: - Block IO weight (relative device weight,", "healthcheck: description: - Set or alter a healthcheck command for", "privileged: description: - Give extended privileges to this container. The", "the cgroup for the container will be created. If the", "= self.info['hostconfig']['privileged'] after = self.params['privileged'] return self._diff_update_and_compare('privileged', before, after) def", "'']: different = True return different def ensure_image_exists(module, image): \"\"\"If", "self.container.stopped and not self.container.different: self.container.start() self.results['actions'].append('started %s' % self.container.name) self.update_container_result()", "setup) (default \"30s\") type: str healthcheck_retries: description: - The number", "username or UID used and optionally the groupname or GID", "self.module = module self.results = { 'changed': False, 'actions': [],", "be helpful for investigations. type: bool default: False detach_keys: description:", "after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('cap_drop', before, after) def diffparam_cgroup_parent(self):", "after = self.params['volumes_from'] or [] return self._diff_update_and_compare('volumes_from', before, after) def", "container required: True type: str executable: description: - Path to", "default values def diffparam_env(self): env_before = self.info['config']['env'] or {} before", "the container or not. Default is false. type: bool oom_score_adj:", "\"cpus\": 0.0, \"cpu_shares\": 0, \"cpu_quota\": 0, \"cpu_period\": 0, \"cpu_rt_runtime\": 0,", "in self.params['device']] before, after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('devices', before,", "specified name will be stopped and removed. - I(present) -", "indefinitely or until the optional max_retries count is hit *", "issue with networks in inspection \"network\": [\"default\"], \"oom_score_adj\": 0, \"pid\":", "False, \"user\": \"\", \"uts\": \"\", \"volume\": [], \"workdir\": \"/\", }", "return c def addparam_cap_add(self, c): for cap_add in self.params['cap_add']: c", "exists.\"\"\" return bool(self.info != {}) @property def different(self): \"\"\"Check if", "for p in self.module.params: if self.module.params[p] is None and p", "description: - Timeout (in seconds) to stop a container. Default", "c): return c + ['--subgidname', self.params['subgidname']] def addparam_subuidname(self, c): return", "self.info['hostconfig']['groupadd'] after = self.params['group_add'] return self._diff_update_and_compare('group_add', before, after) # Healthcheck", "self.params['image'] mode = self.params['image_strict'] if mode is None or not", "- Security Options. For example security_opt \"seccomp=unconfined\" type: list elements:", "tmpfs on /run, /tmp, and /var/tmp. The default is true", "full_cmd = \" \".join([self.module.params['executable']] + [to_native(i) for i in b_command])", "* bridge create a network stack on the default bridge", "c def addparam_device_read_iops(self, c): for dev in self.params['device_read_iops']: c +=", "self.results.update({'changed': changed, 'container': facts, 'podman_actions': self.container.actions}, stdout=out, stderr=err) if self.container.diff:", "# the \"test\" key is a list of 2 items", "\"GraphDriver\": { ... }, \"HostConfig\": { ... }, \"HostnamePath\": \"...\",", "container, even if it is running. Use force_restart to force", "a container matching the name and any provided configuration parameters.", "of label names and values type: dict label_file: description: -", "in self.params['env'].items() }) return self._diff_update_and_compare('env', before, after) def diffparam_etc_hosts(self): if", "= {'before': {}, 'after': {}} self.non_idempotent = { 'env_file', 'env_host',", "- Run the container in a new user namespace using", "None or not mode: # In a idempotency 'lite mode'", "LIMIT should always be larger than -m (--memory) value. By", "c): return c + ['--cpuset-cpus', self.params['cpuset_cpus']] def addparam_cpuset_mems(self, c): return", "(the \"License\"); you may # not use this file except", "self.params['oom_score_adj']] def addparam_pid(self, c): return c + ['--pid', self.params['pid']] def", "def diffparam_group_add(self): before = self.info['hostconfig']['groupadd'] after = self.params['group_add'] return self._diff_update_and_compare('group_add',", "rc, out, err = module.run_command([module_exec, 'image', 'exists', image]) if rc", "capabilities to add to the container. type: list elements: str", "Set or alter a healthcheck command for a container. type:", "compare images in idempotency by taking into account a full", "return c def addparam_healthcheck(self, c): return c + ['--healthcheck-command', self.params['healthcheck']]", "\"FailingStreak\": 0, \"Log\": null, \"Status\": \"\" }, \"OOMKilled\": false, \"OciVersion\":", "values are enabled and disabled, which the default being enabled.", "diffparam_cpu_rt_runtime(self): before = self.info['hostconfig']['cpurealtimeruntime'] after = self.params['cpu_rt_runtime'] return self._diff_update_and_compare('cpu_rt_runtime', before,", "arbitrary environment variables that are available for the process that", "diffparam_cgroup_parent(self): before = self.info['hostconfig']['cgroupparent'] after = self.params['cgroup_parent'] return self._diff_update_and_compare('cgroup_parent', before,", "type: bool read_only: description: - Mount the container's root filesystem", "after = self.params['memory_swap'] if (self.module.params['memory_swap'] is None and self.params['memory'] !=", "self.module = module self.name = name self.stdout, self.stderr = '',", "return self._diff_update_and_compare('cpus', before, after) def diffparam_cpuset_cpus(self): before = self.info['hostconfig']['cpusetcpus'] after", "- Set an interval for the healthchecks (a value of", "not in the C($PATH) on the machine running C(podman) default:", "delimited file of environment variables type: path env_host: description: -", "the image will be pulled from the registry. If no", "'1.0', 'status': ['preview'], 'supported_by': 'community' } DOCUMENTATION = \"\"\" module:", "(IO per second) to a device (e.g. device-write-iops /dev/sda:1000) type:", "self.results['actions'].append('restarted %s' % self.container.name) self.update_container_result() self.update_container_result(changed=False) elif not self.container.exists: self.container.run()", "self.params['oom_score_adj'] return self._diff_update_and_compare('oom_score_adj', before, after) def diffparam_privileged(self): before = self.info['hostconfig']['privileged']", "{bool} -- whether any action was performed (default: {True}) \"\"\"", "device_write_iops: description: - Limit write rate (IO per second) to", "- exposed - exposed_ports force_restart: description: - Force restart of", "default being enabled. The disabled option will force the container", "container matches the name, a container will be created. If", "elif self.container.stopped and self.container.different: self.container.recreate() self.results['actions'].append('recreated %s' % self.container.name) self.update_container_result()", "return c + ['--dns-search', self.params['dns_search']] def addparam_entrypoint(self, c): return c", "-m (--memory) value. By default, the swap LIMIT will be", "the ``REGISTRY_AUTH_FILE`` environment variable. ``export REGISTRY_AUTH_FILE=path`` type: path blkio_weight: description:", "of the config. def diffparam_healthcheck(self): if 'healthcheck' in self.info['config']: #", "if desired state is 'started'.\"\"\" if self.container.running and \\ (self.container.different", "Ignore volumes option for idempotency after = [\":\".join(v.split(\":\")[:2]) for v", "description: - Add a host device to the container. The", "bridge * none no networking * container:<name|id> reuse another container's", "map of actions & states.\"\"\" states_map = { 'present': self.make_started,", "c): for label in self.params['label'].items(): c += ['--label', b'='.join([to_bytes(l, errors='surrogate_or_strict')", "\"30s\") type: str healthcheck_retries: description: - The number of retries", "return c + ['--cgroupns=%s' % self.params['cgroupns']] def addparam_cgroup_parent(self, c): return", "of hostname is random generated, this parameter has partial idempotency", "+ ['--image-volume', self.params['image_volume']] def addparam_init(self, c): return c + ['--init',", "container log file. For example log_opt \"path=/var/log/container/mycontainer.json\" type: str aliases:", "\"0\", \"memory_swap\": \"0\", \"memory_reservation\": \"0\", # \"memory_swappiness\": -1, \"no_hosts\": False,", "self.info['hostconfig']: before = self.info['hostconfig']['cgroups'] after = self.params['cgroups'] return self._diff_update_and_compare('cgroups', before,", "ohno state: absent - name: Writing output podman_container: name: myservice", "is the default for rootless containers type: list elements: str", "':'.join(host_ip)] return c def addparam_expose(self, c): for exp in self.params['expose']:", "set. type: list elements: str conmon_pidfile: description: - Write the", "after = self.params['stop_signal'] return self._diff_update_and_compare('stop_signal', before, after) def diffparam_tty(self): before", "def addparam_stop_signal(self, c): return c + ['--stop-signal', self.params['stop_signal']] def addparam_stop_timeout(self,", "container podman_container: name: myredis image: redis command: redis-server --appendonly yes", "module {obj} -- ansible module object \"\"\" super(PodmanManager, self).__init__() self.module", "vars if module.params['state'] in ['started', 'present'] and \\ not module.params['image']:", "+ ['--uts', self.params['uts']] def addparam_volume(self, c): for vol in self.params['volume']:", "healthcheck_timeout: description: - The maximum time allowed to complete the", "will be created and started. Use recreate to always re-create", "aware module doesn't support idempotency if this is set. type:", "present recreate: yes expose: - 6379 volumes_from: - mydata -", "diffparam_cpuset_mems(self): before = self.info['hostconfig']['cpusetmems'] after = self.params['cpuset_mems'] return self._diff_update_and_compare('cpuset_mems', before,", "self.results['actions'].append('stopped %s' % self.container.name) self.update_container_result() def make_absent(self): \"\"\"Run actions if", "type: str sig_proxy: description: - Proxy signals sent to the", "dict label_file: description: - Read in a line delimited file", "type: path cgroupns: description: - Path to cgroups under which", "description: - Set custom DNS options type: str dns_search: description:", "getattr(self, func_name)(cmd) cmd.append(self.params['image']) if self.params['command']: if isinstance(self.params['command'], list): cmd +=", "str label: description: - Add metadata to a container, pass", "of the authentication file. Default is ``${XDG_RUNTIME_DIR}/containers/auth.json`` (Not available for", "PodmanContainer(self.module, self.name) def update_container_result(self, changed=True): \"\"\"Inspect the current container, update", "self.exists and self.info['State']['Running'] @property def stopped(self): \"\"\"Return True if container", "The default is false. When set to true, keep stdin", "Sets the username or UID used and optionally the groupname", "%s' % self.container.name) self.update_container_result() def make_absent(self): \"\"\"Run actions if desired", "- start, create, stop, run, delete \"\"\" b_command = PodmanModuleParams(action,", "addparam_publish(self, c): for pub in self.params['publish']: c += ['--publish', pub]", "authentication file by setting the ``REGISTRY_AUTH_FILE`` environment variable. ``export REGISTRY_AUTH_FILE=path``", "return self._diff_update_and_compare('cpuset_cpus', before, after) def diffparam_cpuset_mems(self): before = self.info['hostconfig']['cpusetmems'] after", "self.action in ['start', 'stop', 'delete']: return self.start_stop_delete() if self.action in", "are passed into the container if set for the podman", "self.info['hostconfig']['cpusetmems'] after = self.params['cpuset_mems'] return self._diff_update_and_compare('cpuset_mems', before, after) def diffparam_device(self):", "and then if the container is running moves it to", "or not out or \"version\" not in out: self.module.fail_json(msg=\"%s run", "{ ... }, \"HostnamePath\": \"...\", \"HostsPath\": \"...\", \"ID\": \"...\", \"Image\":", "class. Arguments: module {obj} -- ansible module object \"\"\" super(PodmanManager,", "doesn't support idempotency if this is set. type: list elements:", "slirp4netns to create a user network stack. This is the", "description: - Keep STDIN open even if not attached. The", "dict cap_add: description: - List of capabilities to add to", "description: - A limit value equal to memory plus swap.", "Specify a static IP address for the container, for example", "c += ['--expose', exp] return c def addparam_gidmap(self, c): return", "List of capabilities to add to the container. type: list", "= self.params['ipc'] return self._diff_update_and_compare('ipc', before, after) def diffparam_label(self): before =", "the podman kill or podman stop commands. Valid values are", "can be helpful for investigations. type: bool default: False detach_keys:", "volumes volumes_from: description: - Mount volumes from the specified container(s).", "= { 'env_file', 'env_host', \"ulimit\", # Defaults depend on user", "self._diff_update_and_compare('device_read_bps', before, after) def diffparam_device_read_iops(self): before = self.info['hostconfig']['blkiodevicereadiops'] or []", "to the container. The format is <device-on-host>[:<device-on-container>][:<permissions>] (e.g. device /dev/sdc:/dev/xvdc:rwm)", "self.params['label'].items() }) return self._diff_update_and_compare('label', before, after) def diffparam_log_driver(self): before =", "bool image_volume: description: - Tells podman how to handle the", "str workdir: description: - Working directory inside the container. The", "def addparam_privileged(self, c): return c + ['--privileged=%s' % self.params['privileged']] def", "/etc/hosts for the container Default is false. type: bool oom_kill_disable:", "vol in self.params['volume']: if vol: c += ['--volume', vol] return", "that are available for the process that will be launched", "self.info['hostconfig']['privileged'] after = self.params['privileged'] return self._diff_update_and_compare('privileged', before, after) def diffparam_pid(self):", "or a list. type: raw cpu_period: description: - Limit the", "+ ['--cpus', self.params['cpus']] def addparam_cpuset_cpus(self, c): return c + ['--cpuset-cpus',", "\"default\", \"cgroup_parent\": \"\", \"cidfile\": \"\", \"cpus\": 0.0, \"cpu_shares\": 0, \"cpu_quota\":", "versions if 'cgroups' in self.info['hostconfig']: before = self.info['hostconfig']['cgroups'] after =", "a list. type: raw cpu_period: description: - Limit the CPU", "= self.params['cpu_shares'] return self._diff_update_and_compare('cpu_shares', before, after) def diffparam_cpus(self): before =", "self.info['config']['labels'] or {} after = before.copy() if self.params['label']: after.update({ str(k).lower():", "the container.\"\"\" self._perform_action('stop') def start(self): \"\"\"Start the container.\"\"\" self._perform_action('start') def", "and if the container is not joining another container's network", "A limit value equal to memory plus swap. Must be", "def addparam_etc_hosts(self, c): for host_ip in self.params['etc_hosts'].items(): c += ['--add-host',", "name with registry and namespaces. type: bool default: False init:", "c): return c + ['--read-only=%s' % self.params['read_only']] def addparam_read_only_tmpfs(self, c):", "the amount of time in a given CPU period Real", "BOOLEAN_KEY: \"yes\" - name: Container present podman_container: name: mycontainer state:", "addparam_memory_swappiness(self, c): return c + ['--memory-swappiness', self.params['memory_swappiness']] def addparam_mount(self, c):", "False aliases: - restart gidmap: description: - Run the container", "process than Podman, so this is necessary when using systemd", "int mount: description: - Attach a filesystem mount to the", "str choices: - default - disabled cidfile: description: - Write", "c): return c + ['--ipc', self.params['ipc']] def addparam_kernel_memory(self, c): return", "specified container(s). type: list elements: str workdir: description: - Working", "c def addparam_cap_add(self, c): for cap_add in self.params['cap_add']: c +=", "['--device', dev] return c def addparam_device_read_bps(self, c): for dev in", "security_opt \"seccomp=unconfined\" type: list elements: str shm_size: description: - Size", "default is true. type: bool stop_signal: description: - Signal to", "i in before] after = self.params['device_write_bps'] or [] before, after", "- Set the UTS mode for the container type: str", "real-time runtime in microseconds. This flag tells the kernel to", "current container, update results with last info, exit. Keyword Arguments:", "wish to set the search domain) type: str entrypoint: description:", "podman_version self.module = module def construct_command_from_params(self): \"\"\"Create a podman command", "diffparam_uts(self): before = self.info['hostconfig']['utsmode'] after = self.params['uts'] return self._diff_update_and_compare('uts', before,", "only. type: str memory_swap: description: - A limit value equal", "The disabled option will force the container to not create", "module_exec = module.params['executable'] if not image: return image_actions rc, out,", "['--uts', self.params['uts']] def addparam_volume(self, c): for vol in self.params['volume']: if", "= self.params['blkio_weight'] return self._diff_update_and_compare('blkio_weight', before, after) def diffparam_blkio_weight_device(self): before =", "running moves it to a stopped state. type: str default:", "return c + ['--userns', self.params['userns']] def addparam_uts(self, c): return c", "type: str cpuset_cpus: description: - CPUs in which to allow", "after) def diffparam_cap_add(self): before = self.info['effectivecaps'] or [] after =", "cmd] if self.action == 'delete': cmd = ['rm', '-f', self.params['name']]", "# TODO(sshnaidm): to inspect image to get the default command", "is to create a private IPC namespace (POSIX SysV IPC)", "i in after] return self._diff_update_and_compare('command', before, after) return False def", "diffparam_image(self): # TODO(sshnaidm): for strict image compare mode use SHAs", "= self.get_info() self.version = self._get_podman_version() self.diff = {} self.actions =", "cgroup for the container will be created. If the path", "to restrict the container's Real Time CPU usage to the", "a container podman_container: name: mycontainer state: stopped - name: Start", "Number of CPUs. The default is 0.0 which means no", "usage. This flag tell the kernel to restrict the container's", "- Set the Network mode for the container * bridge", "default: False init: description: - Run an init inside the", "log file. For example log_opt \"path=/var/log/container/mycontainer.json\" type: str aliases: -", "disabled cidfile: description: - Write the container ID to the", "= [] if self.module.params['cap_add'] is not None: after += [\"cap_\"", "self).__init__() self.module = module self.results = { 'changed': False, 'actions':", "configuration. Use the recreate option to force the re-creation of", "state is 'absent'.\"\"\" if not self.container.exists: self.results.update({'changed': False}) elif self.container.exists:", "def addparam_no_hosts(self, c): return c + ['--no-hosts=%s' % self.params['no_hosts']] def", "be pulled from the registry. If no tag is included,", "= True return different def ensure_image_exists(module, image): \"\"\"If image is", "If this is the case, the image is assumed to", "running C(podman) default: 'podman' type: str state: description: - I(absent)", "using systemd to restart Podman containers. type: path command: description:", "for annotate in self.params['annotation'].items(): c += ['--annotation', '='.join(annotate)] return c", "will be created. If a container matches the name but", "stop a container. Default is 10. type: int subgidname: description:", "- I(stopped) - Asserts that the container is first I(present),", "[self.module.params['executable'], b'container', b'inspect', self.name]) return json.loads(out)[0] if rc == 0", "c): return c + ['--memory-swappiness', self.params['memory_swappiness']] def addparam_mount(self, c): return", "['--pids-limit', self.params['pids_limit']] def addparam_pod(self, c): return c + ['--pod', self.params['pod']]", "err = self.module.run_command( [self.module.params['executable'], b'container'] + b_command, expand_user_and_vars=False) self.stdout =", "- absent - present - stopped - started image: description:", "Restart containers when they exit, regardless of status, retrying indefinitely", "__init__(self, action, params, podman_version, module): self.params = params self.action =", "Read in a line delimited file of environment variables type:", "before, after) def diffparam_command(self): # TODO(sshnaidm): to inspect image to", "be set to double the value of --memory Note -", "= self.params['user'] return self._diff_update_and_compare('user', before, after) def diffparam_uts(self): before =", "container's pids limit. Set -1 to have unlimited pids for", "self.params['cmd_args'] class PodmanDefaults: def __init__(self, module, podman_version): self.module = module", "'stopped'.\"\"\" if not self.container.exists and not self.image: self.module.fail_json(msg='Cannot create container", "self.run() class PodmanManager: \"\"\"Module manager class. Defines according to parameters", "parameter has partial idempotency only. def diffparam_hostname(self): before = self.info['config']['hostname']", "the map with 'name' in the /etc/subgid file. type: str", "0, \"cpuset_cpus\": \"\", \"cpuset_mems\": \"\", \"detach\": True, \"device\": [], \"env_host\":", "'bind' - 'tmpfs' - 'ignore' image_strict: description: - Whether to", "+ ['--pid', self.params['pid']] def addparam_pids_limit(self, c): return c + ['--pids-limit',", "will be removed in Ansible 2.12. - Empty if C(state)", "A container matching the specified name will be stopped and", "if self.restart: self.container.restart() self.results['actions'].append('restarted %s' % self.container.name) self.update_container_result() self.update_container_result(changed=False) elif", "default - disabled cidfile: description: - Write the container ID", "Can only be used if no additional CNI networks to", "the default log_path def diffparam_log_opt(self): before = self.info['logpath'] if self.module.params['log_opt']", "return self._diff_update_and_compare('no_hosts', before, after) def diffparam_oom_score_adj(self): before = self.info['hostconfig']['oomscoreadj'] after", "expressed in time format like 2m3s. The default value is", "second) from a device (e.g. device-read-bps /dev/sda:1mb) type: list device_read_iops:", "self.params['restart_policy']] def addparam_rm(self, c): if self.params['rm']: c += ['--rm'] return", "by applicable law or agreed to in writing, software #", "the \"test\" key is a list of 2 items where", "limitations # under the License. # flake8: noqa: E501 from", "or g) Note - idempotency is supported for integers only.", "\"2019-06-17T19:13:10.157518963+03:00\", \"Healthcheck\": { \"FailingStreak\": 0, \"Log\": null, \"Status\": \"\" },", "c): for blkio in self.params['blkio_weight_device'].items(): c += ['--blkio-weight-device', ':'.join(blkio)] return", "func.startswith(\"addparam\")] params_set = (i for i in self.params if self.params[i]", "* none no networking * container:<name|id> reuse another container's network", "Podman containers requirements: - \"Podman installed on host\" options: name:", "[ ... ], \"Name\": \"myservice\", \"Namespace\": \"\", \"NetworkSettings\": { \"Bridge\":", "command. Arguments: action {str} -- action type from 'run', 'stop',", "container in systemd mode. The default is true. type: bool", "can be b (bytes), k (kilobytes), m(megabytes), or g (gigabytes).", "given CPU period Real Time tasks may consume. type: int", "is None and before: after = before else: after =", "c + ['--userns', self.params['userns']] def addparam_uts(self, c): return c +", "module parameters \"\"\" def __init__(self, action, params, podman_version, module): self.params", "['--ulimit', u] return c def addparam_user(self, c): return c +", "in sorted( diffs['before'].items())]) + \"\\n\" self.diff['after'] = \"\\n\".join( [\"%s -", "memory parameter before = str(self.info['hostconfig']['memoryswap']) after = self.params['memory_swap'] if (self.module.params['memory_swap']", "before else: after = self.params['log_opt'].split(\"=\")[1] return self._diff_update_and_compare('log_opt', before, after) def", "-- list of byte strings for Popen command \"\"\" if", "c): for secopt in self.params['security_opt']: c += ['--security-opt', secopt] return", "return c + ['--gidmap', self.params['gidmap']] def addparam_group_add(self, c): for g", "rate (bytes per second) from a device (e.g. device-read-bps /dev/sda:1mb)", "0, \"cpu_rt_runtime\": 0, \"cpu_rt_period\": 0, \"cpuset_cpus\": \"\", \"cpuset_mems\": \"\", \"detach\":", "\"\"\"Inspect container and gather info about it.\"\"\" rc, out, err", "return self._diff_update_and_compare('device_write_iops', before, after) # Limited idempotency, it can't guess", "self.params['workdir']] # Add your own args for podman command def", "options are bind, tmpfs, or ignore (default bind) type: str", "dev in self.params['device_read_iops']: c += ['--device-read-iops', dev] return c def", "after) def diffparam_device_read_bps(self): before = self.info['hostconfig']['blkiodevicereadbps'] or [] before =", "applicable law or agreed to in writing, software # distributed", "0, \"cpu_quota\": 0, \"cpu_period\": 0, \"cpu_rt_runtime\": 0, \"cpu_rt_period\": 0, \"cpuset_cpus\":", "= self.params['workdir'] return self._diff_update_and_compare('workdir', before, after) def is_different(self): diff_func_list =", "- Set or alter a healthcheck command for a container.", "PodmanContainer: \"\"\"Perform container tasks. Manages podman container, inspects it and", "code, retrying indefinitely or until the optional max_retries count is", "after): if before != after: self.diff['before'].update({param_name: before}) self.diff['after'].update({param_name: after}) return", "% ( param, minv, self.podman_version)) if maxv and LooseVersion(maxv) <", "be updated, if it can be. If it cannot be", "addparam_device_read_iops(self, c): for dev in self.params['device_read_iops']: c += ['--device-read-iops', dev]", "it if not default before = False after = self.params['env_host']", "return c + ['--dns', ','.join(self.params['dns'])] def addparam_dns_option(self, c): return c", "list device_write_bps: description: - Limit write rate (bytes per second)", "\"Podman installed on host\" options: name: description: - Name of", "set up port redirection on the host system. type: list", "to join * slirp4netns use slirp4netns to create a user", "str annotation: description: - Add an annotation to the container.", "environment variables are passed into the container if set for", "int cpu_shares: description: - CPU shares (relative weight) type: int", "def diffparam_tty(self): before = self.info['config']['tty'] after = self.params['tty'] return self._diff_update_and_compare('tty',", "publish: description: - Publish a container's port, or range of", "only. def diffparam_hostname(self): before = self.info['config']['hostname'] after = self.params['hostname'] or", "% self.container.name) self.update_container_result() if self.container.stopped: self.update_container_result(changed=False) elif self.container.running: self.container.stop() self.results['actions'].append('stopped", "- \"<NAME> (@sshnaidm)\" version_added: '2.9' short_description: Manage podman containers notes:", "sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('devices', before, after) def diffparam_device_read_bps(self): before =", "param in params_set: func_name = \"_\".join([\"addparam\", param]) if func_name in", "\"\"\"Perform action with container. Arguments: action {str} -- action to", "the kernel to limit the amount of time in a", "count is hit * always - Restart containers when they", "minv='1.6.2') return c + ['--cgroupns=%s' % self.params['cgroupns']] def addparam_cgroup_parent(self, c):", "def addparam_memory_swappiness(self, c): return c + ['--memory-swappiness', self.params['memory_swappiness']] def addparam_mount(self,", "the pod for you, preference the pod name with \"new:\"", "if not self.container.exists: self.container.create() self.results['actions'].append('created %s' % self.container.name) self.update_container_result() if", "= self.info['conmonpidfile'] if self.module.params['conmon_pidfile'] is None: after = before else:", "dff_func(): if fail_fast: return True else: different = True #", "cmd_args: description: - Any additionl command options you want to", "parameters. If no container matches the name, a container will", "description: - Overwrite the default ENTRYPOINT of the image type:", "for func in dir(self) if callable(getattr(self, func)) and func.startswith( \"diffparam\")]", "are available for the process that will be launched inside", "return c def addparam_publish_all(self, c): return c + ['--publish-all=%s' %", "before = self.info['hostconfig']['blkioweight'] after = self.params['blkio_weight'] return self._diff_update_and_compare('blkio_weight', before, after)", "ns:<path> path to a network namespace to join * slirp4netns", "+ i.lower() for i in self.module.params['cap_add']] after += before before,", "type: dict aliases: - add_hosts expose: description: - Expose a", "after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('device_read_bps', before, after) def diffparam_device_read_iops(self):", "type: str http_proxy: description: - By default proxy environment variables", "Add additional groups to run as type: list healthcheck: description:", "name and any provided configuration. If no container matches the", "type: str network: description: - Set the Network mode for", "depend on user and platform, impossible to guess } def", "after) def diffparam_cgroups(self): # Cgroups output is not supported in", "list of byte strings for Popen command \"\"\" if self.action", "pub] return c def addparam_publish_all(self, c): return c + ['--publish-all=%s'", "options. Used to set the path to the container log", "\"k8s-file\". type: str choices: - k8s-file - journald - json-file", "diffparam_cpus(self): before = int(self.info['hostconfig']['nanocpus']) / 1000000000 after = self.params['cpus'] return", "return c def addparam_device_read_bps(self, c): for dev in self.params['device_read_bps']: c", "str shm_size: description: - Size of /dev/shm. The format is", "= podman_version self.default_dict = None self.info = yaml.safe_load(json.dumps(info).lower()) self.params =", "\"RestartCount\": 0, \"Rootfs\": \"\", \"State\": { \"Dead\": false, \"Error\": \"\",", "self.check_version('--cgroupns', minv='1.6.2') return c + ['--cgroupns=%s' % self.params['cgroupns']] def addparam_cgroup_parent(self,", "healthcheck before an interval is considered failed. Like start-period, the", "setting the http_proxy option to false. The environment variables passed", "def addparam_shm_size(self, c): return c + ['--shm-size', self.params['shm_size']] def addparam_sig_proxy(self,", "{str} -- name of image Returns: list -- list of", "= { 'changed': False, 'actions': [], 'container': {}, } self.name", "stop, restart and manage Podman containers requirements: - \"Podman installed", "- Mount volumes from the specified container(s). type: list elements:", "- idempotency is supported for integers only. type: str label:", "- Set the user namespace mode for the container. It", "working directory for running binaries within a container is the", "false. The environment variables passed in include http_proxy, https_proxy, ftp_proxy,", "def diffparam_pid(self): before = self.info['hostconfig']['pidmode'] after = self.params['pid'] return self._diff_update_and_compare('pid',", "\"\"\"Run actions if desired state is 'started'.\"\"\" if self.container.running and", "host use the podman host network stack. * <network-name>|<network-id> connect", "the returned fact will be removed in Ansible 2.12. -", "- idempotency is supported for integers only. type: str memory_reservation:", "PodmanContainer class. Arguments: module {obj} -- ansible module object name", "no automatic timer setup) (default \"30s\") type: str healthcheck_retries: description:", "default is true. type: bool tmpfs: description: - Create a", "module: podman_container author: - \"<NAME> (@sshnaidm)\" version_added: '2.9' short_description: Manage", "healthcheck is considered to be unhealthy. The default value is", "author: - \"<NAME> (@sshnaidm)\" version_added: '2.9' short_description: Manage podman containers", "is supported for integers only. type: str label: description: -", "name: myapplication image: redis state: started restart: yes etc_hosts: other:", "+ ['--healthcheck-start-period', self.params['healthcheck_start_period']] def addparam_healthcheck_timeout(self, c): return c + ['--healthcheck-timeout',", "[] description: - Start, stop, restart and manage Podman containers", "after = before else: after = self.params['log_opt'].split(\"=\")[1] return self._diff_update_and_compare('log_opt', before,", "- Use all current host environment variables in container. Defaults", "description: - Create a tmpfs mount. For example tmpfs \"/tmp\"", "return self._diff_update_and_compare('annotation', before, after) def diffparam_env_host(self): # It's impossible to", "Use the recreate option to force the re-creation of the", "}, \"ConmonPidFile\": \"...\", \"Created\": \"2019-06-17T19:13:09.873858307+03:00\", \"Dependencies\": [], \"Driver\": \"overlay\", \"EffectiveCaps\":", "i in cmd] def check_version(self, param, minv=None, maxv=None): if minv", "and platform, impossible to guess } def defaultize(self): params_with_defaults =", "['--healthcheck-timeout', self.params['healthcheck_timeout']] def addparam_hostname(self, c): return c + ['--hostname', self.params['hostname']]", "all current host environment variables in container. Defaults to false.", "and reaps processes. type: str init_path: description: - Path to", "c): return c + ['--healthcheck-timeout', self.params['healthcheck_timeout']] def addparam_hostname(self, c): return", "or [] before, after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('device_write_iops', before,", "the matching container. - I(started) - Asserts there is a", "container matching the specified name will be stopped and removed.", "stdout=out, stderr=err) def run(self): \"\"\"Run the container.\"\"\" self._perform_action('run') def delete(self):", "choices: - k8s-file - journald - json-file log_opt: description: -", "LIMIT will be set to double the value of --memory", "= self.params['memory_reservation'] return self._diff_update_and_compare('memory_reservation', before, after) def diffparam_network(self): before =", "self.params['hostname']] def addparam_http_proxy(self, c): return c + ['--http-proxy=%s' % self.params['http_proxy']]", "self).__init__() self.module = module self.name = name self.stdout, self.stderr =", "setting the ``REGISTRY_AUTH_FILE`` environment variable. ``export REGISTRY_AUTH_FILE=path`` type: path blkio_weight:", "+ ['--workdir', self.params['workdir']] # Add your own args for podman", "def ensure_image_exists(module, image): \"\"\"If image is passed, ensure it exists,", "on user and platform, impossible to guess } def defaultize(self):", "g] return c def addparam_healthcheck(self, c): return c + ['--healthcheck-command',", "= str(self.info['hostconfig']['memoryreservation']) after = self.params['memory_reservation'] return self._diff_update_and_compare('memory_reservation', before, after) def", "- idempotency is supported for integers only. type: str memory_swap:", "different.\"\"\" diffcheck = PodmanContainerDiff(self.module, self.info, self.version) is_different = diffcheck.is_different() diffs", "'exists', image]) if rc == 0: return image_actions rc, out,", "Add an annotation to the container. The format is key", "- Tune the host's OOM preferences for containers (accepts -1000", "you don't wish to set the search domain) type: str", "usage to the period you specify. type: int cpu_rt_runtime: description:", "self.container.get_info() if changed else self.container.info out, err = self.container.stdout, self.container.stderr", "self.params['label'].items(): c += ['--label', b'='.join([to_bytes(l, errors='surrogate_or_strict') for l in label])]", "updated, it will be removed and re-created with the requested", "# libpod issue with networks in inspection \"network\": [\"default\"], \"oom_score_adj\":", "re-created with the requested config. Image version will be taken", "def addparam_cidfile(self, c): return c + ['--cidfile', self.params['cidfile']] def addparam_conmon_pidfile(self,", "addparam_device_write_bps(self, c): for dev in self.params['device_write_bps']: c += ['--device-write-bps', dev]", "system uses bytes. If you omit the size entirely, the", "desired state is 'started'.\"\"\" if self.container.running and \\ (self.container.different or", "= self.info['config']['annotations'] or {} after = before.copy() if self.module.params['annotation'] is", "in after.split()] elif isinstance(after, list): after = [i.lower() for i", "PodmanDefaults( self.module, self.version).default_dict() for p in self.module.params: if self.module.params[p] is", "['--init-path', self.params['init_path']] def addparam_interactive(self, c): return c + ['--interactive=%s' %", "Limit the CPU real-time runtime in microseconds. This flag tells", "dev] return c def addparam_device_read_bps(self, c): for dev in self.params['device_read_bps']:", "self.info['hostconfig']['utsmode'] after = self.params['uts'] return self._diff_update_and_compare('uts', before, after) def diffparam_volume(self):", "-- dictionary of module parameters \"\"\" def __init__(self, action, params,", "a line delimited file of environment variables type: path env_host:", "[] after = before[:] if self.module.params['cap_drop'] is not None: for", "this is the case, the image is assumed to be", "after = self.params['command'] if isinstance(after, str): after = [i.lower() for", "remote commands) You can also override the default path of", "path=/var/log/container/mycontainer.json log_driver: k8s-file \"\"\" RETURN = \"\"\" container: description: -", "Create a data container podman_container: name: mydata image: busybox volume:", "/run, /tmp, and /var/tmp. The default is true type: bool", "the container will create CGroups. Valid values are enabled and", "device /dev/sdc:/dev/xvdc:rwm) type: list elements: str device_read_bps: description: - Limit", "self.params['name']] return [to_bytes(i, errors='surrogate_or_strict') for i in cmd] def check_version(self,", "redirection on the host system. type: list elements: str aliases:", "cmd = [self.action, '--name', self.params['name']] all_param_methods = [func for func", "tells the kernel to limit the amount of time in", "container podman_container: name: myapplication image: redis state: started restart: yes", "return c + ['--no-hosts=%s' % self.params['no_hosts']] def addparam_oom_kill_disable(self, c): return", "start, create, stop, run, delete \"\"\" b_command = PodmanModuleParams(action, self.module.params,", "list elements: str aliases: - exposed - exposed_ports force_restart: description:", "in diff_func_list: dff_func = getattr(self, func_name) if dff_func(): if fail_fast:", "must be within the default CNI network's pool (default 10.88.0.0/16).", "no_hosts: description: - Do not create /etc/hosts for the container", "to be unhealthy. The default value is 3. type: int", "return c def addparam_workdir(self, c): return c + ['--workdir', self.params['workdir']]", "= self.params['device_read_iops'] or [] before, after = sorted(list(set(before))), sorted(list(set(after))) return", "specified!') if not self.container.exists: self.container.create() self.results['actions'].append('created %s' % self.container.name) self.update_container_result()", "stop, run, delete \"\"\" b_command = PodmanModuleParams(action, self.module.params, self.version, self.module,", "after = [\":\".join(v.split(\":\")[:2]) for v in self.params['volume']] before, after =", "after = self.params['env_host'] return self._diff_update_and_compare('env_host', before, after) def diffparam_blkio_weight(self): before", "not None: after.update(self.params['annotation']) return self._diff_update_and_compare('annotation', before, after) def diffparam_env_host(self): #", "['--publish-all=%s' % self.params['publish_all']] def addparam_read_only(self, c): return c + ['--read-only=%s'", "groups to run as type: list healthcheck: description: - Set", "after) def diffparam_network(self): before = [self.info['hostconfig']['networkmode']] after = self.params['network'] return", "k, v in sorted( diffs['before'].items())]) + \"\\n\" self.diff['after'] = \"\\n\".join(", "out, err = self.container.stdout, self.container.stderr self.results.update({'changed': changed, 'container': facts, 'podman_actions':", "= \"\\n\".join( [\"%s - %s\" % (k, v) for k,", "the container will be updated, if it can be. If", "for vol in self.params['volumes_from']: c += ['--volumes-from', vol] return c", "self.module = module self.version = podman_version self.default_dict = None self.info", "self._diff_update_and_compare('cap_add', before, after) def diffparam_cap_drop(self): before = self.info['effectivecaps'] or []", "of /dev/shm. The format is <number><unit>. number must be greater", "in before: if m['type'] == 'volume': volumes.append([m['name'], m['destination']]) else: volumes.append([m['source'],", "after) def diffparam_cpu_shares(self): before = self.info['hostconfig']['cpushares'] after = self.params['cpu_shares'] return", "return c + ['--pid', self.params['pid']] def addparam_pids_limit(self, c): return c", "self.module.fail_json(msg=\"Unexpected logic error happened, \" \"please contact maintainers ASAP!\") def", "only be used if no additional CNI networks to join", "locally. type: str annotation: description: - Add an annotation to", "after = self.params['device_write_iops'] or [] before, after = sorted(list(set(before))), sorted(list(set(after)))", "to perform - start, create, stop, run, delete \"\"\" b_command", "= self.container.get_info() if changed else self.container.info out, err = self.container.stdout,", "= self.params['device_write_iops'] or [] before, after = sorted(list(set(before))), sorted(list(set(after))) return", "( param, minv, self.podman_version)) def addparam_annotation(self, c): for annotate in", "driver. Used to set the log driver for the container.", "will be set to double the value of --memory Note", "for p in self.non_idempotent: if self.module.params[p] is not None and", "addparam_healthcheck_start_period(self, c): return c + ['--healthcheck-start-period', self.params['healthcheck_start_period']] def addparam_healthcheck_timeout(self, c):", "Limit read rate (bytes per second) from a device (e.g.", "option allows you to specify arbitrary environment variables that are", "def addparam_memory(self, c): return c + ['--memory', self.params['memory']] def addparam_memory_reservation(self,", "action self.podman_version = podman_version self.module = module def construct_command_from_params(self): \"\"\"Create", "\"...\", \"HostsPath\": \"...\", \"ID\": \"...\", \"Image\": \"...\", \"ImageName\": \"docker.io/library/busybox:latest\", \"IsInfra\":", "- Default is to create a private IPC namespace (POSIX", "after = self.params['pid'] return self._diff_update_and_compare('pid', before, after) def diffparam_rm(self): before", "string or a list. type: raw cpu_period: description: - Limit", "with container. Arguments: action {str} -- action to perform -", "no limit. type: str cpuset_cpus: description: - CPUs in which", "to random ports on the host interfaces. The default is", "image is not found, the image will be pulled from", "if before: volumes = [] for m in before: if", "main(): module = AnsibleModule( argument_spec=yaml.safe_load(DOCUMENTATION)['options'], mutually_exclusive=( ['no_hosts', 'etc_hosts'], ), supports_check_mode=True,", "str healthcheck_interval: description: - Set an interval for the healthchecks", "\"cpuset_cpus\": \"\", \"cpuset_mems\": \"\", \"detach\": True, \"device\": [], \"env_host\": False,", "= self.info['hostconfig']['cpusetmems'] after = self.params['cpuset_mems'] return self._diff_update_and_compare('cpuset_mems', before, after) def", "be configured!\" % module.params['state']) PodmanManager(module).execute() if __name__ == '__main__': main()", "{dict} -- dictionary of module parameters \"\"\" def __init__(self, action,", "c): return c + ['--pid', self.params['pid']] def addparam_pids_limit(self, c): return", "in detach mode type: bool default: True debug: description: -", "c + ['--oom-kill-disable=%s' % self.params['oom_kill_disable']] def addparam_oom_score_adj(self, c): return c", "else {} def _get_podman_version(self): rc, out, err = self.module.run_command( [self.module.params['executable'],", "in self.params['blkio_weight_device'].items(): c += ['--blkio-weight-device', ':'.join(blkio)] return c def addparam_cap_add(self,", "c): for cap_drop in self.params['cap_drop']: c += ['--cap-drop', cap_drop] return", "self.params['cpu_shares'] return self._diff_update_and_compare('cpu_shares', before, after) def diffparam_cpus(self): before = int(self.info['hostconfig']['nanocpus'])", "not out or \"version\" not in out: self.module.fail_json(msg=\"%s run failed!\"", "Tune a container's memory swappiness behavior. Accepts an integer between", "['--privileged=%s' % self.params['privileged']] def addparam_publish(self, c): for pub in self.params['publish']:", "!= 0: self.module.fail_json( msg=\"Can't %s container %s\" % (action, self.name),", "after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('devices', before, after) def diffparam_device_read_bps(self):", "if not image: return image_actions rc, out, err = module.run_command([module_exec,", "when it exits. The default is false. type: bool aliases:", "list -- list of byte strings for Popen command \"\"\"", "mode. The default is true. type: bool tmpfs: description: -", "'', '' self.info = self.get_info() self.version = self._get_podman_version() self.diff =", "self.params['cpu_shares']] def addparam_cpus(self, c): return c + ['--cpus', self.params['cpus']] def", "self.diff['after'].update({param_name: after}) return True return False def diffparam_annotation(self): before =", "return self._diff_update_and_compare('security_opt', before, after) def diffparam_stop_signal(self): before = self.info['config']['stopsignal'] after", "type: int blkio_weight_device: description: - Block IO weight (relative device", "the current container, update results with last info, exit. Keyword", "not module.params['image']: module.fail_json(msg=\"State '%s' required image to be configured!\" %", "Set custom DNS options type: str dns_search: description: - Set", "+= ['--env', b\"=\".join([to_bytes(k, errors='surrogate_or_strict') for k in env_value])] return c", "init process. Cgroups will be created if they do not", "type: str interactive: description: - Keep STDIN open even if", "CPUs. The default is 0.0 which means no limit. type:", "return False def diffparam_cidfile(self): before = self.info['hostconfig']['containeridfile'] after = self.params['cidfile']", "expose \"3300-3310\") to set up port redirection on the host", "c): return c + ['--sig-proxy=%s' % self.params['sig_proxy']] def addparam_stop_signal(self, c):", "Add your own args for podman command def addparam_cmd_args(self, c):", "- A container matching the specified name will be stopped", "false, \"StopSignal\": 15, \"Tty\": false, \"User\": { \"gid\": 0, \"uid\":", "always re-create a matching container, even if it is running.", "force_restart: description: - Force restart of container. type: bool default:", "err if rc != 0: self.module.fail_json( msg=\"Can't %s container %s\"", "registered vars since Ansible 2.8. For compatibility reasons, the facts", "self.params['privileged'] return self._diff_update_and_compare('privileged', before, after) def diffparam_pid(self): before = self.info['hostconfig']['pidmode']", "parameters. Returns: list -- list of byte strings for Popen", "DEVICE_NAME[:]WEIGHT). type: dict cap_add: description: - List of capabilities to", "in self.info['hostconfig']['extrahosts']]) else: before = {} after = self.params['etc_hosts'] return", "c + ['--init-path', self.params['init_path']] def addparam_interactive(self, c): return c +", "description: - Publish all exposed ports to random ports on", "yaml.safe_load(json.dumps(info).lower()) self.params = self.defaultize() self.diff = {'before': {}, 'after': {}}", "object \"\"\" super(PodmanManager, self).__init__() self.module = module self.results = {", "podman bind mounts /HOST-DIR in the host to /CONTAINER-DIR in", "return c + ['--tty=%s' % self.params['tty']] def addparam_uidmap(self, c): for", "and removed. - I(present) - Asserts the existence of a", "mode for the container * bridge create a network stack", "version will be taken into account when comparing configuration. Use", "c): for dev in self.params['device']: c += ['--device', dev] return", "make the pod for you, preference the pod name with", "def addparam_systemd(self, c): return c + ['--systemd=%s' % self.params['systemd']] def", "['--log-driver', self.params['log_driver']] def addparam_log_opt(self, c): return c + ['--log-opt', self.params['log_opt']]", "to be configured!\" % module.params['state']) PodmanManager(module).execute() if __name__ == '__main__':", "type: str choices: - default - disabled cidfile: description: -", "['--interactive=%s' % self.params['interactive']] def addparam_ip(self, c): return c + ['--ip',", "\"LogPath\": \"/tmp/container/mycontainer.json\", \"MountLabel\": \"system_u:object_r:container_file_t:s0:c282,c782\", \"Mounts\": [ ... ], \"Name\": \"myservice\",", "containers requirements: - \"Podman installed on host\" options: name: description:", "-- ansible module object name {str} -- name of container", "str choices: - k8s-file - journald - json-file log_opt: description:", "self._diff_update_and_compare('etc_hosts', before, after) def diffparam_group_add(self): before = self.info['hostconfig']['groupadd'] after =", "self.params['cpu_period']] def addparam_cpu_rt_period(self, c): return c + ['--cpu-rt-period', self.params['cpu_rt_period']] def", "object name {str} -- name of container \"\"\" super(PodmanContainer, self).__init__()", "description: - Expose a port, or a range of ports", "Time CPU usage. This flag tell the kernel to restrict", "- The number of retries allowed before a healthcheck is", "def diffparam_hostname(self): before = self.info['config']['hostname'] after = self.params['hostname'] or before", "tmpfs, or ignore (default bind) type: str choices: - 'bind'", "Version 2.0 (the \"License\"); you may # not use this", "self.params['cgroup_parent'] return self._diff_update_and_compare('cgroup_parent', before, after) def diffparam_cgroups(self): # Cgroups output", "--appendonly yes state: present recreate: yes expose: - 6379 volumes_from:", "namespace using the map with 'name' in the /etc/subgid file.", "+ ['--kernel-memory', self.params['kernel_memory']] def addparam_label(self, c): for label in self.params['label'].items():", "-- ansible module object \"\"\" super(PodmanManager, self).__init__() self.module = module", "a container is the root directory (/). type: str \"\"\"", "inspection \"network\": [\"default\"], \"oom_score_adj\": 0, \"pid\": \"\", \"privileged\": False, \"rm\":", "the container.\"\"\" self._perform_action('create') def recreate(self): \"\"\"Recreate the container.\"\"\" self.delete() self.run()", "before, after) def diffparam_cap_drop(self): before = self.info['effectivecaps'] or [] after", "Automatically remove the container when it exits. The default is", "= [\":\".join(v) for v in volumes] # Ignore volumes option", "pod: description: - Run container in an existing pod. If", "sent to the podman run command to the container process.", "before, after) def diffparam_cgroups(self): # Cgroups output is not supported", "c + ['--cgroups=%s' % self.params['cgroups']] def addparam_cgroupns(self, c): self.check_version('--cgroupns', minv='1.6.2')", "if self.module._diff and is_different and diffs['before'] and diffs['after']: self.diff['before'] =", "authentication file. Default is ``${XDG_RUNTIME_DIR}/containers/auth.json`` (Not available for remote commands)", "in after: after.remove(c) before, after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('cap_drop',", "before = self.info['config']['workingdir'] after = self.params['workdir'] return self._diff_update_and_compare('workdir', before, after)", "def diffparam_image(self): # TODO(sshnaidm): for strict image compare mode use", "of the conmon process to a file. conmon runs in", "addparam_ulimit(self, c): for u in self.params['ulimit']: c += ['--ulimit', u]", "= self.info['hostconfig']['ipcmode'] after = self.params['ipc'] return self._diff_update_and_compare('ipc', before, after) def", "is a list of 2 items where the first one", "return self._diff_update_and_compare('conmon_pidfile', before, after) def diffparam_cpu_period(self): before = self.info['hostconfig']['cpuperiod'] after", "in self.params['device_read_iops']: c += ['--device-read-iops', dev] return c def addparam_device_write_bps(self,", "container will be created. If the path is not absolute,", "\"version\" not in out: self.module.fail_json(msg=\"%s run failed!\" % self.module.params['executable']) return", "if container exists and is not running now.\"\"\" return self.exists", "return c def addparam_device_write_iops(self, c): for dev in self.params['device_write_iops']: c", "before, after) def diffparam_cap_add(self): before = self.info['effectivecaps'] or [] after", "Start, stop, restart and manage Podman containers requirements: - \"Podman", "container is running now.\"\"\" return self.exists and self.info['State']['Running'] @property def", "state is 'stopped'.\"\"\" if not self.container.exists and not self.image: self.module.fail_json(msg='Cannot", "def addparam_http_proxy(self, c): return c + ['--http-proxy=%s' % self.params['http_proxy']] def", "for k, v in self.params['label'].items() }) return self._diff_update_and_compare('label', before, after)", "], \"Hostname\": \"\", \"Image\": \"docker.io/library/busybox:latest\", \"Labels\": null, \"OpenStdin\": false, \"StdinOnce\":", "before, after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('device_write_iops', before, after) #", "def addparam_ip(self, c): return c + ['--ip', self.params['ip']] def addparam_ipc(self,", "return different def ensure_image_exists(module, image): \"\"\"If image is passed, ensure", "in cmd] def check_version(self, param, minv=None, maxv=None): if minv and", "diffparam_cpu_shares(self): before = self.info['hostconfig']['cpushares'] after = self.params['cpu_shares'] return self._diff_update_and_compare('cpu_shares', before,", "filesystem mount to the container. bind or tmpfs For example", "with present and started states to force the re-creation of", "present and started states to force the re-creation of an", "c def addparam_shm_size(self, c): return c + ['--shm-size', self.params['shm_size']] def", "= int(self.info['hostconfig']['nanocpus']) / 1000000000 after = self.params['cpus'] return self._diff_update_and_compare('cpus', before,", "before] after = self.params['device_read_iops'] or [] before, after = sorted(list(set(before))),", "+ ['--memory-reservation', self.params['memory_reservation']] def addparam_memory_swap(self, c): return c + ['--memory-swap',", "mount. For example tmpfs \"/tmp\" \"rw,size=787448k,mode=1777\" type: dict tty: description:", "the size entirely, the system uses 64m type: str sig_proxy:", "- Repository path (or image name) and tag used to", "self.info['config']['tty'] after = self.params['tty'] return self._diff_update_and_compare('tty', before, after) def diffparam_user(self):", "pid: description: - Set the PID mode for the container", "Ansible 2.12. - Empty if C(state) is I(absent). returned: always", "dev in self.params['device']: c += ['--device', dev] return c def", "v) for k, v in sorted( diffs['after'].items())]) + \"\\n\" return", "self._diff_update_and_compare('cpus', before, after) def diffparam_cpuset_cpus(self): before = self.info['hostconfig']['cpusetcpus'] after =", "to always re-create a matching container, even if it is", "\"\"\"Return True if container exists and is not running now.\"\"\"", "added to the container's ``/etc/hosts`` file. type: dict aliases: -", "for tmpfs in self.params['tmpfs'].items(): c += ['--tmpfs', ':'.join(tmpfs)] return c", "set to true, keep stdin open even if not attached.", "after = self.params['network'] return self._diff_update_and_compare('network', before, after) def diffparam_no_hosts(self): before", "image_actions.append(\"pulled image %s\" % image) return image_actions class PodmanContainer: \"\"\"Perform", "set the search domain) type: str entrypoint: description: - Overwrite", "['--ipc', self.params['ipc']] def addparam_kernel_memory(self, c): return c + ['--kernel-memory', self.params['kernel_memory']]", "from the container. type: list elements: str cgroup_parent: description: -", "Because of hostname is random generated, this parameter has partial", "['--memory-reservation', self.params['memory_reservation']] def addparam_memory_swap(self, c): return c + ['--memory-swap', self.params['memory_swap']]", "- Asserts there is a running container matching the name", "to force the re-creation of an existing container. type: bool", "will be created. type: str cgroups: description: - Determines whether", "after) def diffparam_label(self): before = self.info['config']['labels'] or {} after =", "def addparam_cpu_period(self, c): return c + ['--cpu-period', self.params['cpu_period']] def addparam_cpu_rt_period(self,", "gather info about it.\"\"\" rc, out, err = self.module.run_command( [self.module.params['executable'],", "the user namespace mode for the container. It defaults to", "self.diff = {'before': {}, 'after': {}} self.non_idempotent = { 'env_file',", "self.params['log_driver'] return self._diff_update_and_compare('log_driver', before, after) # Parameter has limited idempotency,", "The format is <device-on-host>[:<device-on-container>][:<permissions>] (e.g. device /dev/sdc:/dev/xvdc:rwm) type: list elements:", "in no automatic timer setup) (default \"30s\") type: str healthcheck_retries:", "for i in after.split()] elif isinstance(after, list): after = [i.lower()", "options you want to pass to podman command, cmd_args -", "Use with present and started states to force the re-creation", "= states_map[self.state] process_action() self.module.fail_json(msg=\"Unexpected logic error happened, \" \"please contact", "binary. type: str interactive: description: - Keep STDIN open even", "/etc/subuid file. type: str sysctl: description: - Configure namespaced kernel", "% self.params['read_only']] def addparam_read_only_tmpfs(self, c): return c + ['--read-only-tmpfs=%s' %", "Memory nodes (MEMs) in which to allow execution (0-3, 0,1).", "the container log file. For example log_opt \"path=/var/log/container/mycontainer.json\" type: str", "addparam_ip(self, c): return c + ['--ip', self.params['ip']] def addparam_ipc(self, c):", "+ ['--hostname', self.params['hostname']] def addparam_http_proxy(self, c): return c + ['--http-proxy=%s'", "run(self): \"\"\"Run the container.\"\"\" self._perform_action('run') def delete(self): \"\"\"Delete the container.\"\"\"", "the container Default is false. type: bool oom_kill_disable: description: -", "the swap LIMIT will be set to double the value", "range of ports (e.g. expose \"3300-3310\") to set up port", "def addparam_mount(self, c): return c + ['--mount', self.params['mount']] def addparam_network(self,", "expressed in a time format such as 1m22s. The default", "self._perform_action('start') def create(self): \"\"\"Create the container.\"\"\" self._perform_action('create') def recreate(self): \"\"\"Recreate", "'delete': cmd = ['rm', '-f', self.params['name']] return [to_bytes(i, errors='surrogate_or_strict') for", "['--cpuset-cpus', self.params['cpuset_cpus']] def addparam_cpuset_mems(self, c): return c + ['--cpuset-mems', self.params['cpuset_mems']]", "- Dict of host-to-IP mappings, where each host name is", "AnsibleModule from ansible.module_utils._text import to_bytes, to_native ANSIBLE_METADATA = { 'metadata_version':", "after = self.params['image'] mode = self.params['image_strict'] if mode is None", "bind mounts /HOST-DIR in the host to /CONTAINER-DIR in the", "addparam_interactive(self, c): return c + ['--interactive=%s' % self.params['interactive']] def addparam_ip(self,", "type: bool image_volume: description: - Tells podman how to handle", "strict image compare mode use SHAs before = self.info['config']['image'] after", "%s' % self.container.name) self.update_container_result() elif self.container.stopped and self.container.different: self.container.recreate() self.results['actions'].append('recreated", "OOM Killer for the container or not. Default is false.", "self.recreate): self.container.recreate() self.results['actions'].append('recreated %s' % self.container.name) self.update_container_result() elif self.container.running and", "type: path blkio_weight: description: - Block IO weight (relative weight)", "in self.params['group_add']: c += ['--group-add', g] return c def addparam_healthcheck(self,", "image_actions rc, out, err = module.run_command([module_exec, 'image', 'exists', image]) if", "+ \"\\n\" return is_different @property def running(self): \"\"\"Return True if", "and diffs['before'] and diffs['after']: self.diff['before'] = \"\\n\".join( [\"%s - %s\"", "after = self.params['conmon_pidfile'] return self._diff_update_and_compare('conmon_pidfile', before, after) def diffparam_cpu_period(self): before", "= self.params['stop_signal'] return self._diff_update_and_compare('stop_signal', before, after) def diffparam_tty(self): before =", "100. type: int mount: description: - Attach a filesystem mount", "in a given CPU period Real Time tasks may consume.", "{obj} -- ansible module object \"\"\" super(PodmanManager, self).__init__() self.module =", "before = self.info['hostconfig']['cgroups'] after = self.params['cgroups'] return self._diff_update_and_compare('cgroups', before, after)", "Return additional information which can be helpful for investigations. type:", "self.params['rm']: c += ['--rm'] return c def addparam_rootfs(self, c): return", "c): self.check_version('--env-host', minv='1.5.0') return c + ['--env-host=%s' % self.params['env_host']] def", "manager class. Defines according to parameters what actions should be", "file system. The dafault is false. type: bool security_opt: description:", "environment variables passed in include http_proxy, https_proxy, ftp_proxy, no_proxy, and", "with last info, exit. Keyword Arguments: changed {bool} -- whether", "vol] return c def addparam_volumes_from(self, c): for vol in self.params['volumes_from']:", "def diffparam_blkio_weight(self): before = self.info['hostconfig']['blkioweight'] after = self.params['blkio_weight'] return self._diff_update_and_compare('blkio_weight',", "c): return c + ['--workdir', self.params['workdir']] # Add your own", "retrying indefinitely or until the optional max_retries count is hit", "uidmap: description: - Run the container in a new user", "to self.defaults related to podman version return self.defaults class PodmanContainerDiff:", "default it's twice memory parameter before = str(self.info['hostconfig']['memoryswap']) after =", "device_read_bps: description: - Limit read rate (bytes per second) from", "for secopt in self.params['security_opt']: c += ['--security-opt', secopt] return c", "\"io.kubernetes.cri-o.ContainerType\": \"sandbox\", \"io.kubernetes.cri-o.TTY\": \"false\" }, \"AttachStderr\": false, \"AttachStdin\": false, \"AttachStdout\":", "def addparam_kernel_memory(self, c): return c + ['--kernel-memory', self.params['kernel_memory']] def addparam_label(self,", "into account when comparing configuration. Use the recreate option to", "in self.params['etc_hosts'].items(): c += ['--add-host', ':'.join(host_ip)] return c def addparam_expose(self,", "params_with_defaults[p] = self.module.params[p] return params_with_defaults def _diff_update_and_compare(self, param_name, before, after):", "+ ['--log-opt', self.params['log_opt']] def addparam_memory(self, c): return c + ['--memory',", "that forwards signals and reaps processes. type: str init_path: description:", "% self.container.name) self.results.update({'changed': True}) self.results.update({'container': {}, 'podman_actions': self.container.actions}) self.module.exit_json(**self.results) def", "type: str sysctl: description: - Configure namespaced kernel parameters at", "+ ['--authfile', self.params['authfile']] def addparam_blkio_weight(self, c): return c + ['--blkio-weight',", "exists, if not - pull it or fail. Arguments: module", "out, err = module.run_command([module_exec, 'image', 'pull', image]) if rc !=", "if minv and LooseVersion(minv) > LooseVersion( self.podman_version): self.module.fail_json(msg=\"Parameter %s is", "network stack * host use the podman host network stack.", "type: bool default: False restart_policy: description: - Restart policy to", "module.params['executable'] if not image: return image_actions rc, out, err =", "namespace using the supplied mapping. type: list ulimit: description: -", "Give extended privileges to this container. The default is false.", "Foundation # All Rights Reserved. # # Licensed under the", "stop commands. Valid values are * no - Do not", "\"\"\"Execute the desired action according to map of actions &", "a port, or a range of ports (e.g. expose \"3300-3310\")", "container. If an image is not found, the image will", "str uts: description: - Set the UTS mode for the", "self._diff_update_and_compare('command', before, after) return False def diffparam_conmon_pidfile(self): before = self.info['conmonpidfile']", "before = self.info['conmonpidfile'] if self.module.params['conmon_pidfile'] is None: after = before", "entrypoint: description: - Overwrite the default ENTRYPOINT of the image", "user namespaces are disabled. type: str uts: description: - Set", "bind or tmpfs For example mount \"type=bind,source=/path/on/host,destination=/path/in/container\" type: str network:", "a podman command from given module parameters. Returns: list --", "if fail_fast: return True else: different = True # Check", "the container's Real Time CPU usage to the period you", "self.params['ipc']] def addparam_kernel_memory(self, c): return c + ['--kernel-memory', self.params['kernel_memory']] def", "\"CAP_CHOWN\", ... ], \"Config\": { \"Annotations\": { \"io.kubernetes.cri-o.ContainerType\": \"sandbox\", \"io.kubernetes.cri-o.TTY\":", "supported till podman \" \"version %s only! Current version is", "image: description: - Repository path (or image name) and tag", "STDIN open even if not attached. The default is false.", "self.params['device_read_bps'] or [] before, after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('device_read_bps',", "return c + ['--memory-reservation', self.params['memory_reservation']] def addparam_memory_swap(self, c): return c", "make_started(self): \"\"\"Run actions if desired state is 'started'.\"\"\" if self.container.running", "- Memory soft limit (format 100m, where unit = b,", "re-create a matching container, even if it is running. Use", "True return False def diffparam_annotation(self): before = self.info['config']['annotations'] or {}", "c += ['--label', b'='.join([to_bytes(l, errors='surrogate_or_strict') for l in label])] return", "'run']: cmd = [self.action, '--name', self.params['name']] all_param_methods = [func for", "/tmp, and /var/tmp. The default is true type: bool recreate:", "c): return c + ['--label-file', self.params['label_file']] def addparam_log_driver(self, c): return", "the /etc/subgid file. type: str subuidname: description: - Run the", "def diffparam_label(self): before = self.info['config']['labels'] or {} after = before.copy()", "v in volumes] # Ignore volumes option for idempotency after", "2.8. For compatibility reasons, the facts are also accessible directly", "- CPUs in which to allow execution (0-3, 0,1) type:", "return c + ['--pids-limit', self.params['pids_limit']] def addparam_pod(self, c): return c", "%s\" % image, stdout=out, stderr=err) image_actions.append(\"pulled image %s\" % image)", "volumes_from: - mydata - name: Restart a container podman_container: name:", "- Proxy signals sent to the podman run command to", "results with last info, exit. Keyword Arguments: changed {bool} --", "- I(absent) - A container matching the specified name will", "the root directory (/). type: str \"\"\" EXAMPLES = \"\"\"", "action {str} -- action type from 'run', 'stop', 'create', 'delete',", "self.container.delete() self.results['actions'].append('deleted %s' % self.container.name) self.results.update({'changed': True}) self.results.update({'container': {}, 'podman_actions':", "self._diff_update_and_compare('cap_drop', before, after) def diffparam_cgroup_parent(self): before = self.info['hostconfig']['cgroupparent'] after =", "= self.params['cgroups'] return self._diff_update_and_compare('cgroups', before, after) return False def diffparam_cidfile(self):", "addparam_memory_reservation(self, c): return c + ['--memory-reservation', self.params['memory_reservation']] def addparam_memory_swap(self, c):", "for i in env_before} after = before.copy() if self.params['env']: after.update({", "networks to join were specified via 'network:', and if the", "by taking into account a full name with registry and", "+ ['--network', \",\".join(self.params['network'])] def addparam_no_hosts(self, c): return c + ['--no-hosts=%s'", "= self.container.stdout, self.container.stderr self.results.update({'changed': changed, 'container': facts, 'podman_actions': self.container.actions}, stdout=out,", "the container will be created. type: str cgroups: description: -", "isinstance(after, str): after = [i.lower() for i in after.split()] elif", "description: - Automatically remove the container when it exits. The", "self.container.diff}) if self.module.params['debug']: self.results.update({'podman_version': self.container.version}) self.module.exit_json(**self.results) def make_started(self): \"\"\"Run actions", "type: bool default: True debug: description: - Return additional information", "['--pod', self.params['pod']] def addparam_privileged(self, c): return c + ['--privileged=%s' %", "- Asserts the existence of a container matching the name", "str choices: - 'bind' - 'tmpfs' - 'ignore' image_strict: description:", "to disable OOM Killer for the container or not. Default", "after) def diffparam_device_write_iops(self): before = self.info['hostconfig']['blkiodevicewriteiops'] or [] before =", "dns_search with '' if you don't wish to set the", "governing permissions and limitations # under the License. # flake8:", "(default: {True}) \"\"\" facts = self.container.get_info() if changed else self.container.info", "def addparam_ipc(self, c): return c + ['--ipc', self.params['ipc']] def addparam_kernel_memory(self,", "if before == [] and self.module.params['blkio_weight_device'] is None: after =", "in after] return self._diff_update_and_compare('command', before, after) return False def diffparam_conmon_pidfile(self):", "recreate option to force the re-creation of the matching container.", "+ ['--rootfs=%s' % self.params['rootfs']] def addparam_security_opt(self, c): for secopt in", "if self.params['label']: after.update({ str(k).lower(): str(v).lower() for k, v in self.params['label'].items()", "container image: quay.io/bitnami/wildfly state: started - name: Create a data", "of those. Defaults to true type: bool image_volume: description: -", "If you specify, volume /HOST-DIR:/CONTAINER-DIR, podman bind mounts /HOST-DIR in", "c): for g in self.params['group_add']: c += ['--group-add', g] return", "\"memory_reservation\": \"0\", # \"memory_swappiness\": -1, \"no_hosts\": False, # libpod issue", "mode' assume all images from different registries are the same", "if it pulled or nothing was done \"\"\" image_actions =", "self.params['init']] def addparam_init_path(self, c): return c + ['--init-path', self.params['init_path']] def", "addparam_healthcheck_timeout(self, c): return c + ['--healthcheck-timeout', self.params['healthcheck_timeout']] def addparam_hostname(self, c):", "after) def diffparam_memory_swap(self): # By default it's twice memory parameter", "expose: description: - Expose a port, or a range of", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "CGroup options cgroupns and cgroup-parent. type: str choices: - default", "maxv=None): if minv and LooseVersion(minv) > LooseVersion( self.podman_version): self.module.fail_json(msg=\"Parameter %s", "isinstance(after, list): after = [i.lower() for i in after] return", "= self.params['pid'] return self._diff_update_and_compare('pid', before, after) def diffparam_rm(self): before =", "{} before = {i.split(\"=\")[0]: i.split(\"=\")[1] for i in env_before} after", "self.update_container_result(changed=False) elif not self.container.exists: self.container.run() self.results['actions'].append('started %s' % self.container.name) self.update_container_result()", "':'.join(tmpfs)] return c def addparam_tty(self, c): return c + ['--tty=%s'", "rc != 0: self.module.fail_json( msg=\"Can't %s container %s\" % (action,", "value of --memory Note - idempotency is supported for integers", "be disabled by setting the http_proxy option to false. The", "non-0 exit code, retrying indefinitely or until the optional max_retries", "c + ['--subuidname', self.params['subuidname']] def addparam_sysctl(self, c): for sysctl in", "= PodmanDefaults( self.module, self.version).default_dict() for p in self.module.params: if self.module.params[p]", "module.params['image']: module.fail_json(msg=\"State '%s' required image to be configured!\" % module.params['state'])", "= diffcheck.is_different() diffs = diffcheck.diff if self.module._diff and is_different and", "the re-creation of an existing container. type: bool default: False", "present - stopped - started image: description: - Repository path", "aliases: - restart gidmap: description: - Run the container in", "(k, v) for k, v in sorted( diffs['before'].items())]) + \"\\n\"", "return c + ['--restart=%s' % self.params['restart_policy']] def addparam_rm(self, c): if", "c += ['--device-read-iops', dev] return c def addparam_device_write_bps(self, c): for", "\"Path\": \"sh\", \"ProcessLabel\": \"system_u:system_r:container_t:s0:c282,c782\", \"ResolvConfPath\": \"...\", \"RestartCount\": 0, \"Rootfs\": \"\",", "environment variables. This option allows you to specify arbitrary environment", "addparam_sysctl(self, c): for sysctl in self.params['sysctl'].items(): c += ['--sysctl', b\"=\".join([to_bytes(k,", "= self.params['cpu_period'] return self._diff_update_and_compare('cpu_period', before, after) def diffparam_cpu_rt_period(self): before =", "no tag is included, C(latest) will be used. - Can", "of ports, to the host. Format - ip:hostPort:containerPort | ip::containerPort", "fail_fast: return True else: different = True # Check non", "self.module.params['debug']: self.results.update({'podman_version': self.container.version}) self.module.exit_json(**self.results) def make_started(self): \"\"\"Run actions if desired", "first I(present), and then if the container is running moves", "c): return c + ['--shm-size', self.params['shm_size']] def addparam_sig_proxy(self, c): return", "self.params['init_path']] def addparam_interactive(self, c): return c + ['--interactive=%s' % self.params['interactive']]", "self.module, self.version).default_dict() for p in self.module.params: if self.module.params[p] is None", "(Not available for remote commands) You can also override the", "drop from the container. type: list elements: str cgroup_parent: description:", "self.info['effectivecaps'] or [] after = before[:] if self.module.params['cap_drop'] is not", "return c def addparam_device_write_bps(self, c): for dev in self.params['device_write_bps']: c", "str init_path: description: - Path to the container-init binary. type:", "enabled. The disabled option will force the container to not", "is false. type: bool uidmap: description: - Run the container", "NUMA systems. type: str detach: description: - Run container in", "Memory soft limit (format 100m, where unit = b, k,", "false. type: bool oom_score_adj: description: - Tune the host's OOM", "log_driver: description: - Logging driver. Used to set the log", "seconds) to stop a container. Default is 10. type: int", "rc, out, err = module.run_command([module_exec, 'image', 'pull', image]) if rc", "before, after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('devices', before, after) def", "supported from podman \" \"version %s only! Current version is", "\"\"\" super(PodmanManager, self).__init__() self.module = module self.results = { 'changed':", "and disabled, which the default being enabled. The disabled option", "- Any additionl command options you want to pass to", "mode for the container. It defaults to the PODMAN_USERNS environment", "ports: - \"8080:9000\" - \"127.0.0.1:8081:9001/udp\" env: SECRET_KEY: \"ssssh\" BOOLEAN_KEY: \"yes\"", "under the Apache License, Version 2.0 (the \"License\"); you may", "def diffparam_conmon_pidfile(self): before = self.info['conmonpidfile'] if self.module.params['conmon_pidfile'] is None: after", "'lite mode' assume all images from different registries are the", "in self.params['volumes_from']: c += ['--volumes-from', vol] return c def addparam_workdir(self,", "def construct_command_from_params(self): \"\"\"Create a podman command from given module parameters.", "limit the amount of time in a given CPU period", "domain) type: str entrypoint: description: - Overwrite the default ENTRYPOINT", "the specified name will be stopped and removed. - I(present)", "return self._diff_update_and_compare('rm', before, after) def diffparam_security_opt(self): before = self.info['hostconfig']['securityopt'] after", "m in before: if m['type'] == 'volume': volumes.append([m['name'], m['destination']]) else:", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "podman_container: name: myapplication image: redis state: started restart: yes etc_hosts:", "in ['start', 'stop', 'delete']: return self.start_stop_delete() if self.action in ['create',", "= self.module.params['image'] image_actions = ensure_image_exists(self.module, self.image) self.results['actions'] += image_actions self.state", "func in dir(self) if callable(getattr(self, func)) and func.startswith( \"diffparam\")] fail_fast", "str healthcheck_retries: description: - The number of retries allowed before", "def diffparam_memory(self): before = str(self.info['hostconfig']['memory']) after = self.params['memory'] return self._diff_update_and_compare('memory',", "- Container host name. Sets the container host name that", "container that forwards signals and reaps processes. type: str init_path:", "self._diff_update_and_compare('tty', before, after) def diffparam_user(self): before = self.info['config']['user'] if self.module.params['user']", "podman how to handle the builtin image volumes. The options", "description: - If true, the first argument refers to an", "self.params['healthcheck_retries']] def addparam_healthcheck_start_period(self, c): return c + ['--healthcheck-start-period', self.params['healthcheck_start_period']] def", "and 100. type: int mount: description: - Attach a filesystem", "required by applicable law or agreed to in writing, software", "into the container if set for the podman process. This", "fail. Arguments: module {obj} -- ansible module object image {str}", "log_path def diffparam_log_opt(self): before = self.info['logpath'] if self.module.params['log_opt'] in [None,", "image to get the default command if self.module.params['command'] is not", "cap_drop in self.params['cap_drop']: c += ['--cap-drop', cap_drop] return c def", "return c + ['--publish-all=%s' % self.params['publish_all']] def addparam_read_only(self, c): return", "after) def diffparam_cpu_rt_period(self): before = self.info['hostconfig']['cpurealtimeperiod'] after = self.params['cpu_rt_period'] return", "return False def diffparam_annotation(self): before = self.info['config']['annotations'] or {} after", "description: - Default is to create a private IPC namespace", "addparam_security_opt(self, c): for secopt in self.params['security_opt']: c += ['--security-opt', secopt]", "the pod name with \"new:\" type: str privileged: description: -", "own args for podman command def addparam_cmd_args(self, c): return c", "\"\"\"Module manager class. Defines according to parameters what actions should", "addparam_log_driver(self, c): return c + ['--log-driver', self.params['log_driver']] def addparam_log_opt(self, c):", "nothing was done \"\"\" image_actions = [] module_exec = module.params['executable']", "0 }, \"Volumes\": null, \"WorkingDir\": \"/\" }, \"ConmonPidFile\": \"...\", \"Created\":", "addparam_uidmap(self, c): for uidmap in self.params['uidmap']: c += ['--uidmap', uidmap]", "with '' if you don't wish to set the search", "agreed to in writing, software # distributed under the License", "will be used. - Can also be an image ID.", "name: mycontainer state: stopped - name: Start 4 load-balanced containers", "the container.\"\"\" self.delete() self.run() def restart(self): \"\"\"Restart the container.\"\"\" self.stop()", "-- name of container \"\"\" super(PodmanContainer, self).__init__() self.module = module", "bool etc_hosts: description: - Dict of host-to-IP mappings, where each", "execute(self): \"\"\"Execute the desired action according to map of actions", "None) for param in params_set: func_name = \"_\".join([\"addparam\", param]) if", "is running now.\"\"\" return self.exists and self.info['State']['Running'] @property def stopped(self):", "init_path: description: - Path to the container-init binary. type: str", "container in an existing pod. If you want podman to", "than 0. Unit is optional and can be b (bytes),", "the specified command. type: str userns: description: - Set the", "'env_file', 'env_host', \"ulimit\", # Defaults depend on user and platform,", "container exists and is not running now.\"\"\" return self.exists and", "rc == 0: return image_actions rc, out, err = module.run_command([module_exec,", "state: present image: ubuntu:14.04 command: \"sleep 1d\" - name: Stop", "= ['rm', '-f', self.params['name']] return [to_bytes(i, errors='surrogate_or_strict') for i in", "self.version).default_dict() for p in self.module.params: if self.module.params[p] is None and", "c): return c + ['--detach=%s' % self.params['detach']] def addparam_detach_keys(self, c):", "description: - Override command of container. Can be a string", "return c + ['--ipc', self.params['ipc']] def addparam_kernel_memory(self, c): return c", "self.params['read_only']] def addparam_read_only_tmpfs(self, c): return c + ['--read-only-tmpfs=%s' % self.params['read_only_tmpfs']]", "not running now.\"\"\" return self.exists and not self.info['State']['Running'] def get_info(self):", "- Note that facts are part of the registered vars", "str(k).lower(): str(v).lower() for k, v in self.params['env'].items() }) return self._diff_update_and_compare('env',", "if rc != 0: module.fail_json(msg=\"Can't pull image %s\" % image,", "import AnsibleModule from ansible.module_utils._text import to_bytes, to_native ANSIBLE_METADATA = {", "0, \"FinishedAt\": \"2019-06-17T19:13:10.157518963+03:00\", \"Healthcheck\": { \"FailingStreak\": 0, \"Log\": null, \"Status\":", "on the host system. type: list elements: str aliases: -", "Do not create /etc/hosts for the container Default is false.", "is not None: for c in [\"cap_\" + i.lower() for", "from ansible.module_utils._text import to_bytes, to_native ANSIBLE_METADATA = { 'metadata_version': '1.0',", "dev] return c def addparam_dns(self, c): return c + ['--dns',", "c): return c + ['--oom-score-adj', self.params['oom_score_adj']] def addparam_pid(self, c): return", "The default is true. type: bool stop_signal: description: - Signal", "description: - Repository path (or image name) and tag used", "before = str(self.info['hostconfig']['memoryswap']) after = self.params['memory_swap'] if (self.module.params['memory_swap'] is None", "Default is ``${XDG_RUNTIME_DIR}/containers/auth.json`` (Not available for remote commands) You can", "self.container.stopped and self.container.different: self.container.recreate() self.results['actions'].append('recreated %s' % self.container.name) self.update_container_result() elif", "def addparam_env_file(self, c): return c + ['--env-file', self.params['env_file']] def addparam_env_host(self,", "after = self.params['memory'] return self._diff_update_and_compare('memory', before, after) def diffparam_memory_swap(self): #", "0, \"Rootfs\": \"\", \"State\": { \"Dead\": false, \"Error\": \"\", \"ExitCode\":", "true, keep stdin open even if not attached. The default", "}, \"HostConfig\": { ... }, \"HostnamePath\": \"...\", \"HostsPath\": \"...\", \"ID\":", "['--ip', self.params['ip']] def addparam_ipc(self, c): return c + ['--ipc', self.params['ipc']]", "retries allowed before a healthcheck is considered to be unhealthy.", "to guess } def defaultize(self): params_with_defaults = {} self.default_dict =", "in b_command]) self.module.log(\"PODMAN-CONTAINER-DEBUG: %s\" % full_cmd) self.actions.append(full_cmd) if not self.module.check_mode:", "a container to bootstrap. The value can be expressed in", "module object name {str} -- name of container \"\"\" super(PodmanContainer,", "['--stop-timeout', self.params['stop_timeout']] def addparam_subgidname(self, c): return c + ['--subgidname', self.params['subgidname']]", "c + ['--kernel-memory', self.params['kernel_memory']] def addparam_label(self, c): for label in", "restart gidmap: description: - Run the container in a new", "Accepts an integer between 0 and 100. type: int mount:", "version return self.defaults class PodmanContainerDiff: def __init__(self, module, info, podman_version):", "\"\"\" module: podman_container author: - \"<NAME> (@sshnaidm)\" version_added: '2.9' short_description:", "def addparam_gidmap(self, c): return c + ['--gidmap', self.params['gidmap']] def addparam_group_add(self,", "Run container in systemd mode. The default is true. type:", "+= ['--device-write-bps', dev] return c def addparam_device_write_iops(self, c): for dev", "related to podman version return self.defaults class PodmanContainerDiff: def __init__(self,", "in before] after = self.params['device_write_bps'] or [] before, after =", "This is the default for rootless containers type: list elements:", "c def addparam_ulimit(self, c): for u in self.params['ulimit']: c +=", "images in idempotency by taking into account a full name", "exit with a non-0 exit code, retrying indefinitely or until", "per second) from a device (e.g. device-read-bps /dev/sda:1mb) type: list", "follow when containers exit. Restart policy will not take effect", "self.container = PodmanContainer(self.module, self.name) def update_container_result(self, changed=True): \"\"\"Inspect the current", "description: - Mount volumes from the specified container(s). type: list", "podman CLI command. Arguments: action {str} -- action type from", "diffparam_etc_hosts(self): if self.info['hostconfig']['extrahosts']: before = dict([i.split(\":\") for i in self.info['hostconfig']['extrahosts']])", "get_info(self): \"\"\"Inspect container and gather info about it.\"\"\" rc, out,", "or ignore (default bind) type: str choices: - 'bind' -", "+ ['--env-file', self.params['env_file']] def addparam_env_host(self, c): self.check_version('--env-host', minv='1.5.0') return c", "self.module.check_mode: rc, out, err = self.module.run_command( [self.module.params['executable'], b'container'] + b_command,", "self._diff_update_and_compare('ipc', before, after) def diffparam_label(self): before = self.info['config']['labels'] or {}", "str memory_reservation: description: - Memory soft limit (format 100m, where", "the host system. type: list elements: str aliases: - exposed", "self.params['read_only_tmpfs']] def addparam_restart_policy(self, c): return c + ['--restart=%s' % self.params['restart_policy']]", "c): return c + ['--healthcheck-interval', self.params['healthcheck_interval']] def addparam_healthcheck_retries(self, c): return", "return c + ['--cpu-period', self.params['cpu_period']] def addparam_cpu_rt_period(self, c): return c", "c): return c + ['--stop-signal', self.params['stop_signal']] def addparam_stop_timeout(self, c): return", "= self.info['config']['image'] after = self.params['image'] mode = self.params['image_strict'] if mode", "ubuntu:14.04 command: \"sleep 1d\" - name: Stop a container podman_container:", "running. Use force_restart to force a matching container to be", "{ \"FailingStreak\": 0, \"Log\": null, \"Status\": \"\" }, \"OOMKilled\": false,", "address for the container, for example '10.88.64.128'. Can only be", "Container present podman_container: name: mycontainer state: present image: ubuntu:14.04 command:", "= self.info['hostconfig']['autoremove'] after = self.params['rm'] return self._diff_update_and_compare('rm', before, after) def", "\"Error\": \"\", \"ExitCode\": 0, \"FinishedAt\": \"2019-06-17T19:13:10.157518963+03:00\", \"Healthcheck\": { \"FailingStreak\": 0,", "is 3. type: int healthcheck_start_period: description: - The initialization time", "{}, } self.name = self.module.params['name'] self.executable = \\ self.module.get_bin_path(self.module.params['executable'], required=True)", "used and optionally the groupname or GID for the specified", "# # Licensed under the Apache License, Version 2.0 (the", "before else: after = self.params['user'] return self._diff_update_and_compare('user', before, after) def", "before, after) def diffparam_log_driver(self): before = self.info['hostconfig']['logconfig']['type'] after = self.params['log_driver']", "as read only. Default is false type: bool read_only_tmpfs: description:", "Current version is %s\" % ( param, minv, self.podman_version)) if", "c): return c + ['--restart=%s' % self.params['restart_policy']] def addparam_rm(self, c):", "Path of the authentication file. Default is ``${XDG_RUNTIME_DIR}/containers/auth.json`` (Not available", "c + ['--sig-proxy=%s' % self.params['sig_proxy']] def addparam_stop_signal(self, c): return c", "make_absent(self): \"\"\"Run actions if desired state is 'absent'.\"\"\" if not", "if self.module.params['user'] is None and before: after = before else:", "single character or ctrl-value type: str device: description: - Add", "diffparam_network(self): before = [self.info['hostconfig']['networkmode']] after = self.params['network'] return self._diff_update_and_compare('network', before,", "['--env-file', self.params['env_file']] def addparam_env_host(self, c): self.check_version('--env-host', minv='1.5.0') return c +", "moves it to a stopped state. type: str default: started", "builtin image volumes. The options are bind, tmpfs, or ignore", "exposed_ports force_restart: description: - Force restart of container. type: bool", "example log_driver \"k8s-file\". type: str choices: - k8s-file - journald", "the unit, the system uses bytes. If you omit the", "default working directory for running binaries within a container is", "def check_version(self, param, minv=None, maxv=None): if minv and LooseVersion(minv) >", "\"OpenStdin\": false, \"StdinOnce\": false, \"StopSignal\": 15, \"Tty\": false, \"User\": {", "str sig_proxy: description: - Proxy signals sent to the podman", "# under the License. # flake8: noqa: E501 from __future__", "- \"8080:9000\" - \"127.0.0.1:8081:9001/udp\" env: SECRET_KEY: \"ssssh\" BOOLEAN_KEY: \"yes\" -", "limit. type: str cpuset_cpus: description: - CPUs in which to", "Working directory inside the container. The default working directory for", "self._diff_update_and_compare('privileged', before, after) def diffparam_pid(self): before = self.info['hostconfig']['pidmode'] after =", "'started': self.make_started, 'absent': self.make_absent, 'stopped': self.make_stopped } process_action = states_map[self.state]", "stack. * <network-name>|<network-id> connect to a user-defined network * ns:<path>", "is None: after = before else: after = self.params['conmon_pidfile'] return", "version is %s\" % ( param, minv, self.podman_version)) if maxv", "container matches the name but the provided configuration does not", "like 2m3s. The default value is 0s type: str healthcheck_timeout:", "remove the container when it exits. The default is false.", "of arguments for podman CLI command. Arguments: action {str} --", "before = str(self.info['hostconfig']['memoryreservation']) after = self.params['memory_reservation'] return self._diff_update_and_compare('memory_reservation', before, after)", "# \"CMD-SHELL\" and the second one is the actual healthcheck", "Licensed under the Apache License, Version 2.0 (the \"License\"); you", "self.container.actions}) self.module.exit_json(**self.results) def execute(self): \"\"\"Execute the desired action according to", "self.module.params['force_restart'] self.recreate = self.module.params['recreate'] self.container = PodmanContainer(self.module, self.name) def update_container_result(self,", "perform - start, create, stop, run, delete \"\"\" b_command =", "ansible.module_utils._text import to_bytes, to_native ANSIBLE_METADATA = { 'metadata_version': '1.0', 'status':", "c): for dev in self.params['device_write_iops']: c += ['--device-write-iops', dev] return", "removed. - I(present) - Asserts the existence of a container", "IPC namespace (POSIX SysV IPC) for the container type: str", "OpenStack Foundation # All Rights Reserved. # # Licensed under", "def start(self): \"\"\"Start the container.\"\"\" self._perform_action('start') def create(self): \"\"\"Create the", "dev in self.params['device_write_iops']: c += ['--device-write-iops', dev] return c def", "self.params['log_opt']] def addparam_memory(self, c): return c + ['--memory', self.params['memory']] def", "states to force the re-creation of an existing container. type:", "_get_podman_version(self): rc, out, err = self.module.run_command( [self.module.params['executable'], b'--version']) if rc", "\"Dependencies\": [], \"Driver\": \"overlay\", \"EffectiveCaps\": [ \"CAP_CHOWN\", ... ], \"ExecIDs\":", "\"\"\" facts = self.container.get_info() if changed else self.container.info out, err", "sysctl in self.params['sysctl'].items(): c += ['--sysctl', b\"=\".join([to_bytes(k, errors='surrogate_or_strict') for k", "str entrypoint: description: - Overwrite the default ENTRYPOINT of the", "# Healthcheck is only defined in container config if a", "executable if it is not in the C($PATH) on the", "c): return c + ['--dns', ','.join(self.params['dns'])] def addparam_dns_option(self, c): return", "command \"\"\" if self.action in ['start', 'stop', 'delete']: return self.start_stop_delete()", "name: ohno state: absent - name: Writing output podman_container: name:", "double the value of --memory Note - idempotency is supported", "mount \"type=bind,source=/path/on/host,destination=/path/in/container\" type: str network: description: - Set the Network", "self.params['healthcheck_timeout']] def addparam_hostname(self, c): return c + ['--hostname', self.params['hostname']] def", "if container is running now.\"\"\" return self.exists and self.info['State']['Running'] @property", "self.params['env_host'] return self._diff_update_and_compare('env_host', before, after) def diffparam_blkio_weight(self): before = self.info['hostconfig']['blkioweight']", "addparam_group_add(self, c): for g in self.params['group_add']: c += ['--group-add', g]", "when image' ' is not specified!') if not self.container.exists: self.container.create()", "% self.module.params['executable']) return out.split(\"version\")[1].strip() def _perform_action(self, action): \"\"\"Perform action with", "add to the container. type: list elements: str cap_drop: description:", "'start']: cmd = [self.action, self.params['name']] return [to_bytes(i, errors='surrogate_or_strict') for i", "- Limit read rate (bytes per second) from a device", "self.params['sig_proxy']] def addparam_stop_signal(self, c): return c + ['--stop-signal', self.params['stop_signal']] def", "image_strict: description: - Whether to compare images in idempotency by", "the container. For example log_driver \"k8s-file\". type: str choices: -", "str ipc: description: - Default is to create a private", "c + ['--memory', self.params['memory']] def addparam_memory_reservation(self, c): return c +", "for i in self.params if self.params[i] is not None) for", "%s container %s\" % (action, self.name), stdout=out, stderr=err) def run(self):", "the system uses 64m type: str sig_proxy: description: - Proxy", "'container': facts, 'podman_actions': self.container.actions}, stdout=out, stderr=err) if self.container.diff: self.results.update({'diff': self.container.diff})", "action with container. Arguments: action {str} -- action to perform", "if container exists.\"\"\" return bool(self.info != {}) @property def different(self):", "state. type: str default: started choices: - absent - present", "i in self.info['hostconfig']['devices']] after = [\":\".join(i.split(\":\")[:2]) for i in self.params['device']]", "Parameter has limited idempotency, unable to guess the default log_path", "# In a idempotency 'lite mode' assume all images from", "in inspection \"network\": [\"default\"], \"oom_score_adj\": 0, \"pid\": \"\", \"privileged\": False,", "hostPort:containerPort | containerPort type: list elements: str aliases: - ports", "list elements: str aliases: - volumes volumes_from: description: - Mount", "param, minv, self.podman_version)) def addparam_annotation(self, c): for annotate in self.params['annotation'].items():", "\"HostnamePath\": \"...\", \"HostsPath\": \"...\", \"ID\": \"...\", \"Image\": \"...\", \"ImageName\": \"docker.io/library/busybox:latest\",", "def addparam_cpus(self, c): return c + ['--cpus', self.params['cpus']] def addparam_cpuset_cpus(self,", "diffparam_memory(self): before = str(self.info['hostconfig']['memory']) after = self.params['memory'] return self._diff_update_and_compare('memory', before,", "secopt] return c def addparam_shm_size(self, c): return c + ['--shm-size',", "\"\"\" container: description: - Facts representing the current state of", "before == [] and self.module.params['blkio_weight_device'] is None: after = []", "self.params['gidmap']] def addparam_group_add(self, c): for g in self.params['group_add']: c +=", "'present'] and \\ not module.params['image']: module.fail_json(msg=\"State '%s' required image to", "that the container is first I(present), and then if the", "addparam_detach(self, c): return c + ['--detach=%s' % self.params['detach']] def addparam_detach_keys(self,", "podman_container: name: ohno state: absent - name: Writing output podman_container:", "before.replace(\":latest\", \"\") after = after.replace(\":latest\", \"\") before = before.split(\"/\")[-1] after", "\"k8s-file\", \"memory\": \"0\", \"memory_swap\": \"0\", \"memory_reservation\": \"0\", # \"memory_swappiness\": -1,", "%s' % self.container.name) self.update_container_result() if self.container.stopped: self.update_container_result(changed=False) elif self.container.running: self.container.stop()", "container. type: list elements: str cap_drop: description: - List of", "\"CAP_CHOWN\", ... ], \"ExecIDs\": [], \"ExitCommand\": [ \"/usr/bin/podman\", \"--root\", ...", "to a container, pass dictionary of label names and values", "addparam_blkio_weight_device(self, c): for blkio in self.params['blkio_weight_device'].items(): c += ['--blkio-weight-device', ':'.join(blkio)]", "= module.params['executable'] if not image: return image_actions rc, out, err", "elif self.container.running: self.container.stop() self.results['actions'].append('stopped %s' % self.container.name) self.update_container_result() def make_absent(self):", "for running binaries within a container is the root directory", "check_version(self, param, minv=None, maxv=None): if minv and LooseVersion(minv) > LooseVersion(", "here any changes to self.defaults related to podman version return", "security_opt: description: - Security Options. For example security_opt \"seccomp=unconfined\" type:", "unable to guess the default log_path def diffparam_log_opt(self): before =", "in writing, software # distributed under the License is distributed", "self._diff_update_and_compare('group_add', before, after) # Healthcheck is only defined in container", "to podman command, cmd_args - ['--other-param', 'value'] Be aware module", "blkio in self.params['blkio_weight_device'].items(): c += ['--blkio-weight-device', ':'.join(blkio)] return c def", "object image {str} -- name of image Returns: list --", "on the default bridge * none no networking * container:<name|id>", "the default command if self.module.params['command'] is not None: before =", "return c + ['--privileged=%s' % self.params['privileged']] def addparam_publish(self, c): for", "%s\" % (action, self.name), stdout=out, stderr=err) def run(self): \"\"\"Run the", "diffparam_conmon_pidfile(self): before = self.info['conmonpidfile'] if self.module.params['conmon_pidfile'] is None: after =", "list of arguments for podman CLI command. Arguments: action {str}", "before, after) def diffparam_rm(self): before = self.info['hostconfig']['autoremove'] after = self.params['rm']", "str kernel_memory: description: - Kernel memory limit (format <number>[<unit>], where", "requested config. Image version will be taken into account when", "networks in inspection \"network\": [\"default\"], \"oom_score_adj\": 0, \"pid\": \"\", \"privileged\":", "}, \"StaticDir\": \"...\" ... }' \"\"\" class PodmanModuleParams: \"\"\"Creates list", "environment variables in container. Defaults to false. type: bool etc_hosts:", "specified via 'network:', and if the container is not joining", "vol: c += ['--volume', vol] return c def addparam_volumes_from(self, c):", "Facts representing the current state of the container. Matches the", "if rc == 0 else {} def _get_podman_version(self): rc, out,", "module object image {str} -- name of image Returns: list", "def addparam_cpuset_mems(self, c): return c + ['--cpuset-mems', self.params['cpuset_mems']] def addparam_detach(self,", "for g in self.params['group_add']: c += ['--group-add', g] return c", "used. - Can also be an image ID. If this", "\"privileged\": False, \"rm\": False, \"security_opt\": [], \"stop_signal\": 15, \"tty\": False,", "str detach: description: - Run container in detach mode type:", "swap LIMIT should always be larger than -m (--memory) value.", "a tmpfs mount. For example tmpfs \"/tmp\" \"rw,size=787448k,mode=1777\" type: dict", "variables that are available for the process that will be", "and self.params['memory'] != 0 and self.params['memory'].isdigit()): after = str(int(self.params['memory']) *", "be used. - Can also be an image ID. If", "addparam_kernel_memory(self, c): return c + ['--kernel-memory', self.params['kernel_memory']] def addparam_label(self, c):", "self.info['hostconfig']['blkiodevicereadbps'] or [] before = [\"%s:%s\" % (i['path'], i['rate']) for", "if set for the podman process. This can be disabled", "passed in include http_proxy, https_proxy, ftp_proxy, no_proxy, and also the", "0, \"pid\": \"\", \"privileged\": False, \"rm\": False, \"security_opt\": [], \"stop_signal\":", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "- Name of the container required: True type: str executable:", "for label in self.params['label'].items(): c += ['--label', b'='.join([to_bytes(l, errors='surrogate_or_strict') for", "self.container.exists: self.container.create() self.results['actions'].append('created %s' % self.container.name) self.update_container_result() if self.container.stopped: self.update_container_result(changed=False)", "c + ['--oom-score-adj', self.params['oom_score_adj']] def addparam_pid(self, c): return c +", "addparam_init(self, c): return c + ['--init', self.params['init']] def addparam_init_path(self, c):", "type: list elements: str aliases: - volumes volumes_from: description: -", "\"Image\": \"docker.io/library/busybox:latest\", \"Labels\": null, \"OpenStdin\": false, \"StdinOnce\": false, \"StopSignal\": 15,", "after) def diffparam_user(self): before = self.info['config']['user'] if self.module.params['user'] is None", "def diffparam_rm(self): before = self.info['hostconfig']['autoremove'] after = self.params['rm'] return self._diff_update_and_compare('rm',", "return c def addparam_device_read_iops(self, c): for dev in self.params['device_read_iops']: c", "None: after = before else: after = self.params['conmon_pidfile'] return self._diff_update_and_compare('conmon_pidfile',", "contact maintainers ASAP!\") def main(): module = AnsibleModule( argument_spec=yaml.safe_load(DOCUMENTATION)['options'], mutually_exclusive=(", "which to allow execution (0-3, 0,1) type: str cpuset_mems: description:", "desired action according to map of actions & states.\"\"\" states_map", "Publish all exposed ports to random ports on the host", "directory for running binaries within a container is the root", "-- ansible module object image {str} -- name of image", "self._diff_update_and_compare('cidfile', before, after) def diffparam_command(self): # TODO(sshnaidm): to inspect image", "= self.info['config']['cmd'] after = self.params['command'] if isinstance(after, str): after =", "c def addparam_cgroups(self, c): self.check_version('--cgroups', minv='1.6.0') return c + ['--cgroups=%s'", "+ ['--subuidname', self.params['subuidname']] def addparam_sysctl(self, c): for sysctl in self.params['sysctl'].items():", "\"Args\": [ \"sh\" ], \"BoundingCaps\": [ \"CAP_CHOWN\", ... ], \"Config\":", "is false. When set to true, keep stdin open even", "default, the swap LIMIT will be set to double the", "this is set. type: list elements: str conmon_pidfile: description: -", "new user namespace using the supplied mapping. type: str group_add:", "c): for dev in self.params['device_read_bps']: c += ['--device-read-bps', dev] return", "which to allow execution (0-3, 0,1). Only effective on NUMA", "then mount a read-write tmpfs on /run, /tmp, and /var/tmp.", "if container is different.\"\"\" diffcheck = PodmanContainerDiff(self.module, self.info, self.version) is_different", "# Unless required by applicable law or agreed to in", "restart Podman containers. type: path command: description: - Override command", "c + ['--detach=%s' % self.params['detach']] def addparam_detach_keys(self, c): return c", "= self.params['hostname'] or before return self._diff_update_and_compare('hostname', before, after) def diffparam_image(self):", "in self.params['ulimit']: c += ['--ulimit', u] return c def addparam_user(self,", "self.info['hostconfig']['blkioweight'] after = self.params['blkio_weight'] return self._diff_update_and_compare('blkio_weight', before, after) def diffparam_blkio_weight_device(self):", "+ ['--detach-keys', self.params['detach_keys']] def addparam_device(self, c): for dev in self.params['device']:", "is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES", "join * slirp4netns use slirp4netns to create a user network", "idempotency, it can't guess default values def diffparam_env(self): env_before =", "\"PATH=/usr/sbin:/usr/bin:/sbin:/bin\", \"TERM=xterm\", \"HOSTNAME=\", \"container=podman\" ], \"Hostname\": \"\", \"Image\": \"docker.io/library/busybox:latest\", \"Labels\":", "container host name that is available inside the container. type:", "self.params['memory']] def addparam_memory_reservation(self, c): return c + ['--memory-reservation', self.params['memory_reservation']] def", "msg=\"Can't %s container %s\" % (action, self.name), stdout=out, stderr=err) def", "return self._diff_update_and_compare('cidfile', before, after) def diffparam_command(self): # TODO(sshnaidm): to inspect", "module {obj} -- ansible module object image {str} -- name", "0: return image_actions rc, out, err = module.run_command([module_exec, 'image', 'pull',", "['--cgroupns=%s' % self.params['cgroupns']] def addparam_cgroup_parent(self, c): return c + ['--cgroup-parent',", "self.container.exists: self.results.update({'changed': False}) elif self.container.exists: self.container.delete() self.results['actions'].append('deleted %s' % self.container.name)", "int cpu_rt_runtime: description: - Limit the CPU real-time runtime in", "def diffparam_device_read_iops(self): before = self.info['hostconfig']['blkiodevicereadiops'] or [] before = [\"%s:%s\"", "- Restart containers when they exit with a non-0 exit", "EXAMPLES = \"\"\" - name: Run container podman_container: name: container", "['--mount', self.params['mount']] def addparam_network(self, c): return c + ['--network', \",\".join(self.params['network'])]", "self.info['effectivecaps'] or [] after = [] if self.module.params['cap_add'] is not", "false. type: bool etc_hosts: description: - Dict of host-to-IP mappings,", "unlimited pids for the container. type: str pod: description: -", "self.params['blkio_weight'] return self._diff_update_and_compare('blkio_weight', before, after) def diffparam_blkio_weight_device(self): before = self.info['hostconfig']['blkioweightdevice']", "Re-create a redis container podman_container: name: myredis image: redis command:", "\"Healthcheck\": { \"FailingStreak\": 0, \"Log\": null, \"Status\": \"\" }, \"OOMKilled\":", "c += ['--ulimit', u] return c def addparam_user(self, c): return", "containers type: list elements: str aliases: - net no_hosts: description:", "+ ['--http-proxy=%s' % self.params['http_proxy']] def addparam_image_volume(self, c): return c +", "'absent'.\"\"\" if not self.container.exists: self.results.update({'changed': False}) elif self.container.exists: self.container.delete() self.results['actions'].append('deleted", "bool(self.info != {}) @property def different(self): \"\"\"Check if container is", "Use force_restart to force a matching container to be stopped", "self.params['cpuset_mems']] def addparam_detach(self, c): return c + ['--detach=%s' % self.params['detach']]", "variable. ``export REGISTRY_AUTH_FILE=path`` type: path blkio_weight: description: - Block IO", "= \"_\".join([\"addparam\", param]) if func_name in all_param_methods: cmd = getattr(self,", "containers (accepts -1000 to 1000) type: int pid: description: -", "after = self.params['healthcheck'] or before return self._diff_update_and_compare('healthcheck', before, after) #", "no additional CNI networks to join were specified via 'network:',", "type: list elements: str workdir: description: - Working directory inside", "default value is 30s type: str hostname: description: - Container", "str rm: description: - Automatically remove the container when it", "ports, to the host. Format - ip:hostPort:containerPort | ip::containerPort |", "% self.container.name) self.update_container_result() elif self.container.stopped and self.container.different: self.container.recreate() self.results['actions'].append('recreated %s'", "= sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('cap_drop', before, after) def diffparam_cgroup_parent(self): before", "out self.stderr = err if rc != 0: self.module.fail_json( msg=\"Can't", "a redis container podman_container: name: myredis image: redis command: redis-server", "not in out: self.module.fail_json(msg=\"%s run failed!\" % self.module.params['executable']) return out.split(\"version\")[1].strip()", "False restart_policy: description: - Restart policy to follow when containers", "before, after) def diffparam_oom_score_adj(self): before = self.info['hostconfig']['oomscoreadj'] after = self.params['oom_score_adj']", "def addparam_pids_limit(self, c): return c + ['--pids-limit', self.params['pids_limit']] def addparam_pod(self,", "in self.params['publish']: c += ['--publish', pub] return c def addparam_publish_all(self,", "+ ['--cpu-period', self.params['cpu_period']] def addparam_cpu_rt_period(self, c): return c + ['--cpu-rt-period',", "errors='surrogate_or_strict') for k in sysctl])] return c def addparam_systemd(self, c):", "limited idempotency, unable to guess the default log_path def diffparam_log_opt(self):", "getattr(self, func_name) if dff_func(): if fail_fast: return True else: different", "list elements: str dns_option: description: - Set custom DNS options", "['--read-only=%s' % self.params['read_only']] def addparam_read_only_tmpfs(self, c): return c + ['--read-only-tmpfs=%s'", "the registry. If no tag is included, C(latest) will be", "the cgroups path of the init process. Cgroups will be", "than -m (--memory) value. By default, the swap LIMIT will", "is_different(self): diff_func_list = [func for func in dir(self) if callable(getattr(self,", "in systemd mode. The default is true. type: bool tmpfs:", "[] before, after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('device_read_iops', before, after)", "- Publish all exposed ports to random ports on the", "\"\", \"kernelmemory\": \"0\", \"log_driver\": \"k8s-file\", \"memory\": \"0\", \"memory_swap\": \"0\", \"memory_reservation\":", "self.info['hostconfig']['cpusetcpus'] after = self.params['cpuset_cpus'] return self._diff_update_and_compare('cpuset_cpus', before, after) def diffparam_cpuset_mems(self):", "host. Format - ip:hostPort:containerPort | ip::containerPort | hostPort:containerPort | containerPort", "if this is set. type: list elements: str conmon_pidfile: description:", "network stack. This is the default for rootless containers type:", "run, delete \"\"\" b_command = PodmanModuleParams(action, self.module.params, self.version, self.module, ).construct_command_from_params()", "the container. bind or tmpfs For example mount \"type=bind,source=/path/on/host,destination=/path/in/container\" type:", "before = self.info['hostconfig']['groupadd'] after = self.params['group_add'] return self._diff_update_and_compare('group_add', before, after)", "shares (relative weight) type: int cpus: description: - Number of", "self.info['config']['healthcheck']['test'][1] else: before = '' after = self.params['healthcheck'] or before", "b\"=\".join([to_bytes(k, errors='surrogate_or_strict') for k in sysctl])] return c def addparam_systemd(self,", "default: 'podman' type: str state: description: - I(absent) - A", "diffparam_healthcheck(self): if 'healthcheck' in self.info['config']: # the \"test\" key is", "= self.params['cidfile'] return self._diff_update_and_compare('cidfile', before, after) def diffparam_command(self): # TODO(sshnaidm):", "{} after = before.copy() if self.module.params['annotation'] is not None: after.update(self.params['annotation'])", "self.defaults class PodmanContainerDiff: def __init__(self, module, info, podman_version): self.module =", "return c + ['--cpus', self.params['cpus']] def addparam_cpuset_cpus(self, c): return c", "uidmap] return c def addparam_ulimit(self, c): for u in self.params['ulimit']:", "the re-creation of the matching container. - I(started) - Asserts", "], \"Name\": \"myservice\", \"Namespace\": \"\", \"NetworkSettings\": { \"Bridge\": \"\", ...", "before, after) def diffparam_cpu_rt_period(self): before = self.info['hostconfig']['cpurealtimeperiod'] after = self.params['cpu_rt_period']", "path cgroupns: description: - Path to cgroups under which the", "# \"memory_swappiness\": -1, \"no_hosts\": False, # libpod issue with networks", "helpful for investigations. type: bool default: False detach_keys: description: -", "self.results.update({'changed': True}) self.results.update({'container': {}, 'podman_actions': self.container.actions}) self.module.exit_json(**self.results) def execute(self): \"\"\"Execute", "the supplied mapping. type: list ulimit: description: - Ulimit options", "Overwrite the default ENTRYPOINT of the image type: str env:", "swap LIMIT will be set to double the value of", "supplied mapping. type: list ulimit: description: - Ulimit options type:", "'present': self.make_started, 'started': self.make_started, 'absent': self.make_absent, 'stopped': self.make_stopped } process_action", "or [] after = self.params['volumes_from'] or [] return self._diff_update_and_compare('volumes_from', before,", "type: list elements: str aliases: - net no_hosts: description: -", "Real Time tasks may consume. type: int cpu_shares: description: -", "- exposed_ports force_restart: description: - Force restart of container. type:", "the default being enabled. The disabled option will force the", "- Path to the container-init binary. type: str interactive: description:", "idempotency 'lite mode' assume all images from different registries are", "return self._diff_update_and_compare('log_driver', before, after) # Parameter has limited idempotency, unable", "= { 'present': self.make_started, 'started': self.make_started, 'absent': self.make_absent, 'stopped': self.make_stopped", "return self._diff_update_and_compare('network', before, after) def diffparam_no_hosts(self): before = not bool(self.info['hostspath'])", "list ulimit: description: - Ulimit options type: list user: description:", "p in self.non_idempotent: if self.module.params[p] is not None and self.module.params[p]", "/dev/sda:1mb) type: list device_read_iops: description: - Limit read rate (IO", "Keep STDIN open even if not attached. The default is", "\"\"\" EXAMPLES = \"\"\" - name: Run container podman_container: name:", "| containerPort type: list elements: str aliases: - ports -", "podman_container: name: myredis image: redis command: redis-server --appendonly yes state:", "SIGTERM. type: int stop_timeout: description: - Timeout (in seconds) to", "\"healthcheck\": \"\", \"ipc\": \"\", \"kernelmemory\": \"0\", \"log_driver\": \"k8s-file\", \"memory\": \"0\",", "c): return c + ['--http-proxy=%s' % self.params['http_proxy']] def addparam_image_volume(self, c):", "else: before = '' after = self.params['healthcheck'] or before return", "configured; otherwise the config key isn't part of the config.", "self.container.start() self.results['actions'].append('started %s' % self.container.name) self.update_container_result() def make_stopped(self): \"\"\"Run actions", "1000) type: int pid: description: - Set the PID mode", "stderr=err) image_actions.append(\"pulled image %s\" % image) return image_actions class PodmanContainer:", "False, # libpod issue with networks in inspection \"network\": [\"default\"],", "env: description: - Set environment variables. This option allows you", "inside of the container. type: dict env_file: description: - Read", "and self.module.params[p] not in [{}, [], '']: different = True", "and thus conflicts with CGroup options cgroupns and cgroup-parent. type:", "not restart containers on exit * on-failure[:max_retries] - Restart containers", "type: list elements: str cap_drop: description: - List of capabilities", "self.results['actions'].append('started %s' % self.container.name) self.update_container_result() elif self.container.stopped and self.container.different: self.container.recreate()", "type: list user: description: - Sets the username or UID", "device (e.g. device-read-bps /dev/sda:1mb) type: list device_read_iops: description: - Limit", "= self.module.run_command( [self.module.params['executable'], b'container'] + b_command, expand_user_and_vars=False) self.stdout = out", "c def addparam_cap_drop(self, c): for cap_drop in self.params['cap_drop']: c +=", "Writing output podman_container: name: myservice image: busybox log_options: path=/var/log/container/mycontainer.json log_driver:", "and not self.info['State']['Running'] def get_info(self): \"\"\"Inspect container and gather info", "c + ['--cpu-rt-period', self.params['cpu_rt_period']] def addparam_cpu_rt_runtime(self, c): return c +", "self.params['tty'] return self._diff_update_and_compare('tty', before, after) def diffparam_user(self): before = self.info['config']['user']", "# Cgroups output is not supported in all versions if", "type: dict cap_add: description: - List of capabilities to add", "is %s\" % ( param, minv, self.podman_version)) def addparam_annotation(self, c):", "exit. Keyword Arguments: changed {bool} -- whether any action was", "make_stopped(self): \"\"\"Run actions if desired state is 'stopped'.\"\"\" if not", "is 'started'.\"\"\" if self.container.running and \\ (self.container.different or self.recreate): self.container.recreate()", "the License. You may obtain # a copy of the", "type: str \"\"\" EXAMPLES = \"\"\" - name: Run container", "\"cpu_quota\": 0, \"cpu_period\": 0, \"cpu_rt_runtime\": 0, \"cpu_rt_period\": 0, \"cpuset_cpus\": \"\",", "self.params['tty']] def addparam_uidmap(self, c): for uidmap in self.params['uidmap']: c +=", "with CGroup options cgroupns and cgroup-parent. type: str choices: -", "addparam_cgroup_parent(self, c): return c + ['--cgroup-parent', self.params['cgroup_parent']] def addparam_cidfile(self, c):", "c + ['--memory-swappiness', self.params['memory_swappiness']] def addparam_mount(self, c): return c +", "diffparam_group_add(self): before = self.info['hostconfig']['groupadd'] after = self.params['group_add'] return self._diff_update_and_compare('group_add', before,", "return c def addparam_authfile(self, c): return c + ['--authfile', self.params['authfile']]", "params_with_defaults[p] = self.default_dict[p] else: params_with_defaults[p] = self.module.params[p] return params_with_defaults def", "def addparam_cpu_rt_runtime(self, c): return c + ['--cpu-rt-runtime', self.params['cpu_rt_runtime']] def addparam_cpu_shares(self,", "self.params['uidmap']: c += ['--uidmap', uidmap] return c def addparam_ulimit(self, c):", "= True return self._diff_update_and_compare('no_hosts', before, after) def diffparam_oom_score_adj(self): before =", "someuser/anotherappimage command: sleep 1d with_sequence: count=4 - name: remove container", "# By default it's twice memory parameter before = str(self.info['hostconfig']['memoryswap'])", "def addparam_rm(self, c): if self.params['rm']: c += ['--rm'] return c", "% self.params['oom_kill_disable']] def addparam_oom_score_adj(self, c): return c + ['--oom-score-adj', self.params['oom_score_adj']]", "/HOST-DIR in the host to /CONTAINER-DIR in the podman container.", "different def ensure_image_exists(module, image): \"\"\"If image is passed, ensure it", "% (i['path'], i['rate']) for i in before] after = self.params['device_read_bps']", "'network:', and if the container is not joining another container's", "started - name: Create a data container podman_container: name: mydata", "is considered failed. Like start-period, the value can be expressed", "dict tty: description: - Allocate a pseudo-TTY. The default is", "False def diffparam_cidfile(self): before = self.info['hostconfig']['containeridfile'] after = self.params['cidfile'] return", "... ], \"GraphDriver\": { ... }, \"HostConfig\": { ... },", "type: list elements: str conmon_pidfile: description: - Write the pid", "after = [i.lower() for i in after.split()] elif isinstance(after, list):", "= params self.action = action self.podman_version = podman_version self.module =", "== ['none']: after = True return self._diff_update_and_compare('no_hosts', before, after) def", "Empty if C(state) is I(absent). returned: always type: dict sample:", "func)) and func.startswith(\"addparam\")] params_set = (i for i in self.params", "\"3300-3310\") to set up port redirection on the host system.", "self.params['detach_keys']] def addparam_device(self, c): for dev in self.params['device']: c +=", "whether any action was performed (default: {True}) \"\"\" facts =", "are also accessible directly as C(podman_container). Note that the returned", "after = self.params['log_opt'].split(\"=\")[1] return self._diff_update_and_compare('log_opt', before, after) def diffparam_memory(self): before", "self.podman_version)) def addparam_annotation(self, c): for annotate in self.params['annotation'].items(): c +=", "\"sleep 1d\" - name: Stop a container podman_container: name: mycontainer", "after = self.params['cpu_rt_runtime'] return self._diff_update_and_compare('cpu_rt_runtime', before, after) def diffparam_cpu_shares(self): before", "return c + self.params['cmd_args'] class PodmanDefaults: def __init__(self, module, podman_version):", "the CPU real-time runtime in microseconds. This flag tells the", "\"volume\": [], \"workdir\": \"/\", } def default_dict(self): # make here", "\"NetworkSettings\": { \"Bridge\": \"\", ... }, \"Path\": \"sh\", \"ProcessLabel\": \"system_u:system_r:container_t:s0:c282,c782\",", "self.info['config']['image'] after = self.params['image'] mode = self.params['image_strict'] if mode is", "flag tell the kernel to restrict the container's Real Time", "is SIGTERM. type: int stop_timeout: description: - Timeout (in seconds)", "pids_limit: description: - Tune the container's pids limit. Set -1", "\"ImageName\": \"docker.io/library/busybox:latest\", \"IsInfra\": false, \"LogPath\": \"/tmp/container/mycontainer.json\", \"MountLabel\": \"system_u:object_r:container_file_t:s0:c282,c782\", \"Mounts\": [", "\"...\", \"Image\": \"...\", \"ImageName\": \"docker.io/library/busybox:latest\", \"IsInfra\": false, \"LogPath\": \"/tmp/container/mycontainer.json\", \"MountLabel\":", "\"\"\"Create the container.\"\"\" self._perform_action('create') def recreate(self): \"\"\"Recreate the container.\"\"\" self.delete()", "b\"=\".join([to_bytes(k, errors='surrogate_or_strict') for k in env_value])] return c def addparam_env_file(self,", "PodmanContainerDiff(self.module, self.info, self.version) is_different = diffcheck.is_different() diffs = diffcheck.diff if", "description: - Memory nodes (MEMs) in which to allow execution", "- pull it or fail. Arguments: module {obj} -- ansible", "Arguments: action {str} -- action to perform - start, create,", "addparam_cidfile(self, c): return c + ['--cidfile', self.params['cidfile']] def addparam_conmon_pidfile(self, c):", "mode for the container type: str pids_limit: description: - Tune", "if self.module.params['command'] is not None: before = self.info['config']['cmd'] after =", "not found, the image will be pulled from the registry.", "work on input vars if module.params['state'] in ['started', 'present'] and", "to join were specified via 'network:', and if the container", "self.make_absent, 'stopped': self.make_stopped } process_action = states_map[self.state] process_action() self.module.fail_json(msg=\"Unexpected logic", "True type: str executable: description: - Path to C(podman) executable", "according to parameters what actions should be applied to container", "Unit is optional and can be b (bytes), k (kilobytes),", "i.lower() for i in self.module.params['cap_add']] after += before before, after", "+ ['--oom-score-adj', self.params['oom_score_adj']] def addparam_pid(self, c): return c + ['--pid',", "Defaults to true type: bool image_volume: description: - Tells podman", "= self.info['config']['env'] or {} before = {i.split(\"=\")[0]: i.split(\"=\")[1] for i", "\"\"\"Check if container exists.\"\"\" return bool(self.info != {}) @property def", "container is not joining another container's network namespace via 'network", "Use recreate to always re-create a matching container, even if", "a non-0 exit code, retrying indefinitely or until the optional", "+ ['--privileged=%s' % self.params['privileged']] def addparam_publish(self, c): for pub in", "\"\") after = after.replace(\":latest\", \"\") before = before.split(\"/\")[-1] after =", "self.update_container_result() def make_absent(self): \"\"\"Run actions if desired state is 'absent'.\"\"\"", "True if container exists and is not running now.\"\"\" return", "variables are passed into the container if set for the", "[to_bytes(i, errors='surrogate_or_strict') for i in cmd] def check_version(self, param, minv=None,", "output. - Note that facts are part of the registered", "= self.info['hostconfig']['blkiodevicereadiops'] or [] before = [\"%s:%s\" % (i['path'], i['rate'])", "only. type: str memory_reservation: description: - Memory soft limit (format", "list): after = [i.lower() for i in after] return self._diff_update_and_compare('command',", "ports - published - published_ports publish_all: description: - Publish all", "consume. type: int cpu_shares: description: - CPU shares (relative weight)", "['--volume', vol] return c def addparam_volumes_from(self, c): for vol in", "be taken into account when comparing configuration. Use the recreate", "to 1000) type: int pid: description: - Set the PID", "- Sets the username or UID used and optionally the", "stopped and removed. - I(present) - Asserts the existence of", "= str(int(self.params['memory']) * 2) return self._diff_update_and_compare('memory_swap', before, after) def diffparam_memory_reservation(self):", "['--memory', self.params['memory']] def addparam_memory_reservation(self, c): return c + ['--memory-reservation', self.params['memory_reservation']]", "full_cmd) self.actions.append(full_cmd) if not self.module.check_mode: rc, out, err = self.module.run_command(", "return self._diff_update_and_compare('cpu_rt_period', before, after) def diffparam_cpu_rt_runtime(self): before = self.info['hostconfig']['cpurealtimeruntime'] after", "after = str(int(self.params['memory']) * 2) return self._diff_update_and_compare('memory_swap', before, after) def", "'10.88.64.128'. Can only be used if no additional CNI networks", "License for the specific language governing permissions and limitations #", "read rate (bytes per second) from a device (e.g. device-read-bps", "- Limit write rate (bytes per second) to a device", "Repository path (or image name) and tag used to create", "podman_version): self.module = module self.version = podman_version self.default_dict = None", "self.image = self.module.params['image'] image_actions = ensure_image_exists(self.module, self.image) self.results['actions'] += image_actions", "cgroup_parent: description: - Path to cgroups under which the cgroup", "errors='surrogate_or_strict') for k in env_value])] return c def addparam_env_file(self, c):", "def diffparam_network(self): before = [self.info['hostconfig']['networkmode']] after = self.params['network'] return self._diff_update_and_compare('network',", "self.params['shm_size']] def addparam_sig_proxy(self, c): return c + ['--sig-proxy=%s' % self.params['sig_proxy']]", "range of ports, to the host. Format - ip:hostPort:containerPort |", "yes expose: - 6379 volumes_from: - mydata - name: Restart", "start(self): \"\"\"Start the container.\"\"\" self._perform_action('start') def create(self): \"\"\"Create the container.\"\"\"", "ASAP!\") def main(): module = AnsibleModule( argument_spec=yaml.safe_load(DOCUMENTATION)['options'], mutually_exclusive=( ['no_hosts', 'etc_hosts'],", "or g (gigabytes). If you omit the unit, the system", "comparing configuration. Use the recreate option to force the re-creation", "return c + ['--init-path', self.params['init_path']] def addparam_interactive(self, c): return c", "or {} after = before.copy() if self.module.params['annotation'] is not None:", "0 or not out or \"version\" not in out: self.module.fail_json(msg=\"%s", "after = before.copy() if self.params['label']: after.update({ str(k).lower(): str(v).lower() for k,", "['--group-add', g] return c def addparam_healthcheck(self, c): return c +", "type: bool recreate: description: - Use with present and started", "% image) return image_actions class PodmanContainer: \"\"\"Perform container tasks. Manages", "- Run container in an existing pod. If you want", "Manages podman container, inspects it and checks its current state", "if func_name in all_param_methods: cmd = getattr(self, func_name)(cmd) cmd.append(self.params['image']) if", "second) from a device (e.g. device-read-iops /dev/sda:1000) type: list device_write_bps:", "if self.params['command']: if isinstance(self.params['command'], list): cmd += self.params['command'] else: cmd", "for dev in self.params['device']: c += ['--device', dev] return c", "log_options: path=/var/log/container/mycontainer.json log_driver: k8s-file \"\"\" RETURN = \"\"\" container: description:", "[] before = [\"%s:%s\" % (i['path'], i['rate']) for i in", "self.info['State']['Running'] def get_info(self): \"\"\"Inspect container and gather info about it.\"\"\"", "after = [\":\".join(i.split(\":\")[:2]) for i in self.params['device']] before, after =", "for containers (accepts -1000 to 1000) type: int pid: description:", "is a key in the dictionary. Each host name will", "the cgroup for the container will be created. type: str", "c): return c + ['--image-volume', self.params['image_volume']] def addparam_init(self, c): return", "if module.params['state'] in ['started', 'present'] and \\ not module.params['image']: module.fail_json(msg=\"State", "- Working directory inside the container. The default working directory", "after) def diffparam_workdir(self): before = self.info['config']['workingdir'] after = self.params['workdir'] return", "after) def diffparam_cpu_period(self): before = self.info['hostconfig']['cpuperiod'] after = self.params['cpu_period'] return", "a string or a list. type: raw cpu_period: description: -", "tag is included, C(latest) will be used. - Can also", "healthcheck_start_period: description: - The initialization time needed for a container", "custom DNS search domains (Use dns_search with '' if you", "container podman_container: name: mycontainer state: stopped - name: Start 4", "if they do not already exist. type: path cgroupns: description:", "(gigabytes). If you omit the unit, the system uses bytes.", "self._diff_update_and_compare('log_driver', before, after) # Parameter has limited idempotency, unable to", "% self.container.name) self.update_container_result() elif self.container.running and not self.container.different: if self.restart:", "% self.params['sig_proxy']] def addparam_stop_signal(self, c): return c + ['--stop-signal', self.params['stop_signal']]", "} def defaultize(self): params_with_defaults = {} self.default_dict = PodmanDefaults( self.module,", "file. type: dict aliases: - add_hosts expose: description: - Expose", "c): return c + ['--env-file', self.params['env_file']] def addparam_env_host(self, c): self.check_version('--env-host',", "LooseVersion(maxv) < LooseVersion( self.podman_version): self.module.fail_json(msg=\"Parameter %s is supported till podman", "yes state: present recreate: yes expose: - 6379 volumes_from: -", "for v in self.params['volume']] before, after = sorted(list(set(before))), sorted(list(set(after))) return", "diffparam_memory_reservation(self): before = str(self.info['hostconfig']['memoryreservation']) after = self.params['memory_reservation'] return self._diff_update_and_compare('memory_reservation', before,", "return c + ['--label-file', self.params['label_file']] def addparam_log_driver(self, c): return c", "module): \"\"\"Initialize PodmanManager class. Arguments: module {obj} -- ansible module", "in self.params['volume']] before, after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('volume', before,", "pub in self.params['publish']: c += ['--publish', pub] return c def", "the UTS mode for the container type: str volume: description:", "{True}) \"\"\" facts = self.container.get_info() if changed else self.container.info out,", "kernel parameters at runtime type: dict systemd: description: - Run", "info, podman_version): self.module = module self.version = podman_version self.default_dict =", "a container, pass dictionary of label names and values type:", "- Overwrite the default ENTRYPOINT of the image type: str", "\"AttachStdin\": false, \"AttachStdout\": false, \"Cmd\": [ \"sh\" ], \"Domainname\": \"\",", "healthchecks (a value of disable results in no automatic timer", "The default is false. type: bool publish: description: - Publish", "containers when they exit, regardless of status, retrying indefinitely type:", "value means user namespaces are disabled. type: str uts: description:", "before, after) def diffparam_device_write_bps(self): before = self.info['hostconfig']['blkiodevicewritebps'] or [] before", "['--cgroup-parent', self.params['cgroup_parent']] def addparam_cidfile(self, c): return c + ['--cidfile', self.params['cidfile']]", "the container in a new user namespace using the supplied", "for i in before] after = self.params['device_write_bps'] or [] before,", "false. type: bool security_opt: description: - Security Options. For example", "container ID to the file type: path cmd_args: description: -", "sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('cap_drop', before, after) def diffparam_cgroup_parent(self): before =", "default ENTRYPOINT of the image type: str env: description: -", "self.params['security_opt']: c += ['--security-opt', secopt] return c def addparam_shm_size(self, c):", "- I(started) - Asserts there is a running container matching", "will be created. If the path is not absolute, the", "return c + ['--log-driver', self.params['log_driver']] def addparam_log_opt(self, c): return c", "c): for vol in self.params['volumes_from']: c += ['--volumes-from', vol] return", "of status, retrying indefinitely type: str rm: description: - Automatically", "additional information which can be helpful for investigations. type: bool", "host name that is available inside the container. type: str", "cgroupns: description: - Path to cgroups under which the cgroup", "before = int(self.info['hostconfig']['nanocpus']) / 1000000000 after = self.params['cpus'] return self._diff_update_and_compare('cpus',", "6379 volumes_from: - mydata - name: Restart a container podman_container:", "self.info['hostconfig']['volumesfrom'] or [] after = self.params['volumes_from'] or [] return self._diff_update_and_compare('volumes_from',", "%s' % self.container.name) self.update_container_result() def make_stopped(self): \"\"\"Run actions if desired", "in self.info['hostconfig']['devices']] after = [\":\".join(i.split(\":\")[:2]) for i in self.params['device']] before,", "in container. Defaults to false. type: bool etc_hosts: description: -", "assumed to be available locally. type: str annotation: description: -", "\"\"\" if self.action in ['start', 'stop', 'delete']: return self.start_stop_delete() if", "Default is 10. type: int subgidname: description: - Run the", "The default is false. type: bool read_only: description: - Mount", "return [to_bytes(i, errors='surrogate_or_strict') for i in cmd] if self.action ==", "to the container. The format is key value, multiple times.", "after = before[:] if self.module.params['cap_drop'] is not None: for c", "err = module.run_command([module_exec, 'image', 'pull', image]) if rc != 0:", "\"etc_hosts\": {}, \"group_add\": [], \"healthcheck\": \"\", \"ipc\": \"\", \"kernelmemory\": \"0\",", "to force the re-creation of the matching container. - I(started)", "- log_options memory: description: - Memory limit (format 10k, where", "self.params['cpu_rt_period'] return self._diff_update_and_compare('cpu_rt_period', before, after) def diffparam_cpu_rt_runtime(self): before = self.info['hostconfig']['cpurealtimeruntime']", "items where the first one is # \"CMD-SHELL\" and the", "\"Namespace\": \"\", \"NetworkSettings\": { \"Bridge\": \"\", ... }, \"Path\": \"sh\",", "the container that forwards signals and reaps processes. type: str", "\"/usr/bin/podman\", \"--root\", ... ], \"GraphDriver\": { ... }, \"HostConfig\": {", "IPC) for the container type: str kernel_memory: description: - Kernel", "\"cidfile\": \"\", \"cpus\": 0.0, \"cpu_shares\": 0, \"cpu_quota\": 0, \"cpu_period\": 0,", "p in self.module.params: if self.module.params[p] is None and p in", "to add to the container. type: list elements: str cap_drop:", "\"\\n\".join( [\"%s - %s\" % (k, v) for k, v", "before = self.info['hostconfig']['blkiodevicereadbps'] or [] before = [\"%s:%s\" % (i['path'],", "after = self.params['device_read_bps'] or [] before, after = sorted(list(set(before))), sorted(list(set(after)))", "% (i['path'], i['rate']) for i in before] after = self.params['device_read_iops']", "no container matches the name, a container will be created.", "['--healthcheck-command', self.params['healthcheck']] def addparam_healthcheck_interval(self, c): return c + ['--healthcheck-interval', self.params['healthcheck_interval']]", "self.module.params['annotation'] is not None: after.update(self.params['annotation']) return self._diff_update_and_compare('annotation', before, after) def", "aliases: - ports - published - published_ports publish_all: description: -", "otherwise the config key isn't part of the config. def", "(--memory) value. By default, the swap LIMIT will be set", "\"\"\"Run actions if desired state is 'absent'.\"\"\" if not self.container.exists:", "You can also override the default path of the authentication", "dict env_file: description: - Read in a line delimited file", "self.params = params self.action = action self.podman_version = podman_version self.module", "params self.action = action self.podman_version = podman_version self.module = module", "the container-init binary. type: str interactive: description: - Keep STDIN", "ports (e.g. expose \"3300-3310\") to set up port redirection on", "default log_path def diffparam_log_opt(self): before = self.info['logpath'] if self.module.params['log_opt'] in", "description: - Read in a line delimited file of labels", "before, after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('security_opt', before, after) def", "+ ['--blkio-weight', self.params['blkio_weight']] def addparam_blkio_weight_device(self, c): for blkio in self.params['blkio_weight_device'].items():", "return c + ['--cpuset-mems', self.params['cpuset_mems']] def addparam_detach(self, c): return c", "will be stopped and removed. - I(present) - Asserts the", "#!/usr/bin/python # Copyright (c) 2019 OpenStack Foundation # All Rights", "in which to allow execution (0-3, 0,1) type: str cpuset_mems:", "current state \"\"\" def __init__(self, module, name): \"\"\"Initialize PodmanContainer class.", "- name: Create a data container podman_container: name: mydata image:", "If container is running in --read-only mode, then mount a", "% self.params['detach']] def addparam_detach_keys(self, c): return c + ['--detach-keys', self.params['detach_keys']]", "c + ['--workdir', self.params['workdir']] # Add your own args for", "the path is considered to be relative to the cgroups", "== 0 else {} def _get_podman_version(self): rc, out, err =", "# WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "options cgroupns and cgroup-parent. type: str choices: - default -", "after = [] else: after = self.params['blkio_weight_device'] return self._diff_update_and_compare('blkio_weight_device', before,", "Default is false type: bool read_only_tmpfs: description: - If container", "['no_hosts', 'etc_hosts'], ), supports_check_mode=True, ) # work on input vars", "false. type: bool oom_kill_disable: description: - Whether to disable OOM", "c): for env_value in self.params['env'].items(): c += ['--env', b\"=\".join([to_bytes(k, errors='surrogate_or_strict')", "- Attach a filesystem mount to the container. bind or", "partial idempotency only. def diffparam_hostname(self): before = self.info['config']['hostname'] after =", "name will be stopped and removed. - I(present) - Asserts", "addparam_dns_search(self, c): return c + ['--dns-search', self.params['dns_search']] def addparam_entrypoint(self, c):", "using the map with 'name' in the /etc/subgid file. type:", "= [\"%s:%s\" % (i['path'], i['rate']) for i in before] after", "using the supplied mapping. type: str group_add: description: - Add", "\"AttachStderr\": false, \"AttachStdin\": false, \"AttachStdout\": false, \"Cmd\": [ \"sh\" ],", "delimited file of labels type: str log_driver: description: - Logging", "self.container.name) self.update_container_result() elif self.container.stopped and self.container.different: self.container.recreate() self.results['actions'].append('recreated %s' %", "description: - Tune the container's pids limit. Set -1 to", "- Allocate a pseudo-TTY. The default is false. type: bool", "process to a file. conmon runs in a separate process", "busybox log_options: path=/var/log/container/mycontainer.json log_driver: k8s-file \"\"\" RETURN = \"\"\" container:", "Cgroups will be created if they do not already exist.", "container.\"\"\" self._perform_action('start') def create(self): \"\"\"Create the container.\"\"\" self._perform_action('create') def recreate(self):", "uidmap in self.params['uidmap']: c += ['--uidmap', uidmap] return c def", "recreate(self): \"\"\"Recreate the container.\"\"\" self.delete() self.run() def restart(self): \"\"\"Restart the", "description: - Force restart of container. type: bool default: False", "= [\":\".join(i.split(\":\")[:2]) for i in self.params['device']] before, after = sorted(list(set(before))),", "bind) type: str choices: - 'bind' - 'tmpfs' - 'ignore'", "for i in self.info['hostconfig']['extrahosts']]) else: before = {} after =", "the provided configuration does not match, the container will be", "\"pid\": \"\", \"privileged\": False, \"rm\": False, \"security_opt\": [], \"stop_signal\": 15,", "= sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('device_write_bps', before, after) def diffparam_device_write_iops(self): before", "Restart containers when they exit with a non-0 exit code,", "= '', '' self.info = self.get_info() self.version = self._get_podman_version() self.diff", "no networking * container:<name|id> reuse another container's network stack *", "(k, v) for k, v in sorted( diffs['after'].items())]) + \"\\n\"", "the value can be expressed in a time format such", "cgroups: description: - Determines whether the container will create CGroups.", "disabled. type: str uts: description: - Set the UTS mode", "if 'healthcheck' in self.info['config']: # the \"test\" key is a", "signals and reaps processes. type: str init_path: description: - Path", "a container is stopped via the podman kill or podman", "the container type: str pids_limit: description: - Tune the container's", "driver for the container. For example log_driver \"k8s-file\". type: str", "Timeout (in seconds) to stop a container. Default is 10.", "return self._diff_update_and_compare('cap_add', before, after) def diffparam_cap_drop(self): before = self.info['effectivecaps'] or", "before before, after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('cap_add', before, after)", "DNS servers type: list elements: str dns_option: description: - Set", "if self.params['env']: after.update({ str(k).lower(): str(v).lower() for k, v in self.params['env'].items()", "['rm', '-f', self.params['name']] return [to_bytes(i, errors='surrogate_or_strict') for i in cmd]", "sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('device_read_bps', before, after) def diffparam_device_read_iops(self): before =", "for you, preference the pod name with \"new:\" type: str", "for podman command def addparam_cmd_args(self, c): return c + self.params['cmd_args']", "label names and values type: dict label_file: description: - Read", "!= {}) @property def different(self): \"\"\"Check if container is different.\"\"\"", "(kilobytes), m(megabytes), or g (gigabytes). If you omit the unit,", "\"OOMKilled\": false, \"OciVersion\": \"1.0.1-dev\", \"Paused\": false, \"Pid\": 4083, \"Restarting\": false,", "self.params['cap_add']: c += ['--cap-add', cap_add] return c def addparam_cap_drop(self, c):", "the container.\"\"\" self._perform_action('run') def delete(self): \"\"\"Delete the container.\"\"\" self._perform_action('delete') def", "CNI networks to join were specified via 'network:', and if", "+ ['--cpuset-mems', self.params['cpuset_mems']] def addparam_detach(self, c): return c + ['--detach=%s'", "if isinstance(after, str): after = [i.lower() for i in after.split()]", "import absolute_import, division, print_function __metaclass__ = type import json from", "- Path to C(podman) executable if it is not in", "into account a full name with registry and namespaces. type:", "param_name, before, after): if before != after: self.diff['before'].update({param_name: before}) self.diff['after'].update({param_name:", "return c + ['--env-file', self.params['env_file']] def addparam_env_host(self, c): self.check_version('--env-host', minv='1.5.0')", "description: - Do not create /etc/hosts for the container Default", "for i in b_command]) self.module.log(\"PODMAN-CONTAINER-DEBUG: %s\" % full_cmd) self.actions.append(full_cmd) if", "for investigations. type: bool default: False detach_keys: description: - Override", "in ['create', 'run']: cmd = [self.action, '--name', self.params['name']] all_param_methods =", "\"0\", \"log_driver\": \"k8s-file\", \"memory\": \"0\", \"memory_swap\": \"0\", \"memory_reservation\": \"0\", #", "even if it is running. Use force_restart to force a", "dictionary. Each host name will be added to the container's", "before, after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('device_read_iops', before, after) def", "first one is # \"CMD-SHELL\" and the second one is", "description: - Logging driver specific options. Used to set the", "you specify. type: int cpu_rt_runtime: description: - Limit the CPU", "\"blkio_weight\": 0, \"cgroups\": \"default\", \"cgroup_parent\": \"\", \"cidfile\": \"\", \"cpus\": 0.0,", "addparam_entrypoint(self, c): return c + ['--entrypoint', self.params['entrypoint']] def addparam_env(self, c):", "not mode: # In a idempotency 'lite mode' assume all", "c + ['--authfile', self.params['authfile']] def addparam_blkio_weight(self, c): return c +", "False, 'actions': [], 'container': {}, } self.name = self.module.params['name'] self.executable", "cpu_shares: description: - CPU shares (relative weight) type: int cpus:", "params, podman_version, module): self.params = params self.action = action self.podman_version", "[ \"sh\" ], \"Domainname\": \"\", \"Entrypoint\": \"\", \"Env\": [ \"PATH=/usr/sbin:/usr/bin:/sbin:/bin\",", "is not specified!') if not self.container.exists: self.container.create() self.results['actions'].append('created %s' %", "def addparam_cap_drop(self, c): for cap_drop in self.params['cap_drop']: c += ['--cap-drop',", "sorted(list(set(after))) return self._diff_update_and_compare('cap_drop', before, after) def diffparam_cgroup_parent(self): before = self.info['hostconfig']['cgroupparent']", "or [] before, after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('device_read_iops', before,", "container podman_container: name: ohno state: absent - name: Writing output", "/etc/subgid file. type: str subuidname: description: - Run the container", "Kernel memory limit (format <number>[<unit>], where unit = b, k,", "self.params['sysctl'].items(): c += ['--sysctl', b\"=\".join([to_bytes(k, errors='surrogate_or_strict') for k in sysctl])]", "callable(getattr(self, func)) and func.startswith( \"diffparam\")] fail_fast = not bool(self.module._diff) different", "\"Bridge\": \"\", ... }, \"Path\": \"sh\", \"ProcessLabel\": \"system_u:system_r:container_t:s0:c282,c782\", \"ResolvConfPath\": \"...\",", "\"Status\": \"exited\" }, \"StaticDir\": \"...\" ... }' \"\"\" class PodmanModuleParams:", "inspection output. - Note that facts are part of the", "sorted(list(set(after))) return self._diff_update_and_compare('device_read_iops', before, after) def diffparam_device_write_bps(self): before = self.info['hostconfig']['blkiodevicewritebps']", "self.params['rootfs']] def addparam_security_opt(self, c): for secopt in self.params['security_opt']: c +=", "if self.params['network'] == ['none']: after = True return self._diff_update_and_compare('no_hosts', before,", "exp in self.params['expose']: c += ['--expose', exp] return c def", "_perform_action(self, action): \"\"\"Perform action with container. Arguments: action {str} --", "\"Config\": { \"Annotations\": { \"io.kubernetes.cri-o.ContainerType\": \"sandbox\", \"io.kubernetes.cri-o.TTY\": \"false\" }, \"AttachStderr\":", "= self.info['hostconfig']['securityopt'] after = self.params['security_opt'] before, after = sorted(list(set(before))), sorted(list(set(after)))", "description: - Run the container in a new user namespace", "before, after) def diffparam_cpu_rt_runtime(self): before = self.info['hostconfig']['cpurealtimeruntime'] after = self.params['cpu_rt_runtime']", "Signal to stop a container. Default is SIGTERM. type: int", "addparam_device(self, c): for dev in self.params['device']: c += ['--device', dev]", "type: list elements: str aliases: - ports - published -", "\"\"\" class PodmanModuleParams: \"\"\"Creates list of arguments for podman CLI", "the case, the image is assumed to be available locally.", "actions if desired state is 'started'.\"\"\" if self.container.running and \\", "uses bytes. If you omit the size entirely, the system", "str aliases: - log_options memory: description: - Memory limit (format", "description: - CPU shares (relative weight) type: int cpus: description:", "network stack on the default bridge * none no networking", "return c + ['--stop-timeout', self.params['stop_timeout']] def addparam_subgidname(self, c): return c", "% (i['path'], i['rate']) for i in before] after = self.params['device_write_iops']", "m or g) Note - idempotency is supported for integers", "run failed!\" % self.module.params['executable']) return out.split(\"version\")[1].strip() def _perform_action(self, action): \"\"\"Perform", "(format 100m, where unit = b, k, m or g)", "--memory Note - idempotency is supported for integers only. type:", "machine running C(podman) default: 'podman' type: str state: description: -", "before, after) def diffparam_device_write_iops(self): before = self.info['hostconfig']['blkiodevicewriteiops'] or [] before", "class PodmanModuleParams: \"\"\"Creates list of arguments for podman CLI command.", "\"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY", "\"Rootfs\": \"\", \"State\": { \"Dead\": false, \"Error\": \"\", \"ExitCode\": 0,", "the container. The default working directory for running binaries within", "# Ignore volumes option for idempotency after = [\":\".join(v.split(\":\")[:2]) for", "multiple times. type: dict authfile: description: - Path of the", "type: str choices: - 'bind' - 'tmpfs' - 'ignore' image_strict:", "\"ssssh\" BOOLEAN_KEY: \"yes\" - name: Container present podman_container: name: mycontainer", "stop(self): \"\"\"Stop the container.\"\"\" self._perform_action('stop') def start(self): \"\"\"Start the container.\"\"\"", "aliases: - net no_hosts: description: - Do not create /etc/hosts", "self.params['http_proxy']] def addparam_image_volume(self, c): return c + ['--image-volume', self.params['image_volume']] def", "were specified via 'network:', and if the container is not", "SIGCHLD, SIGSTOP, and SIGKILL are not proxied. The default is", "def default_dict(self): # make here any changes to self.defaults related", "the container.\"\"\" self.stop() self.run() class PodmanManager: \"\"\"Module manager class. Defines", "def addparam_init(self, c): return c + ['--init', self.params['init']] def addparam_init_path(self,", "is true. type: bool stop_signal: description: - Signal to stop", "addparam_stop_signal(self, c): return c + ['--stop-signal', self.params['stop_signal']] def addparam_stop_timeout(self, c):", "the value of --memory Note - idempotency is supported for", "a read-write tmpfs on /run, /tmp, and /var/tmp. The default", "env_before = self.info['config']['env'] or {} before = {i.split(\"=\")[0]: i.split(\"=\")[1] for", "True return different def ensure_image_exists(module, image): \"\"\"If image is passed,", "self.info['hostconfig']['cpuperiod'] after = self.params['cpu_period'] return self._diff_update_and_compare('cpu_period', before, after) def diffparam_cpu_rt_period(self):", "return True else: different = True # Check non idempotent", "true type: bool recreate: description: - Use with present and", "/HOST-DIR:/CONTAINER-DIR, podman bind mounts /HOST-DIR in the host to /CONTAINER-DIR", "0. Unit is optional and can be b (bytes), k", "\"gid\": 0, \"uid\": 0 }, \"Volumes\": null, \"WorkingDir\": \"/\" },", "limit (format 10k, where unit = b, k, m or", "return c + ['--memory', self.params['memory']] def addparam_memory_reservation(self, c): return c", "matching the name and any provided configuration parameters. If no", "type: bool uidmap: description: - Run the container in a", "addparam_cpus(self, c): return c + ['--cpus', self.params['cpus']] def addparam_cpuset_cpus(self, c):", "return False def diffparam_conmon_pidfile(self): before = self.info['conmonpidfile'] if self.module.params['conmon_pidfile'] is", "omit the size entirely, the system uses 64m type: str", "false, \"Cmd\": [ \"sh\" ], \"Domainname\": \"\", \"Entrypoint\": \"\", \"Env\":", "vol in self.params['volumes_from']: c += ['--volumes-from', vol] return c def", "after) def diffparam_etc_hosts(self): if self.info['hostconfig']['extrahosts']: before = dict([i.split(\":\") for i", "\"CMD-SHELL\" and the second one is the actual healthcheck command.", "if desired state is 'absent'.\"\"\" if not self.container.exists: self.results.update({'changed': False})", "short_description: Manage podman containers notes: [] description: - Start, stop,", "after.remove(c) before, after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('cap_drop', before, after)", "100m, where unit = b, k, m or g) Note", "+ ['--userns', self.params['userns']] def addparam_uts(self, c): return c + ['--uts',", "for the container. For example log_driver \"k8s-file\". type: str choices:", "domains (Use dns_search with '' if you don't wish to", "False, \"rm\": False, \"security_opt\": [], \"stop_signal\": 15, \"tty\": False, \"user\":", "= self.default_dict[p] else: params_with_defaults[p] = self.module.params[p] return params_with_defaults def _diff_update_and_compare(self,", "description: - Override the key sequence for detaching a container.", "self.defaultize() self.diff = {'before': {}, 'after': {}} self.non_idempotent = {", "self.params['pod']] def addparam_privileged(self, c): return c + ['--privileged=%s' % self.params['privileged']]", "healthcheck # was configured; otherwise the config key isn't part", "= self.params['cgroup_parent'] return self._diff_update_and_compare('cgroup_parent', before, after) def diffparam_cgroups(self): # Cgroups", "to the cgroups path of the init process. Cgroups will", "equal to memory plus swap. Must be used with the", "matching container, even if it is running. Use force_restart to", "the podman process. This can be disabled by setting the", "character or ctrl-value type: str device: description: - Add a", "['--uidmap', uidmap] return c def addparam_ulimit(self, c): for u in", "['start', 'stop', 'delete']: return self.start_stop_delete() if self.action in ['create', 'run']:", "= self.params['rm'] return self._diff_update_and_compare('rm', before, after) def diffparam_security_opt(self): before =", "given module parameters. Returns: list -- list of byte strings", "default is 0.0 which means no limit. type: str cpuset_cpus:", "self.params['no_hosts']] def addparam_oom_kill_disable(self, c): return c + ['--oom-kill-disable=%s' % self.params['oom_kill_disable']]", "['--tty=%s' % self.params['tty']] def addparam_uidmap(self, c): for uidmap in self.params['uidmap']:", "def addparam_env(self, c): for env_value in self.params['env'].items(): c += ['--env',", "self.recreate = self.module.params['recreate'] self.container = PodmanContainer(self.module, self.name) def update_container_result(self, changed=True):", "actions if desired state is 'stopped'.\"\"\" if not self.container.exists and", "= self.info['hostconfig']['cgroupparent'] after = self.params['cgroup_parent'] return self._diff_update_and_compare('cgroup_parent', before, after) def", "c): return c + ['--log-driver', self.params['log_driver']] def addparam_log_opt(self, c): return", "rc, out, err = self.module.run_command( [self.module.params['executable'], b'--version']) if rc !=", "['--publish', pub] return c def addparam_publish_all(self, c): return c +", "else: before = {} after = self.params['etc_hosts'] return self._diff_update_and_compare('etc_hosts', before,", "after += [\"cap_\" + i.lower() for i in self.module.params['cap_add']] after", "self.params['memory_reservation']] def addparam_memory_swap(self, c): return c + ['--memory-swap', self.params['memory_swap']] def", "%s\" % (k, v) for k, v in sorted( diffs['after'].items())])", "type: str log_driver: description: - Logging driver. Used to set", "description: - Whether to disable OOM Killer for the container", "Set the user namespace mode for the container. It defaults", "this is necessary when using systemd to restart Podman containers.", "bool oom_score_adj: description: - Tune the host's OOM preferences for", "container in a new user namespace using the map with", "before = self.info['hostconfig']['cpuperiod'] after = self.params['cpu_period'] return self._diff_update_and_compare('cpu_period', before, after)", "stack. This is the default for rootless containers type: list", "return c def addparam_tty(self, c): return c + ['--tty=%s' %", "to_bytes, to_native ANSIBLE_METADATA = { 'metadata_version': '1.0', 'status': ['preview'], 'supported_by':", "return self._diff_update_and_compare('cgroup_parent', before, after) def diffparam_cgroups(self): # Cgroups output is", "or self.recreate): self.container.recreate() self.results['actions'].append('recreated %s' % self.container.name) self.update_container_result() elif self.container.running", "type: str subuidname: description: - Run the container in a", "host name. Sets the container host name that is available", "in self.params['label'].items() }) return self._diff_update_and_compare('label', before, after) def diffparam_log_driver(self): before", "for integers only. type: str memory_reservation: description: - Memory soft", "str(int(self.params['memory']) * 2) return self._diff_update_and_compare('memory_swap', before, after) def diffparam_memory_reservation(self): before", "i['rate']) for i in before] after = self.params['device_write_iops'] or []", "vol] return c def addparam_workdir(self, c): return c + ['--workdir',", "facts = self.container.get_info() if changed else self.container.info out, err =", "i in self.module.params['cap_drop']]: if c in after: after.remove(c) before, after", "running now.\"\"\" return self.exists and not self.info['State']['Running'] def get_info(self): \"\"\"Inspect", "[self.module.params['executable'], b'--version']) if rc != 0 or not out or", "defaults to the PODMAN_USERNS environment variable. An empty value means", "+ ['--cgroup-parent', self.params['cgroup_parent']] def addparam_cidfile(self, c): return c + ['--cidfile',", "file. conmon runs in a separate process than Podman, so", "in self.params['tmpfs'].items(): c += ['--tmpfs', ':'.join(tmpfs)] return c def addparam_tty(self,", "c + ['--memory-reservation', self.params['memory_reservation']] def addparam_memory_swap(self, c): return c +", "def addparam_group_add(self, c): for g in self.params['group_add']: c += ['--group-add',", "type: bool aliases: - remove rootfs: description: - If true,", "after.update({ str(k).lower(): str(v).lower() for k, v in self.params['label'].items() }) return", "['--other-param', 'value'] Be aware module doesn't support idempotency if this", "or nothing was done \"\"\" image_actions = [] module_exec =", "# work on input vars if module.params['state'] in ['started', 'present']", "after}) return True return False def diffparam_annotation(self): before = self.info['config']['annotations']", "+= ['--annotation', '='.join(annotate)] return c def addparam_authfile(self, c): return c", "PID mode for the container type: str pids_limit: description: -", "The default value is 3. type: int healthcheck_start_period: description: -", "self.params['device_write_iops']: c += ['--device-write-iops', dev] return c def addparam_dns(self, c):", "return self._diff_update_and_compare('cpu_shares', before, after) def diffparam_cpus(self): before = int(self.info['hostconfig']['nanocpus']) /", "c def addparam_workdir(self, c): return c + ['--workdir', self.params['workdir']] #", "self.make_started, 'absent': self.make_absent, 'stopped': self.make_stopped } process_action = states_map[self.state] process_action()", "Used to set the log driver for the container. For", "- List of capabilities to add to the container. type:", "m['type'] == 'volume': volumes.append([m['name'], m['destination']]) else: volumes.append([m['source'], m['destination']]) before =", "\"Driver\": \"overlay\", \"EffectiveCaps\": [ \"CAP_CHOWN\", ... ], \"ExecIDs\": [], \"ExitCommand\":", "self.params['expose']: c += ['--expose', exp] return c def addparam_gidmap(self, c):", "initialization time needed for a container to bootstrap. The value", "open even if not attached. The default is false. When", "\"ExitCode\": 0, \"FinishedAt\": \"2019-06-17T19:13:10.157518963+03:00\", \"Healthcheck\": { \"FailingStreak\": 0, \"Log\": null,", "false, \"User\": { \"gid\": 0, \"uid\": 0 }, \"Volumes\": null,", "return self._diff_update_and_compare('pid', before, after) def diffparam_rm(self): before = self.info['hostconfig']['autoremove'] after", "if callable(getattr(self, func)) and func.startswith( \"diffparam\")] fail_fast = not bool(self.module._diff)", "launched inside of the container. type: dict env_file: description: -", "\\ self.module.get_bin_path(self.module.params['executable'], required=True) self.image = self.module.params['image'] image_actions = ensure_image_exists(self.module, self.image)", "ip: description: - Specify a static IP address for the", "self.module.fail_json(msg=\"Parameter %s is supported from podman \" \"version %s only!", "} self.name = self.module.params['name'] self.executable = \\ self.module.get_bin_path(self.module.params['executable'], required=True) self.image", "current state of the container. Matches the podman inspection output.", "the name and any provided configuration parameters. If no container", "image]) if rc == 0: return image_actions rc, out, err", "str executable: description: - Path to C(podman) executable if it", "create a user network stack. This is the default for", "your own args for podman command def addparam_cmd_args(self, c): return", "addparam_tty(self, c): return c + ['--tty=%s' % self.params['tty']] def addparam_uidmap(self,", "0 else {} def _get_podman_version(self): rc, out, err = self.module.run_command(", "before = self.info['hostconfig']['blkiodevicewriteiops'] or [] before = [\"%s:%s\" % (i['path'],", "container.\"\"\" self._perform_action('stop') def start(self): \"\"\"Start the container.\"\"\" self._perform_action('start') def create(self):", "c): for vol in self.params['volume']: if vol: c += ['--volume',", "- Give extended privileges to this container. The default is", "idempotency is supported for integers only. type: str label: description:", "The default is 0.0 which means no limit. type: str", "== 'volume': volumes.append([m['name'], m['destination']]) else: volumes.append([m['source'], m['destination']]) before = [\":\".join(v)", "for cap_drop in self.params['cap_drop']: c += ['--cap-drop', cap_drop] return c", "return image_actions class PodmanContainer: \"\"\"Perform container tasks. Manages podman container,", "in self.params['device']: c += ['--device', dev] return c def addparam_device_read_bps(self,", "permissions and limitations # under the License. # flake8: noqa:", "int stop_timeout: description: - Timeout (in seconds) to stop a", "= \"\"\" module: podman_container author: - \"<NAME> (@sshnaidm)\" version_added: '2.9'", "\"Annotations\": { \"io.kubernetes.cri-o.ContainerType\": \"sandbox\", \"io.kubernetes.cri-o.TTY\": \"false\" }, \"AttachStderr\": false, \"AttachStdin\":", "diffparam_no_hosts(self): before = not bool(self.info['hostspath']) after = self.params['no_hosts'] if self.params['network']", "\"Paused\": false, \"Pid\": 4083, \"Restarting\": false, \"Running\": false, \"StartedAt\": \"2019-06-17T19:13:10.152479729+03:00\",", "to the container. type: list elements: str cap_drop: description: -", "str(self.info['hostconfig']['memory']) after = self.params['memory'] return self._diff_update_and_compare('memory', before, after) def diffparam_memory_swap(self):", "The default working directory for running binaries within a container", "{} self.default_dict = PodmanDefaults( self.module, self.version).default_dict() for p in self.module.params:", "before, after) def diffparam_cpuset_cpus(self): before = self.info['hostconfig']['cpusetcpus'] after = self.params['cpuset_cpus']", "and self.params['memory'].isdigit()): after = str(int(self.params['memory']) * 2) return self._diff_update_and_compare('memory_swap', before,", "Run an init inside the container that forwards signals and", "Set custom DNS servers type: list elements: str dns_option: description:", "failed!\" % self.module.params['executable']) return out.split(\"version\")[1].strip() def _perform_action(self, action): \"\"\"Perform action", "Defaults to false. type: bool etc_hosts: description: - Dict of", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "after) def diffparam_blkio_weight(self): before = self.info['hostconfig']['blkioweight'] after = self.params['blkio_weight'] return", "def diffparam_stop_signal(self): before = self.info['config']['stopsignal'] after = self.params['stop_signal'] return self._diff_update_and_compare('stop_signal',", "c def addparam_env_file(self, c): return c + ['--env-file', self.params['env_file']] def", "a idempotency 'lite mode' assume all images from different registries", "type: list dns: description: - Set custom DNS servers type:", "for integers only. type: str memory_swap: description: - A limit", "self.params['privileged']] def addparam_publish(self, c): for pub in self.params['publish']: c +=", "['--shm-size', self.params['shm_size']] def addparam_sig_proxy(self, c): return c + ['--sig-proxy=%s' %", "c): return c + ['--conmon-pidfile', self.params['conmon_pidfile']] def addparam_cpu_period(self, c): return", "name: Container present podman_container: name: mycontainer state: present image: ubuntu:14.04", "labels type: str log_driver: description: - Logging driver. Used to", "network's pool (default 10.88.0.0/16). type: str ipc: description: - Default", "= [] @property def exists(self): \"\"\"Check if container exists.\"\"\" return", "dafault is false. type: bool security_opt: description: - Security Options.", "second) to a device (e.g. device-write-bps /dev/sda:1mb) type: list device_write_iops:", "investigations. type: bool default: False detach_keys: description: - Override the", "v in sorted( diffs['before'].items())]) + \"\\n\" self.diff['after'] = \"\\n\".join( [\"%s", "Arguments: module {obj} -- ansible module object name {str} --", "['--cap-add', cap_add] return c def addparam_cap_drop(self, c): for cap_drop in", "in time format like 2m3s. The default value is 0s", "def addparam_memory_swap(self, c): return c + ['--memory-swap', self.params['memory_swap']] def addparam_memory_swappiness(self,", "type: int pid: description: - Set the PID mode for", "By default proxy environment variables are passed into the container", "if self.module.params['annotation'] is not None: after.update(self.params['annotation']) return self._diff_update_and_compare('annotation', before, after)", "considered to be unhealthy. The default value is 3. type:", "return self._diff_update_and_compare('label', before, after) def diffparam_log_driver(self): before = self.info['hostconfig']['logconfig']['type'] after", "v in self.params['env'].items() }) return self._diff_update_and_compare('env', before, after) def diffparam_etc_hosts(self):", "than Podman, so this is necessary when using systemd to", "% ( param, minv, self.podman_version)) def addparam_annotation(self, c): for annotate", "system. The dafault is false. type: bool security_opt: description: -", "the License. # flake8: noqa: E501 from __future__ import absolute_import,", "not None: before = self.info['config']['cmd'] after = self.params['command'] if isinstance(after,", "cmd_args - ['--other-param', 'value'] Be aware module doesn't support idempotency", "- Read in a line delimited file of environment variables", "return c def addparam_shm_size(self, c): return c + ['--shm-size', self.params['shm_size']]", "with 'name' in the /etc/subuid file. type: str sysctl: description:", "in before] after = self.params['device_write_iops'] or [] before, after =", "redis container podman_container: name: myredis image: redis command: redis-server --appendonly", "argument refers to an exploded container on the file system.", "bool(self.info['hostspath']) after = self.params['no_hosts'] if self.params['network'] == ['none']: after =", "for cap_add in self.params['cap_add']: c += ['--cap-add', cap_add] return c", "it can be. If it cannot be updated, it will", "ftp_proxy, no_proxy, and also the upper case versions of those.", "['--read-only-tmpfs=%s' % self.params['read_only_tmpfs']] def addparam_restart_policy(self, c): return c + ['--restart=%s'", "\"\", ... }, \"Path\": \"sh\", \"ProcessLabel\": \"system_u:system_r:container_t:s0:c282,c782\", \"ResolvConfPath\": \"...\", \"RestartCount\":", "and tag used to create the container. If an image", "c): return c + ['--dns-option', self.params['dns_option']] def addparam_dns_search(self, c): return", "Create a bind mount. If you specify, volume /HOST-DIR:/CONTAINER-DIR, podman", "mode: # In a idempotency 'lite mode' assume all images", "self.params['command']: if isinstance(self.params['command'], list): cmd += self.params['command'] else: cmd +=", "weight, format DEVICE_NAME[:]WEIGHT). type: dict cap_add: description: - List of", "before = False after = self.params['env_host'] return self._diff_update_and_compare('env_host', before, after)", "a device (e.g. device-read-bps /dev/sda:1mb) type: list device_read_iops: description: -", "when they exit, regardless of status, retrying indefinitely type: str", "= self.params['conmon_pidfile'] return self._diff_update_and_compare('conmon_pidfile', before, after) def diffparam_cpu_period(self): before =", "\"Created\": \"2019-06-17T19:13:09.873858307+03:00\", \"Dependencies\": [], \"Driver\": \"overlay\", \"EffectiveCaps\": [ \"CAP_CHOWN\", ...", "= module self.name = name self.stdout, self.stderr = '', ''", "plus swap. Must be used with the -m (--memory) flag.", "+= ['--blkio-weight-device', ':'.join(blkio)] return c def addparam_cap_add(self, c): for cap_add", "command. before = self.info['config']['healthcheck']['test'][1] else: before = '' after =", "before = self.info['hostconfig']['cpurealtimeperiod'] after = self.params['cpu_rt_period'] return self._diff_update_and_compare('cpu_rt_period', before, after)", "v in self.params['volume']] before, after = sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('volume',", "Path to C(podman) executable if it is not in the", "addparam_userns(self, c): return c + ['--userns', self.params['userns']] def addparam_uts(self, c):", "return c + ['--pod', self.params['pod']] def addparam_privileged(self, c): return c", "before else: after = self.params['conmon_pidfile'] return self._diff_update_and_compare('conmon_pidfile', before, after) def", "str volume: description: - Create a bind mount. If you", "after) def diffparam_tty(self): before = self.info['config']['tty'] after = self.params['tty'] return", "yes etc_hosts: other: \"127.0.0.1\" restart_policy: \"no\" device: \"/dev/sda:/dev/xvda:rwm\" ports: -", "description: - Limit the CPU real-time period in microseconds. Limit", "before = self.info['config']['cmd'] after = self.params['command'] if isinstance(after, str): after", "return self._diff_update_and_compare('uts', before, after) def diffparam_volume(self): before = self.info['mounts'] if", "64m type: str sig_proxy: description: - Proxy signals sent to", "time format like 2m3s. The default value is 0s type:", "in include http_proxy, https_proxy, ftp_proxy, no_proxy, and also the upper", "sorted(list(set(before))), sorted(list(set(after))) return self._diff_update_and_compare('volume', before, after) def diffparam_volumes_from(self): before =", "the name, a container will be created. If a container", "sleep 1d with_sequence: count=4 - name: remove container podman_container: name:", "c + ['--healthcheck-timeout', self.params['healthcheck_timeout']] def addparam_hostname(self, c): return c +", "provided configuration. If no container matches the name, a container", "self.name = name self.stdout, self.stderr = '', '' self.info =", "in Ansible 2.12. - Empty if C(state) is I(absent). returned:", "= False for func_name in diff_func_list: dff_func = getattr(self, func_name)", "\"Cmd\": [ \"sh\" ], \"Domainname\": \"\", \"Entrypoint\": \"\", \"Env\": [", "p in self.default_dict: params_with_defaults[p] = self.default_dict[p] else: params_with_defaults[p] = self.module.params[p]", "c + ['--stop-timeout', self.params['stop_timeout']] def addparam_subgidname(self, c): return c +", "bool ip: description: - Specify a static IP address for", "tty: description: - Allocate a pseudo-TTY. The default is false.", "def stopped(self): \"\"\"Return True if container exists and is not", "u] return c def addparam_user(self, c): return c + ['--user',", "\"\"\" super(PodmanContainer, self).__init__() self.module = module self.name = name self.stdout,", "if callable(getattr(self, func)) and func.startswith(\"addparam\")] params_set = (i for i", "rootless containers type: list elements: str aliases: - net no_hosts:", "= self.info['hostconfig']['logconfig']['type'] after = self.params['log_driver'] return self._diff_update_and_compare('log_driver', before, after) #", "None self.info = yaml.safe_load(json.dumps(info).lower()) self.params = self.defaultize() self.diff = {'before':", "image_actions = [] module_exec = module.params['executable'] if not image: return", "class PodmanContainer: \"\"\"Perform container tasks. Manages podman container, inspects it", "for c in [\"cap_\" + i.lower() for i in self.module.params['cap_drop']]:", "\"0\", \"memory_reservation\": \"0\", # \"memory_swappiness\": -1, \"no_hosts\": False, # libpod", "the container. Matches the podman inspection output. - Note that", "def addparam_env_host(self, c): self.check_version('--env-host', minv='1.5.0') return c + ['--env-host=%s' %", "is %s\" % ( param, minv, self.podman_version)) if maxv and", "by setting the http_proxy option to false. The environment variables", "for l in label])] return c def addparam_label_file(self, c): return", "to false. The environment variables passed in include http_proxy, https_proxy,", "for i in self.module.params['cap_drop']]: if c in after: after.remove(c) before,", "addparam_network(self, c): return c + ['--network', \",\".join(self.params['network'])] def addparam_no_hosts(self, c):", "return self._diff_update_and_compare('healthcheck', before, after) # Because of hostname is random", "- If true, the first argument refers to an exploded", "false. type: bool publish: description: - Publish a container's port,", "None: for c in [\"cap_\" + i.lower() for i in", "description: - Dict of host-to-IP mappings, where each host name", "until the optional max_retries count is hit * always -", "\"HostsPath\": \"...\", \"ID\": \"...\", \"Image\": \"...\", \"ImageName\": \"docker.io/library/busybox:latest\", \"IsInfra\": false,", "\"cpu_rt_period\": 0, \"cpuset_cpus\": \"\", \"cpuset_mems\": \"\", \"detach\": True, \"device\": [],", "'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community' } DOCUMENTATION = \"\"\"", "and also the upper case versions of those. Defaults to", "manage Podman containers requirements: - \"Podman installed on host\" options:", "second one is the actual healthcheck command. before = self.info['config']['healthcheck']['test'][1]", "self.info['config']['workingdir'] after = self.params['workdir'] return self._diff_update_and_compare('workdir', before, after) def is_different(self):", "self.container.diff: self.results.update({'diff': self.container.diff}) if self.module.params['debug']: self.results.update({'podman_version': self.container.version}) self.module.exit_json(**self.results) def make_started(self):", "if self.params['rm']: c += ['--rm'] return c def addparam_rootfs(self, c):", "name of image Returns: list -- list of image actions", "if not - pull it or fail. Arguments: module {obj}", "- The initialization time needed for a container to bootstrap.", "is the case, the image is assumed to be available", "for the podman process. This can be disabled by setting", "%s is supported from podman \" \"version %s only! Current", "= self.info['config']['workingdir'] after = self.params['workdir'] return self._diff_update_and_compare('workdir', before, after) def", "the file type: path cmd_args: description: - Any additionl command", "ensure_image_exists(module, image): \"\"\"If image is passed, ensure it exists, if", "Override the key sequence for detaching a container. Format is", "self.params['env'].items() }) return self._diff_update_and_compare('env', before, after) def diffparam_etc_hosts(self): if self.info['hostconfig']['extrahosts']:", "def diffparam_volume(self): before = self.info['mounts'] if before: volumes = []", "in --read-only mode, then mount a read-write tmpfs on /run,", "environment variables that are available for the process that will", "if (self.module.params['memory_swap'] is None and self.params['memory'] != 0 and self.params['memory'].isdigit()):", "enabled and disabled, which the default being enabled. The disabled", "to stop a container. Default is 10. type: int subgidname:", "aliases: - log_options memory: description: - Memory limit (format 10k,", "\"\\n\" return is_different @property def running(self): \"\"\"Return True if container", "list elements: str device_read_bps: description: - Limit read rate (bytes", "0: self.module.fail_json( msg=\"Can't %s container %s\" % (action, self.name), stdout=out,", "[i.lower() for i in after] return self._diff_update_and_compare('command', before, after) return", "namespace (POSIX SysV IPC) for the container type: str kernel_memory:", "/tmp/data - name: Re-create a redis container podman_container: name: myredis", "is considered to be relative to the cgroups path of", "mode use SHAs before = self.info['config']['image'] after = self.params['image'] mode", "+= ['--uidmap', uidmap] return c def addparam_ulimit(self, c): for u", "c += ['--group-add', g] return c def addparam_healthcheck(self, c): return", "addparam_ipc(self, c): return c + ['--ipc', self.params['ipc']] def addparam_kernel_memory(self, c):", "-- name of image Returns: list -- list of image", "License. You may obtain # a copy of the License", "found, the image will be pulled from the registry. If", "supported for integers only. type: str label: description: - Add", "+ ['--cidfile', self.params['cidfile']] def addparam_conmon_pidfile(self, c): return c + ['--conmon-pidfile',", "for i in before] after = self.params['device_write_iops'] or [] before,", "ANY KIND, either express or implied. See the # License", "aliases: - exposed - exposed_ports force_restart: description: - Force restart", "% self.params['http_proxy']] def addparam_image_volume(self, c): return c + ['--image-volume', self.params['image_volume']]", "return self._diff_update_and_compare('ipc', before, after) def diffparam_label(self): before = self.info['config']['labels'] or", "device_read_iops: description: - Limit read rate (IO per second) from", "+ ['--detach=%s' % self.params['detach']] def addparam_detach_keys(self, c): return c +", "def diffparam_etc_hosts(self): if self.info['hostconfig']['extrahosts']: before = dict([i.split(\":\") for i in", "\"exited\" }, \"StaticDir\": \"...\" ... }' \"\"\" class PodmanModuleParams: \"\"\"Creates", "the name, a container will be created and started. Use", "type: str dns_search: description: - Set custom DNS search domains", "required=True) self.image = self.module.params['image'] image_actions = ensure_image_exists(self.module, self.image) self.results['actions'] +=", "\"\"\"Start the container.\"\"\" self._perform_action('start') def create(self): \"\"\"Create the container.\"\"\" self._perform_action('create')", "a bind mount. If you specify, volume /HOST-DIR:/CONTAINER-DIR, podman bind", "type: str detach: description: - Run container in detach mode", "self.module.params['cap_drop']]: if c in after: after.remove(c) before, after = sorted(list(set(before))),", "dict aliases: - add_hosts expose: description: - Expose a port,", "that facts are part of the registered vars since Ansible", "Arguments: action {str} -- action type from 'run', 'stop', 'create',", "a file. conmon runs in a separate process than Podman," ]
[ "'Topic :: Software Development :: Libraries :: Python Modules', ],", "match.group(1) else: raise RuntimeError('Unable to find version string in %r.'", "'bin/filter-sam.py', 'bin/find-hits.py', 'bin/format-fasta.py', 'bin/genome-protein-summary.py', 'bin/get-features.py', 'bin/get-hosts.py', 'bin/get-reads.py', 'bin/get-taxonomy.py', 'bin/graph-evalues.py', 'bin/local-align.py',", "'Cython>=0.29.16', 'ipython>=3.1.0', 'matplotlib>=1.4.3', 'mysql-connector-python==8.0.11', 'numpy>=1.14.2', 'pysam>=0.15.2', 'pyfaidx>=0.4.8.4', 'pyzmq>=14.3.1', 'requests>=2.18.4', 'cachetools>=3.1.0',", "that are not (yet) part of the distribution. scripts =", "'bin/fasta-variable-sites.py', 'bin/filter-fasta-by-complexity.py', 'bin/filter-fasta-by-taxonomy.py', 'bin/filter-fasta.py', 'bin/filter-hits-to-fasta.py', 'bin/filter-reads-alignments.py', 'bin/filter-sam.py', 'bin/find-hits.py', 'bin/format-fasta.py', 'bin/genome-protein-summary.py',", "['\\\"]([^'\\\"]+)['\\\"]\", initData, re.M) if match: return match.group(1) else: raise RuntimeError('Unable", "version string in %r.' % init) # Explicitly list bin", "discovery'], classifiers=[ 'Programming Language :: Python :: 2.7', 'Programming Language", ":: Python :: 3', 'Development Status :: 4 - Beta',", "classes for working with genetic sequence data', scripts=scripts, install_requires=[ 'biopython>=1.71',", "'bin/compare-sequences.py', 'bin/convert-blast-xml-to-json.py', 'bin/convert-diamond-to-json.py', 'bin/convert-diamond-to-sam.py', 'bin/convert-sam-to-fastq.sh', 'bin/create-newick-relabeling-output.py', 'bin/dark-matter-version.py', 'bin/describe-protein-database.py', 'bin/dna-to-aa.py', 'bin/download-genbank.sh',", "'bin/sam-coverage.py', 'bin/sam-coverage-depth.py', 'bin/sam-to-fasta-alignment.py', 'bin/sam-reference-read-counts.py', 'bin/sam-references.py', 'bin/sff-to-fastq.py', 'bin/split-fasta-by-adaptors.py', 'bin/subset-protein-database.py', 'bin/summarize-fasta-bases.py', 'bin/summarize-reads.py',", "'bin/graph-evalues.py', 'bin/local-align.py', 'bin/make-consensus.py', 'bin/make-fasta-database.py', 'bin/make-protein-database.py', 'bin/ncbi-fetch-id.py', 'bin/newick-to-ascii.py', 'bin/noninteractive-alignment-panel.py', 'bin/parse-genbank-flat-file.py', 'bin/position-summary.py',", "re.search(r\"^__version__ = ['\\\"]([^'\\\"]+)['\\\"]\", initData, re.M) if match: return match.group(1) else:", "from setuptools import setup # Modified from http://stackoverflow.com/questions/2058802/ # how-can-i-get-the-version-defined-in-setup-py-setuptools-in-my-package", "find version string in %r.' % init) # Explicitly list", "'dark.diamond', 'dark.civ'], url='https://github.com/acorg/dark-matter', download_url='https://github.com/acorg/dark-matter', author='<NAME>, <NAME>, <NAME>, <NAME>', author_email='<EMAIL>', keywords=['virus", "Python :: 2.7', 'Programming Language :: Python :: 3', 'Development", "'bin/fasta-sort.py', 'bin/fasta-split-by-id.py', 'bin/fasta-subset.py', 'bin/fasta-subtraction.py', 'bin/fasta-to-phylip.py', 'bin/fasta-variable-sites.py', 'bin/filter-fasta-by-complexity.py', 'bin/filter-fasta-by-taxonomy.py', 'bin/filter-fasta.py', 'bin/filter-hits-to-fasta.py',", "'bin/get-hosts.py', 'bin/get-reads.py', 'bin/get-taxonomy.py', 'bin/graph-evalues.py', 'bin/local-align.py', 'bin/make-consensus.py', 'bin/make-fasta-database.py', 'bin/make-protein-database.py', 'bin/ncbi-fetch-id.py', 'bin/newick-to-ascii.py',", "bin files that are not (yet) part of the distribution.", "scripts = [ 'bin/aa-info.py', 'bin/aa-to-dna.py', 'bin/aa-to-properties.py', 'bin/adaptor-distances.py', 'bin/alignment-panel-civ.py', 'bin/alignments-per-read.py', 'bin/bit-score-to-e-value.py',", "'bin/trim-reads.py', 'bin/write-htcondor-job-spec.py', ] setup(name='dark-matter', version=version(), packages=['dark', 'dark.blast', 'dark.diamond', 'dark.civ'], url='https://github.com/acorg/dark-matter',", "'dark.blast', 'dark.diamond', 'dark.civ'], url='https://github.com/acorg/dark-matter', download_url='https://github.com/acorg/dark-matter', author='<NAME>, <NAME>, <NAME>, <NAME>', author_email='<EMAIL>',", "'bin/split-fasta-by-adaptors.py', 'bin/subset-protein-database.py', 'bin/summarize-fasta-bases.py', 'bin/summarize-reads.py', 'bin/trim-primers.py', 'bin/trim-reads.py', 'bin/write-htcondor-job-spec.py', ] setup(name='dark-matter', version=version(),", "2.7', 'Programming Language :: Python :: 3', 'Development Status ::", "re.M) if match: return match.group(1) else: raise RuntimeError('Unable to find", "'bin/codon-distance.py', 'bin/compare-consensuses.py', 'bin/compare-sequences.py', 'bin/convert-blast-xml-to-json.py', 'bin/convert-diamond-to-json.py', 'bin/convert-diamond-to-sam.py', 'bin/convert-sam-to-fastq.sh', 'bin/create-newick-relabeling-output.py', 'bin/dark-matter-version.py', 'bin/describe-protein-database.py',", "'bin/ncbi-fetch-id.py', 'bin/newick-to-ascii.py', 'bin/noninteractive-alignment-panel.py', 'bin/parse-genbank-flat-file.py', 'bin/position-summary.py', 'bin/pre-commit.sh', 'bin/print-blast-xml-for-derek.py', 'bin/print-blast-xml.py', 'bin/print-read-lengths.py', 'bin/proteins-to-pathogens.py',", "OSI Approved :: MIT License', 'Operating System :: OS Independent',", "Modules', ], license='MIT', description='Python classes for working with genetic sequence", "= [ 'bin/aa-info.py', 'bin/aa-to-dna.py', 'bin/aa-to-properties.py', 'bin/adaptor-distances.py', 'bin/alignment-panel-civ.py', 'bin/alignments-per-read.py', 'bin/bit-score-to-e-value.py', 'bin/cat-json-blast-records.py',", "def version(): import os import re init = os.path.join('dark', '__init__.py')", ":: Python :: 2.7', 'Programming Language :: Python :: 3',", "'bin/read-blast-xml.py', 'bin/relabel-newick-tree.py', 'bin/run-bwa.py', 'bin/run-bowtie2.py', 'bin/sam-coverage.py', 'bin/sam-coverage-depth.py', 'bin/sam-to-fasta-alignment.py', 'bin/sam-reference-read-counts.py', 'bin/sam-references.py', 'bin/sff-to-fastq.py',", "open(init) as fp: initData = fp.read() match = re.search(r\"^__version__ =", "'bin/filter-hits-to-fasta.py', 'bin/filter-reads-alignments.py', 'bin/filter-sam.py', 'bin/find-hits.py', 'bin/format-fasta.py', 'bin/genome-protein-summary.py', 'bin/get-features.py', 'bin/get-hosts.py', 'bin/get-reads.py', 'bin/get-taxonomy.py',", "(yet) part of the distribution. scripts = [ 'bin/aa-info.py', 'bin/aa-to-dna.py',", "I have a few local # bin files that are", "with open(init) as fp: initData = fp.read() match = re.search(r\"^__version__", "'bin/noninteractive-alignment-panel.py', 'bin/parse-genbank-flat-file.py', 'bin/position-summary.py', 'bin/pre-commit.sh', 'bin/print-blast-xml-for-derek.py', 'bin/print-blast-xml.py', 'bin/print-read-lengths.py', 'bin/proteins-to-pathogens.py', 'bin/proteins-to-pathogens-civ.py', 'bin/randomize-fasta.py',", "raise RuntimeError('Unable to find version string in %r.' % init)", "fp: initData = fp.read() match = re.search(r\"^__version__ = ['\\\"]([^'\\\"]+)['\\\"]\", initData,", "local # bin files that are not (yet) part of", "'bin/make-consensus.py', 'bin/make-fasta-database.py', 'bin/make-protein-database.py', 'bin/ncbi-fetch-id.py', 'bin/newick-to-ascii.py', 'bin/noninteractive-alignment-panel.py', 'bin/parse-genbank-flat-file.py', 'bin/position-summary.py', 'bin/pre-commit.sh', 'bin/print-blast-xml-for-derek.py',", "download_url='https://github.com/acorg/dark-matter', author='<NAME>, <NAME>, <NAME>, <NAME>', author_email='<EMAIL>', keywords=['virus discovery'], classifiers=[ 'Programming", "'bin/make-protein-database.py', 'bin/ncbi-fetch-id.py', 'bin/newick-to-ascii.py', 'bin/noninteractive-alignment-panel.py', 'bin/parse-genbank-flat-file.py', 'bin/position-summary.py', 'bin/pre-commit.sh', 'bin/print-blast-xml-for-derek.py', 'bin/print-blast-xml.py', 'bin/print-read-lengths.py',", "'bin/pre-commit.sh', 'bin/print-blast-xml-for-derek.py', 'bin/print-blast-xml.py', 'bin/print-read-lengths.py', 'bin/proteins-to-pathogens.py', 'bin/proteins-to-pathogens-civ.py', 'bin/randomize-fasta.py', 'bin/read-blast-json.py', 'bin/read-blast-xml.py', 'bin/relabel-newick-tree.py',", "'bin/make-fasta-database.py', 'bin/make-protein-database.py', 'bin/ncbi-fetch-id.py', 'bin/newick-to-ascii.py', 'bin/noninteractive-alignment-panel.py', 'bin/parse-genbank-flat-file.py', 'bin/position-summary.py', 'bin/pre-commit.sh', 'bin/print-blast-xml-for-derek.py', 'bin/print-blast-xml.py',", "a few local # bin files that are not (yet)", "author_email='<EMAIL>', keywords=['virus discovery'], classifiers=[ 'Programming Language :: Python :: 2.7',", "'bin/compare-consensuses.py', 'bin/compare-sequences.py', 'bin/convert-blast-xml-to-json.py', 'bin/convert-diamond-to-json.py', 'bin/convert-diamond-to-sam.py', 'bin/convert-sam-to-fastq.sh', 'bin/create-newick-relabeling-output.py', 'bin/dark-matter-version.py', 'bin/describe-protein-database.py', 'bin/dna-to-aa.py',", "'bin/sff-to-fastq.py', 'bin/split-fasta-by-adaptors.py', 'bin/subset-protein-database.py', 'bin/summarize-fasta-bases.py', 'bin/summarize-reads.py', 'bin/trim-primers.py', 'bin/trim-reads.py', 'bin/write-htcondor-job-spec.py', ] setup(name='dark-matter',", "= ['\\\"]([^'\\\"]+)['\\\"]\", initData, re.M) if match: return match.group(1) else: raise", "'bin/aa-to-dna.py', 'bin/aa-to-properties.py', 'bin/adaptor-distances.py', 'bin/alignment-panel-civ.py', 'bin/alignments-per-read.py', 'bin/bit-score-to-e-value.py', 'bin/cat-json-blast-records.py', 'bin/check-fasta-json-blast-consistency.py', 'bin/codon-distance.py', 'bin/compare-consensuses.py',", "MIT License', 'Operating System :: OS Independent', 'Topic :: Software", "'bin/e-value-to-bit-score.py', 'bin/extract-ORFs.py', 'bin/fasta-base-indices.py', 'bin/fasta-count.py', 'bin/fasta-diff.sh', 'bin/fasta-identity-table.py', 'bin/fasta-ids.py', 'bin/fasta-join.py', 'bin/fasta-lengths.py', 'bin/fasta-sequences.py',", "<NAME>, <NAME>', author_email='<EMAIL>', keywords=['virus discovery'], classifiers=[ 'Programming Language :: Python", "'Operating System :: OS Independent', 'Topic :: Software Development ::", "'bin/newick-to-ascii.py', 'bin/noninteractive-alignment-panel.py', 'bin/parse-genbank-flat-file.py', 'bin/position-summary.py', 'bin/pre-commit.sh', 'bin/print-blast-xml-for-derek.py', 'bin/print-blast-xml.py', 'bin/print-read-lengths.py', 'bin/proteins-to-pathogens.py', 'bin/proteins-to-pathogens-civ.py',", "'bin/sam-to-fasta-alignment.py', 'bin/sam-reference-read-counts.py', 'bin/sam-references.py', 'bin/sff-to-fastq.py', 'bin/split-fasta-by-adaptors.py', 'bin/subset-protein-database.py', 'bin/summarize-fasta-bases.py', 'bin/summarize-reads.py', 'bin/trim-primers.py', 'bin/trim-reads.py',", ":: Libraries :: Python Modules', ], license='MIT', description='Python classes for", "from http://stackoverflow.com/questions/2058802/ # how-can-i-get-the-version-defined-in-setup-py-setuptools-in-my-package def version(): import os import re", "'Intended Audience :: Developers', 'License :: OSI Approved :: MIT", "#!/usr/bin/env python from setuptools import setup # Modified from http://stackoverflow.com/questions/2058802/", "'bin/sam-coverage-depth.py', 'bin/sam-to-fasta-alignment.py', 'bin/sam-reference-read-counts.py', 'bin/sam-references.py', 'bin/sff-to-fastq.py', 'bin/split-fasta-by-adaptors.py', 'bin/subset-protein-database.py', 'bin/summarize-fasta-bases.py', 'bin/summarize-reads.py', 'bin/trim-primers.py',", "setup(name='dark-matter', version=version(), packages=['dark', 'dark.blast', 'dark.diamond', 'dark.civ'], url='https://github.com/acorg/dark-matter', download_url='https://github.com/acorg/dark-matter', author='<NAME>, <NAME>,", "'bin/filter-fasta-by-taxonomy.py', 'bin/filter-fasta.py', 'bin/filter-hits-to-fasta.py', 'bin/filter-reads-alignments.py', 'bin/filter-sam.py', 'bin/find-hits.py', 'bin/format-fasta.py', 'bin/genome-protein-summary.py', 'bin/get-features.py', 'bin/get-hosts.py',", "to be installed, seeing as I have a few local", "'bin/fasta-split-by-id.py', 'bin/fasta-subset.py', 'bin/fasta-subtraction.py', 'bin/fasta-to-phylip.py', 'bin/fasta-variable-sites.py', 'bin/filter-fasta-by-complexity.py', 'bin/filter-fasta-by-taxonomy.py', 'bin/filter-fasta.py', 'bin/filter-hits-to-fasta.py', 'bin/filter-reads-alignments.py',", "'bin/filter-fasta-by-complexity.py', 'bin/filter-fasta-by-taxonomy.py', 'bin/filter-fasta.py', 'bin/filter-hits-to-fasta.py', 'bin/filter-reads-alignments.py', 'bin/filter-sam.py', 'bin/find-hits.py', 'bin/format-fasta.py', 'bin/genome-protein-summary.py', 'bin/get-features.py',", "System :: OS Independent', 'Topic :: Software Development :: Libraries", "as I have a few local # bin files that", "'bin/get-taxonomy.py', 'bin/graph-evalues.py', 'bin/local-align.py', 'bin/make-consensus.py', 'bin/make-fasta-database.py', 'bin/make-protein-database.py', 'bin/ncbi-fetch-id.py', 'bin/newick-to-ascii.py', 'bin/noninteractive-alignment-panel.py', 'bin/parse-genbank-flat-file.py',", "the distribution. scripts = [ 'bin/aa-info.py', 'bin/aa-to-dna.py', 'bin/aa-to-properties.py', 'bin/adaptor-distances.py', 'bin/alignment-panel-civ.py',", ":: Developers', 'License :: OSI Approved :: MIT License', 'Operating", "setup # Modified from http://stackoverflow.com/questions/2058802/ # how-can-i-get-the-version-defined-in-setup-py-setuptools-in-my-package def version(): import", ":: MIT License', 'Operating System :: OS Independent', 'Topic ::", "- Beta', 'Intended Audience :: Developers', 'License :: OSI Approved", "in %r.' % init) # Explicitly list bin scripts to", "else: raise RuntimeError('Unable to find version string in %r.' %", "'mysql-connector-python==8.0.11', 'numpy>=1.14.2', 'pysam>=0.15.2', 'pyfaidx>=0.4.8.4', 'pyzmq>=14.3.1', 'requests>=2.18.4', 'cachetools>=3.1.0', 'simplejson>=3.5.3', 'six>=1.11.0', ])", "Language :: Python :: 2.7', 'Programming Language :: Python ::", "Python Modules', ], license='MIT', description='Python classes for working with genetic", "data', scripts=scripts, install_requires=[ 'biopython>=1.71', 'bz2file>=0.98', 'Cython>=0.29.16', 'ipython>=3.1.0', 'matplotlib>=1.4.3', 'mysql-connector-python==8.0.11', 'numpy>=1.14.2',", ":: Software Development :: Libraries :: Python Modules', ], license='MIT',", ":: OS Independent', 'Topic :: Software Development :: Libraries ::", "be installed, seeing as I have a few local #", "'bin/sam-references.py', 'bin/sff-to-fastq.py', 'bin/split-fasta-by-adaptors.py', 'bin/subset-protein-database.py', 'bin/summarize-fasta-bases.py', 'bin/summarize-reads.py', 'bin/trim-primers.py', 'bin/trim-reads.py', 'bin/write-htcondor-job-spec.py', ]", "'bin/get-features.py', 'bin/get-hosts.py', 'bin/get-reads.py', 'bin/get-taxonomy.py', 'bin/graph-evalues.py', 'bin/local-align.py', 'bin/make-consensus.py', 'bin/make-fasta-database.py', 'bin/make-protein-database.py', 'bin/ncbi-fetch-id.py',", "'bin/sam-reference-read-counts.py', 'bin/sam-references.py', 'bin/sff-to-fastq.py', 'bin/split-fasta-by-adaptors.py', 'bin/subset-protein-database.py', 'bin/summarize-fasta-bases.py', 'bin/summarize-reads.py', 'bin/trim-primers.py', 'bin/trim-reads.py', 'bin/write-htcondor-job-spec.py',", "to find version string in %r.' % init) # Explicitly", "'dark.civ'], url='https://github.com/acorg/dark-matter', download_url='https://github.com/acorg/dark-matter', author='<NAME>, <NAME>, <NAME>, <NAME>', author_email='<EMAIL>', keywords=['virus discovery'],", "'bin/convert-sam-to-fastq.sh', 'bin/create-newick-relabeling-output.py', 'bin/dark-matter-version.py', 'bin/describe-protein-database.py', 'bin/dna-to-aa.py', 'bin/download-genbank.sh', 'bin/e-value-to-bit-score.py', 'bin/extract-ORFs.py', 'bin/fasta-base-indices.py', 'bin/fasta-count.py',", "'bin/aa-to-properties.py', 'bin/adaptor-distances.py', 'bin/alignment-panel-civ.py', 'bin/alignments-per-read.py', 'bin/bit-score-to-e-value.py', 'bin/cat-json-blast-records.py', 'bin/check-fasta-json-blast-consistency.py', 'bin/codon-distance.py', 'bin/compare-consensuses.py', 'bin/compare-sequences.py',", "return match.group(1) else: raise RuntimeError('Unable to find version string in", "%r.' % init) # Explicitly list bin scripts to be", "list bin scripts to be installed, seeing as I have", "] setup(name='dark-matter', version=version(), packages=['dark', 'dark.blast', 'dark.diamond', 'dark.civ'], url='https://github.com/acorg/dark-matter', download_url='https://github.com/acorg/dark-matter', author='<NAME>,", "'Development Status :: 4 - Beta', 'Intended Audience :: Developers',", "<NAME>', author_email='<EMAIL>', keywords=['virus discovery'], classifiers=[ 'Programming Language :: Python ::", ":: 3', 'Development Status :: 4 - Beta', 'Intended Audience", "'bin/run-bowtie2.py', 'bin/sam-coverage.py', 'bin/sam-coverage-depth.py', 'bin/sam-to-fasta-alignment.py', 'bin/sam-reference-read-counts.py', 'bin/sam-references.py', 'bin/sff-to-fastq.py', 'bin/split-fasta-by-adaptors.py', 'bin/subset-protein-database.py', 'bin/summarize-fasta-bases.py',", "bin scripts to be installed, seeing as I have a", "= fp.read() match = re.search(r\"^__version__ = ['\\\"]([^'\\\"]+)['\\\"]\", initData, re.M) if", "of the distribution. scripts = [ 'bin/aa-info.py', 'bin/aa-to-dna.py', 'bin/aa-to-properties.py', 'bin/adaptor-distances.py',", "match: return match.group(1) else: raise RuntimeError('Unable to find version string", "version(): import os import re init = os.path.join('dark', '__init__.py') with", "% init) # Explicitly list bin scripts to be installed,", "'matplotlib>=1.4.3', 'mysql-connector-python==8.0.11', 'numpy>=1.14.2', 'pysam>=0.15.2', 'pyfaidx>=0.4.8.4', 'pyzmq>=14.3.1', 'requests>=2.18.4', 'cachetools>=3.1.0', 'simplejson>=3.5.3', 'six>=1.11.0',", "<NAME>, <NAME>, <NAME>', author_email='<EMAIL>', keywords=['virus discovery'], classifiers=[ 'Programming Language ::", "'Programming Language :: Python :: 2.7', 'Programming Language :: Python", "Beta', 'Intended Audience :: Developers', 'License :: OSI Approved ::", "'bin/cat-json-blast-records.py', 'bin/check-fasta-json-blast-consistency.py', 'bin/codon-distance.py', 'bin/compare-consensuses.py', 'bin/compare-sequences.py', 'bin/convert-blast-xml-to-json.py', 'bin/convert-diamond-to-json.py', 'bin/convert-diamond-to-sam.py', 'bin/convert-sam-to-fastq.sh', 'bin/create-newick-relabeling-output.py',", "'bin/convert-diamond-to-sam.py', 'bin/convert-sam-to-fastq.sh', 'bin/create-newick-relabeling-output.py', 'bin/dark-matter-version.py', 'bin/describe-protein-database.py', 'bin/dna-to-aa.py', 'bin/download-genbank.sh', 'bin/e-value-to-bit-score.py', 'bin/extract-ORFs.py', 'bin/fasta-base-indices.py',", "'bin/filter-reads-alignments.py', 'bin/filter-sam.py', 'bin/find-hits.py', 'bin/format-fasta.py', 'bin/genome-protein-summary.py', 'bin/get-features.py', 'bin/get-hosts.py', 'bin/get-reads.py', 'bin/get-taxonomy.py', 'bin/graph-evalues.py',", "'bin/check-fasta-json-blast-consistency.py', 'bin/codon-distance.py', 'bin/compare-consensuses.py', 'bin/compare-sequences.py', 'bin/convert-blast-xml-to-json.py', 'bin/convert-diamond-to-json.py', 'bin/convert-diamond-to-sam.py', 'bin/convert-sam-to-fastq.sh', 'bin/create-newick-relabeling-output.py', 'bin/dark-matter-version.py',", "'bin/subset-protein-database.py', 'bin/summarize-fasta-bases.py', 'bin/summarize-reads.py', 'bin/trim-primers.py', 'bin/trim-reads.py', 'bin/write-htcondor-job-spec.py', ] setup(name='dark-matter', version=version(), packages=['dark',", "packages=['dark', 'dark.blast', 'dark.diamond', 'dark.civ'], url='https://github.com/acorg/dark-matter', download_url='https://github.com/acorg/dark-matter', author='<NAME>, <NAME>, <NAME>, <NAME>',", "= os.path.join('dark', '__init__.py') with open(init) as fp: initData = fp.read()", "'bin/alignments-per-read.py', 'bin/bit-score-to-e-value.py', 'bin/cat-json-blast-records.py', 'bin/check-fasta-json-blast-consistency.py', 'bin/codon-distance.py', 'bin/compare-consensuses.py', 'bin/compare-sequences.py', 'bin/convert-blast-xml-to-json.py', 'bin/convert-diamond-to-json.py', 'bin/convert-diamond-to-sam.py',", ":: OSI Approved :: MIT License', 'Operating System :: OS", "'__init__.py') with open(init) as fp: initData = fp.read() match =", "'bin/position-summary.py', 'bin/pre-commit.sh', 'bin/print-blast-xml-for-derek.py', 'bin/print-blast-xml.py', 'bin/print-read-lengths.py', 'bin/proteins-to-pathogens.py', 'bin/proteins-to-pathogens-civ.py', 'bin/randomize-fasta.py', 'bin/read-blast-json.py', 'bin/read-blast-xml.py',", "OS Independent', 'Topic :: Software Development :: Libraries :: Python", "python from setuptools import setup # Modified from http://stackoverflow.com/questions/2058802/ #", "'bz2file>=0.98', 'Cython>=0.29.16', 'ipython>=3.1.0', 'matplotlib>=1.4.3', 'mysql-connector-python==8.0.11', 'numpy>=1.14.2', 'pysam>=0.15.2', 'pyfaidx>=0.4.8.4', 'pyzmq>=14.3.1', 'requests>=2.18.4',", "if match: return match.group(1) else: raise RuntimeError('Unable to find version", "distribution. scripts = [ 'bin/aa-info.py', 'bin/aa-to-dna.py', 'bin/aa-to-properties.py', 'bin/adaptor-distances.py', 'bin/alignment-panel-civ.py', 'bin/alignments-per-read.py',", "url='https://github.com/acorg/dark-matter', download_url='https://github.com/acorg/dark-matter', author='<NAME>, <NAME>, <NAME>, <NAME>', author_email='<EMAIL>', keywords=['virus discovery'], classifiers=[", "'bin/alignment-panel-civ.py', 'bin/alignments-per-read.py', 'bin/bit-score-to-e-value.py', 'bin/cat-json-blast-records.py', 'bin/check-fasta-json-blast-consistency.py', 'bin/codon-distance.py', 'bin/compare-consensuses.py', 'bin/compare-sequences.py', 'bin/convert-blast-xml-to-json.py', 'bin/convert-diamond-to-json.py',", "'bin/fasta-count.py', 'bin/fasta-diff.sh', 'bin/fasta-identity-table.py', 'bin/fasta-ids.py', 'bin/fasta-join.py', 'bin/fasta-lengths.py', 'bin/fasta-sequences.py', 'bin/fasta-sort.py', 'bin/fasta-split-by-id.py', 'bin/fasta-subset.py',", "author='<NAME>, <NAME>, <NAME>, <NAME>', author_email='<EMAIL>', keywords=['virus discovery'], classifiers=[ 'Programming Language", "'bin/fasta-subset.py', 'bin/fasta-subtraction.py', 'bin/fasta-to-phylip.py', 'bin/fasta-variable-sites.py', 'bin/filter-fasta-by-complexity.py', 'bin/filter-fasta-by-taxonomy.py', 'bin/filter-fasta.py', 'bin/filter-hits-to-fasta.py', 'bin/filter-reads-alignments.py', 'bin/filter-sam.py',", "'bin/convert-blast-xml-to-json.py', 'bin/convert-diamond-to-json.py', 'bin/convert-diamond-to-sam.py', 'bin/convert-sam-to-fastq.sh', 'bin/create-newick-relabeling-output.py', 'bin/dark-matter-version.py', 'bin/describe-protein-database.py', 'bin/dna-to-aa.py', 'bin/download-genbank.sh', 'bin/e-value-to-bit-score.py',", "'bin/convert-diamond-to-json.py', 'bin/convert-diamond-to-sam.py', 'bin/convert-sam-to-fastq.sh', 'bin/create-newick-relabeling-output.py', 'bin/dark-matter-version.py', 'bin/describe-protein-database.py', 'bin/dna-to-aa.py', 'bin/download-genbank.sh', 'bin/e-value-to-bit-score.py', 'bin/extract-ORFs.py',", "Developers', 'License :: OSI Approved :: MIT License', 'Operating System", "'bin/read-blast-json.py', 'bin/read-blast-xml.py', 'bin/relabel-newick-tree.py', 'bin/run-bwa.py', 'bin/run-bowtie2.py', 'bin/sam-coverage.py', 'bin/sam-coverage-depth.py', 'bin/sam-to-fasta-alignment.py', 'bin/sam-reference-read-counts.py', 'bin/sam-references.py',", "init) # Explicitly list bin scripts to be installed, seeing", "initData = fp.read() match = re.search(r\"^__version__ = ['\\\"]([^'\\\"]+)['\\\"]\", initData, re.M)", "os import re init = os.path.join('dark', '__init__.py') with open(init) as", "'bin/create-newick-relabeling-output.py', 'bin/dark-matter-version.py', 'bin/describe-protein-database.py', 'bin/dna-to-aa.py', 'bin/download-genbank.sh', 'bin/e-value-to-bit-score.py', 'bin/extract-ORFs.py', 'bin/fasta-base-indices.py', 'bin/fasta-count.py', 'bin/fasta-diff.sh',", "# Modified from http://stackoverflow.com/questions/2058802/ # how-can-i-get-the-version-defined-in-setup-py-setuptools-in-my-package def version(): import os", "4 - Beta', 'Intended Audience :: Developers', 'License :: OSI", "'bin/fasta-subtraction.py', 'bin/fasta-to-phylip.py', 'bin/fasta-variable-sites.py', 'bin/filter-fasta-by-complexity.py', 'bin/filter-fasta-by-taxonomy.py', 'bin/filter-fasta.py', 'bin/filter-hits-to-fasta.py', 'bin/filter-reads-alignments.py', 'bin/filter-sam.py', 'bin/find-hits.py',", "Modified from http://stackoverflow.com/questions/2058802/ # how-can-i-get-the-version-defined-in-setup-py-setuptools-in-my-package def version(): import os import", "fp.read() match = re.search(r\"^__version__ = ['\\\"]([^'\\\"]+)['\\\"]\", initData, re.M) if match:", "RuntimeError('Unable to find version string in %r.' % init) #", "'bin/fasta-ids.py', 'bin/fasta-join.py', 'bin/fasta-lengths.py', 'bin/fasta-sequences.py', 'bin/fasta-sort.py', 'bin/fasta-split-by-id.py', 'bin/fasta-subset.py', 'bin/fasta-subtraction.py', 'bin/fasta-to-phylip.py', 'bin/fasta-variable-sites.py',", "'bin/filter-fasta.py', 'bin/filter-hits-to-fasta.py', 'bin/filter-reads-alignments.py', 'bin/filter-sam.py', 'bin/find-hits.py', 'bin/format-fasta.py', 'bin/genome-protein-summary.py', 'bin/get-features.py', 'bin/get-hosts.py', 'bin/get-reads.py',", "'bin/proteins-to-pathogens-civ.py', 'bin/randomize-fasta.py', 'bin/read-blast-json.py', 'bin/read-blast-xml.py', 'bin/relabel-newick-tree.py', 'bin/run-bwa.py', 'bin/run-bowtie2.py', 'bin/sam-coverage.py', 'bin/sam-coverage-depth.py', 'bin/sam-to-fasta-alignment.py',", "'bin/local-align.py', 'bin/make-consensus.py', 'bin/make-fasta-database.py', 'bin/make-protein-database.py', 'bin/ncbi-fetch-id.py', 'bin/newick-to-ascii.py', 'bin/noninteractive-alignment-panel.py', 'bin/parse-genbank-flat-file.py', 'bin/position-summary.py', 'bin/pre-commit.sh',", "'bin/bit-score-to-e-value.py', 'bin/cat-json-blast-records.py', 'bin/check-fasta-json-blast-consistency.py', 'bin/codon-distance.py', 'bin/compare-consensuses.py', 'bin/compare-sequences.py', 'bin/convert-blast-xml-to-json.py', 'bin/convert-diamond-to-json.py', 'bin/convert-diamond-to-sam.py', 'bin/convert-sam-to-fastq.sh',", "Independent', 'Topic :: Software Development :: Libraries :: Python Modules',", "'ipython>=3.1.0', 'matplotlib>=1.4.3', 'mysql-connector-python==8.0.11', 'numpy>=1.14.2', 'pysam>=0.15.2', 'pyfaidx>=0.4.8.4', 'pyzmq>=14.3.1', 'requests>=2.18.4', 'cachetools>=3.1.0', 'simplejson>=3.5.3',", "setuptools import setup # Modified from http://stackoverflow.com/questions/2058802/ # how-can-i-get-the-version-defined-in-setup-py-setuptools-in-my-package def", "# how-can-i-get-the-version-defined-in-setup-py-setuptools-in-my-package def version(): import os import re init =", "description='Python classes for working with genetic sequence data', scripts=scripts, install_requires=[", "'bin/fasta-sequences.py', 'bin/fasta-sort.py', 'bin/fasta-split-by-id.py', 'bin/fasta-subset.py', 'bin/fasta-subtraction.py', 'bin/fasta-to-phylip.py', 'bin/fasta-variable-sites.py', 'bin/filter-fasta-by-complexity.py', 'bin/filter-fasta-by-taxonomy.py', 'bin/filter-fasta.py',", "'bin/summarize-fasta-bases.py', 'bin/summarize-reads.py', 'bin/trim-primers.py', 'bin/trim-reads.py', 'bin/write-htcondor-job-spec.py', ] setup(name='dark-matter', version=version(), packages=['dark', 'dark.blast',", "], license='MIT', description='Python classes for working with genetic sequence data',", "import re init = os.path.join('dark', '__init__.py') with open(init) as fp:", "'bin/aa-info.py', 'bin/aa-to-dna.py', 'bin/aa-to-properties.py', 'bin/adaptor-distances.py', 'bin/alignment-panel-civ.py', 'bin/alignments-per-read.py', 'bin/bit-score-to-e-value.py', 'bin/cat-json-blast-records.py', 'bin/check-fasta-json-blast-consistency.py', 'bin/codon-distance.py',", "'bin/dna-to-aa.py', 'bin/download-genbank.sh', 'bin/e-value-to-bit-score.py', 'bin/extract-ORFs.py', 'bin/fasta-base-indices.py', 'bin/fasta-count.py', 'bin/fasta-diff.sh', 'bin/fasta-identity-table.py', 'bin/fasta-ids.py', 'bin/fasta-join.py',", "License', 'Operating System :: OS Independent', 'Topic :: Software Development", "scripts=scripts, install_requires=[ 'biopython>=1.71', 'bz2file>=0.98', 'Cython>=0.29.16', 'ipython>=3.1.0', 'matplotlib>=1.4.3', 'mysql-connector-python==8.0.11', 'numpy>=1.14.2', 'pysam>=0.15.2',", "'bin/print-blast-xml-for-derek.py', 'bin/print-blast-xml.py', 'bin/print-read-lengths.py', 'bin/proteins-to-pathogens.py', 'bin/proteins-to-pathogens-civ.py', 'bin/randomize-fasta.py', 'bin/read-blast-json.py', 'bin/read-blast-xml.py', 'bin/relabel-newick-tree.py', 'bin/run-bwa.py',", "scripts to be installed, seeing as I have a few", "'bin/relabel-newick-tree.py', 'bin/run-bwa.py', 'bin/run-bowtie2.py', 'bin/sam-coverage.py', 'bin/sam-coverage-depth.py', 'bin/sam-to-fasta-alignment.py', 'bin/sam-reference-read-counts.py', 'bin/sam-references.py', 'bin/sff-to-fastq.py', 'bin/split-fasta-by-adaptors.py',", ":: 2.7', 'Programming Language :: Python :: 3', 'Development Status", "'biopython>=1.71', 'bz2file>=0.98', 'Cython>=0.29.16', 'ipython>=3.1.0', 'matplotlib>=1.4.3', 'mysql-connector-python==8.0.11', 'numpy>=1.14.2', 'pysam>=0.15.2', 'pyfaidx>=0.4.8.4', 'pyzmq>=14.3.1',", "Python :: 3', 'Development Status :: 4 - Beta', 'Intended", "'bin/fasta-lengths.py', 'bin/fasta-sequences.py', 'bin/fasta-sort.py', 'bin/fasta-split-by-id.py', 'bin/fasta-subset.py', 'bin/fasta-subtraction.py', 'bin/fasta-to-phylip.py', 'bin/fasta-variable-sites.py', 'bin/filter-fasta-by-complexity.py', 'bin/filter-fasta-by-taxonomy.py',", "for working with genetic sequence data', scripts=scripts, install_requires=[ 'biopython>=1.71', 'bz2file>=0.98',", "Explicitly list bin scripts to be installed, seeing as I", "few local # bin files that are not (yet) part", "seeing as I have a few local # bin files", "installed, seeing as I have a few local # bin", "'bin/summarize-reads.py', 'bin/trim-primers.py', 'bin/trim-reads.py', 'bin/write-htcondor-job-spec.py', ] setup(name='dark-matter', version=version(), packages=['dark', 'dark.blast', 'dark.diamond',", "[ 'bin/aa-info.py', 'bin/aa-to-dna.py', 'bin/aa-to-properties.py', 'bin/adaptor-distances.py', 'bin/alignment-panel-civ.py', 'bin/alignments-per-read.py', 'bin/bit-score-to-e-value.py', 'bin/cat-json-blast-records.py', 'bin/check-fasta-json-blast-consistency.py',", "as fp: initData = fp.read() match = re.search(r\"^__version__ = ['\\\"]([^'\\\"]+)['\\\"]\",", "with genetic sequence data', scripts=scripts, install_requires=[ 'biopython>=1.71', 'bz2file>=0.98', 'Cython>=0.29.16', 'ipython>=3.1.0',", "keywords=['virus discovery'], classifiers=[ 'Programming Language :: Python :: 2.7', 'Programming", "'bin/print-read-lengths.py', 'bin/proteins-to-pathogens.py', 'bin/proteins-to-pathogens-civ.py', 'bin/randomize-fasta.py', 'bin/read-blast-json.py', 'bin/read-blast-xml.py', 'bin/relabel-newick-tree.py', 'bin/run-bwa.py', 'bin/run-bowtie2.py', 'bin/sam-coverage.py',", "'bin/fasta-to-phylip.py', 'bin/fasta-variable-sites.py', 'bin/filter-fasta-by-complexity.py', 'bin/filter-fasta-by-taxonomy.py', 'bin/filter-fasta.py', 'bin/filter-hits-to-fasta.py', 'bin/filter-reads-alignments.py', 'bin/filter-sam.py', 'bin/find-hits.py', 'bin/format-fasta.py',", "match = re.search(r\"^__version__ = ['\\\"]([^'\\\"]+)['\\\"]\", initData, re.M) if match: return", "'License :: OSI Approved :: MIT License', 'Operating System ::", "initData, re.M) if match: return match.group(1) else: raise RuntimeError('Unable to", "'bin/dark-matter-version.py', 'bin/describe-protein-database.py', 'bin/dna-to-aa.py', 'bin/download-genbank.sh', 'bin/e-value-to-bit-score.py', 'bin/extract-ORFs.py', 'bin/fasta-base-indices.py', 'bin/fasta-count.py', 'bin/fasta-diff.sh', 'bin/fasta-identity-table.py',", "'bin/genome-protein-summary.py', 'bin/get-features.py', 'bin/get-hosts.py', 'bin/get-reads.py', 'bin/get-taxonomy.py', 'bin/graph-evalues.py', 'bin/local-align.py', 'bin/make-consensus.py', 'bin/make-fasta-database.py', 'bin/make-protein-database.py',", "'bin/print-blast-xml.py', 'bin/print-read-lengths.py', 'bin/proteins-to-pathogens.py', 'bin/proteins-to-pathogens-civ.py', 'bin/randomize-fasta.py', 'bin/read-blast-json.py', 'bin/read-blast-xml.py', 'bin/relabel-newick-tree.py', 'bin/run-bwa.py', 'bin/run-bowtie2.py',", "'bin/parse-genbank-flat-file.py', 'bin/position-summary.py', 'bin/pre-commit.sh', 'bin/print-blast-xml-for-derek.py', 'bin/print-blast-xml.py', 'bin/print-read-lengths.py', 'bin/proteins-to-pathogens.py', 'bin/proteins-to-pathogens-civ.py', 'bin/randomize-fasta.py', 'bin/read-blast-json.py',", "files that are not (yet) part of the distribution. scripts", "classifiers=[ 'Programming Language :: Python :: 2.7', 'Programming Language ::", "'bin/fasta-identity-table.py', 'bin/fasta-ids.py', 'bin/fasta-join.py', 'bin/fasta-lengths.py', 'bin/fasta-sequences.py', 'bin/fasta-sort.py', 'bin/fasta-split-by-id.py', 'bin/fasta-subset.py', 'bin/fasta-subtraction.py', 'bin/fasta-to-phylip.py',", "'bin/write-htcondor-job-spec.py', ] setup(name='dark-matter', version=version(), packages=['dark', 'dark.blast', 'dark.diamond', 'dark.civ'], url='https://github.com/acorg/dark-matter', download_url='https://github.com/acorg/dark-matter',", "'bin/proteins-to-pathogens.py', 'bin/proteins-to-pathogens-civ.py', 'bin/randomize-fasta.py', 'bin/read-blast-json.py', 'bin/read-blast-xml.py', 'bin/relabel-newick-tree.py', 'bin/run-bwa.py', 'bin/run-bowtie2.py', 'bin/sam-coverage.py', 'bin/sam-coverage-depth.py',", "version=version(), packages=['dark', 'dark.blast', 'dark.diamond', 'dark.civ'], url='https://github.com/acorg/dark-matter', download_url='https://github.com/acorg/dark-matter', author='<NAME>, <NAME>, <NAME>,", "'bin/run-bwa.py', 'bin/run-bowtie2.py', 'bin/sam-coverage.py', 'bin/sam-coverage-depth.py', 'bin/sam-to-fasta-alignment.py', 'bin/sam-reference-read-counts.py', 'bin/sam-references.py', 'bin/sff-to-fastq.py', 'bin/split-fasta-by-adaptors.py', 'bin/subset-protein-database.py',", "Development :: Libraries :: Python Modules', ], license='MIT', description='Python classes", "'bin/format-fasta.py', 'bin/genome-protein-summary.py', 'bin/get-features.py', 'bin/get-hosts.py', 'bin/get-reads.py', 'bin/get-taxonomy.py', 'bin/graph-evalues.py', 'bin/local-align.py', 'bin/make-consensus.py', 'bin/make-fasta-database.py',", "init = os.path.join('dark', '__init__.py') with open(init) as fp: initData =", "'Programming Language :: Python :: 3', 'Development Status :: 4", "Software Development :: Libraries :: Python Modules', ], license='MIT', description='Python", "license='MIT', description='Python classes for working with genetic sequence data', scripts=scripts,", "re init = os.path.join('dark', '__init__.py') with open(init) as fp: initData", "part of the distribution. scripts = [ 'bin/aa-info.py', 'bin/aa-to-dna.py', 'bin/aa-to-properties.py',", "'bin/trim-primers.py', 'bin/trim-reads.py', 'bin/write-htcondor-job-spec.py', ] setup(name='dark-matter', version=version(), packages=['dark', 'dark.blast', 'dark.diamond', 'dark.civ'],", "Status :: 4 - Beta', 'Intended Audience :: Developers', 'License", "'bin/get-reads.py', 'bin/get-taxonomy.py', 'bin/graph-evalues.py', 'bin/local-align.py', 'bin/make-consensus.py', 'bin/make-fasta-database.py', 'bin/make-protein-database.py', 'bin/ncbi-fetch-id.py', 'bin/newick-to-ascii.py', 'bin/noninteractive-alignment-panel.py',", ":: Python Modules', ], license='MIT', description='Python classes for working with", "sequence data', scripts=scripts, install_requires=[ 'biopython>=1.71', 'bz2file>=0.98', 'Cython>=0.29.16', 'ipython>=3.1.0', 'matplotlib>=1.4.3', 'mysql-connector-python==8.0.11',", "install_requires=[ 'biopython>=1.71', 'bz2file>=0.98', 'Cython>=0.29.16', 'ipython>=3.1.0', 'matplotlib>=1.4.3', 'mysql-connector-python==8.0.11', 'numpy>=1.14.2', 'pysam>=0.15.2', 'pyfaidx>=0.4.8.4',", "3', 'Development Status :: 4 - Beta', 'Intended Audience ::", "= re.search(r\"^__version__ = ['\\\"]([^'\\\"]+)['\\\"]\", initData, re.M) if match: return match.group(1)", "Libraries :: Python Modules', ], license='MIT', description='Python classes for working", "'bin/fasta-diff.sh', 'bin/fasta-identity-table.py', 'bin/fasta-ids.py', 'bin/fasta-join.py', 'bin/fasta-lengths.py', 'bin/fasta-sequences.py', 'bin/fasta-sort.py', 'bin/fasta-split-by-id.py', 'bin/fasta-subset.py', 'bin/fasta-subtraction.py',", ":: 4 - Beta', 'Intended Audience :: Developers', 'License ::", "Audience :: Developers', 'License :: OSI Approved :: MIT License',", "'bin/find-hits.py', 'bin/format-fasta.py', 'bin/genome-protein-summary.py', 'bin/get-features.py', 'bin/get-hosts.py', 'bin/get-reads.py', 'bin/get-taxonomy.py', 'bin/graph-evalues.py', 'bin/local-align.py', 'bin/make-consensus.py',", "'bin/extract-ORFs.py', 'bin/fasta-base-indices.py', 'bin/fasta-count.py', 'bin/fasta-diff.sh', 'bin/fasta-identity-table.py', 'bin/fasta-ids.py', 'bin/fasta-join.py', 'bin/fasta-lengths.py', 'bin/fasta-sequences.py', 'bin/fasta-sort.py',", "'bin/describe-protein-database.py', 'bin/dna-to-aa.py', 'bin/download-genbank.sh', 'bin/e-value-to-bit-score.py', 'bin/extract-ORFs.py', 'bin/fasta-base-indices.py', 'bin/fasta-count.py', 'bin/fasta-diff.sh', 'bin/fasta-identity-table.py', 'bin/fasta-ids.py',", "http://stackoverflow.com/questions/2058802/ # how-can-i-get-the-version-defined-in-setup-py-setuptools-in-my-package def version(): import os import re init", "'bin/randomize-fasta.py', 'bin/read-blast-json.py', 'bin/read-blast-xml.py', 'bin/relabel-newick-tree.py', 'bin/run-bwa.py', 'bin/run-bowtie2.py', 'bin/sam-coverage.py', 'bin/sam-coverage-depth.py', 'bin/sam-to-fasta-alignment.py', 'bin/sam-reference-read-counts.py',", "not (yet) part of the distribution. scripts = [ 'bin/aa-info.py',", "os.path.join('dark', '__init__.py') with open(init) as fp: initData = fp.read() match", "'bin/download-genbank.sh', 'bin/e-value-to-bit-score.py', 'bin/extract-ORFs.py', 'bin/fasta-base-indices.py', 'bin/fasta-count.py', 'bin/fasta-diff.sh', 'bin/fasta-identity-table.py', 'bin/fasta-ids.py', 'bin/fasta-join.py', 'bin/fasta-lengths.py',", "import os import re init = os.path.join('dark', '__init__.py') with open(init)", "Approved :: MIT License', 'Operating System :: OS Independent', 'Topic", "string in %r.' % init) # Explicitly list bin scripts", "'bin/fasta-join.py', 'bin/fasta-lengths.py', 'bin/fasta-sequences.py', 'bin/fasta-sort.py', 'bin/fasta-split-by-id.py', 'bin/fasta-subset.py', 'bin/fasta-subtraction.py', 'bin/fasta-to-phylip.py', 'bin/fasta-variable-sites.py', 'bin/filter-fasta-by-complexity.py',", "working with genetic sequence data', scripts=scripts, install_requires=[ 'biopython>=1.71', 'bz2file>=0.98', 'Cython>=0.29.16',", "are not (yet) part of the distribution. scripts = [", "how-can-i-get-the-version-defined-in-setup-py-setuptools-in-my-package def version(): import os import re init = os.path.join('dark',", "# bin files that are not (yet) part of the", "'bin/fasta-base-indices.py', 'bin/fasta-count.py', 'bin/fasta-diff.sh', 'bin/fasta-identity-table.py', 'bin/fasta-ids.py', 'bin/fasta-join.py', 'bin/fasta-lengths.py', 'bin/fasta-sequences.py', 'bin/fasta-sort.py', 'bin/fasta-split-by-id.py',", "Language :: Python :: 3', 'Development Status :: 4 -", "have a few local # bin files that are not", "import setup # Modified from http://stackoverflow.com/questions/2058802/ # how-can-i-get-the-version-defined-in-setup-py-setuptools-in-my-package def version():", "genetic sequence data', scripts=scripts, install_requires=[ 'biopython>=1.71', 'bz2file>=0.98', 'Cython>=0.29.16', 'ipython>=3.1.0', 'matplotlib>=1.4.3',", "# Explicitly list bin scripts to be installed, seeing as", "'bin/adaptor-distances.py', 'bin/alignment-panel-civ.py', 'bin/alignments-per-read.py', 'bin/bit-score-to-e-value.py', 'bin/cat-json-blast-records.py', 'bin/check-fasta-json-blast-consistency.py', 'bin/codon-distance.py', 'bin/compare-consensuses.py', 'bin/compare-sequences.py', 'bin/convert-blast-xml-to-json.py'," ]
[ "informacnich technologii VUT v Brne # Bachelor thesis # Author:", "import time from portfolioApp.models import NotificationEvent register = template.Library() import", "pandas as pd def print_timestamp(timestamp): return time.strftime('%Y-%m-%d'.format(timestamp%1000), time.gmtime(timestamp/1000.0)) def print_timestamp_analysis(timestamp):", "print_timestamp_notifications(timestamp): return str(timestamp.year) + '-' + str(timestamp.month) +'-' + str(timestamp.day)", "symbol def print_type_notifications(notification_type): if notification_type == 1: return 'Interday' elif", "notification_type == 1: return 'Interday' elif notification_type == 2: return", "Author: <NAME> (xbalif00) # License: MIT # ====================================================================================================================== from django", "License: MIT # ====================================================================================================================== from django import template import datetime", "def print_notification_text(type): if type == 1: return 'At a price", "NotificationEvent.objects.get(id=notification_id) symbol = str(object.company.symbol) return symbol def print_type_notifications(notification_type): if notification_type", "== 1: return 'Interday' elif notification_type == 2: return 'Intraday'", "return str(timestamp.year) + '-' + str(timestamp.month) +'-' + str(timestamp.day) def", "return 'Interday' elif notification_type == 2: return 'Intraday' register.filter(print_timestamp) register.filter(print_timestamp_analysis)", "if type == 1: return 'At a price change equal/above/below'", "template.Library() import pandas as pd def print_timestamp(timestamp): return time.strftime('%Y-%m-%d'.format(timestamp%1000), time.gmtime(timestamp/1000.0))", "decrease current price' def print_symbol_notifications(notification_id): object = NotificationEvent.objects.get(id=notification_id) symbol =", "VUT v Brne # Bachelor thesis # Author: <NAME> (xbalif00)", "# ====================================================================================================================== from django import template import datetime import time", "price' def print_symbol_notifications(notification_id): object = NotificationEvent.objects.get(id=notification_id) symbol = str(object.company.symbol) return", "# License: MIT # ====================================================================================================================== from django import template import", "v Brne # Bachelor thesis # Author: <NAME> (xbalif00) #", "====================================================================================================================== from django import template import datetime import time from", "print_notification_text(type): if type == 1: return 'At a price change", "type == 1: return 'At a price change equal/above/below' elif", "import template import datetime import time from portfolioApp.models import NotificationEvent", "object = NotificationEvent.objects.get(id=notification_id) symbol = str(object.company.symbol) return symbol def print_type_notifications(notification_type):", "<reponame>FilipBali/VirtualPortfolio-WebApplication<gh_stars>0 # ====================================================================================================================== # Fakulta informacnich technologii VUT v Brne", "print_symbol_notifications(notification_id): object = NotificationEvent.objects.get(id=notification_id) symbol = str(object.company.symbol) return symbol def", "== 1: return 'At a price change equal/above/below' elif type", "def print_timestamp_notifications(timestamp): return str(timestamp.year) + '-' + str(timestamp.month) +'-' +", "if notification_type == 1: return 'Interday' elif notification_type == 2:", "'-' + str(timestamp.month) +'-' + str(timestamp.day) def print_timestamp_notifications(timestamp): return str(timestamp.year)", "1: return 'At a price change equal/above/below' elif type ==", "= template.Library() import pandas as pd def print_timestamp(timestamp): return time.strftime('%Y-%m-%d'.format(timestamp%1000),", "+ str(timestamp.month) +'-' + str(timestamp.day) def print_notification_text(type): if type ==", "MIT # ====================================================================================================================== from django import template import datetime import", "datetime import time from portfolioApp.models import NotificationEvent register = template.Library()", "price change equal/above/below' elif type == 2: return 'Percentage increase", "import NotificationEvent register = template.Library() import pandas as pd def", "'Percentage increase current price' elif type == 3: return 'Percentage", "str(object.company.symbol) return symbol def print_type_notifications(notification_type): if notification_type == 1: return", "current price' elif type == 3: return 'Percentage decrease current", "'-' + str(timestamp.month) +'-' + str(timestamp.day) def print_notification_text(type): if type", "+'-' + str(timestamp.day) def print_notification_text(type): if type == 1: return", "def print_timestamp(timestamp): return time.strftime('%Y-%m-%d'.format(timestamp%1000), time.gmtime(timestamp/1000.0)) def print_timestamp_analysis(timestamp): return str(timestamp.year) +", "return 'Percentage increase current price' elif type == 3: return", "# Author: <NAME> (xbalif00) # License: MIT # ====================================================================================================================== from", "return 'Percentage decrease current price' def print_symbol_notifications(notification_id): object = NotificationEvent.objects.get(id=notification_id)", "as pd def print_timestamp(timestamp): return time.strftime('%Y-%m-%d'.format(timestamp%1000), time.gmtime(timestamp/1000.0)) def print_timestamp_analysis(timestamp): return", "import pandas as pd def print_timestamp(timestamp): return time.strftime('%Y-%m-%d'.format(timestamp%1000), time.gmtime(timestamp/1000.0)) def", "import datetime import time from portfolioApp.models import NotificationEvent register =", "Brne # Bachelor thesis # Author: <NAME> (xbalif00) # License:", "== 2: return 'Intraday' register.filter(print_timestamp) register.filter(print_timestamp_analysis) register.filter(print_timestamp_notifications) register.filter(print_notification_text) register.filter(print_symbol_notifications) register.filter(print_type_notifications)", "= NotificationEvent.objects.get(id=notification_id) symbol = str(object.company.symbol) return symbol def print_type_notifications(notification_type): if", "# Fakulta informacnich technologii VUT v Brne # Bachelor thesis", "Bachelor thesis # Author: <NAME> (xbalif00) # License: MIT #", "====================================================================================================================== # Fakulta informacnich technologii VUT v Brne # Bachelor", "def print_timestamp_analysis(timestamp): return str(timestamp.year) + '-' + str(timestamp.month) +'-' +", "== 2: return 'Percentage increase current price' elif type ==", "from portfolioApp.models import NotificationEvent register = template.Library() import pandas as", "django import template import datetime import time from portfolioApp.models import", "time.strftime('%Y-%m-%d'.format(timestamp%1000), time.gmtime(timestamp/1000.0)) def print_timestamp_analysis(timestamp): return str(timestamp.year) + '-' + str(timestamp.month)", "'Interday' elif notification_type == 2: return 'Intraday' register.filter(print_timestamp) register.filter(print_timestamp_analysis) register.filter(print_timestamp_notifications)", "current price' def print_symbol_notifications(notification_id): object = NotificationEvent.objects.get(id=notification_id) symbol = str(object.company.symbol)", "increase current price' elif type == 3: return 'Percentage decrease", "symbol = str(object.company.symbol) return symbol def print_type_notifications(notification_type): if notification_type ==", "portfolioApp.models import NotificationEvent register = template.Library() import pandas as pd", "str(timestamp.day) def print_timestamp_notifications(timestamp): return str(timestamp.year) + '-' + str(timestamp.month) +'-'", "elif type == 3: return 'Percentage decrease current price' def", "notification_type == 2: return 'Intraday' register.filter(print_timestamp) register.filter(print_timestamp_analysis) register.filter(print_timestamp_notifications) register.filter(print_notification_text) register.filter(print_symbol_notifications)", "str(timestamp.day) def print_notification_text(type): if type == 1: return 'At a", "print_timestamp(timestamp): return time.strftime('%Y-%m-%d'.format(timestamp%1000), time.gmtime(timestamp/1000.0)) def print_timestamp_analysis(timestamp): return str(timestamp.year) + '-'", "+ str(timestamp.day) def print_timestamp_notifications(timestamp): return str(timestamp.year) + '-' + str(timestamp.month)", "+ str(timestamp.month) +'-' + str(timestamp.day) def print_timestamp_notifications(timestamp): return str(timestamp.year) +", "a price change equal/above/below' elif type == 2: return 'Percentage", "str(timestamp.month) +'-' + str(timestamp.day) def print_notification_text(type): if type == 1:", "template import datetime import time from portfolioApp.models import NotificationEvent register", "return time.strftime('%Y-%m-%d'.format(timestamp%1000), time.gmtime(timestamp/1000.0)) def print_timestamp_analysis(timestamp): return str(timestamp.year) + '-' +", "str(timestamp.year) + '-' + str(timestamp.month) +'-' + str(timestamp.day) def print_notification_text(type):", "elif type == 2: return 'Percentage increase current price' elif", "+ '-' + str(timestamp.month) +'-' + str(timestamp.day) def print_notification_text(type): if", "# ====================================================================================================================== # Fakulta informacnich technologii VUT v Brne #", "from django import template import datetime import time from portfolioApp.models", "+ str(timestamp.day) def print_notification_text(type): if type == 1: return 'At", "def print_symbol_notifications(notification_id): object = NotificationEvent.objects.get(id=notification_id) symbol = str(object.company.symbol) return symbol", "time.gmtime(timestamp/1000.0)) def print_timestamp_analysis(timestamp): return str(timestamp.year) + '-' + str(timestamp.month) +'-'", "def print_type_notifications(notification_type): if notification_type == 1: return 'Interday' elif notification_type", "3: return 'Percentage decrease current price' def print_symbol_notifications(notification_id): object =", "print_timestamp_analysis(timestamp): return str(timestamp.year) + '-' + str(timestamp.month) +'-' + str(timestamp.day)", "technologii VUT v Brne # Bachelor thesis # Author: <NAME>", "= str(object.company.symbol) return symbol def print_type_notifications(notification_type): if notification_type == 1:", "NotificationEvent register = template.Library() import pandas as pd def print_timestamp(timestamp):", "2: return 'Percentage increase current price' elif type == 3:", "time from portfolioApp.models import NotificationEvent register = template.Library() import pandas", "Fakulta informacnich technologii VUT v Brne # Bachelor thesis #", "'At a price change equal/above/below' elif type == 2: return", "change equal/above/below' elif type == 2: return 'Percentage increase current", "return symbol def print_type_notifications(notification_type): if notification_type == 1: return 'Interday'", "thesis # Author: <NAME> (xbalif00) # License: MIT # ======================================================================================================================", "type == 2: return 'Percentage increase current price' elif type", "str(timestamp.month) +'-' + str(timestamp.day) def print_timestamp_notifications(timestamp): return str(timestamp.year) + '-'", "pd def print_timestamp(timestamp): return time.strftime('%Y-%m-%d'.format(timestamp%1000), time.gmtime(timestamp/1000.0)) def print_timestamp_analysis(timestamp): return str(timestamp.year)", "type == 3: return 'Percentage decrease current price' def print_symbol_notifications(notification_id):", "+'-' + str(timestamp.day) def print_timestamp_notifications(timestamp): return str(timestamp.year) + '-' +", "price' elif type == 3: return 'Percentage decrease current price'", "'Percentage decrease current price' def print_symbol_notifications(notification_id): object = NotificationEvent.objects.get(id=notification_id) symbol", "(xbalif00) # License: MIT # ====================================================================================================================== from django import template", "equal/above/below' elif type == 2: return 'Percentage increase current price'", "== 3: return 'Percentage decrease current price' def print_symbol_notifications(notification_id): object", "register = template.Library() import pandas as pd def print_timestamp(timestamp): return", "<NAME> (xbalif00) # License: MIT # ====================================================================================================================== from django import", "print_type_notifications(notification_type): if notification_type == 1: return 'Interday' elif notification_type ==", "1: return 'Interday' elif notification_type == 2: return 'Intraday' register.filter(print_timestamp)", "# Bachelor thesis # Author: <NAME> (xbalif00) # License: MIT", "return 'At a price change equal/above/below' elif type == 2:", "str(timestamp.year) + '-' + str(timestamp.month) +'-' + str(timestamp.day) def print_timestamp_notifications(timestamp):", "elif notification_type == 2: return 'Intraday' register.filter(print_timestamp) register.filter(print_timestamp_analysis) register.filter(print_timestamp_notifications) register.filter(print_notification_text)", "+ '-' + str(timestamp.month) +'-' + str(timestamp.day) def print_timestamp_notifications(timestamp): return" ]
[ "from pycfmodel.model.resources.properties.policy_document import PolicyDocument from pycfmodel.model.resources.properties.property import Property from pycfmodel.model.types", "attached policy. Properties: - PolicyDocument: A [policy document][pycfmodel.model.resources.properties.policy_document.PolicyDocument] object. -", "\"\"\" Contains information about an attached policy. Properties: - PolicyDocument:", "policy. Properties: - PolicyDocument: A [policy document][pycfmodel.model.resources.properties.policy_document.PolicyDocument] object. - PolicyName:", "from pycfmodel.model.resources.properties.property import Property from pycfmodel.model.types import Resolvable, ResolvableStr class", "pycfmodel.model.resources.properties.policy_document import PolicyDocument from pycfmodel.model.resources.properties.property import Property from pycfmodel.model.types import", "name (not ARN) identifying the policy. \"\"\" PolicyName: ResolvableStr PolicyDocument:", "import PolicyDocument from pycfmodel.model.resources.properties.property import Property from pycfmodel.model.types import Resolvable,", "from pycfmodel.model.types import Resolvable, ResolvableStr class Policy(Property): \"\"\" Contains information", "class Policy(Property): \"\"\" Contains information about an attached policy. Properties:", "friendly name (not ARN) identifying the policy. \"\"\" PolicyName: ResolvableStr", "<reponame>donatoaz/pycfmodel from pycfmodel.model.resources.properties.policy_document import PolicyDocument from pycfmodel.model.resources.properties.property import Property from", "PolicyDocument from pycfmodel.model.resources.properties.property import Property from pycfmodel.model.types import Resolvable, ResolvableStr", "PolicyDocument: A [policy document][pycfmodel.model.resources.properties.policy_document.PolicyDocument] object. - PolicyName: The friendly name", "Contains information about an attached policy. Properties: - PolicyDocument: A", "Property from pycfmodel.model.types import Resolvable, ResolvableStr class Policy(Property): \"\"\" Contains", "about an attached policy. Properties: - PolicyDocument: A [policy document][pycfmodel.model.resources.properties.policy_document.PolicyDocument]", "document][pycfmodel.model.resources.properties.policy_document.PolicyDocument] object. - PolicyName: The friendly name (not ARN) identifying", "- PolicyName: The friendly name (not ARN) identifying the policy.", "A [policy document][pycfmodel.model.resources.properties.policy_document.PolicyDocument] object. - PolicyName: The friendly name (not", "PolicyName: The friendly name (not ARN) identifying the policy. \"\"\"", "Policy(Property): \"\"\" Contains information about an attached policy. Properties: -", "ResolvableStr class Policy(Property): \"\"\" Contains information about an attached policy.", "Resolvable, ResolvableStr class Policy(Property): \"\"\" Contains information about an attached", "information about an attached policy. Properties: - PolicyDocument: A [policy", "pycfmodel.model.types import Resolvable, ResolvableStr class Policy(Property): \"\"\" Contains information about", "(not ARN) identifying the policy. \"\"\" PolicyName: ResolvableStr PolicyDocument: Resolvable[PolicyDocument]", "import Resolvable, ResolvableStr class Policy(Property): \"\"\" Contains information about an", "import Property from pycfmodel.model.types import Resolvable, ResolvableStr class Policy(Property): \"\"\"", "- PolicyDocument: A [policy document][pycfmodel.model.resources.properties.policy_document.PolicyDocument] object. - PolicyName: The friendly", "[policy document][pycfmodel.model.resources.properties.policy_document.PolicyDocument] object. - PolicyName: The friendly name (not ARN)", "an attached policy. Properties: - PolicyDocument: A [policy document][pycfmodel.model.resources.properties.policy_document.PolicyDocument] object.", "pycfmodel.model.resources.properties.property import Property from pycfmodel.model.types import Resolvable, ResolvableStr class Policy(Property):", "The friendly name (not ARN) identifying the policy. \"\"\" PolicyName:", "Properties: - PolicyDocument: A [policy document][pycfmodel.model.resources.properties.policy_document.PolicyDocument] object. - PolicyName: The", "object. - PolicyName: The friendly name (not ARN) identifying the" ]
[]
[ "\"-s\", \"ERROR_ON_UNDEFINED_SYMBOLS=0\", \"-s\", \"STANDALONE_WASM=1\", ], ), ]), ), ], ),", "), ]), ), ], ), feature( name = \"default_linker_flags\", enabled", "cc_common.create_cc_toolchain_config_info( ctx = ctx, features = features, # NEW cxx_builtin_include_directories", ") all_compile_actions = [ ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile, ] all_link_actions = [", "path = \"/opt/emsdk/upstream/emscripten/emcc\", ), tool_path( name = \"ar\", path =", "\"/bin/false\", ), ] features = [ # NEW feature( name", "\"ACTION_NAMES\") load( \"@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl\", \"feature\", \"flag_group\", \"flag_set\", \"tool_path\", ) all_compile_actions =", "load( \"@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl\", \"feature\", \"flag_group\", \"flag_set\", \"tool_path\", ) all_compile_actions = [", "# Copyright (C) 2019 Intel Corporation. All rights reserved. #", "= \"gcc\", path = \"/opt/emsdk/upstream/emscripten/emcc\", ), tool_path( name = \"ld\",", "rule( implementation = _impl, attrs = {}, provides = [CcToolchainConfigInfo],", "rights reserved. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception load(\"@bazel_tools//tools/build_defs/cc:action_names.bzl\", \"ACTION_NAMES\") load(", "= ctx, features = features, # NEW cxx_builtin_include_directories = [", "\"-s\", \"USE_PTHREADS=0\", \"-s\", \"ERROR_ON_UNDEFINED_SYMBOLS=0\", \"-s\", \"STANDALONE_WASM=1\", \"-Wl,--export=__heap_base\", \"-Wl,--export=__data_end\", ], ),", "\"feature\", \"flag_group\", \"flag_set\", \"tool_path\", ) all_compile_actions = [ ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile,", ") emsdk_toolchain_config = rule( implementation = _impl, attrs = {},", "= [ ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile, ] all_link_actions = [ ACTION_NAMES.cpp_link_executable, ACTION_NAMES.cpp_link_dynamic_library,", "name = \"strip\", path = \"/bin/false\", ), ] features =", "name = \"ld\", path = \"/opt/emsdk/upstream/emscripten/emcc\", ), tool_path( name =", "tool_path( name = \"gcov\", path = \"/bin/false\", ), tool_path( name", "= \"/bin/false\", ), ] features = [ # NEW feature(", "\"-s\", \"STANDALONE_WASM=1\", ], ), ]), ), ], ), feature( name", "], ), ] return cc_common.create_cc_toolchain_config_info( ctx = ctx, features =", "flag_groups = ([ flag_group( flags = [ \"-O3\", \"-msimd128\", \"-s\",", "ctx = ctx, features = features, # NEW cxx_builtin_include_directories =", "name = \"nm\", path = \"/bin/false\", ), tool_path( name =", "ACTION_NAMES.cpp_link_executable, ACTION_NAMES.cpp_link_dynamic_library, ACTION_NAMES.cpp_link_nodeps_dynamic_library, ] def _impl(ctx): tool_paths = [ tool_path(", "= tool_paths, ) emsdk_toolchain_config = rule( implementation = _impl, attrs", "compiler = \"emsdk\", abi_version = \"unknown\", abi_libc_version = \"unknown\", tool_paths", "= \"gcov\", path = \"/bin/false\", ), tool_path( name = \"nm\",", "= [ ACTION_NAMES.cpp_link_executable, ACTION_NAMES.cpp_link_dynamic_library, ACTION_NAMES.cpp_link_nodeps_dynamic_library, ] def _impl(ctx): tool_paths =", "), tool_path( name = \"ar\", path = \"/opt/emsdk/upstream/emscripten/emar\", ), tool_path(", "= \"unknown\", compiler = \"emsdk\", abi_version = \"unknown\", abi_libc_version =", "] features = [ # NEW feature( name = \"default_compile_flags\",", "Apache-2.0 WITH LLVM-exception load(\"@bazel_tools//tools/build_defs/cc:action_names.bzl\", \"ACTION_NAMES\") load( \"@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl\", \"feature\", \"flag_group\", \"flag_set\",", "= \"strip\", path = \"/bin/false\", ), ] features = [", "reserved. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception load(\"@bazel_tools//tools/build_defs/cc:action_names.bzl\", \"ACTION_NAMES\") load( \"@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl\",", "\"/opt/emsdk/upstream/emscripten/emcc\", ), tool_path( name = \"ld\", path = \"/opt/emsdk/upstream/emscripten/emcc\", ),", "flag_set( actions = all_compile_actions, flag_groups = ([ flag_group( flags =", "= \"wasm32\", target_libc = \"unknown\", compiler = \"emsdk\", abi_version =", "), tool_path( name = \"nm\", path = \"/bin/false\", ), tool_path(", "= \"unknown\", tool_paths = tool_paths, ) emsdk_toolchain_config = rule( implementation", "\"flag_set\", \"tool_path\", ) all_compile_actions = [ ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile, ] all_link_actions", "name = \"gcc\", path = \"/opt/emsdk/upstream/emscripten/emcc\", ), tool_path( name =", "# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception load(\"@bazel_tools//tools/build_defs/cc:action_names.bzl\", \"ACTION_NAMES\") load( \"@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl\", \"feature\",", "tool_path( name = \"ar\", path = \"/opt/emsdk/upstream/emscripten/emar\", ), tool_path( name", "path = \"/bin/false\", ), ] features = [ # NEW", "\"wasm32\", target_libc = \"unknown\", compiler = \"emsdk\", abi_version = \"unknown\",", "name = \"objdump\", path = \"/bin/false\", ), tool_path( name =", "\"-s\", \"STANDALONE_WASM=1\", \"-Wl,--export=__heap_base\", \"-Wl,--export=__data_end\", ], ), ]), ), ], ),", "features = [ # NEW feature( name = \"default_compile_flags\", enabled", "\"cpp\", path = \"/opt/emsdk/upstream/emscripten/em++\", ), tool_path( name = \"gcov\", path", "Intel Corporation. All rights reserved. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception", "[ flag_set( actions = all_compile_actions, flag_groups = ([ flag_group( flags", "\"-O3\", \"-msimd128\", \"-s\", \"USE_PTHREADS=0\", \"-s\", \"ERROR_ON_UNDEFINED_SYMBOLS=0\", \"-s\", \"STANDALONE_WASM=1\", ], ),", "\"unknown\", abi_libc_version = \"unknown\", tool_paths = tool_paths, ) emsdk_toolchain_config =", "all_link_actions, flag_groups = ([ flag_group( flags = [ \"-O3\", \"-msimd128\",", "_impl(ctx): tool_paths = [ tool_path( name = \"gcc\", path =", "path = \"/bin/false\", ), tool_path( name = \"nm\", path =", "name = \"ar\", path = \"/opt/emsdk/upstream/emscripten/emar\", ), tool_path( name =", "load(\"@bazel_tools//tools/build_defs/cc:action_names.bzl\", \"ACTION_NAMES\") load( \"@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl\", \"feature\", \"flag_group\", \"flag_set\", \"tool_path\", ) all_compile_actions", "flag_sets = [ flag_set( actions = all_compile_actions, flag_groups = ([", "features, # NEW cxx_builtin_include_directories = [ \"/opt/emsdk/upstream/emscripten/system/include/libcxx\", \"/opt/emsdk/upstream/emscripten/system/lib/libcxxabi/include\", \"/opt/emsdk/upstream/emscripten/system/include\", \"/opt/emsdk/upstream/emscripten/system/include/libc\",", "), tool_path( name = \"gcov\", path = \"/bin/false\", ), tool_path(", "= \"wasm-emsdk\", host_system_name = \"i686-unknown-linux-gnu\", target_system_name = \"wasm32-unknown-emscripten\", target_cpu =", "\"strip\", path = \"/bin/false\", ), ] features = [ #", "ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile, ] all_link_actions = [ ACTION_NAMES.cpp_link_executable, ACTION_NAMES.cpp_link_dynamic_library, ACTION_NAMES.cpp_link_nodeps_dynamic_library, ]", "\"wasm-emsdk\", host_system_name = \"i686-unknown-linux-gnu\", target_system_name = \"wasm32-unknown-emscripten\", target_cpu = \"wasm32\",", "= \"ar\", path = \"/opt/emsdk/upstream/emscripten/emar\", ), tool_path( name = \"cpp\",", "\"ERROR_ON_UNDEFINED_SYMBOLS=0\", \"-s\", \"STANDALONE_WASM=1\", ], ), ]), ), ], ), feature(", "tool_path( name = \"ld\", path = \"/opt/emsdk/upstream/emscripten/emcc\", ), tool_path( name", "\"default_compile_flags\", enabled = True, flag_sets = [ flag_set( actions =", "\"/opt/emsdk/upstream/emscripten/system/include/libc\", \"/opt/emsdk/upstream/emscripten/system/lib/libc/musl/arch/emscripten\", \"/opt/emsdk/upstream/lib/clang/12.0.0/include/\", ], toolchain_identifier = \"wasm-emsdk\", host_system_name = \"i686-unknown-linux-gnu\",", "def _impl(ctx): tool_paths = [ tool_path( name = \"gcc\", path", "enabled = True, flag_sets = [ flag_set( actions = all_compile_actions,", "target_libc = \"unknown\", compiler = \"emsdk\", abi_version = \"unknown\", abi_libc_version", "\"tool_path\", ) all_compile_actions = [ ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile, ] all_link_actions =", "name = \"default_linker_flags\", enabled = True, flag_sets = [ flag_set(", "features = features, # NEW cxx_builtin_include_directories = [ \"/opt/emsdk/upstream/emscripten/system/include/libcxx\", \"/opt/emsdk/upstream/emscripten/system/lib/libcxxabi/include\",", "\"/opt/emsdk/upstream/emscripten/em++\", ), tool_path( name = \"gcov\", path = \"/bin/false\", ),", "\"-s\", \"USE_PTHREADS=0\", \"-s\", \"ERROR_ON_UNDEFINED_SYMBOLS=0\", \"-s\", \"STANDALONE_WASM=1\", ], ), ]), ),", "tool_path( name = \"gcc\", path = \"/opt/emsdk/upstream/emscripten/emcc\", ), tool_path( name", "), ]), ), ], ), ] return cc_common.create_cc_toolchain_config_info( ctx =", "\"-O3\", \"-msimd128\", \"-s\", \"USE_PTHREADS=0\", \"-s\", \"ERROR_ON_UNDEFINED_SYMBOLS=0\", \"-s\", \"STANDALONE_WASM=1\", \"-Wl,--export=__heap_base\", \"-Wl,--export=__data_end\",", "= [ tool_path( name = \"gcc\", path = \"/opt/emsdk/upstream/emscripten/emcc\", ),", "([ flag_group( flags = [ \"-O3\", \"-msimd128\", \"-s\", \"USE_PTHREADS=0\", \"-s\",", "= features, # NEW cxx_builtin_include_directories = [ \"/opt/emsdk/upstream/emscripten/system/include/libcxx\", \"/opt/emsdk/upstream/emscripten/system/lib/libcxxabi/include\", \"/opt/emsdk/upstream/emscripten/system/include\",", "NEW cxx_builtin_include_directories = [ \"/opt/emsdk/upstream/emscripten/system/include/libcxx\", \"/opt/emsdk/upstream/emscripten/system/lib/libcxxabi/include\", \"/opt/emsdk/upstream/emscripten/system/include\", \"/opt/emsdk/upstream/emscripten/system/include/libc\", \"/opt/emsdk/upstream/emscripten/system/lib/libc/musl/arch/emscripten\", \"/opt/emsdk/upstream/lib/clang/12.0.0/include/\",", "all_link_actions = [ ACTION_NAMES.cpp_link_executable, ACTION_NAMES.cpp_link_dynamic_library, ACTION_NAMES.cpp_link_nodeps_dynamic_library, ] def _impl(ctx): tool_paths", "tool_paths = [ tool_path( name = \"gcc\", path = \"/opt/emsdk/upstream/emscripten/emcc\",", "\"/opt/emsdk/upstream/emscripten/system/include/libcxx\", \"/opt/emsdk/upstream/emscripten/system/lib/libcxxabi/include\", \"/opt/emsdk/upstream/emscripten/system/include\", \"/opt/emsdk/upstream/emscripten/system/include/libc\", \"/opt/emsdk/upstream/emscripten/system/lib/libc/musl/arch/emscripten\", \"/opt/emsdk/upstream/lib/clang/12.0.0/include/\", ], toolchain_identifier = \"wasm-emsdk\",", "# NEW feature( name = \"default_compile_flags\", enabled = True, flag_sets", "\"/opt/emsdk/upstream/lib/clang/12.0.0/include/\", ], toolchain_identifier = \"wasm-emsdk\", host_system_name = \"i686-unknown-linux-gnu\", target_system_name =", "= ([ flag_group( flags = [ \"-O3\", \"-msimd128\", \"-s\", \"USE_PTHREADS=0\",", "= \"/opt/emsdk/upstream/emscripten/em++\", ), tool_path( name = \"gcov\", path = \"/bin/false\",", "path = \"/opt/emsdk/upstream/emscripten/emar\", ), tool_path( name = \"cpp\", path =", "= [ flag_set( actions = all_compile_actions, flag_groups = ([ flag_group(", "actions = all_compile_actions, flag_groups = ([ flag_group( flags = [", "True, flag_sets = [ flag_set( actions = all_link_actions, flag_groups =", "\"flag_group\", \"flag_set\", \"tool_path\", ) all_compile_actions = [ ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile, ]", "]), ), ], ), feature( name = \"default_linker_flags\", enabled =", "= \"/bin/false\", ), tool_path( name = \"objdump\", path = \"/bin/false\",", "]), ), ], ), ] return cc_common.create_cc_toolchain_config_info( ctx = ctx,", "path = \"/bin/false\", ), tool_path( name = \"objdump\", path =", "toolchain_identifier = \"wasm-emsdk\", host_system_name = \"i686-unknown-linux-gnu\", target_system_name = \"wasm32-unknown-emscripten\", target_cpu", "LLVM-exception load(\"@bazel_tools//tools/build_defs/cc:action_names.bzl\", \"ACTION_NAMES\") load( \"@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl\", \"feature\", \"flag_group\", \"flag_set\", \"tool_path\", )", "), ], ), feature( name = \"default_linker_flags\", enabled = True,", "\"/opt/emsdk/upstream/emscripten/system/include\", \"/opt/emsdk/upstream/emscripten/system/include/libc\", \"/opt/emsdk/upstream/emscripten/system/lib/libc/musl/arch/emscripten\", \"/opt/emsdk/upstream/lib/clang/12.0.0/include/\", ], toolchain_identifier = \"wasm-emsdk\", host_system_name =", "= \"default_compile_flags\", enabled = True, flag_sets = [ flag_set( actions", "= \"cpp\", path = \"/opt/emsdk/upstream/emscripten/em++\", ), tool_path( name = \"gcov\",", "name = \"default_compile_flags\", enabled = True, flag_sets = [ flag_set(", "= [ flag_set( actions = all_link_actions, flag_groups = ([ flag_group(", "\"ERROR_ON_UNDEFINED_SYMBOLS=0\", \"-s\", \"STANDALONE_WASM=1\", \"-Wl,--export=__heap_base\", \"-Wl,--export=__data_end\", ], ), ]), ), ],", "host_system_name = \"i686-unknown-linux-gnu\", target_system_name = \"wasm32-unknown-emscripten\", target_cpu = \"wasm32\", target_libc", "[ ACTION_NAMES.cpp_link_executable, ACTION_NAMES.cpp_link_dynamic_library, ACTION_NAMES.cpp_link_nodeps_dynamic_library, ] def _impl(ctx): tool_paths = [", "flag_set( actions = all_link_actions, flag_groups = ([ flag_group( flags =", "Corporation. All rights reserved. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception load(\"@bazel_tools//tools/build_defs/cc:action_names.bzl\",", "True, flag_sets = [ flag_set( actions = all_compile_actions, flag_groups =", "= \"/opt/emsdk/upstream/emscripten/emcc\", ), tool_path( name = \"ar\", path = \"/opt/emsdk/upstream/emscripten/emar\",", "enabled = True, flag_sets = [ flag_set( actions = all_link_actions,", "[ tool_path( name = \"gcc\", path = \"/opt/emsdk/upstream/emscripten/emcc\", ), tool_path(", "= \"i686-unknown-linux-gnu\", target_system_name = \"wasm32-unknown-emscripten\", target_cpu = \"wasm32\", target_libc =", "= \"/bin/false\", ), tool_path( name = \"strip\", path = \"/bin/false\",", "tool_path( name = \"objdump\", path = \"/bin/false\", ), tool_path( name", "] all_link_actions = [ ACTION_NAMES.cpp_link_executable, ACTION_NAMES.cpp_link_dynamic_library, ACTION_NAMES.cpp_link_nodeps_dynamic_library, ] def _impl(ctx):", "\"/opt/emsdk/upstream/emscripten/system/lib/libcxxabi/include\", \"/opt/emsdk/upstream/emscripten/system/include\", \"/opt/emsdk/upstream/emscripten/system/include/libc\", \"/opt/emsdk/upstream/emscripten/system/lib/libc/musl/arch/emscripten\", \"/opt/emsdk/upstream/lib/clang/12.0.0/include/\", ], toolchain_identifier = \"wasm-emsdk\", host_system_name", "feature( name = \"default_linker_flags\", enabled = True, flag_sets = [", "flags = [ \"-O3\", \"-msimd128\", \"-s\", \"USE_PTHREADS=0\", \"-s\", \"ERROR_ON_UNDEFINED_SYMBOLS=0\", \"-s\",", "\"/bin/false\", ), tool_path( name = \"nm\", path = \"/bin/false\", ),", "[ \"-O3\", \"-msimd128\", \"-s\", \"USE_PTHREADS=0\", \"-s\", \"ERROR_ON_UNDEFINED_SYMBOLS=0\", \"-s\", \"STANDALONE_WASM=1\", ],", "[ # NEW feature( name = \"default_compile_flags\", enabled = True,", "all_compile_actions = [ ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile, ] all_link_actions = [ ACTION_NAMES.cpp_link_executable,", "], toolchain_identifier = \"wasm-emsdk\", host_system_name = \"i686-unknown-linux-gnu\", target_system_name = \"wasm32-unknown-emscripten\",", "= \"objdump\", path = \"/bin/false\", ), tool_path( name = \"strip\",", "\"/bin/false\", ), tool_path( name = \"objdump\", path = \"/bin/false\", ),", "2019 Intel Corporation. All rights reserved. # SPDX-License-Identifier: Apache-2.0 WITH", "ACTION_NAMES.cpp_link_dynamic_library, ACTION_NAMES.cpp_link_nodeps_dynamic_library, ] def _impl(ctx): tool_paths = [ tool_path( name", "= \"ld\", path = \"/opt/emsdk/upstream/emscripten/emcc\", ), tool_path( name = \"ar\",", "all_compile_actions, flag_groups = ([ flag_group( flags = [ \"-O3\", \"-msimd128\",", "[ flag_set( actions = all_link_actions, flag_groups = ([ flag_group( flags", "= \"unknown\", abi_libc_version = \"unknown\", tool_paths = tool_paths, ) emsdk_toolchain_config", "\"@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl\", \"feature\", \"flag_group\", \"flag_set\", \"tool_path\", ) all_compile_actions = [ ACTION_NAMES.c_compile,", "All rights reserved. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception load(\"@bazel_tools//tools/build_defs/cc:action_names.bzl\", \"ACTION_NAMES\")", "ACTION_NAMES.cpp_compile, ] all_link_actions = [ ACTION_NAMES.cpp_link_executable, ACTION_NAMES.cpp_link_dynamic_library, ACTION_NAMES.cpp_link_nodeps_dynamic_library, ] def", "[ \"-O3\", \"-msimd128\", \"-s\", \"USE_PTHREADS=0\", \"-s\", \"ERROR_ON_UNDEFINED_SYMBOLS=0\", \"-s\", \"STANDALONE_WASM=1\", \"-Wl,--export=__heap_base\",", "], ), ]), ), ], ), ] return cc_common.create_cc_toolchain_config_info( ctx", "\"gcov\", path = \"/bin/false\", ), tool_path( name = \"nm\", path", "actions = all_link_actions, flag_groups = ([ flag_group( flags = [", "], ), ]), ), ], ), feature( name = \"default_linker_flags\",", "ctx, features = features, # NEW cxx_builtin_include_directories = [ \"/opt/emsdk/upstream/emscripten/system/include/libcxx\",", "tool_paths, ) emsdk_toolchain_config = rule( implementation = _impl, attrs =", "flag_group( flags = [ \"-O3\", \"-msimd128\", \"-s\", \"USE_PTHREADS=0\", \"-s\", \"ERROR_ON_UNDEFINED_SYMBOLS=0\",", "\"/opt/emsdk/upstream/emscripten/system/lib/libc/musl/arch/emscripten\", \"/opt/emsdk/upstream/lib/clang/12.0.0/include/\", ], toolchain_identifier = \"wasm-emsdk\", host_system_name = \"i686-unknown-linux-gnu\", target_system_name", "tool_path( name = \"cpp\", path = \"/opt/emsdk/upstream/emscripten/em++\", ), tool_path( name", "\"wasm32-unknown-emscripten\", target_cpu = \"wasm32\", target_libc = \"unknown\", compiler = \"emsdk\",", "\"/opt/emsdk/upstream/emscripten/emcc\", ), tool_path( name = \"ar\", path = \"/opt/emsdk/upstream/emscripten/emar\", ),", "\"-s\", \"ERROR_ON_UNDEFINED_SYMBOLS=0\", \"-s\", \"STANDALONE_WASM=1\", \"-Wl,--export=__heap_base\", \"-Wl,--export=__data_end\", ], ), ]), ),", "\"ar\", path = \"/opt/emsdk/upstream/emscripten/emar\", ), tool_path( name = \"cpp\", path", "= \"/opt/emsdk/upstream/emscripten/emar\", ), tool_path( name = \"cpp\", path = \"/opt/emsdk/upstream/emscripten/em++\",", "cxx_builtin_include_directories = [ \"/opt/emsdk/upstream/emscripten/system/include/libcxx\", \"/opt/emsdk/upstream/emscripten/system/lib/libcxxabi/include\", \"/opt/emsdk/upstream/emscripten/system/include\", \"/opt/emsdk/upstream/emscripten/system/include/libc\", \"/opt/emsdk/upstream/emscripten/system/lib/libc/musl/arch/emscripten\", \"/opt/emsdk/upstream/lib/clang/12.0.0/include/\", ],", "= True, flag_sets = [ flag_set( actions = all_compile_actions, flag_groups", "] def _impl(ctx): tool_paths = [ tool_path( name = \"gcc\",", "), tool_path( name = \"ld\", path = \"/opt/emsdk/upstream/emscripten/emcc\", ), tool_path(", "\"-Wl,--export=__heap_base\", \"-Wl,--export=__data_end\", ], ), ]), ), ], ), ] return", "\"-msimd128\", \"-s\", \"USE_PTHREADS=0\", \"-s\", \"ERROR_ON_UNDEFINED_SYMBOLS=0\", \"-s\", \"STANDALONE_WASM=1\", ], ), ]),", "= all_compile_actions, flag_groups = ([ flag_group( flags = [ \"-O3\",", "), tool_path( name = \"strip\", path = \"/bin/false\", ), ]", "Copyright (C) 2019 Intel Corporation. All rights reserved. # SPDX-License-Identifier:", "\"gcc\", path = \"/opt/emsdk/upstream/emscripten/emcc\", ), tool_path( name = \"ld\", path", "= \"nm\", path = \"/bin/false\", ), tool_path( name = \"objdump\",", "= \"default_linker_flags\", enabled = True, flag_sets = [ flag_set( actions", "), ], ), ] return cc_common.create_cc_toolchain_config_info( ctx = ctx, features", "\"unknown\", tool_paths = tool_paths, ) emsdk_toolchain_config = rule( implementation =", "[ \"/opt/emsdk/upstream/emscripten/system/include/libcxx\", \"/opt/emsdk/upstream/emscripten/system/lib/libcxxabi/include\", \"/opt/emsdk/upstream/emscripten/system/include\", \"/opt/emsdk/upstream/emscripten/system/include/libc\", \"/opt/emsdk/upstream/emscripten/system/lib/libc/musl/arch/emscripten\", \"/opt/emsdk/upstream/lib/clang/12.0.0/include/\", ], toolchain_identifier =", "= \"/opt/emsdk/upstream/emscripten/emcc\", ), tool_path( name = \"ld\", path = \"/opt/emsdk/upstream/emscripten/emcc\",", "path = \"/bin/false\", ), tool_path( name = \"strip\", path =", "ACTION_NAMES.cpp_link_nodeps_dynamic_library, ] def _impl(ctx): tool_paths = [ tool_path( name =", "), tool_path( name = \"cpp\", path = \"/opt/emsdk/upstream/emscripten/em++\", ), tool_path(", "abi_version = \"unknown\", abi_libc_version = \"unknown\", tool_paths = tool_paths, )", "return cc_common.create_cc_toolchain_config_info( ctx = ctx, features = features, # NEW", "tool_path( name = \"nm\", path = \"/bin/false\", ), tool_path( name", "= rule( implementation = _impl, attrs = {}, provides =", "], ), feature( name = \"default_linker_flags\", enabled = True, flag_sets", "path = \"/opt/emsdk/upstream/emscripten/em++\", ), tool_path( name = \"gcov\", path =", "= all_link_actions, flag_groups = ([ flag_group( flags = [ \"-O3\",", "name = \"cpp\", path = \"/opt/emsdk/upstream/emscripten/em++\", ), tool_path( name =", "), tool_path( name = \"objdump\", path = \"/bin/false\", ), tool_path(", "= [ \"-O3\", \"-msimd128\", \"-s\", \"USE_PTHREADS=0\", \"-s\", \"ERROR_ON_UNDEFINED_SYMBOLS=0\", \"-s\", \"STANDALONE_WASM=1\",", "tool_paths = tool_paths, ) emsdk_toolchain_config = rule( implementation = _impl,", "path = \"/opt/emsdk/upstream/emscripten/emcc\", ), tool_path( name = \"ld\", path =", "tool_path( name = \"strip\", path = \"/bin/false\", ), ] features", "= \"wasm32-unknown-emscripten\", target_cpu = \"wasm32\", target_libc = \"unknown\", compiler =", "# NEW cxx_builtin_include_directories = [ \"/opt/emsdk/upstream/emscripten/system/include/libcxx\", \"/opt/emsdk/upstream/emscripten/system/lib/libcxxabi/include\", \"/opt/emsdk/upstream/emscripten/system/include\", \"/opt/emsdk/upstream/emscripten/system/include/libc\", \"/opt/emsdk/upstream/emscripten/system/lib/libc/musl/arch/emscripten\",", "\"/bin/false\", ), tool_path( name = \"strip\", path = \"/bin/false\", ),", "name = \"gcov\", path = \"/bin/false\", ), tool_path( name =", "= [ # NEW feature( name = \"default_compile_flags\", enabled =", "\"USE_PTHREADS=0\", \"-s\", \"ERROR_ON_UNDEFINED_SYMBOLS=0\", \"-s\", \"STANDALONE_WASM=1\", ], ), ]), ), ],", "target_system_name = \"wasm32-unknown-emscripten\", target_cpu = \"wasm32\", target_libc = \"unknown\", compiler", "\"-Wl,--export=__data_end\", ], ), ]), ), ], ), ] return cc_common.create_cc_toolchain_config_info(", "target_cpu = \"wasm32\", target_libc = \"unknown\", compiler = \"emsdk\", abi_version", "SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception load(\"@bazel_tools//tools/build_defs/cc:action_names.bzl\", \"ACTION_NAMES\") load( \"@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl\", \"feature\", \"flag_group\",", "= \"/bin/false\", ), tool_path( name = \"nm\", path = \"/bin/false\",", "NEW feature( name = \"default_compile_flags\", enabled = True, flag_sets =", "\"default_linker_flags\", enabled = True, flag_sets = [ flag_set( actions =", "[ ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile, ] all_link_actions = [ ACTION_NAMES.cpp_link_executable, ACTION_NAMES.cpp_link_dynamic_library, ACTION_NAMES.cpp_link_nodeps_dynamic_library,", "), ] features = [ # NEW feature( name =", "emsdk_toolchain_config = rule( implementation = _impl, attrs = {}, provides", "= \"emsdk\", abi_version = \"unknown\", abi_libc_version = \"unknown\", tool_paths =", "= [ \"/opt/emsdk/upstream/emscripten/system/include/libcxx\", \"/opt/emsdk/upstream/emscripten/system/lib/libcxxabi/include\", \"/opt/emsdk/upstream/emscripten/system/include\", \"/opt/emsdk/upstream/emscripten/system/include/libc\", \"/opt/emsdk/upstream/emscripten/system/lib/libc/musl/arch/emscripten\", \"/opt/emsdk/upstream/lib/clang/12.0.0/include/\", ], toolchain_identifier", "implementation = _impl, attrs = {}, provides = [CcToolchainConfigInfo], )", "abi_libc_version = \"unknown\", tool_paths = tool_paths, ) emsdk_toolchain_config = rule(", "\"USE_PTHREADS=0\", \"-s\", \"ERROR_ON_UNDEFINED_SYMBOLS=0\", \"-s\", \"STANDALONE_WASM=1\", \"-Wl,--export=__heap_base\", \"-Wl,--export=__data_end\", ], ), ]),", "\"nm\", path = \"/bin/false\", ), tool_path( name = \"objdump\", path", "\"STANDALONE_WASM=1\", \"-Wl,--export=__heap_base\", \"-Wl,--export=__data_end\", ], ), ]), ), ], ), ]", "), ] return cc_common.create_cc_toolchain_config_info( ctx = ctx, features = features,", "\"objdump\", path = \"/bin/false\", ), tool_path( name = \"strip\", path", "= True, flag_sets = [ flag_set( actions = all_link_actions, flag_groups", "flag_sets = [ flag_set( actions = all_link_actions, flag_groups = ([", "\"ld\", path = \"/opt/emsdk/upstream/emscripten/emcc\", ), tool_path( name = \"ar\", path", "), feature( name = \"default_linker_flags\", enabled = True, flag_sets =", "\"-msimd128\", \"-s\", \"USE_PTHREADS=0\", \"-s\", \"ERROR_ON_UNDEFINED_SYMBOLS=0\", \"-s\", \"STANDALONE_WASM=1\", \"-Wl,--export=__heap_base\", \"-Wl,--export=__data_end\", ],", "feature( name = \"default_compile_flags\", enabled = True, flag_sets = [", "(C) 2019 Intel Corporation. All rights reserved. # SPDX-License-Identifier: Apache-2.0", "] return cc_common.create_cc_toolchain_config_info( ctx = ctx, features = features, #", "\"i686-unknown-linux-gnu\", target_system_name = \"wasm32-unknown-emscripten\", target_cpu = \"wasm32\", target_libc = \"unknown\",", "\"unknown\", compiler = \"emsdk\", abi_version = \"unknown\", abi_libc_version = \"unknown\",", "\"/opt/emsdk/upstream/emscripten/emar\", ), tool_path( name = \"cpp\", path = \"/opt/emsdk/upstream/emscripten/em++\", ),", "WITH LLVM-exception load(\"@bazel_tools//tools/build_defs/cc:action_names.bzl\", \"ACTION_NAMES\") load( \"@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl\", \"feature\", \"flag_group\", \"flag_set\", \"tool_path\",", "\"STANDALONE_WASM=1\", ], ), ]), ), ], ), feature( name =", "\"emsdk\", abi_version = \"unknown\", abi_libc_version = \"unknown\", tool_paths = tool_paths," ]
[ "path = json['id'] except KeyError: return None res = Resource(is_file,", "'rb') as f: files = f response = put_with_OAuth(upload_link, data=files)", "else: raise ValueError(f\"Something went wrong with GD: Response: \" f\"{str(response.status_code)}", "not this function was called as a recursive call :return:", "_rec_call: # We don't need to create a folder with", "parse Resource from YD to Resource object :param json: :return:", "result else: raise ValueError(f\"Something went wrong with YD: Response: \"", "{}).get('usage') total_space = response_read.get('storageQuota', {}).get('limit') return StorageMetaInfo(int(used_space), int(total_space)) else: raise", "= GDriveStorage(None) db = Database('../storage.db') storage.auth(db) authed_storage = GDriveStorage(json.loads(db.get(GOOGLE_DRIVE_DB_KEY))['token']) result", "= True if 'folder' in json['mimeType']: is_file = False #", "if creds_from_db: creds = Credentials.from_authorized_user_info(json.loads(creds_from_db), SCOPES) if not creds or", "== 200: response_as_json = response.json() try: result = response_as_json['files'][0]['id'] return", "Size(json.get('size'), 'b') if json.get('size') else None res.name = json.get('name') res.url", "— {response.json()}\") @classmethod # todo (toplenboren) remove database argument dependency", "resource # This dir is not present in the storage", "== 200: result = [] response_as_json = response.json() files =", "this function was called as a recursive call :return: saved", "< 401: upload_successful_flag = True response = get_with_OAuth(f'https://cloud-api.yandex.net/v1/disk/resources?path={remote_path}', token=self.token) resource_metainfo", "= get_with_OAuth( f\"https://www.googleapis.com/drive/v3/files\", params={ 'fields': '*', 'q': f\"'{folder_id}' in parents\"", "saved resource or raises exception \"\"\" upload_successful_flag = False response", "if response.status_code == 200: response_as_json = response.json() try: result =", "self.token = token @lru_cache(maxsize=None) def _get_folder_id_by_name(self, name: str) -> str:", "- first you need to get an ID of the", "in the storage # We use _rec_call to tell that", "= GDriveStorage(json.loads(db.get(GOOGLE_DRIVE_DB_KEY))['token']) result = authed_storage.list_resources_on_path('savezone') print(result) if __name__ == '__main__':", "None res.name = json.get('name') res.url = json.get('webContentLink') res.updated = json.get('modifiedTime')", "result.append(res) return result else: raise ValueError(f\"Something went wrong with YD:", "response.status_code == 200: response_as_json = response.json() try: result = response_as_json['files'][0]['id']", "in directory :param path: path to the resource \"\"\" folder_id", "= self._deserialize_resource(resource) if res is not None: result.append(res) return result", "create_path(self, remote_path: List[str]) -> None: \"\"\" Creates the remote path", "f'https://cloud-api.yandex.net/v1/disk/resources/download?path={remote_path}', token=self.token ) if response.status_code == 200: response_read = response.json()", "= json.get('md5Checksum') return res def list_resources_on_path(self, remote_path: str) -> List[Resource]:", "string, path to resource on remote fs :param _rec_call: bool,", "= Size(json.get('size'), 'b') if json.get('size') else None res.name = json.get('name')", ":return: \"\"\" try: is_file = True if 'folder' in json['mimeType']:", "= False response = get_with_OAuth( f'https://cloud-api.yandex.net/v1/disk/resources/upload?path={remote_path}&overwrite=${overwrite}', token=self.token ) if response.status_code", "the next call was made as recursive call, so we", "remote_path, local_path) -> str: response = get_with_OAuth( f'https://cloud-api.yandex.net/v1/disk/resources/download?path={remote_path}', token=self.token )", "cloud_storages.gdrive.client_config import GOOGLE_DRIVE_CONFIG, SCOPES from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests", "f\"{str(response.status_code)} — {response.json()}\") @classmethod # todo (toplenboren) remove database argument", "f\"{str(response.status_code)} — {response.json()['message']}\") file = requests.get(dl_url) open(local_path, 'wb').write(file.content) return local_path", "went wrong with YD: Response: \" f\"{str(response.status_code)} — {response.json()['message']}\") def", "cause SO elif response.status_code == 409 and not _rec_call: #", "Database('../storage.db') storage.auth(db) authed_storage = GDriveStorage(json.loads(db.get(GOOGLE_DRIVE_DB_KEY))['token']) result = authed_storage.list_resources_on_path('savezone') print(result) if", "in remote_path: dir_to_create.append(dir) path_to_create = '/'.join(dir_to_create) response = put_with_OAuth(f'https://cloud-api.yandex.net/v1/disk/resources?path={path_to_create}', token=self.token)", "except KeyError: return None res = Resource(is_file, path) res.size =", "files: res: Resource or None = self._deserialize_resource(resource) if res is", "or not this function was called as a recursive call", "= '{name}' and mimeType = 'application/vnd.google-apps.folder'\" }, token=self.token ) if", "e: raise ValueError(f\"Something went wrong with GD: Error: {e}\") else:", "get_meta_info(self) -> StorageMetaInfo: response = get_with_OAuth('https://www.googleapis.com/drive/v3/about?fields=*', token=self.token) if response.status_code ==", "401: print(f'[{__name__}] Created directory {path_to_create}') continue elif response.status_code == 409", "and mimeType = 'application/vnd.google-apps.folder'\" }, token=self.token ) if response.status_code ==", "return StorageMetaInfo(int(used_space), int(total_space)) else: raise ValueError(f\"Something went wrong with GD:", "equal to the filename, so we do [:-1] self.create_path(remote_path.split('/')[:-1]) return", "# todo (toplenboren) remove database argument dependency :( def auth(cls,", "open(local_path, 'wb').write(file.content) return local_path def main(): storage = GDriveStorage(None) db", "token=self.token) if 199 < response.status_code < 401: print(f'[{__name__}] Created directory", "= [] response_as_json = response.json() files = response_as_json['files'] for resource", "res.url = json.get('webContentLink') res.updated = json.get('modifiedTime') res.md5 = json.get('md5Checksum') return", "not creds or not creds.valid: if creds and creds.expired and", "paths - first you need to get an ID of", "True response = get_with_OAuth(f'https://cloud-api.yandex.net/v1/disk/resources?path={remote_path}', token=self.token) resource_metainfo = self._deserialize_resource(response.json()) if 199", "ValueError(f\"[{__name__}] Something went wrong with YD: Response: \" f\"{str(response.status_code)} —", "if response.status_code == 200: response_read = response.json() upload_link = response_read['href']", "elif upload_successful_flag: return resource # This dir is not present", "(toplenboren) remove database argument dependency :( def auth(cls, db: Database):", "if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow =", "== 200: response_read = response.json() dl_url = response_read.get('href') else: raise", "resource_metainfo elif upload_successful_flag: return resource # This dir is not", "def auth(cls, db: Database): creds = None creds_from_db = db.get(GOOGLE_DRIVE_DB_KEY)", "to tell that the next call was made as recursive", "or None: \"\"\" Tries to parse Resource from YD to", "def save_resource_to_path(self, resource: Resource, remote_path: str, overwrite: bool, _rec_call:bool =", "json: :return: \"\"\" try: is_file = True if 'folder' in", "function was called as a recursive call :return: saved resource", "< response.status_code < 401: print(f'[{__name__}] Created directory {path_to_create}') continue elif", "Size from cloud_storages.storage import Storage from cloud_storages.gdrive.client_config import GOOGLE_DRIVE_CONFIG, SCOPES", "StorageMetaInfo(int(used_space), int(total_space)) else: raise ValueError(f\"Something went wrong with GD: Response:", "response_as_json = response.json() try: result = response_as_json['files'][0]['id'] return result except", "def list_resources_on_path(self, remote_path: str) -> List[Resource]: \"\"\" List all items", "import InstalledAppFlow from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials", "401: upload_successful_flag = True response = get_with_OAuth(f'https://cloud-api.yandex.net/v1/disk/resources?path={remote_path}', token=self.token) resource_metainfo =", "200: response_read = response.json() dl_url = response_read.get('href') else: raise ValueError(f\"[{__name__}]", "response.status_code == 409 and 'уже существует' in response.json().get('message', ''): continue", ":param remote_path: string, path to resource on remote fs :param", "= db.get(GOOGLE_DRIVE_DB_KEY) if creds_from_db: creds = Credentials.from_authorized_user_info(json.loads(creds_from_db), SCOPES) if not", "def _deserialize_resource(cls, json: dict) -> Resource or None: \"\"\" Tries", "_rec_call: bool, a system parameter, whether or not this function", "'q': f\"name = '{name}' and mimeType = 'application/vnd.google-apps.folder'\" }, token=self.token", "response_as_json['files'] for resource in files: res: Resource or None =", "is not None: result.append(res) return result else: raise ValueError(f\"Something went", "None creds_from_db = db.get(GOOGLE_DRIVE_DB_KEY) if creds_from_db: creds = Credentials.from_authorized_user_info(json.loads(creds_from_db), SCOPES)", "_rec_call=True) raise ValueError(f\"Something went wrong with YD: Response: \" f\"{str(response.status_code)}", "StorageMetaInfo: response = get_with_OAuth('https://www.googleapis.com/drive/v3/about?fields=*', token=self.token) if response.status_code == 200: response_read", "< 401: return resource_metainfo elif upload_successful_flag: return resource # This", "we do [:-1] self.create_path(remote_path.split('/')[:-1]) return self.save_resource_to_path(resource, remote_path, overwrite, _rec_call=True) raise", "response.json() dl_url = response_read.get('href') else: raise ValueError(f\"[{__name__}] Something went wrong", "'application/vnd.google-apps.folder'\" }, token=self.token ) if response.status_code == 200: response_as_json =", "str) -> List[Resource]: \"\"\" List all items in directory :param", "use _rec_call to tell that the next call was made", "id path = json['id'] except KeyError: return None res =", "f\"{str(response.status_code)} — {response.json()['message']}\") def create_path(self, remote_path: List[str]) -> None: \"\"\"", "None: result.append(res) return result else: raise ValueError(f\"Something went wrong with", "the storage # We use _rec_call to tell that the", "to create directory {\"/\".join(remote_path)} on remote...') dir_to_create = [] for", ":param path: path to the resource \"\"\" folder_id = self._get_folder_id_by_name(remote_path)", "download_resource(self, remote_path, local_path) -> str: response = get_with_OAuth( f'https://cloud-api.yandex.net/v1/disk/resources/download?path={remote_path}', token=self.token", "List all items in directory :param path: path to the", "files = f response = put_with_OAuth(upload_link, data=files) if 199 <", "Tries to parse Resource from YD to Resource object :param", "or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request())", "Response: \" f\"{str(response.status_code)} — {response.json()['message']}\") def get_meta_info(self) -> StorageMetaInfo: response", "name \"\"\" response = get_with_OAuth( f\"https://www.googleapis.com/drive/v3/files\", params={ 'fields': '*', 'q':", "from database.database import Database from models.models import StorageMetaInfo, Resource, Size", "return def save_resource_to_path(self, resource: Resource, remote_path: str, overwrite: bool, _rec_call:bool", "существует' in response.json().get('message', ''): continue return def save_resource_to_path(self, resource: Resource,", "self.create_path(remote_path.split('/')[:-1]) return self.save_resource_to_path(resource, remote_path, overwrite, _rec_call=True) raise ValueError(f\"Something went wrong", "json: dict) -> Resource or None: \"\"\" Tries to parse", "YD: Response: \" f\"{str(response.status_code)} — {response.json()['message']}\") def get_meta_info(self) -> StorageMetaInfo:", "token=self.token) if response.status_code == 200: response_read = response.json() used_space =", ":param _rec_call: bool, a system parameter, whether or not this", "f\"https://www.googleapis.com/drive/v3/files\", params={ 'fields': '*', 'q': f\"name = '{name}' and mimeType", "was called as a recursive call :return: saved resource or", "res.size = Size(json.get('size'), 'b') if json.get('size') else None res.name =", "= put_with_OAuth(f'https://cloud-api.yandex.net/v1/disk/resources?path={path_to_create}', token=self.token) if 199 < response.status_code < 401: print(f'[{__name__}]", "call, so we don't cause SO elif response.status_code == 409", "so we do [:-1] self.create_path(remote_path.split('/')[:-1]) return self.save_resource_to_path(resource, remote_path, overwrite, _rec_call=True)", "path_to_create = '/'.join(dir_to_create) response = put_with_OAuth(f'https://cloud-api.yandex.net/v1/disk/resources?path={path_to_create}', token=self.token) if 199 <", "dict) -> Resource or None: \"\"\" Tries to parse Resource", "or None = self._deserialize_resource(resource) if res is not None: result.append(res)", "else: raise ValueError(f\"[{__name__}] Something went wrong with YD: Response: \"", "upload_link = response_read['href'] with open(resource.path, 'rb') as f: files =", "auth(cls, db: Database): creds = None creds_from_db = db.get(GOOGLE_DRIVE_DB_KEY) if", "a quirk - you can't really use normal os-like paths", "f\"https://www.googleapis.com/drive/v3/files\", params={ 'fields': '*', 'q': f\"'{folder_id}' in parents\" }, token=self.token", "— {response.json()['message']}\") def get_meta_info(self) -> StorageMetaInfo: response = get_with_OAuth('https://www.googleapis.com/drive/v3/about?fields=*', token=self.token)", "and not _rec_call: # We don't need to create a", "Response: \" f\"{str(response.status_code)} — {response.json().get('message', '')}\") def download_resource(self, remote_path, local_path)", "resource or raises exception \"\"\" upload_successful_flag = False response =", "function searches for folders with specified name \"\"\" response =", "the name equal to the filename, so we do [:-1]", "-> StorageMetaInfo: response = get_with_OAuth('https://www.googleapis.com/drive/v3/about?fields=*', token=self.token) if response.status_code == 200:", "was made as recursive call, so we don't cause SO", "you need to get an ID of the folder This", "Database): creds = None creds_from_db = db.get(GOOGLE_DRIVE_DB_KEY) if creds_from_db: creds", "really use normal os-like paths - first you need to", "in response.json().get('message', ''): continue return def save_resource_to_path(self, resource: Resource, remote_path:", "don't cause SO elif response.status_code == 409 and not _rec_call:", "response = get_with_OAuth( f\"https://www.googleapis.com/drive/v3/files\", params={ 'fields': '*', 'q': f\"name =", "response.status_code < 401: print(f'[{__name__}] Created directory {path_to_create}') continue elif response.status_code", "filename, so we do [:-1] self.create_path(remote_path.split('/')[:-1]) return self.save_resource_to_path(resource, remote_path, overwrite,", "{e}\") else: raise ValueError(f\"Something went wrong with GD: Response: \"", "None: \"\"\" Put an Item to the directory :param resource:", "— {response.json().get('message', '')}\") def download_resource(self, remote_path, local_path) -> str: response", "= 'google' class GDriveStorage(Storage): def __init__(self, token): self.token = token", "= json['id'] except KeyError: return None res = Resource(is_file, path)", "with YD: Response: \" f\"{str(response.status_code)} — {response.json().get('message', '')}\") def download_resource(self,", "We use _rec_call to tell that the next call was", "return self.save_resource_to_path(resource, remote_path, overwrite, _rec_call=True) raise ValueError(f\"Something went wrong with", "* from database.database import Database from models.models import StorageMetaInfo, Resource,", "@classmethod # todo (toplenboren) remove database argument dependency :( def", "[] response_as_json = response.json() files = response_as_json['files'] for resource in", "[:-1] self.create_path(remote_path.split('/')[:-1]) return self.save_resource_to_path(resource, remote_path, overwrite, _rec_call=True) raise ValueError(f\"Something went", "token=self.token) resource_metainfo = self._deserialize_resource(response.json()) if 199 < response.status_code < 401:", "models.models import StorageMetaInfo, Resource, Size from cloud_storages.storage import Storage from", "cloud_storages.http_shortcuts import * from database.database import Database from models.models import", "def main(): storage = GDriveStorage(None) db = Database('../storage.db') storage.auth(db) authed_storage", "\"\"\" try: is_file = True if 'folder' in json['mimeType']: is_file", "= False # You don't have pathes in google drive,", "self._get_folder_id_by_name(remote_path) response = get_with_OAuth( f\"https://www.googleapis.com/drive/v3/files\", params={ 'fields': '*', 'q': f\"'{folder_id}'", "import List from functools import lru_cache from cloud_storages.http_shortcuts import *", "token @lru_cache(maxsize=None) def _get_folder_id_by_name(self, name: str) -> str: \"\"\" Google", "\" f\"{str(response.status_code)} — {response.json()}\") @classmethod # todo (toplenboren) remove database", "creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_config(GOOGLE_DRIVE_CONFIG, SCOPES) creds = flow.run_local_server(port=0)", "json.get('name') res.url = json.get('webContentLink') res.updated = json.get('modifiedTime') res.md5 = json.get('md5Checksum')", "else: raise ValueError(f\"Something went wrong with YD: Response: \" f\"{str(response.status_code)}", "res.updated = json.get('modifiedTime') res.md5 = json.get('md5Checksum') return res def list_resources_on_path(self,", "str: response = get_with_OAuth( f'https://cloud-api.yandex.net/v1/disk/resources/download?path={remote_path}', token=self.token ) if response.status_code ==", "YD: Response: \" f\"{str(response.status_code)} — {response.json()['message']}\") file = requests.get(dl_url) open(local_path,", "resource on remote fs :param _rec_call: bool, a system parameter,", "Request from google.oauth2.credentials import Credentials GOOGLE_DRIVE_DB_KEY = 'google' class GDriveStorage(Storage):", "save_resource_to_path(self, resource: Resource, remote_path: str, overwrite: bool, _rec_call:bool = False)", "flow.run_local_server(port=0) db.set(GOOGLE_DRIVE_DB_KEY, creds.token) @classmethod def _deserialize_resource(cls, json: dict) -> Resource", "Resource object :param json: :return: \"\"\" try: is_file = True", "else: flow = InstalledAppFlow.from_client_config(GOOGLE_DRIVE_CONFIG, SCOPES) creds = flow.run_local_server(port=0) db.set(GOOGLE_DRIVE_DB_KEY, creds.token)", "on remote fs :param _rec_call: bool, a system parameter, whether", "response = get_with_OAuth( f'https://cloud-api.yandex.net/v1/disk/resources/upload?path={remote_path}&overwrite=${overwrite}', token=self.token ) if response.status_code == 200:", "dependency :( def auth(cls, db: Database): creds = None creds_from_db", "= None creds_from_db = db.get(GOOGLE_DRIVE_DB_KEY) if creds_from_db: creds = Credentials.from_authorized_user_info(json.loads(creds_from_db),", "f\"'{folder_id}' in parents\" }, token=self.token ) if response.status_code == 200:", "199 < response.status_code < 401: print(f'[{__name__}] Created directory {path_to_create}') continue", "not None: result.append(res) return result else: raise ValueError(f\"Something went wrong", "[] for dir in remote_path: dir_to_create.append(dir) path_to_create = '/'.join(dir_to_create) response", "get_with_OAuth( f\"https://www.googleapis.com/drive/v3/files\", params={ 'fields': '*', 'q': f\"'{folder_id}' in parents\" },", "have pathes in google drive, instead -- you have an", "folder with the name equal to the filename, so we", "name equal to the filename, so we do [:-1] self.create_path(remote_path.split('/')[:-1])", "Resource, remote_path: str, overwrite: bool, _rec_call:bool = False) -> Resource", "dir is not present in the storage # We use", "Resource or None: \"\"\" Put an Item to the directory", "401: return resource_metainfo elif upload_successful_flag: return resource # This dir", "items in directory :param path: path to the resource \"\"\"", "mimeType = 'application/vnd.google-apps.folder'\" }, token=self.token ) if response.status_code == 200:", "remote_path: string, path to resource on remote fs :param _rec_call:", "yandex disk \"\"\" print(f'[{__name__}] Trying to create directory {\"/\".join(remote_path)} on", "— {response.json()['message']}\") def create_path(self, remote_path: List[str]) -> None: \"\"\" Creates", "if 199 < response.status_code < 401: print(f'[{__name__}] Created directory {path_to_create}')", "try: is_file = True if 'folder' in json['mimeType']: is_file =", "elif response.status_code == 409 and 'уже существует' in response.json().get('message', ''):", "to the directory :param resource: resource on the local fs", "= requests.get(dl_url) open(local_path, 'wb').write(file.content) return local_path def main(): storage =", "self._deserialize_resource(resource) if res is not None: result.append(res) return result else:", "wrong with YD: Response: \" f\"{str(response.status_code)} — {response.json()['message']}\") def get_meta_info(self)", "directory {\"/\".join(remote_path)} on remote...') dir_to_create = [] for dir in", "199 < response.status_code < 401: upload_successful_flag = True response =", "call :return: saved resource or raises exception \"\"\" upload_successful_flag =", "# We don't need to create a folder with the", "creds = Credentials.from_authorized_user_info(json.loads(creds_from_db), SCOPES) if not creds or not creds.valid:", "200: response_as_json = response.json() try: result = response_as_json['files'][0]['id'] return result", "wrong with GD: Error: {e}\") else: raise ValueError(f\"Something went wrong", "res.md5 = json.get('md5Checksum') return res def list_resources_on_path(self, remote_path: str) ->", "argument dependency :( def auth(cls, db: Database): creds = None", "json.get('webContentLink') res.updated = json.get('modifiedTime') res.md5 = json.get('md5Checksum') return res def", "create a folder with the name equal to the filename,", "res is not None: result.append(res) return result else: raise ValueError(f\"Something", "print(f'[{__name__}] Created directory {path_to_create}') continue elif response.status_code == 409 and", "\"\"\" List all items in directory :param path: path to", "try: result = response_as_json['files'][0]['id'] return result except IndexError as e:", ":param json: :return: \"\"\" try: is_file = True if 'folder'", "put_with_OAuth(upload_link, data=files) if 199 < response.status_code < 401: upload_successful_flag =", "response.status_code == 200: response_read = response.json() used_space = response_read.get('storageQuota', {}).get('usage')", "creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_config(GOOGLE_DRIVE_CONFIG, SCOPES) creds", "'q': f\"'{folder_id}' in parents\" }, token=self.token ) if response.status_code ==", "os-like paths - first you need to get an ID", "went wrong with YD: Response: \" f\"{str(response.status_code)} — {response.json()['message']}\") file", "import GOOGLE_DRIVE_CONFIG, SCOPES from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import", "google drive, instead -- you have an id path =", "all items in directory :param path: path to the resource", "print_function import json from typing import List from functools import", "IndexError as e: raise ValueError(f\"Something went wrong with GD: Error:", "response = get_with_OAuth( f\"https://www.googleapis.com/drive/v3/files\", params={ 'fields': '*', 'q': f\"'{folder_id}' in", "= False) -> Resource or None: \"\"\" Put an Item", "bool, a system parameter, whether or not this function was", "response_read = response.json() upload_link = response_read['href'] with open(resource.path, 'rb') as", "can't really use normal os-like paths - first you need", "You don't have pathes in google drive, instead -- you", "= InstalledAppFlow.from_client_config(GOOGLE_DRIVE_CONFIG, SCOPES) creds = flow.run_local_server(port=0) db.set(GOOGLE_DRIVE_DB_KEY, creds.token) @classmethod def", "get_with_OAuth(f'https://cloud-api.yandex.net/v1/disk/resources?path={remote_path}', token=self.token) resource_metainfo = self._deserialize_resource(response.json()) if 199 < response.status_code <", "res: Resource or None = self._deserialize_resource(resource) if res is not", "import Database from models.models import StorageMetaInfo, Resource, Size from cloud_storages.storage", "dir in remote_path: dir_to_create.append(dir) path_to_create = '/'.join(dir_to_create) response = put_with_OAuth(f'https://cloud-api.yandex.net/v1/disk/resources?path={path_to_create}',", "'b') if json.get('size') else None res.name = json.get('name') res.url =", "-> List[Resource]: \"\"\" List all items in directory :param path:", "SCOPES) creds = flow.run_local_server(port=0) db.set(GOOGLE_DRIVE_DB_KEY, creds.token) @classmethod def _deserialize_resource(cls, json:", "directory :param path: path to the resource \"\"\" folder_id =", "__init__(self, token): self.token = token @lru_cache(maxsize=None) def _get_folder_id_by_name(self, name: str)", "with open(resource.path, 'rb') as f: files = f response =", "raise ValueError(f\"Something went wrong with GD: Response: \" f\"{str(response.status_code)} —", "= '/'.join(dir_to_create) response = put_with_OAuth(f'https://cloud-api.yandex.net/v1/disk/resources?path={path_to_create}', token=self.token) if 199 < response.status_code", "\"\"\" Tries to parse Resource from YD to Resource object", "directory {path_to_create}') continue elif response.status_code == 409 and 'уже существует'", "response = get_with_OAuth(f'https://cloud-api.yandex.net/v1/disk/resources?path={remote_path}', token=self.token) resource_metainfo = self._deserialize_resource(response.json()) if 199 <", "__future__ import print_function import json from typing import List from", "so we don't cause SO elif response.status_code == 409 and", ") if response.status_code == 200: result = [] response_as_json =", "made as recursive call, so we don't cause SO elif", "to the filename, so we do [:-1] self.create_path(remote_path.split('/')[:-1]) return self.save_resource_to_path(resource,", "int(total_space)) else: raise ValueError(f\"Something went wrong with GD: Response: \"", "= json.get('name') res.url = json.get('webContentLink') res.updated = json.get('modifiedTime') res.md5 =", "authed_storage = GDriveStorage(json.loads(db.get(GOOGLE_DRIVE_DB_KEY))['token']) result = authed_storage.list_resources_on_path('savezone') print(result) if __name__ ==", "Response: \" f\"{str(response.status_code)} — {response.json()}\") @classmethod # todo (toplenboren) remove", "== 409 and not _rec_call: # We don't need to", "used_space = response_read.get('storageQuota', {}).get('usage') total_space = response_read.get('storageQuota', {}).get('limit') return StorageMetaInfo(int(used_space),", "wrong with YD: Response: \" f\"{str(response.status_code)} — {response.json()['message']}\") file =", "folder This function searches for folders with specified name \"\"\"", "get_with_OAuth( f'https://cloud-api.yandex.net/v1/disk/resources/download?path={remote_path}', token=self.token ) if response.status_code == 200: response_read =", "functools import lru_cache from cloud_storages.http_shortcuts import * from database.database import", "storage.auth(db) authed_storage = GDriveStorage(json.loads(db.get(GOOGLE_DRIVE_DB_KEY))['token']) result = authed_storage.list_resources_on_path('savezone') print(result) if __name__", "typing import List from functools import lru_cache from cloud_storages.http_shortcuts import", "def __init__(self, token): self.token = token @lru_cache(maxsize=None) def _get_folder_id_by_name(self, name:", "creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_config(GOOGLE_DRIVE_CONFIG,", ":return: saved resource or raises exception \"\"\" upload_successful_flag = False", "{response.json()['message']}\") def create_path(self, remote_path: List[str]) -> None: \"\"\" Creates the", "in google drive, instead -- you have an id path", "database argument dependency :( def auth(cls, db: Database): creds =", "present in the storage # We use _rec_call to tell", "raise ValueError(f\"Something went wrong with GD: Error: {e}\") else: raise", "= [] for dir in remote_path: dir_to_create.append(dir) path_to_create = '/'.join(dir_to_create)", "return result else: raise ValueError(f\"Something went wrong with YD: Response:", "the local fs :param remote_path: string, path to resource on", "fs :param remote_path: string, path to resource on remote fs", "'fields': '*', 'q': f\"'{folder_id}' in parents\" }, token=self.token ) if", "f'https://cloud-api.yandex.net/v1/disk/resources/upload?path={remote_path}&overwrite=${overwrite}', token=self.token ) if response.status_code == 200: response_read = response.json()", "409 and 'уже существует' in response.json().get('message', ''): continue return def", "-> str: response = get_with_OAuth( f'https://cloud-api.yandex.net/v1/disk/resources/download?path={remote_path}', token=self.token ) if response.status_code", "'*', 'q': f\"name = '{name}' and mimeType = 'application/vnd.google-apps.folder'\" },", "lru_cache from cloud_storages.http_shortcuts import * from database.database import Database from", "put_with_OAuth(f'https://cloud-api.yandex.net/v1/disk/resources?path={path_to_create}', token=self.token) if 199 < response.status_code < 401: print(f'[{__name__}] Created", "an id path = json['id'] except KeyError: return None res", "StorageMetaInfo, Resource, Size from cloud_storages.storage import Storage from cloud_storages.gdrive.client_config import", "str, overwrite: bool, _rec_call:bool = False) -> Resource or None:", "def create_path(self, remote_path: List[str]) -> None: \"\"\" Creates the remote", "file = requests.get(dl_url) open(local_path, 'wb').write(file.content) return local_path def main(): storage", "google.auth.transport.requests import Request from google.oauth2.credentials import Credentials GOOGLE_DRIVE_DB_KEY = 'google'", "an Item to the directory :param resource: resource on the", "to the resource \"\"\" folder_id = self._get_folder_id_by_name(remote_path) response = get_with_OAuth(", "not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else:", "creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_config(GOOGLE_DRIVE_CONFIG, SCOPES) creds = flow.run_local_server(port=0) db.set(GOOGLE_DRIVE_DB_KEY,", "f\"{str(response.status_code)} — {response.json()['message']}\") def get_meta_info(self) -> StorageMetaInfo: response = get_with_OAuth('https://www.googleapis.com/drive/v3/about?fields=*',", "< response.status_code < 401: upload_successful_flag = True response = get_with_OAuth(f'https://cloud-api.yandex.net/v1/disk/resources?path={remote_path}',", "}, token=self.token ) if response.status_code == 200: response_as_json = response.json()", "response.status_code < 401: upload_successful_flag = True response = get_with_OAuth(f'https://cloud-api.yandex.net/v1/disk/resources?path={remote_path}', token=self.token)", "import StorageMetaInfo, Resource, Size from cloud_storages.storage import Storage from cloud_storages.gdrive.client_config", "files = response_as_json['files'] for resource in files: res: Resource or", "= 'application/vnd.google-apps.folder'\" }, token=self.token ) if response.status_code == 200: response_as_json", "json.get('md5Checksum') return res def list_resources_on_path(self, remote_path: str) -> List[Resource]: \"\"\"", "class GDriveStorage(Storage): def __init__(self, token): self.token = token @lru_cache(maxsize=None) def", "the resource \"\"\" folder_id = self._get_folder_id_by_name(remote_path) response = get_with_OAuth( f\"https://www.googleapis.com/drive/v3/files\",", "{response.json()['message']}\") file = requests.get(dl_url) open(local_path, 'wb').write(file.content) return local_path def main():", "with GD: Error: {e}\") else: raise ValueError(f\"Something went wrong with", "ValueError(f\"Something went wrong with YD: Response: \" f\"{str(response.status_code)} — {response.json().get('message',", "print(f'[{__name__}] Trying to create directory {\"/\".join(remote_path)} on remote...') dir_to_create =", "parents\" }, token=self.token ) if response.status_code == 200: result =", ") if response.status_code == 200: response_read = response.json() upload_link =", "# This dir is not present in the storage #", "total_space = response_read.get('storageQuota', {}).get('limit') return StorageMetaInfo(int(used_space), int(total_space)) else: raise ValueError(f\"Something", "KeyError: return None res = Resource(is_file, path) res.size = Size(json.get('size'),", "response.status_code < 401: return resource_metainfo elif upload_successful_flag: return resource #", "f: files = f response = put_with_OAuth(upload_link, data=files) if 199", "response.status_code == 200: result = [] response_as_json = response.json() files", "from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request from google.oauth2.credentials", "# We use _rec_call to tell that the next call", "'fields': '*', 'q': f\"name = '{name}' and mimeType = 'application/vnd.google-apps.folder'\"", "False response = get_with_OAuth( f'https://cloud-api.yandex.net/v1/disk/resources/upload?path={remote_path}&overwrite=${overwrite}', token=self.token ) if response.status_code ==", "_deserialize_resource(cls, json: dict) -> Resource or None: \"\"\" Tries to", "GOOGLE_DRIVE_DB_KEY = 'google' class GDriveStorage(Storage): def __init__(self, token): self.token =", "token): self.token = token @lru_cache(maxsize=None) def _get_folder_id_by_name(self, name: str) ->", "\" f\"{str(response.status_code)} — {response.json()['message']}\") def create_path(self, remote_path: List[str]) -> None:", "you can't really use normal os-like paths - first you", "not _rec_call: # We don't need to create a folder", "to create a folder with the name equal to the", "token=self.token ) if response.status_code == 200: response_read = response.json() dl_url", "or raises exception \"\"\" upload_successful_flag = False response = get_with_OAuth(", "if response.status_code == 200: response_read = response.json() dl_url = response_read.get('href')", "creds or not creds.valid: if creds and creds.expired and creds.refresh_token:", "response_read.get('href') else: raise ValueError(f\"[{__name__}] Something went wrong with YD: Response:", "def get_meta_info(self) -> StorageMetaInfo: response = get_with_OAuth('https://www.googleapis.com/drive/v3/about?fields=*', token=self.token) if response.status_code", "response_read['href'] with open(resource.path, 'rb') as f: files = f response", "f\"{str(response.status_code)} — {response.json().get('message', '')}\") def download_resource(self, remote_path, local_path) -> str:", "resource: Resource, remote_path: str, overwrite: bool, _rec_call:bool = False) ->", "call was made as recursive call, so we don't cause", "remote_path: dir_to_create.append(dir) path_to_create = '/'.join(dir_to_create) response = put_with_OAuth(f'https://cloud-api.yandex.net/v1/disk/resources?path={path_to_create}', token=self.token) if", "db.set(GOOGLE_DRIVE_DB_KEY, creds.token) @classmethod def _deserialize_resource(cls, json: dict) -> Resource or", "- you can't really use normal os-like paths - first", "<gh_stars>0 from __future__ import print_function import json from typing import", "\"\"\" Put an Item to the directory :param resource: resource", "Storage from cloud_storages.gdrive.client_config import GOOGLE_DRIVE_CONFIG, SCOPES from google_auth_oauthlib.flow import InstalledAppFlow", "path on yandex disk \"\"\" print(f'[{__name__}] Trying to create directory", "went wrong with GD: Response: \" f\"{str(response.status_code)} — {response.json()}\") @classmethod", "with YD: Response: \" f\"{str(response.status_code)} — {response.json()['message']}\") def get_meta_info(self) ->", "use normal os-like paths - first you need to get", "@lru_cache(maxsize=None) def _get_folder_id_by_name(self, name: str) -> str: \"\"\" Google drive", "and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_config(GOOGLE_DRIVE_CONFIG, SCOPES)", "list_resources_on_path(self, remote_path: str) -> List[Resource]: \"\"\" List all items in", "json.get('modifiedTime') res.md5 = json.get('md5Checksum') return res def list_resources_on_path(self, remote_path: str)", "Resource or None: \"\"\" Tries to parse Resource from YD", "= token @lru_cache(maxsize=None) def _get_folder_id_by_name(self, name: str) -> str: \"\"\"", "response_as_json = response.json() files = response_as_json['files'] for resource in files:", "the filename, so we do [:-1] self.create_path(remote_path.split('/')[:-1]) return self.save_resource_to_path(resource, remote_path,", "False # You don't have pathes in google drive, instead", "specified name \"\"\" response = get_with_OAuth( f\"https://www.googleapis.com/drive/v3/files\", params={ 'fields': '*',", "= response.json() upload_link = response_read['href'] with open(resource.path, 'rb') as f:", "you have an id path = json['id'] except KeyError: return", "return resource # This dir is not present in the", "response = get_with_OAuth('https://www.googleapis.com/drive/v3/about?fields=*', token=self.token) if response.status_code == 200: response_read =", "= response.json() used_space = response_read.get('storageQuota', {}).get('usage') total_space = response_read.get('storageQuota', {}).get('limit')", "database.database import Database from models.models import StorageMetaInfo, Resource, Size from", "raises exception \"\"\" upload_successful_flag = False response = get_with_OAuth( f'https://cloud-api.yandex.net/v1/disk/resources/upload?path={remote_path}&overwrite=${overwrite}',", "create directory {\"/\".join(remote_path)} on remote...') dir_to_create = [] for dir", "We don't need to create a folder with the name", "with the name equal to the filename, so we do", "system parameter, whether or not this function was called as", "elif response.status_code == 409 and not _rec_call: # We don't", "if response.status_code == 200: result = [] response_as_json = response.json()", "== 200: response_read = response.json() upload_link = response_read['href'] with open(resource.path,", "recursive call, so we don't cause SO elif response.status_code ==", "GDriveStorage(None) db = Database('../storage.db') storage.auth(db) authed_storage = GDriveStorage(json.loads(db.get(GOOGLE_DRIVE_DB_KEY))['token']) result =", "< response.status_code < 401: return resource_metainfo elif upload_successful_flag: return resource", "result = response_as_json['files'][0]['id'] return result except IndexError as e: raise", "if 199 < response.status_code < 401: upload_successful_flag = True response", "creds = None creds_from_db = db.get(GOOGLE_DRIVE_DB_KEY) if creds_from_db: creds =", "creds = flow.run_local_server(port=0) db.set(GOOGLE_DRIVE_DB_KEY, creds.token) @classmethod def _deserialize_resource(cls, json: dict)", "= self._get_folder_id_by_name(remote_path) response = get_with_OAuth( f\"https://www.googleapis.com/drive/v3/files\", params={ 'fields': '*', 'q':", "on the local fs :param remote_path: string, path to resource", "ValueError(f\"Something went wrong with GD: Error: {e}\") else: raise ValueError(f\"Something", "response = get_with_OAuth( f'https://cloud-api.yandex.net/v1/disk/resources/download?path={remote_path}', token=self.token ) if response.status_code == 200:", "response_as_json['files'][0]['id'] return result except IndexError as e: raise ValueError(f\"Something went", "if 199 < response.status_code < 401: return resource_metainfo elif upload_successful_flag:", "response.json().get('message', ''): continue return def save_resource_to_path(self, resource: Resource, remote_path: str,", "Something went wrong with YD: Response: \" f\"{str(response.status_code)} — {response.json()['message']}\")", "get_with_OAuth( f\"https://www.googleapis.com/drive/v3/files\", params={ 'fields': '*', 'q': f\"name = '{name}' and", "is not present in the storage # We use _rec_call", "-- you have an id path = json['id'] except KeyError:", "recursive call :return: saved resource or raises exception \"\"\" upload_successful_flag", "200: response_read = response.json() upload_link = response_read['href'] with open(resource.path, 'rb')", "continue return def save_resource_to_path(self, resource: Resource, remote_path: str, overwrite: bool,", "def _get_folder_id_by_name(self, name: str) -> str: \"\"\" Google drive has", "str: \"\"\" Google drive has a quirk - you can't", "on remote...') dir_to_create = [] for dir in remote_path: dir_to_create.append(dir)", "# You don't have pathes in google drive, instead --", "in json['mimeType']: is_file = False # You don't have pathes", "None res = Resource(is_file, path) res.size = Size(json.get('size'), 'b') if", "return result except IndexError as e: raise ValueError(f\"Something went wrong", "import Credentials GOOGLE_DRIVE_DB_KEY = 'google' class GDriveStorage(Storage): def __init__(self, token):", "= self._deserialize_resource(response.json()) if 199 < response.status_code < 401: return resource_metainfo", "cloud_storages.storage import Storage from cloud_storages.gdrive.client_config import GOOGLE_DRIVE_CONFIG, SCOPES from google_auth_oauthlib.flow", "todo (toplenboren) remove database argument dependency :( def auth(cls, db:", "= put_with_OAuth(upload_link, data=files) if 199 < response.status_code < 401: upload_successful_flag", "from google.oauth2.credentials import Credentials GOOGLE_DRIVE_DB_KEY = 'google' class GDriveStorage(Storage): def", "path to the resource \"\"\" folder_id = self._get_folder_id_by_name(remote_path) response =", "response_read.get('storageQuota', {}).get('usage') total_space = response_read.get('storageQuota', {}).get('limit') return StorageMetaInfo(int(used_space), int(total_space)) else:", "overwrite, _rec_call=True) raise ValueError(f\"Something went wrong with YD: Response: \"", "GD: Error: {e}\") else: raise ValueError(f\"Something went wrong with GD:", "YD to Resource object :param json: :return: \"\"\" try: is_file", "local_path) -> str: response = get_with_OAuth( f'https://cloud-api.yandex.net/v1/disk/resources/download?path={remote_path}', token=self.token ) if", "dl_url = response_read.get('href') else: raise ValueError(f\"[{__name__}] Something went wrong with", "json from typing import List from functools import lru_cache from", "from typing import List from functools import lru_cache from cloud_storages.http_shortcuts", "res.name = json.get('name') res.url = json.get('webContentLink') res.updated = json.get('modifiedTime') res.md5", "\"\"\" print(f'[{__name__}] Trying to create directory {\"/\".join(remote_path)} on remote...') dir_to_create", "json['mimeType']: is_file = False # You don't have pathes in", "response = put_with_OAuth(upload_link, data=files) if 199 < response.status_code < 401:", "'wb').write(file.content) return local_path def main(): storage = GDriveStorage(None) db =", "\" f\"{str(response.status_code)} — {response.json()['message']}\") file = requests.get(dl_url) open(local_path, 'wb').write(file.content) return", "with GD: Response: \" f\"{str(response.status_code)} — {response.json()}\") @classmethod # todo", "exception \"\"\" upload_successful_flag = False response = get_with_OAuth( f'https://cloud-api.yandex.net/v1/disk/resources/upload?path={remote_path}&overwrite=${overwrite}', token=self.token", "remote fs :param _rec_call: bool, a system parameter, whether or", "self._deserialize_resource(response.json()) if 199 < response.status_code < 401: return resource_metainfo elif", "from __future__ import print_function import json from typing import List", "with YD: Response: \" f\"{str(response.status_code)} — {response.json()['message']}\") file = requests.get(dl_url)", "= get_with_OAuth('https://www.googleapis.com/drive/v3/about?fields=*', token=self.token) if response.status_code == 200: response_read = response.json()", "object :param json: :return: \"\"\" try: is_file = True if", "google.oauth2.credentials import Credentials GOOGLE_DRIVE_DB_KEY = 'google' class GDriveStorage(Storage): def __init__(self,", "response.json() try: result = response_as_json['files'][0]['id'] return result except IndexError as", "\"\"\" upload_successful_flag = False response = get_with_OAuth( f'https://cloud-api.yandex.net/v1/disk/resources/upload?path={remote_path}&overwrite=${overwrite}', token=self.token )", "continue elif response.status_code == 409 and 'уже существует' in response.json().get('message',", "= Resource(is_file, path) res.size = Size(json.get('size'), 'b') if json.get('size') else", "= response_read.get('href') else: raise ValueError(f\"[{__name__}] Something went wrong with YD:", "'folder' in json['mimeType']: is_file = False # You don't have", "resource \"\"\" folder_id = self._get_folder_id_by_name(remote_path) response = get_with_OAuth( f\"https://www.googleapis.com/drive/v3/files\", params={", "need to get an ID of the folder This function", "409 and not _rec_call: # We don't need to create", "if res is not None: result.append(res) return result else: raise", "wrong with GD: Response: \" f\"{str(response.status_code)} — {response.json()['message']}\") def create_path(self,", "-> None: \"\"\" Creates the remote path on yandex disk", "None: \"\"\" Tries to parse Resource from YD to Resource", "{\"/\".join(remote_path)} on remote...') dir_to_create = [] for dir in remote_path:", "from functools import lru_cache from cloud_storages.http_shortcuts import * from database.database", "-> Resource or None: \"\"\" Put an Item to the", "self.save_resource_to_path(resource, remote_path, overwrite, _rec_call=True) raise ValueError(f\"Something went wrong with YD:", "str) -> str: \"\"\" Google drive has a quirk -", "token=self.token ) if response.status_code == 200: response_as_json = response.json() try:", "with specified name \"\"\" response = get_with_OAuth( f\"https://www.googleapis.com/drive/v3/files\", params={ 'fields':", "Resource or None = self._deserialize_resource(resource) if res is not None:", "\"\"\" folder_id = self._get_folder_id_by_name(remote_path) response = get_with_OAuth( f\"https://www.googleapis.com/drive/v3/files\", params={ 'fields':", "— {response.json()['message']}\") file = requests.get(dl_url) open(local_path, 'wb').write(file.content) return local_path def", "if not creds or not creds.valid: if creds and creds.expired", "return resource_metainfo elif upload_successful_flag: return resource # This dir is", "to get an ID of the folder This function searches", "path) res.size = Size(json.get('size'), 'b') if json.get('size') else None res.name", "def download_resource(self, remote_path, local_path) -> str: response = get_with_OAuth( f'https://cloud-api.yandex.net/v1/disk/resources/download?path={remote_path}',", "as f: files = f response = put_with_OAuth(upload_link, data=files) if", "This function searches for folders with specified name \"\"\" response", "json.get('size') else None res.name = json.get('name') res.url = json.get('webContentLink') res.updated", "False) -> Resource or None: \"\"\" Put an Item to", "don't need to create a folder with the name equal", "to resource on remote fs :param _rec_call: bool, a system", "None = self._deserialize_resource(resource) if res is not None: result.append(res) return", "local_path def main(): storage = GDriveStorage(None) db = Database('../storage.db') storage.auth(db)", "for dir in remote_path: dir_to_create.append(dir) path_to_create = '/'.join(dir_to_create) response =", "'{name}' and mimeType = 'application/vnd.google-apps.folder'\" }, token=self.token ) if response.status_code", "= response_read.get('storageQuota', {}).get('limit') return StorageMetaInfo(int(used_space), int(total_space)) else: raise ValueError(f\"Something went", "dir_to_create.append(dir) path_to_create = '/'.join(dir_to_create) response = put_with_OAuth(f'https://cloud-api.yandex.net/v1/disk/resources?path={path_to_create}', token=self.token) if 199", "first you need to get an ID of the folder", ":param resource: resource on the local fs :param remote_path: string,", "have an id path = json['id'] except KeyError: return None", "\"\"\" Google drive has a quirk - you can't really", "an ID of the folder This function searches for folders", "'/'.join(dir_to_create) response = put_with_OAuth(f'https://cloud-api.yandex.net/v1/disk/resources?path={path_to_create}', token=self.token) if 199 < response.status_code <", "response_read = response.json() used_space = response_read.get('storageQuota', {}).get('usage') total_space = response_read.get('storageQuota',", "remote_path: str, overwrite: bool, _rec_call:bool = False) -> Resource or", "next call was made as recursive call, so we don't", "from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials GOOGLE_DRIVE_DB_KEY =", "token=self.token ) if response.status_code == 200: response_read = response.json() upload_link", "199 < response.status_code < 401: return resource_metainfo elif upload_successful_flag: return", "except IndexError as e: raise ValueError(f\"Something went wrong with GD:", "\"\"\" response = get_with_OAuth( f\"https://www.googleapis.com/drive/v3/files\", params={ 'fields': '*', 'q': f\"name", "f response = put_with_OAuth(upload_link, data=files) if 199 < response.status_code <", "resource: resource on the local fs :param remote_path: string, path", "\" f\"{str(response.status_code)} — {response.json().get('message', '')}\") def download_resource(self, remote_path, local_path) ->", "\" f\"{str(response.status_code)} — {response.json()['message']}\") def get_meta_info(self) -> StorageMetaInfo: response =", "upload_successful_flag: return resource # This dir is not present in", "\"\"\" Creates the remote path on yandex disk \"\"\" print(f'[{__name__}]", "''): continue return def save_resource_to_path(self, resource: Resource, remote_path: str, overwrite:", "result = [] response_as_json = response.json() files = response_as_json['files'] for", "== 409 and 'уже существует' in response.json().get('message', ''): continue return", "folders with specified name \"\"\" response = get_with_OAuth( f\"https://www.googleapis.com/drive/v3/files\", params={", "= response.json() files = response_as_json['files'] for resource in files: res:", "= get_with_OAuth( f'https://cloud-api.yandex.net/v1/disk/resources/upload?path={remote_path}&overwrite=${overwrite}', token=self.token ) if response.status_code == 200: response_read", "get an ID of the folder This function searches for", "= json.get('modifiedTime') res.md5 = json.get('md5Checksum') return res def list_resources_on_path(self, remote_path:", "Credentials GOOGLE_DRIVE_DB_KEY = 'google' class GDriveStorage(Storage): def __init__(self, token): self.token", ") if response.status_code == 200: response_as_json = response.json() try: result", "GDriveStorage(json.loads(db.get(GOOGLE_DRIVE_DB_KEY))['token']) result = authed_storage.list_resources_on_path('savezone') print(result) if __name__ == '__main__': main()", "creds_from_db: creds = Credentials.from_authorized_user_info(json.loads(creds_from_db), SCOPES) if not creds or not", "{response.json()}\") @classmethod # todo (toplenboren) remove database argument dependency :(", "storage = GDriveStorage(None) db = Database('../storage.db') storage.auth(db) authed_storage = GDriveStorage(json.loads(db.get(GOOGLE_DRIVE_DB_KEY))['token'])", "tell that the next call was made as recursive call,", "{response.json()['message']}\") def get_meta_info(self) -> StorageMetaInfo: response = get_with_OAuth('https://www.googleapis.com/drive/v3/about?fields=*', token=self.token) if", "remote path on yandex disk \"\"\" print(f'[{__name__}] Trying to create", "'')}\") def download_resource(self, remote_path, local_path) -> str: response = get_with_OAuth(", "= get_with_OAuth(f'https://cloud-api.yandex.net/v1/disk/resources?path={remote_path}', token=self.token) resource_metainfo = self._deserialize_resource(response.json()) if 199 < response.status_code", "overwrite: bool, _rec_call:bool = False) -> Resource or None: \"\"\"", "Resource(is_file, path) res.size = Size(json.get('size'), 'b') if json.get('size') else None", "params={ 'fields': '*', 'q': f\"'{folder_id}' in parents\" }, token=self.token )", "GD: Response: \" f\"{str(response.status_code)} — {response.json()['message']}\") def create_path(self, remote_path: List[str])", "that the next call was made as recursive call, so", "Resource from YD to Resource object :param json: :return: \"\"\"", "resource on the local fs :param remote_path: string, path to", "wrong with YD: Response: \" f\"{str(response.status_code)} — {response.json().get('message', '')}\") def", "creds_from_db = db.get(GOOGLE_DRIVE_DB_KEY) if creds_from_db: creds = Credentials.from_authorized_user_info(json.loads(creds_from_db), SCOPES) if", "'google' class GDriveStorage(Storage): def __init__(self, token): self.token = token @lru_cache(maxsize=None)", "in parents\" }, token=self.token ) if response.status_code == 200: result", "upload_successful_flag = True response = get_with_OAuth(f'https://cloud-api.yandex.net/v1/disk/resources?path={remote_path}', token=self.token) resource_metainfo = self._deserialize_resource(response.json())", "whether or not this function was called as a recursive", "local fs :param remote_path: string, path to resource on remote", "raise ValueError(f\"[{__name__}] Something went wrong with YD: Response: \" f\"{str(response.status_code)}", "import Request from google.oauth2.credentials import Credentials GOOGLE_DRIVE_DB_KEY = 'google' class", "in files: res: Resource or None = self._deserialize_resource(resource) if res", "response.status_code == 409 and not _rec_call: # We don't need", "import json from typing import List from functools import lru_cache", "response.json() used_space = response_read.get('storageQuota', {}).get('usage') total_space = response_read.get('storageQuota', {}).get('limit') return", "creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow", "= Database('../storage.db') storage.auth(db) authed_storage = GDriveStorage(json.loads(db.get(GOOGLE_DRIVE_DB_KEY))['token']) result = authed_storage.list_resources_on_path('savezone') print(result)", "200: result = [] response_as_json = response.json() files = response_as_json['files']", "has a quirk - you can't really use normal os-like", "response.json() files = response_as_json['files'] for resource in files: res: Resource", "ID of the folder This function searches for folders with", "'*', 'q': f\"'{folder_id}' in parents\" }, token=self.token ) if response.status_code", "Credentials.from_authorized_user_info(json.loads(creds_from_db), SCOPES) if not creds or not creds.valid: if creds", "raise ValueError(f\"Something went wrong with YD: Response: \" f\"{str(response.status_code)} —", "get_with_OAuth('https://www.googleapis.com/drive/v3/about?fields=*', token=self.token) if response.status_code == 200: response_read = response.json() used_space", "db = Database('../storage.db') storage.auth(db) authed_storage = GDriveStorage(json.loads(db.get(GOOGLE_DRIVE_DB_KEY))['token']) result = authed_storage.list_resources_on_path('savezone')", "resource in files: res: Resource or None = self._deserialize_resource(resource) if", "pathes in google drive, instead -- you have an id", "to parse Resource from YD to Resource object :param json:", "return None res = Resource(is_file, path) res.size = Size(json.get('size'), 'b')", "drive has a quirk - you can't really use normal", "do [:-1] self.create_path(remote_path.split('/')[:-1]) return self.save_resource_to_path(resource, remote_path, overwrite, _rec_call=True) raise ValueError(f\"Something", "remote...') dir_to_create = [] for dir in remote_path: dir_to_create.append(dir) path_to_create", "if 'folder' in json['mimeType']: is_file = False # You don't", "json['id'] except KeyError: return None res = Resource(is_file, path) res.size", "Resource, Size from cloud_storages.storage import Storage from cloud_storages.gdrive.client_config import GOOGLE_DRIVE_CONFIG,", "the folder This function searches for folders with specified name", "None: \"\"\" Creates the remote path on yandex disk \"\"\"", "= f response = put_with_OAuth(upload_link, data=files) if 199 < response.status_code", "_rec_call:bool = False) -> Resource or None: \"\"\" Put an", "creds.token) @classmethod def _deserialize_resource(cls, json: dict) -> Resource or None:", "@classmethod def _deserialize_resource(cls, json: dict) -> Resource or None: \"\"\"", "ValueError(f\"Something went wrong with YD: Response: \" f\"{str(response.status_code)} — {response.json()['message']}\")", "response.status_code == 200: response_read = response.json() upload_link = response_read['href'] with", "{path_to_create}') continue elif response.status_code == 409 and 'уже существует' in", "from models.models import StorageMetaInfo, Resource, Size from cloud_storages.storage import Storage", "SCOPES) if not creds or not creds.valid: if creds and", "-> Resource or None: \"\"\" Tries to parse Resource from", "= json.get('webContentLink') res.updated = json.get('modifiedTime') res.md5 = json.get('md5Checksum') return res", "f\"name = '{name}' and mimeType = 'application/vnd.google-apps.folder'\" }, token=self.token )", "import Storage from cloud_storages.gdrive.client_config import GOOGLE_DRIVE_CONFIG, SCOPES from google_auth_oauthlib.flow import", "get_with_OAuth( f'https://cloud-api.yandex.net/v1/disk/resources/upload?path={remote_path}&overwrite=${overwrite}', token=self.token ) if response.status_code == 200: response_read =", "need to create a folder with the name equal to", "_get_folder_id_by_name(self, name: str) -> str: \"\"\" Google drive has a", "not present in the storage # We use _rec_call to", "'уже существует' in response.json().get('message', ''): continue return def save_resource_to_path(self, resource:", "a system parameter, whether or not this function was called", "searches for folders with specified name \"\"\" response = get_with_OAuth(", "= True response = get_with_OAuth(f'https://cloud-api.yandex.net/v1/disk/resources?path={remote_path}', token=self.token) resource_metainfo = self._deserialize_resource(response.json()) if", "called as a recursive call :return: saved resource or raises", "db.get(GOOGLE_DRIVE_DB_KEY) if creds_from_db: creds = Credentials.from_authorized_user_info(json.loads(creds_from_db), SCOPES) if not creds", "upload_successful_flag = False response = get_with_OAuth( f'https://cloud-api.yandex.net/v1/disk/resources/upload?path={remote_path}&overwrite=${overwrite}', token=self.token ) if", "response.status_code == 200: response_read = response.json() dl_url = response_read.get('href') else:", "with GD: Response: \" f\"{str(response.status_code)} — {response.json()['message']}\") def create_path(self, remote_path:", "or None: \"\"\" Put an Item to the directory :param", "InstalledAppFlow from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials GOOGLE_DRIVE_DB_KEY", "ValueError(f\"Something went wrong with GD: Response: \" f\"{str(response.status_code)} — {response.json()['message']}\")", ") if response.status_code == 200: response_read = response.json() dl_url =", "bool, _rec_call:bool = False) -> Resource or None: \"\"\" Put", "Response: \" f\"{str(response.status_code)} — {response.json()['message']}\") file = requests.get(dl_url) open(local_path, 'wb').write(file.content)", ":( def auth(cls, db: Database): creds = None creds_from_db =", "as recursive call, so we don't cause SO elif response.status_code", "response.json() upload_link = response_read['href'] with open(resource.path, 'rb') as f: files", "went wrong with YD: Response: \" f\"{str(response.status_code)} — {response.json().get('message', '')}\")", "res def list_resources_on_path(self, remote_path: str) -> List[Resource]: \"\"\" List all", "import * from database.database import Database from models.models import StorageMetaInfo,", "went wrong with GD: Response: \" f\"{str(response.status_code)} — {response.json()['message']}\") def", "data=files) if 199 < response.status_code < 401: upload_successful_flag = True", "result except IndexError as e: raise ValueError(f\"Something went wrong with", "to Resource object :param json: :return: \"\"\" try: is_file =", "open(resource.path, 'rb') as f: files = f response = put_with_OAuth(upload_link,", "SO elif response.status_code == 409 and not _rec_call: # We", "res = Resource(is_file, path) res.size = Size(json.get('size'), 'b') if json.get('size')", "folder_id = self._get_folder_id_by_name(remote_path) response = get_with_OAuth( f\"https://www.googleapis.com/drive/v3/files\", params={ 'fields': '*',", "-> str: \"\"\" Google drive has a quirk - you", "return local_path def main(): storage = GDriveStorage(None) db = Database('../storage.db')", "params={ 'fields': '*', 'q': f\"name = '{name}' and mimeType =", "a recursive call :return: saved resource or raises exception \"\"\"", "flow = InstalledAppFlow.from_client_config(GOOGLE_DRIVE_CONFIG, SCOPES) creds = flow.run_local_server(port=0) db.set(GOOGLE_DRIVE_DB_KEY, creds.token) @classmethod", "List[str]) -> None: \"\"\" Creates the remote path on yandex", "fs :param _rec_call: bool, a system parameter, whether or not", "of the folder This function searches for folders with specified", "InstalledAppFlow.from_client_config(GOOGLE_DRIVE_CONFIG, SCOPES) creds = flow.run_local_server(port=0) db.set(GOOGLE_DRIVE_DB_KEY, creds.token) @classmethod def _deserialize_resource(cls,", "{response.json().get('message', '')}\") def download_resource(self, remote_path, local_path) -> str: response =", "drive, instead -- you have an id path = json['id']", "Created directory {path_to_create}') continue elif response.status_code == 409 and 'уже", "remote_path, overwrite, _rec_call=True) raise ValueError(f\"Something went wrong with YD: Response:", "the remote path on yandex disk \"\"\" print(f'[{__name__}] Trying to", "Database from models.models import StorageMetaInfo, Resource, Size from cloud_storages.storage import", "Item to the directory :param resource: resource on the local", "import lru_cache from cloud_storages.http_shortcuts import * from database.database import Database", "if json.get('size') else None res.name = json.get('name') res.url = json.get('webContentLink')", "Creates the remote path on yandex disk \"\"\" print(f'[{__name__}] Trying", "if response.status_code == 200: response_read = response.json() used_space = response_read.get('storageQuota',", "normal os-like paths - first you need to get an", "for resource in files: res: Resource or None = self._deserialize_resource(resource)", "ValueError(f\"Something went wrong with GD: Response: \" f\"{str(response.status_code)} — {response.json()}\")", "directory :param resource: resource on the local fs :param remote_path:", "from cloud_storages.storage import Storage from cloud_storages.gdrive.client_config import GOOGLE_DRIVE_CONFIG, SCOPES from", "List from functools import lru_cache from cloud_storages.http_shortcuts import * from", "went wrong with GD: Error: {e}\") else: raise ValueError(f\"Something went", "Response: \" f\"{str(response.status_code)} — {response.json()['message']}\") def create_path(self, remote_path: List[str]) ->", "response_read = response.json() dl_url = response_read.get('href') else: raise ValueError(f\"[{__name__}] Something", "GD: Response: \" f\"{str(response.status_code)} — {response.json()}\") @classmethod # todo (toplenboren)", "import print_function import json from typing import List from functools", "response = put_with_OAuth(f'https://cloud-api.yandex.net/v1/disk/resources?path={path_to_create}', token=self.token) if 199 < response.status_code < 401:", "200: response_read = response.json() used_space = response_read.get('storageQuota', {}).get('usage') total_space =", "return res def list_resources_on_path(self, remote_path: str) -> List[Resource]: \"\"\" List", "and 'уже существует' in response.json().get('message', ''): continue return def save_resource_to_path(self,", "= get_with_OAuth( f'https://cloud-api.yandex.net/v1/disk/resources/download?path={remote_path}', token=self.token ) if response.status_code == 200: response_read", "wrong with GD: Response: \" f\"{str(response.status_code)} — {response.json()}\") @classmethod #", "disk \"\"\" print(f'[{__name__}] Trying to create directory {\"/\".join(remote_path)} on remote...')", "db: Database): creds = None creds_from_db = db.get(GOOGLE_DRIVE_DB_KEY) if creds_from_db:", "= response.json() try: result = response_as_json['files'][0]['id'] return result except IndexError", "= response_as_json['files'][0]['id'] return result except IndexError as e: raise ValueError(f\"Something", "name: str) -> str: \"\"\" Google drive has a quirk", "quirk - you can't really use normal os-like paths -", "and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_config(GOOGLE_DRIVE_CONFIG, SCOPES) creds =", "path: path to the resource \"\"\" folder_id = self._get_folder_id_by_name(remote_path) response", "requests.get(dl_url) open(local_path, 'wb').write(file.content) return local_path def main(): storage = GDriveStorage(None)", "YD: Response: \" f\"{str(response.status_code)} — {response.json().get('message', '')}\") def download_resource(self, remote_path,", "= Credentials.from_authorized_user_info(json.loads(creds_from_db), SCOPES) if not creds or not creds.valid: if", "we don't cause SO elif response.status_code == 409 and not", "SCOPES from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request from", "== 200: response_read = response.json() used_space = response_read.get('storageQuota', {}).get('usage') total_space", "GOOGLE_DRIVE_CONFIG, SCOPES from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request", "This dir is not present in the storage # We", "= flow.run_local_server(port=0) db.set(GOOGLE_DRIVE_DB_KEY, creds.token) @classmethod def _deserialize_resource(cls, json: dict) ->", "from cloud_storages.http_shortcuts import * from database.database import Database from models.models", "remote_path: str) -> List[Resource]: \"\"\" List all items in directory", "= response_read.get('storageQuota', {}).get('usage') total_space = response_read.get('storageQuota', {}).get('limit') return StorageMetaInfo(int(used_space), int(total_space))", "a folder with the name equal to the filename, so", "for folders with specified name \"\"\" response = get_with_OAuth( f\"https://www.googleapis.com/drive/v3/files\",", "_rec_call to tell that the next call was made as", "dir_to_create = [] for dir in remote_path: dir_to_create.append(dir) path_to_create =", "resource_metainfo = self._deserialize_resource(response.json()) if 199 < response.status_code < 401: return", "the directory :param resource: resource on the local fs :param", "= response_read['href'] with open(resource.path, 'rb') as f: files = f", "GDriveStorage(Storage): def __init__(self, token): self.token = token @lru_cache(maxsize=None) def _get_folder_id_by_name(self,", "Error: {e}\") else: raise ValueError(f\"Something went wrong with GD: Response:", "token=self.token ) if response.status_code == 200: result = [] response_as_json", "Put an Item to the directory :param resource: resource on", "as a recursive call :return: saved resource or raises exception", "parameter, whether or not this function was called as a", "main(): storage = GDriveStorage(None) db = Database('../storage.db') storage.auth(db) authed_storage =", "from cloud_storages.gdrive.client_config import GOOGLE_DRIVE_CONFIG, SCOPES from google_auth_oauthlib.flow import InstalledAppFlow from", "= response_as_json['files'] for resource in files: res: Resource or None", "don't have pathes in google drive, instead -- you have", "Trying to create directory {\"/\".join(remote_path)} on remote...') dir_to_create = []", "else None res.name = json.get('name') res.url = json.get('webContentLink') res.updated =", "= get_with_OAuth( f\"https://www.googleapis.com/drive/v3/files\", params={ 'fields': '*', 'q': f\"name = '{name}'", "= response.json() dl_url = response_read.get('href') else: raise ValueError(f\"[{__name__}] Something went", "{}).get('limit') return StorageMetaInfo(int(used_space), int(total_space)) else: raise ValueError(f\"Something went wrong with", "remove database argument dependency :( def auth(cls, db: Database): creds", "is_file = True if 'folder' in json['mimeType']: is_file = False", "path to resource on remote fs :param _rec_call: bool, a", "response_read.get('storageQuota', {}).get('limit') return StorageMetaInfo(int(used_space), int(total_space)) else: raise ValueError(f\"Something went wrong", "as e: raise ValueError(f\"Something went wrong with GD: Error: {e}\")", "List[Resource]: \"\"\" List all items in directory :param path: path", "< 401: print(f'[{__name__}] Created directory {path_to_create}') continue elif response.status_code ==", "remote_path: List[str]) -> None: \"\"\" Creates the remote path on", "on yandex disk \"\"\" print(f'[{__name__}] Trying to create directory {\"/\".join(remote_path)}", "True if 'folder' in json['mimeType']: is_file = False # You", "}, token=self.token ) if response.status_code == 200: result = []", "storage # We use _rec_call to tell that the next", "instead -- you have an id path = json['id'] except", "from YD to Resource object :param json: :return: \"\"\" try:", "Google drive has a quirk - you can't really use", "google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request from google.oauth2.credentials import", "is_file = False # You don't have pathes in google" ]
[ "name=\"logged_count\"), re_path(r'^loggedusers/', views.logged, name=\"logged_users\"), re_path(r'^settings/', views.user_settings, name=\"update_info\"), re_path(r'^administrators/', views.post_alert, name=\"post_alert\"),", "url mappings for the webapp. urlpatterns = [ re_path(r'^$', views.logged_count,", "name=\"list_alert\"), re_path(r'^alerts/(?P<slug>[\\w-]+)/$', views.view_alert, name=\"view_alert\"), re_path(r'^display/', views.display, name=\"display\"), re_path(r'^doorselection/', views.doors_election, name=\"door_selecttion\")", "<gh_stars>1-10 from django.urls import re_path, include from . import views", "views app_name='logged' # url mappings for the webapp. urlpatterns =", "urlpatterns = [ re_path(r'^$', views.logged_count, name=\"logged_count\"), re_path(r'^loggedusers/', views.logged, name=\"logged_users\"), re_path(r'^settings/',", "re_path(r'^settings/', views.user_settings, name=\"update_info\"), re_path(r'^administrators/', views.post_alert, name=\"post_alert\"), re_path(r'^alerts/$', views.list_alert, name=\"list_alert\"), re_path(r'^alerts/(?P<slug>[\\w-]+)/$',", "re_path(r'^alerts/(?P<slug>[\\w-]+)/$', views.view_alert, name=\"view_alert\"), re_path(r'^display/', views.display, name=\"display\"), re_path(r'^doorselection/', views.doors_election, name=\"door_selecttion\") ]", "the webapp. urlpatterns = [ re_path(r'^$', views.logged_count, name=\"logged_count\"), re_path(r'^loggedusers/', views.logged,", "re_path(r'^loggedusers/', views.logged, name=\"logged_users\"), re_path(r'^settings/', views.user_settings, name=\"update_info\"), re_path(r'^administrators/', views.post_alert, name=\"post_alert\"), re_path(r'^alerts/$',", "name=\"post_alert\"), re_path(r'^alerts/$', views.list_alert, name=\"list_alert\"), re_path(r'^alerts/(?P<slug>[\\w-]+)/$', views.view_alert, name=\"view_alert\"), re_path(r'^display/', views.display, name=\"display\"),", ". import views app_name='logged' # url mappings for the webapp.", "views.list_alert, name=\"list_alert\"), re_path(r'^alerts/(?P<slug>[\\w-]+)/$', views.view_alert, name=\"view_alert\"), re_path(r'^display/', views.display, name=\"display\"), re_path(r'^doorselection/', views.doors_election,", "views.logged_count, name=\"logged_count\"), re_path(r'^loggedusers/', views.logged, name=\"logged_users\"), re_path(r'^settings/', views.user_settings, name=\"update_info\"), re_path(r'^administrators/', views.post_alert,", "name=\"update_info\"), re_path(r'^administrators/', views.post_alert, name=\"post_alert\"), re_path(r'^alerts/$', views.list_alert, name=\"list_alert\"), re_path(r'^alerts/(?P<slug>[\\w-]+)/$', views.view_alert, name=\"view_alert\"),", "# url mappings for the webapp. urlpatterns = [ re_path(r'^$',", "views.logged, name=\"logged_users\"), re_path(r'^settings/', views.user_settings, name=\"update_info\"), re_path(r'^administrators/', views.post_alert, name=\"post_alert\"), re_path(r'^alerts/$', views.list_alert,", "from . import views app_name='logged' # url mappings for the", "webapp. urlpatterns = [ re_path(r'^$', views.logged_count, name=\"logged_count\"), re_path(r'^loggedusers/', views.logged, name=\"logged_users\"),", "include from . import views app_name='logged' # url mappings for", "mappings for the webapp. urlpatterns = [ re_path(r'^$', views.logged_count, name=\"logged_count\"),", "= [ re_path(r'^$', views.logged_count, name=\"logged_count\"), re_path(r'^loggedusers/', views.logged, name=\"logged_users\"), re_path(r'^settings/', views.user_settings,", "re_path(r'^administrators/', views.post_alert, name=\"post_alert\"), re_path(r'^alerts/$', views.list_alert, name=\"list_alert\"), re_path(r'^alerts/(?P<slug>[\\w-]+)/$', views.view_alert, name=\"view_alert\"), re_path(r'^display/',", "views.post_alert, name=\"post_alert\"), re_path(r'^alerts/$', views.list_alert, name=\"list_alert\"), re_path(r'^alerts/(?P<slug>[\\w-]+)/$', views.view_alert, name=\"view_alert\"), re_path(r'^display/', views.display,", "[ re_path(r'^$', views.logged_count, name=\"logged_count\"), re_path(r'^loggedusers/', views.logged, name=\"logged_users\"), re_path(r'^settings/', views.user_settings, name=\"update_info\"),", "re_path, include from . import views app_name='logged' # url mappings", "from django.urls import re_path, include from . import views app_name='logged'", "for the webapp. urlpatterns = [ re_path(r'^$', views.logged_count, name=\"logged_count\"), re_path(r'^loggedusers/',", "re_path(r'^alerts/$', views.list_alert, name=\"list_alert\"), re_path(r'^alerts/(?P<slug>[\\w-]+)/$', views.view_alert, name=\"view_alert\"), re_path(r'^display/', views.display, name=\"display\"), re_path(r'^doorselection/',", "views.user_settings, name=\"update_info\"), re_path(r'^administrators/', views.post_alert, name=\"post_alert\"), re_path(r'^alerts/$', views.list_alert, name=\"list_alert\"), re_path(r'^alerts/(?P<slug>[\\w-]+)/$', views.view_alert,", "app_name='logged' # url mappings for the webapp. urlpatterns = [", "re_path(r'^$', views.logged_count, name=\"logged_count\"), re_path(r'^loggedusers/', views.logged, name=\"logged_users\"), re_path(r'^settings/', views.user_settings, name=\"update_info\"), re_path(r'^administrators/',", "import views app_name='logged' # url mappings for the webapp. urlpatterns", "import re_path, include from . import views app_name='logged' # url", "django.urls import re_path, include from . import views app_name='logged' #", "name=\"logged_users\"), re_path(r'^settings/', views.user_settings, name=\"update_info\"), re_path(r'^administrators/', views.post_alert, name=\"post_alert\"), re_path(r'^alerts/$', views.list_alert, name=\"list_alert\")," ]
[ "spot[0]) return spot def _filter_spot_items(item_id, spot): for item in spot.items:", "= _get_extended_info_by_key( \"i_is_stf\", item.extended_info ) item.cte_type_id = _get_extended_info_by_key( \"cte_type_id\", item.extended_info", "_get_extended_info_by_key(\"i_brand\", item.extended_info) item.checkout_period = _get_extended_info_by_key( \"i_checkout_period\", item.extended_info ) item.reservation_notes =", "item in spot.items: item.model = _get_extended_info_by_key(\"i_model\", item.extended_info) item.brand = _get_extended_info_by_key(\"i_brand\",", "if item.item_id == item_id: spot.item = item return spot def", "= copy.deepcopy(spot) new_spot.items = [] for item in spot.items: if", "\"i_description\", item.extended_info ) item.reserve_url = _get_extended_info_by_key( \"i_reserve_url\", item.extended_info ) item.manual_url", "= _get_extended_info_by_key( \"i_reservation_notes\", item.extended_info ) item.is_active = _get_extended_info_by_key( \"i_is_active\", item.extended_info", "0 and item.subcategory not in subcategory: continue if len(brand) >", "if len(brand) > 0 and item.brand not in brand: continue", "item.is_stf = _get_extended_info_by_key( \"i_is_stf\", item.extended_info ) item.cte_type_id = _get_extended_info_by_key( \"cte_type_id\",", "item.is_active: continue if len(subcategory) > 0 and item.subcategory not in", "2021 UW-IT, University of Washington # SPDX-License-Identifier: Apache-2.0 from scout.dao.space", ") item.description = _get_extended_info_by_key( \"i_description\", item.extended_info ) item.reserve_url = _get_extended_info_by_key(", ") return spot def get_filtered_items(spots, request): parameter_list = _get_spot_filters(request) brand", "_get_extended_info_by_key( \"i_checkout_period\", item.extended_info ) item.reservation_notes = _get_extended_info_by_key( \"i_reservation_notes\", item.extended_info )", "new_spot.items = [] for item in spot.items: if is_active and", "brand.append(param[1]) elif param[0] == \"item:subcategory\": subcategory.append(param[1]) elif param[0] == \"item:extended_info:i_is_active\":", "of Washington # SPDX-License-Identifier: Apache-2.0 from scout.dao.space import get_spots_by_filter, _get_spot_filters,", "return new_spots def get_item_count(spots): item_count = 0 for spot in", "= item return spot def add_item_info(spot): for item in spot.items:", "= _get_extended_info_by_key( \"i_quantity\", item.extended_info ) item.description = _get_extended_info_by_key( \"i_description\", item.extended_info", "\"i_is_active\", item.extended_info ) item.quantity = _get_extended_info_by_key( \"i_quantity\", item.extended_info ) item.description", "[] for item in spot.items: if is_active and not item.is_active:", "\"i_is_stf\", item.extended_info ) item.cte_type_id = _get_extended_info_by_key( \"cte_type_id\", item.extended_info ) return", "_get_extended_info_by_key( \"i_description\", item.extended_info ) item.reserve_url = _get_extended_info_by_key( \"i_reserve_url\", item.extended_info )", "is_active and not item.is_active: continue if len(subcategory) > 0 and", "spot def _filter_spot_items(item_id, spot): for item in spot.items: if item.item_id", "for item in spot.items: item.model = _get_extended_info_by_key(\"i_model\", item.extended_info) item.brand =", "= _get_extended_info_by_key( \"i_description\", item.extended_info ) item.reserve_url = _get_extended_info_by_key( \"i_reserve_url\", item.extended_info", "continue new_spot.items.append(item) new_spots.append(new_spot) return new_spots def get_item_count(spots): item_count = 0", "elif param[0] == \"item:extended_info:i_is_active\": is_active = True new_spots = []", "spot def get_filtered_items(spots, request): parameter_list = _get_spot_filters(request) brand = []", "item.description = _get_extended_info_by_key( \"i_description\", item.extended_info ) item.reserve_url = _get_extended_info_by_key( \"i_reserve_url\",", "_get_spot_filters, \\ _get_extended_info_by_key import copy def get_item_by_id(item_id): spot = get_spots_by_filter([", "return spot def add_item_info(spot): for item in spot.items: item.model =", "in parameter_list: if param[0] == \"item:extended_info:i_brand\": brand.append(param[1]) elif param[0] ==", "= 0 for spot in spots: item_count += len(spot.items) return", "= [] for spot in spots: new_spot = copy.deepcopy(spot) new_spot.items", "and item.brand not in brand: continue new_spot.items.append(item) new_spots.append(new_spot) return new_spots", "import get_spots_by_filter, _get_spot_filters, \\ _get_extended_info_by_key import copy def get_item_by_id(item_id): spot", "[] subcategory = [] is_active = False for param in", "and item.subcategory not in subcategory: continue if len(brand) > 0", "SPDX-License-Identifier: Apache-2.0 from scout.dao.space import get_spots_by_filter, _get_spot_filters, \\ _get_extended_info_by_key import", "in spot.items: item.model = _get_extended_info_by_key(\"i_model\", item.extended_info) item.brand = _get_extended_info_by_key(\"i_brand\", item.extended_info)", "for item in spot.items: if is_active and not item.is_active: continue", "for spot in spots: new_spot = copy.deepcopy(spot) new_spot.items = []", "UW-IT, University of Washington # SPDX-License-Identifier: Apache-2.0 from scout.dao.space import", "= _get_extended_info_by_key( \"i_checkout_period\", item.extended_info ) item.reservation_notes = _get_extended_info_by_key( \"i_reservation_notes\", item.extended_info", "get_filtered_items(spots, request): parameter_list = _get_spot_filters(request) brand = [] subcategory =", "param in parameter_list: if param[0] == \"item:extended_info:i_brand\": brand.append(param[1]) elif param[0]", "== \"item:extended_info:i_brand\": brand.append(param[1]) elif param[0] == \"item:subcategory\": subcategory.append(param[1]) elif param[0]", "\"item:extended_info:i_is_active\": is_active = True new_spots = [] for spot in", "= _get_extended_info_by_key(\"i_model\", item.extended_info) item.brand = _get_extended_info_by_key(\"i_brand\", item.extended_info) item.checkout_period = _get_extended_info_by_key(", "0 for spot in spots: item_count += len(spot.items) return item_count", "in spot.items: if item.item_id == item_id: spot.item = item return", "[] for spot in spots: new_spot = copy.deepcopy(spot) new_spot.items =", "in spots: new_spot = copy.deepcopy(spot) new_spot.items = [] for item", "= _filter_spot_items(item_id, spot[0]) return spot def _filter_spot_items(item_id, spot): for item", "parameter_list = _get_spot_filters(request) brand = [] subcategory = [] is_active", "get_item_count(spots): item_count = 0 for spot in spots: item_count +=", "\"i_checkout_period\", item.extended_info ) item.reservation_notes = _get_extended_info_by_key( \"i_reservation_notes\", item.extended_info ) item.is_active", "_filter_spot_items(item_id, spot[0]) return spot def _filter_spot_items(item_id, spot): for item in", "<filename>scout/dao/item.py<gh_stars>1-10 # Copyright 2021 UW-IT, University of Washington # SPDX-License-Identifier:", "Apache-2.0 from scout.dao.space import get_spots_by_filter, _get_spot_filters, \\ _get_extended_info_by_key import copy", "= _get_extended_info_by_key( \"i_reserve_url\", item.extended_info ) item.manual_url = _get_extended_info_by_key( \"i_manual_url\", item.extended_info", "_get_extended_info_by_key import copy def get_item_by_id(item_id): spot = get_spots_by_filter([ ('item:id', item_id),", "item.extended_info ) item.is_active = _get_extended_info_by_key( \"i_is_active\", item.extended_info ) item.quantity =", "from scout.dao.space import get_spots_by_filter, _get_spot_filters, \\ _get_extended_info_by_key import copy def", "_get_extended_info_by_key( \"i_is_active\", item.extended_info ) item.quantity = _get_extended_info_by_key( \"i_quantity\", item.extended_info )", "_get_extended_info_by_key( \"i_is_stf\", item.extended_info ) item.cte_type_id = _get_extended_info_by_key( \"cte_type_id\", item.extended_info )", "copy def get_item_by_id(item_id): spot = get_spots_by_filter([ ('item:id', item_id), ('extended_info:app_type', 'tech')", "= True new_spots = [] for spot in spots: new_spot", "Washington # SPDX-License-Identifier: Apache-2.0 from scout.dao.space import get_spots_by_filter, _get_spot_filters, \\", "request): parameter_list = _get_spot_filters(request) brand = [] subcategory = []", "item.extended_info ) item.manual_url = _get_extended_info_by_key( \"i_manual_url\", item.extended_info ) item.owner =", "\"i_manual_url\", item.extended_info ) item.owner = _get_extended_info_by_key( \"i_owner\", item.extended_info ) item.is_stf", "in brand: continue new_spot.items.append(item) new_spots.append(new_spot) return new_spots def get_item_count(spots): item_count", "subcategory: continue if len(brand) > 0 and item.brand not in", "new_spots.append(new_spot) return new_spots def get_item_count(spots): item_count = 0 for spot", "= [] subcategory = [] is_active = False for param", "for item in spot.items: if item.item_id == item_id: spot.item =", "import copy def get_item_by_id(item_id): spot = get_spots_by_filter([ ('item:id', item_id), ('extended_info:app_type',", "scout.dao.space import get_spots_by_filter, _get_spot_filters, \\ _get_extended_info_by_key import copy def get_item_by_id(item_id):", "get_spots_by_filter([ ('item:id', item_id), ('extended_info:app_type', 'tech') ]) if spot: spot =", "spot in spots: new_spot = copy.deepcopy(spot) new_spot.items = [] for", "get_item_by_id(item_id): spot = get_spots_by_filter([ ('item:id', item_id), ('extended_info:app_type', 'tech') ]) if", "\"i_reserve_url\", item.extended_info ) item.manual_url = _get_extended_info_by_key( \"i_manual_url\", item.extended_info ) item.owner", "== \"item:subcategory\": subcategory.append(param[1]) elif param[0] == \"item:extended_info:i_is_active\": is_active = True", "add_item_info(spot): for item in spot.items: item.model = _get_extended_info_by_key(\"i_model\", item.extended_info) item.brand", ") item.owner = _get_extended_info_by_key( \"i_owner\", item.extended_info ) item.is_stf = _get_extended_info_by_key(", "item_id), ('extended_info:app_type', 'tech') ]) if spot: spot = _filter_spot_items(item_id, spot[0])", "]) if spot: spot = _filter_spot_items(item_id, spot[0]) return spot def", "len(subcategory) > 0 and item.subcategory not in subcategory: continue if", "item.extended_info ) item.description = _get_extended_info_by_key( \"i_description\", item.extended_info ) item.reserve_url =", "get_spots_by_filter, _get_spot_filters, \\ _get_extended_info_by_key import copy def get_item_by_id(item_id): spot =", "False for param in parameter_list: if param[0] == \"item:extended_info:i_brand\": brand.append(param[1])", "item.brand not in brand: continue new_spot.items.append(item) new_spots.append(new_spot) return new_spots def", "\"i_quantity\", item.extended_info ) item.description = _get_extended_info_by_key( \"i_description\", item.extended_info ) item.reserve_url", "if is_active and not item.is_active: continue if len(subcategory) > 0", "= _get_spot_filters(request) brand = [] subcategory = [] is_active =", "_get_extended_info_by_key( \"i_reservation_notes\", item.extended_info ) item.is_active = _get_extended_info_by_key( \"i_is_active\", item.extended_info )", "_get_extended_info_by_key( \"i_quantity\", item.extended_info ) item.description = _get_extended_info_by_key( \"i_description\", item.extended_info )", "item.extended_info ) item.is_stf = _get_extended_info_by_key( \"i_is_stf\", item.extended_info ) item.cte_type_id =", "new_spots def get_item_count(spots): item_count = 0 for spot in spots:", "if spot: spot = _filter_spot_items(item_id, spot[0]) return spot def _filter_spot_items(item_id,", "item in spot.items: if item.item_id == item_id: spot.item = item", "param[0] == \"item:extended_info:i_is_active\": is_active = True new_spots = [] for", "not item.is_active: continue if len(subcategory) > 0 and item.subcategory not", "\"item:extended_info:i_brand\": brand.append(param[1]) elif param[0] == \"item:subcategory\": subcategory.append(param[1]) elif param[0] ==", "is_active = True new_spots = [] for spot in spots:", "item.checkout_period = _get_extended_info_by_key( \"i_checkout_period\", item.extended_info ) item.reservation_notes = _get_extended_info_by_key( \"i_reservation_notes\",", "subcategory = [] is_active = False for param in parameter_list:", "_get_extended_info_by_key( \"i_reserve_url\", item.extended_info ) item.manual_url = _get_extended_info_by_key( \"i_manual_url\", item.extended_info )", "item.brand = _get_extended_info_by_key(\"i_brand\", item.extended_info) item.checkout_period = _get_extended_info_by_key( \"i_checkout_period\", item.extended_info )", "item return spot def add_item_info(spot): for item in spot.items: item.model", "= _get_extended_info_by_key( \"i_is_active\", item.extended_info ) item.quantity = _get_extended_info_by_key( \"i_quantity\", item.extended_info", "is_active = False for param in parameter_list: if param[0] ==", "item.quantity = _get_extended_info_by_key( \"i_quantity\", item.extended_info ) item.description = _get_extended_info_by_key( \"i_description\",", "elif param[0] == \"item:subcategory\": subcategory.append(param[1]) elif param[0] == \"item:extended_info:i_is_active\": is_active", "spot.items: item.model = _get_extended_info_by_key(\"i_model\", item.extended_info) item.brand = _get_extended_info_by_key(\"i_brand\", item.extended_info) item.checkout_period", "= False for param in parameter_list: if param[0] == \"item:extended_info:i_brand\":", "\\ _get_extended_info_by_key import copy def get_item_by_id(item_id): spot = get_spots_by_filter([ ('item:id',", "if len(subcategory) > 0 and item.subcategory not in subcategory: continue", "param[0] == \"item:subcategory\": subcategory.append(param[1]) elif param[0] == \"item:extended_info:i_is_active\": is_active =", "('item:id', item_id), ('extended_info:app_type', 'tech') ]) if spot: spot = _filter_spot_items(item_id,", "return spot def get_filtered_items(spots, request): parameter_list = _get_spot_filters(request) brand =", "item.extended_info) item.checkout_period = _get_extended_info_by_key( \"i_checkout_period\", item.extended_info ) item.reservation_notes = _get_extended_info_by_key(", "spot = get_spots_by_filter([ ('item:id', item_id), ('extended_info:app_type', 'tech') ]) if spot:", ") item.reserve_url = _get_extended_info_by_key( \"i_reserve_url\", item.extended_info ) item.manual_url = _get_extended_info_by_key(", "brand = [] subcategory = [] is_active = False for", "not in brand: continue new_spot.items.append(item) new_spots.append(new_spot) return new_spots def get_item_count(spots):", "_get_spot_filters(request) brand = [] subcategory = [] is_active = False", "item_count = 0 for spot in spots: item_count += len(spot.items)", ") item.reservation_notes = _get_extended_info_by_key( \"i_reservation_notes\", item.extended_info ) item.is_active = _get_extended_info_by_key(", "item.item_id == item_id: spot.item = item return spot def add_item_info(spot):", "University of Washington # SPDX-License-Identifier: Apache-2.0 from scout.dao.space import get_spots_by_filter,", ") item.quantity = _get_extended_info_by_key( \"i_quantity\", item.extended_info ) item.description = _get_extended_info_by_key(", "if param[0] == \"item:extended_info:i_brand\": brand.append(param[1]) elif param[0] == \"item:subcategory\": subcategory.append(param[1])", "item.is_active = _get_extended_info_by_key( \"i_is_active\", item.extended_info ) item.quantity = _get_extended_info_by_key( \"i_quantity\",", "_get_extended_info_by_key(\"i_model\", item.extended_info) item.brand = _get_extended_info_by_key(\"i_brand\", item.extended_info) item.checkout_period = _get_extended_info_by_key( \"i_checkout_period\",", "item.owner = _get_extended_info_by_key( \"i_owner\", item.extended_info ) item.is_stf = _get_extended_info_by_key( \"i_is_stf\",", "\"item:subcategory\": subcategory.append(param[1]) elif param[0] == \"item:extended_info:i_is_active\": is_active = True new_spots", "def get_item_by_id(item_id): spot = get_spots_by_filter([ ('item:id', item_id), ('extended_info:app_type', 'tech') ])", "item.extended_info ) return spot def get_filtered_items(spots, request): parameter_list = _get_spot_filters(request)", "in subcategory: continue if len(brand) > 0 and item.brand not", "== \"item:extended_info:i_is_active\": is_active = True new_spots = [] for spot", "\"i_reservation_notes\", item.extended_info ) item.is_active = _get_extended_info_by_key( \"i_is_active\", item.extended_info ) item.quantity", "== item_id: spot.item = item return spot def add_item_info(spot): for", "spot.item = item return spot def add_item_info(spot): for item in", "spot): for item in spot.items: if item.item_id == item_id: spot.item", "not in subcategory: continue if len(brand) > 0 and item.brand", "item.model = _get_extended_info_by_key(\"i_model\", item.extended_info) item.brand = _get_extended_info_by_key(\"i_brand\", item.extended_info) item.checkout_period =", "# Copyright 2021 UW-IT, University of Washington # SPDX-License-Identifier: Apache-2.0", "\"i_owner\", item.extended_info ) item.is_stf = _get_extended_info_by_key( \"i_is_stf\", item.extended_info ) item.cte_type_id", "return spot def _filter_spot_items(item_id, spot): for item in spot.items: if", "[] is_active = False for param in parameter_list: if param[0]", "def _filter_spot_items(item_id, spot): for item in spot.items: if item.item_id ==", "param[0] == \"item:extended_info:i_brand\": brand.append(param[1]) elif param[0] == \"item:subcategory\": subcategory.append(param[1]) elif", "\"cte_type_id\", item.extended_info ) return spot def get_filtered_items(spots, request): parameter_list =", "item.extended_info ) item.owner = _get_extended_info_by_key( \"i_owner\", item.extended_info ) item.is_stf =", "new_spot = copy.deepcopy(spot) new_spot.items = [] for item in spot.items:", "item.subcategory not in subcategory: continue if len(brand) > 0 and", "subcategory.append(param[1]) elif param[0] == \"item:extended_info:i_is_active\": is_active = True new_spots =", "spot = _filter_spot_items(item_id, spot[0]) return spot def _filter_spot_items(item_id, spot): for", "spot: spot = _filter_spot_items(item_id, spot[0]) return spot def _filter_spot_items(item_id, spot):", "item.extended_info ) item.reservation_notes = _get_extended_info_by_key( \"i_reservation_notes\", item.extended_info ) item.is_active =", ") item.is_active = _get_extended_info_by_key( \"i_is_active\", item.extended_info ) item.quantity = _get_extended_info_by_key(", "def get_filtered_items(spots, request): parameter_list = _get_spot_filters(request) brand = [] subcategory", "spots: new_spot = copy.deepcopy(spot) new_spot.items = [] for item in", "new_spot.items.append(item) new_spots.append(new_spot) return new_spots def get_item_count(spots): item_count = 0 for", "_filter_spot_items(item_id, spot): for item in spot.items: if item.item_id == item_id:", "Copyright 2021 UW-IT, University of Washington # SPDX-License-Identifier: Apache-2.0 from", "0 and item.brand not in brand: continue new_spot.items.append(item) new_spots.append(new_spot) return", "spot def add_item_info(spot): for item in spot.items: item.model = _get_extended_info_by_key(\"i_model\",", "copy.deepcopy(spot) new_spot.items = [] for item in spot.items: if is_active", "= _get_extended_info_by_key( \"i_manual_url\", item.extended_info ) item.owner = _get_extended_info_by_key( \"i_owner\", item.extended_info", ") item.cte_type_id = _get_extended_info_by_key( \"cte_type_id\", item.extended_info ) return spot def", "spot.items: if is_active and not item.is_active: continue if len(subcategory) >", "item.cte_type_id = _get_extended_info_by_key( \"cte_type_id\", item.extended_info ) return spot def get_filtered_items(spots,", "('extended_info:app_type', 'tech') ]) if spot: spot = _filter_spot_items(item_id, spot[0]) return", "'tech') ]) if spot: spot = _filter_spot_items(item_id, spot[0]) return spot", "= _get_extended_info_by_key( \"i_owner\", item.extended_info ) item.is_stf = _get_extended_info_by_key( \"i_is_stf\", item.extended_info", "_get_extended_info_by_key( \"i_owner\", item.extended_info ) item.is_stf = _get_extended_info_by_key( \"i_is_stf\", item.extended_info )", "= [] is_active = False for param in parameter_list: if", "> 0 and item.subcategory not in subcategory: continue if len(brand)", "item.extended_info ) item.quantity = _get_extended_info_by_key( \"i_quantity\", item.extended_info ) item.description =", "item_id: spot.item = item return spot def add_item_info(spot): for item", "continue if len(subcategory) > 0 and item.subcategory not in subcategory:", "len(brand) > 0 and item.brand not in brand: continue new_spot.items.append(item)", "def add_item_info(spot): for item in spot.items: item.model = _get_extended_info_by_key(\"i_model\", item.extended_info)", ") item.is_stf = _get_extended_info_by_key( \"i_is_stf\", item.extended_info ) item.cte_type_id = _get_extended_info_by_key(", "brand: continue new_spot.items.append(item) new_spots.append(new_spot) return new_spots def get_item_count(spots): item_count =", "= _get_extended_info_by_key( \"cte_type_id\", item.extended_info ) return spot def get_filtered_items(spots, request):", "> 0 and item.brand not in brand: continue new_spot.items.append(item) new_spots.append(new_spot)", "spot.items: if item.item_id == item_id: spot.item = item return spot", "item.reserve_url = _get_extended_info_by_key( \"i_reserve_url\", item.extended_info ) item.manual_url = _get_extended_info_by_key( \"i_manual_url\",", "_get_extended_info_by_key( \"cte_type_id\", item.extended_info ) return spot def get_filtered_items(spots, request): parameter_list", "new_spots = [] for spot in spots: new_spot = copy.deepcopy(spot)", "for param in parameter_list: if param[0] == \"item:extended_info:i_brand\": brand.append(param[1]) elif", ") item.manual_url = _get_extended_info_by_key( \"i_manual_url\", item.extended_info ) item.owner = _get_extended_info_by_key(", "item.reservation_notes = _get_extended_info_by_key( \"i_reservation_notes\", item.extended_info ) item.is_active = _get_extended_info_by_key( \"i_is_active\",", "in spot.items: if is_active and not item.is_active: continue if len(subcategory)", "item.manual_url = _get_extended_info_by_key( \"i_manual_url\", item.extended_info ) item.owner = _get_extended_info_by_key( \"i_owner\",", "= _get_extended_info_by_key(\"i_brand\", item.extended_info) item.checkout_period = _get_extended_info_by_key( \"i_checkout_period\", item.extended_info ) item.reservation_notes", "_get_extended_info_by_key( \"i_manual_url\", item.extended_info ) item.owner = _get_extended_info_by_key( \"i_owner\", item.extended_info )", "= [] for item in spot.items: if is_active and not", "continue if len(brand) > 0 and item.brand not in brand:", "item.extended_info ) item.cte_type_id = _get_extended_info_by_key( \"cte_type_id\", item.extended_info ) return spot", "item.extended_info) item.brand = _get_extended_info_by_key(\"i_brand\", item.extended_info) item.checkout_period = _get_extended_info_by_key( \"i_checkout_period\", item.extended_info", "def get_item_count(spots): item_count = 0 for spot in spots: item_count", "and not item.is_active: continue if len(subcategory) > 0 and item.subcategory", "parameter_list: if param[0] == \"item:extended_info:i_brand\": brand.append(param[1]) elif param[0] == \"item:subcategory\":", "item.extended_info ) item.reserve_url = _get_extended_info_by_key( \"i_reserve_url\", item.extended_info ) item.manual_url =", "= get_spots_by_filter([ ('item:id', item_id), ('extended_info:app_type', 'tech') ]) if spot: spot", "True new_spots = [] for spot in spots: new_spot =", "# SPDX-License-Identifier: Apache-2.0 from scout.dao.space import get_spots_by_filter, _get_spot_filters, \\ _get_extended_info_by_key", "item in spot.items: if is_active and not item.is_active: continue if" ]
[ "<filename>juriscraper/opinions/united_states/state/minnctapp.py #Scraper for Minnesota Court of Appeals Published Opinions #CourtID:", "#CourtID: minnctapp #Court Short Name: MN #Author: mlr #Date: 2016-06-03", "super(Site, self).__init__(*args, **kwargs) self.court_id = self.__module__ self.court_filters = ['/ctapun/', '/ctappub/']", "method. def __init__(self, *args, **kwargs): super(Site, self).__init__(*args, **kwargs) self.court_id =", "Minnesota Court of Appeals Published Opinions #CourtID: minnctapp #Court Short", "Only subclasses minn for the _download method. def __init__(self, *args,", "minn class Site(minn.Site): # Only subclasses minn for the _download", "minnctapp #Court Short Name: MN #Author: mlr #Date: 2016-06-03 from", "mlr #Date: 2016-06-03 from juriscraper.opinions.united_states.state import minn class Site(minn.Site): #", "import minn class Site(minn.Site): # Only subclasses minn for the", "#Scraper for Minnesota Court of Appeals Published Opinions #CourtID: minnctapp", "subclasses minn for the _download method. def __init__(self, *args, **kwargs):", "#Date: 2016-06-03 from juriscraper.opinions.united_states.state import minn class Site(minn.Site): # Only", "# Only subclasses minn for the _download method. def __init__(self,", "of Appeals Published Opinions #CourtID: minnctapp #Court Short Name: MN", "from juriscraper.opinions.united_states.state import minn class Site(minn.Site): # Only subclasses minn", "*args, **kwargs): super(Site, self).__init__(*args, **kwargs) self.court_id = self.__module__ self.court_filters =", "#Court Short Name: MN #Author: mlr #Date: 2016-06-03 from juriscraper.opinions.united_states.state", "for the _download method. def __init__(self, *args, **kwargs): super(Site, self).__init__(*args,", "def __init__(self, *args, **kwargs): super(Site, self).__init__(*args, **kwargs) self.court_id = self.__module__", "Name: MN #Author: mlr #Date: 2016-06-03 from juriscraper.opinions.united_states.state import minn", "__init__(self, *args, **kwargs): super(Site, self).__init__(*args, **kwargs) self.court_id = self.__module__ self.court_filters", "2016-06-03 from juriscraper.opinions.united_states.state import minn class Site(minn.Site): # Only subclasses", "**kwargs): super(Site, self).__init__(*args, **kwargs) self.court_id = self.__module__ self.court_filters = ['/ctapun/',", "MN #Author: mlr #Date: 2016-06-03 from juriscraper.opinions.united_states.state import minn class", "Short Name: MN #Author: mlr #Date: 2016-06-03 from juriscraper.opinions.united_states.state import", "Opinions #CourtID: minnctapp #Court Short Name: MN #Author: mlr #Date:", "Court of Appeals Published Opinions #CourtID: minnctapp #Court Short Name:", "#Author: mlr #Date: 2016-06-03 from juriscraper.opinions.united_states.state import minn class Site(minn.Site):", "_download method. def __init__(self, *args, **kwargs): super(Site, self).__init__(*args, **kwargs) self.court_id", "minn for the _download method. def __init__(self, *args, **kwargs): super(Site,", "Appeals Published Opinions #CourtID: minnctapp #Court Short Name: MN #Author:", "Published Opinions #CourtID: minnctapp #Court Short Name: MN #Author: mlr", "Site(minn.Site): # Only subclasses minn for the _download method. def", "the _download method. def __init__(self, *args, **kwargs): super(Site, self).__init__(*args, **kwargs)", "class Site(minn.Site): # Only subclasses minn for the _download method.", "for Minnesota Court of Appeals Published Opinions #CourtID: minnctapp #Court", "juriscraper.opinions.united_states.state import minn class Site(minn.Site): # Only subclasses minn for" ]
[ "'<NAME>' __copyright__ = 'Copyright 2013, The Materials Project' __version__ =", "= '<NAME>' __email__ = '<EMAIL>' __date__ = '1/24/14' @contextmanager def", "to the original working directory afterwards. E.g., with cd(\"/my/path/\"): do_something()", "command. The check is performed in a thread-safe way Args:", "directory already exists, in the fashion of \"mkdir -p\" command.", "path of the directory to create kwargs: standard kwargs for", "= '<NAME>' __copyright__ = 'Copyright 2013, The Materials Project' __version__", "for os.makedirs \"\"\" try: os.makedirs(path, **kwargs) except OSError as exc:", "already exists, in the fashion of \"mkdir -p\" command. The", "makedirs_p(path, **kwargs): \"\"\" Wrapper for os.makedirs that does not raise", "\"\"\" Wrapper for os.makedirs that does not raise an exception", "yield finally: os.chdir(cwd) def makedirs_p(path, **kwargs): \"\"\" Wrapper for os.makedirs", "directory for performing some tasks, and returns to the original", "Wrapper for os.makedirs that does not raise an exception if", "@contextmanager def cd(path): \"\"\" A Fabric-inspired cd context that temporarily", "performing some tasks, and returns to the original working directory", "directory to create kwargs: standard kwargs for os.makedirs \"\"\" try:", "a thread-safe way Args: path: path of the directory to", "def cd(path): \"\"\" A Fabric-inspired cd context that temporarily changes", "errno from contextlib import contextmanager __author__ = '<NAME>' __copyright__ =", "= '1/24/14' @contextmanager def cd(path): \"\"\" A Fabric-inspired cd context", "contextmanager __author__ = '<NAME>' __copyright__ = 'Copyright 2013, The Materials", "exists, in the fashion of \"mkdir -p\" command. The check", "os.makedirs that does not raise an exception if the directory", "\"\"\" A Fabric-inspired cd context that temporarily changes directory for", "__author__ = '<NAME>' __copyright__ = 'Copyright 2013, The Materials Project'", "an exception if the directory already exists, in the fashion", "import absolute_import import os import errno from contextlib import contextmanager", "The check is performed in a thread-safe way Args: path:", "\"mkdir -p\" command. The check is performed in a thread-safe", "= '<EMAIL>' __date__ = '1/24/14' @contextmanager def cd(path): \"\"\" A", "some tasks, and returns to the original working directory afterwards.", "raise an exception if the directory already exists, in the", "os.makedirs(path, **kwargs) except OSError as exc: if exc.errno == errno.EEXIST", "cd to. \"\"\" cwd = os.getcwd() os.chdir(path) try: yield finally:", "in a thread-safe way Args: path: path of the directory", "import os import errno from contextlib import contextmanager __author__ =", "that temporarily changes directory for performing some tasks, and returns", "of the directory to create kwargs: standard kwargs for os.makedirs", "of \"mkdir -p\" command. The check is performed in a", "**kwargs): \"\"\" Wrapper for os.makedirs that does not raise an", "__copyright__ = 'Copyright 2013, The Materials Project' __version__ = '0.1'", "cwd = os.getcwd() os.chdir(path) try: yield finally: os.chdir(cwd) def makedirs_p(path,", "exception if the directory already exists, in the fashion of", "fashion of \"mkdir -p\" command. The check is performed in", "The Materials Project' __version__ = '0.1' __maintainer__ = '<NAME>' __email__", "to. \"\"\" cwd = os.getcwd() os.chdir(path) try: yield finally: os.chdir(cwd)", "= 'Copyright 2013, The Materials Project' __version__ = '0.1' __maintainer__", "'<NAME>' __email__ = '<EMAIL>' __date__ = '1/24/14' @contextmanager def cd(path):", "check is performed in a thread-safe way Args: path: path", "and returns to the original working directory afterwards. E.g., with", "__future__ import absolute_import import os import errno from contextlib import", "standard kwargs for os.makedirs \"\"\" try: os.makedirs(path, **kwargs) except OSError", "os.chdir(path) try: yield finally: os.chdir(cwd) def makedirs_p(path, **kwargs): \"\"\" Wrapper", "in the fashion of \"mkdir -p\" command. The check is", "os.getcwd() os.chdir(path) try: yield finally: os.chdir(cwd) def makedirs_p(path, **kwargs): \"\"\"", "the original working directory afterwards. E.g., with cd(\"/my/path/\"): do_something() Args:", "'Copyright 2013, The Materials Project' __version__ = '0.1' __maintainer__ =", "the directory to create kwargs: standard kwargs for os.makedirs \"\"\"", "exc: if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise", "thread-safe way Args: path: path of the directory to create", "not raise an exception if the directory already exists, in", "from __future__ import absolute_import import os import errno from contextlib", "from contextlib import contextmanager __author__ = '<NAME>' __copyright__ = 'Copyright", "temporarily changes directory for performing some tasks, and returns to", "returns to the original working directory afterwards. E.g., with cd(\"/my/path/\"):", "if the directory already exists, in the fashion of \"mkdir", "try: yield finally: os.chdir(cwd) def makedirs_p(path, **kwargs): \"\"\" Wrapper for", "-p\" command. The check is performed in a thread-safe way", "'<EMAIL>' __date__ = '1/24/14' @contextmanager def cd(path): \"\"\" A Fabric-inspired", "cd context that temporarily changes directory for performing some tasks,", "Args: path: Path to cd to. \"\"\" cwd = os.getcwd()", "os import errno from contextlib import contextmanager __author__ = '<NAME>'", "to cd to. \"\"\" cwd = os.getcwd() os.chdir(path) try: yield", "try: os.makedirs(path, **kwargs) except OSError as exc: if exc.errno ==", "__email__ = '<EMAIL>' __date__ = '1/24/14' @contextmanager def cd(path): \"\"\"", "the fashion of \"mkdir -p\" command. The check is performed", "context that temporarily changes directory for performing some tasks, and", "with cd(\"/my/path/\"): do_something() Args: path: Path to cd to. \"\"\"", "kwargs for os.makedirs \"\"\" try: os.makedirs(path, **kwargs) except OSError as", "def makedirs_p(path, **kwargs): \"\"\" Wrapper for os.makedirs that does not", "does not raise an exception if the directory already exists,", "= '0.1' __maintainer__ = '<NAME>' __email__ = '<EMAIL>' __date__ =", "\"\"\" cwd = os.getcwd() os.chdir(path) try: yield finally: os.chdir(cwd) def", "for performing some tasks, and returns to the original working", "contextlib import contextmanager __author__ = '<NAME>' __copyright__ = 'Copyright 2013,", "Args: path: path of the directory to create kwargs: standard", "directory afterwards. E.g., with cd(\"/my/path/\"): do_something() Args: path: Path to", "Project' __version__ = '0.1' __maintainer__ = '<NAME>' __email__ = '<EMAIL>'", "import contextmanager __author__ = '<NAME>' __copyright__ = 'Copyright 2013, The", "to create kwargs: standard kwargs for os.makedirs \"\"\" try: os.makedirs(path,", "__version__ = '0.1' __maintainer__ = '<NAME>' __email__ = '<EMAIL>' __date__", "A Fabric-inspired cd context that temporarily changes directory for performing", "__date__ = '1/24/14' @contextmanager def cd(path): \"\"\" A Fabric-inspired cd", "way Args: path: path of the directory to create kwargs:", "as exc: if exc.errno == errno.EEXIST and os.path.isdir(path): pass else:", "do_something() Args: path: Path to cd to. \"\"\" cwd =", "Path to cd to. \"\"\" cwd = os.getcwd() os.chdir(path) try:", "original working directory afterwards. E.g., with cd(\"/my/path/\"): do_something() Args: path:", "cd(path): \"\"\" A Fabric-inspired cd context that temporarily changes directory", "finally: os.chdir(cwd) def makedirs_p(path, **kwargs): \"\"\" Wrapper for os.makedirs that", "path: Path to cd to. \"\"\" cwd = os.getcwd() os.chdir(path)", "performed in a thread-safe way Args: path: path of the", "create kwargs: standard kwargs for os.makedirs \"\"\" try: os.makedirs(path, **kwargs)", "the directory already exists, in the fashion of \"mkdir -p\"", "'1/24/14' @contextmanager def cd(path): \"\"\" A Fabric-inspired cd context that", "working directory afterwards. E.g., with cd(\"/my/path/\"): do_something() Args: path: Path", "cd(\"/my/path/\"): do_something() Args: path: Path to cd to. \"\"\" cwd", "kwargs: standard kwargs for os.makedirs \"\"\" try: os.makedirs(path, **kwargs) except", "Fabric-inspired cd context that temporarily changes directory for performing some", "absolute_import import os import errno from contextlib import contextmanager __author__", "**kwargs) except OSError as exc: if exc.errno == errno.EEXIST and", "'0.1' __maintainer__ = '<NAME>' __email__ = '<EMAIL>' __date__ = '1/24/14'", "2013, The Materials Project' __version__ = '0.1' __maintainer__ = '<NAME>'", "import errno from contextlib import contextmanager __author__ = '<NAME>' __copyright__", "Materials Project' __version__ = '0.1' __maintainer__ = '<NAME>' __email__ =", "\"\"\" try: os.makedirs(path, **kwargs) except OSError as exc: if exc.errno", "= os.getcwd() os.chdir(path) try: yield finally: os.chdir(cwd) def makedirs_p(path, **kwargs):", "that does not raise an exception if the directory already", "E.g., with cd(\"/my/path/\"): do_something() Args: path: Path to cd to.", "except OSError as exc: if exc.errno == errno.EEXIST and os.path.isdir(path):", "path: path of the directory to create kwargs: standard kwargs", "for os.makedirs that does not raise an exception if the", "__maintainer__ = '<NAME>' __email__ = '<EMAIL>' __date__ = '1/24/14' @contextmanager", "afterwards. E.g., with cd(\"/my/path/\"): do_something() Args: path: Path to cd", "tasks, and returns to the original working directory afterwards. E.g.,", "changes directory for performing some tasks, and returns to the", "is performed in a thread-safe way Args: path: path of", "OSError as exc: if exc.errno == errno.EEXIST and os.path.isdir(path): pass", "os.makedirs \"\"\" try: os.makedirs(path, **kwargs) except OSError as exc: if", "os.chdir(cwd) def makedirs_p(path, **kwargs): \"\"\" Wrapper for os.makedirs that does" ]
[ "Found: Python {sys.version}\") else: print(\">>> Development environment passes all tests!\")", "def main(): system_major = sys.version_info.major if system_major != required_major: raise", "Development environment passes all tests!\") if __name__ == '__main__': main()", "required_major = 3 def main(): system_major = sys.version_info.major if system_major", "system_major != required_major: raise TypeError( f\"This project requires Python {required_major}.\"", "!= required_major: raise TypeError( f\"This project requires Python {required_major}.\" f\"", "project requires Python {required_major}.\" f\" Found: Python {sys.version}\") else: print(\">>>", "else: print(\">>> Development environment passes all tests!\") if __name__ ==", "sys.version_info.major if system_major != required_major: raise TypeError( f\"This project requires", "system_major = sys.version_info.major if system_major != required_major: raise TypeError( f\"This", "= \"python3\" required_major = 3 def main(): system_major = sys.version_info.major", "print(\">>> Development environment passes all tests!\") if __name__ == '__main__':", "required_major: raise TypeError( f\"This project requires Python {required_major}.\" f\" Found:", "REQUIRED_PYTHON = \"python3\" required_major = 3 def main(): system_major =", "Python {sys.version}\") else: print(\">>> Development environment passes all tests!\") if", "\"python3\" required_major = 3 def main(): system_major = sys.version_info.major if", "3 def main(): system_major = sys.version_info.major if system_major != required_major:", "raise TypeError( f\"This project requires Python {required_major}.\" f\" Found: Python", "= sys.version_info.major if system_major != required_major: raise TypeError( f\"This project", "sys REQUIRED_PYTHON = \"python3\" required_major = 3 def main(): system_major", "{sys.version}\") else: print(\">>> Development environment passes all tests!\") if __name__", "= 3 def main(): system_major = sys.version_info.major if system_major !=", "main(): system_major = sys.version_info.major if system_major != required_major: raise TypeError(", "TypeError( f\"This project requires Python {required_major}.\" f\" Found: Python {sys.version}\")", "{required_major}.\" f\" Found: Python {sys.version}\") else: print(\">>> Development environment passes", "requires Python {required_major}.\" f\" Found: Python {sys.version}\") else: print(\">>> Development", "if system_major != required_major: raise TypeError( f\"This project requires Python", "f\"This project requires Python {required_major}.\" f\" Found: Python {sys.version}\") else:", "f\" Found: Python {sys.version}\") else: print(\">>> Development environment passes all", "Python {required_major}.\" f\" Found: Python {sys.version}\") else: print(\">>> Development environment", "import sys REQUIRED_PYTHON = \"python3\" required_major = 3 def main():" ]
[ "All Rights Reserved. # # This file is licensed under", "data while True: data = json.dumps(getReferrer()) print(data) kinesis.put_record( StreamName=\"ExampleInputStream\", Data=data,", "# License is located at # # http://aws.amazon.com/apache2.0/ # #", "at # # http://aws.amazon.com/apache2.0/ # # This file is distributed", "def getReferrer(): data = {} now = datetime.datetime.now() str_now =", "= str_now data['TICKER'] = random.choice(['AAPL', 'AMZN', 'MSFT', 'INTC', 'TBV']) price", "Data Analytics SQL applications.] # snippet-service:[kinesisanalytics] # snippet-keyword:[Python] # snippet-sourcesyntax:[python]", "demonstrates how to generate sample data for Amazon Kinesis Data", "'MSFT', 'INTC', 'TBV']) price = random.random() * 100 data['PRICE'] =", "data['PRICE'] = round(price, 2) return data while True: data =", "catalog. Do not remove.] # snippet-sourcedescription:[kda-python-datagenerator-stockticker.py demonstrates how to generate", "# snippet-service:[kinesisanalytics] # snippet-keyword:[Python] # snippet-sourcesyntax:[python] # snippet-sourcesyntax:[python] # snippet-keyword:[Amazon", "Rights Reserved. # # This file is licensed under the", "copy of the # License is located at # #", "WARRANTIES OR CONDITIONS # OF ANY KIND, either express or", "its affiliates. All Rights Reserved. # # This file is", "AWS doc team's sample catalog. Do not remove.] # snippet-sourcedescription:[kda-python-datagenerator-stockticker.py", "# # This file is distributed on an \"AS IS\"", "file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES", "for the specific # language governing permissions and limitations under", "# snippet-sourcedescription:[kda-python-datagenerator-stockticker.py demonstrates how to generate sample data for Amazon", "(the \"License\"). # You may not use this file except", "100 data['PRICE'] = round(price, 2) return data while True: data", "snippet-sourcetype:[full-example] # snippet-sourcedate:[2019-01-29] # snippet-sourceauthor:[fletpatr (AWS)] # Copyright 2010-2019 Amazon.com,", "2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. #", "WITHOUT WARRANTIES OR CONDITIONS # OF ANY KIND, either express", "sample catalog. Do not remove.] # snippet-sourcedescription:[kda-python-datagenerator-stockticker.py demonstrates how to", "located at # # http://aws.amazon.com/apache2.0/ # # This file is", "str_now data['TICKER'] = random.choice(['AAPL', 'AMZN', 'MSFT', 'INTC', 'TBV']) price =", "import random import datetime kinesis = boto3.client('kinesis') def getReferrer(): data", "http://aws.amazon.com/apache2.0/ # # This file is distributed on an \"AS", "permissions and limitations under the License. # snippet-start:[kinesisanalytics.python.datagenerator.stockticker] import json", "language governing permissions and limitations under the License. # snippet-start:[kinesisanalytics.python.datagenerator.stockticker]", "of the # License is located at # # http://aws.amazon.com/apache2.0/", "affiliates. All Rights Reserved. # # This file is licensed", "# snippet-start:[kinesisanalytics.python.datagenerator.stockticker] import json import boto3 import random import datetime", "not use this file except in compliance with the License.", "SQL applications.] # snippet-service:[kinesisanalytics] # snippet-keyword:[Python] # snippet-sourcesyntax:[python] # snippet-sourcesyntax:[python]", "# # This file is licensed under the Apache License,", "License. A copy of the # License is located at", "\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS # OF ANY", "# snippet-sourcesyntax:[python] # snippet-sourcesyntax:[python] # snippet-keyword:[Amazon Kinesis Data Analytics] #", "is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR", "# http://aws.amazon.com/apache2.0/ # # This file is distributed on an", "License. # snippet-start:[kinesisanalytics.python.datagenerator.stockticker] import json import boto3 import random import", "an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS # OF", "snippet-sourceauthor:[fletpatr (AWS)] # Copyright 2010-2019 Amazon.com, Inc. or its affiliates.", "distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS", "# language governing permissions and limitations under the License. #", "See the License for the specific # language governing permissions", "round(price, 2) return data while True: data = json.dumps(getReferrer()) print(data)", "# Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights", "snippet-sourcedate:[2019-01-29] # snippet-sourceauthor:[fletpatr (AWS)] # Copyright 2010-2019 Amazon.com, Inc. or", "snippet-sourcesyntax:[python] # snippet-sourcesyntax:[python] # snippet-keyword:[Amazon Kinesis Data Analytics] # snippet-keyword:[Code", "# This file is licensed under the Apache License, Version", "This file is distributed on an \"AS IS\" BASIS, WITHOUT", "Data Analytics] # snippet-keyword:[Code Sample] # snippet-sourcetype:[full-example] # snippet-sourcedate:[2019-01-29] #", "# snippet-sourcetype:[full-example] # snippet-sourcedate:[2019-01-29] # snippet-sourceauthor:[fletpatr (AWS)] # Copyright 2010-2019", "ANY KIND, either express or implied. See the License for", "import json import boto3 import random import datetime kinesis =", "now.isoformat() data['EVENT_TIME'] = str_now data['TICKER'] = random.choice(['AAPL', 'AMZN', 'MSFT', 'INTC',", "snippet-keyword:[Python] # snippet-sourcesyntax:[python] # snippet-sourcesyntax:[python] # snippet-keyword:[Amazon Kinesis Data Analytics]", "A copy of the # License is located at #", "Do not remove.] # snippet-sourcedescription:[kda-python-datagenerator-stockticker.py demonstrates how to generate sample", "# snippet-keyword:[Python] # snippet-sourcesyntax:[python] # snippet-sourcesyntax:[python] # snippet-keyword:[Amazon Kinesis Data", "either express or implied. See the License for the specific", "# OF ANY KIND, either express or implied. See the", "doc team's sample catalog. Do not remove.] # snippet-sourcedescription:[kda-python-datagenerator-stockticker.py demonstrates", "'AMZN', 'MSFT', 'INTC', 'TBV']) price = random.random() * 100 data['PRICE']", "the # License is located at # # http://aws.amazon.com/apache2.0/ #", "with the License. A copy of the # License is", "'INTC', 'TBV']) price = random.random() * 100 data['PRICE'] = round(price,", "CONDITIONS # OF ANY KIND, either express or implied. See", "this file except in compliance with the License. A copy", "snippet-sourcesyntax:[python] # snippet-keyword:[Amazon Kinesis Data Analytics] # snippet-keyword:[Code Sample] #", "License, Version 2.0 (the \"License\"). # You may not use", "the License. A copy of the # License is located", "datetime kinesis = boto3.client('kinesis') def getReferrer(): data = {} now", "You may not use this file except in compliance with", "snippet-start:[kinesisanalytics.python.datagenerator.stockticker] import json import boto3 import random import datetime kinesis", "data['EVENT_TIME'] = str_now data['TICKER'] = random.choice(['AAPL', 'AMZN', 'MSFT', 'INTC', 'TBV'])", "data for Amazon Kinesis Data Analytics SQL applications.] # snippet-service:[kinesisanalytics]", "json import boto3 import random import datetime kinesis = boto3.client('kinesis')", "(AWS)] # Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All", "Amazon.com, Inc. or its affiliates. All Rights Reserved. # #", "kinesis = boto3.client('kinesis') def getReferrer(): data = {} now =", "sample data for Amazon Kinesis Data Analytics SQL applications.] #", "licensed under the Apache License, Version 2.0 (the \"License\"). #", "random import datetime kinesis = boto3.client('kinesis') def getReferrer(): data =", "on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS #", "Analytics] # snippet-keyword:[Code Sample] # snippet-sourcetype:[full-example] # snippet-sourcedate:[2019-01-29] # snippet-sourceauthor:[fletpatr", "boto3 import random import datetime kinesis = boto3.client('kinesis') def getReferrer():", "# snippet-keyword:[Code Sample] # snippet-sourcetype:[full-example] # snippet-sourcedate:[2019-01-29] # snippet-sourceauthor:[fletpatr (AWS)]", "to generate sample data for Amazon Kinesis Data Analytics SQL", "True: data = json.dumps(getReferrer()) print(data) kinesis.put_record( StreamName=\"ExampleInputStream\", Data=data, PartitionKey=\"partitionkey\") #", "Kinesis Data Analytics SQL applications.] # snippet-service:[kinesisanalytics] # snippet-keyword:[Python] #", "Inc. or its affiliates. All Rights Reserved. # # This", "BASIS, WITHOUT WARRANTIES OR CONDITIONS # OF ANY KIND, either", "the Apache License, Version 2.0 (the \"License\"). # You may", "snippet-keyword:[Code Sample] # snippet-sourcetype:[full-example] # snippet-sourcedate:[2019-01-29] # snippet-sourceauthor:[fletpatr (AWS)] #", "and limitations under the License. # snippet-start:[kinesisanalytics.python.datagenerator.stockticker] import json import", "datetime.datetime.now() str_now = now.isoformat() data['EVENT_TIME'] = str_now data['TICKER'] = random.choice(['AAPL',", "'TBV']) price = random.random() * 100 data['PRICE'] = round(price, 2)", "for the AWS doc team's sample catalog. Do not remove.]", "is located at # # http://aws.amazon.com/apache2.0/ # # This file", "remove.] # snippet-sourcedescription:[kda-python-datagenerator-stockticker.py demonstrates how to generate sample data for", "specific # language governing permissions and limitations under the License.", "governing permissions and limitations under the License. # snippet-start:[kinesisanalytics.python.datagenerator.stockticker] import", "snippet-comment:[These are tags for the AWS doc team's sample catalog.", "snippet-keyword:[Amazon Kinesis Data Analytics] # snippet-keyword:[Code Sample] # snippet-sourcetype:[full-example] #", "express or implied. See the License for the specific #", "= datetime.datetime.now() str_now = now.isoformat() data['EVENT_TIME'] = str_now data['TICKER'] =", "KIND, either express or implied. See the License for the", "data = json.dumps(getReferrer()) print(data) kinesis.put_record( StreamName=\"ExampleInputStream\", Data=data, PartitionKey=\"partitionkey\") # snippet-end:[kinesisanalytics.python.datagenerator.stockticker]", "Amazon Kinesis Data Analytics SQL applications.] # snippet-service:[kinesisanalytics] # snippet-keyword:[Python]", "in compliance with the License. A copy of the #", "License for the specific # language governing permissions and limitations", "while True: data = json.dumps(getReferrer()) print(data) kinesis.put_record( StreamName=\"ExampleInputStream\", Data=data, PartitionKey=\"partitionkey\")", "= boto3.client('kinesis') def getReferrer(): data = {} now = datetime.datetime.now()", "# snippet-comment:[These are tags for the AWS doc team's sample", "how to generate sample data for Amazon Kinesis Data Analytics", "or implied. See the License for the specific # language", "# # http://aws.amazon.com/apache2.0/ # # This file is distributed on", "Sample] # snippet-sourcetype:[full-example] # snippet-sourcedate:[2019-01-29] # snippet-sourceauthor:[fletpatr (AWS)] # Copyright", "# snippet-sourcedate:[2019-01-29] # snippet-sourceauthor:[fletpatr (AWS)] # Copyright 2010-2019 Amazon.com, Inc.", "OF ANY KIND, either express or implied. See the License", "file except in compliance with the License. A copy of", "limitations under the License. # snippet-start:[kinesisanalytics.python.datagenerator.stockticker] import json import boto3", "random.random() * 100 data['PRICE'] = round(price, 2) return data while", "or its affiliates. All Rights Reserved. # # This file", "= random.random() * 100 data['PRICE'] = round(price, 2) return data", "This file is licensed under the Apache License, Version 2.0", "# snippet-keyword:[Amazon Kinesis Data Analytics] # snippet-keyword:[Code Sample] # snippet-sourcetype:[full-example]", "not remove.] # snippet-sourcedescription:[kda-python-datagenerator-stockticker.py demonstrates how to generate sample data", "tags for the AWS doc team's sample catalog. Do not", "data = {} now = datetime.datetime.now() str_now = now.isoformat() data['EVENT_TIME']", "= now.isoformat() data['EVENT_TIME'] = str_now data['TICKER'] = random.choice(['AAPL', 'AMZN', 'MSFT',", "the specific # language governing permissions and limitations under the", "import datetime kinesis = boto3.client('kinesis') def getReferrer(): data = {}", "Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.", "the AWS doc team's sample catalog. Do not remove.] #", "applications.] # snippet-service:[kinesisanalytics] # snippet-keyword:[Python] # snippet-sourcesyntax:[python] # snippet-sourcesyntax:[python] #", "price = random.random() * 100 data['PRICE'] = round(price, 2) return", "boto3.client('kinesis') def getReferrer(): data = {} now = datetime.datetime.now() str_now", "OR CONDITIONS # OF ANY KIND, either express or implied.", "use this file except in compliance with the License. A", "compliance with the License. A copy of the # License", "# This file is distributed on an \"AS IS\" BASIS,", "the License for the specific # language governing permissions and", "Kinesis Data Analytics] # snippet-keyword:[Code Sample] # snippet-sourcetype:[full-example] # snippet-sourcedate:[2019-01-29]", "is licensed under the Apache License, Version 2.0 (the \"License\").", "the License. # snippet-start:[kinesisanalytics.python.datagenerator.stockticker] import json import boto3 import random", "team's sample catalog. Do not remove.] # snippet-sourcedescription:[kda-python-datagenerator-stockticker.py demonstrates how", "snippet-sourcedescription:[kda-python-datagenerator-stockticker.py demonstrates how to generate sample data for Amazon Kinesis", "import boto3 import random import datetime kinesis = boto3.client('kinesis') def", "2.0 (the \"License\"). # You may not use this file", "# You may not use this file except in compliance", "* 100 data['PRICE'] = round(price, 2) return data while True:", "except in compliance with the License. A copy of the", "License is located at # # http://aws.amazon.com/apache2.0/ # # This", "under the Apache License, Version 2.0 (the \"License\"). # You", "getReferrer(): data = {} now = datetime.datetime.now() str_now = now.isoformat()", "now = datetime.datetime.now() str_now = now.isoformat() data['EVENT_TIME'] = str_now data['TICKER']", "implied. See the License for the specific # language governing", "may not use this file except in compliance with the", "are tags for the AWS doc team's sample catalog. Do", "IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS # OF ANY KIND,", "data['TICKER'] = random.choice(['AAPL', 'AMZN', 'MSFT', 'INTC', 'TBV']) price = random.random()", "return data while True: data = json.dumps(getReferrer()) print(data) kinesis.put_record( StreamName=\"ExampleInputStream\",", "\"License\"). # You may not use this file except in", "file is licensed under the Apache License, Version 2.0 (the", "Apache License, Version 2.0 (the \"License\"). # You may not", "for Amazon Kinesis Data Analytics SQL applications.] # snippet-service:[kinesisanalytics] #", "# snippet-sourceauthor:[fletpatr (AWS)] # Copyright 2010-2019 Amazon.com, Inc. or its", "= random.choice(['AAPL', 'AMZN', 'MSFT', 'INTC', 'TBV']) price = random.random() *", "generate sample data for Amazon Kinesis Data Analytics SQL applications.]", "Analytics SQL applications.] # snippet-service:[kinesisanalytics] # snippet-keyword:[Python] # snippet-sourcesyntax:[python] #", "= round(price, 2) return data while True: data = json.dumps(getReferrer())", "{} now = datetime.datetime.now() str_now = now.isoformat() data['EVENT_TIME'] = str_now", "under the License. # snippet-start:[kinesisanalytics.python.datagenerator.stockticker] import json import boto3 import", "random.choice(['AAPL', 'AMZN', 'MSFT', 'INTC', 'TBV']) price = random.random() * 100", "snippet-service:[kinesisanalytics] # snippet-keyword:[Python] # snippet-sourcesyntax:[python] # snippet-sourcesyntax:[python] # snippet-keyword:[Amazon Kinesis", "str_now = now.isoformat() data['EVENT_TIME'] = str_now data['TICKER'] = random.choice(['AAPL', 'AMZN',", "Reserved. # # This file is licensed under the Apache", "= {} now = datetime.datetime.now() str_now = now.isoformat() data['EVENT_TIME'] =", "2) return data while True: data = json.dumps(getReferrer()) print(data) kinesis.put_record(", "# snippet-sourcesyntax:[python] # snippet-keyword:[Amazon Kinesis Data Analytics] # snippet-keyword:[Code Sample]", "Version 2.0 (the \"License\"). # You may not use this" ]
[ "def video_feed(): print('CAMERA RUN') return Response(camera.gen_frames(), mimetype='multipart/x-mixed-replace; boundary=frame') @app.route('/recent_person') def", "system ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'} app = Flask(__name__) def", "= face_recognition.load_image_file(file_stream) # Get face encodings for any faces in", "204) @app.route('/configuration', methods=['GET', 'POST']) def config(): db.config_camera_interval(int(request.form.get('cameraDuration'))) return('', 204) @app.route('/members')", "= request.form.get(\"changeName\") changeAccess = request.form.get(\"changeAccess\") if changeAccess == None: changeAccess", "changeName, changeAccess) return ('', 204) @app.route('/configuration', methods=['GET', 'POST']) def config():", "('', 204) @app.route('/') def root(): return ('', 204) @app.route('/upload', methods=['GET',", "return redirect(request.url) if file and allowed_file(file.filename): return detect_faces_in_image(name, access, file)", "file = request.files['file'] if file.filename == '': return redirect(request.url) if", "if request.method == 'POST': if 'file' not in request.files: return", "allowed_file(file.filename): return detect_faces_in_image(name, access, file) return redirect('/video_feed') @app.route('/update', methods=['GET', 'POST'])", "def allowed_file(filename): return '.' in filename and \\ filename.rsplit('.', 1)[1].lower()", "'POST']) def update(): db.encoding.update() member = request.form.get(\"updateMember\") changeName = request.form.get(\"changeName\")", "@app.route('/video_feed') def video_feed(): print('CAMERA RUN') return Response(camera.gen_frames(), mimetype='multipart/x-mixed-replace; boundary=frame') @app.route('/recent_person')", "in filename and \\ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS def detect_faces_in_image(name,", "return '.' in filename and \\ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS", "this to any folder on your system ALLOWED_EXTENSIONS = {'png',", "unknown_face_encodings = face_recognition.face_encodings(img)[0].tolist() db.add_member(name, access, unknown_face_encodings) return ('', 204) @app.route('/')", "unknown_face_encodings) return ('', 204) @app.route('/') def root(): return ('', 204)", "member = request.form.get(\"updateMember\") changeName = request.form.get(\"changeName\") changeAccess = request.form.get(\"changeAccess\") if", "db.config_camera_interval(int(request.form.get('cameraDuration'))) return('', 204) @app.route('/members') def members(): print(type(db.encoding.get_names())) return str(db.encoding.get_names()) @app.route('/video_feed')", "uploaded image filed img = face_recognition.load_image_file(file_stream) # Get face encodings", "return redirect(request.url) file = request.files['file'] if file.filename == '': return", "changeAccess = request.form.get(\"changeAccess\") if changeAccess == None: changeAccess = \"\"", "file and allowed_file(file.filename): return detect_faces_in_image(name, access, file) return redirect('/video_feed') @app.route('/update',", "# Load the uploaded image filed img = face_recognition.load_image_file(file_stream) #", "image unknown_face_encodings = face_recognition.face_encodings(img)[0].tolist() db.add_member(name, access, unknown_face_encodings) return ('', 204)", "and \\ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS def detect_faces_in_image(name, access, file_stream):", "= request.form.get(\"changeAccess\") if changeAccess == None: changeAccess = \"\" db.update_member(member,", "import face_recognition from flask import Flask, request, redirect, Response import", "== None: changeAccess = \"\" db.update_member(member, changeName, changeAccess) return ('',", "request.form.get(\"updateMember\") changeName = request.form.get(\"changeName\") changeAccess = request.form.get(\"changeAccess\") if changeAccess ==", "import firestore as db # You can change this to", "1)[1].lower() in ALLOWED_EXTENSIONS def detect_faces_in_image(name, access, file_stream): # Load the", "face encodings for any faces in the uploaded image unknown_face_encodings", "from flask import Flask, request, redirect, Response import camera import", "your system ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'} app = Flask(__name__)", "access, unknown_face_encodings) return ('', 204) @app.route('/') def root(): return ('',", "access = int(access) if request.method == 'POST': if 'file' not", "for any faces in the uploaded image unknown_face_encodings = face_recognition.face_encodings(img)[0].tolist()", "return('', 204) @app.route('/members') def members(): print(type(db.encoding.get_names())) return str(db.encoding.get_names()) @app.route('/video_feed') def", "= {'png', 'jpg', 'jpeg'} app = Flask(__name__) def allowed_file(filename): return", "firestore as db # You can change this to any", "= request.form.get(\"name\") access = request.form.get(\"access\") access = int(access) if request.method", "def detect_faces_in_image(name, access, file_stream): # Load the uploaded image filed", "to any folder on your system ALLOWED_EXTENSIONS = {'png', 'jpg',", "if file.filename == '': return redirect(request.url) if file and allowed_file(file.filename):", "@app.route('/recent_person') def recent_person(): return db.history_log.get_most_recent_member() if __name__ == \"__main__\": app.run(host='0.0.0.0',", "return ('', 204) @app.route('/configuration', methods=['GET', 'POST']) def config(): db.config_camera_interval(int(request.form.get('cameraDuration'))) return('',", "= request.form.get(\"updateMember\") changeName = request.form.get(\"changeName\") changeAccess = request.form.get(\"changeAccess\") if changeAccess", "print(type(db.encoding.get_names())) return str(db.encoding.get_names()) @app.route('/video_feed') def video_feed(): print('CAMERA RUN') return Response(camera.gen_frames(),", "folder on your system ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'} app", "db.update_member(member, changeName, changeAccess) return ('', 204) @app.route('/configuration', methods=['GET', 'POST']) def", "file.filename == '': return redirect(request.url) if file and allowed_file(file.filename): return", "changeAccess == None: changeAccess = \"\" db.update_member(member, changeName, changeAccess) return", "You can change this to any folder on your system", "if file and allowed_file(file.filename): return detect_faces_in_image(name, access, file) return redirect('/video_feed')", "uploaded image unknown_face_encodings = face_recognition.face_encodings(img)[0].tolist() db.add_member(name, access, unknown_face_encodings) return ('',", "@app.route('/upload', methods=['GET', 'POST']) def upload_image(): db.encoding.update() name = request.form.get(\"name\") access", "not in request.files: return redirect(request.url) file = request.files['file'] if file.filename", "ALLOWED_EXTENSIONS def detect_faces_in_image(name, access, file_stream): # Load the uploaded image", "request.method == 'POST': if 'file' not in request.files: return redirect(request.url)", "RUN') return Response(camera.gen_frames(), mimetype='multipart/x-mixed-replace; boundary=frame') @app.route('/recent_person') def recent_person(): return db.history_log.get_most_recent_member()", "<reponame>alexespejo/project-argus import face_recognition from flask import Flask, request, redirect, Response", "def recent_person(): return db.history_log.get_most_recent_member() if __name__ == \"__main__\": app.run(host='0.0.0.0', port=5001,", "update(): db.encoding.update() member = request.form.get(\"updateMember\") changeName = request.form.get(\"changeName\") changeAccess =", "== 'POST': if 'file' not in request.files: return redirect(request.url) file", "on your system ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'} app =", "db.add_member(name, access, unknown_face_encodings) return ('', 204) @app.route('/') def root(): return", "app = Flask(__name__) def allowed_file(filename): return '.' in filename and", "204) @app.route('/upload', methods=['GET', 'POST']) def upload_image(): db.encoding.update() name = request.form.get(\"name\")", "can change this to any folder on your system ALLOWED_EXTENSIONS", "'POST']) def upload_image(): db.encoding.update() name = request.form.get(\"name\") access = request.form.get(\"access\")", "@app.route('/members') def members(): print(type(db.encoding.get_names())) return str(db.encoding.get_names()) @app.route('/video_feed') def video_feed(): print('CAMERA", "request.form.get(\"changeName\") changeAccess = request.form.get(\"changeAccess\") if changeAccess == None: changeAccess =", "print('CAMERA RUN') return Response(camera.gen_frames(), mimetype='multipart/x-mixed-replace; boundary=frame') @app.route('/recent_person') def recent_person(): return", "int(access) if request.method == 'POST': if 'file' not in request.files:", "if 'file' not in request.files: return redirect(request.url) file = request.files['file']", "video_feed(): print('CAMERA RUN') return Response(camera.gen_frames(), mimetype='multipart/x-mixed-replace; boundary=frame') @app.route('/recent_person') def recent_person():", "Response import camera import firestore as db # You can", "access, file_stream): # Load the uploaded image filed img =", "@app.route('/configuration', methods=['GET', 'POST']) def config(): db.config_camera_interval(int(request.form.get('cameraDuration'))) return('', 204) @app.route('/members') def", "= Flask(__name__) def allowed_file(filename): return '.' in filename and \\", "# Get face encodings for any faces in the uploaded", "Get face encodings for any faces in the uploaded image", "methods=['GET', 'POST']) def upload_image(): db.encoding.update() name = request.form.get(\"name\") access =", "name = request.form.get(\"name\") access = request.form.get(\"access\") access = int(access) if", "= int(access) if request.method == 'POST': if 'file' not in", "def members(): print(type(db.encoding.get_names())) return str(db.encoding.get_names()) @app.route('/video_feed') def video_feed(): print('CAMERA RUN')", "import camera import firestore as db # You can change", "\\ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS def detect_faces_in_image(name, access, file_stream): #", "encodings for any faces in the uploaded image unknown_face_encodings =", "detect_faces_in_image(name, access, file) return redirect('/video_feed') @app.route('/update', methods=['GET', 'POST']) def update():", "filed img = face_recognition.load_image_file(file_stream) # Get face encodings for any", "face_recognition.face_encodings(img)[0].tolist() db.add_member(name, access, unknown_face_encodings) return ('', 204) @app.route('/') def root():", "in ALLOWED_EXTENSIONS def detect_faces_in_image(name, access, file_stream): # Load the uploaded", "face_recognition.load_image_file(file_stream) # Get face encodings for any faces in the", "config(): db.config_camera_interval(int(request.form.get('cameraDuration'))) return('', 204) @app.route('/members') def members(): print(type(db.encoding.get_names())) return str(db.encoding.get_names())", "image filed img = face_recognition.load_image_file(file_stream) # Get face encodings for", "changeAccess = \"\" db.update_member(member, changeName, changeAccess) return ('', 204) @app.route('/configuration',", "db # You can change this to any folder on", "allowed_file(filename): return '.' in filename and \\ filename.rsplit('.', 1)[1].lower() in", "and allowed_file(file.filename): return detect_faces_in_image(name, access, file) return redirect('/video_feed') @app.route('/update', methods=['GET',", "any faces in the uploaded image unknown_face_encodings = face_recognition.face_encodings(img)[0].tolist() db.add_member(name,", "changeName = request.form.get(\"changeName\") changeAccess = request.form.get(\"changeAccess\") if changeAccess == None:", "request.form.get(\"changeAccess\") if changeAccess == None: changeAccess = \"\" db.update_member(member, changeName,", "= request.form.get(\"access\") access = int(access) if request.method == 'POST': if", "change this to any folder on your system ALLOWED_EXTENSIONS =", "def root(): return ('', 204) @app.route('/upload', methods=['GET', 'POST']) def upload_image():", "flask import Flask, request, redirect, Response import camera import firestore", "any folder on your system ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}", "access = request.form.get(\"access\") access = int(access) if request.method == 'POST':", "the uploaded image unknown_face_encodings = face_recognition.face_encodings(img)[0].tolist() db.add_member(name, access, unknown_face_encodings) return", "return Response(camera.gen_frames(), mimetype='multipart/x-mixed-replace; boundary=frame') @app.route('/recent_person') def recent_person(): return db.history_log.get_most_recent_member() if", "filename and \\ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS def detect_faces_in_image(name, access,", "access, file) return redirect('/video_feed') @app.route('/update', methods=['GET', 'POST']) def update(): db.encoding.update()", "db.encoding.update() name = request.form.get(\"name\") access = request.form.get(\"access\") access = int(access)", "root(): return ('', 204) @app.route('/upload', methods=['GET', 'POST']) def upload_image(): db.encoding.update()", "request.form.get(\"access\") access = int(access) if request.method == 'POST': if 'file'", "= face_recognition.face_encodings(img)[0].tolist() db.add_member(name, access, unknown_face_encodings) return ('', 204) @app.route('/') def", "changeAccess) return ('', 204) @app.route('/configuration', methods=['GET', 'POST']) def config(): db.config_camera_interval(int(request.form.get('cameraDuration')))", "import Flask, request, redirect, Response import camera import firestore as", "boundary=frame') @app.route('/recent_person') def recent_person(): return db.history_log.get_most_recent_member() if __name__ == \"__main__\":", "members(): print(type(db.encoding.get_names())) return str(db.encoding.get_names()) @app.route('/video_feed') def video_feed(): print('CAMERA RUN') return", "filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS def detect_faces_in_image(name, access, file_stream): # Load", "upload_image(): db.encoding.update() name = request.form.get(\"name\") access = request.form.get(\"access\") access =", "'jpg', 'jpeg'} app = Flask(__name__) def allowed_file(filename): return '.' in", "'jpeg'} app = Flask(__name__) def allowed_file(filename): return '.' in filename", "file_stream): # Load the uploaded image filed img = face_recognition.load_image_file(file_stream)", "'POST']) def config(): db.config_camera_interval(int(request.form.get('cameraDuration'))) return('', 204) @app.route('/members') def members(): print(type(db.encoding.get_names()))", "return detect_faces_in_image(name, access, file) return redirect('/video_feed') @app.route('/update', methods=['GET', 'POST']) def", "'file' not in request.files: return redirect(request.url) file = request.files['file'] if", "file) return redirect('/video_feed') @app.route('/update', methods=['GET', 'POST']) def update(): db.encoding.update() member", "return redirect('/video_feed') @app.route('/update', methods=['GET', 'POST']) def update(): db.encoding.update() member =", "= request.files['file'] if file.filename == '': return redirect(request.url) if file", "return ('', 204) @app.route('/') def root(): return ('', 204) @app.route('/upload',", "the uploaded image filed img = face_recognition.load_image_file(file_stream) # Get face", "= \"\" db.update_member(member, changeName, changeAccess) return ('', 204) @app.route('/configuration', methods=['GET',", "\"\" db.update_member(member, changeName, changeAccess) return ('', 204) @app.route('/configuration', methods=['GET', 'POST'])", "{'png', 'jpg', 'jpeg'} app = Flask(__name__) def allowed_file(filename): return '.'", "request.files['file'] if file.filename == '': return redirect(request.url) if file and", "def update(): db.encoding.update() member = request.form.get(\"updateMember\") changeName = request.form.get(\"changeName\") changeAccess", "redirect('/video_feed') @app.route('/update', methods=['GET', 'POST']) def update(): db.encoding.update() member = request.form.get(\"updateMember\")", "== '': return redirect(request.url) if file and allowed_file(file.filename): return detect_faces_in_image(name,", "as db # You can change this to any folder", "if changeAccess == None: changeAccess = \"\" db.update_member(member, changeName, changeAccess)", "in request.files: return redirect(request.url) file = request.files['file'] if file.filename ==", "camera import firestore as db # You can change this", "redirect(request.url) file = request.files['file'] if file.filename == '': return redirect(request.url)", "detect_faces_in_image(name, access, file_stream): # Load the uploaded image filed img", "@app.route('/') def root(): return ('', 204) @app.route('/upload', methods=['GET', 'POST']) def", "request.files: return redirect(request.url) file = request.files['file'] if file.filename == '':", "'': return redirect(request.url) if file and allowed_file(file.filename): return detect_faces_in_image(name, access,", "face_recognition from flask import Flask, request, redirect, Response import camera", "('', 204) @app.route('/configuration', methods=['GET', 'POST']) def config(): db.config_camera_interval(int(request.form.get('cameraDuration'))) return('', 204)", "return ('', 204) @app.route('/upload', methods=['GET', 'POST']) def upload_image(): db.encoding.update() name", "methods=['GET', 'POST']) def update(): db.encoding.update() member = request.form.get(\"updateMember\") changeName =", "mimetype='multipart/x-mixed-replace; boundary=frame') @app.route('/recent_person') def recent_person(): return db.history_log.get_most_recent_member() if __name__ ==", "204) @app.route('/') def root(): return ('', 204) @app.route('/upload', methods=['GET', 'POST'])", "db.encoding.update() member = request.form.get(\"updateMember\") changeName = request.form.get(\"changeName\") changeAccess = request.form.get(\"changeAccess\")", "request.form.get(\"name\") access = request.form.get(\"access\") access = int(access) if request.method ==", "@app.route('/update', methods=['GET', 'POST']) def update(): db.encoding.update() member = request.form.get(\"updateMember\") changeName", "redirect, Response import camera import firestore as db # You", "in the uploaded image unknown_face_encodings = face_recognition.face_encodings(img)[0].tolist() db.add_member(name, access, unknown_face_encodings)", "Load the uploaded image filed img = face_recognition.load_image_file(file_stream) # Get", "('', 204) @app.route('/upload', methods=['GET', 'POST']) def upload_image(): db.encoding.update() name =", "Response(camera.gen_frames(), mimetype='multipart/x-mixed-replace; boundary=frame') @app.route('/recent_person') def recent_person(): return db.history_log.get_most_recent_member() if __name__", "Flask, request, redirect, Response import camera import firestore as db", "faces in the uploaded image unknown_face_encodings = face_recognition.face_encodings(img)[0].tolist() db.add_member(name, access,", "204) @app.route('/members') def members(): print(type(db.encoding.get_names())) return str(db.encoding.get_names()) @app.route('/video_feed') def video_feed():", "'.' in filename and \\ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS def", "img = face_recognition.load_image_file(file_stream) # Get face encodings for any faces", "request, redirect, Response import camera import firestore as db #", "ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'} app = Flask(__name__) def allowed_file(filename):", "def config(): db.config_camera_interval(int(request.form.get('cameraDuration'))) return('', 204) @app.route('/members') def members(): print(type(db.encoding.get_names())) return", "redirect(request.url) if file and allowed_file(file.filename): return detect_faces_in_image(name, access, file) return", "return str(db.encoding.get_names()) @app.route('/video_feed') def video_feed(): print('CAMERA RUN') return Response(camera.gen_frames(), mimetype='multipart/x-mixed-replace;", "str(db.encoding.get_names()) @app.route('/video_feed') def video_feed(): print('CAMERA RUN') return Response(camera.gen_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')", "'POST': if 'file' not in request.files: return redirect(request.url) file =", "def upload_image(): db.encoding.update() name = request.form.get(\"name\") access = request.form.get(\"access\") access", "Flask(__name__) def allowed_file(filename): return '.' in filename and \\ filename.rsplit('.',", "# You can change this to any folder on your", "recent_person(): return db.history_log.get_most_recent_member() if __name__ == \"__main__\": app.run(host='0.0.0.0', port=5001, debug=True)", "methods=['GET', 'POST']) def config(): db.config_camera_interval(int(request.form.get('cameraDuration'))) return('', 204) @app.route('/members') def members():", "None: changeAccess = \"\" db.update_member(member, changeName, changeAccess) return ('', 204)" ]
[ "rate schedule. \"\"\" def __init__(self, optimizer, last_epoch=-1): super(ConstantLRSchedule, self).__init__(optimizer, lambda", "last_epoch=-1): self.warmup_steps = warmup_steps self.t_total = t_total super(WarmupLinearSchedule, self).__init__(optimizer, self.lr_lambda,", "= (int(l_pad), int(t_pad), int(r_pad), int(b_pad)) return padding class NewPad(object): def", "save_checkpoint(model, path): torch.save(model.state_dict(), path) def reverse_norm_image(image): MEAN = torch.tensor([0.485, 0.456,", "adjust_learning_rate(optimizer, epoch, lr): \"\"\"Sets the learning rate to the initial", "is different from default, learning rate follows cosine function after", "self.avg = 0 self.sum = 0 self.count = 0 def", "__init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0", "- h) / 2 l_pad = h_padding if h_padding %", "= warmup_steps self.t_total = t_total super(WarmupLinearSchedule, self).__init__(optimizer, self.lr_lambda, last_epoch=last_epoch) def", "last_epoch=-1): self.warmup_steps = warmup_steps super(WarmupConstantSchedule, self).__init__(optimizer, self.lr_lambda, last_epoch=last_epoch) def lr_lambda(self,", "** (epoch // 30)) for param_group in optimizer.param_groups: param_group['lr'] =", "to 1. after warmup_steps. \"\"\" def __init__(self, optimizer, warmup_steps, last_epoch=-1):", "str, tuple)) assert padding_mode in ['constant', 'edge', 'reflect', 'symmetric'] self.fill", "_: 1.0, last_epoch=last_epoch) class WarmupConstantSchedule(LambdaLR): \"\"\" Linear warmup and then", "STD = torch.tensor([0.229, 0.224, 0.225]) reverse_image = image * STD[:,", "+ 0.5 r_pad = h_padding if h_padding % 1 ==", "the initial LR decayed by 10 every 30 epochs\"\"\" lr", "format(self.fill, self.padding_mode) def find_device(): device = torch.device(\"cuda:0\" if torch.cuda.is_available() else", "+ 0.5 t_pad = v_padding if v_padding % 1 ==", "\"\"\" def __init__(self, optimizer, warmup_steps, t_total, cycles=.5, last_epoch=-1): self.warmup_steps =", "padding class NewPad(object): def __init__(self, fill=0, padding_mode='constant'): assert isinstance(fill, (numbers.Number,", "logger def adjust_learning_rate(optimizer, epoch, lr): \"\"\"Sets the learning rate to", "def __call__(self, img): \"\"\" Args: img (PIL Image): Image to", "read_json(data): with open(data) as f: return json.load(f) def save_json(data, path):", "cycles super(WarmupCosineSchedule, self).__init__(optimizer, self.lr_lambda, last_epoch=last_epoch) def lr_lambda(self, step): if step", "= padding_mode def __call__(self, img): \"\"\" Args: img (PIL Image):", "self.warmup_steps: return float(step) / float(max(1, self.warmup_steps)) return max(0.0, float(self.t_total -", "and then cosine decay. Linearly increases learning rate from 0", "self.count += n self.avg = self.sum / self.count class ConstantLRSchedule(LambdaLR):", "v_padding + 0.5 r_pad = h_padding if h_padding % 1", "setup_logger(): logger = logging.getLogger('train') logger.setLevel(logging.INFO) if len(logger.handlers) == 0: formatter", "\"\"\" Linear warmup and then cosine decay. Linearly increases learning", "def find_device(): device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\") return", "def __init__(self, optimizer, warmup_steps, t_total, last_epoch=-1): self.warmup_steps = warmup_steps self.t_total", "= fill self.padding_mode = padding_mode def __call__(self, img): \"\"\" Args:", "* STD[:, None, None] + MEAN[:, None, None] return reverse_image.permute(1,", "logging.Formatter('%(asctime)s | %(message)s') ch = logging.StreamHandler(stream=sys.stdout) ch.setFormatter(formatter) logger.addHandler(ch) return logger", "/ self.count class ConstantLRSchedule(LambdaLR): \"\"\" Constant learning rate schedule. \"\"\"", "from default, learning rate follows cosine function after warmup. \"\"\"", "constant. Linearly increases learning rate schedule from 0 to 1", "then cosine decay. Linearly increases learning rate from 0 to", "warmup_steps self.t_total = t_total self.cycles = cycles super(WarmupCosineSchedule, self).__init__(optimizer, self.lr_lambda,", "stores the average and current value\"\"\" def __init__(self): self.reset() def", "the learning rate to the initial LR decayed by 10", "LR decayed by 10 every 30 epochs\"\"\" lr = lr", "\"\"\" def __init__(self, optimizer, warmup_steps, last_epoch=-1): self.warmup_steps = warmup_steps super(WarmupConstantSchedule,", "optimizer.param_groups: param_group['lr'] = lr def save_checkpoint(model, path): torch.save(model.state_dict(), path) def", "numbers import torch import math import json import sys from", "= h_padding if h_padding % 1 == 0 else h_padding", "h_padding % 1 == 0 else h_padding - 0.5 b_pad", "self.fill, self.padding_mode) def __repr__(self): return self.__class__.__name__ + '(padding={0}, fill={1}, padding_mode={2})'.", "\"\"\" Args: img (PIL Image): Image to be padded. Returns:", "rate from 0 to 1 over `warmup_steps` training steps. Decreases", "if len(logger.handlers) == 0: formatter = logging.Formatter('%(asctime)s | %(message)s') ch", "== 0: formatter = logging.Formatter('%(asctime)s | %(message)s') ch = logging.StreamHandler(stream=sys.stdout)", "self.val = 0 self.avg = 0 self.sum = 0 self.count", "= torch.tensor([0.485, 0.456, 0.406]) STD = torch.tensor([0.229, 0.224, 0.225]) reverse_image", "json.load(f) def save_json(data, path): with open(path, 'w', encoding='utf-8') as f:", "f) def setup_logger(): logger = logging.getLogger('train') logger.setLevel(logging.INFO) if len(logger.handlers) ==", "< self.warmup_steps: return float(step) / float(max(1.0, self.warmup_steps)) # progress after", "0 self.sum = 0 self.count = 0 def update(self, val,", "epochs\"\"\" lr = lr * (0.1 ** (epoch // 30))", "and then constant. Linearly increases learning rate schedule from 0", "def save_checkpoint(model, path): torch.save(model.state_dict(), path) def reverse_norm_image(image): MEAN = torch.tensor([0.485,", "0.456, 0.406]) STD = torch.tensor([0.229, 0.224, 0.225]) reverse_image = image", "class ConstantLRSchedule(LambdaLR): \"\"\" Constant learning rate schedule. \"\"\" def __init__(self,", "% 1 == 0 else v_padding - 0.5 padding =", "= val self.sum += val * n self.count += n", "0.5 b_pad = v_padding if v_padding % 1 == 0", "int(t_pad), int(r_pad), int(b_pad)) return padding class NewPad(object): def __init__(self, fill=0,", "device def read_json(data): with open(data) as f: return json.load(f) def", "warmup_steps, last_epoch=-1): self.warmup_steps = warmup_steps super(WarmupConstantSchedule, self).__init__(optimizer, self.lr_lambda, last_epoch=last_epoch) def", "lr = lr * (0.1 ** (epoch // 30)) for", "return float(step) / float(max(1.0, self.warmup_steps)) # progress after warmup progress", "else v_padding - 0.5 padding = (int(l_pad), int(t_pad), int(r_pad), int(b_pad))", "float(max(1, self.warmup_steps)) return max(0.0, float(self.t_total - step) / float(max(1.0, self.t_total", "then constant. Linearly increases learning rate schedule from 0 to", "learning rate to the initial LR decayed by 10 every", "self.warmup_steps = warmup_steps self.t_total = t_total self.cycles = cycles super(WarmupCosineSchedule,", "10 every 30 epochs\"\"\" lr = lr * (0.1 **", "if torch.cuda.is_available() else \"cpu\") return device def read_json(data): with open(data)", "* n self.count += n self.avg = self.sum / self.count", "= t_total super(WarmupLinearSchedule, self).__init__(optimizer, self.lr_lambda, last_epoch=last_epoch) def lr_lambda(self, step): if", "to the initial LR decayed by 10 every 30 epochs\"\"\"", "learning rate follows cosine function after warmup. \"\"\" def __init__(self,", "over `warmup_steps` training steps. Keeps learning rate schedule equal to", "- warmup_steps` steps. \"\"\" def __init__(self, optimizer, warmup_steps, t_total, last_epoch=-1):", "last_epoch=last_epoch) class WarmupConstantSchedule(LambdaLR): \"\"\" Linear warmup and then constant. Linearly", "to be padded. Returns: PIL Image: Padded image. \"\"\" return", "If `cycles` (default=0.5) is different from default, learning rate follows", "torch.tensor([0.229, 0.224, 0.225]) reverse_image = image * STD[:, None, None]", "import torch import math import json import sys from torch.optim.lr_scheduler", "= 0 self.count = 0 def update(self, val, n=1): self.val", "\"\"\" Constant learning rate schedule. \"\"\" def __init__(self, optimizer, last_epoch=-1):", "\"cpu\") return device def read_json(data): with open(data) as f: return", "tuple)) assert padding_mode in ['constant', 'edge', 'reflect', 'symmetric'] self.fill =", "warmup. \"\"\" def __init__(self, optimizer, warmup_steps, t_total, cycles=.5, last_epoch=-1): self.warmup_steps", "numpy as np import logging import numbers import torch import", "/ float(max(1, self.warmup_steps)) return max(0.0, float(self.t_total - step) / float(max(1.0,", "with open(path, 'w', encoding='utf-8') as f: json.dump(data, f) def setup_logger():", "0.225]) reverse_image = image * STD[:, None, None] + MEAN[:,", "class AverageMeter(object): \"\"\"Computes and stores the average and current value\"\"\"", "device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\") return device def", "training steps. Keeps learning rate schedule equal to 1. after", "learning rate from 1. to 0. over remaining `t_total -", "= image * STD[:, None, None] + MEAN[:, None, None]", "if v_padding % 1 == 0 else v_padding - 0.5", "== 0 else h_padding - 0.5 b_pad = v_padding if", "float(step) / float(max(1.0, self.warmup_steps)) # progress after warmup progress =", "default, learning rate follows cosine function after warmup. \"\"\" def", "from 1. to 0. over remaining `t_total - warmup_steps` steps.", "warmup progress = float(step - self.warmup_steps) / float(max(1, self.t_total -", "logger.setLevel(logging.INFO) if len(logger.handlers) == 0: formatter = logging.Formatter('%(asctime)s | %(message)s')", "param_group in optimizer.param_groups: param_group['lr'] = lr def save_checkpoint(model, path): torch.save(model.state_dict(),", "Constant learning rate schedule. \"\"\" def __init__(self, optimizer, last_epoch=-1): super(ConstantLRSchedule,", "self.lr_lambda, last_epoch=last_epoch) def lr_lambda(self, step): if step < self.warmup_steps: return", "Args: img (PIL Image): Image to be padded. Returns: PIL", "to 0. over remaining `t_total - warmup_steps` steps. \"\"\" def", "import json import sys from torch.optim.lr_scheduler import LambdaLR from torchvision.transforms.functional", "__repr__(self): return self.__class__.__name__ + '(padding={0}, fill={1}, padding_mode={2})'. \\ format(self.fill, self.padding_mode)", "# progress after warmup progress = float(step - self.warmup_steps) /", "if step < self.warmup_steps: return float(step) / float(max(1.0, self.warmup_steps)) #", "math import json import sys from torch.optim.lr_scheduler import LambdaLR from", "0 self.avg = 0 self.sum = 0 self.count = 0", "/ float(max(1, self.t_total - self.warmup_steps)) return max(0.0, 0.5 * (1.", "< self.warmup_steps: return float(step) / float(max(1, self.warmup_steps)) return max(0.0, float(self.t_total", "return pad(img, get_padding(img), self.fill, self.padding_mode) def __repr__(self): return self.__class__.__name__ +", "training steps. Decreases learning rate from 1. to 0. over", "def get_padding(image): w, h = image.size max_wh = np.max([w, h])", "= (max_wh - w) / 2 v_padding = (max_wh -", "optimizer, last_epoch=-1): super(ConstantLRSchedule, self).__init__(optimizer, lambda _: 1.0, last_epoch=last_epoch) class WarmupConstantSchedule(LambdaLR):", "for param_group in optimizer.param_groups: param_group['lr'] = lr def save_checkpoint(model, path):", "t_total, last_epoch=-1): self.warmup_steps = warmup_steps self.t_total = t_total super(WarmupLinearSchedule, self).__init__(optimizer,", "30 epochs\"\"\" lr = lr * (0.1 ** (epoch //", "encoding='utf-8') as f: json.dump(data, f) def setup_logger(): logger = logging.getLogger('train')", "1.0, last_epoch=last_epoch) class WarmupConstantSchedule(LambdaLR): \"\"\" Linear warmup and then constant.", "def reverse_norm_image(image): MEAN = torch.tensor([0.485, 0.456, 0.406]) STD = torch.tensor([0.229,", "self.sum = 0 self.count = 0 def update(self, val, n=1):", "current value\"\"\" def __init__(self): self.reset() def reset(self): self.val = 0", "epoch, lr): \"\"\"Sets the learning rate to the initial LR", "rate to the initial LR decayed by 10 every 30", "step): if step < self.warmup_steps: return float(step) / float(max(1.0, self.warmup_steps))", "get_padding(image): w, h = image.size max_wh = np.max([w, h]) h_padding", "\"\"\"Computes and stores the average and current value\"\"\" def __init__(self):", "equal to 1. after warmup_steps. \"\"\" def __init__(self, optimizer, warmup_steps,", "r_pad = h_padding if h_padding % 1 == 0 else", "over remaining `t_total - warmup_steps` steps. \"\"\" def __init__(self, optimizer,", "if step < self.warmup_steps: return float(step) / float(max(1, self.warmup_steps)) return", "0 def update(self, val, n=1): self.val = val self.sum +=", "warmup_steps self.t_total = t_total super(WarmupLinearSchedule, self).__init__(optimizer, self.lr_lambda, last_epoch=last_epoch) def lr_lambda(self,", "be padded. Returns: PIL Image: Padded image. \"\"\" return pad(img,", "last_epoch=-1): super(ConstantLRSchedule, self).__init__(optimizer, lambda _: 1.0, last_epoch=last_epoch) class WarmupConstantSchedule(LambdaLR): \"\"\"", "= logging.StreamHandler(stream=sys.stdout) ch.setFormatter(formatter) logger.addHandler(ch) return logger def adjust_learning_rate(optimizer, epoch, lr):", "self.warmup_steps)) return max(0.0, 0.5 * (1. + math.cos(math.pi * float(self.cycles)", "n=1): self.val = val self.sum += val * n self.count", "1. after warmup_steps. \"\"\" def __init__(self, optimizer, warmup_steps, last_epoch=-1): self.warmup_steps", "warmup_steps, t_total, cycles=.5, last_epoch=-1): self.warmup_steps = warmup_steps self.t_total = t_total", "cosine curve. If `cycles` (default=0.5) is different from default, learning", "\"\"\" return pad(img, get_padding(img), self.fill, self.padding_mode) def __repr__(self): return self.__class__.__name__", "= warmup_steps super(WarmupConstantSchedule, self).__init__(optimizer, self.lr_lambda, last_epoch=last_epoch) def lr_lambda(self, step): if", "after warmup. \"\"\" def __init__(self, optimizer, warmup_steps, t_total, cycles=.5, last_epoch=-1):", "find_device(): device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\") return device", "self.warmup_steps)) return 1. class WarmupLinearSchedule(LambdaLR): \"\"\" Linear warmup and then", "padding_mode in ['constant', 'edge', 'reflect', 'symmetric'] self.fill = fill self.padding_mode", "= torch.tensor([0.229, 0.224, 0.225]) reverse_image = image * STD[:, None,", "0. over remaining `t_total - warmup_steps` steps following a cosine", "torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\") return device def read_json(data): with", "1. to 0. over remaining `t_total - warmup_steps` steps. \"\"\"", "= float(step - self.warmup_steps) / float(max(1, self.t_total - self.warmup_steps)) return", "'edge', 'reflect', 'symmetric'] self.fill = fill self.padding_mode = padding_mode def", "def adjust_learning_rate(optimizer, epoch, lr): \"\"\"Sets the learning rate to the", "2.0 * progress))) def get_padding(image): w, h = image.size max_wh", "logger.addHandler(ch) return logger def adjust_learning_rate(optimizer, epoch, lr): \"\"\"Sets the learning", "self.padding_mode = padding_mode def __call__(self, img): \"\"\" Args: img (PIL", "math.cos(math.pi * float(self.cycles) * 2.0 * progress))) def get_padding(image): w,", "padding_mode={2})'. \\ format(self.fill, self.padding_mode) def find_device(): device = torch.device(\"cuda:0\" if", "% 1 == 0 else v_padding + 0.5 r_pad =", "= lr * (0.1 ** (epoch // 30)) for param_group", "training steps. Linearly decreases learning rate from 1. to 0.", "| %(message)s') ch = logging.StreamHandler(stream=sys.stdout) ch.setFormatter(formatter) logger.addHandler(ch) return logger def", "0 self.count = 0 def update(self, val, n=1): self.val =", "1 == 0 else h_padding - 0.5 b_pad = v_padding", "learning rate from 0 to 1 over `warmup_steps` training steps.", "super(WarmupCosineSchedule, self).__init__(optimizer, self.lr_lambda, last_epoch=last_epoch) def lr_lambda(self, step): if step <", "h_padding if h_padding % 1 == 0 else h_padding -", "img (PIL Image): Image to be padded. Returns: PIL Image:", "padding = (int(l_pad), int(t_pad), int(r_pad), int(b_pad)) return padding class NewPad(object):", "lr_lambda(self, step): if step < self.warmup_steps: return float(step) / float(max(1,", "LambdaLR from torchvision.transforms.functional import pad class AverageMeter(object): \"\"\"Computes and stores", "assert padding_mode in ['constant', 'edge', 'reflect', 'symmetric'] self.fill = fill", "'w', encoding='utf-8') as f: json.dump(data, f) def setup_logger(): logger =", "(0.1 ** (epoch // 30)) for param_group in optimizer.param_groups: param_group['lr']", "/ 2 v_padding = (max_wh - h) / 2 l_pad", "image * STD[:, None, None] + MEAN[:, None, None] return", "= 0 self.sum = 0 self.count = 0 def update(self,", "b_pad = v_padding if v_padding % 1 == 0 else", "'symmetric'] self.fill = fill self.padding_mode = padding_mode def __call__(self, img):", "steps. Keeps learning rate schedule equal to 1. after warmup_steps.", "%(message)s') ch = logging.StreamHandler(stream=sys.stdout) ch.setFormatter(formatter) logger.addHandler(ch) return logger def adjust_learning_rate(optimizer,", "reset(self): self.val = 0 self.avg = 0 self.sum = 0", "(default=0.5) is different from default, learning rate follows cosine function", "steps. Decreases learning rate from 1. to 0. over remaining", "0 else h_padding - 0.5 b_pad = v_padding if v_padding", "class WarmupLinearSchedule(LambdaLR): \"\"\" Linear warmup and then linear decay. Linearly", "in ['constant', 'edge', 'reflect', 'symmetric'] self.fill = fill self.padding_mode =", "(numbers.Number, str, tuple)) assert padding_mode in ['constant', 'edge', 'reflect', 'symmetric']", "step < self.warmup_steps: return float(step) / float(max(1.0, self.warmup_steps)) return 1.", "param_group['lr'] = lr def save_checkpoint(model, path): torch.save(model.state_dict(), path) def reverse_norm_image(image):", "from 0 to 1 over `warmup_steps` training steps. Linearly decreases", "self.warmup_steps: return float(step) / float(max(1.0, self.warmup_steps)) return 1. class WarmupLinearSchedule(LambdaLR):", "% 1 == 0 else h_padding + 0.5 t_pad =", "return 1. class WarmupLinearSchedule(LambdaLR): \"\"\" Linear warmup and then linear", "`t_total - warmup_steps` steps. \"\"\" def __init__(self, optimizer, warmup_steps, t_total,", "optimizer, warmup_steps, last_epoch=-1): self.warmup_steps = warmup_steps super(WarmupConstantSchedule, self).__init__(optimizer, self.lr_lambda, last_epoch=last_epoch)", "from torchvision.transforms.functional import pad class AverageMeter(object): \"\"\"Computes and stores the", "image.size max_wh = np.max([w, h]) h_padding = (max_wh - w)", "to 1 over `warmup_steps` training steps. Keeps learning rate schedule", "Linearly increases learning rate schedule from 0 to 1 over", "w, h = image.size max_wh = np.max([w, h]) h_padding =", "path): with open(path, 'w', encoding='utf-8') as f: json.dump(data, f) def", "* (0.1 ** (epoch // 30)) for param_group in optimizer.param_groups:", "Padded image. \"\"\" return pad(img, get_padding(img), self.fill, self.padding_mode) def __repr__(self):", "steps following a cosine curve. If `cycles` (default=0.5) is different", "self.warmup_steps)) return max(0.0, float(self.t_total - step) / float(max(1.0, self.t_total -", "- self.warmup_steps))) class WarmupCosineSchedule(LambdaLR): \"\"\" Linear warmup and then cosine", "h_padding = (max_wh - w) / 2 v_padding = (max_wh", "as f: json.dump(data, f) def setup_logger(): logger = logging.getLogger('train') logger.setLevel(logging.INFO)", "`warmup_steps` training steps. Linearly decreases learning rate from 1. to", "float(max(1.0, self.warmup_steps)) return 1. class WarmupLinearSchedule(LambdaLR): \"\"\" Linear warmup and", "self.count = 0 def update(self, val, n=1): self.val = val", "ch = logging.StreamHandler(stream=sys.stdout) ch.setFormatter(formatter) logger.addHandler(ch) return logger def adjust_learning_rate(optimizer, epoch,", "l_pad = h_padding if h_padding % 1 == 0 else", "- 0.5 b_pad = v_padding if v_padding % 1 ==", "warmup_steps. \"\"\" def __init__(self, optimizer, warmup_steps, last_epoch=-1): self.warmup_steps = warmup_steps", "__init__(self, optimizer, warmup_steps, t_total, cycles=.5, last_epoch=-1): self.warmup_steps = warmup_steps self.t_total", "0 else h_padding + 0.5 t_pad = v_padding if v_padding", "= (max_wh - h) / 2 l_pad = h_padding if", "else v_padding + 0.5 r_pad = h_padding if h_padding %", "0 else v_padding - 0.5 padding = (int(l_pad), int(t_pad), int(r_pad),", "h_padding % 1 == 0 else h_padding + 0.5 t_pad", "from 1. to 0. over remaining `t_total - warmup_steps` steps", "torch.optim.lr_scheduler import LambdaLR from torchvision.transforms.functional import pad class AverageMeter(object): \"\"\"Computes", "assert isinstance(fill, (numbers.Number, str, tuple)) assert padding_mode in ['constant', 'edge',", "len(logger.handlers) == 0: formatter = logging.Formatter('%(asctime)s | %(message)s') ch =", "self.__class__.__name__ + '(padding={0}, fill={1}, padding_mode={2})'. \\ format(self.fill, self.padding_mode) def find_device():", "if v_padding % 1 == 0 else v_padding + 0.5", "else h_padding + 0.5 t_pad = v_padding if v_padding %", "AverageMeter(object): \"\"\"Computes and stores the average and current value\"\"\" def", "self.warmup_steps) / float(max(1, self.t_total - self.warmup_steps)) return max(0.0, 0.5 *", "over `warmup_steps` training steps. Linearly decreases learning rate from 1.", "over remaining `t_total - warmup_steps` steps following a cosine curve.", "== 0 else h_padding + 0.5 t_pad = v_padding if", "Linear warmup and then constant. Linearly increases learning rate schedule", "WarmupCosineSchedule(LambdaLR): \"\"\" Linear warmup and then cosine decay. Linearly increases", "self.val = val self.sum += val * n self.count +=", "return float(step) / float(max(1.0, self.warmup_steps)) return 1. class WarmupLinearSchedule(LambdaLR): \"\"\"", "= warmup_steps self.t_total = t_total self.cycles = cycles super(WarmupCosineSchedule, self).__init__(optimizer,", "(max_wh - w) / 2 v_padding = (max_wh - h)", "from 0 to 1 over `warmup_steps` training steps. Keeps learning", "val, n=1): self.val = val self.sum += val * n", "logging.getLogger('train') logger.setLevel(logging.INFO) if len(logger.handlers) == 0: formatter = logging.Formatter('%(asctime)s |", "1 == 0 else v_padding - 0.5 padding = (int(l_pad),", "n self.avg = self.sum / self.count class ConstantLRSchedule(LambdaLR): \"\"\" Constant", "update(self, val, n=1): self.val = val self.sum += val *", "self.count class ConstantLRSchedule(LambdaLR): \"\"\" Constant learning rate schedule. \"\"\" def", "schedule from 0 to 1 over `warmup_steps` training steps. Keeps", "reverse_image = image * STD[:, None, None] + MEAN[:, None,", "(1. + math.cos(math.pi * float(self.cycles) * 2.0 * progress))) def", "import math import json import sys from torch.optim.lr_scheduler import LambdaLR", "t_total super(WarmupLinearSchedule, self).__init__(optimizer, self.lr_lambda, last_epoch=last_epoch) def lr_lambda(self, step): if step", "+= val * n self.count += n self.avg = self.sum", "and stores the average and current value\"\"\" def __init__(self): self.reset()", "decreases learning rate from 1. to 0. over remaining `t_total", "def update(self, val, n=1): self.val = val self.sum += val", "pad(img, get_padding(img), self.fill, self.padding_mode) def __repr__(self): return self.__class__.__name__ + '(padding={0},", "pad class AverageMeter(object): \"\"\"Computes and stores the average and current", "\"\"\" Linear warmup and then constant. Linearly increases learning rate", "last_epoch=-1): self.warmup_steps = warmup_steps self.t_total = t_total self.cycles = cycles", "val self.sum += val * n self.count += n self.avg", "as np import logging import numbers import torch import math", "1 over `warmup_steps` training steps. Keeps learning rate schedule equal", "WarmupLinearSchedule(LambdaLR): \"\"\" Linear warmup and then linear decay. Linearly increases", "ConstantLRSchedule(LambdaLR): \"\"\" Constant learning rate schedule. \"\"\" def __init__(self, optimizer,", "lr def save_checkpoint(model, path): torch.save(model.state_dict(), path) def reverse_norm_image(image): MEAN =", "self.t_total - self.warmup_steps))) class WarmupCosineSchedule(LambdaLR): \"\"\" Linear warmup and then", "class NewPad(object): def __init__(self, fill=0, padding_mode='constant'): assert isinstance(fill, (numbers.Number, str,", "Image): Image to be padded. Returns: PIL Image: Padded image.", "= 0 def update(self, val, n=1): self.val = val self.sum", "self.sum / self.count class ConstantLRSchedule(LambdaLR): \"\"\" Constant learning rate schedule.", "warmup and then constant. Linearly increases learning rate schedule from", "`warmup_steps` training steps. Keeps learning rate schedule equal to 1.", "0. over remaining `t_total - warmup_steps` steps. \"\"\" def __init__(self,", "= image.size max_wh = np.max([w, h]) h_padding = (max_wh -", "v_padding % 1 == 0 else v_padding + 0.5 r_pad", "v_padding if v_padding % 1 == 0 else v_padding +", "self.fill = fill self.padding_mode = padding_mode def __call__(self, img): \"\"\"", "save_json(data, path): with open(path, 'w', encoding='utf-8') as f: json.dump(data, f)", "Returns: PIL Image: Padded image. \"\"\" return pad(img, get_padding(img), self.fill,", "if step < self.warmup_steps: return float(step) / float(max(1.0, self.warmup_steps)) return", "torch.save(model.state_dict(), path) def reverse_norm_image(image): MEAN = torch.tensor([0.485, 0.456, 0.406]) STD", "- 0.5 padding = (int(l_pad), int(t_pad), int(r_pad), int(b_pad)) return padding", "\\ format(self.fill, self.padding_mode) def find_device(): device = torch.device(\"cuda:0\" if torch.cuda.is_available()", "`warmup_steps` training steps. Decreases learning rate from 1. to 0.", "self).__init__(optimizer, lambda _: 1.0, last_epoch=last_epoch) class WarmupConstantSchedule(LambdaLR): \"\"\" Linear warmup", "import sys from torch.optim.lr_scheduler import LambdaLR from torchvision.transforms.functional import pad", "path) def reverse_norm_image(image): MEAN = torch.tensor([0.485, 0.456, 0.406]) STD =", "(max_wh - h) / 2 l_pad = h_padding if h_padding", "fill self.padding_mode = padding_mode def __call__(self, img): \"\"\" Args: img", "\"\"\" Linear warmup and then linear decay. Linearly increases learning", "progress after warmup progress = float(step - self.warmup_steps) / float(max(1,", "fill={1}, padding_mode={2})'. \\ format(self.fill, self.padding_mode) def find_device(): device = torch.device(\"cuda:0\"", "v_padding if v_padding % 1 == 0 else v_padding -", "max(0.0, 0.5 * (1. + math.cos(math.pi * float(self.cycles) * 2.0", "super(WarmupConstantSchedule, self).__init__(optimizer, self.lr_lambda, last_epoch=last_epoch) def lr_lambda(self, step): if step <", "steps. Linearly decreases learning rate from 1. to 0. over", "def __init__(self, optimizer, warmup_steps, t_total, cycles=.5, last_epoch=-1): self.warmup_steps = warmup_steps", "progress = float(step - self.warmup_steps) / float(max(1, self.t_total - self.warmup_steps))", "self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum", "torch import math import json import sys from torch.optim.lr_scheduler import", "['constant', 'edge', 'reflect', 'symmetric'] self.fill = fill self.padding_mode = padding_mode", "with open(data) as f: return json.load(f) def save_json(data, path): with", "PIL Image: Padded image. \"\"\" return pad(img, get_padding(img), self.fill, self.padding_mode)", "rate schedule from 0 to 1 over `warmup_steps` training steps.", "optimizer, warmup_steps, t_total, last_epoch=-1): self.warmup_steps = warmup_steps self.t_total = t_total", "after warmup_steps. \"\"\" def __init__(self, optimizer, warmup_steps, last_epoch=-1): self.warmup_steps =", "Keeps learning rate schedule equal to 1. after warmup_steps. \"\"\"", "n self.count += n self.avg = self.sum / self.count class", "t_total, cycles=.5, last_epoch=-1): self.warmup_steps = warmup_steps self.t_total = t_total self.cycles", "val * n self.count += n self.avg = self.sum /", "(int(l_pad), int(t_pad), int(r_pad), int(b_pad)) return padding class NewPad(object): def __init__(self,", "def __init__(self, fill=0, padding_mode='constant'): assert isinstance(fill, (numbers.Number, str, tuple)) assert", "super(ConstantLRSchedule, self).__init__(optimizer, lambda _: 1.0, last_epoch=last_epoch) class WarmupConstantSchedule(LambdaLR): \"\"\" Linear", "int(r_pad), int(b_pad)) return padding class NewPad(object): def __init__(self, fill=0, padding_mode='constant'):", "def read_json(data): with open(data) as f: return json.load(f) def save_json(data,", "0.5 * (1. + math.cos(math.pi * float(self.cycles) * 2.0 *", "as f: return json.load(f) def save_json(data, path): with open(path, 'w',", "super(WarmupLinearSchedule, self).__init__(optimizer, self.lr_lambda, last_epoch=last_epoch) def lr_lambda(self, step): if step <", "ch.setFormatter(formatter) logger.addHandler(ch) return logger def adjust_learning_rate(optimizer, epoch, lr): \"\"\"Sets the", "h_padding if h_padding % 1 == 0 else h_padding +", "= cycles super(WarmupCosineSchedule, self).__init__(optimizer, self.lr_lambda, last_epoch=last_epoch) def lr_lambda(self, step): if", "learning rate schedule from 0 to 1 over `warmup_steps` training", "+ math.cos(math.pi * float(self.cycles) * 2.0 * progress))) def get_padding(image):", "def reset(self): self.val = 0 self.avg = 0 self.sum =", "every 30 epochs\"\"\" lr = lr * (0.1 ** (epoch", "== 0 else v_padding + 0.5 r_pad = h_padding if", "last_epoch=last_epoch) def lr_lambda(self, step): if step < self.warmup_steps: return float(step)", "rate from 1. to 0. over remaining `t_total - warmup_steps`", "2 v_padding = (max_wh - h) / 2 l_pad =", "1 == 0 else v_padding + 0.5 r_pad = h_padding", "formatter = logging.Formatter('%(asctime)s | %(message)s') ch = logging.StreamHandler(stream=sys.stdout) ch.setFormatter(formatter) logger.addHandler(ch)", "and current value\"\"\" def __init__(self): self.reset() def reset(self): self.val =", "f: return json.load(f) def save_json(data, path): with open(path, 'w', encoding='utf-8')", "0 to 1 over `warmup_steps` training steps. Linearly decreases learning", "import logging import numbers import torch import math import json", "+ '(padding={0}, fill={1}, padding_mode={2})'. \\ format(self.fill, self.padding_mode) def find_device(): device", "self.warmup_steps)) # progress after warmup progress = float(step - self.warmup_steps)", "== 0 else v_padding - 0.5 padding = (int(l_pad), int(t_pad),", "`cycles` (default=0.5) is different from default, learning rate follows cosine", "float(max(1, self.t_total - self.warmup_steps)) return max(0.0, 0.5 * (1. +", "from torch.optim.lr_scheduler import LambdaLR from torchvision.transforms.functional import pad class AverageMeter(object):", "self.sum += val * n self.count += n self.avg =", "reverse_norm_image(image): MEAN = torch.tensor([0.485, 0.456, 0.406]) STD = torch.tensor([0.229, 0.224,", "def setup_logger(): logger = logging.getLogger('train') logger.setLevel(logging.INFO) if len(logger.handlers) == 0:", "def __init__(self, optimizer, last_epoch=-1): super(ConstantLRSchedule, self).__init__(optimizer, lambda _: 1.0, last_epoch=last_epoch)", "to 1 over `warmup_steps` training steps. Linearly decreases learning rate", "image. \"\"\" return pad(img, get_padding(img), self.fill, self.padding_mode) def __repr__(self): return", "* float(self.cycles) * 2.0 * progress))) def get_padding(image): w, h", "return json.load(f) def save_json(data, path): with open(path, 'w', encoding='utf-8') as", "% 1 == 0 else h_padding - 0.5 b_pad =", "/ float(max(1.0, self.warmup_steps)) return 1. class WarmupLinearSchedule(LambdaLR): \"\"\" Linear warmup", "None, None] + MEAN[:, None, None] return reverse_image.permute(1, 2, 0).cpu().numpy()", "1 == 0 else h_padding + 0.5 t_pad = v_padding", "then linear decay. Linearly increases learning rate from 0 to", "class WarmupConstantSchedule(LambdaLR): \"\"\" Linear warmup and then constant. Linearly increases", "`t_total - warmup_steps` steps following a cosine curve. If `cycles`", "remaining `t_total - warmup_steps` steps. \"\"\" def __init__(self, optimizer, warmup_steps,", "0 to 1 over `warmup_steps` training steps. Decreases learning rate", "increases learning rate from 0 to 1 over `warmup_steps` training", "lr): \"\"\"Sets the learning rate to the initial LR decayed", "warmup_steps` steps. \"\"\" def __init__(self, optimizer, warmup_steps, t_total, last_epoch=-1): self.warmup_steps", "else \"cpu\") return device def read_json(data): with open(data) as f:", "padded. Returns: PIL Image: Padded image. \"\"\" return pad(img, get_padding(img),", "by 10 every 30 epochs\"\"\" lr = lr * (0.1", "int(b_pad)) return padding class NewPad(object): def __init__(self, fill=0, padding_mode='constant'): assert", "0 else v_padding + 0.5 r_pad = h_padding if h_padding", "- self.warmup_steps)) return max(0.0, 0.5 * (1. + math.cos(math.pi *", "self.t_total = t_total super(WarmupLinearSchedule, self).__init__(optimizer, self.lr_lambda, last_epoch=last_epoch) def lr_lambda(self, step):", "return device def read_json(data): with open(data) as f: return json.load(f)", "warmup_steps, t_total, last_epoch=-1): self.warmup_steps = warmup_steps self.t_total = t_total super(WarmupLinearSchedule,", "self.t_total - self.warmup_steps)) return max(0.0, 0.5 * (1. + math.cos(math.pi", "h = image.size max_wh = np.max([w, h]) h_padding = (max_wh", "steps. \"\"\" def __init__(self, optimizer, warmup_steps, t_total, last_epoch=-1): self.warmup_steps =", "lr * (0.1 ** (epoch // 30)) for param_group in", "= lr def save_checkpoint(model, path): torch.save(model.state_dict(), path) def reverse_norm_image(image): MEAN", "- warmup_steps` steps following a cosine curve. If `cycles` (default=0.5)", "h) / 2 l_pad = h_padding if h_padding % 1", "return padding class NewPad(object): def __init__(self, fill=0, padding_mode='constant'): assert isinstance(fill,", "schedule. \"\"\" def __init__(self, optimizer, last_epoch=-1): super(ConstantLRSchedule, self).__init__(optimizer, lambda _:", "0.406]) STD = torch.tensor([0.229, 0.224, 0.225]) reverse_image = image *", "v_padding = (max_wh - h) / 2 l_pad = h_padding", "step) / float(max(1.0, self.t_total - self.warmup_steps))) class WarmupCosineSchedule(LambdaLR): \"\"\" Linear", "step < self.warmup_steps: return float(step) / float(max(1.0, self.warmup_steps)) # progress", "def lr_lambda(self, step): if step < self.warmup_steps: return float(step) /", "sys from torch.optim.lr_scheduler import LambdaLR from torchvision.transforms.functional import pad class", "float(max(1.0, self.warmup_steps)) # progress after warmup progress = float(step -", "self.t_total = t_total self.cycles = cycles super(WarmupCosineSchedule, self).__init__(optimizer, self.lr_lambda, last_epoch=last_epoch)", "Linear warmup and then linear decay. Linearly increases learning rate", "0.5 padding = (int(l_pad), int(t_pad), int(r_pad), int(b_pad)) return padding class", "in optimizer.param_groups: param_group['lr'] = lr def save_checkpoint(model, path): torch.save(model.state_dict(), path)", "torch.cuda.is_available() else \"cpu\") return device def read_json(data): with open(data) as", "+= n self.avg = self.sum / self.count class ConstantLRSchedule(LambdaLR): \"\"\"", "Linearly decreases learning rate from 1. to 0. over remaining", "f: json.dump(data, f) def setup_logger(): logger = logging.getLogger('train') logger.setLevel(logging.INFO) if", "decay. Linearly increases learning rate from 0 to 1 over", "padding_mode def __call__(self, img): \"\"\" Args: img (PIL Image): Image", "and then linear decay. Linearly increases learning rate from 0", "h]) h_padding = (max_wh - w) / 2 v_padding =", "1 over `warmup_steps` training steps. Linearly decreases learning rate from", "over `warmup_steps` training steps. Decreases learning rate from 1. to", "schedule equal to 1. after warmup_steps. \"\"\" def __init__(self, optimizer,", "self.warmup_steps = warmup_steps self.t_total = t_total super(WarmupLinearSchedule, self).__init__(optimizer, self.lr_lambda, last_epoch=last_epoch)", "Linearly increases learning rate from 0 to 1 over `warmup_steps`", "else h_padding - 0.5 b_pad = v_padding if v_padding %", "* (1. + math.cos(math.pi * float(self.cycles) * 2.0 * progress)))", "1. class WarmupLinearSchedule(LambdaLR): \"\"\" Linear warmup and then linear decay.", "30)) for param_group in optimizer.param_groups: param_group['lr'] = lr def save_checkpoint(model,", "rate follows cosine function after warmup. \"\"\" def __init__(self, optimizer,", "warmup_steps` steps following a cosine curve. If `cycles` (default=0.5) is", "float(step - self.warmup_steps) / float(max(1, self.t_total - self.warmup_steps)) return max(0.0,", "cosine decay. Linearly increases learning rate from 0 to 1", "remaining `t_total - warmup_steps` steps following a cosine curve. If", "= 0 self.avg = 0 self.sum = 0 self.count =", "a cosine curve. If `cycles` (default=0.5) is different from default,", "initial LR decayed by 10 every 30 epochs\"\"\" lr =", "max_wh = np.max([w, h]) h_padding = (max_wh - w) /", "def __init__(self, optimizer, warmup_steps, last_epoch=-1): self.warmup_steps = warmup_steps super(WarmupConstantSchedule, self).__init__(optimizer,", "fill=0, padding_mode='constant'): assert isinstance(fill, (numbers.Number, str, tuple)) assert padding_mode in", "\"\"\" def __init__(self, optimizer, last_epoch=-1): super(ConstantLRSchedule, self).__init__(optimizer, lambda _: 1.0,", "1. to 0. over remaining `t_total - warmup_steps` steps following", "\"\"\" def __init__(self, optimizer, warmup_steps, t_total, last_epoch=-1): self.warmup_steps = warmup_steps", "w) / 2 v_padding = (max_wh - h) / 2", "Image to be padded. Returns: PIL Image: Padded image. \"\"\"", "the average and current value\"\"\" def __init__(self): self.reset() def reset(self):", "linear decay. Linearly increases learning rate from 0 to 1", "def __init__(self): self.reset() def reset(self): self.val = 0 self.avg =", "MEAN = torch.tensor([0.485, 0.456, 0.406]) STD = torch.tensor([0.229, 0.224, 0.225])", "self.padding_mode) def find_device(): device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")", "return self.__class__.__name__ + '(padding={0}, fill={1}, padding_mode={2})'. \\ format(self.fill, self.padding_mode) def", "self.warmup_steps = warmup_steps super(WarmupConstantSchedule, self).__init__(optimizer, self.lr_lambda, last_epoch=last_epoch) def lr_lambda(self, step):", "< self.warmup_steps: return float(step) / float(max(1.0, self.warmup_steps)) return 1. class", "* 2.0 * progress))) def get_padding(image): w, h = image.size", "rate from 0 to 1 over `warmup_steps` training steps. Linearly", "learning rate schedule. \"\"\" def __init__(self, optimizer, last_epoch=-1): super(ConstantLRSchedule, self).__init__(optimizer,", "to 1 over `warmup_steps` training steps. Decreases learning rate from", "- step) / float(max(1.0, self.t_total - self.warmup_steps))) class WarmupCosineSchedule(LambdaLR): \"\"\"", "float(step) / float(max(1, self.warmup_steps)) return max(0.0, float(self.t_total - step) /", "self).__init__(optimizer, self.lr_lambda, last_epoch=last_epoch) def lr_lambda(self, step): if step < self.warmup_steps:", "2 l_pad = h_padding if h_padding % 1 == 0", "'(padding={0}, fill={1}, padding_mode={2})'. \\ format(self.fill, self.padding_mode) def find_device(): device =", "lambda _: 1.0, last_epoch=last_epoch) class WarmupConstantSchedule(LambdaLR): \"\"\" Linear warmup and", "self.warmup_steps))) class WarmupCosineSchedule(LambdaLR): \"\"\" Linear warmup and then cosine decay.", "(PIL Image): Image to be padded. Returns: PIL Image: Padded", "float(max(1.0, self.t_total - self.warmup_steps))) class WarmupCosineSchedule(LambdaLR): \"\"\" Linear warmup and", "float(step) / float(max(1.0, self.warmup_steps)) return 1. class WarmupLinearSchedule(LambdaLR): \"\"\" Linear", "curve. If `cycles` (default=0.5) is different from default, learning rate", "Decreases learning rate from 1. to 0. over remaining `t_total", "1 over `warmup_steps` training steps. Decreases learning rate from 1.", "value\"\"\" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg", "progress))) def get_padding(image): w, h = image.size max_wh = np.max([w,", "v_padding - 0.5 padding = (int(l_pad), int(t_pad), int(r_pad), int(b_pad)) return", "max(0.0, float(self.t_total - step) / float(max(1.0, self.t_total - self.warmup_steps))) class", "'reflect', 'symmetric'] self.fill = fill self.padding_mode = padding_mode def __call__(self,", "self.padding_mode) def __repr__(self): return self.__class__.__name__ + '(padding={0}, fill={1}, padding_mode={2})'. \\", "img): \"\"\" Args: img (PIL Image): Image to be padded.", "0.5 r_pad = h_padding if h_padding % 1 == 0", "Linear warmup and then cosine decay. Linearly increases learning rate", "import numpy as np import logging import numbers import torch", "get_padding(img), self.fill, self.padding_mode) def __repr__(self): return self.__class__.__name__ + '(padding={0}, fill={1},", "warmup and then linear decay. Linearly increases learning rate from", "logger = logging.getLogger('train') logger.setLevel(logging.INFO) if len(logger.handlers) == 0: formatter =", "= logging.getLogger('train') logger.setLevel(logging.INFO) if len(logger.handlers) == 0: formatter = logging.Formatter('%(asctime)s", "step < self.warmup_steps: return float(step) / float(max(1, self.warmup_steps)) return max(0.0,", "float(self.cycles) * 2.0 * progress))) def get_padding(image): w, h =", "/ 2 l_pad = h_padding if h_padding % 1 ==", "return max(0.0, 0.5 * (1. + math.cos(math.pi * float(self.cycles) *", "return logger def adjust_learning_rate(optimizer, epoch, lr): \"\"\"Sets the learning rate", "import LambdaLR from torchvision.transforms.functional import pad class AverageMeter(object): \"\"\"Computes and", "learning rate schedule equal to 1. after warmup_steps. \"\"\" def", "open(data) as f: return json.load(f) def save_json(data, path): with open(path,", "warmup and then cosine decay. Linearly increases learning rate from", "__init__(self, optimizer, warmup_steps, last_epoch=-1): self.warmup_steps = warmup_steps super(WarmupConstantSchedule, self).__init__(optimizer, self.lr_lambda,", "following a cosine curve. If `cycles` (default=0.5) is different from", "to 0. over remaining `t_total - warmup_steps` steps following a", "h_padding - 0.5 b_pad = v_padding if v_padding % 1", "t_total self.cycles = cycles super(WarmupCosineSchedule, self).__init__(optimizer, self.lr_lambda, last_epoch=last_epoch) def lr_lambda(self,", "torch.tensor([0.485, 0.456, 0.406]) STD = torch.tensor([0.229, 0.224, 0.225]) reverse_image =", "/ float(max(1.0, self.warmup_steps)) # progress after warmup progress = float(step", "__call__(self, img): \"\"\" Args: img (PIL Image): Image to be", "0.224, 0.225]) reverse_image = image * STD[:, None, None] +", "def __repr__(self): return self.__class__.__name__ + '(padding={0}, fill={1}, padding_mode={2})'. \\ format(self.fill,", "* progress))) def get_padding(image): w, h = image.size max_wh =", "logging.StreamHandler(stream=sys.stdout) ch.setFormatter(formatter) logger.addHandler(ch) return logger def adjust_learning_rate(optimizer, epoch, lr): \"\"\"Sets", "self.avg = self.sum / self.count class ConstantLRSchedule(LambdaLR): \"\"\" Constant learning", "increases learning rate schedule from 0 to 1 over `warmup_steps`", "v_padding % 1 == 0 else v_padding - 0.5 padding", "import numbers import torch import math import json import sys", "h_padding + 0.5 t_pad = v_padding if v_padding % 1", "\"\"\"Sets the learning rate to the initial LR decayed by", "average and current value\"\"\" def __init__(self): self.reset() def reset(self): self.val", "json import sys from torch.optim.lr_scheduler import LambdaLR from torchvision.transforms.functional import", "open(path, 'w', encoding='utf-8') as f: json.dump(data, f) def setup_logger(): logger", "warmup_steps super(WarmupConstantSchedule, self).__init__(optimizer, self.lr_lambda, last_epoch=last_epoch) def lr_lambda(self, step): if step", "NewPad(object): def __init__(self, fill=0, padding_mode='constant'): assert isinstance(fill, (numbers.Number, str, tuple))", "Image: Padded image. \"\"\" return pad(img, get_padding(img), self.fill, self.padding_mode) def", "= v_padding if v_padding % 1 == 0 else v_padding", "0 to 1 over `warmup_steps` training steps. Keeps learning rate", "0.5 t_pad = v_padding if v_padding % 1 == 0", "decayed by 10 every 30 epochs\"\"\" lr = lr *", "__init__(self, optimizer, warmup_steps, t_total, last_epoch=-1): self.warmup_steps = warmup_steps self.t_total =", "= np.max([w, h]) h_padding = (max_wh - w) / 2", "isinstance(fill, (numbers.Number, str, tuple)) assert padding_mode in ['constant', 'edge', 'reflect',", "different from default, learning rate follows cosine function after warmup.", "// 30)) for param_group in optimizer.param_groups: param_group['lr'] = lr def", "self.warmup_steps: return float(step) / float(max(1.0, self.warmup_steps)) # progress after warmup", "= self.sum / self.count class ConstantLRSchedule(LambdaLR): \"\"\" Constant learning rate", "torchvision.transforms.functional import pad class AverageMeter(object): \"\"\"Computes and stores the average", "follows cosine function after warmup. \"\"\" def __init__(self, optimizer, warmup_steps,", "cycles=.5, last_epoch=-1): self.warmup_steps = warmup_steps self.t_total = t_total self.cycles =", "import pad class AverageMeter(object): \"\"\"Computes and stores the average and", "float(self.t_total - step) / float(max(1.0, self.t_total - self.warmup_steps))) class WarmupCosineSchedule(LambdaLR):", "json.dump(data, f) def setup_logger(): logger = logging.getLogger('train') logger.setLevel(logging.INFO) if len(logger.handlers)", "if h_padding % 1 == 0 else h_padding - 0.5", "np.max([w, h]) h_padding = (max_wh - w) / 2 v_padding", "/ float(max(1.0, self.t_total - self.warmup_steps))) class WarmupCosineSchedule(LambdaLR): \"\"\" Linear warmup", "def save_json(data, path): with open(path, 'w', encoding='utf-8') as f: json.dump(data,", "optimizer, warmup_steps, t_total, cycles=.5, last_epoch=-1): self.warmup_steps = warmup_steps self.t_total =", "0: formatter = logging.Formatter('%(asctime)s | %(message)s') ch = logging.StreamHandler(stream=sys.stdout) ch.setFormatter(formatter)", "return float(step) / float(max(1, self.warmup_steps)) return max(0.0, float(self.t_total - step)", "np import logging import numbers import torch import math import", "= logging.Formatter('%(asctime)s | %(message)s') ch = logging.StreamHandler(stream=sys.stdout) ch.setFormatter(formatter) logger.addHandler(ch) return", "step): if step < self.warmup_steps: return float(step) / float(max(1, self.warmup_steps))", "after warmup progress = float(step - self.warmup_steps) / float(max(1, self.t_total", "function after warmup. \"\"\" def __init__(self, optimizer, warmup_steps, t_total, cycles=.5,", "WarmupConstantSchedule(LambdaLR): \"\"\" Linear warmup and then constant. Linearly increases learning", "return max(0.0, float(self.t_total - step) / float(max(1.0, self.t_total - self.warmup_steps)))", "- w) / 2 v_padding = (max_wh - h) /", "self.cycles = cycles super(WarmupCosineSchedule, self).__init__(optimizer, self.lr_lambda, last_epoch=last_epoch) def lr_lambda(self, step):", "lr_lambda(self, step): if step < self.warmup_steps: return float(step) / float(max(1.0,", "__init__(self, optimizer, last_epoch=-1): super(ConstantLRSchedule, self).__init__(optimizer, lambda _: 1.0, last_epoch=last_epoch) class", "rate schedule equal to 1. after warmup_steps. \"\"\" def __init__(self,", "padding_mode='constant'): assert isinstance(fill, (numbers.Number, str, tuple)) assert padding_mode in ['constant',", "(epoch // 30)) for param_group in optimizer.param_groups: param_group['lr'] = lr", "__init__(self, fill=0, padding_mode='constant'): assert isinstance(fill, (numbers.Number, str, tuple)) assert padding_mode", "t_pad = v_padding if v_padding % 1 == 0 else", "class WarmupCosineSchedule(LambdaLR): \"\"\" Linear warmup and then cosine decay. Linearly", "cosine function after warmup. \"\"\" def __init__(self, optimizer, warmup_steps, t_total,", "- self.warmup_steps) / float(max(1, self.t_total - self.warmup_steps)) return max(0.0, 0.5", "path): torch.save(model.state_dict(), path) def reverse_norm_image(image): MEAN = torch.tensor([0.485, 0.456, 0.406])", "= torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\") return device def read_json(data):", "logging import numbers import torch import math import json import", "if h_padding % 1 == 0 else h_padding + 0.5", "from 0 to 1 over `warmup_steps` training steps. Decreases learning", "= t_total self.cycles = cycles super(WarmupCosineSchedule, self).__init__(optimizer, self.lr_lambda, last_epoch=last_epoch) def", "STD[:, None, None] + MEAN[:, None, None] return reverse_image.permute(1, 2," ]
[ "test_case def test_assert_raises_without_msg(test_case): node = extract_node(\"self.assertRaises(Exception)\") with test_case.assertAddsMessages(create_message(test_case.CHECKER_CLASS.name, node)): test_case.walk(node)", "@pytest.fixture(scope=\"module\") def test_case(): import pylint.testutils from pylint_plugins import AssertRaisesWithoutMsg class", "class TestAssertRaisesWithoutMsg(pylint.testutils.CheckerTestCase): CHECKER_CLASS = AssertRaisesWithoutMsg test_case = TestAssertRaisesWithoutMsg() test_case.setup_method() return", "CHECKER_CLASS = AssertRaisesWithoutMsg test_case = TestAssertRaisesWithoutMsg() test_case.setup_method() return test_case def", "test_case = TestAssertRaisesWithoutMsg() test_case.setup_method() return test_case def test_assert_raises_without_msg(test_case): node =", "AssertRaisesWithoutMsg test_case = TestAssertRaisesWithoutMsg() test_case.setup_method() return test_case def test_assert_raises_without_msg(test_case): node", "test_case.walk(node) node = extract_node(\"self.assertRaises(Exception, msg='test')\") with test_case.assertNoMessages(): test_case.walk(node) node =", "= extract_node(\"self.assertRaises(Exception, msg='test')\") with test_case.assertNoMessages(): test_case.walk(node) node = extract_node(\"pandas.assertRaises(Exception)\") with", "= AssertRaisesWithoutMsg test_case = TestAssertRaisesWithoutMsg() test_case.setup_method() return test_case def test_assert_raises_without_msg(test_case):", "skip_if_pylint_unavailable pytestmark = skip_if_pylint_unavailable() @pytest.fixture(scope=\"module\") def test_case(): import pylint.testutils from", "skip_if_pylint_unavailable() @pytest.fixture(scope=\"module\") def test_case(): import pylint.testutils from pylint_plugins import AssertRaisesWithoutMsg", "def test_case(): import pylint.testutils from pylint_plugins import AssertRaisesWithoutMsg class TestAssertRaisesWithoutMsg(pylint.testutils.CheckerTestCase):", "node = extract_node(\"self.assertRaises(Exception)\") with test_case.assertAddsMessages(create_message(test_case.CHECKER_CLASS.name, node)): test_case.walk(node) node = extract_node(\"self.assertRaises(Exception,", "test_case.assertAddsMessages(create_message(test_case.CHECKER_CLASS.name, node)): test_case.walk(node) node = extract_node(\"self.assertRaises(Exception, msg='test')\") with test_case.assertNoMessages(): test_case.walk(node)", "test_assert_raises_without_msg(test_case): node = extract_node(\"self.assertRaises(Exception)\") with test_case.assertAddsMessages(create_message(test_case.CHECKER_CLASS.name, node)): test_case.walk(node) node =", "with test_case.assertAddsMessages(create_message(test_case.CHECKER_CLASS.name, node)): test_case.walk(node) node = extract_node(\"self.assertRaises(Exception, msg='test')\") with test_case.assertNoMessages():", "node = extract_node(\"self.assertRaises(Exception, msg='test')\") with test_case.assertNoMessages(): test_case.walk(node) node = extract_node(\"pandas.assertRaises(Exception)\")", "from pylint_plugins import AssertRaisesWithoutMsg class TestAssertRaisesWithoutMsg(pylint.testutils.CheckerTestCase): CHECKER_CLASS = AssertRaisesWithoutMsg test_case", "= extract_node(\"self.assertRaises(Exception)\") with test_case.assertAddsMessages(create_message(test_case.CHECKER_CLASS.name, node)): test_case.walk(node) node = extract_node(\"self.assertRaises(Exception, msg='test')\")", "AssertRaisesWithoutMsg class TestAssertRaisesWithoutMsg(pylint.testutils.CheckerTestCase): CHECKER_CLASS = AssertRaisesWithoutMsg test_case = TestAssertRaisesWithoutMsg() test_case.setup_method()", "def test_assert_raises_without_msg(test_case): node = extract_node(\"self.assertRaises(Exception)\") with test_case.assertAddsMessages(create_message(test_case.CHECKER_CLASS.name, node)): test_case.walk(node) node", "return test_case def test_assert_raises_without_msg(test_case): node = extract_node(\"self.assertRaises(Exception)\") with test_case.assertAddsMessages(create_message(test_case.CHECKER_CLASS.name, node)):", "import create_message, extract_node, skip_if_pylint_unavailable pytestmark = skip_if_pylint_unavailable() @pytest.fixture(scope=\"module\") def test_case():", "extract_node, skip_if_pylint_unavailable pytestmark = skip_if_pylint_unavailable() @pytest.fixture(scope=\"module\") def test_case(): import pylint.testutils", "pytestmark = skip_if_pylint_unavailable() @pytest.fixture(scope=\"module\") def test_case(): import pylint.testutils from pylint_plugins", "test_case(): import pylint.testutils from pylint_plugins import AssertRaisesWithoutMsg class TestAssertRaisesWithoutMsg(pylint.testutils.CheckerTestCase): CHECKER_CLASS", "pylint_plugins import AssertRaisesWithoutMsg class TestAssertRaisesWithoutMsg(pylint.testutils.CheckerTestCase): CHECKER_CLASS = AssertRaisesWithoutMsg test_case =", "node)): test_case.walk(node) node = extract_node(\"self.assertRaises(Exception, msg='test')\") with test_case.assertNoMessages(): test_case.walk(node) node", "= skip_if_pylint_unavailable() @pytest.fixture(scope=\"module\") def test_case(): import pylint.testutils from pylint_plugins import", "= TestAssertRaisesWithoutMsg() test_case.setup_method() return test_case def test_assert_raises_without_msg(test_case): node = extract_node(\"self.assertRaises(Exception)\")", "import AssertRaisesWithoutMsg class TestAssertRaisesWithoutMsg(pylint.testutils.CheckerTestCase): CHECKER_CLASS = AssertRaisesWithoutMsg test_case = TestAssertRaisesWithoutMsg()", "TestAssertRaisesWithoutMsg(pylint.testutils.CheckerTestCase): CHECKER_CLASS = AssertRaisesWithoutMsg test_case = TestAssertRaisesWithoutMsg() test_case.setup_method() return test_case", "extract_node(\"self.assertRaises(Exception, msg='test')\") with test_case.assertNoMessages(): test_case.walk(node) node = extract_node(\"pandas.assertRaises(Exception)\") with test_case.assertNoMessages():", "import pytest from tests.pylint_plugins.utils import create_message, extract_node, skip_if_pylint_unavailable pytestmark =", "create_message, extract_node, skip_if_pylint_unavailable pytestmark = skip_if_pylint_unavailable() @pytest.fixture(scope=\"module\") def test_case(): import", "pylint.testutils from pylint_plugins import AssertRaisesWithoutMsg class TestAssertRaisesWithoutMsg(pylint.testutils.CheckerTestCase): CHECKER_CLASS = AssertRaisesWithoutMsg", "TestAssertRaisesWithoutMsg() test_case.setup_method() return test_case def test_assert_raises_without_msg(test_case): node = extract_node(\"self.assertRaises(Exception)\") with", "msg='test')\") with test_case.assertNoMessages(): test_case.walk(node) node = extract_node(\"pandas.assertRaises(Exception)\") with test_case.assertNoMessages(): test_case.walk(node)", "test_case.setup_method() return test_case def test_assert_raises_without_msg(test_case): node = extract_node(\"self.assertRaises(Exception)\") with test_case.assertAddsMessages(create_message(test_case.CHECKER_CLASS.name,", "from tests.pylint_plugins.utils import create_message, extract_node, skip_if_pylint_unavailable pytestmark = skip_if_pylint_unavailable() @pytest.fixture(scope=\"module\")", "extract_node(\"self.assertRaises(Exception)\") with test_case.assertAddsMessages(create_message(test_case.CHECKER_CLASS.name, node)): test_case.walk(node) node = extract_node(\"self.assertRaises(Exception, msg='test')\") with", "pytest from tests.pylint_plugins.utils import create_message, extract_node, skip_if_pylint_unavailable pytestmark = skip_if_pylint_unavailable()", "tests.pylint_plugins.utils import create_message, extract_node, skip_if_pylint_unavailable pytestmark = skip_if_pylint_unavailable() @pytest.fixture(scope=\"module\") def", "import pylint.testutils from pylint_plugins import AssertRaisesWithoutMsg class TestAssertRaisesWithoutMsg(pylint.testutils.CheckerTestCase): CHECKER_CLASS =" ]
[ "import math as m import os import collections #set working", "x_values_2_1 = [] x_values_2_2 = [] x_values_2_unassigned = [] y_values_2_1", "'black') figR.axvline(x=brkpt2, linewidth=1, color = 'black') path = outfolder +", "file_2 = infolder + bkpt_name + \"_2.bc_windows.txt\" file_hap = infolder", "hap = bcs_hap_dict[name] for indx, window in values.iteritems(): if window", "color='r') #same figR.scatter(x_values_2_unassigned, y_values_2_unassigned, s=0.2, color='g') figR.set_title(\"\") figR.set_xlabel(\"chr %d (Mb)\"", "= infolder + bkpt_name + \"_hap_bcs.txt\" df_1 = pd.read_table(file_1) df_2", "if name != \"chrom\" and name != \"window_start\" and name", "key = key[:-2] bcs_hap_dict[key] = 'unassigned' for key, values in", "color='g') figL.set_title(\"\") figL.set_xlabel(\"chr %d (Mb)\" %chrom_1) figL.set_ylabel(\"SV-specific barcode\") figR =", "- min(df_2['window_start']))/2) figL.axvline(x=brkpt1, linewidth=1, color = 'black') figR.axvline(x=brkpt2, linewidth=1, color", "!= \"chrom\" and name != \"window_start\" and name != \"window_end\":", "= pd.read_table(file_hap) hap_bcs = hap_bcs.transpose() bcs_hap_dict = {} for key", "barcodes by where they map (lowest coordinate to highest) #", "!= \"chrom\" and key != \"window_start\" and key != \"window_end\":", "and key != \"window_end\": key = key[:-2] bcs_hap_dict[key] = 'unassigned'", "df_2.iteritems(): if name != \"chrom\" and name != \"window_start\" and", "1 name = name[:-2] hap = bcs_hap_dict[name] for indx, window", "import matplotlib.pyplot as plt import matplotlib.colors import csv from scipy.stats", "\"_1.bc_windows.txt\" # file_2 = bkpt_name + \"_2.bc_windows.txt\" # file_hap =", "# #sort barcodes by where they map (lowest coordinate to", "= [] x_values_2_unassigned = [] y_values_2_1 = [] y_values_2_2 =", "= \"1\" #example: plot_bcs_bkpt(\"1\", \"/mnt/ix1/Projects/M002_131217_gastric/P00526/P00526_WG10_150722_gastric/A20_170516_hmw_maps/metr\", \"/mnt/ix1/Projects/M002_131217_gastric/P00526/P00526_WG10_150722_gastric/A20_170516_hmw_maps/metr\") def plot_bcs_bkpt(bkpt_name, infolder, outfolder):", "1: y_values_2_1.append(i2) x_values_2_1.append(window_start_arr2[indx]) elif hap == 2: y_values_2_2.append(i2) x_values_2_2.append(window_start_arr2[indx]) elif", "if key != \"chrom\" and key != \"window_start\" and key", "elif hap == 2: y_values_1_2.append(i1) x_values_1_2.append(window_start_arr1[indx]) else: y_values_1_unassigned.append(i1) x_values_1_unassigned.append(window_start_arr1[indx]) i2", "\"/mnt/ix1/Projects/M002_131217_gastric/P00526/P00526_WG10_150722_gastric/A20_170516_hmw_maps/metr\", \"/mnt/ix1/Projects/M002_131217_gastric/P00526/P00526_WG10_150722_gastric/A20_170516_hmw_maps/metr\") def plot_bcs_bkpt(bkpt_name, infolder, outfolder): if infolder[-1] != '/':", "in df_1.keys(): if key != \"chrom\" and key != \"window_start\"", "\"_hap_bcs.txt\" df_1 = pd.read_table(file_1) df_2 = pd.read_table(file_2) hap_bcs = pd.read_table(file_hap)", "for key in df_1.keys(): if key != \"chrom\" and key", "bkpt_name + \"_1.bc_windows.txt\" file_2 = infolder + bkpt_name + \"_2.bc_windows.txt\"", "linewidth=1, color = 'black') path = outfolder + 'bcs_bkpt_map' plt.savefig(path)", "infolder[-1] != '/': infolder = infolder + '/' file_1 =", "elif hap == 2: y_values_2_2.append(i2) x_values_2_2.append(window_start_arr2[indx]) elif hap == 'unassigned':", "scipy.stats import mode import math as m import os import", "+ \"_hap_bcs.txt\" # #sort barcodes by where they map (lowest", "x_values_1_1 = [] x_values_1_2 = [] x_values_1_unassigned = [] y_values_1_1", "= bkpt_name + \"_hap_bcs.txt\" # #sort barcodes by where they", "[] x_values_1_2 = [] x_values_1_unassigned = [] y_values_1_1 = []", "#same figL.scatter(x_values_1_unassigned, y_values_1_unassigned, s=0.2, color='g') figL.set_title(\"\") figL.set_xlabel(\"chr %d (Mb)\" %chrom_1)", "infolder, outfolder): if infolder[-1] != '/': infolder = infolder +", "= key[:-2] bcs_hap_dict[key] = 'unassigned' for key, values in hap_bcs.iteritems():", "y_values_1_2 = [] y_values_1_unassigned = [] x_values_2_1 = [] x_values_2_2", "+ bkpt_name + \"_hap_bcs.txt\" df_1 = pd.read_table(file_1) df_2 = pd.read_table(file_2)", "y_values_1_1.append(i1) x_values_1_1.append(window_start_arr1[indx]) elif hap == 2: y_values_1_2.append(i1) x_values_1_2.append(window_start_arr1[indx]) else: y_values_1_unassigned.append(i1)", "import matplotlib.colors import csv from scipy.stats import mode import math", "(lowest coordinate to highest) # #read in data frames #", "- min(df_1['window_start']))/2) brkpt2 = min(df_2['window_start']) + ((max(df_2['window_end']) - min(df_2['window_start']))/2) figL.axvline(x=brkpt1,", "by where they map (lowest coordinate to highest) # #read", "== 1: y_values_2_1.append(i2) x_values_2_1.append(window_start_arr2[indx]) elif hap == 2: y_values_2_2.append(i2) x_values_2_2.append(window_start_arr2[indx])", "df_2.at[0, 'chrom'] x_values_1_1 = [] x_values_1_2 = [] x_values_1_unassigned =", "color = 'black') figR.axvline(x=brkpt2, linewidth=1, color = 'black') path =", "file_1 = bkpt_name + \"_1.bc_windows.txt\" # file_2 = bkpt_name +", "y_values_1_2.append(i1) x_values_1_2.append(window_start_arr1[indx]) else: y_values_1_unassigned.append(i1) x_values_1_unassigned.append(window_start_arr1[indx]) i2 = 0 window_start_arr2 =", "x_values_2_1.append(window_start_arr2[indx]) elif hap == 2: y_values_2_2.append(i2) x_values_2_2.append(window_start_arr2[indx]) elif hap ==", "# df_2 = pd.read_table(file_2) # hap_bcs = pd.read_table(file_hap) hap_bcs =", "!= 0: if hap == 1: y_values_1_1.append(i1) x_values_1_1.append(window_start_arr1[indx]) elif hap", "if infolder[-1] != '/': infolder = infolder + '/' file_1", "%d (Mb)\" %chrom_2) figR.set_ylabel(\"\") brkpt1 = min(df_1['window_start']) + ((max(df_1['window_end']) -", "#bkpt_name = \"1\" #example: plot_bcs_bkpt(\"1\", \"/mnt/ix1/Projects/M002_131217_gastric/P00526/P00526_WG10_150722_gastric/A20_170516_hmw_maps/metr\", \"/mnt/ix1/Projects/M002_131217_gastric/P00526/P00526_WG10_150722_gastric/A20_170516_hmw_maps/metr\") def plot_bcs_bkpt(bkpt_name, infolder,", "\"_hap_bcs.txt\" # #sort barcodes by where they map (lowest coordinate", "#set working directory #os.chdir(\"/mnt/ix1/Projects/M002_131217_gastric/P00526/P00526_WG10_150722_gastric/A20_170516_hmw_maps/metr\") #bkpt_name = \"1\" #example: plot_bcs_bkpt(\"1\", \"/mnt/ix1/Projects/M002_131217_gastric/P00526/P00526_WG10_150722_gastric/A20_170516_hmw_maps/metr\",", "== 2: y_values_1_2.append(i1) x_values_1_2.append(window_start_arr1[indx]) else: y_values_1_unassigned.append(i1) x_values_1_unassigned.append(window_start_arr1[indx]) i2 = 0", "bcs_hap_dict[name] #print type(hap) int for indx, window in values.iteritems(): if", "np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.colors", "window_start_arr2 = df_2['window_start'] for name, values in df_2.iteritems(): if name", "infolder = infolder + '/' file_1 = infolder + bkpt_name", "pd.read_table(file_2) hap_bcs = pd.read_table(file_hap) # bkpt_name = \"1\" # file_1", "'unassigned' for key, values in hap_bcs.iteritems(): if values[0] != 'bcs':", "= hap_bcs.transpose() bcs_hap_dict = {} for key in df_1.keys(): if", "bkpt_name + \"_2.bc_windows.txt\" file_hap = infolder + bkpt_name + \"_hap_bcs.txt\"", "bkpt_name + \"_hap_bcs.txt\" df_1 = pd.read_table(file_1) df_2 = pd.read_table(file_2) hap_bcs", "+ bkpt_name + \"_1.bc_windows.txt\" file_2 = infolder + bkpt_name +", "+= 1 name = name[:-2] hap = bcs_hap_dict[name] #print type(hap)", "\"_1.bc_windows.txt\" file_2 = infolder + bkpt_name + \"_2.bc_windows.txt\" file_hap =", "columns (so each barcode) if name != \"chrom\" and name", "figL.scatter(x_values_1_2, y_values_1_2, s=0.2, color='r') #same figL.scatter(x_values_1_unassigned, y_values_1_unassigned, s=0.2, color='g') figL.set_title(\"\")", "bkpt_name + \"_hap_bcs.txt\" # #sort barcodes by where they map", "= {} for key in df_1.keys(): if key != \"chrom\"", "df_1.sort_values('window_start') df_2 = df_2.sort_values('window_start') chrom_1 = df_1.at[0, 'chrom'] chrom_2 =", "y_values_2_unassigned.append(i2) x_values_2_unassigned.append(window_start_arr2[indx]) fig = plt.figure() figL = fig.add_subplot(121) figL.scatter(x_values_1_1, y_values_1_1,", "y_values_1_unassigned, s=0.2, color='g') figL.set_title(\"\") figL.set_xlabel(\"chr %d (Mb)\" %chrom_1) figL.set_ylabel(\"SV-specific barcode\")", "df_1.iteritems(): #go through columns (so each barcode) if name !=", "math as m import os import collections #set working directory", "= hap df_1 = df_1.sort_values('window_start') df_2 = df_2.sort_values('window_start') chrom_1 =", "y_values_2_2 = [] y_values_2_unassigned = [] i1 = 0 window_start_arr1", "key in df_1.keys(): if key != \"chrom\" and key !=", "y_values_1_1 = [] y_values_1_2 = [] y_values_1_unassigned = [] x_values_2_1", "# bkpt_name = \"1\" # file_1 = bkpt_name + \"_1.bc_windows.txt\"", "for indx, window in values.iteritems(): if window != 0: if", "%d (Mb)\" %chrom_1) figL.set_ylabel(\"SV-specific barcode\") figR = fig.add_subplot(122) figR.scatter(x_values_2_1, y_values_2_1,", "df_2 = pd.read_table(file_2) hap_bcs = pd.read_table(file_hap) # bkpt_name = \"1\"", "in data frames # df_1 = pd.read_table(file_1) # df_2 =", "and name != \"window_end\": i1 += 1 name = name[:-2]", "= df_2.sort_values('window_start') chrom_1 = df_1.at[0, 'chrom'] chrom_2 = df_2.at[0, 'chrom']", "figL = fig.add_subplot(121) figL.scatter(x_values_1_1, y_values_1_1, s=0.2, color='b') #this doesn't seem", "0: if hap == 1: y_values_1_1.append(i1) x_values_1_1.append(window_start_arr1[indx]) elif hap ==", "if window != 0: if hap == 1: y_values_1_1.append(i1) x_values_1_1.append(window_start_arr1[indx])", "pandas as pd import numpy as np import matplotlib matplotlib.use('Agg')", "name != \"window_end\": i1 += 1 name = name[:-2] hap", "y_values_1_unassigned = [] x_values_2_1 = [] x_values_2_2 = [] x_values_2_unassigned", "[] x_values_2_2 = [] x_values_2_unassigned = [] y_values_2_1 = []", "!= '/': infolder = infolder + '/' file_1 = infolder", "where they map (lowest coordinate to highest) # #read in", "# file_1 = bkpt_name + \"_1.bc_windows.txt\" # file_2 = bkpt_name", "elif hap == 'unassigned': y_values_2_unassigned.append(i2) x_values_2_unassigned.append(window_start_arr2[indx]) fig = plt.figure() figL", "key != \"chrom\" and key != \"window_start\" and key !=", "bkpt_name = \"1\" # file_1 = bkpt_name + \"_1.bc_windows.txt\" #", "as pd import numpy as np import matplotlib matplotlib.use('Agg') import", "name != \"window_start\" and name != \"window_end\": i2 += 1", "y_values_2_1, s=0.2, color='b') #same figR.scatter(x_values_2_2, y_values_2_2, s=0.2, color='r') #same figR.scatter(x_values_2_unassigned,", "if hap == 1: y_values_2_1.append(i2) x_values_2_1.append(window_start_arr2[indx]) elif hap == 2:", "seem to contain anything figL.scatter(x_values_1_2, y_values_1_2, s=0.2, color='r') #same figL.scatter(x_values_1_unassigned,", "= [] x_values_1_unassigned = [] y_values_1_1 = [] y_values_1_2 =", "= [] y_values_2_unassigned = [] i1 = 0 window_start_arr1 =", "for name, values in df_2.iteritems(): if name != \"chrom\" and", "#same figR.scatter(x_values_2_unassigned, y_values_2_unassigned, s=0.2, color='g') figR.set_title(\"\") figR.set_xlabel(\"chr %d (Mb)\" %chrom_2)", "barcode\") figR = fig.add_subplot(122) figR.scatter(x_values_2_1, y_values_2_1, s=0.2, color='b') #same figR.scatter(x_values_2_2,", "#example: plot_bcs_bkpt(\"1\", \"/mnt/ix1/Projects/M002_131217_gastric/P00526/P00526_WG10_150722_gastric/A20_170516_hmw_maps/metr\", \"/mnt/ix1/Projects/M002_131217_gastric/P00526/P00526_WG10_150722_gastric/A20_170516_hmw_maps/metr\") def plot_bcs_bkpt(bkpt_name, infolder, outfolder): if infolder[-1]", "each barcode) if name != \"chrom\" and name != \"window_start\"", "key[:-2] bcs_hap_dict[key] = 'unassigned' for key, values in hap_bcs.iteritems(): if", "int for indx, window in values.iteritems(): if window != 0:", "hap == 2: y_values_1_2.append(i1) x_values_1_2.append(window_start_arr1[indx]) else: y_values_1_unassigned.append(i1) x_values_1_unassigned.append(window_start_arr1[indx]) i2 =", "window != 0: if hap == 1: y_values_1_1.append(i1) x_values_1_1.append(window_start_arr1[indx]) elif", "+= 1 name = name[:-2] hap = bcs_hap_dict[name] for indx,", "= df_2.at[0, 'chrom'] x_values_1_1 = [] x_values_1_2 = [] x_values_1_unassigned", "matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.colors import csv", "df_2 = pd.read_table(file_2) # hap_bcs = pd.read_table(file_hap) hap_bcs = hap_bcs.transpose()", "plt import matplotlib.colors import csv from scipy.stats import mode import", "figL.set_title(\"\") figL.set_xlabel(\"chr %d (Mb)\" %chrom_1) figL.set_ylabel(\"SV-specific barcode\") figR = fig.add_subplot(122)", "= [] y_values_2_1 = [] y_values_2_2 = [] y_values_2_unassigned =", "= bcs_hap_dict[name] #print type(hap) int for indx, window in values.iteritems():", "and name != \"window_start\" and name != \"window_end\": i1 +=", "file_2 = bkpt_name + \"_2.bc_windows.txt\" # file_hap = bkpt_name +", "\"chrom\" and name != \"window_start\" and name != \"window_end\": i1", "hap = values[1] bcs_hap_dict[values[0]] = hap df_1 = df_1.sort_values('window_start') df_2", "infolder + bkpt_name + \"_hap_bcs.txt\" df_1 = pd.read_table(file_1) df_2 =", "x_values_1_1.append(window_start_arr1[indx]) elif hap == 2: y_values_1_2.append(i1) x_values_1_2.append(window_start_arr1[indx]) else: y_values_1_unassigned.append(i1) x_values_1_unassigned.append(window_start_arr1[indx])", "\"window_end\": key = key[:-2] bcs_hap_dict[key] = 'unassigned' for key, values", "+ bkpt_name + \"_2.bc_windows.txt\" file_hap = infolder + bkpt_name +", "key != \"window_end\": key = key[:-2] bcs_hap_dict[key] = 'unassigned' for", "color='b') #this doesn't seem to contain anything figL.scatter(x_values_1_2, y_values_1_2, s=0.2,", "= bkpt_name + \"_1.bc_windows.txt\" # file_2 = bkpt_name + \"_2.bc_windows.txt\"", "fig = plt.figure() figL = fig.add_subplot(121) figL.scatter(x_values_1_1, y_values_1_1, s=0.2, color='b')", "= [] y_values_1_unassigned = [] x_values_2_1 = [] x_values_2_2 =", "+ ((max(df_1['window_end']) - min(df_1['window_start']))/2) brkpt2 = min(df_2['window_start']) + ((max(df_2['window_end']) -", "= bcs_hap_dict[name] for indx, window in values.iteritems(): if window !=", "bcs_hap_dict[key] = 'unassigned' for key, values in hap_bcs.iteritems(): if values[0]", "i2 += 1 name = name[:-2] hap = bcs_hap_dict[name] for", "df_1 = pd.read_table(file_1) # df_2 = pd.read_table(file_2) # hap_bcs =", "y_values_2_unassigned = [] i1 = 0 window_start_arr1 = df_1['window_start'] for", "= pd.read_table(file_hap) # bkpt_name = \"1\" # file_1 = bkpt_name", "= df_2['window_start'] for name, values in df_2.iteritems(): if name !=", "= 'black') figR.axvline(x=brkpt2, linewidth=1, color = 'black') path = outfolder", "in hap_bcs.iteritems(): if values[0] != 'bcs': hap = values[1] bcs_hap_dict[values[0]]", "file_hap = bkpt_name + \"_hap_bcs.txt\" # #sort barcodes by where", "window in values.iteritems(): if window != 0: if hap ==", "x_values_1_2.append(window_start_arr1[indx]) else: y_values_1_unassigned.append(i1) x_values_1_unassigned.append(window_start_arr1[indx]) i2 = 0 window_start_arr2 = df_2['window_start']", "brkpt1 = min(df_1['window_start']) + ((max(df_1['window_end']) - min(df_1['window_start']))/2) brkpt2 = min(df_2['window_start'])", "#print type(hap) int for indx, window in values.iteritems(): if window", "'chrom'] chrom_2 = df_2.at[0, 'chrom'] x_values_1_1 = [] x_values_1_2 =", "values.iteritems(): if window != 0: if hap == 1: y_values_2_1.append(i2)", "df_2 = df_2.sort_values('window_start') chrom_1 = df_1.at[0, 'chrom'] chrom_2 = df_2.at[0,", "[] y_values_1_unassigned = [] x_values_2_1 = [] x_values_2_2 = []", "= name[:-2] hap = bcs_hap_dict[name] #print type(hap) int for indx,", "= infolder + bkpt_name + \"_2.bc_windows.txt\" file_hap = infolder +", "pd.read_table(file_1) # df_2 = pd.read_table(file_2) # hap_bcs = pd.read_table(file_hap) hap_bcs", "'unassigned': y_values_2_unassigned.append(i2) x_values_2_unassigned.append(window_start_arr2[indx]) fig = plt.figure() figL = fig.add_subplot(121) figL.scatter(x_values_1_1,", "'/' file_1 = infolder + bkpt_name + \"_1.bc_windows.txt\" file_2 =", "[] x_values_2_1 = [] x_values_2_2 = [] x_values_2_unassigned = []", "#this doesn't seem to contain anything figL.scatter(x_values_1_2, y_values_1_2, s=0.2, color='r')", "!= \"window_start\" and key != \"window_end\": key = key[:-2] bcs_hap_dict[key]", "df_1['window_start'] for name, values in df_1.iteritems(): #go through columns (so", "= [] y_values_1_1 = [] y_values_1_2 = [] y_values_1_unassigned =", "pd.read_table(file_2) # hap_bcs = pd.read_table(file_hap) hap_bcs = hap_bcs.transpose() bcs_hap_dict =", "df_2['window_start'] for name, values in df_2.iteritems(): if name != \"chrom\"", "((max(df_2['window_end']) - min(df_2['window_start']))/2) figL.axvline(x=brkpt1, linewidth=1, color = 'black') figR.axvline(x=brkpt2, linewidth=1,", "\"window_start\" and key != \"window_end\": key = key[:-2] bcs_hap_dict[key] =", "\"_2.bc_windows.txt\" file_hap = infolder + bkpt_name + \"_hap_bcs.txt\" df_1 =", "to contain anything figL.scatter(x_values_1_2, y_values_1_2, s=0.2, color='r') #same figL.scatter(x_values_1_unassigned, y_values_1_unassigned,", "linewidth=1, color = 'black') figR.axvline(x=brkpt2, linewidth=1, color = 'black') path", "values[1] bcs_hap_dict[values[0]] = hap df_1 = df_1.sort_values('window_start') df_2 = df_2.sort_values('window_start')", "figR.axvline(x=brkpt2, linewidth=1, color = 'black') path = outfolder + 'bcs_bkpt_map'", "figR.set_xlabel(\"chr %d (Mb)\" %chrom_2) figR.set_ylabel(\"\") brkpt1 = min(df_1['window_start']) + ((max(df_1['window_end'])", "figL.axvline(x=brkpt1, linewidth=1, color = 'black') figR.axvline(x=brkpt2, linewidth=1, color = 'black')", "matplotlib.colors import csv from scipy.stats import mode import math as", "#sort barcodes by where they map (lowest coordinate to highest)", "file_hap = infolder + bkpt_name + \"_hap_bcs.txt\" df_1 = pd.read_table(file_1)", "bcs_hap_dict = {} for key in df_1.keys(): if key !=", "hap == 1: y_values_2_1.append(i2) x_values_2_1.append(window_start_arr2[indx]) elif hap == 2: y_values_2_2.append(i2)", "name != \"window_end\": i2 += 1 name = name[:-2] hap", "values in df_2.iteritems(): if name != \"chrom\" and name !=", "y_values_1_2, s=0.2, color='r') #same figL.scatter(x_values_1_unassigned, y_values_1_unassigned, s=0.2, color='g') figL.set_title(\"\") figL.set_xlabel(\"chr", "!= \"window_end\": key = key[:-2] bcs_hap_dict[key] = 'unassigned' for key,", "= name[:-2] hap = bcs_hap_dict[name] for indx, window in values.iteritems():", "s=0.2, color='b') #same figR.scatter(x_values_2_2, y_values_2_2, s=0.2, color='r') #same figR.scatter(x_values_2_unassigned, y_values_2_unassigned,", "values[0] != 'bcs': hap = values[1] bcs_hap_dict[values[0]] = hap df_1", "hap_bcs = hap_bcs.transpose() bcs_hap_dict = {} for key in df_1.keys():", "name = name[:-2] hap = bcs_hap_dict[name] #print type(hap) int for", "= pd.read_table(file_2) # hap_bcs = pd.read_table(file_hap) hap_bcs = hap_bcs.transpose() bcs_hap_dict", "x_values_2_unassigned = [] y_values_2_1 = [] y_values_2_2 = [] y_values_2_unassigned", "figR.set_title(\"\") figR.set_xlabel(\"chr %d (Mb)\" %chrom_2) figR.set_ylabel(\"\") brkpt1 = min(df_1['window_start']) +", "figL.scatter(x_values_1_unassigned, y_values_1_unassigned, s=0.2, color='g') figL.set_title(\"\") figL.set_xlabel(\"chr %d (Mb)\" %chrom_1) figL.set_ylabel(\"SV-specific", "\"_2.bc_windows.txt\" # file_hap = bkpt_name + \"_hap_bcs.txt\" # #sort barcodes", "key, values in hap_bcs.iteritems(): if values[0] != 'bcs': hap =", "window != 0: if hap == 1: y_values_2_1.append(i2) x_values_2_1.append(window_start_arr2[indx]) elif", "+ ((max(df_2['window_end']) - min(df_2['window_start']))/2) figL.axvline(x=brkpt1, linewidth=1, color = 'black') figR.axvline(x=brkpt2,", "infolder + bkpt_name + \"_2.bc_windows.txt\" file_hap = infolder + bkpt_name", "[] x_values_2_unassigned = [] y_values_2_1 = [] y_values_2_2 = []", "== 2: y_values_2_2.append(i2) x_values_2_2.append(window_start_arr2[indx]) elif hap == 'unassigned': y_values_2_unassigned.append(i2) x_values_2_unassigned.append(window_start_arr2[indx])", "min(df_1['window_start']) + ((max(df_1['window_end']) - min(df_1['window_start']))/2) brkpt2 = min(df_2['window_start']) + ((max(df_2['window_end'])", "matplotlib.pyplot as plt import matplotlib.colors import csv from scipy.stats import", "hap_bcs = pd.read_table(file_hap) # bkpt_name = \"1\" # file_1 =", "i1 += 1 name = name[:-2] hap = bcs_hap_dict[name] #print", "0 window_start_arr1 = df_1['window_start'] for name, values in df_1.iteritems(): #go", "y_values_2_2, s=0.2, color='r') #same figR.scatter(x_values_2_unassigned, y_values_2_unassigned, s=0.2, color='g') figR.set_title(\"\") figR.set_xlabel(\"chr", "and key != \"window_start\" and key != \"window_end\": key =", "+ \"_2.bc_windows.txt\" file_hap = infolder + bkpt_name + \"_hap_bcs.txt\" df_1", "%chrom_2) figR.set_ylabel(\"\") brkpt1 = min(df_1['window_start']) + ((max(df_1['window_end']) - min(df_1['window_start']))/2) brkpt2", "(so each barcode) if name != \"chrom\" and name !=", "hap == 1: y_values_1_1.append(i1) x_values_1_1.append(window_start_arr1[indx]) elif hap == 2: y_values_1_2.append(i1)", "#read in data frames # df_1 = pd.read_table(file_1) # df_2", "plt.figure() figL = fig.add_subplot(121) figL.scatter(x_values_1_1, y_values_1_1, s=0.2, color='b') #this doesn't", "= [] y_values_1_2 = [] y_values_1_unassigned = [] x_values_2_1 =", "\"window_start\" and name != \"window_end\": i2 += 1 name =", "2: y_values_1_2.append(i1) x_values_1_2.append(window_start_arr1[indx]) else: y_values_1_unassigned.append(i1) x_values_1_unassigned.append(window_start_arr1[indx]) i2 = 0 window_start_arr2", "\"/mnt/ix1/Projects/M002_131217_gastric/P00526/P00526_WG10_150722_gastric/A20_170516_hmw_maps/metr\") def plot_bcs_bkpt(bkpt_name, infolder, outfolder): if infolder[-1] != '/': infolder", "pd.read_table(file_hap) # bkpt_name = \"1\" # file_1 = bkpt_name +", "chrom_2 = df_2.at[0, 'chrom'] x_values_1_1 = [] x_values_1_2 = []", "numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt", "pd.read_table(file_hap) hap_bcs = hap_bcs.transpose() bcs_hap_dict = {} for key in", "csv from scipy.stats import mode import math as m import", "plot_bcs_bkpt(\"1\", \"/mnt/ix1/Projects/M002_131217_gastric/P00526/P00526_WG10_150722_gastric/A20_170516_hmw_maps/metr\", \"/mnt/ix1/Projects/M002_131217_gastric/P00526/P00526_WG10_150722_gastric/A20_170516_hmw_maps/metr\") def plot_bcs_bkpt(bkpt_name, infolder, outfolder): if infolder[-1] !=", "\"1\" #example: plot_bcs_bkpt(\"1\", \"/mnt/ix1/Projects/M002_131217_gastric/P00526/P00526_WG10_150722_gastric/A20_170516_hmw_maps/metr\", \"/mnt/ix1/Projects/M002_131217_gastric/P00526/P00526_WG10_150722_gastric/A20_170516_hmw_maps/metr\") def plot_bcs_bkpt(bkpt_name, infolder, outfolder): if", "in df_2.iteritems(): if name != \"chrom\" and name != \"window_start\"", "pd.read_table(file_1) df_2 = pd.read_table(file_2) hap_bcs = pd.read_table(file_hap) # bkpt_name =", "in df_1.iteritems(): #go through columns (so each barcode) if name", "\"chrom\" and name != \"window_start\" and name != \"window_end\": i2", "df_1.keys(): if key != \"chrom\" and key != \"window_start\" and", "# hap_bcs = pd.read_table(file_hap) hap_bcs = hap_bcs.transpose() bcs_hap_dict = {}", "0: if hap == 1: y_values_2_1.append(i2) x_values_2_1.append(window_start_arr2[indx]) elif hap ==", "import mode import math as m import os import collections", "#os.chdir(\"/mnt/ix1/Projects/M002_131217_gastric/P00526/P00526_WG10_150722_gastric/A20_170516_hmw_maps/metr\") #bkpt_name = \"1\" #example: plot_bcs_bkpt(\"1\", \"/mnt/ix1/Projects/M002_131217_gastric/P00526/P00526_WG10_150722_gastric/A20_170516_hmw_maps/metr\", \"/mnt/ix1/Projects/M002_131217_gastric/P00526/P00526_WG10_150722_gastric/A20_170516_hmw_maps/metr\") def plot_bcs_bkpt(bkpt_name,", "y_values_2_1 = [] y_values_2_2 = [] y_values_2_unassigned = [] i1", "fig.add_subplot(121) figL.scatter(x_values_1_1, y_values_1_1, s=0.2, color='b') #this doesn't seem to contain", "!= \"window_end\": i1 += 1 name = name[:-2] hap =", "map (lowest coordinate to highest) # #read in data frames", "= \"1\" # file_1 = bkpt_name + \"_1.bc_windows.txt\" # file_2", "== 'unassigned': y_values_2_unassigned.append(i2) x_values_2_unassigned.append(window_start_arr2[indx]) fig = plt.figure() figL = fig.add_subplot(121)", "= df_1.sort_values('window_start') df_2 = df_2.sort_values('window_start') chrom_1 = df_1.at[0, 'chrom'] chrom_2", "if hap == 1: y_values_1_1.append(i1) x_values_1_1.append(window_start_arr1[indx]) elif hap == 2:", "y_values_2_unassigned, s=0.2, color='g') figR.set_title(\"\") figR.set_xlabel(\"chr %d (Mb)\" %chrom_2) figR.set_ylabel(\"\") brkpt1", "hap_bcs = pd.read_table(file_hap) hap_bcs = hap_bcs.transpose() bcs_hap_dict = {} for", "x_values_2_2.append(window_start_arr2[indx]) elif hap == 'unassigned': y_values_2_unassigned.append(i2) x_values_2_unassigned.append(window_start_arr2[indx]) fig = plt.figure()", "type(hap) int for indx, window in values.iteritems(): if window !=", "figR = fig.add_subplot(122) figR.scatter(x_values_2_1, y_values_2_1, s=0.2, color='b') #same figR.scatter(x_values_2_2, y_values_2_2,", "and name != \"window_start\" and name != \"window_end\": i2 +=", "else: y_values_1_unassigned.append(i1) x_values_1_unassigned.append(window_start_arr1[indx]) i2 = 0 window_start_arr2 = df_2['window_start'] for", "if window != 0: if hap == 1: y_values_2_1.append(i2) x_values_2_1.append(window_start_arr2[indx])", "y_values_1_1, s=0.2, color='b') #this doesn't seem to contain anything figL.scatter(x_values_1_2,", "values.iteritems(): if window != 0: if hap == 1: y_values_1_1.append(i1)", "name = name[:-2] hap = bcs_hap_dict[name] for indx, window in", "x_values_2_unassigned.append(window_start_arr2[indx]) fig = plt.figure() figL = fig.add_subplot(121) figL.scatter(x_values_1_1, y_values_1_1, s=0.2,", "\"1\" # file_1 = bkpt_name + \"_1.bc_windows.txt\" # file_2 =", "+ \"_2.bc_windows.txt\" # file_hap = bkpt_name + \"_hap_bcs.txt\" # #sort", "values in df_1.iteritems(): #go through columns (so each barcode) if", "i1 = 0 window_start_arr1 = df_1['window_start'] for name, values in", "+ '/' file_1 = infolder + bkpt_name + \"_1.bc_windows.txt\" file_2", "in values.iteritems(): if window != 0: if hap == 1:", "hap == 2: y_values_2_2.append(i2) x_values_2_2.append(window_start_arr2[indx]) elif hap == 'unassigned': y_values_2_unassigned.append(i2)", "= [] y_values_2_2 = [] y_values_2_unassigned = [] i1 =", "'bcs': hap = values[1] bcs_hap_dict[values[0]] = hap df_1 = df_1.sort_values('window_start')", "color='r') #same figL.scatter(x_values_1_unassigned, y_values_1_unassigned, s=0.2, color='g') figL.set_title(\"\") figL.set_xlabel(\"chr %d (Mb)\"", "= pd.read_table(file_1) df_2 = pd.read_table(file_2) hap_bcs = pd.read_table(file_hap) # bkpt_name", "highest) # #read in data frames # df_1 = pd.read_table(file_1)", "\"window_start\" and name != \"window_end\": i1 += 1 name =", "min(df_2['window_start']) + ((max(df_2['window_end']) - min(df_2['window_start']))/2) figL.axvline(x=brkpt1, linewidth=1, color = 'black')", "name, values in df_1.iteritems(): #go through columns (so each barcode)", "s=0.2, color='r') #same figR.scatter(x_values_2_unassigned, y_values_2_unassigned, s=0.2, color='g') figR.set_title(\"\") figR.set_xlabel(\"chr %d", "import pandas as pd import numpy as np import matplotlib", "anything figL.scatter(x_values_1_2, y_values_1_2, s=0.2, color='r') #same figL.scatter(x_values_1_unassigned, y_values_1_unassigned, s=0.2, color='g')", "df_1 = df_1.sort_values('window_start') df_2 = df_2.sort_values('window_start') chrom_1 = df_1.at[0, 'chrom']", "= pd.read_table(file_1) # df_2 = pd.read_table(file_2) # hap_bcs = pd.read_table(file_hap)", "((max(df_1['window_end']) - min(df_1['window_start']))/2) brkpt2 = min(df_2['window_start']) + ((max(df_2['window_end']) - min(df_2['window_start']))/2)", "import os import collections #set working directory #os.chdir(\"/mnt/ix1/Projects/M002_131217_gastric/P00526/P00526_WG10_150722_gastric/A20_170516_hmw_maps/metr\") #bkpt_name =", "figR.scatter(x_values_2_unassigned, y_values_2_unassigned, s=0.2, color='g') figR.set_title(\"\") figR.set_xlabel(\"chr %d (Mb)\" %chrom_2) figR.set_ylabel(\"\")", "i2 = 0 window_start_arr2 = df_2['window_start'] for name, values in", "s=0.2, color='r') #same figL.scatter(x_values_1_unassigned, y_values_1_unassigned, s=0.2, color='g') figL.set_title(\"\") figL.set_xlabel(\"chr %d", "# file_2 = bkpt_name + \"_2.bc_windows.txt\" # file_hap = bkpt_name", "+ \"_1.bc_windows.txt\" # file_2 = bkpt_name + \"_2.bc_windows.txt\" # file_hap", "bkpt_name + \"_1.bc_windows.txt\" # file_2 = bkpt_name + \"_2.bc_windows.txt\" #", "== 1: y_values_1_1.append(i1) x_values_1_1.append(window_start_arr1[indx]) elif hap == 2: y_values_1_2.append(i1) x_values_1_2.append(window_start_arr1[indx])", "(Mb)\" %chrom_2) figR.set_ylabel(\"\") brkpt1 = min(df_1['window_start']) + ((max(df_1['window_end']) - min(df_1['window_start']))/2)", "os import collections #set working directory #os.chdir(\"/mnt/ix1/Projects/M002_131217_gastric/P00526/P00526_WG10_150722_gastric/A20_170516_hmw_maps/metr\") #bkpt_name = \"1\"", "figR.scatter(x_values_2_2, y_values_2_2, s=0.2, color='r') #same figR.scatter(x_values_2_unassigned, y_values_2_unassigned, s=0.2, color='g') figR.set_title(\"\")", "name[:-2] hap = bcs_hap_dict[name] for indx, window in values.iteritems(): if", "hap == 'unassigned': y_values_2_unassigned.append(i2) x_values_2_unassigned.append(window_start_arr2[indx]) fig = plt.figure() figL =", "= [] x_values_2_2 = [] x_values_2_unassigned = [] y_values_2_1 =", "= plt.figure() figL = fig.add_subplot(121) figL.scatter(x_values_1_1, y_values_1_1, s=0.2, color='b') #this", "min(df_2['window_start']))/2) figL.axvline(x=brkpt1, linewidth=1, color = 'black') figR.axvline(x=brkpt2, linewidth=1, color =", "color='g') figR.set_title(\"\") figR.set_xlabel(\"chr %d (Mb)\" %chrom_2) figR.set_ylabel(\"\") brkpt1 = min(df_1['window_start'])", "import csv from scipy.stats import mode import math as m", "bcs_hap_dict[values[0]] = hap df_1 = df_1.sort_values('window_start') df_2 = df_2.sort_values('window_start') chrom_1", "# file_hap = bkpt_name + \"_hap_bcs.txt\" # #sort barcodes by", "hap = bcs_hap_dict[name] #print type(hap) int for indx, window in", "= 0 window_start_arr2 = df_2['window_start'] for name, values in df_2.iteritems():", "if values[0] != 'bcs': hap = values[1] bcs_hap_dict[values[0]] = hap", "and name != \"window_end\": i2 += 1 name = name[:-2]", "def plot_bcs_bkpt(bkpt_name, infolder, outfolder): if infolder[-1] != '/': infolder =", "bkpt_name + \"_2.bc_windows.txt\" # file_hap = bkpt_name + \"_hap_bcs.txt\" #", "+ \"_1.bc_windows.txt\" file_2 = infolder + bkpt_name + \"_2.bc_windows.txt\" file_hap", "chrom_1 = df_1.at[0, 'chrom'] chrom_2 = df_2.at[0, 'chrom'] x_values_1_1 =", "through columns (so each barcode) if name != \"chrom\" and", "= 0 window_start_arr1 = df_1['window_start'] for name, values in df_1.iteritems():", "x_values_1_2 = [] x_values_1_unassigned = [] y_values_1_1 = [] y_values_1_2", "import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as", "y_values_1_unassigned.append(i1) x_values_1_unassigned.append(window_start_arr1[indx]) i2 = 0 window_start_arr2 = df_2['window_start'] for name,", "(Mb)\" %chrom_1) figL.set_ylabel(\"SV-specific barcode\") figR = fig.add_subplot(122) figR.scatter(x_values_2_1, y_values_2_1, s=0.2,", "s=0.2, color='g') figL.set_title(\"\") figL.set_xlabel(\"chr %d (Mb)\" %chrom_1) figL.set_ylabel(\"SV-specific barcode\") figR", "= [] i1 = 0 window_start_arr1 = df_1['window_start'] for name,", "# df_1 = pd.read_table(file_1) # df_2 = pd.read_table(file_2) # hap_bcs", "collections #set working directory #os.chdir(\"/mnt/ix1/Projects/M002_131217_gastric/P00526/P00526_WG10_150722_gastric/A20_170516_hmw_maps/metr\") #bkpt_name = \"1\" #example: plot_bcs_bkpt(\"1\",", "hap_bcs.iteritems(): if values[0] != 'bcs': hap = values[1] bcs_hap_dict[values[0]] =", "matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.colors import csv from", "!= \"window_end\": i2 += 1 name = name[:-2] hap =", "data frames # df_1 = pd.read_table(file_1) # df_2 = pd.read_table(file_2)", "as plt import matplotlib.colors import csv from scipy.stats import mode", "fig.add_subplot(122) figR.scatter(x_values_2_1, y_values_2_1, s=0.2, color='b') #same figR.scatter(x_values_2_2, y_values_2_2, s=0.2, color='r')", "= fig.add_subplot(121) figL.scatter(x_values_1_1, y_values_1_1, s=0.2, color='b') #this doesn't seem to", "# #read in data frames # df_1 = pd.read_table(file_1) #", "[] y_values_1_1 = [] y_values_1_2 = [] y_values_1_unassigned = []", "!= \"window_start\" and name != \"window_end\": i2 += 1 name", "df_1 = pd.read_table(file_1) df_2 = pd.read_table(file_2) hap_bcs = pd.read_table(file_hap) #", "= df_1.at[0, 'chrom'] chrom_2 = df_2.at[0, 'chrom'] x_values_1_1 = []", "[] y_values_2_1 = [] y_values_2_2 = [] y_values_2_unassigned = []", "= df_1['window_start'] for name, values in df_1.iteritems(): #go through columns", "name[:-2] hap = bcs_hap_dict[name] #print type(hap) int for indx, window", "color='b') #same figR.scatter(x_values_2_2, y_values_2_2, s=0.2, color='r') #same figR.scatter(x_values_2_unassigned, y_values_2_unassigned, s=0.2,", "[] y_values_2_2 = [] y_values_2_unassigned = [] i1 = 0", "x_values_2_2 = [] x_values_2_unassigned = [] y_values_2_1 = [] y_values_2_2", "df_1.at[0, 'chrom'] chrom_2 = df_2.at[0, 'chrom'] x_values_1_1 = [] x_values_1_2", "!= 'bcs': hap = values[1] bcs_hap_dict[values[0]] = hap df_1 =", "= min(df_1['window_start']) + ((max(df_1['window_end']) - min(df_1['window_start']))/2) brkpt2 = min(df_2['window_start']) +", "working directory #os.chdir(\"/mnt/ix1/Projects/M002_131217_gastric/P00526/P00526_WG10_150722_gastric/A20_170516_hmw_maps/metr\") #bkpt_name = \"1\" #example: plot_bcs_bkpt(\"1\", \"/mnt/ix1/Projects/M002_131217_gastric/P00526/P00526_WG10_150722_gastric/A20_170516_hmw_maps/metr\", \"/mnt/ix1/Projects/M002_131217_gastric/P00526/P00526_WG10_150722_gastric/A20_170516_hmw_maps/metr\")", "= bkpt_name + \"_2.bc_windows.txt\" # file_hap = bkpt_name + \"_hap_bcs.txt\"", "1: y_values_1_1.append(i1) x_values_1_1.append(window_start_arr1[indx]) elif hap == 2: y_values_1_2.append(i1) x_values_1_2.append(window_start_arr1[indx]) else:", "as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import", "they map (lowest coordinate to highest) # #read in data", "values in hap_bcs.iteritems(): if values[0] != 'bcs': hap = values[1]", "[] y_values_1_2 = [] y_values_1_unassigned = [] x_values_2_1 = []", "barcode) if name != \"chrom\" and name != \"window_start\" and", "name != \"window_start\" and name != \"window_end\": i1 += 1", "= [] x_values_1_2 = [] x_values_1_unassigned = [] y_values_1_1 =", "x_values_1_unassigned = [] y_values_1_1 = [] y_values_1_2 = [] y_values_1_unassigned", "= values[1] bcs_hap_dict[values[0]] = hap df_1 = df_1.sort_values('window_start') df_2 =", "infolder + '/' file_1 = infolder + bkpt_name + \"_1.bc_windows.txt\"", "{} for key in df_1.keys(): if key != \"chrom\" and", "hap_bcs.transpose() bcs_hap_dict = {} for key in df_1.keys(): if key", "figR.set_ylabel(\"\") brkpt1 = min(df_1['window_start']) + ((max(df_1['window_end']) - min(df_1['window_start']))/2) brkpt2 =", "#go through columns (so each barcode) if name != \"chrom\"", "pd import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot", "[] i1 = 0 window_start_arr1 = df_1['window_start'] for name, values", "= infolder + bkpt_name + \"_1.bc_windows.txt\" file_2 = infolder +", "= min(df_2['window_start']) + ((max(df_2['window_end']) - min(df_2['window_start']))/2) figL.axvline(x=brkpt1, linewidth=1, color =", "= infolder + '/' file_1 = infolder + bkpt_name +", "= fig.add_subplot(122) figR.scatter(x_values_2_1, y_values_2_1, s=0.2, color='b') #same figR.scatter(x_values_2_2, y_values_2_2, s=0.2,", "to highest) # #read in data frames # df_1 =", "[] y_values_2_unassigned = [] i1 = 0 window_start_arr1 = df_1['window_start']", "hap df_1 = df_1.sort_values('window_start') df_2 = df_2.sort_values('window_start') chrom_1 = df_1.at[0,", "directory #os.chdir(\"/mnt/ix1/Projects/M002_131217_gastric/P00526/P00526_WG10_150722_gastric/A20_170516_hmw_maps/metr\") #bkpt_name = \"1\" #example: plot_bcs_bkpt(\"1\", \"/mnt/ix1/Projects/M002_131217_gastric/P00526/P00526_WG10_150722_gastric/A20_170516_hmw_maps/metr\", \"/mnt/ix1/Projects/M002_131217_gastric/P00526/P00526_WG10_150722_gastric/A20_170516_hmw_maps/metr\") def", "figL.scatter(x_values_1_1, y_values_1_1, s=0.2, color='b') #this doesn't seem to contain anything", "\"chrom\" and key != \"window_start\" and key != \"window_end\": key", "for name, values in df_1.iteritems(): #go through columns (so each", "mode import math as m import os import collections #set", "\"window_end\": i1 += 1 name = name[:-2] hap = bcs_hap_dict[name]", "name, values in df_2.iteritems(): if name != \"chrom\" and name", "s=0.2, color='g') figR.set_title(\"\") figR.set_xlabel(\"chr %d (Mb)\" %chrom_2) figR.set_ylabel(\"\") brkpt1 =", "'chrom'] x_values_1_1 = [] x_values_1_2 = [] x_values_1_unassigned = []", "figL.set_ylabel(\"SV-specific barcode\") figR = fig.add_subplot(122) figR.scatter(x_values_2_1, y_values_2_1, s=0.2, color='b') #same", "x_values_1_unassigned.append(window_start_arr1[indx]) i2 = 0 window_start_arr2 = df_2['window_start'] for name, values", "0 window_start_arr2 = df_2['window_start'] for name, values in df_2.iteritems(): if", "#same figR.scatter(x_values_2_2, y_values_2_2, s=0.2, color='r') #same figR.scatter(x_values_2_unassigned, y_values_2_unassigned, s=0.2, color='g')", "infolder + bkpt_name + \"_1.bc_windows.txt\" file_2 = infolder + bkpt_name", "= pd.read_table(file_2) hap_bcs = pd.read_table(file_hap) # bkpt_name = \"1\" #", "coordinate to highest) # #read in data frames # df_1", "+ \"_hap_bcs.txt\" df_1 = pd.read_table(file_1) df_2 = pd.read_table(file_2) hap_bcs =", "= 'unassigned' for key, values in hap_bcs.iteritems(): if values[0] !=", "!= \"window_start\" and name != \"window_end\": i1 += 1 name", "df_2.sort_values('window_start') chrom_1 = df_1.at[0, 'chrom'] chrom_2 = df_2.at[0, 'chrom'] x_values_1_1", "for key, values in hap_bcs.iteritems(): if values[0] != 'bcs': hap", "contain anything figL.scatter(x_values_1_2, y_values_1_2, s=0.2, color='r') #same figL.scatter(x_values_1_unassigned, y_values_1_unassigned, s=0.2,", "frames # df_1 = pd.read_table(file_1) # df_2 = pd.read_table(file_2) #", "1 name = name[:-2] hap = bcs_hap_dict[name] #print type(hap) int", "%chrom_1) figL.set_ylabel(\"SV-specific barcode\") figR = fig.add_subplot(122) figR.scatter(x_values_2_1, y_values_2_1, s=0.2, color='b')", "indx, window in values.iteritems(): if window != 0: if hap", "file_1 = infolder + bkpt_name + \"_1.bc_windows.txt\" file_2 = infolder", "y_values_2_2.append(i2) x_values_2_2.append(window_start_arr2[indx]) elif hap == 'unassigned': y_values_2_unassigned.append(i2) x_values_2_unassigned.append(window_start_arr2[indx]) fig =", "bcs_hap_dict[name] for indx, window in values.iteritems(): if window != 0:", "figL.set_xlabel(\"chr %d (Mb)\" %chrom_1) figL.set_ylabel(\"SV-specific barcode\") figR = fig.add_subplot(122) figR.scatter(x_values_2_1,", "min(df_1['window_start']))/2) brkpt2 = min(df_2['window_start']) + ((max(df_2['window_end']) - min(df_2['window_start']))/2) figL.axvline(x=brkpt1, linewidth=1,", "window_start_arr1 = df_1['window_start'] for name, values in df_1.iteritems(): #go through", "name != \"chrom\" and name != \"window_start\" and name !=", "import collections #set working directory #os.chdir(\"/mnt/ix1/Projects/M002_131217_gastric/P00526/P00526_WG10_150722_gastric/A20_170516_hmw_maps/metr\") #bkpt_name = \"1\" #example:", "\"window_end\": i2 += 1 name = name[:-2] hap = bcs_hap_dict[name]", "[] x_values_1_unassigned = [] y_values_1_1 = [] y_values_1_2 = []", "import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.colors import", "s=0.2, color='b') #this doesn't seem to contain anything figL.scatter(x_values_1_2, y_values_1_2,", "= [] x_values_2_1 = [] x_values_2_2 = [] x_values_2_unassigned =", "from scipy.stats import mode import math as m import os", "brkpt2 = min(df_2['window_start']) + ((max(df_2['window_end']) - min(df_2['window_start']))/2) figL.axvline(x=brkpt1, linewidth=1, color", "as m import os import collections #set working directory #os.chdir(\"/mnt/ix1/Projects/M002_131217_gastric/P00526/P00526_WG10_150722_gastric/A20_170516_hmw_maps/metr\")", "m import os import collections #set working directory #os.chdir(\"/mnt/ix1/Projects/M002_131217_gastric/P00526/P00526_WG10_150722_gastric/A20_170516_hmw_maps/metr\") #bkpt_name", "outfolder): if infolder[-1] != '/': infolder = infolder + '/'", "figR.scatter(x_values_2_1, y_values_2_1, s=0.2, color='b') #same figR.scatter(x_values_2_2, y_values_2_2, s=0.2, color='r') #same", "'/': infolder = infolder + '/' file_1 = infolder +", "!= 0: if hap == 1: y_values_2_1.append(i2) x_values_2_1.append(window_start_arr2[indx]) elif hap", "y_values_2_1.append(i2) x_values_2_1.append(window_start_arr2[indx]) elif hap == 2: y_values_2_2.append(i2) x_values_2_2.append(window_start_arr2[indx]) elif hap", "key != \"window_start\" and key != \"window_end\": key = key[:-2]", "2: y_values_2_2.append(i2) x_values_2_2.append(window_start_arr2[indx]) elif hap == 'unassigned': y_values_2_unassigned.append(i2) x_values_2_unassigned.append(window_start_arr2[indx]) fig", "doesn't seem to contain anything figL.scatter(x_values_1_2, y_values_1_2, s=0.2, color='r') #same", "plot_bcs_bkpt(bkpt_name, infolder, outfolder): if infolder[-1] != '/': infolder = infolder" ]
[ "[] not_alnum = [] for index, char in enumerate(chars): if", "f'get_index_different_char({arg}) should return index {exp}' assert get_index_different_char(arg) == exp, err", "3, 4, 5, 'A', 'b', 'a', 'b', 'c'], ['=', '=',", "list('abcde'), # noqa E231 ) expected = [2, 4, 1,", "else: not_alnum.append(index) result = alnum[0] if len(alnum) < len(not_alnum) else", "= [2, 4, 1, 5, 8] for arg, exp in", "len(not_alnum) else not_alnum[0] return result # tests def test_wrong_char(): inputs", "+ list('abcde'), # noqa E231 ) expected = [2, 4,", "zip(inputs, expected): err = f'get_index_different_char({arg}) should return index {exp}' assert", "';', '?', '¡'], list(range(1,9)) + ['}'] + list('abcde'), # noqa", "get_index_different_char(chars): alnum = [] not_alnum = [] for index, char", "def test_wrong_char(): inputs = ( ['A', 'f', '.', 'Q', 2],", "# tests def test_wrong_char(): inputs = ( ['A', 'f', '.',", "tests def test_wrong_char(): inputs = ( ['A', 'f', '.', 'Q',", "arg, exp in zip(inputs, expected): err = f'get_index_different_char({arg}) should return", "list(range(1,9)) + ['}'] + list('abcde'), # noqa E231 ) expected", "= [] for index, char in enumerate(chars): if str(char).isalnum(): alnum.append(index)", "= [] not_alnum = [] for index, char in enumerate(chars):", "alnum = [] not_alnum = [] for index, char in", "< len(not_alnum) else not_alnum[0] return result # tests def test_wrong_char():", "if str(char).isalnum(): alnum.append(index) else: not_alnum.append(index) result = alnum[0] if len(alnum)", "'/', 9, ':', ';', '?', '¡'], list(range(1,9)) + ['}'] +", "test_wrong_char(): inputs = ( ['A', 'f', '.', 'Q', 2], ['.',", "4, 5, 'A', 'b', 'a', 'b', 'c'], ['=', '=', '',", "return result # tests def test_wrong_char(): inputs = ( ['A',", "'a'], [1, '=', 3, 4, 5, 'A', 'b', 'a', 'b',", "8] for arg, exp in zip(inputs, expected): err = f'get_index_different_char({arg})", "= ( ['A', 'f', '.', 'Q', 2], ['.', '{', '", "[2, 4, 1, 5, 8] for arg, exp in zip(inputs,", "['}'] + list('abcde'), # noqa E231 ) expected = [2,", "[1, '=', 3, 4, 5, 'A', 'b', 'a', 'b', 'c'],", "'', '/', '/', 9, ':', ';', '?', '¡'], list(range(1,9)) +", "for index, char in enumerate(chars): if str(char).isalnum(): alnum.append(index) else: not_alnum.append(index)", "len(alnum) < len(not_alnum) else not_alnum[0] return result # tests def", "char in enumerate(chars): if str(char).isalnum(): alnum.append(index) else: not_alnum.append(index) result =", "else not_alnum[0] return result # tests def test_wrong_char(): inputs =", "enumerate(chars): if str(char).isalnum(): alnum.append(index) else: not_alnum.append(index) result = alnum[0] if", "# noqa E231 ) expected = [2, 4, 1, 5,", "'c'], ['=', '=', '', '/', '/', 9, ':', ';', '?',", "':', ';', '?', '¡'], list(range(1,9)) + ['}'] + list('abcde'), #", "4, 1, 5, 8] for arg, exp in zip(inputs, expected):", "= f'get_index_different_char({arg}) should return index {exp}' assert get_index_different_char(arg) == exp,", "5, 'A', 'b', 'a', 'b', 'c'], ['=', '=', '', '/',", "5, 8] for arg, exp in zip(inputs, expected): err =", "expected = [2, 4, 1, 5, 8] for arg, exp", "'{', ' ^', '%', 'a'], [1, '=', 3, 4, 5,", "'=', 3, 4, 5, 'A', 'b', 'a', 'b', 'c'], ['=',", "^', '%', 'a'], [1, '=', 3, 4, 5, 'A', 'b',", "= alnum[0] if len(alnum) < len(not_alnum) else not_alnum[0] return result", "'?', '¡'], list(range(1,9)) + ['}'] + list('abcde'), # noqa E231", "' ^', '%', 'a'], [1, '=', 3, 4, 5, 'A',", "not_alnum = [] for index, char in enumerate(chars): if str(char).isalnum():", "not_alnum.append(index) result = alnum[0] if len(alnum) < len(not_alnum) else not_alnum[0]", "result = alnum[0] if len(alnum) < len(not_alnum) else not_alnum[0] return", "'b', 'a', 'b', 'c'], ['=', '=', '', '/', '/', 9,", "9, ':', ';', '?', '¡'], list(range(1,9)) + ['}'] + list('abcde'),", "<reponame>ChidinmaKO/Chobe-bitesofpy def get_index_different_char(chars): alnum = [] not_alnum = [] for", "not_alnum[0] return result # tests def test_wrong_char(): inputs = (", "[] for index, char in enumerate(chars): if str(char).isalnum(): alnum.append(index) else:", "alnum.append(index) else: not_alnum.append(index) result = alnum[0] if len(alnum) < len(not_alnum)", "'/', '/', 9, ':', ';', '?', '¡'], list(range(1,9)) + ['}']", "alnum[0] if len(alnum) < len(not_alnum) else not_alnum[0] return result #", "in enumerate(chars): if str(char).isalnum(): alnum.append(index) else: not_alnum.append(index) result = alnum[0]", "['A', 'f', '.', 'Q', 2], ['.', '{', ' ^', '%',", "['=', '=', '', '/', '/', 9, ':', ';', '?', '¡'],", "'a', 'b', 'c'], ['=', '=', '', '/', '/', 9, ':',", "exp in zip(inputs, expected): err = f'get_index_different_char({arg}) should return index", "inputs = ( ['A', 'f', '.', 'Q', 2], ['.', '{',", "E231 ) expected = [2, 4, 1, 5, 8] for", "noqa E231 ) expected = [2, 4, 1, 5, 8]", "'=', '', '/', '/', 9, ':', ';', '?', '¡'], list(range(1,9))", "'¡'], list(range(1,9)) + ['}'] + list('abcde'), # noqa E231 )", "def get_index_different_char(chars): alnum = [] not_alnum = [] for index,", "expected): err = f'get_index_different_char({arg}) should return index {exp}' assert get_index_different_char(arg)", "( ['A', 'f', '.', 'Q', 2], ['.', '{', ' ^',", "'%', 'a'], [1, '=', 3, 4, 5, 'A', 'b', 'a',", "'b', 'c'], ['=', '=', '', '/', '/', 9, ':', ';',", "'f', '.', 'Q', 2], ['.', '{', ' ^', '%', 'a'],", "err = f'get_index_different_char({arg}) should return index {exp}' assert get_index_different_char(arg) ==", "2], ['.', '{', ' ^', '%', 'a'], [1, '=', 3,", "result # tests def test_wrong_char(): inputs = ( ['A', 'f',", "'Q', 2], ['.', '{', ' ^', '%', 'a'], [1, '=',", "str(char).isalnum(): alnum.append(index) else: not_alnum.append(index) result = alnum[0] if len(alnum) <", "for arg, exp in zip(inputs, expected): err = f'get_index_different_char({arg}) should", "['.', '{', ' ^', '%', 'a'], [1, '=', 3, 4,", "in zip(inputs, expected): err = f'get_index_different_char({arg}) should return index {exp}'", ") expected = [2, 4, 1, 5, 8] for arg,", "'.', 'Q', 2], ['.', '{', ' ^', '%', 'a'], [1,", "if len(alnum) < len(not_alnum) else not_alnum[0] return result # tests", "index, char in enumerate(chars): if str(char).isalnum(): alnum.append(index) else: not_alnum.append(index) result", "1, 5, 8] for arg, exp in zip(inputs, expected): err", "+ ['}'] + list('abcde'), # noqa E231 ) expected =", "'A', 'b', 'a', 'b', 'c'], ['=', '=', '', '/', '/'," ]
[ "Blueprint('langid', __name__) class UrlForm(FlaskForm): url = StringField( 'URL', validators=[validators.DataRequired(), validators.URL(message='Sorry,", "'Extractor', default=langid.EXTRACTORS[0], choices=[(i, i) for i in langid.EXTRACTORS], validators=[validators.DataRequired()]) model_class", "import logging from flask import Blueprint from flask import Flask,", "templated blueprint_langid = Blueprint('langid', __name__) class UrlForm(FlaskForm): url = StringField(", "wtforms.widgets import TextArea import langid from utils.utils import templated blueprint_langid", "request, flash from flask_wtf import FlaskForm from wtforms import StringField,", "@blueprint_langid.route('/text', methods=['GET', 'POST']) @templated('langid.html') def predict_text(): form = TextForm(request.form) if", "for f, errs in form.errors.items(): flash(\"%s: %s\" % (f, \"<br>\".join(errs)),", "validators.URL(message='Sorry, this is not a valid URL,')]) wMin = IntegerRangeField(", "blueprint_langid = Blueprint('langid', __name__) class UrlForm(FlaskForm): url = StringField( 'URL',", "% (f, \"<br>\".join(errs)), 'danger') return dict(form=form) try: results = langid.mixed_sentences_from_urls(", "validators=[validators.DataRequired()]) return_raw = BooleanField( 'Display raw sentences', default=False ) class", "is not a valid URL,')]) wMin = IntegerRangeField( 'Min. words',", "valid URL,')]) wMin = IntegerRangeField( 'Min. words', default=5, validators=[validators.DataRequired(), validators.NumberRange(min=1,", "sentences', default=False ) class TextForm(FlaskForm): text = StringField( 'Text', widget=TextArea(),", "return dict(form=form) return dict(form=form, results=results, labels=langid.DEFAULT_LABELS) @blueprint_langid.route('/text', methods=['GET', 'POST']) @templated('langid.html')", "from flask import Blueprint from flask import Flask, render_template, request,", "wtforms.fields.html5 import IntegerRangeField from wtforms.widgets import TextArea import langid from", "return_raw=form.return_raw.data) except Exception as e: flash('Something went wrong %s' %", "in langid.MODELS], validators=[validators.DataRequired()]) return_raw = BooleanField( 'Display raw sentences', default=False", "validators=[validators.DataRequired(), validators.URL(message='Sorry, this is not a valid URL,')]) wMin =", "= BooleanField( 'Display raw sentences', default=False ) class TextForm(FlaskForm): text", "model=form.model_class.data, with_proba=True, min_words=form.wMin.data, return_raw=form.return_raw.data) except Exception as e: flash('Something went", "extractor_name=form.extractor_class.data, model=form.model_class.data, with_proba=True, min_words=form.wMin.data, return_raw=form.return_raw.data) except Exception as e: flash('Something", "UrlForm(FlaskForm): url = StringField( 'URL', validators=[validators.DataRequired(), validators.URL(message='Sorry, this is not", "validators, SelectField, BooleanField from wtforms.fields.html5 import IntegerRangeField from wtforms.widgets import", "widget=TextArea(), validators=[validators.DataRequired()]) model_class = SelectField( 'Model', default=langid.MODELS[0], choices=[(i, i) for", "flash('Something went wrong %s' % e, 'danger') logging.exception(e) return dict(form=form)", "wtforms import StringField, validators, SelectField, BooleanField from wtforms.fields.html5 import IntegerRangeField", "import templated blueprint_langid = Blueprint('langid', __name__) class UrlForm(FlaskForm): url =", "def predict_text(): form = TextForm(request.form) if request.method == 'GET': return", "predict_text(): form = TextForm(request.form) if request.method == 'GET': return dict(form=form)", "\"<br>\".join(errs)), 'danger') return dict(form=form) results = [[r] for r in", "dict(form=form) results = [[r] for r in langid.lang_of_text( form.text.data, model=form.model_class.data,", "from flask_wtf import FlaskForm from wtforms import StringField, validators, SelectField,", "words', default=5, validators=[validators.DataRequired(), validators.NumberRange(min=1, max=20)]) extractor_class = SelectField( 'Extractor', default=langid.EXTRACTORS[0],", "for i in langid.MODELS], validators=[validators.DataRequired()]) return_raw = BooleanField( 'Display raw", "'URL', validators=[validators.DataRequired(), validators.URL(message='Sorry, this is not a valid URL,')]) wMin", "methods=['GET', 'POST']) @templated('langid.html') def predict_text(): form = TextForm(request.form) if request.method", "Flask, render_template, request, flash from flask_wtf import FlaskForm from wtforms", "from flask import Flask, render_template, request, flash from flask_wtf import", "r in langid.lang_of_text( form.text.data, model=form.model_class.data, with_proba=True)] return dict(form=form, results=results, labels=langid.DEFAULT_LABELS)", "import IntegerRangeField from wtforms.widgets import TextArea import langid from utils.utils", "in langid.MODELS], validators=[validators.DataRequired()]) @blueprint_langid.route('/', methods=['GET', 'POST']) @templated('index.html') def crawl(): form", "% (f, \"<br>\".join(errs)), 'danger') return dict(form=form) results = [[r] for", "= IntegerRangeField( 'Min. words', default=5, validators=[validators.DataRequired(), validators.NumberRange(min=1, max=20)]) extractor_class =", "'POST']) @templated('langid.html') def predict_text(): form = TextForm(request.form) if request.method ==", "url = StringField( 'URL', validators=[validators.DataRequired(), validators.URL(message='Sorry, this is not a", "= StringField( 'Text', widget=TextArea(), validators=[validators.DataRequired()]) model_class = SelectField( 'Model', default=langid.MODELS[0],", "logging.exception(e) return dict(form=form) return dict(form=form, results=results, labels=langid.DEFAULT_LABELS) @blueprint_langid.route('/text', methods=['GET', 'POST'])", "f, errs in form.errors.items(): flash(\"%s: %s\" % (f, \"<br>\".join(errs)), 'danger')", "e: flash('Something went wrong %s' % e, 'danger') logging.exception(e) return", "import TextArea import langid from utils.utils import templated blueprint_langid =", "results=results, labels=langid.DEFAULT_LABELS) @blueprint_langid.route('/text', methods=['GET', 'POST']) @templated('langid.html') def predict_text(): form =", "IntegerRangeField( 'Min. words', default=5, validators=[validators.DataRequired(), validators.NumberRange(min=1, max=20)]) extractor_class = SelectField(", "i in langid.EXTRACTORS], validators=[validators.DataRequired()]) model_class = SelectField( 'Model', default=langid.MODELS[0], choices=[(i,", "utils.utils import templated blueprint_langid = Blueprint('langid', __name__) class UrlForm(FlaskForm): url", "logging from flask import Blueprint from flask import Flask, render_template,", "choices=[(i, i) for i in langid.MODELS], validators=[validators.DataRequired()]) @blueprint_langid.route('/', methods=['GET', 'POST'])", "@blueprint_langid.route('/', methods=['GET', 'POST']) @templated('index.html') def crawl(): form = UrlForm(request.form) if", "wMin = IntegerRangeField( 'Min. words', default=5, validators=[validators.DataRequired(), validators.NumberRange(min=1, max=20)]) extractor_class", "flask import Blueprint from flask import Flask, render_template, request, flash", "'POST']) @templated('index.html') def crawl(): form = UrlForm(request.form) if request.method ==", "TextForm(request.form) if request.method == 'GET': return dict(form=form) elif not form.validate():", "try: results = langid.mixed_sentences_from_urls( form.url.data.strip(), extractor_name=form.extractor_class.data, model=form.model_class.data, with_proba=True, min_words=form.wMin.data, return_raw=form.return_raw.data)", "e, 'danger') logging.exception(e) return dict(form=form) return dict(form=form, results=results, labels=langid.DEFAULT_LABELS) @blueprint_langid.route('/text',", "form.url.data.strip(), extractor_name=form.extractor_class.data, model=form.model_class.data, with_proba=True, min_words=form.wMin.data, return_raw=form.return_raw.data) except Exception as e:", "default=langid.MODELS[0], choices=[(i, i) for i in langid.MODELS], validators=[validators.DataRequired()]) return_raw =", "form = UrlForm(request.form) if request.method == 'GET': return dict(form=form) elif", "default=False ) class TextForm(FlaskForm): text = StringField( 'Text', widget=TextArea(), validators=[validators.DataRequired()])", "default=5, validators=[validators.DataRequired(), validators.NumberRange(min=1, max=20)]) extractor_class = SelectField( 'Extractor', default=langid.EXTRACTORS[0], choices=[(i,", "raw sentences', default=False ) class TextForm(FlaskForm): text = StringField( 'Text',", ") class TextForm(FlaskForm): text = StringField( 'Text', widget=TextArea(), validators=[validators.DataRequired()]) model_class", "SelectField( 'Extractor', default=langid.EXTRACTORS[0], choices=[(i, i) for i in langid.EXTRACTORS], validators=[validators.DataRequired()])", "default=langid.EXTRACTORS[0], choices=[(i, i) for i in langid.EXTRACTORS], validators=[validators.DataRequired()]) model_class =", "import langid from utils.utils import templated blueprint_langid = Blueprint('langid', __name__)", "form.errors.items(): flash(\"%s: %s\" % (f, \"<br>\".join(errs)), 'danger') return dict(form=form) try:", "return dict(form=form, results=results, labels=langid.DEFAULT_LABELS) @blueprint_langid.route('/text', methods=['GET', 'POST']) @templated('langid.html') def predict_text():", "= StringField( 'URL', validators=[validators.DataRequired(), validators.URL(message='Sorry, this is not a valid", "choices=[(i, i) for i in langid.EXTRACTORS], validators=[validators.DataRequired()]) model_class = SelectField(", "%s\" % (f, \"<br>\".join(errs)), 'danger') return dict(form=form) results = [[r]", "langid.MODELS], validators=[validators.DataRequired()]) @blueprint_langid.route('/', methods=['GET', 'POST']) @templated('index.html') def crawl(): form =", "StringField, validators, SelectField, BooleanField from wtforms.fields.html5 import IntegerRangeField from wtforms.widgets", "import StringField, validators, SelectField, BooleanField from wtforms.fields.html5 import IntegerRangeField from", "validators=[validators.DataRequired(), validators.NumberRange(min=1, max=20)]) extractor_class = SelectField( 'Extractor', default=langid.EXTRACTORS[0], choices=[(i, i)", "URL,')]) wMin = IntegerRangeField( 'Min. words', default=5, validators=[validators.DataRequired(), validators.NumberRange(min=1, max=20)])", "if request.method == 'GET': return dict(form=form) elif not form.validate(): for", "import Flask, render_template, request, flash from flask_wtf import FlaskForm from", "class UrlForm(FlaskForm): url = StringField( 'URL', validators=[validators.DataRequired(), validators.URL(message='Sorry, this is", "[[r] for r in langid.lang_of_text( form.text.data, model=form.model_class.data, with_proba=True)] return dict(form=form,", "i) for i in langid.EXTRACTORS], validators=[validators.DataRequired()]) model_class = SelectField( 'Model',", "% e, 'danger') logging.exception(e) return dict(form=form) return dict(form=form, results=results, labels=langid.DEFAULT_LABELS)", "StringField( 'Text', widget=TextArea(), validators=[validators.DataRequired()]) model_class = SelectField( 'Model', default=langid.MODELS[0], choices=[(i,", "went wrong %s' % e, 'danger') logging.exception(e) return dict(form=form) return", "i in langid.MODELS], validators=[validators.DataRequired()]) return_raw = BooleanField( 'Display raw sentences',", "= SelectField( 'Model', default=langid.MODELS[0], choices=[(i, i) for i in langid.MODELS],", "langid.EXTRACTORS], validators=[validators.DataRequired()]) model_class = SelectField( 'Model', default=langid.MODELS[0], choices=[(i, i) for", "'Min. words', default=5, validators=[validators.DataRequired(), validators.NumberRange(min=1, max=20)]) extractor_class = SelectField( 'Extractor',", "crawl(): form = UrlForm(request.form) if request.method == 'GET': return dict(form=form)", "model_class = SelectField( 'Model', default=langid.MODELS[0], choices=[(i, i) for i in", "dict(form=form) return dict(form=form, results=results, labels=langid.DEFAULT_LABELS) @blueprint_langid.route('/text', methods=['GET', 'POST']) @templated('langid.html') def", "TextArea import langid from utils.utils import templated blueprint_langid = Blueprint('langid',", "for r in langid.lang_of_text( form.text.data, model=form.model_class.data, with_proba=True)] return dict(form=form, results=results,", "in form.errors.items(): flash(\"%s: %s\" % (f, \"<br>\".join(errs)), 'danger') return dict(form=form)", "flash from flask_wtf import FlaskForm from wtforms import StringField, validators,", "request.method == 'GET': return dict(form=form) elif not form.validate(): for f,", "@templated('langid.html') def predict_text(): form = TextForm(request.form) if request.method == 'GET':", "return dict(form=form) results = [[r] for r in langid.lang_of_text( form.text.data,", "elif not form.validate(): for f, errs in form.errors.items(): flash(\"%s: %s\"", "Exception as e: flash('Something went wrong %s' % e, 'danger')", "= Blueprint('langid', __name__) class UrlForm(FlaskForm): url = StringField( 'URL', validators=[validators.DataRequired(),", "TextForm(FlaskForm): text = StringField( 'Text', widget=TextArea(), validators=[validators.DataRequired()]) model_class = SelectField(", "'danger') return dict(form=form) results = [[r] for r in langid.lang_of_text(", "(f, \"<br>\".join(errs)), 'danger') return dict(form=form) try: results = langid.mixed_sentences_from_urls( form.url.data.strip(),", "= TextForm(request.form) if request.method == 'GET': return dict(form=form) elif not", "langid from utils.utils import templated blueprint_langid = Blueprint('langid', __name__) class", "from wtforms.fields.html5 import IntegerRangeField from wtforms.widgets import TextArea import langid", "import Blueprint from flask import Flask, render_template, request, flash from", "%s\" % (f, \"<br>\".join(errs)), 'danger') return dict(form=form) try: results =", "form.validate(): for f, errs in form.errors.items(): flash(\"%s: %s\" % (f,", "flash(\"%s: %s\" % (f, \"<br>\".join(errs)), 'danger') return dict(form=form) try: results", "langid.mixed_sentences_from_urls( form.url.data.strip(), extractor_name=form.extractor_class.data, model=form.model_class.data, with_proba=True, min_words=form.wMin.data, return_raw=form.return_raw.data) except Exception as", "import FlaskForm from wtforms import StringField, validators, SelectField, BooleanField from", "from wtforms import StringField, validators, SelectField, BooleanField from wtforms.fields.html5 import", "a valid URL,')]) wMin = IntegerRangeField( 'Min. words', default=5, validators=[validators.DataRequired(),", "validators=[validators.DataRequired()]) @blueprint_langid.route('/', methods=['GET', 'POST']) @templated('index.html') def crawl(): form = UrlForm(request.form)", "== 'GET': return dict(form=form) elif not form.validate(): for f, errs", "for i in langid.MODELS], validators=[validators.DataRequired()]) @blueprint_langid.route('/', methods=['GET', 'POST']) @templated('index.html') def", "def crawl(): form = UrlForm(request.form) if request.method == 'GET': return", "class TextForm(FlaskForm): text = StringField( 'Text', widget=TextArea(), validators=[validators.DataRequired()]) model_class =", "return_raw = BooleanField( 'Display raw sentences', default=False ) class TextForm(FlaskForm):", "i) for i in langid.MODELS], validators=[validators.DataRequired()]) return_raw = BooleanField( 'Display", "= UrlForm(request.form) if request.method == 'GET': return dict(form=form) elif not", "form = TextForm(request.form) if request.method == 'GET': return dict(form=form) elif", "(f, \"<br>\".join(errs)), 'danger') return dict(form=form) results = [[r] for r", "dict(form=form) try: results = langid.mixed_sentences_from_urls( form.url.data.strip(), extractor_name=form.extractor_class.data, model=form.model_class.data, with_proba=True, min_words=form.wMin.data,", "as e: flash('Something went wrong %s' % e, 'danger') logging.exception(e)", "flash(\"%s: %s\" % (f, \"<br>\".join(errs)), 'danger') return dict(form=form) results =", "'Model', default=langid.MODELS[0], choices=[(i, i) for i in langid.MODELS], validators=[validators.DataRequired()]) @blueprint_langid.route('/',", "\"<br>\".join(errs)), 'danger') return dict(form=form) try: results = langid.mixed_sentences_from_urls( form.url.data.strip(), extractor_name=form.extractor_class.data,", "FlaskForm from wtforms import StringField, validators, SelectField, BooleanField from wtforms.fields.html5", "i in langid.MODELS], validators=[validators.DataRequired()]) @blueprint_langid.route('/', methods=['GET', 'POST']) @templated('index.html') def crawl():", "dict(form=form) elif not form.validate(): for f, errs in form.errors.items(): flash(\"%s:", "__name__) class UrlForm(FlaskForm): url = StringField( 'URL', validators=[validators.DataRequired(), validators.URL(message='Sorry, this", "dict(form=form, results=results, labels=langid.DEFAULT_LABELS) @blueprint_langid.route('/text', methods=['GET', 'POST']) @templated('langid.html') def predict_text(): form", "'Model', default=langid.MODELS[0], choices=[(i, i) for i in langid.MODELS], validators=[validators.DataRequired()]) return_raw", "labels=langid.DEFAULT_LABELS) @blueprint_langid.route('/text', methods=['GET', 'POST']) @templated('langid.html') def predict_text(): form = TextForm(request.form)", "= SelectField( 'Extractor', default=langid.EXTRACTORS[0], choices=[(i, i) for i in langid.EXTRACTORS],", "'GET': return dict(form=form) elif not form.validate(): for f, errs in", "from wtforms.widgets import TextArea import langid from utils.utils import templated", "this is not a valid URL,')]) wMin = IntegerRangeField( 'Min.", "max=20)]) extractor_class = SelectField( 'Extractor', default=langid.EXTRACTORS[0], choices=[(i, i) for i", "BooleanField( 'Display raw sentences', default=False ) class TextForm(FlaskForm): text =", "i) for i in langid.MODELS], validators=[validators.DataRequired()]) @blueprint_langid.route('/', methods=['GET', 'POST']) @templated('index.html')", "'Text', widget=TextArea(), validators=[validators.DataRequired()]) model_class = SelectField( 'Model', default=langid.MODELS[0], choices=[(i, i)", "'danger') logging.exception(e) return dict(form=form) return dict(form=form, results=results, labels=langid.DEFAULT_LABELS) @blueprint_langid.route('/text', methods=['GET',", "form.errors.items(): flash(\"%s: %s\" % (f, \"<br>\".join(errs)), 'danger') return dict(form=form) results", "'Display raw sentences', default=False ) class TextForm(FlaskForm): text = StringField(", "@templated('index.html') def crawl(): form = UrlForm(request.form) if request.method == 'GET':", "extractor_class = SelectField( 'Extractor', default=langid.EXTRACTORS[0], choices=[(i, i) for i in", "= [[r] for r in langid.lang_of_text( form.text.data, model=form.model_class.data, with_proba=True)] return", "validators=[validators.DataRequired()]) model_class = SelectField( 'Model', default=langid.MODELS[0], choices=[(i, i) for i", "errs in form.errors.items(): flash(\"%s: %s\" % (f, \"<br>\".join(errs)), 'danger') return", "IntegerRangeField from wtforms.widgets import TextArea import langid from utils.utils import", "BooleanField from wtforms.fields.html5 import IntegerRangeField from wtforms.widgets import TextArea import", "min_words=form.wMin.data, return_raw=form.return_raw.data) except Exception as e: flash('Something went wrong %s'", "SelectField, BooleanField from wtforms.fields.html5 import IntegerRangeField from wtforms.widgets import TextArea", "from utils.utils import templated blueprint_langid = Blueprint('langid', __name__) class UrlForm(FlaskForm):", "StringField( 'URL', validators=[validators.DataRequired(), validators.URL(message='Sorry, this is not a valid URL,')])", "flask_wtf import FlaskForm from wtforms import StringField, validators, SelectField, BooleanField", "except Exception as e: flash('Something went wrong %s' % e,", "return dict(form=form) try: results = langid.mixed_sentences_from_urls( form.url.data.strip(), extractor_name=form.extractor_class.data, model=form.model_class.data, with_proba=True,", "validators.NumberRange(min=1, max=20)]) extractor_class = SelectField( 'Extractor', default=langid.EXTRACTORS[0], choices=[(i, i) for", "flask import Flask, render_template, request, flash from flask_wtf import FlaskForm", "with_proba=True, min_words=form.wMin.data, return_raw=form.return_raw.data) except Exception as e: flash('Something went wrong", "Blueprint from flask import Flask, render_template, request, flash from flask_wtf", "'danger') return dict(form=form) try: results = langid.mixed_sentences_from_urls( form.url.data.strip(), extractor_name=form.extractor_class.data, model=form.model_class.data,", "%s' % e, 'danger') logging.exception(e) return dict(form=form) return dict(form=form, results=results,", "not form.validate(): for f, errs in form.errors.items(): flash(\"%s: %s\" %", "UrlForm(request.form) if request.method == 'GET': return dict(form=form) elif not form.validate():", "results = langid.mixed_sentences_from_urls( form.url.data.strip(), extractor_name=form.extractor_class.data, model=form.model_class.data, with_proba=True, min_words=form.wMin.data, return_raw=form.return_raw.data) except", "default=langid.MODELS[0], choices=[(i, i) for i in langid.MODELS], validators=[validators.DataRequired()]) @blueprint_langid.route('/', methods=['GET',", "methods=['GET', 'POST']) @templated('index.html') def crawl(): form = UrlForm(request.form) if request.method", "= langid.mixed_sentences_from_urls( form.url.data.strip(), extractor_name=form.extractor_class.data, model=form.model_class.data, with_proba=True, min_words=form.wMin.data, return_raw=form.return_raw.data) except Exception", "langid.MODELS], validators=[validators.DataRequired()]) return_raw = BooleanField( 'Display raw sentences', default=False )", "choices=[(i, i) for i in langid.MODELS], validators=[validators.DataRequired()]) return_raw = BooleanField(", "return dict(form=form) elif not form.validate(): for f, errs in form.errors.items():", "text = StringField( 'Text', widget=TextArea(), validators=[validators.DataRequired()]) model_class = SelectField( 'Model',", "render_template, request, flash from flask_wtf import FlaskForm from wtforms import", "results = [[r] for r in langid.lang_of_text( form.text.data, model=form.model_class.data, with_proba=True)]", "not a valid URL,')]) wMin = IntegerRangeField( 'Min. words', default=5,", "SelectField( 'Model', default=langid.MODELS[0], choices=[(i, i) for i in langid.MODELS], validators=[validators.DataRequired()])", "for i in langid.EXTRACTORS], validators=[validators.DataRequired()]) model_class = SelectField( 'Model', default=langid.MODELS[0],", "wrong %s' % e, 'danger') logging.exception(e) return dict(form=form) return dict(form=form,", "in langid.EXTRACTORS], validators=[validators.DataRequired()]) model_class = SelectField( 'Model', default=langid.MODELS[0], choices=[(i, i)" ]
[ "# SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class", "and extension, while simplifying cross-class interoperability.\"\"\" homepage = \"http://r-forge.r-project.org/projects/xts/\" url", "by extending zoo, maximizing native format information preservation and allowing", "RXts(RPackage): \"\"\"Provide for uniform handling of R's different time-based data", "while simplifying cross-class interoperability.\"\"\" homepage = \"http://r-forge.r-project.org/projects/xts/\" url = \"https://cloud.r-project.org/src/contrib/xts_0.11-2.tar.gz\"", "# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other", "cross-class interoperability.\"\"\" homepage = \"http://r-forge.r-project.org/projects/xts/\" url = \"https://cloud.r-project.org/src/contrib/xts_0.11-2.tar.gz\" list_url =", "for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack", "homepage = \"http://r-forge.r-project.org/projects/xts/\" url = \"https://cloud.r-project.org/src/contrib/xts_0.11-2.tar.gz\" list_url = \"https://cloud.r-project.org/src/contrib/Archive/xts\" version('0.11-2',", "Spack Project Developers. See the top-level COPYRIGHT file for details.", "MIT) from spack import * class RXts(RPackage): \"\"\"Provide for uniform", "2013-2021 Lawrence Livermore National Security, LLC and other # Spack", "\"https://cloud.r-project.org/src/contrib/xts_0.11-2.tar.gz\" list_url = \"https://cloud.r-project.org/src/contrib/Archive/xts\" version('0.11-2', sha256='12772f6a66aab5b84b0665c470f11a3d8d8a992955c027261cfe8e6077ee13b8') version('0.9-7', sha256='f11f7cb98f4b92b7f6632a2151257914130880c267736ef5a264b5dc2dfb7098') depends_on('r-zoo@1.7-12:', type=('build',", "National Security, LLC and other # Spack Project Developers. See", "* class RXts(RPackage): \"\"\"Provide for uniform handling of R's different", "LLC and other # Spack Project Developers. See the top-level", "level customization and extension, while simplifying cross-class interoperability.\"\"\" homepage =", "\"http://r-forge.r-project.org/projects/xts/\" url = \"https://cloud.r-project.org/src/contrib/xts_0.11-2.tar.gz\" list_url = \"https://cloud.r-project.org/src/contrib/Archive/xts\" version('0.11-2', sha256='12772f6a66aab5b84b0665c470f11a3d8d8a992955c027261cfe8e6077ee13b8') version('0.9-7',", "SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RXts(RPackage):", "information preservation and allowing for user level customization and extension,", "spack import * class RXts(RPackage): \"\"\"Provide for uniform handling of", "format information preservation and allowing for user level customization and", "Security, LLC and other # Spack Project Developers. See the", "details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import", "url = \"https://cloud.r-project.org/src/contrib/xts_0.11-2.tar.gz\" list_url = \"https://cloud.r-project.org/src/contrib/Archive/xts\" version('0.11-2', sha256='12772f6a66aab5b84b0665c470f11a3d8d8a992955c027261cfe8e6077ee13b8') version('0.9-7', sha256='f11f7cb98f4b92b7f6632a2151257914130880c267736ef5a264b5dc2dfb7098')", "simplifying cross-class interoperability.\"\"\" homepage = \"http://r-forge.r-project.org/projects/xts/\" url = \"https://cloud.r-project.org/src/contrib/xts_0.11-2.tar.gz\" list_url", "list_url = \"https://cloud.r-project.org/src/contrib/Archive/xts\" version('0.11-2', sha256='12772f6a66aab5b84b0665c470f11a3d8d8a992955c027261cfe8e6077ee13b8') version('0.9-7', sha256='f11f7cb98f4b92b7f6632a2151257914130880c267736ef5a264b5dc2dfb7098') depends_on('r-zoo@1.7-12:', type=('build', 'run'))", "handling of R's different time-based data classes by extending zoo,", "time-based data classes by extending zoo, maximizing native format information", "for uniform handling of R's different time-based data classes by", "extending zoo, maximizing native format information preservation and allowing for", "for user level customization and extension, while simplifying cross-class interoperability.\"\"\"", "See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier:", "data classes by extending zoo, maximizing native format information preservation", "allowing for user level customization and extension, while simplifying cross-class", "OR MIT) from spack import * class RXts(RPackage): \"\"\"Provide for", "and other # Spack Project Developers. See the top-level COPYRIGHT", "# # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import *", "preservation and allowing for user level customization and extension, while", "zoo, maximizing native format information preservation and allowing for user", "Copyright 2013-2021 Lawrence Livermore National Security, LLC and other #", "interoperability.\"\"\" homepage = \"http://r-forge.r-project.org/projects/xts/\" url = \"https://cloud.r-project.org/src/contrib/xts_0.11-2.tar.gz\" list_url = \"https://cloud.r-project.org/src/contrib/Archive/xts\"", "the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0", "class RXts(RPackage): \"\"\"Provide for uniform handling of R's different time-based", "\"\"\"Provide for uniform handling of R's different time-based data classes", "different time-based data classes by extending zoo, maximizing native format", "customization and extension, while simplifying cross-class interoperability.\"\"\" homepage = \"http://r-forge.r-project.org/projects/xts/\"", "file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from", "# Spack Project Developers. See the top-level COPYRIGHT file for", "classes by extending zoo, maximizing native format information preservation and", "uniform handling of R's different time-based data classes by extending", "Project Developers. See the top-level COPYRIGHT file for details. #", "Lawrence Livermore National Security, LLC and other # Spack Project", "R's different time-based data classes by extending zoo, maximizing native", "and allowing for user level customization and extension, while simplifying", "(Apache-2.0 OR MIT) from spack import * class RXts(RPackage): \"\"\"Provide", "of R's different time-based data classes by extending zoo, maximizing", "Developers. See the top-level COPYRIGHT file for details. # #", "user level customization and extension, while simplifying cross-class interoperability.\"\"\" homepage", "extension, while simplifying cross-class interoperability.\"\"\" homepage = \"http://r-forge.r-project.org/projects/xts/\" url =", "from spack import * class RXts(RPackage): \"\"\"Provide for uniform handling", "= \"http://r-forge.r-project.org/projects/xts/\" url = \"https://cloud.r-project.org/src/contrib/xts_0.11-2.tar.gz\" list_url = \"https://cloud.r-project.org/src/contrib/Archive/xts\" version('0.11-2', sha256='12772f6a66aab5b84b0665c470f11a3d8d8a992955c027261cfe8e6077ee13b8')", "= \"https://cloud.r-project.org/src/contrib/xts_0.11-2.tar.gz\" list_url = \"https://cloud.r-project.org/src/contrib/Archive/xts\" version('0.11-2', sha256='12772f6a66aab5b84b0665c470f11a3d8d8a992955c027261cfe8e6077ee13b8') version('0.9-7', sha256='f11f7cb98f4b92b7f6632a2151257914130880c267736ef5a264b5dc2dfb7098') depends_on('r-zoo@1.7-12:',", "Livermore National Security, LLC and other # Spack Project Developers.", "other # Spack Project Developers. See the top-level COPYRIGHT file", "maximizing native format information preservation and allowing for user level", "COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT)", "top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR", "native format information preservation and allowing for user level customization", "import * class RXts(RPackage): \"\"\"Provide for uniform handling of R's" ]
[ "if reload: item.load() res.append(item) if item.id not in ids_done: ids_done.append(item.id)", "is free software: you can redistribute it and/or modify #", "= name # means we need to remember the parent", "def _new(self, name, jsxobject=None, autosave=True, **kwargs): \"\"\" :param name: for", "= [i.name for i in Item.select()] if len(res) > 50:", "ids = self._model.find_ids(**kwargs) for id in ids: if id not", "autosave=autosave, **kwargs) self._check(jsconfig) return jsconfig def _check_children(self): if not self._cache_use:", "key in props: kwargs_to_obj_new[key] = val else: kwargs_to_class[key] = val", "item in self.find(): try: item.delete() except Exception as e: j.shell()", "ids_done.append(item.id) kwargs = self._kwargs_update(kwargs) # this is more efficient no", "\"\"\" :param name: :return: \"\"\" self._delete(name=name) def _delete(self, name=None): if", "only use the index return self.count(name=name) == 1 def _children_get(self,", "\"\"\" it it exists will delete if first when delete", "in Belgium will get the Copyright & Authorship for all", "the safe bet) assert jsconfig._id > 0 mother_id = jsconfig._mother_id_get()", "kwargs = self._kwargs_update(kwargs) # TODO do proper count query return", "if filter and filter != \"*\": condition = Item.name.startswith(filter) and", "reload=False, **kwargs): \"\"\" :param name: of the object \"\"\" #", "self._classname)) # new = False res = self.find(name=name) if len(res)", "at <https://github.com/threefoldtech>. # jumpscale is free software: you can redistribute", ":return: \"\"\" self._delete(name=name) def _delete(self, name=None): if name: _, child", "else: match = False if match: if reload: item.load() res.append(item)", "e.g. color=\"red\",... :return: list of the config objects \"\"\" res", "find(self, reload=False, **kwargs): \"\"\" :param kwargs: e.g. color=\"red\",... :return: list", "mother_id if filter and filter != \"*\": condition = Item.name.startswith(filter)", "WITHOUT ANY WARRANTY; without even the implied warranty of #", ":param name: :param jsxobject: :param autosave: sets the autosave argument", "\"\"\" :param name: for the CONFIG item (is a unique", "= [] for _, item in self._children.items(): x.append(item) x =", "die=False) if child: return child.delete() else: return self.reset() if not", "in ids_done: ids_done.append(item.id) kwargs = self._kwargs_update(kwargs) # this is more", "in ids: if id not in ids_done: item = self.get(id=id,", "import JSConfigBCDBBase class JSConfigsBCDB(JSConfigBCDBBase): def _childclass_selector(self, jsxobject, **kwargs): \"\"\" allow", "now the safe bet) assert jsconfig._id > 0 mother_id =", "self._get(name=name, die=False) if child: return child.delete() else: return self.reset() if", "self._children == {} def _check(self, jsconfig): if jsconfig._id is None:", "reload=reload, autosave=False) res.append(item) return res def _kwargs_update(self, kwargs): mother_id =", "under the terms of the GNU General Public License as", "# jumpscale is distributed in the hope that it will", "self._kwargs_update(kwargs) # this is more efficient no need to go", "res = [] ids_done = [] for key, item in", "_, child = self._get(name=name, die=False) if child: return child.delete() else:", "else: kwargs_to_class[key] = val jsxobject = self._model.new(data=kwargs_to_obj_new) else: jsxobject =", "== mother_id if filter and filter != \"*\": condition =", "_ when * at end it will be considered a", "[] for _, item in self._children.items(): x.append(item) x = self._filter(filter=filter,", "came from DB and schema is not same as config", "from Jumpscale import j from .JSConfigBCDBBase import JSConfigBCDBBase class JSConfigsBCDB(JSConfigBCDBBase):", "**kwargs) else: # check that the stored values correspond with", "at start it will be considered a end of line", "# new = False res = self.find(name=name) if len(res) <", "be considered a end of line filter (endswith) when R", "objects \"\"\" kwargs = self._kwargs_update(kwargs) # TODO do proper count", "return jsconfig def _check_children(self): if not self._cache_use: assert self._children ==", "the license will automatically become Apache v2 for all code", "warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.", "return 2, jsxconfig def reset(self): \"\"\" will destroy all data", "= self.find(name=name) if len(res) < 1: if not die: return", "Jumpscale import j from .JSConfigBCDBBase import JSConfigBCDBBase class JSConfigsBCDB(JSConfigBCDBBase): def", "val jsxobject = self._model.new(data=kwargs_to_obj_new) else: jsxobject = self._model.new() jsxobject.name =", "!= mother_id: jsxobject.mother_id = mother_id jsconfig_klass = self._childclass_selector(jsxobject=jsxobject) jsconfig =", "any later version. # # jumpscale is distributed in the", "if not jsconfig: self._log_debug(\"NEW OBJ:%s:%s\" % (name, self._classname)) jsconfig =", "for _, item in self._children.items(): x.append(item) x = self._filter(filter=filter, llist=x,", "self._children) rc, jsconfig = self._get(name=name, id=id, die=needexist, reload=reload) if not", "license will automatically become Apache v2 for all code related", "before the function returns. If set to False, you need", "or # (at your option) any later version. # #", "def reset(self): \"\"\" will destroy all data in the DB,", "autosave=True, **kwargs): \"\"\" :param name: for the CONFIG item (is", "already in mem ids = self._model.find_ids(**kwargs) for id in ids:", "!= getattr(item, key): match = False else: match = False", "PURPOSE. See the # GNU General Public License v3 for", "return 1, self._new(name, obj) obj = self._validate_child(name) if obj: if", "in self.find(): try: item.delete() except Exception as e: j.shell() if", "jsxobject=None, autosave=True, **kwargs): \"\"\" it it exists will delete if", "autosave=True, reload=False, **kwargs): \"\"\" :param name: of the object \"\"\"", "of bankruptcy) # then Incubaid NV also in Belgium will", "mother_id: condition = Item.mother_id == mother_id if filter and filter", "be smarter in how we use the index for item", "all changes made since July 2018 # and the license", "self.reset() if not name and self._parent: if self._classname in self._parent._children:", "config objects \"\"\" kwargs = self._kwargs_update(kwargs) # TODO do proper", "but for now the safe bet) assert jsconfig._id > 0", "def new(self, name, jsxobject=None, autosave=True, **kwargs): \"\"\" it it exists", "when R as first char its considered to be a", "Foundation, either version 3 of the License, or # (at", "isinstance(self._parent, j.baseclasses.factory): # only delete when not a factory means", "from DB and schema is not same as config mgmt", "(the data of the model) \"\"\" kwargs = self._kwargs_update(kwargs) return", "assert jsconfig.mother_id == mother_id assert jsconfig._model.schema._md5 == self._model.schema._md5 def _new(self,", "autosave=True): if id: obj = self._model.get(id) name = obj.name return", "Item.mother_id == mother_id if filter and filter != \"*\": condition", "_delete(self, name=None): if name: _, child = self._get(name=name, die=False) if", "\"\"\" self._delete(name=name) def _delete(self, name=None): if name: _, child =", "# LICENSE END from Jumpscale import j from .JSConfigBCDBBase import", "raise j.exceptions.Base( \"Found more than 1 service for :%s, name", "item._hasattr(key): if val != getattr(item, key): match = False else:", "will ignore _ when * at end it will be", "no check required yet return # lets do some tests", "in x: x.append(item) return x def __str__(self): return \"jsxconfigobj:collection:%s\" %", "Item.name.startswith(filter) and condition if condition else Item.name.startswith(filter) if condition: res", "Authorship for all changes made since July 2018 # and", "file is part of jumpscale at <https://github.com/threefoldtech>. # jumpscale is", "True for key, val in kwargs.items(): if item._hasattr(key): if val", "if kwargs: kwargs_to_obj_new = {} props = [i.name for i", "Item.name.startswith(filter) if condition: res = [i.name for i in Item.select().where(condition)]", "self._new(name, obj) obj = self._validate_child(name) if obj: if reload: obj.load()", ":return: the service \"\"\" kwargs_to_class = {} if not jsxobject:", "self._mother_id_get() if mother_id: if jsxobject.mother_id != mother_id: jsxobject.mother_id = mother_id", "specify the jsxobject :param kwargs: the data elements which will", "\"\"\" kwargs = self._kwargs_update(kwargs) # TODO do proper count query", "GNU General Public License # along with jumpscale or jumpscale", "class we're building del self._parent._children[self._data.name] def exists(self, name=\"main\"): \"\"\" :param", "do new object, exists\") jsconfig = self._new(name=name, jsxobject=jsxobject, autosave=autosave, **kwargs)", "child:'%s'from '%s'\" % (name, self._classname)) # new = False res", "use the index for item in self.find(): if item not", "factory means is a custom class we're building del self._parent._children[self._data.name]", "A PARTICULAR PURPOSE. See the # GNU General Public License", "the Free Software Foundation, either version 3 of the License,", "become Apache v2 for all code related to Jumpscale &", "for item in self.find(): if item not in x: x.append(item)", "then will show all, if None will ignore _ when", "j from .JSConfigBCDBBase import JSConfigBCDBBase class JSConfigsBCDB(JSConfigBCDBBase): def _childclass_selector(self, jsxobject,", "self._model.schema._md5 def _new(self, name, jsxobject=None, autosave=True, **kwargs): \"\"\" :param name:", ":return: \"\"\" self._log_debug(\"reset all data\") for item in self.find(): try:", "jsxconfig = res[0] jsxconfig._autosave = autosave return 2, jsxconfig def", "even the implied warranty of # MERCHANTABILITY or FITNESS FOR", "in self.find(): if item not in x: x.append(item) return x", "your option) any later version. # # jumpscale is distributed", "if jsconfig._id is None: # model has never been saved", "free software: you can redistribute it and/or modify # it", "config mgmt class j.shell() changed = False jsconfig._data._autosave = False", "data in the DB, be carefull :return: \"\"\" self._log_debug(\"reset all", "if not self._mother_id_get(): self._model.index.destroy() def _children_names_get(self, filter=None): condition = False", "= [] for key, item in list(self._children.items()): match = True", "e.g. color=\"red\",... :return: list of the data objects (the data", "if obj: return True # will only use the index", "or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU", "the implied warranty of # MERCHANTABILITY or FITNESS FOR A", "the autosave argument on the data and also saves the", "JSConfigBCDBBase class JSConfigsBCDB(JSConfigBCDBBase): def _childclass_selector(self, jsxobject, **kwargs): \"\"\" allow custom", "if mother_id: assert jsconfig.mother_id == mother_id assert jsconfig._model.schema._md5 == self._model.schema._md5", "jsconfig._autosave = autosave # lets do some tests (maybe in", "data came from DB and schema is not same as", "kwargs: e.g. color=\"red\",... :return: list of the data objects (the", "self.find(name=name) if len(res) < 1: if not die: return 3,", "jsxobject=jsxobject, autosave=autosave, **kwargs) self._check(jsconfig) return jsconfig def _check_children(self): if not", "saved no check required yet return # lets do some", "in kwargs.items(): if item._hasattr(key): if val != getattr(item, key): match", "x: x.append(item) return x def __str__(self): return \"jsxconfigobj:collection:%s\" % self._model.schema.url", "= self._model.new(data=kwargs_to_obj_new) else: jsxobject = self._model.new() jsxobject.name = name #", "1: raise j.exceptions.Base( \"Found more than 1 service for :%s,", "of the GNU General Public License as published by #", "that the stored values correspond with kwargs given # means", "index return self.count(name=name) == 1 def _children_get(self, filter=None): \"\"\" :param", "end of line filter (endswith) when R as first char", "if not self._cache_use: assert self._children == {} def _check(self, jsconfig):", "id not in ids_done: item = self.get(id=id, reload=reload, autosave=False) res.append(item)", "= mother_id jsconfig_klass = self._childclass_selector(jsxobject=jsxobject) jsconfig = jsconfig_klass(parent=self, jsxobject=jsxobject, **kwargs_to_class)", "(self.__class__._location, name) ) elif len(res) > 1: raise j.exceptions.Base( \"Found", "autosave # lets do some tests (maybe in future can", "in ids_done: item = self.get(id=id, reload=reload, autosave=False) res.append(item) return res", "can redistribute it and/or modify # it under the terms", "in how we use the index for item in self.find():", "\"Found more than 1 service for :%s, name searched for:%s\"", "res = self.find(name=name) if len(res) < 1: if not die:", "= self._model.find_ids(**kwargs) for id in ids: if id not in", "self._check(jsconfig) jsconfig._triggers_call(jsconfig, \"get\") return jsconfig def _get(self, name=\"main\", id=None, die=True,", "(name, self._classname)) # new = False res = self.find(name=name) if", "efficient no need to go to backend stor if the", "by # the Free Software Foundation, either version 3 of", "filter != \"*\": condition = Item.name.startswith(filter) and condition if condition", "self._model.find_ids(**kwargs) for id in ids: if id not in ids_done:", "# TODO do proper count query return len(list(self._model.find_ids(**kwargs))) def _findData(self,", "index for item in self.find(): if item not in x:", "jsxobject=None, autosave=True, **kwargs): \"\"\" :param name: for the CONFIG item", "None: # model has never been saved no check required", "= self.get(id=id, reload=reload, autosave=False) res.append(item) return res def _kwargs_update(self, kwargs):", "jsconfig.save() except Exception as e: print(\"CHECK WHY ERROR\") j.shell() jsconfig._autosave", "= self._new(name=name, autosave=autosave, **kwargs) else: # check that the stored", "in Item.select()] if len(res) > 50: return [] return res", "autosave=False) res.append(item) return res def _kwargs_update(self, kwargs): mother_id = self._mother_id_get()", "version. # # jumpscale is distributed in the hope that", "elements which will be given to JSXObject underneith (given to", "in mem ids = self._model.find_ids(**kwargs) for id in ids: if", "e.g. color=\"red\",... :return: list of the config objects \"\"\" kwargs", "match: if reload: item.load() res.append(item) if item.id not in ids_done:", "changed = False jsconfig._data._autosave = False for key, val in", "llist=x, nameonly=False) # be smarter in how we use the", "id in ids: if id not in ids_done: item =", "# then Incubaid NV also in Belgium will get the", "start it will be considered a end of line filter", "for key, val in kwargs.items(): if not getattr(jsconfig, key) ==", "rc, jsconfig = self._get(name=name, id=id, die=needexist, reload=reload) if not jsconfig:", "the service, client, ...) :param jsxobject: you can right away", "filter=None): condition = False Item = self._model.index.sql mother_id = self._mother_id_get()", "do proper count query return len(list(self._model.find_ids(**kwargs))) def _findData(self, **kwargs): \"\"\"", "more than 1 service for :%s, name searched for:%s\" %", "self._parent: if self._classname in self._parent._children: if not isinstance(self._parent, j.baseclasses.factory): #", "to exist (e.g. because of bankruptcy) # then Incubaid NV", "# jumpscale is free software: you can redistribute it and/or", "the object before the function returns. If set to False,", "mem ids = self._model.find_ids(**kwargs) for id in ids: if id", "stored values correspond with kwargs given # means comes from", "of which child class to use :return: \"\"\" return self.__class__._CHILDCLASS", "jsconfig def _get(self, name=\"main\", id=None, die=True, reload=False, autosave=True): if id:", "we're building del self._parent._children[self._data.name] def exists(self, name=\"main\"): \"\"\" :param name:", "not a factory means is a custom class we're building", "for now the safe bet) assert jsconfig._id > 0 mother_id", "j.exceptions.Base( \"Did not find instance for:%s, name searched for:%s\" %", "item.load() res.append(item) if item.id not in ids_done: ids_done.append(item.id) kwargs =", "def find(self, reload=False, **kwargs): \"\"\" :param kwargs: e.g. color=\"red\",... :return:", "for the CONFIG item (is a unique name for the", ":param kwargs: e.g. color=\"red\",... :return: list of the data objects", "service, client, ...) :param jsxobject: you can right away specify", "not jsxobject: if kwargs: kwargs_to_obj_new = {} props = [i.name", "if item not in x: x.append(item) return x def __str__(self):", "the License, or # (at your option) any later version.", "reload: obj.load() return 1, obj self._log_debug(\"get child:'%s'from '%s'\" % (name,", "name: _, child = self._get(name=name, die=False) if child: return child.delete()", "later version. # # jumpscale is distributed in the hope", "works. If not, see <http://www.gnu.org/licenses/>. # LICENSE END from Jumpscale", "of the model) \"\"\" kwargs = self._kwargs_update(kwargs) return self._model.find(**kwargs) def", "in kwargs.items(): if key in props: kwargs_to_obj_new[key] = val else:", "mother_id = self._mother_id_get() if mother_id: condition = Item.mother_id == mother_id", "j.exceptions.Base(\"cannot do new object, exists\") jsconfig = self._new(name=name, jsxobject=jsxobject, autosave=autosave,", "also in Belgium will get the Copyright & Authorship for", "1, self._new(name, obj) obj = self._validate_child(name) if obj: if reload:", "if reload: obj.load() return 1, obj self._log_debug(\"get child:'%s'from '%s'\" %", "def save(self): for item in self._children_get(): if item._hasattr(\"save\"): item.save() def", "carefull :return: \"\"\" self._log_debug(\"reset all data\") for item in self.find():", "kwargs.items(): if not getattr(jsconfig, key) == val: changed = True", "self._model.index.sql mother_id = self._mother_id_get() if mother_id: condition = Item.mother_id ==", "modify # it under the terms of the GNU General", "terms of the GNU General Public License as published by", "ERROR\") j.shell() jsconfig._autosave = autosave # lets do some tests", "to False, you need to explicitly save the object. :param", "from the database if not jsconfig._data._model.schema._md5 == jsconfig._model.schema._md5: # means", "details. # # You should have received a copy of", "_childclass_selector(self, jsxobject, **kwargs): \"\"\" allow custom implementation of which child", "autosave: self._children[name].save() jsxobject._autosave = autosave return self._children[name] def get(self, name=\"main\",", "self._model.index.destroy() def _children_names_get(self, filter=None): condition = False Item = self._model.index.sql", "self._classname in self._parent._children: if not isinstance(self._parent, j.baseclasses.factory): # only delete", "def _children_get(self, filter=None): \"\"\" :param filter: is '' then will", "id=id, die=needexist, reload=reload) if not jsconfig: self._log_debug(\"NEW OBJ:%s:%s\" % (name,", "\"*\": condition = Item.name.startswith(filter) and condition if condition else Item.name.startswith(filter)", "mother_id: kwargs[\"mother_id\"] = mother_id return kwargs def count(self, **kwargs): \"\"\"", "regex everything else is a full match :return: \"\"\" #", ":return: \"\"\" # TODO implement filter properly x = []", "child.delete() else: return self.reset() if not name and self._parent: if", "published by # the Free Software Foundation, either version 3", "obj = self._validate_child(name) if obj: if reload: obj.load() return 1,", "= res[0] jsxconfig._autosave = autosave return 2, jsxconfig def reset(self):", "name # means we need to remember the parent id", "self._parent._children[self._data.name] def exists(self, name=\"main\"): \"\"\" :param name: of the object", "jumpscale or jumpscale derived works. If not, see <http://www.gnu.org/licenses/>. #", "of the config objects \"\"\" kwargs = self._kwargs_update(kwargs) # TODO", "mother_id return kwargs def count(self, **kwargs): \"\"\" :param kwargs: e.g.", "for item in self._children_get(): if item._hasattr(\"save\"): item.save() def delete(self, name=None):", "# only delete when not a factory means is a", "changed = True setattr(jsconfig, key, val) if changed and autosave:", "res.append(item) if item.id not in ids_done: ids_done.append(item.id) kwargs = self._kwargs_update(kwargs)", "a factory means is a custom class we're building del", "mother_id: if jsxobject.mother_id != mother_id: jsxobject.mother_id = mother_id jsconfig_klass =", "the config objects \"\"\" kwargs = self._kwargs_update(kwargs) # TODO do", "not find instance for:%s, name searched for:%s\" % (self.__class__._location, name)", "name: :return: \"\"\" self._delete(name=name) def _delete(self, name=None): if name: _,", "delete == True :param name: :param jsxobject: :param autosave: sets", "service \"\"\" kwargs_to_class = {} if not jsxobject: if kwargs:", "if mother_id: if jsxobject.mother_id != mother_id: jsxobject.mother_id = mother_id jsconfig_klass", "res = [i.name for i in Item.select().where(condition)] else: res =", "ceases to exist (e.g. because of bankruptcy) # then Incubaid", "name = obj.name return 1, self._new(name, obj) obj = self._validate_child(name)", "condition = Item.mother_id == mother_id if filter and filter !=", "in list(self._children.items()): match = True for key, val in kwargs.items():", "model) \"\"\" kwargs = self._kwargs_update(kwargs) return self._model.find(**kwargs) def save(self): for", "obj) obj = self._validate_child(name) if obj: if reload: obj.load() return", "self.find(): try: item.delete() except Exception as e: j.shell() if not", "**kwargs): \"\"\" :param name: of the object \"\"\" # will", "if item._hasattr(key): if val != getattr(item, key): match = False", "now the safe bet) self._check(jsconfig) jsconfig._triggers_call(jsconfig, \"get\") return jsconfig def", "= False if match: if reload: item.load() res.append(item) if item.id", "setattr(jsconfig, key, val) if changed and autosave: try: jsconfig.save() except", "of the object \"\"\" # will reload if needed (not", "!= \"*\": condition = Item.name.startswith(filter) and condition if condition else", "= self._mother_id_get() if mother_id: condition = Item.mother_id == mother_id if", "return kwargs def count(self, **kwargs): \"\"\" :param kwargs: e.g. color=\"red\",...", "the jsxobject :param kwargs: the data elements which will be", "self._filter(filter=filter, llist=x, nameonly=False) # be smarter in how we use", "= False jsconfig._data._autosave = False for key, val in kwargs.items():", "= autosave self._children[name] = jsconfig if autosave: self._children[name].save() jsxobject._autosave =", "in self._children.items(): x.append(item) x = self._filter(filter=filter, llist=x, nameonly=False) # be", "else is a full match :return: \"\"\" # TODO implement", "received a copy of the GNU General Public License #", "or jumpscale derived works. If not, see <http://www.gnu.org/licenses/>. # LICENSE", "name=\"main\"): \"\"\" :param name: of the object \"\"\" obj =", "part of jumpscale at <https://github.com/threefoldtech>. # jumpscale is free software:", "list of the config objects \"\"\" res = [] ids_done", "of the GNU General Public License # along with jumpscale", "i in self._model.schema.properties] for key, val in kwargs.items(): if key", "TECH NV ceases to exist (e.g. because of bankruptcy) #", "License as published by # the Free Software Foundation, either", "key, val in kwargs.items(): if not getattr(jsconfig, key) == val:", "the data objects (the data of the model) \"\"\" kwargs", "_findData(self, **kwargs): \"\"\" :param kwargs: e.g. color=\"red\",... :return: list of", "end it will be considered a prefix when * at", "for key, val in kwargs.items(): if key in props: kwargs_to_obj_new[key]", "mother_id = self._mother_id_get() if mother_id: kwargs[\"mother_id\"] = mother_id return kwargs", "self._childclass_selector(jsxobject=jsxobject) jsconfig = jsconfig_klass(parent=self, jsxobject=jsxobject, **kwargs_to_class) jsconfig._triggers_call(jsconfig, \"new\") jsconfig._autosave =", "if item._hasattr(\"save\"): item.save() def delete(self, name=None): \"\"\" :param name: :return:", "= self._get(name=name, id=id, die=needexist, reload=reload) if not jsconfig: self._log_debug(\"NEW OBJ:%s:%s\"", "and schema is not same as config mgmt class j.shell()", "be a regex everything else is a full match :return:", "values correspond with kwargs given # means comes from the", "some tests (maybe in future can be removed, but for", "in self._children) rc, jsconfig = self._get(name=name, id=id, die=needexist, reload=reload) if", "is part of jumpscale at <https://github.com/threefoldtech>. # jumpscale is free", "(maybe in future can be removed, but for now the", "allow custom implementation of which child class to use :return:", "class JSConfigsBCDB(JSConfigBCDBBase): def _childclass_selector(self, jsxobject, **kwargs): \"\"\" allow custom implementation", "if not jsconfig._data._model.schema._md5 == jsconfig._model.schema._md5: # means data came from", "= self._model.get(id) name = obj.name return 1, self._new(name, obj) obj", "TODO implement filter properly x = [] for _, item", "get(self, name=\"main\", id=None, needexist=False, autosave=True, reload=False, **kwargs): \"\"\" :param name:", "see https://www.threefold.tech/ # In case TF TECH NV ceases to", "e: print(\"CHECK WHY ERROR\") j.shell() jsconfig._autosave = autosave # lets", "tests (maybe in future can be removed, but for now", ":return: list of the config objects \"\"\" res = []", "that it will be useful, # but WITHOUT ANY WARRANTY;", "only delete when not a factory means is a custom", "**kwargs): \"\"\" it it exists will delete if first when", "not jsconfig._data._model.schema._md5 == jsconfig._model.schema._md5: # means data came from DB", "[i.name for i in Item.select()] if len(res) > 50: return", "delete(self, name=None): \"\"\" :param name: :return: \"\"\" self._delete(name=name) def _delete(self,", "# and the license will automatically become Apache v2 for", "not in ids_done: item = self.get(id=id, reload=reload, autosave=False) res.append(item) return", "autosave=autosave, **kwargs) else: # check that the stored values correspond", "as e: print(\"CHECK WHY ERROR\") j.shell() jsconfig._autosave = autosave #", "either version 3 of the License, or # (at your", "= self._mother_id_get() if mother_id: kwargs[\"mother_id\"] = mother_id return kwargs def", "all data\") for item in self.find(): try: item.delete() except Exception", "if obj: if reload: obj.load() return 1, obj self._log_debug(\"get child:'%s'from", "item = self.get(id=id, reload=reload, autosave=False) res.append(item) return res def _kwargs_update(self,", "== jsconfig._model.schema._md5: # means data came from DB and schema", "(is a unique name for the service, client, ...) :param", "the # GNU General Public License v3 for more details.", "v2 for all code related to Jumpscale & DigitalMe #", "NV ceases to exist (e.g. because of bankruptcy) # then", "more details. # # You should have received a copy", "j.shell() changed = False jsconfig._data._autosave = False for key, val", "means we need to remember the parent id mother_id =", "to explicitly save the object. :param kwargs: :return: \"\"\" if", "kwargs given # means comes from the database if not", "in props: kwargs_to_obj_new[key] = val else: kwargs_to_class[key] = val jsxobject", "raise j.exceptions.Base( \"Did not find instance for:%s, name searched for:%s\"", "given to JSXObject underneith (given to constructor) :return: the service", "not self._mother_id_get(): self._model.index.destroy() def _children_names_get(self, filter=None): condition = False Item", "will only use the index return self.count(name=name) == 1 def", "== self._model.schema._md5 def _new(self, name, jsxobject=None, autosave=True, **kwargs): \"\"\" :param", "be useful, # but WITHOUT ANY WARRANTY; without even the", "jsconfig._triggers_call(jsconfig, \"new\") jsconfig._autosave = autosave self._children[name] = jsconfig if autosave:", "Belgium will get the Copyright & Authorship for all changes", "the object \"\"\" # will reload if needed (not in", "data of the model) \"\"\" kwargs = self._kwargs_update(kwargs) return self._model.find(**kwargs)", "# check that the stored values correspond with kwargs given", "In case TF TECH NV ceases to exist (e.g. because", "CONFIG item (is a unique name for the service, client,", "= jsconfig_klass(parent=self, jsxobject=jsxobject, **kwargs_to_class) jsconfig._triggers_call(jsconfig, \"new\") jsconfig._autosave = autosave self._children[name]", "else: # check that the stored values correspond with kwargs", "if not isinstance(self._parent, j.baseclasses.factory): # only delete when not a", "NV in Belgium see https://www.threefold.tech/ # In case TF TECH", "delete if first when delete == True :param name: :param", "the Copyright & Authorship for all changes made since July", "Item.select()] if len(res) > 50: return [] return res def", "means comes from the database if not jsconfig._data._model.schema._md5 == jsconfig._model.schema._md5:", "the CONFIG item (is a unique name for the service,", "find instance for:%s, name searched for:%s\" % (self.__class__._location, name) )", "sets the autosave argument on the data and also saves", "if len(res) > 50: return [] return res def find(self,", "assert self._children == {} def _check(self, jsconfig): if jsconfig._id is", "\"\"\" allow custom implementation of which child class to use", "# along with jumpscale or jumpscale derived works. If not,", "save the object. :param kwargs: :return: \"\"\" if self.exists(name=name): raise", "if not name and self._parent: if self._classname in self._parent._children: if", "\"\"\" # TODO implement filter properly x = [] for", "def _check_children(self): if not self._cache_use: assert self._children == {} def", "not jsconfig: self._log_debug(\"NEW OBJ:%s:%s\" % (name, self._classname)) jsconfig = self._new(name=name,", "DigitalMe # This file is part of jumpscale at <https://github.com/threefoldtech>.", "jsconfig._autosave = autosave self._children[name] = jsconfig if autosave: self._children[name].save() jsxobject._autosave", "first char its considered to be a regex everything else", "False if match: if reload: item.load() res.append(item) if item.id not", "= [i.name for i in Item.select().where(condition)] else: res = [i.name", "= mother_id return kwargs def count(self, **kwargs): \"\"\" :param kwargs:", "# be smarter in how we use the index for", "{} if not jsxobject: if kwargs: kwargs_to_obj_new = {} props", "jsxobject = self._model.new() jsxobject.name = name # means we need", "if item.id not in ids_done: ids_done.append(item.id) kwargs = self._kwargs_update(kwargs) #", "self._kwargs_update(kwargs) # TODO do proper count query return len(list(self._model.find_ids(**kwargs))) def", "TECH NV in Belgium see https://www.threefold.tech/ # In case TF", "return len(list(self._model.find_ids(**kwargs))) def _findData(self, **kwargs): \"\"\" :param kwargs: e.g. color=\"red\",...", "self._new(name=name, jsxobject=jsxobject, autosave=autosave, **kwargs) self._check(jsconfig) return jsconfig def _check_children(self): if", "when delete == True :param name: :param jsxobject: :param autosave:", "argument on the data and also saves the object before", "a regex everything else is a full match :return: \"\"\"", "a end of line filter (endswith) when R as first", "JSXObject underneith (given to constructor) :return: the service \"\"\" kwargs_to_class", "for id in ids: if id not in ids_done: item", "return [] return res def find(self, reload=False, **kwargs): \"\"\" :param", "parent id mother_id = self._mother_id_get() if mother_id: if jsxobject.mother_id !=", "# This file is part of jumpscale at <https://github.com/threefoldtech>. #", "class j.shell() changed = False jsconfig._data._autosave = False for key,", "try: item.delete() except Exception as e: j.shell() if not self._mother_id_get():", "<http://www.gnu.org/licenses/>. # LICENSE END from Jumpscale import j from .JSConfigBCDBBase", ":param name: :return: \"\"\" self._delete(name=name) def _delete(self, name=None): if name:", "all, if None will ignore _ when * at end", "because of bankruptcy) # then Incubaid NV also in Belgium", "in the DB, be carefull :return: \"\"\" self._log_debug(\"reset all data\")", "schema is not same as config mgmt class j.shell() changed", "kwargs.items(): if item._hasattr(key): if val != getattr(item, key): match =", "no need to go to backend stor if the objects", "save(self): for item in self._children_get(): if item._hasattr(\"save\"): item.save() def delete(self,", "return jsconfig def _get(self, name=\"main\", id=None, die=True, reload=False, autosave=True): if", "mother_id = self._mother_id_get() if mother_id: if jsxobject.mother_id != mother_id: jsxobject.mother_id", "list of the data objects (the data of the model)", "a prefix when * at start it will be considered", "self._mother_id_get() if mother_id: kwargs[\"mother_id\"] = mother_id return kwargs def count(self,", "> 1: raise j.exceptions.Base( \"Found more than 1 service for", "smarter in how we use the index for item in", "return 1, obj self._log_debug(\"get child:'%s'from '%s'\" % (name, self._classname)) #", "DB, be carefull :return: \"\"\" self._log_debug(\"reset all data\") for item", "filter: is '' then will show all, if None will", "show all, if None will ignore _ when * at", "condition = False Item = self._model.index.sql mother_id = self._mother_id_get() if", "changes made since July 2018 # and the license will", "% (self.__class__._location, name) ) else: jsxconfig = res[0] jsxconfig._autosave =", "def _childclass_selector(self, jsxobject, **kwargs): \"\"\" allow custom implementation of which", "query return len(list(self._model.find_ids(**kwargs))) def _findData(self, **kwargs): \"\"\" :param kwargs: e.g.", "for :%s, name searched for:%s\" % (self.__class__._location, name) ) else:", "filter (endswith) when R as first char its considered to", "name, jsxobject=None, autosave=True, **kwargs): \"\"\" :param name: for the CONFIG", "= val jsxobject = self._model.new(data=kwargs_to_obj_new) else: jsxobject = self._model.new() jsxobject.name", "_children_names_get(self, filter=None): condition = False Item = self._model.index.sql mother_id =", "if mother_id: kwargs[\"mother_id\"] = mother_id return kwargs def count(self, **kwargs):", "# but WITHOUT ANY WARRANTY; without even the implied warranty", "Free Software Foundation, either version 3 of the License, or", "Copyright & Authorship for all changes made since July 2018", "jsxobject: :param autosave: sets the autosave argument on the data", "50: return [] return res def find(self, reload=False, **kwargs): \"\"\"", "custom implementation of which child class to use :return: \"\"\"", "item (is a unique name for the service, client, ...)", "yet return # lets do some tests (maybe in future", "and/or modify # it under the terms of the GNU", "implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR", "needed (not in self._children) rc, jsconfig = self._get(name=name, id=id, die=needexist,", "return 3, None raise j.exceptions.Base( \"Did not find instance for:%s,", "False for key, val in kwargs.items(): if not getattr(jsconfig, key)", "prefix when * at start it will be considered a", "name searched for:%s\" % (self.__class__._location, name) ) elif len(res) >", "for:%s\" % (self.__class__._location, name) ) elif len(res) > 1: raise", "jumpscale at <https://github.com/threefoldtech>. # jumpscale is free software: you can", "\"\"\" :param name: of the object \"\"\" # will reload", "name: :param jsxobject: :param autosave: sets the autosave argument on", "if first when delete == True :param name: :param jsxobject:", "key): match = False else: match = False if match:", "count query return len(list(self._model.find_ids(**kwargs))) def _findData(self, **kwargs): \"\"\" :param kwargs:", "else: jsxconfig = res[0] jsxconfig._autosave = autosave return 2, jsxconfig", "= False else: match = False if match: if reload:", "# will reload if needed (not in self._children) rc, jsconfig", "not, see <http://www.gnu.org/licenses/>. # LICENSE END from Jumpscale import j", "bankruptcy) # then Incubaid NV also in Belgium will get", "of the config objects \"\"\" res = [] ids_done =", "# will only use the index return self.count(name=name) == 1", "x = [] for _, item in self._children.items(): x.append(item) x", "it and/or modify # it under the terms of the", "Public License v3 for more details. # # You should", "def exists(self, name=\"main\"): \"\"\" :param name: of the object \"\"\"", "self._log_debug(\"reset all data\") for item in self.find(): try: item.delete() except", "jsconfig._data._model.schema._md5 == jsconfig._model.schema._md5: # means data came from DB and", "(not in self._children) rc, jsconfig = self._get(name=name, id=id, die=needexist, reload=reload)", "will be given to JSXObject underneith (given to constructor) :return:", "= obj.name return 1, self._new(name, obj) obj = self._validate_child(name) if", "mother_id jsconfig_klass = self._childclass_selector(jsxobject=jsxobject) jsconfig = jsconfig_klass(parent=self, jsxobject=jsxobject, **kwargs_to_class) jsconfig._triggers_call(jsconfig,", "\"Did not find instance for:%s, name searched for:%s\" % (self.__class__._location,", "kwargs.items(): if key in props: kwargs_to_obj_new[key] = val else: kwargs_to_class[key]", "_check(self, jsconfig): if jsconfig._id is None: # model has never", "condition = Item.name.startswith(filter) and condition if condition else Item.name.startswith(filter) if", "needexist=False, autosave=True, reload=False, **kwargs): \"\"\" :param name: of the object", "it will be useful, # but WITHOUT ANY WARRANTY; without", "for i in Item.select().where(condition)] else: res = [i.name for i", "will destroy all data in the DB, be carefull :return:", "need to go to backend stor if the objects are", "= False Item = self._model.index.sql mother_id = self._mother_id_get() if mother_id:", "= self._kwargs_update(kwargs) # this is more efficient no need to", "return self._children[name] def get(self, name=\"main\", id=None, needexist=False, autosave=True, reload=False, **kwargs):", "data objects (the data of the model) \"\"\" kwargs =", "full match :return: \"\"\" # TODO implement filter properly x", "exists will delete if first when delete == True :param", "config objects \"\"\" res = [] ids_done = [] for", "autosave return self._children[name] def get(self, name=\"main\", id=None, needexist=False, autosave=True, reload=False,", "self.find(): if item not in x: x.append(item) return x def", ".JSConfigBCDBBase import JSConfigBCDBBase class JSConfigsBCDB(JSConfigBCDBBase): def _childclass_selector(self, jsxobject, **kwargs): \"\"\"", "# # jumpscale is distributed in the hope that it", "**kwargs): \"\"\" :param name: for the CONFIG item (is a", "# this is more efficient no need to go to", "# it under the terms of the GNU General Public", "away specify the jsxobject :param kwargs: the data elements which", "= autosave # lets do some tests (maybe in future", "key, val in kwargs.items(): if key in props: kwargs_to_obj_new[key] =", "> 50: return [] return res def find(self, reload=False, **kwargs):", "1 service for :%s, name searched for:%s\" % (self.__class__._location, name)", "TF TECH NV ceases to exist (e.g. because of bankruptcy)", "can right away specify the jsxobject :param kwargs: the data", "if len(res) < 1: if not die: return 3, None", "kwargs_to_obj_new = {} props = [i.name for i in self._model.schema.properties]", "of the License, or # (at your option) any later", "# means data came from DB and schema is not", "ignore _ when * at end it will be considered", "= autosave return self._children[name] def get(self, name=\"main\", id=None, needexist=False, autosave=True,", "res = [i.name for i in Item.select()] if len(res) >", "name: of the object \"\"\" # will reload if needed", "hope that it will be useful, # but WITHOUT ANY", "kwargs = self._kwargs_update(kwargs) # this is more efficient no need", "it under the terms of the GNU General Public License", "case TF TECH NV ceases to exist (e.g. because of", "reload if needed (not in self._children) rc, jsconfig = self._get(name=name,", "res def _kwargs_update(self, kwargs): mother_id = self._mother_id_get() if mother_id: kwargs[\"mother_id\"]", "See the # GNU General Public License v3 for more", "autosave: try: jsconfig.save() except Exception as e: print(\"CHECK WHY ERROR\")", "try: jsconfig.save() except Exception as e: print(\"CHECK WHY ERROR\") j.shell()", "kwargs def count(self, **kwargs): \"\"\" :param kwargs: e.g. color=\"red\",... :return:", "when not a factory means is a custom class we're", "{} def _check(self, jsconfig): if jsconfig._id is None: # model", "= self._validate_child(name) if obj: return True # will only use", "for:%s, name searched for:%s\" % (self.__class__._location, name) ) elif len(res)", "the GNU General Public License as published by # the", "self._mother_id_get() if mother_id: condition = Item.mother_id == mother_id if filter", "if None will ignore _ when * at end it", "when * at start it will be considered a end", "self.exists(name=name): raise j.exceptions.Base(\"cannot do new object, exists\") jsconfig = self._new(name=name,", "to constructor) :return: the service \"\"\" kwargs_to_class = {} if", "not self._cache_use: assert self._children == {} def _check(self, jsconfig): if", "Public License # along with jumpscale or jumpscale derived works.", "for all changes made since July 2018 # and the", "with kwargs given # means comes from the database if", "for now the safe bet) self._check(jsconfig) jsconfig._triggers_call(jsconfig, \"get\") return jsconfig", "getattr(item, key): match = False else: match = False if", "\"\"\" kwargs_to_class = {} if not jsxobject: if kwargs: kwargs_to_obj_new", "be removed, but for now the safe bet) assert jsconfig._id", "\"\"\" obj = self._validate_child(name) if obj: return True # will", "condition if condition else Item.name.startswith(filter) if condition: res = [i.name", "jsxconfig def reset(self): \"\"\" will destroy all data in the", "delete when not a factory means is a custom class", "FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General", "self._classname)) jsconfig = self._new(name=name, autosave=autosave, **kwargs) else: # check that", "\"\"\" will destroy all data in the DB, be carefull", "of the object \"\"\" obj = self._validate_child(name) if obj: return", "Copyright (C) July 2018: TF TECH NV in Belgium see", "= self._filter(filter=filter, llist=x, nameonly=False) # be smarter in how we", "General Public License as published by # the Free Software", "self._mother_id_get(): self._model.index.destroy() def _children_names_get(self, filter=None): condition = False Item =", "# Copyright (C) July 2018: TF TECH NV in Belgium", "if self.exists(name=name): raise j.exceptions.Base(\"cannot do new object, exists\") jsconfig =", "will be useful, # but WITHOUT ANY WARRANTY; without even", "has never been saved no check required yet return #", "del self._parent._children[self._data.name] def exists(self, name=\"main\"): \"\"\" :param name: of the", "not die: return 3, None raise j.exceptions.Base( \"Did not find", "ids: if id not in ids_done: item = self.get(id=id, reload=reload,", "in kwargs.items(): if not getattr(jsconfig, key) == val: changed =", "the safe bet) self._check(jsconfig) jsconfig._triggers_call(jsconfig, \"get\") return jsconfig def _get(self,", "key, item in list(self._children.items()): match = True for key, val", "will get the Copyright & Authorship for all changes made", "die=needexist, reload=reload) if not jsconfig: self._log_debug(\"NEW OBJ:%s:%s\" % (name, self._classname))", "option) any later version. # # jumpscale is distributed in", "item in list(self._children.items()): match = True for key, val in", "self.count(name=name) == 1 def _children_get(self, filter=None): \"\"\" :param filter: is", "= False for key, val in kwargs.items(): if not getattr(jsconfig,", "considered to be a regex everything else is a full", "key, val) if changed and autosave: try: jsconfig.save() except Exception", "be removed, but for now the safe bet) self._check(jsconfig) jsconfig._triggers_call(jsconfig,", "get the Copyright & Authorship for all changes made since", "automatically become Apache v2 for all code related to Jumpscale", ":return: list of the data objects (the data of the", "raise j.exceptions.Base(\"cannot do new object, exists\") jsconfig = self._new(name=name, jsxobject=jsxobject,", "\"new\") jsconfig._autosave = autosave self._children[name] = jsconfig if autosave: self._children[name].save()", "reload=reload) if not jsconfig: self._log_debug(\"NEW OBJ:%s:%s\" % (name, self._classname)) jsconfig", "else Item.name.startswith(filter) if condition: res = [i.name for i in", "match = False else: match = False if match: if", "\"\"\" kwargs = self._kwargs_update(kwargs) return self._model.find(**kwargs) def save(self): for item", "True :param name: :param jsxobject: :param autosave: sets the autosave", "it will be considered a end of line filter (endswith)", "END from Jumpscale import j from .JSConfigBCDBBase import JSConfigBCDBBase class", "at end it will be considered a prefix when *", "how we use the index for item in self.find(): if", "do some tests (maybe in future can be removed, but", "kwargs_to_obj_new[key] = val else: kwargs_to_class[key] = val jsxobject = self._model.new(data=kwargs_to_obj_new)", "val != getattr(item, key): match = False else: match =", "backend stor if the objects are already in mem ids", "FOR A PARTICULAR PURPOSE. See the # GNU General Public", "License # along with jumpscale or jumpscale derived works. If", "True setattr(jsconfig, key, val) if changed and autosave: try: jsconfig.save()", ":param jsxobject: :param autosave: sets the autosave argument on the", "and condition if condition else Item.name.startswith(filter) if condition: res =", "return child.delete() else: return self.reset() if not name and self._parent:", ":param kwargs: :return: \"\"\" if self.exists(name=name): raise j.exceptions.Base(\"cannot do new", "on the data and also saves the object before the", "& DigitalMe # This file is part of jumpscale at", "assert jsconfig._model.schema._md5 == self._model.schema._md5 def _new(self, name, jsxobject=None, autosave=True, **kwargs):", "res def find(self, reload=False, **kwargs): \"\"\" :param kwargs: e.g. color=\"red\",...", "False jsconfig._data._autosave = False for key, val in kwargs.items(): if", "name, jsxobject=None, autosave=True, **kwargs): \"\"\" it it exists will delete", "jsxobject.mother_id = mother_id jsconfig_klass = self._childclass_selector(jsxobject=jsxobject) jsconfig = jsconfig_klass(parent=self, jsxobject=jsxobject,", "jsconfig = self._new(name=name, jsxobject=jsxobject, autosave=autosave, **kwargs) self._check(jsconfig) return jsconfig def", "as config mgmt class j.shell() changed = False jsconfig._data._autosave =", "assert jsconfig._id > 0 mother_id = jsconfig._mother_id_get() if mother_id: assert", "1, obj self._log_debug(\"get child:'%s'from '%s'\" % (name, self._classname)) # new", "jsxobject :param kwargs: the data elements which will be given", "line filter (endswith) when R as first char its considered", "to be a regex everything else is a full match", "we use the index for item in self.find(): if item", "use :return: \"\"\" return self.__class__._CHILDCLASS def new(self, name, jsxobject=None, autosave=True,", "self._get(name=name, id=id, die=needexist, reload=reload) if not jsconfig: self._log_debug(\"NEW OBJ:%s:%s\" %", "for more details. # # You should have received a", "if autosave: self._children[name].save() jsxobject._autosave = autosave return self._children[name] def get(self,", "item.id not in ids_done: ids_done.append(item.id) kwargs = self._kwargs_update(kwargs) # this", "= self._mother_id_get() if mother_id: if jsxobject.mother_id != mother_id: jsxobject.mother_id =", "redistribute it and/or modify # it under the terms of", "need to remember the parent id mother_id = self._mother_id_get() if", ":param autosave: sets the autosave argument on the data and", "the function returns. If set to False, you need to", "kwargs: :return: \"\"\" if self.exists(name=name): raise j.exceptions.Base(\"cannot do new object,", "Exception as e: print(\"CHECK WHY ERROR\") j.shell() jsconfig._autosave = autosave", "\"\"\" :param kwargs: e.g. color=\"red\",... :return: list of the config", "made since July 2018 # and the license will automatically", "else: res = [i.name for i in Item.select()] if len(res)", "import j from .JSConfigBCDBBase import JSConfigBCDBBase class JSConfigsBCDB(JSConfigBCDBBase): def _childclass_selector(self,", "also saves the object before the function returns. If set", "j.baseclasses.factory): # only delete when not a factory means is", "self._children[name].save() jsxobject._autosave = autosave return self._children[name] def get(self, name=\"main\", id=None,", "<gh_stars>0 # Copyright (C) July 2018: TF TECH NV in", "instance for:%s, name searched for:%s\" % (self.__class__._location, name) ) elif", "\"\"\" :param filter: is '' then will show all, if", "it will be considered a prefix when * at start", "first when delete == True :param name: :param jsxobject: :param", "self._model.new(data=kwargs_to_obj_new) else: jsxobject = self._model.new() jsxobject.name = name # means", "General Public License v3 for more details. # # You", "name for the service, client, ...) :param jsxobject: you can", "= jsconfig._mother_id_get() if mother_id: assert jsconfig.mother_id == mother_id assert jsconfig._model.schema._md5", "= val else: kwargs_to_class[key] = val jsxobject = self._model.new(data=kwargs_to_obj_new) else:", "self._check(jsconfig) return jsconfig def _check_children(self): if not self._cache_use: assert self._children", "Apache v2 for all code related to Jumpscale & DigitalMe", "name=\"main\", id=None, die=True, reload=False, autosave=True): if id: obj = self._model.get(id)", "a unique name for the service, client, ...) :param jsxobject:", "ids_done: item = self.get(id=id, reload=reload, autosave=False) res.append(item) return res def", "name=None): \"\"\" :param name: :return: \"\"\" self._delete(name=name) def _delete(self, name=None):", "implement filter properly x = [] for _, item in", "not name and self._parent: if self._classname in self._parent._children: if not", "_check_children(self): if not self._cache_use: assert self._children == {} def _check(self,", "return # lets do some tests (maybe in future can", "and filter != \"*\": condition = Item.name.startswith(filter) and condition if", "LICENSE END from Jumpscale import j from .JSConfigBCDBBase import JSConfigBCDBBase", "match :return: \"\"\" # TODO implement filter properly x =", "reload: item.load() res.append(item) if item.id not in ids_done: ids_done.append(item.id) kwargs", "jsconfig._model.schema._md5 == self._model.schema._md5 def _new(self, name, jsxobject=None, autosave=True, **kwargs): \"\"\"", "jsconfig = jsconfig_klass(parent=self, jsxobject=jsxobject, **kwargs_to_class) jsconfig._triggers_call(jsconfig, \"new\") jsconfig._autosave = autosave", "jsxobject._autosave = autosave return self._children[name] def get(self, name=\"main\", id=None, needexist=False,", "ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY", "# TODO implement filter properly x = [] for _,", "TODO do proper count query return len(list(self._model.find_ids(**kwargs))) def _findData(self, **kwargs):", ":return: \"\"\" if self.exists(name=name): raise j.exceptions.Base(\"cannot do new object, exists\")", "bet) assert jsconfig._id > 0 mother_id = jsconfig._mother_id_get() if mother_id:", "jsxobject = self._model.new(data=kwargs_to_obj_new) else: jsxobject = self._model.new() jsxobject.name = name", "of line filter (endswith) when R as first char its", "Incubaid NV also in Belgium will get the Copyright &", "lets do some tests (maybe in future can be removed,", "return self._model.find(**kwargs) def save(self): for item in self._children_get(): if item._hasattr(\"save\"):", "self._model.get(id) name = obj.name return 1, self._new(name, obj) obj =", "name and self._parent: if self._classname in self._parent._children: if not isinstance(self._parent,", "= Item.mother_id == mother_id if filter and filter != \"*\":", "== val: changed = True setattr(jsconfig, key, val) if changed", "autosave self._children[name] = jsconfig if autosave: self._children[name].save() jsxobject._autosave = autosave", "the hope that it will be useful, # but WITHOUT", "val) if changed and autosave: try: jsconfig.save() except Exception as", "\"\"\" :param kwargs: e.g. color=\"red\",... :return: list of the data", "jsxobject: you can right away specify the jsxobject :param kwargs:", "jumpscale is distributed in the hope that it will be", "if key in props: kwargs_to_obj_new[key] = val else: kwargs_to_class[key] =", "mgmt class j.shell() changed = False jsconfig._data._autosave = False for", "reload=False, autosave=True): if id: obj = self._model.get(id) name = obj.name", "as first char its considered to be a regex everything", "this is more efficient no need to go to backend", "since July 2018 # and the license will automatically become", "# means we need to remember the parent id mother_id", "item in self.find(): if item not in x: x.append(item) return", "software: you can redistribute it and/or modify # it under", "which child class to use :return: \"\"\" return self.__class__._CHILDCLASS def", "len(res) > 1: raise j.exceptions.Base( \"Found more than 1 service", "for:%s\" % (self.__class__._location, name) ) else: jsxconfig = res[0] jsxconfig._autosave", "len(res) > 50: return [] return res def find(self, reload=False,", "\"\"\" res = [] ids_done = [] for key, item", "right away specify the jsxobject :param kwargs: the data elements", "name: of the object \"\"\" obj = self._validate_child(name) if obj:", "data\") for item in self.find(): try: item.delete() except Exception as", "set to False, you need to explicitly save the object.", "nameonly=False) # be smarter in how we use the index", "self._children[name] = jsconfig if autosave: self._children[name].save() jsxobject._autosave = autosave return", "in self._model.schema.properties] for key, val in kwargs.items(): if key in", "child: return child.delete() else: return self.reset() if not name and", "(endswith) when R as first char its considered to be", "self._children[name] def get(self, name=\"main\", id=None, needexist=False, autosave=True, reload=False, **kwargs): \"\"\"", "not getattr(jsconfig, key) == val: changed = True setattr(jsconfig, key,", "code related to Jumpscale & DigitalMe # This file is", "char its considered to be a regex everything else is", "color=\"red\",... :return: list of the config objects \"\"\" kwargs =", "Belgium see https://www.threefold.tech/ # In case TF TECH NV ceases", "we need to remember the parent id mother_id = self._mother_id_get()", "0 mother_id = jsconfig._mother_id_get() if mother_id: assert jsconfig.mother_id == mother_id", "searched for:%s\" % (self.__class__._location, name) ) else: jsxconfig = res[0]", "along with jumpscale or jumpscale derived works. If not, see", "the parent id mother_id = self._mother_id_get() if mother_id: if jsxobject.mother_id", "kwargs: the data elements which will be given to JSXObject", "saves the object before the function returns. If set to", "for key, item in list(self._children.items()): match = True for key,", "return self.__class__._CHILDCLASS def new(self, name, jsxobject=None, autosave=True, **kwargs): \"\"\" it", ":param kwargs: the data elements which will be given to", "x = self._filter(filter=filter, llist=x, nameonly=False) # be smarter in how", ":param name: for the CONFIG item (is a unique name", "kwargs: kwargs_to_obj_new = {} props = [i.name for i in", "True # will only use the index return self.count(name=name) ==", "is None: # model has never been saved no check", "self._model.find(**kwargs) def save(self): for item in self._children_get(): if item._hasattr(\"save\"): item.save()", "copy of the GNU General Public License # along with", "= self._new(name=name, jsxobject=jsxobject, autosave=autosave, **kwargs) self._check(jsconfig) return jsconfig def _check_children(self):", "object before the function returns. If set to False, you", "self._validate_child(name) if obj: if reload: obj.load() return 1, obj self._log_debug(\"get", "= self._model.new() jsxobject.name = name # means we need to", "https://www.threefold.tech/ # In case TF TECH NV ceases to exist", "in future can be removed, but for now the safe", "condition: res = [i.name for i in Item.select().where(condition)] else: res", "match = False if match: if reload: item.load() res.append(item) if", "which will be given to JSXObject underneith (given to constructor)", "will reload if needed (not in self._children) rc, jsconfig =", "**kwargs_to_class) jsconfig._triggers_call(jsconfig, \"new\") jsconfig._autosave = autosave self._children[name] = jsconfig if", "jsconfig = self._new(name=name, autosave=autosave, **kwargs) else: # check that the", "the data and also saves the object before the function", "when * at end it will be considered a prefix", "not same as config mgmt class j.shell() changed = False", "be given to JSXObject underneith (given to constructor) :return: the", "destroy all data in the DB, be carefull :return: \"\"\"", "# means comes from the database if not jsconfig._data._model.schema._md5 ==", "for i in Item.select()] if len(res) > 50: return []", "stor if the objects are already in mem ids =", "False Item = self._model.index.sql mother_id = self._mother_id_get() if mother_id: condition", "die=True, reload=False, autosave=True): if id: obj = self._model.get(id) name =", "searched for:%s\" % (self.__class__._location, name) ) elif len(res) > 1:", "distributed in the hope that it will be useful, #", "License, or # (at your option) any later version. #", "< 1: if not die: return 3, None raise j.exceptions.Base(", "self.get(id=id, reload=reload, autosave=False) res.append(item) return res def _kwargs_update(self, kwargs): mother_id", "x.append(item) x = self._filter(filter=filter, llist=x, nameonly=False) # be smarter in", "filter and filter != \"*\": condition = Item.name.startswith(filter) and condition", "reload=False, **kwargs): \"\"\" :param kwargs: e.g. color=\"red\",... :return: list of", "props = [i.name for i in self._model.schema.properties] for key, val", "getattr(jsconfig, key) == val: changed = True setattr(jsconfig, key, val)", "JSConfigsBCDB(JSConfigBCDBBase): def _childclass_selector(self, jsxobject, **kwargs): \"\"\" allow custom implementation of", "can be removed, but for now the safe bet) self._check(jsconfig)", "July 2018 # and the license will automatically become Apache", "comes from the database if not jsconfig._data._model.schema._md5 == jsconfig._model.schema._md5: #", "jumpscale derived works. If not, see <http://www.gnu.org/licenses/>. # LICENSE END", "for all code related to Jumpscale & DigitalMe # This", "jsxobject.mother_id != mother_id: jsxobject.mother_id = mother_id jsconfig_klass = self._childclass_selector(jsxobject=jsxobject) jsconfig", "False else: match = False if match: if reload: item.load()", "jsconfig = self._get(name=name, id=id, die=needexist, reload=reload) if not jsconfig: self._log_debug(\"NEW", "* at end it will be considered a prefix when", "new(self, name, jsxobject=None, autosave=True, **kwargs): \"\"\" it it exists will", "autosave: sets the autosave argument on the data and also", "the config objects \"\"\" res = [] ids_done = []", "considered a prefix when * at start it will be", "its considered to be a regex everything else is a", "go to backend stor if the objects are already in", "exist (e.g. because of bankruptcy) # then Incubaid NV also", "You should have received a copy of the GNU General", "to use :return: \"\"\" return self.__class__._CHILDCLASS def new(self, name, jsxobject=None,", "a custom class we're building del self._parent._children[self._data.name] def exists(self, name=\"main\"):", "returns. If set to False, you need to explicitly save", "implementation of which child class to use :return: \"\"\" return", ":return: \"\"\" return self.__class__._CHILDCLASS def new(self, name, jsxobject=None, autosave=True, **kwargs):", "def get(self, name=\"main\", id=None, needexist=False, autosave=True, reload=False, **kwargs): \"\"\" :param", "self._log_debug(\"get child:'%s'from '%s'\" % (name, self._classname)) # new = False", "objects (the data of the model) \"\"\" kwargs = self._kwargs_update(kwargs)", "mother_id assert jsconfig._model.schema._md5 == self._model.schema._md5 def _new(self, name, jsxobject=None, autosave=True,", "kwargs_to_class = {} if not jsxobject: if kwargs: kwargs_to_obj_new =", "the object. :param kwargs: :return: \"\"\" if self.exists(name=name): raise j.exceptions.Base(\"cannot", "to backend stor if the objects are already in mem", "self._model.new() jsxobject.name = name # means we need to remember", "def _children_names_get(self, filter=None): condition = False Item = self._model.index.sql mother_id", "the object \"\"\" obj = self._validate_child(name) if obj: return True", "client, ...) :param jsxobject: you can right away specify the", "= jsconfig if autosave: self._children[name].save() jsxobject._autosave = autosave return self._children[name]", "in Item.select().where(condition)] else: res = [i.name for i in Item.select()]", "jsxobject.name = name # means we need to remember the", "useful, # but WITHOUT ANY WARRANTY; without even the implied", "print(\"CHECK WHY ERROR\") j.shell() jsconfig._autosave = autosave # lets do", "item in self._children.items(): x.append(item) x = self._filter(filter=filter, llist=x, nameonly=False) #", "jsconfig._data._autosave = False for key, val in kwargs.items(): if not", "function returns. If set to False, you need to explicitly", "constructor) :return: the service \"\"\" kwargs_to_class = {} if not", "% (self.__class__._location, name) ) elif len(res) > 1: raise j.exceptions.Base(", "item in self._children_get(): if item._hasattr(\"save\"): item.save() def delete(self, name=None): \"\"\"", "\"\"\" # will reload if needed (not in self._children) rc,", "for i in self._model.schema.properties] for key, val in kwargs.items(): if", "the database if not jsconfig._data._model.schema._md5 == jsconfig._model.schema._md5: # means data", "you can redistribute it and/or modify # it under the", "the GNU General Public License # along with jumpscale or", "== mother_id assert jsconfig._model.schema._md5 == self._model.schema._md5 def _new(self, name, jsxobject=None,", "will show all, if None will ignore _ when *", "key) == val: changed = True setattr(jsconfig, key, val) if", ":param name: of the object \"\"\" # will reload if", "res.append(item) return res def _kwargs_update(self, kwargs): mother_id = self._mother_id_get() if", "'' then will show all, if None will ignore _", "safe bet) self._check(jsconfig) jsconfig._triggers_call(jsconfig, \"get\") return jsconfig def _get(self, name=\"main\",", "self._parent._children: if not isinstance(self._parent, j.baseclasses.factory): # only delete when not", "# You should have received a copy of the GNU", ") elif len(res) > 1: raise j.exceptions.Base( \"Found more than", "service for :%s, name searched for:%s\" % (self.__class__._location, name) )", "if id not in ids_done: item = self.get(id=id, reload=reload, autosave=False)", "not in ids_done: ids_done.append(item.id) kwargs = self._kwargs_update(kwargs) # this is", "obj = self._validate_child(name) if obj: return True # will only", "_kwargs_update(self, kwargs): mother_id = self._mother_id_get() if mother_id: kwargs[\"mother_id\"] = mother_id", "means is a custom class we're building del self._parent._children[self._data.name] def", "remember the parent id mother_id = self._mother_id_get() if mother_id: if", "the index for item in self.find(): if item not in", "2018 # and the license will automatically become Apache v2", "unique name for the service, client, ...) :param jsxobject: you", "(e.g. because of bankruptcy) # then Incubaid NV also in", "kwargs = self._kwargs_update(kwargs) return self._model.find(**kwargs) def save(self): for item in", "item.delete() except Exception as e: j.shell() if not self._mother_id_get(): self._model.index.destroy()", "* at start it will be considered a end of", ":%s, name searched for:%s\" % (self.__class__._location, name) ) else: jsxconfig", "return True # will only use the index return self.count(name=name)", ") else: jsxconfig = res[0] jsxconfig._autosave = autosave return 2,", "mother_id: assert jsconfig.mother_id == mother_id assert jsconfig._model.schema._md5 == self._model.schema._md5 def", "should have received a copy of the GNU General Public", "len(res) < 1: if not die: return 3, None raise", "_get(self, name=\"main\", id=None, die=True, reload=False, autosave=True): if id: obj =", "to go to backend stor if the objects are already", "model has never been saved no check required yet return", "False, you need to explicitly save the object. :param kwargs:", "jumpscale is free software: you can redistribute it and/or modify", "future can be removed, but for now the safe bet)", "% (name, self._classname)) # new = False res = self.find(name=name)", "autosave return 2, jsxconfig def reset(self): \"\"\" will destroy all", "more efficient no need to go to backend stor if", "it exists will delete if first when delete == True", "OBJ:%s:%s\" % (name, self._classname)) jsconfig = self._new(name=name, autosave=autosave, **kwargs) else:", "== True :param name: :param jsxobject: :param autosave: sets the", "safe bet) assert jsconfig._id > 0 mother_id = jsconfig._mother_id_get() if", ":param jsxobject: you can right away specify the jsxobject :param", "die: return 3, None raise j.exceptions.Base( \"Did not find instance", "same as config mgmt class j.shell() changed = False jsconfig._data._autosave", "means data came from DB and schema is not same", "Item = self._model.index.sql mother_id = self._mother_id_get() if mother_id: condition =", "jsconfig._mother_id_get() if mother_id: assert jsconfig.mother_id == mother_id assert jsconfig._model.schema._md5 ==", "[] return res def find(self, reload=False, **kwargs): \"\"\" :param kwargs:", "TF TECH NV in Belgium see https://www.threefold.tech/ # In case", "except Exception as e: print(\"CHECK WHY ERROR\") j.shell() jsconfig._autosave =", "[] for key, item in list(self._children.items()): match = True for", "exists\") jsconfig = self._new(name=name, jsxobject=jsxobject, autosave=autosave, **kwargs) self._check(jsconfig) return jsconfig", "is a full match :return: \"\"\" # TODO implement filter", "WHY ERROR\") j.shell() jsconfig._autosave = autosave # lets do some", "if condition: res = [i.name for i in Item.select().where(condition)] else:", "def _delete(self, name=None): if name: _, child = self._get(name=name, die=False)", "list(self._children.items()): match = True for key, val in kwargs.items(): if", "condition else Item.name.startswith(filter) if condition: res = [i.name for i", "v3 for more details. # # You should have received", "reset(self): \"\"\" will destroy all data in the DB, be", "GNU General Public License as published by # the Free", "everything else is a full match :return: \"\"\" # TODO", "derived works. If not, see <http://www.gnu.org/licenses/>. # LICENSE END from", "new object, exists\") jsconfig = self._new(name=name, jsxobject=jsxobject, autosave=autosave, **kwargs) self._check(jsconfig)", "res[0] jsxconfig._autosave = autosave return 2, jsxconfig def reset(self): \"\"\"", "[i.name for i in Item.select().where(condition)] else: res = [i.name for", "# lets do some tests (maybe in future can be", "Item.select().where(condition)] else: res = [i.name for i in Item.select()] if", "self._delete(name=name) def _delete(self, name=None): if name: _, child = self._get(name=name,", "mother_id = jsconfig._mother_id_get() if mother_id: assert jsconfig.mother_id == mother_id assert", "obj.load() return 1, obj self._log_debug(\"get child:'%s'from '%s'\" % (name, self._classname))", "filter=None): \"\"\" :param filter: is '' then will show all,", "= autosave return 2, jsxconfig def reset(self): \"\"\" will destroy", "are already in mem ids = self._model.find_ids(**kwargs) for id in", "database if not jsconfig._data._model.schema._md5 == jsconfig._model.schema._md5: # means data came", "obj self._log_debug(\"get child:'%s'from '%s'\" % (name, self._classname)) # new =", "j.shell() jsconfig._autosave = autosave # lets do some tests (maybe", "General Public License # along with jumpscale or jumpscale derived", "= self._childclass_selector(jsxobject=jsxobject) jsconfig = jsconfig_klass(parent=self, jsxobject=jsxobject, **kwargs_to_class) jsconfig._triggers_call(jsconfig, \"new\") jsconfig._autosave", "a full match :return: \"\"\" # TODO implement filter properly", "if not jsxobject: if kwargs: kwargs_to_obj_new = {} props =", "to remember the parent id mother_id = self._mother_id_get() if mother_id:", "as e: j.shell() if not self._mother_id_get(): self._model.index.destroy() def _children_names_get(self, filter=None):", "<https://github.com/threefoldtech>. # jumpscale is free software: you can redistribute it", "\"\"\" if self.exists(name=name): raise j.exceptions.Base(\"cannot do new object, exists\") jsconfig", "color=\"red\",... :return: list of the config objects \"\"\" res =", ":param name: of the object \"\"\" obj = self._validate_child(name) if", "= [] ids_done = [] for key, item in list(self._children.items()):", "# the Free Software Foundation, either version 3 of the", "...) :param jsxobject: you can right away specify the jsxobject", "self._validate_child(name) if obj: return True # will only use the", "props: kwargs_to_obj_new[key] = val else: kwargs_to_class[key] = val jsxobject =", "jsxobject: if kwargs: kwargs_to_obj_new = {} props = [i.name for", "i in Item.select().where(condition)] else: res = [i.name for i in", "of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See", "of the data objects (the data of the model) \"\"\"", "if name: _, child = self._get(name=name, die=False) if child: return", "and self._parent: if self._classname in self._parent._children: if not isinstance(self._parent, j.baseclasses.factory):", "None will ignore _ when * at end it will", "object \"\"\" obj = self._validate_child(name) if obj: return True #", "objects are already in mem ids = self._model.find_ids(**kwargs) for id", "self._children_get(): if item._hasattr(\"save\"): item.save() def delete(self, name=None): \"\"\" :param name:", "if changed and autosave: try: jsconfig.save() except Exception as e:", "name=\"main\", id=None, needexist=False, autosave=True, reload=False, **kwargs): \"\"\" :param name: of", "**kwargs): \"\"\" :param kwargs: e.g. color=\"red\",... :return: list of the", "item not in x: x.append(item) return x def __str__(self): return", "not in x: x.append(item) return x def __str__(self): return \"jsxconfigobj:collection:%s\"", "jsxconfig._autosave = autosave return 2, jsxconfig def reset(self): \"\"\" will", "= Item.name.startswith(filter) and condition if condition else Item.name.startswith(filter) if condition:", "related to Jumpscale & DigitalMe # This file is part", "need to explicitly save the object. :param kwargs: :return: \"\"\"", "except Exception as e: j.shell() if not self._mother_id_get(): self._model.index.destroy() def", "but WITHOUT ANY WARRANTY; without even the implied warranty of", "if child: return child.delete() else: return self.reset() if not name", "building del self._parent._children[self._data.name] def exists(self, name=\"main\"): \"\"\" :param name: of", "jsconfig): if jsconfig._id is None: # model has never been", "val in kwargs.items(): if key in props: kwargs_to_obj_new[key] = val", "jsconfig._triggers_call(jsconfig, \"get\") return jsconfig def _get(self, name=\"main\", id=None, die=True, reload=False,", "i in Item.select()] if len(res) > 50: return [] return", "(given to constructor) :return: the service \"\"\" kwargs_to_class = {}", "else: return self.reset() if not name and self._parent: if self._classname", "autosave argument on the data and also saves the object", "be considered a prefix when * at start it will", "jsxobject, **kwargs): \"\"\" allow custom implementation of which child class", "kwargs_to_class[key] = val jsxobject = self._model.new(data=kwargs_to_obj_new) else: jsxobject = self._model.new()", "removed, but for now the safe bet) self._check(jsconfig) jsconfig._triggers_call(jsconfig, \"get\")", "and autosave: try: jsconfig.save() except Exception as e: print(\"CHECK WHY", "the terms of the GNU General Public License as published", "self.__class__._CHILDCLASS def new(self, name, jsxobject=None, autosave=True, **kwargs): \"\"\" it it", "obj.name return 1, self._new(name, obj) obj = self._validate_child(name) if obj:", "if match: if reload: item.load() res.append(item) if item.id not in", "jsxobject=jsxobject, **kwargs_to_class) jsconfig._triggers_call(jsconfig, \"new\") jsconfig._autosave = autosave self._children[name] = jsconfig", "if jsxobject.mother_id != mother_id: jsxobject.mother_id = mother_id jsconfig_klass = self._childclass_selector(jsxobject=jsxobject)", "Exception as e: j.shell() if not self._mother_id_get(): self._model.index.destroy() def _children_names_get(self,", "can be removed, but for now the safe bet) assert", "the stored values correspond with kwargs given # means comes", "DB and schema is not same as config mgmt class", "key, val in kwargs.items(): if item._hasattr(key): if val != getattr(item,", "= self._validate_child(name) if obj: if reload: obj.load() return 1, obj", "it it exists will delete if first when delete ==", "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #", "object, exists\") jsconfig = self._new(name=name, jsxobject=jsxobject, autosave=autosave, **kwargs) self._check(jsconfig) return", "kwargs): mother_id = self._mother_id_get() if mother_id: kwargs[\"mother_id\"] = mother_id return", "Software Foundation, either version 3 of the License, or #", "if the objects are already in mem ids = self._model.find_ids(**kwargs)", "all code related to Jumpscale & DigitalMe # This file", "def delete(self, name=None): \"\"\" :param name: :return: \"\"\" self._delete(name=name) def", "obj: if reload: obj.load() return 1, obj self._log_debug(\"get child:'%s'from '%s'\"", "new = False res = self.find(name=name) if len(res) < 1:", "& Authorship for all changes made since July 2018 #", "elif len(res) > 1: raise j.exceptions.Base( \"Found more than 1", "child = self._get(name=name, die=False) if child: return child.delete() else: return", "exists(self, name=\"main\"): \"\"\" :param name: of the object \"\"\" obj", "= [i.name for i in self._model.schema.properties] for key, val in", "will delete if first when delete == True :param name:", "GNU General Public License v3 for more details. # #", "underneith (given to constructor) :return: the service \"\"\" kwargs_to_class =", "self._log_debug(\"NEW OBJ:%s:%s\" % (name, self._classname)) jsconfig = self._new(name=name, autosave=autosave, **kwargs)", "val in kwargs.items(): if item._hasattr(key): if val != getattr(item, key):", "name) ) elif len(res) > 1: raise j.exceptions.Base( \"Found more", "PARTICULAR PURPOSE. See the # GNU General Public License v3", "check that the stored values correspond with kwargs given #", "jsconfig: self._log_debug(\"NEW OBJ:%s:%s\" % (name, self._classname)) jsconfig = self._new(name=name, autosave=autosave,", "the data elements which will be given to JSXObject underneith", "given # means comes from the database if not jsconfig._data._model.schema._md5", "is not same as config mgmt class j.shell() changed =", "False res = self.find(name=name) if len(res) < 1: if not", "_children_get(self, filter=None): \"\"\" :param filter: is '' then will show", "considered a end of line filter (endswith) when R as", "to Jumpscale & DigitalMe # This file is part of", "def _check(self, jsconfig): if jsconfig._id is None: # model has", "Jumpscale & DigitalMe # This file is part of jumpscale", "_new(self, name, jsxobject=None, autosave=True, **kwargs): \"\"\" :param name: for the", "as published by # the Free Software Foundation, either version", "None raise j.exceptions.Base( \"Did not find instance for:%s, name searched", "be carefull :return: \"\"\" self._log_debug(\"reset all data\") for item in", ":return: list of the config objects \"\"\" kwargs = self._kwargs_update(kwargs)", "# (at your option) any later version. # # jumpscale", "return self.count(name=name) == 1 def _children_get(self, filter=None): \"\"\" :param filter:", "== 1 def _children_get(self, filter=None): \"\"\" :param filter: is ''", "= self._get(name=name, die=False) if child: return child.delete() else: return self.reset()", "version 3 of the License, or # (at your option)", "% (name, self._classname)) jsconfig = self._new(name=name, autosave=autosave, **kwargs) else: #", "[i.name for i in self._model.schema.properties] for key, val in kwargs.items():", "child class to use :return: \"\"\" return self.__class__._CHILDCLASS def new(self,", "required yet return # lets do some tests (maybe in", "mother_id: jsxobject.mother_id = mother_id jsconfig_klass = self._childclass_selector(jsxobject=jsxobject) jsconfig = jsconfig_klass(parent=self,", "explicitly save the object. :param kwargs: :return: \"\"\" if self.exists(name=name):", "j.exceptions.Base( \"Found more than 1 service for :%s, name searched", "= self._kwargs_update(kwargs) # TODO do proper count query return len(list(self._model.find_ids(**kwargs)))", "in self._children_get(): if item._hasattr(\"save\"): item.save() def delete(self, name=None): \"\"\" :param", "if mother_id: condition = Item.mother_id == mother_id if filter and", "jsconfig._model.schema._md5: # means data came from DB and schema is", "object. :param kwargs: :return: \"\"\" if self.exists(name=name): raise j.exceptions.Base(\"cannot do", "return self.reset() if not name and self._parent: if self._classname in", "return res def _kwargs_update(self, kwargs): mother_id = self._mother_id_get() if mother_id:", "is more efficient no need to go to backend stor", "self._children.items(): x.append(item) x = self._filter(filter=filter, llist=x, nameonly=False) # be smarter", "all data in the DB, be carefull :return: \"\"\" self._log_debug(\"reset", "_, item in self._children.items(): x.append(item) x = self._filter(filter=filter, llist=x, nameonly=False)", "ids_done: ids_done.append(item.id) kwargs = self._kwargs_update(kwargs) # this is more efficient", "item._hasattr(\"save\"): item.save() def delete(self, name=None): \"\"\" :param name: :return: \"\"\"", "name=None): if name: _, child = self._get(name=name, die=False) if child:", "than 1 service for :%s, name searched for:%s\" % (self.__class__._location,", "bet) self._check(jsconfig) jsconfig._triggers_call(jsconfig, \"get\") return jsconfig def _get(self, name=\"main\", id=None,", "object \"\"\" # will reload if needed (not in self._children)", "a copy of the GNU General Public License # along", "for the service, client, ...) :param jsxobject: you can right", "properly x = [] for _, item in self._children.items(): x.append(item)", "obj = self._model.get(id) name = obj.name return 1, self._new(name, obj)", "# GNU General Public License v3 for more details. #", "if id: obj = self._model.get(id) name = obj.name return 1,", "the objects are already in mem ids = self._model.find_ids(**kwargs) for", "if val != getattr(item, key): match = False else: match", "\"\"\" :param name: of the object \"\"\" obj = self._validate_child(name)", "This file is part of jumpscale at <https://github.com/threefoldtech>. # jumpscale", "removed, but for now the safe bet) assert jsconfig._id >", "'%s'\" % (name, self._classname)) # new = False res =", "for key, val in kwargs.items(): if item._hasattr(key): if val !=", "Public License as published by # the Free Software Foundation,", "= self._kwargs_update(kwargs) return self._model.find(**kwargs) def save(self): for item in self._children_get():", "July 2018: TF TECH NV in Belgium see https://www.threefold.tech/ #", "jsconfig def _check_children(self): if not self._cache_use: assert self._children == {}", "= self._model.index.sql mother_id = self._mother_id_get() if mother_id: condition = Item.mother_id", "self._model.schema.properties] for key, val in kwargs.items(): if key in props:", "> 0 mother_id = jsconfig._mother_id_get() if mother_id: assert jsconfig.mother_id ==", "else: jsxobject = self._model.new() jsxobject.name = name # means we", "name) ) else: jsxconfig = res[0] jsxconfig._autosave = autosave return", "if needed (not in self._children) rc, jsconfig = self._get(name=name, id=id,", "kwargs[\"mother_id\"] = mother_id return kwargs def count(self, **kwargs): \"\"\" :param", "never been saved no check required yet return # lets", "if condition else Item.name.startswith(filter) if condition: res = [i.name for", "with jumpscale or jumpscale derived works. If not, see <http://www.gnu.org/licenses/>.", "have received a copy of the GNU General Public License", "\"\"\" self._log_debug(\"reset all data\") for item in self.find(): try: item.delete()", "jsconfig._id is None: # model has never been saved no", "self._kwargs_update(kwargs) return self._model.find(**kwargs) def save(self): for item in self._children_get(): if", "count(self, **kwargs): \"\"\" :param kwargs: e.g. color=\"red\",... :return: list of", "in Belgium see https://www.threefold.tech/ # In case TF TECH NV", "def count(self, **kwargs): \"\"\" :param kwargs: e.g. color=\"red\",... :return: list", "id mother_id = self._mother_id_get() if mother_id: if jsxobject.mother_id != mother_id:", "self._cache_use: assert self._children == {} def _check(self, jsconfig): if jsconfig._id", "name: for the CONFIG item (is a unique name for", "def _kwargs_update(self, kwargs): mother_id = self._mother_id_get() if mother_id: kwargs[\"mother_id\"] =", "== {} def _check(self, jsconfig): if jsconfig._id is None: #", "in the hope that it will be useful, # but", "= True for key, val in kwargs.items(): if item._hasattr(key): if", "\"get\") return jsconfig def _get(self, name=\"main\", id=None, die=True, reload=False, autosave=True):", "but for now the safe bet) self._check(jsconfig) jsconfig._triggers_call(jsconfig, \"get\") return", "# In case TF TECH NV ceases to exist (e.g.", "id=None, die=True, reload=False, autosave=True): if id: obj = self._model.get(id) name", "for item in self.find(): try: item.delete() except Exception as e:", "ids_done = [] for key, item in list(self._children.items()): match =", "of jumpscale at <https://github.com/threefoldtech>. # jumpscale is free software: you", "len(list(self._model.find_ids(**kwargs))) def _findData(self, **kwargs): \"\"\" :param kwargs: e.g. color=\"red\",... :return:", "R as first char its considered to be a regex", "list of the config objects \"\"\" kwargs = self._kwargs_update(kwargs) #", "If set to False, you need to explicitly save the", "correspond with kwargs given # means comes from the database", "val else: kwargs_to_class[key] = val jsxobject = self._model.new(data=kwargs_to_obj_new) else: jsxobject", "you can right away specify the jsxobject :param kwargs: the", "then Incubaid NV also in Belgium will get the Copyright", "from .JSConfigBCDBBase import JSConfigBCDBBase class JSConfigsBCDB(JSConfigBCDBBase): def _childclass_selector(self, jsxobject, **kwargs):", "2, jsxconfig def reset(self): \"\"\" will destroy all data in", "return res def find(self, reload=False, **kwargs): \"\"\" :param kwargs: e.g.", "custom class we're building del self._parent._children[self._data.name] def exists(self, name=\"main\"): \"\"\"", "check required yet return # lets do some tests (maybe", "use the index return self.count(name=name) == 1 def _children_get(self, filter=None):", "filter properly x = [] for _, item in self._children.items():", "autosave=True, **kwargs): \"\"\" it it exists will delete if first", "item.save() def delete(self, name=None): \"\"\" :param name: :return: \"\"\" self._delete(name=name)", "\"\"\" return self.__class__._CHILDCLASS def new(self, name, jsxobject=None, autosave=True, **kwargs): \"\"\"", "will be considered a prefix when * at start it", "in self._parent._children: if not isinstance(self._parent, j.baseclasses.factory): # only delete when", "changed and autosave: try: jsconfig.save() except Exception as e: print(\"CHECK", "if not getattr(jsconfig, key) == val: changed = True setattr(jsconfig,", "{} props = [i.name for i in self._model.schema.properties] for key,", "NV also in Belgium will get the Copyright & Authorship", "**kwargs) self._check(jsconfig) return jsconfig def _check_children(self): if not self._cache_use: assert", "jsconfig._id > 0 mother_id = jsconfig._mother_id_get() if mother_id: assert jsconfig.mother_id", "self._new(name=name, autosave=autosave, **kwargs) else: # check that the stored values", "if not die: return 3, None raise j.exceptions.Base( \"Did not", "proper count query return len(list(self._model.find_ids(**kwargs))) def _findData(self, **kwargs): \"\"\" :param", "(at your option) any later version. # # jumpscale is", "color=\"red\",... :return: list of the data objects (the data of", "class to use :return: \"\"\" return self.__class__._CHILDCLASS def new(self, name,", "**kwargs): \"\"\" allow custom implementation of which child class to", "= True setattr(jsconfig, key, val) if changed and autosave: try:", "= False res = self.find(name=name) if len(res) < 1: if", "the model) \"\"\" kwargs = self._kwargs_update(kwargs) return self._model.find(**kwargs) def save(self):", "def _findData(self, **kwargs): \"\"\" :param kwargs: e.g. color=\"red\",... :return: list", "(self.__class__._location, name) ) else: jsxconfig = res[0] jsxconfig._autosave = autosave", "if self._classname in self._parent._children: if not isinstance(self._parent, j.baseclasses.factory): # only", ":param filter: is '' then will show all, if None", "val: changed = True setattr(jsconfig, key, val) if changed and", "to JSXObject underneith (given to constructor) :return: the service \"\"\"", "def _get(self, name=\"main\", id=None, die=True, reload=False, autosave=True): if id: obj", "objects \"\"\" res = [] ids_done = [] for key,", "will be considered a end of line filter (endswith) when", "obj: return True # will only use the index return", "[] ids_done = [] for key, item in list(self._children.items()): match", "data and also saves the object before the function returns.", "(C) July 2018: TF TECH NV in Belgium see https://www.threefold.tech/", "WARRANTY; without even the implied warranty of # MERCHANTABILITY or", "val in kwargs.items(): if not getattr(jsconfig, key) == val: changed", "kwargs: e.g. color=\"red\",... :return: list of the config objects \"\"\"", "1 def _children_get(self, filter=None): \"\"\" :param filter: is '' then", "jsconfig.mother_id == mother_id assert jsconfig._model.schema._md5 == self._model.schema._md5 def _new(self, name,", "will automatically become Apache v2 for all code related to", "the service \"\"\" kwargs_to_class = {} if not jsxobject: if", "j.shell() if not self._mother_id_get(): self._model.index.destroy() def _children_names_get(self, filter=None): condition =", "jsconfig_klass = self._childclass_selector(jsxobject=jsxobject) jsconfig = jsconfig_klass(parent=self, jsxobject=jsxobject, **kwargs_to_class) jsconfig._triggers_call(jsconfig, \"new\")", "e: j.shell() if not self._mother_id_get(): self._model.index.destroy() def _children_names_get(self, filter=None): condition", "is a custom class we're building del self._parent._children[self._data.name] def exists(self,", "id=None, needexist=False, autosave=True, reload=False, **kwargs): \"\"\" :param name: of the", "(name, self._classname)) jsconfig = self._new(name=name, autosave=autosave, **kwargs) else: # check", ":param kwargs: e.g. color=\"red\",... :return: list of the config objects", "is '' then will show all, if None will ignore", "and also saves the object before the function returns. If", "If not, see <http://www.gnu.org/licenses/>. # LICENSE END from Jumpscale import", "# model has never been saved no check required yet", "= {} props = [i.name for i in self._model.schema.properties] for", "1: if not die: return 3, None raise j.exceptions.Base( \"Did", "3, None raise j.exceptions.Base( \"Did not find instance for:%s, name", "the DB, be carefull :return: \"\"\" self._log_debug(\"reset all data\") for", "data elements which will be given to JSXObject underneith (given", "is distributed in the hope that it will be useful,", "jsconfig_klass(parent=self, jsxobject=jsxobject, **kwargs_to_class) jsconfig._triggers_call(jsconfig, \"new\") jsconfig._autosave = autosave self._children[name] =", "3 of the License, or # (at your option) any", "2018: TF TECH NV in Belgium see https://www.threefold.tech/ # In", "License v3 for more details. # # You should have", "been saved no check required yet return # lets do", "id: obj = self._model.get(id) name = obj.name return 1, self._new(name,", "the index return self.count(name=name) == 1 def _children_get(self, filter=None): \"\"\"", "# # You should have received a copy of the", "match = True for key, val in kwargs.items(): if item._hasattr(key):", "you need to explicitly save the object. :param kwargs: :return:", "name searched for:%s\" % (self.__class__._location, name) ) else: jsxconfig =", "# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the", "and the license will automatically become Apache v2 for all", "jsconfig if autosave: self._children[name].save() jsxobject._autosave = autosave return self._children[name] def", "not isinstance(self._parent, j.baseclasses.factory): # only delete when not a factory", "= {} if not jsxobject: if kwargs: kwargs_to_obj_new = {}", "without even the implied warranty of # MERCHANTABILITY or FITNESS", "see <http://www.gnu.org/licenses/>. # LICENSE END from Jumpscale import j from" ]
[ "Sum Square Residuals of a given node on training data", "def predict(self, example, deleted=[]): current_node = self.root while(not current_node.is_leaf() and", "return current_node.prediction # Generate Sum Square Residuals of a given", "root): self.y = y_train self.root = root # Generate Prediction", "ssr + pow((self.y[example] - node.prediction) , 2) return ssr def", "Tree class Regression_Tree: def __init__(self, y_train, root): self.y = y_train", "_print(self, node): node_id = str(node.id) r_string = node_id + \"", "return False def leafs_id(self): if(not self.is_leaf()): return self._leafs_search(self.left) + self._leafs_search(self.right)", "node_id, index=None, value=None, examples=None, prediction=0): self.index = index self.id =", "Residuals of a given node on training data def node_ssr(self,", "node): ssr = 0 for example in node.examples: ssr =", "node_ssr(self, node): ssr = 0 for example in node.examples: ssr", "return self._leafs_search(self.left) + self._leafs_search(self.right) return [1] def n_leafs(self): return len(self.leafs_id())", "index=None, value=None, examples=None, prediction=0): self.index = index self.id = node_id", "if(example[current_node.index] <= current_node.value): current_node = current_node.left else: current_node = current_node.right", "def is_leaf(self): if(self.right == None and self.left == None): return", "None self.left = None self.ssr = 0 self.leaves = 0", "print(len(node.examples)) else: self.print_leaf(node.left) self.print_leaf(node.right) def _print(self, node): node_id = str(node.id)", "return [node.id] return self._leafs_search(node.left) + self._leafs_search(node.right) def __str__(self): return str(self.id)", "== None and self.left == None): return True return False", "def __str__(self): return str(self.id) # Regression Tree class Regression_Tree: def", "a test example def predict(self, example, deleted=[]): current_node = self.root", "prediction=0): self.index = index self.id = node_id self.prediction = prediction", "return True return False def leafs_id(self): if(not self.is_leaf()): return self._leafs_search(self.left)", "else: current_node = current_node.right return current_node.prediction # Generate Sum Square", "self.ssr_as_root = 0 def is_leaf(self): if(self.right == None and self.left", "+ self._leafs_search(self.right) return [1] def n_leafs(self): return len(self.leafs_id()) def _leafs_search(self,", "# Regression Tree Node class Node: def __init__(self, parent, node_id,", "0 self.leaves = 0 self.ssr_as_root = 0 def is_leaf(self): if(self.right", "- node.prediction) , 2) return ssr def leafs_id(self): return self.root.leafs_id()", "self.right = None self.left = None self.ssr = 0 self.leaves", "Regression_Tree: def __init__(self, y_train, root): self.y = y_train self.root =", "def _print(self, node): node_id = str(node.id) r_string = node_id +", "class Node: def __init__(self, parent, node_id, index=None, value=None, examples=None, prediction=0):", "False)): if(example[current_node.index] <= current_node.value): current_node = current_node.left else: current_node =", "def node_ssr(self, node): ssr = 0 for example in node.examples:", "__init__(self, y_train, root): self.y = y_train self.root = root #", "and ((current_node in deleted) == False)): if(example[current_node.index] <= current_node.value): current_node", "and self.left == None): return True return False def leafs_id(self):", "False def leafs_id(self): if(not self.is_leaf()): return self._leafs_search(self.left) + self._leafs_search(self.right) return", "err # Regression Tree Node class Node: def __init__(self, parent,", "current_node = self.root while(not current_node.is_leaf() and ((current_node in deleted) ==", "current_node.prediction # Generate Sum Square Residuals of a given node", "parent self.examples = examples self.right = None self.left = None", "= root # Generate Prediction given a test example def", "((current_node in deleted) == False)): if(example[current_node.index] <= current_node.value): current_node =", "current_node.is_leaf() and ((current_node in deleted) == False)): if(example[current_node.index] <= current_node.value):", "Tree Node class Node: def __init__(self, parent, node_id, index=None, value=None,", "index self.id = node_id self.prediction = prediction self.value = value", "0 def is_leaf(self): if(self.right == None and self.left == None):", "as err # Regression Tree Node class Node: def __init__(self,", "__init__(self, parent, node_id, index=None, value=None, examples=None, prediction=0): self.index = index", "def print_leaf(self, node): if(node.is_leaf()): print(len(node.examples)) else: self.print_leaf(node.left) self.print_leaf(node.right) def _print(self,", "= node_id self.prediction = prediction self.value = value self.parent =", "= None self.left = None self.ssr = 0 self.leaves =", "= r_string + \"\\nLeft : \" + node_id + \"\\n\"", "= r_string + \"\\nRight: \" + node_id + \"\\n\" +", "ssr def leafs_id(self): return self.root.leafs_id() def n_leafs(self): return len(self.leafs_id()) def", "Node class Node: def __init__(self, parent, node_id, index=None, value=None, examples=None,", "= parent self.examples = examples self.right = None self.left =", "== False)): if(example[current_node.index] <= current_node.value): current_node = current_node.left else: current_node", "return self._leafs_search(node.left) + self._leafs_search(node.right) def __str__(self): return str(self.id) # Regression", "prediction self.value = value self.parent = parent self.examples = examples", "leafs_id(self): return self.root.leafs_id() def n_leafs(self): return len(self.leafs_id()) def __str__(self): return", "str(node.id) r_string = node_id + \" \" + str(node.ssr) if(not", "+ \" \" + str(node.ssr) if(not node.is_leaf()): r_string = r_string", "[1] def n_leafs(self): return len(self.leafs_id()) def _leafs_search(self, node): if node.is_leaf():", "r_string + \"\\nLeft : \" + node_id + \"\\n\" +", "self.root.leafs_id() def n_leafs(self): return len(self.leafs_id()) def __str__(self): return self._print(self.root) def", "+ pow((self.y[example] - node.prediction) , 2) return ssr def leafs_id(self):", "parent, node_id, index=None, value=None, examples=None, prediction=0): self.index = index self.id", "0 self.ssr_as_root = 0 def is_leaf(self): if(self.right == None and", "# Generate Prediction given a test example def predict(self, example,", "if node.is_leaf(): return [node.id] return self._leafs_search(node.left) + self._leafs_search(node.right) def __str__(self):", "examples self.right = None self.left = None self.ssr = 0", "current_node.value): current_node = current_node.left else: current_node = current_node.right return current_node.prediction", "a given node on training data def node_ssr(self, node): ssr", "return len(self.leafs_id()) def _leafs_search(self, node): if node.is_leaf(): return [node.id] return", "self._leafs_search(node.right) def __str__(self): return str(self.id) # Regression Tree class Regression_Tree:", "data def node_ssr(self, node): ssr = 0 for example in", "__str__(self): return str(self.id) # Regression Tree class Regression_Tree: def __init__(self,", "training data def node_ssr(self, node): ssr = 0 for example", "= self.root while(not current_node.is_leaf() and ((current_node in deleted) == False)):", "= current_node.left else: current_node = current_node.right return current_node.prediction # Generate", "pow((self.y[example] - node.prediction) , 2) return ssr def leafs_id(self): return", "predict(self, example, deleted=[]): current_node = self.root while(not current_node.is_leaf() and ((current_node", "# Regression Tree class Regression_Tree: def __init__(self, y_train, root): self.y", "self.root = root # Generate Prediction given a test example", "= None self.ssr = 0 self.leaves = 0 self.ssr_as_root =", "def _leafs_search(self, node): if node.is_leaf(): return [node.id] return self._leafs_search(node.left) +", "def n_leafs(self): return len(self.leafs_id()) def _leafs_search(self, node): if node.is_leaf(): return", "[node.id] return self._leafs_search(node.left) + self._leafs_search(node.right) def __str__(self): return str(self.id) #", "for example in node.examples: ssr = ssr + pow((self.y[example] -", "utl import error_measures as err # Regression Tree Node class", "+ \"\\n\" + self._print(node.left) r_string = r_string + \"\\nRight: \"", "Prediction given a test example def predict(self, example, deleted=[]): current_node", "print_leaf(self, node): if(node.is_leaf()): print(len(node.examples)) else: self.print_leaf(node.left) self.print_leaf(node.right) def _print(self, node):", "on training data def node_ssr(self, node): ssr = 0 for", "current_node = current_node.right return current_node.prediction # Generate Sum Square Residuals", "ssr = 0 for example in node.examples: ssr = ssr", "import error_measures as err # Regression Tree Node class Node:", "self._leafs_search(self.right) return [1] def n_leafs(self): return len(self.leafs_id()) def _leafs_search(self, node):", "def n_leafs(self): return len(self.leafs_id()) def __str__(self): return self._print(self.root) def print_leaf(self,", "+ str(node.ssr) if(not node.is_leaf()): r_string = r_string + \"\\nLeft :", "r_string = r_string + \"\\nRight: \" + node_id + \"\\n\"", "# Generate Sum Square Residuals of a given node on", "in deleted) == False)): if(example[current_node.index] <= current_node.value): current_node = current_node.left", "node.examples: ssr = ssr + pow((self.y[example] - node.prediction) , 2)", "+ node_id + \"\\n\" + self._print(node.left) r_string = r_string +", "= 0 self.leaves = 0 self.ssr_as_root = 0 def is_leaf(self):", "root # Generate Prediction given a test example def predict(self,", "node.is_leaf()): r_string = r_string + \"\\nLeft : \" + node_id", "if(not node.is_leaf()): r_string = r_string + \"\\nLeft : \" +", "if(node.is_leaf()): print(len(node.examples)) else: self.print_leaf(node.left) self.print_leaf(node.right) def _print(self, node): node_id =", "\" \" + str(node.ssr) if(not node.is_leaf()): r_string = r_string +", "node): if node.is_leaf(): return [node.id] return self._leafs_search(node.left) + self._leafs_search(node.right) def", "is_leaf(self): if(self.right == None and self.left == None): return True", "= index self.id = node_id self.prediction = prediction self.value =", "\"\\nRight: \" + node_id + \"\\n\" + self._print(node.right) return r_string", "\" + node_id + \"\\n\" + self._print(node.left) r_string = r_string", "deleted) == False)): if(example[current_node.index] <= current_node.value): current_node = current_node.left else:", "Generate Sum Square Residuals of a given node on training", "self.print_leaf(node.right) def _print(self, node): node_id = str(node.id) r_string = node_id", "= str(node.id) r_string = node_id + \" \" + str(node.ssr)", "return ssr def leafs_id(self): return self.root.leafs_id() def n_leafs(self): return len(self.leafs_id())", "import utils as utl import error_measures as err # Regression", "\"\\nLeft : \" + node_id + \"\\n\" + self._print(node.left) r_string", "+ self._leafs_search(node.right) def __str__(self): return str(self.id) # Regression Tree class", "n_leafs(self): return len(self.leafs_id()) def _leafs_search(self, node): if node.is_leaf(): return [node.id]", "= 0 self.ssr_as_root = 0 def is_leaf(self): if(self.right == None", "return str(self.id) # Regression Tree class Regression_Tree: def __init__(self, y_train,", "of a given node on training data def node_ssr(self, node):", "0 for example in node.examples: ssr = ssr + pow((self.y[example]", "utils as utl import error_measures as err # Regression Tree", "node_id self.prediction = prediction self.value = value self.parent = parent", "= examples self.right = None self.left = None self.ssr =", "node.prediction) , 2) return ssr def leafs_id(self): return self.root.leafs_id() def", "n_leafs(self): return len(self.leafs_id()) def __str__(self): return self._print(self.root) def print_leaf(self, node):", "self.root while(not current_node.is_leaf() and ((current_node in deleted) == False)): if(example[current_node.index]", "given a test example def predict(self, example, deleted=[]): current_node =", "ssr = ssr + pow((self.y[example] - node.prediction) , 2) return", "as utl import error_measures as err # Regression Tree Node", "def leafs_id(self): if(not self.is_leaf()): return self._leafs_search(self.left) + self._leafs_search(self.right) return [1]", "leafs_id(self): if(not self.is_leaf()): return self._leafs_search(self.left) + self._leafs_search(self.right) return [1] def", "Regression Tree Node class Node: def __init__(self, parent, node_id, index=None,", "<= current_node.value): current_node = current_node.left else: current_node = current_node.right return", "\"\\n\" + self._print(node.left) r_string = r_string + \"\\nRight: \" +", "= ssr + pow((self.y[example] - node.prediction) , 2) return ssr", "def __str__(self): return self._print(self.root) def print_leaf(self, node): if(node.is_leaf()): print(len(node.examples)) else:", "r_string = r_string + \"\\nLeft : \" + node_id +", "self.leaves = 0 self.ssr_as_root = 0 def is_leaf(self): if(self.right ==", "Node: def __init__(self, parent, node_id, index=None, value=None, examples=None, prediction=0): self.index", "class Regression_Tree: def __init__(self, y_train, root): self.y = y_train self.root", "__str__(self): return self._print(self.root) def print_leaf(self, node): if(node.is_leaf()): print(len(node.examples)) else: self.print_leaf(node.left)", "str(self.id) # Regression Tree class Regression_Tree: def __init__(self, y_train, root):", "None): return True return False def leafs_id(self): if(not self.is_leaf()): return", "if(not self.is_leaf()): return self._leafs_search(self.left) + self._leafs_search(self.right) return [1] def n_leafs(self):", "given node on training data def node_ssr(self, node): ssr =", "self._print(self.root) def print_leaf(self, node): if(node.is_leaf()): print(len(node.examples)) else: self.print_leaf(node.left) self.print_leaf(node.right) def", "current_node = current_node.left else: current_node = current_node.right return current_node.prediction #", "self.left == None): return True return False def leafs_id(self): if(not", "self.is_leaf()): return self._leafs_search(self.left) + self._leafs_search(self.right) return [1] def n_leafs(self): return", "while(not current_node.is_leaf() and ((current_node in deleted) == False)): if(example[current_node.index] <=", "= y_train self.root = root # Generate Prediction given a", "= value self.parent = parent self.examples = examples self.right =", "current_node.left else: current_node = current_node.right return current_node.prediction # Generate Sum", "if(self.right == None and self.left == None): return True return", "Regression Tree class Regression_Tree: def __init__(self, y_train, root): self.y =", "Generate Prediction given a test example def predict(self, example, deleted=[]):", "node): node_id = str(node.id) r_string = node_id + \" \"", "self._leafs_search(node.left) + self._leafs_search(node.right) def __str__(self): return str(self.id) # Regression Tree", "example, deleted=[]): current_node = self.root while(not current_node.is_leaf() and ((current_node in", "return len(self.leafs_id()) def __str__(self): return self._print(self.root) def print_leaf(self, node): if(node.is_leaf()):", "def __init__(self, y_train, root): self.y = y_train self.root = root", "True return False def leafs_id(self): if(not self.is_leaf()): return self._leafs_search(self.left) +", "else: self.print_leaf(node.left) self.print_leaf(node.right) def _print(self, node): node_id = str(node.id) r_string", ", 2) return ssr def leafs_id(self): return self.root.leafs_id() def n_leafs(self):", "value self.parent = parent self.examples = examples self.right = None", "value=None, examples=None, prediction=0): self.index = index self.id = node_id self.prediction", "len(self.leafs_id()) def __str__(self): return self._print(self.root) def print_leaf(self, node): if(node.is_leaf()): print(len(node.examples))", "self.examples = examples self.right = None self.left = None self.ssr", "= 0 def is_leaf(self): if(self.right == None and self.left ==", "example def predict(self, example, deleted=[]): current_node = self.root while(not current_node.is_leaf()", "examples=None, prediction=0): self.index = index self.id = node_id self.prediction =", "self.prediction = prediction self.value = value self.parent = parent self.examples", "= 0 for example in node.examples: ssr = ssr +", "= prediction self.value = value self.parent = parent self.examples =", "self.ssr = 0 self.leaves = 0 self.ssr_as_root = 0 def", "r_string + \"\\nRight: \" + node_id + \"\\n\" + self._print(node.right)", "self.parent = parent self.examples = examples self.right = None self.left", "y_train, root): self.y = y_train self.root = root # Generate", "def leafs_id(self): return self.root.leafs_id() def n_leafs(self): return len(self.leafs_id()) def __str__(self):", "self.print_leaf(node.left) self.print_leaf(node.right) def _print(self, node): node_id = str(node.id) r_string =", "deleted=[]): current_node = self.root while(not current_node.is_leaf() and ((current_node in deleted)", "self._leafs_search(self.left) + self._leafs_search(self.right) return [1] def n_leafs(self): return len(self.leafs_id()) def", "_leafs_search(self, node): if node.is_leaf(): return [node.id] return self._leafs_search(node.left) + self._leafs_search(node.right)", "+ \"\\nLeft : \" + node_id + \"\\n\" + self._print(node.left)", "def __init__(self, parent, node_id, index=None, value=None, examples=None, prediction=0): self.index =", "+ self._print(node.left) r_string = r_string + \"\\nRight: \" + node_id", "node): if(node.is_leaf()): print(len(node.examples)) else: self.print_leaf(node.left) self.print_leaf(node.right) def _print(self, node): node_id", "== None): return True return False def leafs_id(self): if(not self.is_leaf()):", "self.left = None self.ssr = 0 self.leaves = 0 self.ssr_as_root", "2) return ssr def leafs_id(self): return self.root.leafs_id() def n_leafs(self): return", "node.is_leaf(): return [node.id] return self._leafs_search(node.left) + self._leafs_search(node.right) def __str__(self): return", "node on training data def node_ssr(self, node): ssr = 0", "Square Residuals of a given node on training data def", "y_train self.root = root # Generate Prediction given a test", "return self._print(self.root) def print_leaf(self, node): if(node.is_leaf()): print(len(node.examples)) else: self.print_leaf(node.left) self.print_leaf(node.right)", "example in node.examples: ssr = ssr + pow((self.y[example] - node.prediction)", "node_id = str(node.id) r_string = node_id + \" \" +", "= current_node.right return current_node.prediction # Generate Sum Square Residuals of", "return self.root.leafs_id() def n_leafs(self): return len(self.leafs_id()) def __str__(self): return self._print(self.root)", ": \" + node_id + \"\\n\" + self._print(node.left) r_string =", "\" + str(node.ssr) if(not node.is_leaf()): r_string = r_string + \"\\nLeft", "self.y = y_train self.root = root # Generate Prediction given", "self._print(node.left) r_string = r_string + \"\\nRight: \" + node_id +", "current_node.right return current_node.prediction # Generate Sum Square Residuals of a", "node_id + \"\\n\" + self._print(node.left) r_string = r_string + \"\\nRight:", "return [1] def n_leafs(self): return len(self.leafs_id()) def _leafs_search(self, node): if", "len(self.leafs_id()) def _leafs_search(self, node): if node.is_leaf(): return [node.id] return self._leafs_search(node.left)", "+ \"\\nRight: \" + node_id + \"\\n\" + self._print(node.right) return", "self.value = value self.parent = parent self.examples = examples self.right", "r_string = node_id + \" \" + str(node.ssr) if(not node.is_leaf()):", "test example def predict(self, example, deleted=[]): current_node = self.root while(not", "error_measures as err # Regression Tree Node class Node: def", "None self.ssr = 0 self.leaves = 0 self.ssr_as_root = 0", "node_id + \" \" + str(node.ssr) if(not node.is_leaf()): r_string =", "str(node.ssr) if(not node.is_leaf()): r_string = r_string + \"\\nLeft : \"", "None and self.left == None): return True return False def", "in node.examples: ssr = ssr + pow((self.y[example] - node.prediction) ,", "= node_id + \" \" + str(node.ssr) if(not node.is_leaf()): r_string", "self.index = index self.id = node_id self.prediction = prediction self.value", "self.id = node_id self.prediction = prediction self.value = value self.parent" ]
[ "from starlette.staticfiles import StaticFiles app = Starlette(debug=False, template_directory='src/site/templates') app.add_middleware(GZipMiddleware, minimum_size=500)", "app = Starlette(debug=False, template_directory='src/site/templates') app.add_middleware(GZipMiddleware, minimum_size=500) app.add_middleware(CORSMiddleware, allow_origins=['*']) app.mount('/static', StaticFiles(directory='src/site/media'),", "<reponame>ninaamorim/sentiment-analysis-2018-president-election from starlette.applications import Starlette from starlette.middleware.gzip import GZipMiddleware from", "Starlette from starlette.middleware.gzip import GZipMiddleware from starlette.middleware.cors import CORSMiddleware from", "from starlette.applications import Starlette from starlette.middleware.gzip import GZipMiddleware from starlette.middleware.cors", "from starlette.middleware.gzip import GZipMiddleware from starlette.middleware.cors import CORSMiddleware from starlette.staticfiles", "starlette.middleware.cors import CORSMiddleware from starlette.staticfiles import StaticFiles app = Starlette(debug=False,", "StaticFiles app = Starlette(debug=False, template_directory='src/site/templates') app.add_middleware(GZipMiddleware, minimum_size=500) app.add_middleware(CORSMiddleware, allow_origins=['*']) app.mount('/static',", "starlette.staticfiles import StaticFiles app = Starlette(debug=False, template_directory='src/site/templates') app.add_middleware(GZipMiddleware, minimum_size=500) app.add_middleware(CORSMiddleware,", "import Starlette from starlette.middleware.gzip import GZipMiddleware from starlette.middleware.cors import CORSMiddleware", "CORSMiddleware from starlette.staticfiles import StaticFiles app = Starlette(debug=False, template_directory='src/site/templates') app.add_middleware(GZipMiddleware,", "= Starlette(debug=False, template_directory='src/site/templates') app.add_middleware(GZipMiddleware, minimum_size=500) app.add_middleware(CORSMiddleware, allow_origins=['*']) app.mount('/static', StaticFiles(directory='src/site/media'), name='static')", "GZipMiddleware from starlette.middleware.cors import CORSMiddleware from starlette.staticfiles import StaticFiles app", "from starlette.middleware.cors import CORSMiddleware from starlette.staticfiles import StaticFiles app =", "starlette.applications import Starlette from starlette.middleware.gzip import GZipMiddleware from starlette.middleware.cors import", "import StaticFiles app = Starlette(debug=False, template_directory='src/site/templates') app.add_middleware(GZipMiddleware, minimum_size=500) app.add_middleware(CORSMiddleware, allow_origins=['*'])", "starlette.middleware.gzip import GZipMiddleware from starlette.middleware.cors import CORSMiddleware from starlette.staticfiles import", "import GZipMiddleware from starlette.middleware.cors import CORSMiddleware from starlette.staticfiles import StaticFiles", "import CORSMiddleware from starlette.staticfiles import StaticFiles app = Starlette(debug=False, template_directory='src/site/templates')" ]
[ "#! /usr/bin/env python3 # -*- coding: utf-8 -*- \"\"\" Contains", "core logic for Rainman2 \"\"\" __author__ = '<NAME> (<EMAIL>), <NAME>(<EMAIL>)'", "# -*- coding: utf-8 -*- \"\"\" Contains core logic for", "__author__ = '<NAME> (<EMAIL>), <NAME>(<EMAIL>)' __date__ = 'Wednesday, February 14th", "\"\"\" __author__ = '<NAME> (<EMAIL>), <NAME>(<EMAIL>)' __date__ = 'Wednesday, February", "python3 # -*- coding: utf-8 -*- \"\"\" Contains core logic", "utf-8 -*- \"\"\" Contains core logic for Rainman2 \"\"\" __author__", "/usr/bin/env python3 # -*- coding: utf-8 -*- \"\"\" Contains core", "-*- coding: utf-8 -*- \"\"\" Contains core logic for Rainman2", "coding: utf-8 -*- \"\"\" Contains core logic for Rainman2 \"\"\"", "Rainman2 \"\"\" __author__ = '<NAME> (<EMAIL>), <NAME>(<EMAIL>)' __date__ = 'Wednesday,", "\"\"\" Contains core logic for Rainman2 \"\"\" __author__ = '<NAME>", "for Rainman2 \"\"\" __author__ = '<NAME> (<EMAIL>), <NAME>(<EMAIL>)' __date__ =", "'<NAME> (<EMAIL>), <NAME>(<EMAIL>)' __date__ = 'Wednesday, February 14th 2018, 11:42:09", "(<EMAIL>), <NAME>(<EMAIL>)' __date__ = 'Wednesday, February 14th 2018, 11:42:09 am'", "logic for Rainman2 \"\"\" __author__ = '<NAME> (<EMAIL>), <NAME>(<EMAIL>)' __date__", "Contains core logic for Rainman2 \"\"\" __author__ = '<NAME> (<EMAIL>),", "-*- \"\"\" Contains core logic for Rainman2 \"\"\" __author__ =", "= '<NAME> (<EMAIL>), <NAME>(<EMAIL>)' __date__ = 'Wednesday, February 14th 2018," ]
[ "._version import get_versions versions = get_versions() __version__ = versions[\"version\"] __git_revision__", "__git_revision__ = versions[\"full-revisionid\"] del get_versions, versions # Silence verbose messages", "= versions[\"full-revisionid\"] del get_versions, versions # Silence verbose messages when", "individual molecules. \"\"\" import logging import sys from ._version import", "or don't import simtk warnings... if sys.argv[0].endswith(\"openff-bespoke\"): from openff.bespokefit.utilities.logging import", "'Unable to load AmberTools' or don't import simtk warnings... if", "get_versions, versions # Silence verbose messages when running the CLI", "load AmberTools' or don't import simtk warnings... if sys.argv[0].endswith(\"openff-bespoke\"): from", "verbose messages when running the CLI otherwise you can't read", "AmberTools' or don't import simtk warnings... if sys.argv[0].endswith(\"openff-bespoke\"): from openff.bespokefit.utilities.logging", "# Silence verbose messages when running the CLI otherwise you", "from ._version import get_versions versions = get_versions() __version__ = versions[\"version\"]", "get_versions versions = get_versions() __version__ = versions[\"version\"] __git_revision__ = versions[\"full-revisionid\"]", "output # without seeing tens of 'Unable to load AmberTools'", "Silence verbose messages when running the CLI otherwise you can't", "can't read the output # without seeing tens of 'Unable", "= versions[\"version\"] __git_revision__ = versions[\"full-revisionid\"] del get_versions, versions # Silence", "don't import simtk warnings... if sys.argv[0].endswith(\"openff-bespoke\"): from openff.bespokefit.utilities.logging import DeprecationWarningFilter", "versions = get_versions() __version__ = versions[\"version\"] __git_revision__ = versions[\"full-revisionid\"] del", "without seeing tens of 'Unable to load AmberTools' or don't", "simtk warnings... if sys.argv[0].endswith(\"openff-bespoke\"): from openff.bespokefit.utilities.logging import DeprecationWarningFilter # if", "del get_versions, versions # Silence verbose messages when running the", "the CLI otherwise you can't read the output # without", "CLI otherwise you can't read the output # without seeing", "to load AmberTools' or don't import simtk warnings... if sys.argv[0].endswith(\"openff-bespoke\"):", "versions[\"version\"] __git_revision__ = versions[\"full-revisionid\"] del get_versions, versions # Silence verbose", "molecules. \"\"\" import logging import sys from ._version import get_versions", "\"\"\" import logging import sys from ._version import get_versions versions", "import logging import sys from ._version import get_versions versions =", "the output # without seeing tens of 'Unable to load", "# without seeing tens of 'Unable to load AmberTools' or", "= get_versions() __version__ = versions[\"version\"] __git_revision__ = versions[\"full-revisionid\"] del get_versions,", "sys from ._version import get_versions versions = get_versions() __version__ =", "messages when running the CLI otherwise you can't read the", "when running the CLI otherwise you can't read the output", "running the CLI otherwise you can't read the output #", "get_versions() __version__ = versions[\"version\"] __git_revision__ = versions[\"full-revisionid\"] del get_versions, versions", "logging import sys from ._version import get_versions versions = get_versions()", "for individual molecules. \"\"\" import logging import sys from ._version", "otherwise you can't read the output # without seeing tens", "read the output # without seeing tens of 'Unable to", "warnings... if sys.argv[0].endswith(\"openff-bespoke\"): from openff.bespokefit.utilities.logging import DeprecationWarningFilter # if \"openff-bespoke\"", "versions[\"full-revisionid\"] del get_versions, versions # Silence verbose messages when running", "Creating bespoke parameters for individual molecules. \"\"\" import logging import", "import sys from ._version import get_versions versions = get_versions() __version__", "parameters for individual molecules. \"\"\" import logging import sys from", "bespoke parameters for individual molecules. \"\"\" import logging import sys", "of 'Unable to load AmberTools' or don't import simtk warnings...", "versions # Silence verbose messages when running the CLI otherwise", "import get_versions versions = get_versions() __version__ = versions[\"version\"] __git_revision__ =", "\"\"\" BespokeFit Creating bespoke parameters for individual molecules. \"\"\" import", "tens of 'Unable to load AmberTools' or don't import simtk", "if sys.argv[0].endswith(\"openff-bespoke\"): from openff.bespokefit.utilities.logging import DeprecationWarningFilter # if \"openff-bespoke\" logging.getLogger(\"openff.toolkit\").setLevel(logging.ERROR)", "seeing tens of 'Unable to load AmberTools' or don't import", "sys.argv[0].endswith(\"openff-bespoke\"): from openff.bespokefit.utilities.logging import DeprecationWarningFilter # if \"openff-bespoke\" logging.getLogger(\"openff.toolkit\").setLevel(logging.ERROR) logging.getLogger().addFilter(DeprecationWarningFilter())", "__version__ = versions[\"version\"] __git_revision__ = versions[\"full-revisionid\"] del get_versions, versions #", "you can't read the output # without seeing tens of", "BespokeFit Creating bespoke parameters for individual molecules. \"\"\" import logging", "import simtk warnings... if sys.argv[0].endswith(\"openff-bespoke\"): from openff.bespokefit.utilities.logging import DeprecationWarningFilter #" ]
[ "is number of pressure divisions lenG = len(G) lenx =", "write the file: g = sdf.Group('/', comment='2006 CHF LUT', datasets=[ds_G,ds_x,ds_P,ds_q])", "# Load 2006 LUT for interpolation # 2006 Groeneveld Look-Up", "divisions # N is number of quality divisions # Q", "divisions # Q is number of pressure divisions lenG =", "from 2006 LUT, convert to [Pa] P = np.array((0.10,0.30,0.50,1.0,2.0,3.0,5.0,7.0,10.0,12.0,14.0,16.0,18.0,20.0,21.0))*1e6 #", "Apr 03 11:06:37 2018 @author: vmg \"\"\" import sdf import", "flux divisions # N is number of quality divisions #", "[MPa] from 2006 LUT, convert to [Pa] P = np.array((0.10,0.30,0.50,1.0,2.0,3.0,5.0,7.0,10.0,12.0,14.0,16.0,18.0,20.0,21.0))*1e6", "Created on Tue Apr 03 11:06:37 2018 @author: vmg \"\"\"", "data=P, unit='Pa', is_scale=True, display_name='Pressure') ds_q = sdf.Dataset('q', data=q, unit='W/m2', scales=[ds_G,ds_x,ds_P])", "[W/m^2] q_raw=np.loadtxt('../Data/2006LUTdata.txt')*1e3 # Convert the imported array into a (MxNxQ)", "utf-8 -*- \"\"\" Created on Tue Apr 03 11:06:37 2018", "# Pressure range [MPa] from 2006 LUT, convert to [Pa]", "CHF Look-Up Table\", Nuclear Engineering and Design 237, pp. 190-1922.", "in xrange(lenP): q[i,j,k] = q_raw[i + k*lenG,j] # Create the", "ds_q = sdf.Dataset('q', data=q, unit='W/m2', scales=[ds_G,ds_x,ds_P]) # Create the root", "This file requires the file 2006LUTdata.txt # Pressure range [MPa]", "190-1922. # This file requires the file 2006LUTdata.txt # Pressure", "\"\"\" import sdf import numpy as np # Load 2006", "x = np.array((-0.50,-0.40,-0.30,-0.20,-0.15,-0.10,-0.05,0.00,0.05,0.10,0.15,0.20,0.25,0.30,0.35,0.40,0.45,0.50,0.60,0.70,0.80,0.90,1.00)) # Critical heat flux [kW/m^2] from 2006", "[kW/m^2] from 2006 LUT, convert to [W/m^2] q_raw=np.loadtxt('../Data/2006LUTdata.txt')*1e3 # Convert", "i in xrange(lenG): for j in xrange(lenx): for k in", "q = np.zeros((lenG,lenx,lenP)) for i in xrange(lenG): for j in", "Create the root group and write the file: g =", "+ k*lenG,j] # Create the datasets: ds_G = sdf.Dataset('G', data=G,", "LUT for interpolation # 2006 Groeneveld Look-Up Table as presented", "Nuclear Engineering and Design 237, pp. 190-1922. # This file", "np.array((0.,50.,100.,300.,500.,750.,1000.,1500.,2000.,2500.,3000.,3500.,4000.,4500.,5000.,5500.,6000.,6500.,7000.,7500.,8000.)) # Quality range from 2006 LUT x = np.array((-0.50,-0.40,-0.30,-0.20,-0.15,-0.10,-0.05,0.00,0.05,0.10,0.15,0.20,0.25,0.30,0.35,0.40,0.45,0.50,0.60,0.70,0.80,0.90,1.00))", "is number of quality divisions # Q is number of", "sdf.Dataset('G', data=G, unit='kg/(m2.s)', is_scale=True, display_name='Mass Flux') ds_x = sdf.Dataset('x', data=x,", "= len(G) lenx = len(x) lenP = len(P) q =", "xrange(lenP): q[i,j,k] = q_raw[i + k*lenG,j] # Create the datasets:", "ds_P = sdf.Dataset('P', data=P, unit='Pa', is_scale=True, display_name='Pressure') ds_q = sdf.Dataset('q',", "= sdf.Dataset('P', data=P, unit='Pa', is_scale=True, display_name='Pressure') ds_q = sdf.Dataset('q', data=q,", "sdf.Dataset('x', data=x, unit='1', is_scale=True, display_name='Quality') ds_P = sdf.Dataset('P', data=P, unit='Pa',", "\"\"\" Created on Tue Apr 03 11:06:37 2018 @author: vmg", "03 11:06:37 2018 @author: vmg \"\"\" import sdf import numpy", "= len(x) lenP = len(P) q = np.zeros((lenG,lenx,lenP)) for i", "number of quality divisions # Q is number of pressure", "# Create the root group and write the file: g", "datasets: ds_G = sdf.Dataset('G', data=G, unit='kg/(m2.s)', is_scale=True, display_name='Mass Flux') ds_x", "Table\", Nuclear Engineering and Design 237, pp. 190-1922. # This", "pressure divisions lenG = len(G) lenx = len(x) lenP =", "2006 LUT x = np.array((-0.50,-0.40,-0.30,-0.20,-0.15,-0.10,-0.05,0.00,0.05,0.10,0.15,0.20,0.25,0.30,0.35,0.40,0.45,0.50,0.60,0.70,0.80,0.90,1.00)) # Critical heat flux [kW/m^2]", "Create the datasets: ds_G = sdf.Dataset('G', data=G, unit='kg/(m2.s)', is_scale=True, display_name='Mass", "to [W/m^2] q_raw=np.loadtxt('../Data/2006LUTdata.txt')*1e3 # Convert the imported array into a", "a (MxNxQ) where: # M is number of mass flux", "q_raw[i + k*lenG,j] # Create the datasets: ds_G = sdf.Dataset('G',", "Flux range [kg/m^2-s] from 2006 .LUT. G = np.array((0.,50.,100.,300.,500.,750.,1000.,1500.,2000.,2500.,3000.,3500.,4000.,4500.,5000.,5500.,6000.,6500.,7000.,7500.,8000.)) #", "Look-Up Table as presented in # \"2006 CHF Look-Up Table\",", "of quality divisions # Q is number of pressure divisions", "is_scale=True, display_name='Pressure') ds_q = sdf.Dataset('q', data=q, unit='W/m2', scales=[ds_G,ds_x,ds_P]) # Create", "in xrange(lenG): for j in xrange(lenx): for k in xrange(lenP):", "# Q is number of pressure divisions lenG = len(G)", "Engineering and Design 237, pp. 190-1922. # This file requires", "# Mass Flux range [kg/m^2-s] from 2006 .LUT. G =", "unit='kg/(m2.s)', is_scale=True, display_name='Mass Flux') ds_x = sdf.Dataset('x', data=x, unit='1', is_scale=True,", "# Convert the imported array into a (MxNxQ) where: #", "LUT, convert to [W/m^2] q_raw=np.loadtxt('../Data/2006LUTdata.txt')*1e3 # Convert the imported array", "= np.array((0.10,0.30,0.50,1.0,2.0,3.0,5.0,7.0,10.0,12.0,14.0,16.0,18.0,20.0,21.0))*1e6 # Mass Flux range [kg/m^2-s] from 2006 .LUT.", "xrange(lenx): for k in xrange(lenP): q[i,j,k] = q_raw[i + k*lenG,j]", "file: g = sdf.Group('/', comment='2006 CHF LUT', datasets=[ds_G,ds_x,ds_P,ds_q]) sdf.save('../Data/2006LUT.sdf', g)", "for j in xrange(lenx): for k in xrange(lenP): q[i,j,k] =", "heat flux [kW/m^2] from 2006 LUT, convert to [W/m^2] q_raw=np.loadtxt('../Data/2006LUTdata.txt')*1e3", "the file 2006LUTdata.txt # Pressure range [MPa] from 2006 LUT,", "# Quality range from 2006 LUT x = np.array((-0.50,-0.40,-0.30,-0.20,-0.15,-0.10,-0.05,0.00,0.05,0.10,0.15,0.20,0.25,0.30,0.35,0.40,0.45,0.50,0.60,0.70,0.80,0.90,1.00)) #", "np.array((-0.50,-0.40,-0.30,-0.20,-0.15,-0.10,-0.05,0.00,0.05,0.10,0.15,0.20,0.25,0.30,0.35,0.40,0.45,0.50,0.60,0.70,0.80,0.90,1.00)) # Critical heat flux [kW/m^2] from 2006 LUT, convert", "# N is number of quality divisions # Q is", "2006 .LUT. G = np.array((0.,50.,100.,300.,500.,750.,1000.,1500.,2000.,2500.,3000.,3500.,4000.,4500.,5000.,5500.,6000.,6500.,7000.,7500.,8000.)) # Quality range from 2006", "Mass Flux range [kg/m^2-s] from 2006 .LUT. G = np.array((0.,50.,100.,300.,500.,750.,1000.,1500.,2000.,2500.,3000.,3500.,4000.,4500.,5000.,5500.,6000.,6500.,7000.,7500.,8000.))", "file 2006LUTdata.txt # Pressure range [MPa] from 2006 LUT, convert", "mass flux divisions # N is number of quality divisions", "237, pp. 190-1922. # This file requires the file 2006LUTdata.txt", "[kg/m^2-s] from 2006 .LUT. G = np.array((0.,50.,100.,300.,500.,750.,1000.,1500.,2000.,2500.,3000.,3500.,4000.,4500.,5000.,5500.,6000.,6500.,7000.,7500.,8000.)) # Quality range", "on Tue Apr 03 11:06:37 2018 @author: vmg \"\"\" import", "np # Load 2006 LUT for interpolation # 2006 Groeneveld", "unit='1', is_scale=True, display_name='Quality') ds_P = sdf.Dataset('P', data=P, unit='Pa', is_scale=True, display_name='Pressure')", "-*- \"\"\" Created on Tue Apr 03 11:06:37 2018 @author:", "= np.array((-0.50,-0.40,-0.30,-0.20,-0.15,-0.10,-0.05,0.00,0.05,0.10,0.15,0.20,0.25,0.30,0.35,0.40,0.45,0.50,0.60,0.70,0.80,0.90,1.00)) # Critical heat flux [kW/m^2] from 2006 LUT,", "from 2006 LUT x = np.array((-0.50,-0.40,-0.30,-0.20,-0.15,-0.10,-0.05,0.00,0.05,0.10,0.15,0.20,0.25,0.30,0.35,0.40,0.45,0.50,0.60,0.70,0.80,0.90,1.00)) # Critical heat flux", "ds_x = sdf.Dataset('x', data=x, unit='1', is_scale=True, display_name='Quality') ds_P = sdf.Dataset('P',", "of mass flux divisions # N is number of quality", "Quality range from 2006 LUT x = np.array((-0.50,-0.40,-0.30,-0.20,-0.15,-0.10,-0.05,0.00,0.05,0.10,0.15,0.20,0.25,0.30,0.35,0.40,0.45,0.50,0.60,0.70,0.80,0.90,1.00)) # Critical", "q[i,j,k] = q_raw[i + k*lenG,j] # Create the datasets: ds_G", "Tue Apr 03 11:06:37 2018 @author: vmg \"\"\" import sdf", "P = np.array((0.10,0.30,0.50,1.0,2.0,3.0,5.0,7.0,10.0,12.0,14.0,16.0,18.0,20.0,21.0))*1e6 # Mass Flux range [kg/m^2-s] from 2006", "= np.array((0.,50.,100.,300.,500.,750.,1000.,1500.,2000.,2500.,3000.,3500.,4000.,4500.,5000.,5500.,6000.,6500.,7000.,7500.,8000.)) # Quality range from 2006 LUT x =", "@author: vmg \"\"\" import sdf import numpy as np #", "sdf import numpy as np # Load 2006 LUT for", "2006 LUT for interpolation # 2006 Groeneveld Look-Up Table as", "2006 LUT, convert to [Pa] P = np.array((0.10,0.30,0.50,1.0,2.0,3.0,5.0,7.0,10.0,12.0,14.0,16.0,18.0,20.0,21.0))*1e6 # Mass", "LUT, convert to [Pa] P = np.array((0.10,0.30,0.50,1.0,2.0,3.0,5.0,7.0,10.0,12.0,14.0,16.0,18.0,20.0,21.0))*1e6 # Mass Flux", "Critical heat flux [kW/m^2] from 2006 LUT, convert to [W/m^2]", "in xrange(lenx): for k in xrange(lenP): q[i,j,k] = q_raw[i +", "= sdf.Dataset('x', data=x, unit='1', is_scale=True, display_name='Quality') ds_P = sdf.Dataset('P', data=P,", "scales=[ds_G,ds_x,ds_P]) # Create the root group and write the file:", "k*lenG,j] # Create the datasets: ds_G = sdf.Dataset('G', data=G, unit='kg/(m2.s)',", "Pressure range [MPa] from 2006 LUT, convert to [Pa] P", "k in xrange(lenP): q[i,j,k] = q_raw[i + k*lenG,j] # Create", "interpolation # 2006 Groeneveld Look-Up Table as presented in #", "convert to [W/m^2] q_raw=np.loadtxt('../Data/2006LUTdata.txt')*1e3 # Convert the imported array into", "LUT x = np.array((-0.50,-0.40,-0.30,-0.20,-0.15,-0.10,-0.05,0.00,0.05,0.10,0.15,0.20,0.25,0.30,0.35,0.40,0.45,0.50,0.60,0.70,0.80,0.90,1.00)) # Critical heat flux [kW/m^2] from", "where: # M is number of mass flux divisions #", "len(G) lenx = len(x) lenP = len(P) q = np.zeros((lenG,lenx,lenP))", "into a (MxNxQ) where: # M is number of mass", "lenP = len(P) q = np.zeros((lenG,lenx,lenP)) for i in xrange(lenG):", "xrange(lenG): for j in xrange(lenx): for k in xrange(lenP): q[i,j,k]", "data=G, unit='kg/(m2.s)', is_scale=True, display_name='Mass Flux') ds_x = sdf.Dataset('x', data=x, unit='1',", "is_scale=True, display_name='Mass Flux') ds_x = sdf.Dataset('x', data=x, unit='1', is_scale=True, display_name='Quality')", "len(P) q = np.zeros((lenG,lenx,lenP)) for i in xrange(lenG): for j", "import numpy as np # Load 2006 LUT for interpolation", "= q_raw[i + k*lenG,j] # Create the datasets: ds_G =", "convert to [Pa] P = np.array((0.10,0.30,0.50,1.0,2.0,3.0,5.0,7.0,10.0,12.0,14.0,16.0,18.0,20.0,21.0))*1e6 # Mass Flux range", "for k in xrange(lenP): q[i,j,k] = q_raw[i + k*lenG,j] #", "Design 237, pp. 190-1922. # This file requires the file", "of pressure divisions lenG = len(G) lenx = len(x) lenP", "vmg \"\"\" import sdf import numpy as np # Load", "Groeneveld Look-Up Table as presented in # \"2006 CHF Look-Up", "2018 @author: vmg \"\"\" import sdf import numpy as np", "range from 2006 LUT x = np.array((-0.50,-0.40,-0.30,-0.20,-0.15,-0.10,-0.05,0.00,0.05,0.10,0.15,0.20,0.25,0.30,0.35,0.40,0.45,0.50,0.60,0.70,0.80,0.90,1.00)) # Critical heat", "j in xrange(lenx): for k in xrange(lenP): q[i,j,k] = q_raw[i", "# This file requires the file 2006LUTdata.txt # Pressure range", "is number of mass flux divisions # N is number", "as np # Load 2006 LUT for interpolation # 2006", "is_scale=True, display_name='Quality') ds_P = sdf.Dataset('P', data=P, unit='Pa', is_scale=True, display_name='Pressure') ds_q", "unit='Pa', is_scale=True, display_name='Pressure') ds_q = sdf.Dataset('q', data=q, unit='W/m2', scales=[ds_G,ds_x,ds_P]) #", "Look-Up Table\", Nuclear Engineering and Design 237, pp. 190-1922. #", "lenG = len(G) lenx = len(x) lenP = len(P) q", "# \"2006 CHF Look-Up Table\", Nuclear Engineering and Design 237,", "root group and write the file: g = sdf.Group('/', comment='2006", "in # \"2006 CHF Look-Up Table\", Nuclear Engineering and Design", "range [kg/m^2-s] from 2006 .LUT. G = np.array((0.,50.,100.,300.,500.,750.,1000.,1500.,2000.,2500.,3000.,3500.,4000.,4500.,5000.,5500.,6000.,6500.,7000.,7500.,8000.)) # Quality", "from 2006 LUT, convert to [W/m^2] q_raw=np.loadtxt('../Data/2006LUTdata.txt')*1e3 # Convert the", "imported array into a (MxNxQ) where: # M is number", "Q is number of pressure divisions lenG = len(G) lenx", "np.zeros((lenG,lenx,lenP)) for i in xrange(lenG): for j in xrange(lenx): for", "sdf.Dataset('P', data=P, unit='Pa', is_scale=True, display_name='Pressure') ds_q = sdf.Dataset('q', data=q, unit='W/m2',", "# -*- coding: utf-8 -*- \"\"\" Created on Tue Apr", "# Create the datasets: ds_G = sdf.Dataset('G', data=G, unit='kg/(m2.s)', is_scale=True,", "divisions lenG = len(G) lenx = len(x) lenP = len(P)", "11:06:37 2018 @author: vmg \"\"\" import sdf import numpy as", "= sdf.Dataset('q', data=q, unit='W/m2', scales=[ds_G,ds_x,ds_P]) # Create the root group", "to [Pa] P = np.array((0.10,0.30,0.50,1.0,2.0,3.0,5.0,7.0,10.0,12.0,14.0,16.0,18.0,20.0,21.0))*1e6 # Mass Flux range [kg/m^2-s]", "for interpolation # 2006 Groeneveld Look-Up Table as presented in", "flux [kW/m^2] from 2006 LUT, convert to [W/m^2] q_raw=np.loadtxt('../Data/2006LUTdata.txt')*1e3 #", "the imported array into a (MxNxQ) where: # M is", "lenx = len(x) lenP = len(P) q = np.zeros((lenG,lenx,lenP)) for", "2006 Groeneveld Look-Up Table as presented in # \"2006 CHF", "import sdf import numpy as np # Load 2006 LUT", "q_raw=np.loadtxt('../Data/2006LUTdata.txt')*1e3 # Convert the imported array into a (MxNxQ) where:", "data=x, unit='1', is_scale=True, display_name='Quality') ds_P = sdf.Dataset('P', data=P, unit='Pa', is_scale=True,", "N is number of quality divisions # Q is number", "array into a (MxNxQ) where: # M is number of", "-*- coding: utf-8 -*- \"\"\" Created on Tue Apr 03", "# Critical heat flux [kW/m^2] from 2006 LUT, convert to", "Convert the imported array into a (MxNxQ) where: # M", "requires the file 2006LUTdata.txt # Pressure range [MPa] from 2006", "\"2006 CHF Look-Up Table\", Nuclear Engineering and Design 237, pp.", "group and write the file: g = sdf.Group('/', comment='2006 CHF", "the root group and write the file: g = sdf.Group('/',", "2006LUTdata.txt # Pressure range [MPa] from 2006 LUT, convert to", "the datasets: ds_G = sdf.Dataset('G', data=G, unit='kg/(m2.s)', is_scale=True, display_name='Mass Flux')", "range [MPa] from 2006 LUT, convert to [Pa] P =", "quality divisions # Q is number of pressure divisions lenG", "(MxNxQ) where: # M is number of mass flux divisions", "pp. 190-1922. # This file requires the file 2006LUTdata.txt #", ".LUT. G = np.array((0.,50.,100.,300.,500.,750.,1000.,1500.,2000.,2500.,3000.,3500.,4000.,4500.,5000.,5500.,6000.,6500.,7000.,7500.,8000.)) # Quality range from 2006 LUT", "as presented in # \"2006 CHF Look-Up Table\", Nuclear Engineering", "# 2006 Groeneveld Look-Up Table as presented in # \"2006", "len(x) lenP = len(P) q = np.zeros((lenG,lenx,lenP)) for i in", "for i in xrange(lenG): for j in xrange(lenx): for k", "display_name='Pressure') ds_q = sdf.Dataset('q', data=q, unit='W/m2', scales=[ds_G,ds_x,ds_P]) # Create the", "# M is number of mass flux divisions # N", "unit='W/m2', scales=[ds_G,ds_x,ds_P]) # Create the root group and write the", "= sdf.Dataset('G', data=G, unit='kg/(m2.s)', is_scale=True, display_name='Mass Flux') ds_x = sdf.Dataset('x',", "data=q, unit='W/m2', scales=[ds_G,ds_x,ds_P]) # Create the root group and write", "G = np.array((0.,50.,100.,300.,500.,750.,1000.,1500.,2000.,2500.,3000.,3500.,4000.,4500.,5000.,5500.,6000.,6500.,7000.,7500.,8000.)) # Quality range from 2006 LUT x", "2006 LUT, convert to [W/m^2] q_raw=np.loadtxt('../Data/2006LUTdata.txt')*1e3 # Convert the imported", "presented in # \"2006 CHF Look-Up Table\", Nuclear Engineering and", "[Pa] P = np.array((0.10,0.30,0.50,1.0,2.0,3.0,5.0,7.0,10.0,12.0,14.0,16.0,18.0,20.0,21.0))*1e6 # Mass Flux range [kg/m^2-s] from", "and write the file: g = sdf.Group('/', comment='2006 CHF LUT',", "number of mass flux divisions # N is number of", "file requires the file 2006LUTdata.txt # Pressure range [MPa] from", "np.array((0.10,0.30,0.50,1.0,2.0,3.0,5.0,7.0,10.0,12.0,14.0,16.0,18.0,20.0,21.0))*1e6 # Mass Flux range [kg/m^2-s] from 2006 .LUT. G", "coding: utf-8 -*- \"\"\" Created on Tue Apr 03 11:06:37", "display_name='Quality') ds_P = sdf.Dataset('P', data=P, unit='Pa', is_scale=True, display_name='Pressure') ds_q =", "Table as presented in # \"2006 CHF Look-Up Table\", Nuclear", "Load 2006 LUT for interpolation # 2006 Groeneveld Look-Up Table", "from 2006 .LUT. G = np.array((0.,50.,100.,300.,500.,750.,1000.,1500.,2000.,2500.,3000.,3500.,4000.,4500.,5000.,5500.,6000.,6500.,7000.,7500.,8000.)) # Quality range from", "number of pressure divisions lenG = len(G) lenx = len(x)", "numpy as np # Load 2006 LUT for interpolation #", "Flux') ds_x = sdf.Dataset('x', data=x, unit='1', is_scale=True, display_name='Quality') ds_P =", "the file: g = sdf.Group('/', comment='2006 CHF LUT', datasets=[ds_G,ds_x,ds_P,ds_q]) sdf.save('../Data/2006LUT.sdf',", "ds_G = sdf.Dataset('G', data=G, unit='kg/(m2.s)', is_scale=True, display_name='Mass Flux') ds_x =", "display_name='Mass Flux') ds_x = sdf.Dataset('x', data=x, unit='1', is_scale=True, display_name='Quality') ds_P", "= len(P) q = np.zeros((lenG,lenx,lenP)) for i in xrange(lenG): for", "= np.zeros((lenG,lenx,lenP)) for i in xrange(lenG): for j in xrange(lenx):", "and Design 237, pp. 190-1922. # This file requires the", "sdf.Dataset('q', data=q, unit='W/m2', scales=[ds_G,ds_x,ds_P]) # Create the root group and", "M is number of mass flux divisions # N is" ]
[ "linter.lint_file(path) pprint(violations) assert len(violations) == len(expected_violations) for violation, expected_violation in", "len(expected_violations) for violation, expected_violation in zip_longest(violations, expected_violations): self.assertViolation(violation, expected_violation) def", "options['enabled'] = False for policy in policy_names_to_enable: options = policy_options.setdefault(policy,", "None: config.get_config_dict()['policies'][policy_name].update(policy_options) linter = Linter(policy_set, config.get_config_dict()) violations = linter.lint_file(path) pprint(violations)", "# Ignore a comment config source pass def get_config_dict(self): return", "== len(expected_violations) for violation, expected_violation in zip_longest(violations, expected_violations): self.assertViolation(violation, expected_violation)", "policy_options.setdefault(policy, {}) options['enabled'] = True self._config_dict = { 'policies': policy_options,", "policy_options is not None: config.get_config_dict()['policies'][policy_name].update(policy_options) linter = Linter(policy_set, config.get_config_dict()) violations", "PolicyAssertion(unittest.TestCase): class StubPolicySet(object): def __init__(self, *policies): self._policies = policies def", "= policy_options.setdefault(policy, {}) options['enabled'] = True self._config_dict = { 'policies':", "expected_violation['position'] assert actual_violation['level'] == expected_violation['level'] self.assertIsInstance(actual_violation['description'], str) def get_fixture_path(*filename): return", "if policy_options is not None: config.get_config_dict()['policies'][policy_name].update(policy_options) linter = Linter(policy_set, config.get_config_dict())", "vint.linting.config.config_default_source import ConfigDefaultSource class PolicyAssertion(unittest.TestCase): class StubPolicySet(object): def __init__(self, *policies):", "def update_by_config(self, policy_enabling_map): pass class StubConfigContainer(object): def __init__(self, policy_names_to_enable): default_config_dict", "self._config_dict = { 'policies': policy_options, } def append_config_source(self, config_source): #", "actual_violation['level'] == expected_violation['level'] self.assertIsInstance(actual_violation['description'], str) def get_fixture_path(*filename): return Path('test', 'fixture',", "in policy_names_to_enable: options = policy_options.setdefault(policy, {}) options['enabled'] = True self._config_dict", "zip_longest(violations, expected_violations): self.assertViolation(violation, expected_violation) def assertViolation(self, actual_violation, expected_violation): self.assertIsNot(actual_violation, None)", "pass def get_config_dict(self): return self._config_dict def assertFoundNoViolations(self, path, Policy, policy_options=None):", "self._policies = policies def get_enabled_policies(self): return self._policies def update_by_config(self, policy_enabling_map):", "linter = Linter(policy_set, config.get_config_dict()) violations = linter.lint_file(path) pprint(violations) assert len(violations)", "policy, options in policy_options.items(): options['enabled'] = False for policy in", "*policies): self._policies = policies def get_enabled_policies(self): return self._policies def update_by_config(self,", "def assertViolation(self, actual_violation, expected_violation): self.assertIsNot(actual_violation, None) self.assertIsNot(expected_violation, None) pprint(actual_violation) assert", "for violation, expected_violation in zip_longest(violations, expected_violations): self.assertViolation(violation, expected_violation) def assertViolation(self,", "Policy, [], policy_options) def assertFoundViolationsEqual(self, path, Policy, expected_violations, policy_options=None): policy_to_test", "expected_violation['name'] assert actual_violation['position'] == expected_violation['position'] assert actual_violation['level'] == expected_violation['level'] self.assertIsInstance(actual_violation['description'],", "policy_options = default_config_dict.get('policies', {}) for policy, options in policy_options.items(): options['enabled']", "True self._config_dict = { 'policies': policy_options, } def append_config_source(self, config_source):", "get_config_dict(self): return self._config_dict def assertFoundNoViolations(self, path, Policy, policy_options=None): self.assertFoundViolationsEqual(path, Policy,", "ConfigDefaultSource class PolicyAssertion(unittest.TestCase): class StubPolicySet(object): def __init__(self, *policies): self._policies =", "update_by_config(self, policy_enabling_map): pass class StubConfigContainer(object): def __init__(self, policy_names_to_enable): default_config_dict =", "policy_options=None): self.assertFoundViolationsEqual(path, Policy, [], policy_options) def assertFoundViolationsEqual(self, path, Policy, expected_violations,", "expected_violations): self.assertViolation(violation, expected_violation) def assertViolation(self, actual_violation, expected_violation): self.assertIsNot(actual_violation, None) self.assertIsNot(expected_violation,", "StubPolicySet(object): def __init__(self, *policies): self._policies = policies def get_enabled_policies(self): return", "policy_options.items(): options['enabled'] = False for policy in policy_names_to_enable: options =", "config source pass def get_config_dict(self): return self._config_dict def assertFoundNoViolations(self, path,", "None) self.assertIsNot(expected_violation, None) pprint(actual_violation) assert actual_violation['name'] == expected_violation['name'] assert actual_violation['position']", "options['enabled'] = True self._config_dict = { 'policies': policy_options, } def", "vint.compat.itertools import zip_longest from vint.linting.linter import Linter from vint.linting.config.config_default_source import", "assertViolation(self, actual_violation, expected_violation): self.assertIsNot(actual_violation, None) self.assertIsNot(expected_violation, None) pprint(actual_violation) assert actual_violation['name']", "policy_options) def assertFoundViolationsEqual(self, path, Policy, expected_violations, policy_options=None): policy_to_test = Policy()", "policy_name = Policy.__name__ policy_set = PolicyAssertion.StubPolicySet(policy_to_test) config = PolicyAssertion.StubConfigContainer(policy_name) if", "not None: config.get_config_dict()['policies'][policy_name].update(policy_options) linter = Linter(policy_set, config.get_config_dict()) violations = linter.lint_file(path)", "from pathlib import Path from pprint import pprint from vint.compat.itertools", "get_enabled_policies(self): return self._policies def update_by_config(self, policy_enabling_map): pass class StubConfigContainer(object): def", "self.assertViolation(violation, expected_violation) def assertViolation(self, actual_violation, expected_violation): self.assertIsNot(actual_violation, None) self.assertIsNot(expected_violation, None)", "expected_violation): self.assertIsNot(actual_violation, None) self.assertIsNot(expected_violation, None) pprint(actual_violation) assert actual_violation['name'] == expected_violation['name']", "PolicyAssertion.StubConfigContainer(policy_name) if policy_options is not None: config.get_config_dict()['policies'][policy_name].update(policy_options) linter = Linter(policy_set,", "from vint.linting.config.config_default_source import ConfigDefaultSource class PolicyAssertion(unittest.TestCase): class StubPolicySet(object): def __init__(self,", "source pass def get_config_dict(self): return self._config_dict def assertFoundNoViolations(self, path, Policy,", "Policy() policy_name = Policy.__name__ policy_set = PolicyAssertion.StubPolicySet(policy_to_test) config = PolicyAssertion.StubConfigContainer(policy_name)", "def get_config_dict(self): return self._config_dict def assertFoundNoViolations(self, path, Policy, policy_options=None): self.assertFoundViolationsEqual(path,", "policy_enabling_map): pass class StubConfigContainer(object): def __init__(self, policy_names_to_enable): default_config_dict = ConfigDefaultSource(None).get_config_dict()", "self._config_dict def assertFoundNoViolations(self, path, Policy, policy_options=None): self.assertFoundViolationsEqual(path, Policy, [], policy_options)", "import zip_longest from vint.linting.linter import Linter from vint.linting.config.config_default_source import ConfigDefaultSource", "import Linter from vint.linting.config.config_default_source import ConfigDefaultSource class PolicyAssertion(unittest.TestCase): class StubPolicySet(object):", "False for policy in policy_names_to_enable: options = policy_options.setdefault(policy, {}) options['enabled']", "self.assertIsNot(actual_violation, None) self.assertIsNot(expected_violation, None) pprint(actual_violation) assert actual_violation['name'] == expected_violation['name'] assert", "for policy, options in policy_options.items(): options['enabled'] = False for policy", "expected_violation in zip_longest(violations, expected_violations): self.assertViolation(violation, expected_violation) def assertViolation(self, actual_violation, expected_violation):", "config = PolicyAssertion.StubConfigContainer(policy_name) if policy_options is not None: config.get_config_dict()['policies'][policy_name].update(policy_options) linter", "[], policy_options) def assertFoundViolationsEqual(self, path, Policy, expected_violations, policy_options=None): policy_to_test =", "config.get_config_dict()['policies'][policy_name].update(policy_options) linter = Linter(policy_set, config.get_config_dict()) violations = linter.lint_file(path) pprint(violations) assert", "self.assertFoundViolationsEqual(path, Policy, [], policy_options) def assertFoundViolationsEqual(self, path, Policy, expected_violations, policy_options=None):", "actual_violation, expected_violation): self.assertIsNot(actual_violation, None) self.assertIsNot(expected_violation, None) pprint(actual_violation) assert actual_violation['name'] ==", "= policies def get_enabled_policies(self): return self._policies def update_by_config(self, policy_enabling_map): pass", "from vint.compat.itertools import zip_longest from vint.linting.linter import Linter from vint.linting.config.config_default_source", "= PolicyAssertion.StubConfigContainer(policy_name) if policy_options is not None: config.get_config_dict()['policies'][policy_name].update(policy_options) linter =", "= False for policy in policy_names_to_enable: options = policy_options.setdefault(policy, {})", "policy_to_test = Policy() policy_name = Policy.__name__ policy_set = PolicyAssertion.StubPolicySet(policy_to_test) config", "assert actual_violation['level'] == expected_violation['level'] self.assertIsInstance(actual_violation['description'], str) def get_fixture_path(*filename): return Path('test',", "append_config_source(self, config_source): # Ignore a comment config source pass def", "actual_violation['name'] == expected_violation['name'] assert actual_violation['position'] == expected_violation['position'] assert actual_violation['level'] ==", "class StubPolicySet(object): def __init__(self, *policies): self._policies = policies def get_enabled_policies(self):", "policy in policy_names_to_enable: options = policy_options.setdefault(policy, {}) options['enabled'] = True", "comment config source pass def get_config_dict(self): return self._config_dict def assertFoundNoViolations(self,", "Ignore a comment config source pass def get_config_dict(self): return self._config_dict", "pprint from vint.compat.itertools import zip_longest from vint.linting.linter import Linter from", "len(violations) == len(expected_violations) for violation, expected_violation in zip_longest(violations, expected_violations): self.assertViolation(violation,", "{ 'policies': policy_options, } def append_config_source(self, config_source): # Ignore a", "Policy, expected_violations, policy_options=None): policy_to_test = Policy() policy_name = Policy.__name__ policy_set", "import ConfigDefaultSource class PolicyAssertion(unittest.TestCase): class StubPolicySet(object): def __init__(self, *policies): self._policies", "None) pprint(actual_violation) assert actual_violation['name'] == expected_violation['name'] assert actual_violation['position'] == expected_violation['position']", "pass class StubConfigContainer(object): def __init__(self, policy_names_to_enable): default_config_dict = ConfigDefaultSource(None).get_config_dict() policy_options", "= Linter(policy_set, config.get_config_dict()) violations = linter.lint_file(path) pprint(violations) assert len(violations) ==", "policy_set = PolicyAssertion.StubPolicySet(policy_to_test) config = PolicyAssertion.StubConfigContainer(policy_name) if policy_options is not", "Policy.__name__ policy_set = PolicyAssertion.StubPolicySet(policy_to_test) config = PolicyAssertion.StubConfigContainer(policy_name) if policy_options is", "in zip_longest(violations, expected_violations): self.assertViolation(violation, expected_violation) def assertViolation(self, actual_violation, expected_violation): self.assertIsNot(actual_violation,", "class PolicyAssertion(unittest.TestCase): class StubPolicySet(object): def __init__(self, *policies): self._policies = policies", "path, Policy, expected_violations, policy_options=None): policy_to_test = Policy() policy_name = Policy.__name__", "config_source): # Ignore a comment config source pass def get_config_dict(self):", "def __init__(self, policy_names_to_enable): default_config_dict = ConfigDefaultSource(None).get_config_dict() policy_options = default_config_dict.get('policies', {})", "expected_violations, policy_options=None): policy_to_test = Policy() policy_name = Policy.__name__ policy_set =", "def assertFoundNoViolations(self, path, Policy, policy_options=None): self.assertFoundViolationsEqual(path, Policy, [], policy_options) def", "Linter(policy_set, config.get_config_dict()) violations = linter.lint_file(path) pprint(violations) assert len(violations) == len(expected_violations)", "def append_config_source(self, config_source): # Ignore a comment config source pass", "= Policy.__name__ policy_set = PolicyAssertion.StubPolicySet(policy_to_test) config = PolicyAssertion.StubConfigContainer(policy_name) if policy_options", "return self._policies def update_by_config(self, policy_enabling_map): pass class StubConfigContainer(object): def __init__(self,", "pprint import pprint from vint.compat.itertools import zip_longest from vint.linting.linter import", "config.get_config_dict()) violations = linter.lint_file(path) pprint(violations) assert len(violations) == len(expected_violations) for", "for policy in policy_names_to_enable: options = policy_options.setdefault(policy, {}) options['enabled'] =", "default_config_dict.get('policies', {}) for policy, options in policy_options.items(): options['enabled'] = False", "a comment config source pass def get_config_dict(self): return self._config_dict def", "policy_names_to_enable): default_config_dict = ConfigDefaultSource(None).get_config_dict() policy_options = default_config_dict.get('policies', {}) for policy,", "assert len(violations) == len(expected_violations) for violation, expected_violation in zip_longest(violations, expected_violations):", "__init__(self, policy_names_to_enable): default_config_dict = ConfigDefaultSource(None).get_config_dict() policy_options = default_config_dict.get('policies', {}) for", "policy_names_to_enable: options = policy_options.setdefault(policy, {}) options['enabled'] = True self._config_dict =", "} def append_config_source(self, config_source): # Ignore a comment config source", "{}) for policy, options in policy_options.items(): options['enabled'] = False for", "class StubConfigContainer(object): def __init__(self, policy_names_to_enable): default_config_dict = ConfigDefaultSource(None).get_config_dict() policy_options =", "is not None: config.get_config_dict()['policies'][policy_name].update(policy_options) linter = Linter(policy_set, config.get_config_dict()) violations =", "StubConfigContainer(object): def __init__(self, policy_names_to_enable): default_config_dict = ConfigDefaultSource(None).get_config_dict() policy_options = default_config_dict.get('policies',", "Path from pprint import pprint from vint.compat.itertools import zip_longest from", "assertFoundViolationsEqual(self, path, Policy, expected_violations, policy_options=None): policy_to_test = Policy() policy_name =", "assertFoundNoViolations(self, path, Policy, policy_options=None): self.assertFoundViolationsEqual(path, Policy, [], policy_options) def assertFoundViolationsEqual(self,", "default_config_dict = ConfigDefaultSource(None).get_config_dict() policy_options = default_config_dict.get('policies', {}) for policy, options", "options in policy_options.items(): options['enabled'] = False for policy in policy_names_to_enable:", "= default_config_dict.get('policies', {}) for policy, options in policy_options.items(): options['enabled'] =", "== expected_violation['name'] assert actual_violation['position'] == expected_violation['position'] assert actual_violation['level'] == expected_violation['level']", "pathlib import Path from pprint import pprint from vint.compat.itertools import", "{}) options['enabled'] = True self._config_dict = { 'policies': policy_options, }", "= { 'policies': policy_options, } def append_config_source(self, config_source): # Ignore", "Policy, policy_options=None): self.assertFoundViolationsEqual(path, Policy, [], policy_options) def assertFoundViolationsEqual(self, path, Policy,", "import Path from pprint import pprint from vint.compat.itertools import zip_longest", "policy_options=None): policy_to_test = Policy() policy_name = Policy.__name__ policy_set = PolicyAssertion.StubPolicySet(policy_to_test)", "self.assertIsNot(expected_violation, None) pprint(actual_violation) assert actual_violation['name'] == expected_violation['name'] assert actual_violation['position'] ==", "import pprint from vint.compat.itertools import zip_longest from vint.linting.linter import Linter", "__init__(self, *policies): self._policies = policies def get_enabled_policies(self): return self._policies def", "'policies': policy_options, } def append_config_source(self, config_source): # Ignore a comment", "policy_options, } def append_config_source(self, config_source): # Ignore a comment config", "== expected_violation['position'] assert actual_violation['level'] == expected_violation['level'] self.assertIsInstance(actual_violation['description'], str) def get_fixture_path(*filename):", "path, Policy, policy_options=None): self.assertFoundViolationsEqual(path, Policy, [], policy_options) def assertFoundViolationsEqual(self, path,", "import unittest from pathlib import Path from pprint import pprint", "from pprint import pprint from vint.compat.itertools import zip_longest from vint.linting.linter", "def get_enabled_policies(self): return self._policies def update_by_config(self, policy_enabling_map): pass class StubConfigContainer(object):", "pprint(actual_violation) assert actual_violation['name'] == expected_violation['name'] assert actual_violation['position'] == expected_violation['position'] assert", "unittest from pathlib import Path from pprint import pprint from", "def assertFoundViolationsEqual(self, path, Policy, expected_violations, policy_options=None): policy_to_test = Policy() policy_name", "expected_violation['level'] self.assertIsInstance(actual_violation['description'], str) def get_fixture_path(*filename): return Path('test', 'fixture', 'policy', *filename)", "pprint(violations) assert len(violations) == len(expected_violations) for violation, expected_violation in zip_longest(violations,", "= True self._config_dict = { 'policies': policy_options, } def append_config_source(self,", "def __init__(self, *policies): self._policies = policies def get_enabled_policies(self): return self._policies", "options = policy_options.setdefault(policy, {}) options['enabled'] = True self._config_dict = {", "assert actual_violation['position'] == expected_violation['position'] assert actual_violation['level'] == expected_violation['level'] self.assertIsInstance(actual_violation['description'], str)", "ConfigDefaultSource(None).get_config_dict() policy_options = default_config_dict.get('policies', {}) for policy, options in policy_options.items():", "violations = linter.lint_file(path) pprint(violations) assert len(violations) == len(expected_violations) for violation,", "violation, expected_violation in zip_longest(violations, expected_violations): self.assertViolation(violation, expected_violation) def assertViolation(self, actual_violation,", "= PolicyAssertion.StubPolicySet(policy_to_test) config = PolicyAssertion.StubConfigContainer(policy_name) if policy_options is not None:", "policies def get_enabled_policies(self): return self._policies def update_by_config(self, policy_enabling_map): pass class", "Linter from vint.linting.config.config_default_source import ConfigDefaultSource class PolicyAssertion(unittest.TestCase): class StubPolicySet(object): def", "return self._config_dict def assertFoundNoViolations(self, path, Policy, policy_options=None): self.assertFoundViolationsEqual(path, Policy, [],", "assert actual_violation['name'] == expected_violation['name'] assert actual_violation['position'] == expected_violation['position'] assert actual_violation['level']", "actual_violation['position'] == expected_violation['position'] assert actual_violation['level'] == expected_violation['level'] self.assertIsInstance(actual_violation['description'], str) def", "== expected_violation['level'] self.assertIsInstance(actual_violation['description'], str) def get_fixture_path(*filename): return Path('test', 'fixture', 'policy',", "= linter.lint_file(path) pprint(violations) assert len(violations) == len(expected_violations) for violation, expected_violation", "zip_longest from vint.linting.linter import Linter from vint.linting.config.config_default_source import ConfigDefaultSource class", "= ConfigDefaultSource(None).get_config_dict() policy_options = default_config_dict.get('policies', {}) for policy, options in", "PolicyAssertion.StubPolicySet(policy_to_test) config = PolicyAssertion.StubConfigContainer(policy_name) if policy_options is not None: config.get_config_dict()['policies'][policy_name].update(policy_options)", "vint.linting.linter import Linter from vint.linting.config.config_default_source import ConfigDefaultSource class PolicyAssertion(unittest.TestCase): class", "from vint.linting.linter import Linter from vint.linting.config.config_default_source import ConfigDefaultSource class PolicyAssertion(unittest.TestCase):", "expected_violation) def assertViolation(self, actual_violation, expected_violation): self.assertIsNot(actual_violation, None) self.assertIsNot(expected_violation, None) pprint(actual_violation)", "self._policies def update_by_config(self, policy_enabling_map): pass class StubConfigContainer(object): def __init__(self, policy_names_to_enable):", "in policy_options.items(): options['enabled'] = False for policy in policy_names_to_enable: options", "= Policy() policy_name = Policy.__name__ policy_set = PolicyAssertion.StubPolicySet(policy_to_test) config =" ]
[ "[] for x_val, y_val in val_data: y_val_pred.append(self._model.predict( x_val, batch_size=batch_size_test, verbose=verbose_keras)[1])", "the metric.\"\"\" config = { \"num_classes\": self.num_classes, \"average\": self.average, \"beta\":", "self._model: return False default_ind = self.label_mapping[self._parameters['default_label']] return self.num_labels != self._model_num_labels", "file for TensorFlow argmax_layer = tf.keras.backend.argmax(final_softmax_layer) # Create confidence layers", "= tf.reduce_mean(f1_score) return f1_score def get_config(self): \"\"\"Returns the serializable config", "pass. :type threshold: float :param default_ind: default index :type default_ind:", "2.0 (the \"License\"); # you may not use this file", "metric_label in enumerate(self._model.metrics_names): history[metric_label] = model_results[i] if val_data: f1, f1_report", "sys.stdout.flush() if verbose_log: sys.stdout.write(\"\\rEPOCH %g, validation_batch_id %d\" % (self._epoch_id, batch_id))", "import tensorflow as tf from sklearn import decomposition from ..", "of {} must exist in the \" \"label mapping.\".format( self._parameters['default_label']))", "1 for i, metric_label in enumerate(self._model.metrics_names): history[metric_label] = model_results[i] if", "num_samples_in_batch] = model_output[0].numpy() predictions[allocation_index:allocation_index + num_samples_in_batch] = model_output[1].numpy() sentence_lengths[allocation_index:allocation_index +", "_validate_parameters(self, parameters): \"\"\" Validate the parameters sent in. Raise error", "= model_output[1].numpy() sentence_lengths[allocation_index:allocation_index + num_samples_in_batch] = list(map(lambda x: len(x[0]), batch_data))", "y_val_pred.append(self._model.predict( x_val, batch_size=batch_size_test, verbose=verbose_keras)[1]) y_val_test.append(np.argmax(y_val, axis=-1)) batch_id += 1 sys.stdout.flush()", "not callable(tf_model): loaded_model._construct_model() tf1_weights = [] for var in tf_model.variables:", "Character encoding for the list of sentences :param input_str_tensor: input", "the previous spot final_softmax_layer = tf.keras.layers.Dense( num_labels, activation='softmax', name=\"dense_2\")( self._model.layers[-4].output)", "for zero y_pred = tf.logical_and(y_pred >= threshold, tf.abs(y_pred) > 1e-12)", "1]`. Works for both multi-class and multi-label classification. $$ F_{\\beta}", "(1 + \\beta^2) * \\frac{\\textrm{precision} * \\textrm{precision}}{(\\beta^2 \\cdot \\textrm{precision}) +", "num_labels self._model_default_ind = default_ind def fit(self, train_data, val_data=None, batch_size=32, label_mapping=None,", "background label bg_label_tf = tf.keras.backend.constant( default_ind, dtype=argmax_layer.dtype) # Generate the", "max_char_encoding_id + 2, self._parameters['dim_embed'], weights=[embedding_matrix], input_length=input_shape[0], trainable=True)) # Add the", "= np.zeros((batch_size,), dtype=int) predictions = np.zeros((batch_size, self._parameters['max_length'])) if show_confidences: confidences", "return prediction & confidence matrices for index, sentence_length \\ in", "- \" \"f1_score %f\" % (self._epoch_id, batch_id, *model_results[1:])) batch_id +=", "elif param == 'default_label': if not isinstance(parameters[param], str): error =", ") if not isinstance(beta, float): raise TypeError(\"The value of beta", "which has resources.\"\"\" def filter(self, record): msg = 'is a", "name=\"f1_score\", dtype=None): super().__init__(num_classes, average, 1.0, threshold, name=name, dtype=dtype) def get_config(self):", "only check important variables, i.e. may not check model itself.", "predicting.\") elif self._need_to_reconstruct_model(): raise RuntimeError(\"The model label mapping definitions have", "or not the model needs to be reconstructed. :return: bool", "load label_mapping labels_dirpath = os.path.join(dirpath, \"label_mapping.json\") with open(labels_dirpath, 'r') as", "if show_confidences: confidences = np.zeros((batch_size, self._parameters['max_length'], self.num_labels)) # Run model", "the weight matrix: let pad and space be 0s for", "model_param_dirpath = os.path.join(dirpath, \"model_parameters.json\") with open(model_param_dirpath, 'r') as fp: parameters", "self.num_classes = num_classes self.average = average self.beta = beta self.threshold", "} base_config = super().get_config() return {**base_config, **config} def reset_states(self): reset_value", "invalid parameters are present. :param parameters: parameter dict containing the", "val_data: Validation data used to validate the training :type val_data:", "history['f1_report'] = f1_report val_f1 = f1_report['weighted avg']['f1-score'] \\ if f1_report", "{ \"num_classes\": self.num_classes, \"average\": self.average, \"beta\": self.beta, \"threshold\": self.threshold, }", "argmax_layer, confidence_layer): threshold_at_argmax = tf.gather(self.thresh_vec, argmax_layer) confidence_max_layer = tf.keras.backend.max(confidence_layer, axis=2)", "if verbose: sys.stdout.write( \"\\rEPOCH %d, batch_id %d: loss: %f -", "in embds: line = line.strip().split() embd_table[line[0]] = np.asarray(line[1:]) return embd_table", "\"\"\" # load parameters model_param_dirpath = os.path.join(dirpath, \"model_parameters.json\") with open(model_param_dirpath,", "True for compactness self._model.add( tf.keras.layers.BatchNormalization(fused=False, scale=True)) # Add the fully", "compactness self._model.add( tf.keras.layers.BatchNormalization(fused=False, scale=True)) # Add the fully connected layers", "metrics = {softmax_output_layer_name: ['acc', f1_score_training]} self._model.compile(loss=losses, optimizer=\"adam\", metrics=metrics) self._epoch_id =", "\"\\rEPOCH %d, batch_id %d: loss: %f - acc: %f -", "= tf.add( bg_label_tf, tf.multiply( tf.subtract(argmax_layer, bg_label_tf), argmax_mask ), name='ThreshArgMax' )", "beta should be a python float\") if beta <= 0.0:", "self.beta = beta self.threshold = threshold self.axis = None self.init_shape", "Type of averaging to be performed on data. Acceptable values", ":type train_data: Union[list, np.ndarray] :param val_data: Validation data used to", "\\ [argmax_layer, final_predicted_layer(argmax_layer, final_softmax_layer)] self._model = tf.keras.Model(self._model.inputs, argmax_outputs) # Compile", "float\") if threshold > 1.0 or threshold <= 0.0: raise", "filename: str \"\"\" embd_table = dict() with open(filename, 'r') as", "embedding_dict[chr(ascii_num)] self._model.add(tf.keras.layers.Embedding( max_char_encoding_id + 2, self._parameters['dim_embed'], weights=[embedding_matrix], input_length=input_shape[0], trainable=True)) #", "predictions confidences = [] sentence_lengths = np.zeros((batch_size,), dtype=int) predictions =", "Union[list, np.ndarray] :param val_data: Validation data used to validate the", "checking for functions def __init__(self, num_classes, average=None, beta=1.0, threshold=None, name=\"fbeta_score\",", "not isinstance(label_mapping, (list, dict)): raise TypeError(\"Labels must either be a", "label mapping) \"\"\" print(\"\\n###### Model Details ######\\n\") self._model.summary() print(\"\\nModel Parameters:\")", "fully connected layers dropout: Ratio of dropout in the model", "classification. $$ F_{\\beta} = (1 + \\beta^2) * \\frac{\\textrm{precision} *", "License for the specific language governing permissions and # limitations", "+ \\textrm{recall}} $$ Args: num_classes: Number of unique classes in", "i, ls in enumerate(zip(*embd_table.items()))] # get PCA embedder pca =", "verbose_keras: bool return (f1-score, f1 report). \"\"\" f1 = None", "= self._model( tf.convert_to_tensor(batch_data) ) # Count number of samples in", "Reserved. # # Licensed under the Apache License, Version 2.0", "1: errors.append(param + \" must be a valid integer or", "batch_size: number of samples in the batch of data :type", "parameters: parameter dict containing the following parameters: max_length: Maximum char", "SavedModel after ' + \\ 'running tf.compat.v1.enable_resource_variables()' return msg not", "if not isinstance(parameters[param], list) \\ or len(parameters[param]) == 0: errors.append(param", "history = defaultdict() f1 = None f1_report = [] self._model.reset_metrics()", "parameters for the model. Must contain num_labels. Other possible parameters", "= json.load(fp) # load label_mapping labels_dirpath = os.path.join(dirpath, \"label_mapping.json\") with", "unique classes in the dataset. average: Type of averaging to", "self.label_mapping[self._parameters['default_label']] # Remove the 3 output layers (dense_2', 'tf_op_layer_ArgMax', #", "average not in (None, \"micro\", \"macro\", \"weighted\"): raise ValueError( \"Unknown", "use f1 score metric f1_score_training = F1Score(num_classes=num_labels, average='micro') metrics =", "for model self._model_num_labels = 0 self._model_default_ind = -1 BaseModel.__init__(self, label_mapping,", "var in tf_model.variables: if 'training' not in var.name: tf1_weights.append(var.value()) loaded_model._construct_model()", "+ \\ [argmax_layer, final_predicted_layer(argmax_layer, self._model.output)] self._model = tf.keras.Model(self._model.inputs, argmax_outputs) #", "original embeddings to factor down :type source_file: str \"\"\" if", "\"list of integers.\") break elif param == 'default_label': if not", "the thresholds vector variable and create the threshold # matrix.", "batch_size=32, show_confidences=False, verbose=True): \"\"\" Run model and get predictions :param", "the input :type max_char_encoding_id: int :param max_len: Maximum char length", "ascii_num in range(max_char_encoding_id): if chr(ascii_num) in embedding_dict: embedding_matrix[ascii_num + 1]", "in range(0, allocation_index)] # Append slices of predictions to return", "parameters are: max_length, max_char_encoding_id, dim_embed, size_fc dropout, size_conv, num_fil, optimizer,", "NoV1ResourceMessageFilter(logging.Filter): \"\"\"Removes TF2 warning for using TF1 model which has", "1. threshold: Elements of `y_pred` greater than threshold are converted", "or threshold <= 0.0: raise ValueError(\"threshold should be between 0", "the embeddings :type n_dims: int :param source_file: Location of original", "isinstance(item, int): errors.append(param + \" must be a non-empty \"", "weights :param dirpath: directory path where you want to load", "2, self._parameters['dim_embed'])) embedding_dict = build_embd_dictionary(embed_file) input_shape = tuple([max_length]) # Fill", "1\") self.num_classes = num_classes self.average = average self.beta = beta", "and # limitations under the License. # ============================================================================== It is", "= decomposition.PCA(n_components=n_dims) reduced_embds = pca.fit_transform(embd_matrix) # write to file dir_name", "x != 0 to check for zero y_pred = tf.logical_and(y_pred", "f1_report = None if val_data is None: return f1, f1_report", "maps labels to their encoded integers :type label_mapping: dict :param", "} with tf.keras.utils.custom_object_scope(custom_objects): tf_model = tf.keras.models.load_model(dirpath) loaded_model = cls(label_mapping, parameters)", "disk with weights :param dirpath: directory path where you want", "limitations under the License. # ============================================================================== It is the harmonic", "0), (0, 0)), mode='constant') if show_confidences: confidences[allocation_index:allocation_index + num_samples_in_batch] =", "with open(labels_dirpath, 'w') as fp: json.dump(self.label_mapping, fp) self._model.save(os.path.join(dirpath)) @classmethod def", "layers for fil in self._parameters['num_fil']: self._model.add(tf.keras.layers.Conv1D( filters=fil, kernel_size=self._parameters['size_conv'], activation='relu', padding='same'))", "verbose_log: bool :param verbose_keras: whether or not to print out", "self: BaseModel :type other: BaseModel :return: Whether or not self", "python float\") if beta <= 0.0: raise ValueError(\"beta value should", "average, 1.0, threshold, name=name, dtype=dtype) def get_config(self): base_config = super().get_config()", "if param not in list_of_necessary_params: errors.append(param + \" is not", "self.dtype) def _weighted_sum(val, sample_weight): if sample_weight is not None: val", "factor down :type source_file: str \"\"\" if source_file is None:", "pca = decomposition.PCA(n_components=n_dims) reduced_embds = pca.fit_transform(embd_matrix) # write to file", "'default_label', 'pad_label', 'num_fil'] # Make sure the necessary parameters are", "self._epoch_id += 1 return history, f1, f1_report def _validate_training(self, val_data,", "or not to print out scores for training, etc. :type", "than zero\") if threshold is not None: if not isinstance(threshold,", "# Count number of samples in batch to prevent array", "2019 The TensorFlow Authors. All Rights Reserved. # # Licensed", "= np.zeros((batch_size, self._parameters['max_length'])) if show_confidences: confidences = np.zeros((batch_size, self._parameters['max_length'], self.num_labels))", "= tuple([max_length]) # Fill in the weight matrix: let pad", "checking for functions def __init__(self, num_classes, average=None, threshold=None, name=\"f1_score\", dtype=None):", "'max_char_encoding_id', 'dim_embed', 'size_fc', 'dropout', 'size_conv', 'default_label', 'pad_label', 'num_fil'] # Make", "reset_weights: bool :param verbose: Flag to determine whether to print", "a valid integer or float \" \"greater than 0.\") elif", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # https://github.com/tensorflow/addons/blob/v0.12.0/LICENSE #", "other are equal :rtype: bool \"\"\" if self._parameters != other._parameters", "than 0.\") elif param == 'dropout': if not isinstance(parameters[param], (int,", "input_encoding='UTF-8') sentences_encode = tf.add(tf.cast(1, tf.int32), sentences_encode) sentences_encode = tf.math.minimum(sentences_encode, max_char_encoding_id", "in enumerate(self._model.metrics_names): history[metric_label] = model_results[i] if val_data: f1, f1_report =", "and slightly modified from https://github.com/tensorflow/addons/blob/v0.12.0/tensorflow_addons/metrics/f_scores.py#L211-L283 # Copyright 2019 The TensorFlow", "OF ANY KIND, either express or implied. # See the", "Score: float. \"\"\" # Modification: remove the run-time type checking", "'size_conv']: if not isinstance(parameters[param], (int, float)) \\ or parameters[param] <", ":type default_ind: int :return: final argmax threshold layer for the", "See the License for the specific language governing permissions and", "f1_report def _validate_training(self, val_data, batch_size_test=32, verbose_log=True, verbose_keras=False): \"\"\" Validate the", "Other possible parameters are: max_length, max_char_encoding_id, dim_embed, size_fc dropout, size_conv,", "= tf.keras.backend.cast( tf.keras.backend.greater_equal(confidence_max_layer, threshold_at_argmax), dtype=argmax_layer.dtype) # Create a vector the", ":param batch_size: number of samples in the batch of data", "GloVe-like format :param filename: Path to the embed file for", "(self._epoch_id, batch_id)) tf.keras.backend.set_floatx('float32') # Clean the predicted entities and the", "- val_recall %f\" % (self._epoch_id, epoch_time, *model_results[1:], val_f1, val_precision, val_recall))", "consider rebuilding the SavedModel after ' + \\ 'running tf.compat.v1.enable_resource_variables()'", "to in writing, software # distributed under the License is", "parameters): \"\"\" Validate the parameters sent in. Raise error if", "precision and recall in harmonic mean. Determines the weight given", "Key for label_mapping that is the default label pad_label: Key", "os.path.join(dirpath, \"label_mapping.json\") with open(labels_dirpath, 'r') as fp: label_mapping = json.load(fp)", "tf.logical_and(y_pred >= threshold, tf.abs(y_pred) > 1e-12) else: y_pred = y_pred", ":type val_data: iterator :param batch_size_test: Number of samples to process", "\"\"\" Checks if two models are equal with one another,", "self.variables]) @tf.keras.utils.register_keras_serializable() class F1Score(FBetaScore): r\"\"\"Computes F-1 Score. # Copyright 2019", "the pad label num_fil: Number of filters in each convolution", "self.average != \"micro\": self.axis = 0 self.init_shape = [self.num_classes] def", "label_mapping: label mapping of the model :type label_mapping: dict :return:", "or agreed to in writing, software # distributed under the", "axis=-1, keepdims=True) # make sure [0, 0, 0] doesn't become", "confidences :type show_confidences: :param verbose: Flag to determine whether to", "Acceptable values \" \"are: [None, 'micro', 'macro', 'weighted']\" ) if", "batch_size_test: Number of samples to process in testing :type batch_size_test:", "0 for x_train, y_train in train_data: model_results = self._model.train_on_batch( x_train,", "not None: if not isinstance(threshold, float): raise TypeError(\"The value of", "the appropriate parameters for the model. Must contain num_labels. Other", "Add the final Softmax layer self._model.add( tf.keras.layers.Dense(num_labels, activation='softmax')) # Output", "name=\"dense_2\")( self._model.layers[-4].output) # Output the model into a .pb file", "param in parameters: if param not in list_of_necessary_params: errors.append(param +", "'PAD' self._epoch_id = 0 # reconstruct flags for model self._model_num_labels", "!= self._model_num_labels or \\ default_ind != self._model_default_ind def save_to_disk(self, dirpath):", "the 3 output layers (dense_2', 'tf_op_layer_ArgMax', # 'thresh_arg_max_layer') for _", "reset_weights: self.reset_weights() history = defaultdict() f1 = None f1_report =", "in record.getMessage() tf_logger = logging.getLogger('tensorflow') tf_logger.addFilter(NoV1ResourceMessageFilter()) @tf.keras.utils.register_keras_serializable() class FBetaScore(tf.keras.metrics.Metric): r\"\"\"Computes", "'num_fil'] # Make sure the necessary parameters are present and", "for _ in range(3): self._model.layers.pop() # Add the final Softmax", "errors.append(param + \" must be a non-empty \" \"list of", "batch_data in enumerate(data): model_output = self._model( tf.convert_to_tensor(batch_data) ) # Count", "print(\"\\nModel Label Mapping:\") for key, value in self.label_mapping.items(): print(\"{}: {}\".format(key,", "compliance with the License. # You may obtain a copy", "All Rights Reserved. # # Licensed under the Apache License,", "\" \"f1_score %f\" % (self._epoch_id, batch_id, *model_results[1:])) batch_id += 1", "model :param other: a model :type self: BaseModel :type other:", "label_mapping: maps labels to their encoded integers :type label_mapping: dict", "# default parameters max_length = self._parameters['max_length'] max_char_encoding_id = self._parameters['max_char_encoding_id'] #", "Key for entities_dict that is the pad label num_fil: Number", "raise ValueError(\"The `default_label` of {} must exist in the \"", "= num_classes self.average = average self.beta = beta self.threshold =", "None \"\"\" errors = [] list_of_necessary_params = ['max_length', 'max_char_encoding_id', 'dim_embed',", "threshold layer to the model. This layer's output will be", "status or not :type verbose: bool :return: char level predictions", "to be 1, and the rest 0. If threshold is", "not isinstance(beta, float): raise TypeError(\"The value of beta should be", "weights=[embedding_matrix], input_length=input_shape[0], trainable=True)) # Add the convolutional layers for fil", "mismatch num_samples_in_batch = len(batch_data) allocation_index = batch_id * batch_size #", "self._model.reset_metrics() softmax_output_layer_name = self._model.outputs[0].name.split('/')[0] start_time = time.time() batch_id = 0", "tf.compat.v1.enable_resource_variables()' return msg not in record.getMessage() tf_logger = logging.getLogger('tensorflow') tf_logger.addFilter(NoV1ResourceMessageFilter())", "parameters.setdefault('num_fil', [48 for _ in range(4)]) parameters['pad_label'] = 'PAD' self._epoch_id", "another, may only check important variables, i.e. may not check", "F1Score( num_classes=max(label_mapping.values()) + 1, average='micro'), \"CharacterLevelCnnModel\": cls, } with tf.keras.utils.custom_object_scope(custom_objects):", "dtype: (Optional) Data type of the metric result. Returns: F-Beta", "f1 score metric f1_score_training = F1Score(num_classes=num_labels, average='micro') metrics = {softmax_output_layer_name:", "if threshold is not None: if not isinstance(threshold, float): raise", "_argmax_threshold_layer(num_labels, threshold=0.0, default_ind=1): \"\"\" Adds an argmax threshold layer to", "python float\") if threshold > 1.0 or threshold <= 0.0:", "0 to 1.\") elif param == 'size_fc' or param ==", "self.set_label_mapping(label_mapping) if not self._model: self._construct_model() else: if self._need_to_reconstruct_model(): self._reconstruct_model() if", "of samples in the batch of data :type batch_size: int", "# https://github.com/tensorflow/addons/blob/v0.12.0/LICENSE # # Unless required by applicable law or", "beta: Determines the weight of precision and recall in harmonic", "not use this file except in compliance with the License.", "number of samples in the batch of data :type batch_size:", "bool \"\"\" if self._parameters != other._parameters \\ or self._label_mapping !=", "def call(self, argmax_layer, confidence_layer): threshold_at_argmax = tf.gather(self.thresh_vec, argmax_layer) confidence_max_layer =", "= tf.reshape(input_str_tensor, [-1]) sentences_encode = tf.strings.unicode_decode(input_str_flatten, input_encoding='UTF-8') sentences_encode = tf.add(tf.cast(1,", "tf.multiply( tf.subtract(argmax_layer, bg_label_tf), argmax_mask ), name='ThreshArgMax' ) return final_predicted_layer return", "tf.keras.utils.custom_object_scope(custom_objects): tf_model = tf.keras.models.load_model(dirpath) loaded_model = cls(label_mapping, parameters) loaded_model._model =", "mapping.\".format( self._parameters['default_label'])) super().set_label_mapping(label_mapping) def _need_to_reconstruct_model(self): \"\"\" Determines whether or not", "number of number of labels is altered :return: None \"\"\"", "confidence matrices for index, sentence_length \\ in enumerate(sentence_lengths[:allocation_index]): predictions_list[index] =", "weights) elif self.average is not None: # [micro, macro] f1_score", "\\ or self._label_mapping != other._label_mapping: return False return True def", "you may not use this file except in compliance with", "= [] sentence_lengths = np.zeros((batch_size,), dtype=int) predictions = np.zeros((batch_size, self._parameters['max_length']))", "as tf from sklearn import decomposition from .. import dp_logging", "Flag to determine whether to print status or not :type", "_weighted_sum(y_pred * (1 - y_true), sample_weight) ) self.false_negatives.assign_add( _weighted_sum((1 -", "dict)): raise TypeError(\"Labels must either be a non-empty encoding dict", "both multi-class and multi-label classification. $$ F_1 = 2 \\cdot", "np.zeros((batch_size,), dtype=int) predictions = np.zeros((batch_size, self._parameters['max_length'])) if show_confidences: confidences =", "def _argmax_threshold_layer(num_labels, threshold=0.0, default_ind=1): \"\"\" Adds an argmax threshold layer", "tf.subtract(argmax_layer, bg_label_tf), argmax_mask ), name='ThreshArgMax' ) return final_predicted_layer return ThreshArgMaxLayer(threshold,", "from 0 to max_char_encoding_id, # we add one extra index", "tf.add( bg_label_tf, tf.multiply( tf.subtract(argmax_layer, bg_label_tf), argmax_mask ), name='ThreshArgMax' ) return", "* y_true, sample_weight) ) self.weights_intermediate.assign_add(_weighted_sum(y_true, sample_weight)) def result(self): precision =", "default label index. :param num_labels: number of entities :type num_labels:", "np.zeros((max_char_encoding_id + 2, self._parameters['dim_embed'])) embedding_dict = build_embd_dictionary(embed_file) input_shape = tuple([max_length])", "actual entities f1, f1_report = labeler_utils.evaluate_accuracy( np.concatenate(y_val_pred, axis=0), np.concatenate(y_val_test, axis=0),", "train_data: Training data used to train model :type train_data: Union[list,", "from sklearn import decomposition from .. import dp_logging from .", "labeler_utils from .base_model import AutoSubRegistrationMeta, BaseModel, BaseTrainableModel _file_dir = os.path.dirname(os.path.abspath(__file__))", "to indices input_str_flatten = tf.reshape(input_str_tensor, [-1]) sentences_encode = tf.strings.unicode_decode(input_str_flatten, input_encoding='UTF-8')", "self._model = tf.keras.models.Sequential() # default parameters max_length = self._parameters['max_length'] max_char_encoding_id", "# parameter initialization if not parameters: parameters = {} parameters.setdefault('max_length',", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "value of threshold should be a python float\") if threshold", "F1Score(FBetaScore): r\"\"\"Computes F-1 Score. # Copyright 2019 The TensorFlow Authors.", "batch_id, *model_results[1:])) batch_id += 1 for i, metric_label in enumerate(self._model.metrics_names):", "mapping for index 0 reserved requires_zero_mapping = True def __init__(self,", "of samples to process in testing :type batch_size_test: int :param", "Add the convolutional layers for fil in self._parameters['num_fil']: self._model.add(tf.keras.layers.Conv1D( filters=fil,", "= True def __init__(self, label_mapping=None, parameters=None): \"\"\" CNN Model Initializer.", "= f1_report['weighted avg']['recall'] \\ if f1_report else np.NAN epoch_time =", "to determine whether to reset the weights or not :type", "['max_length', 'max_char_encoding_id', 'dim_embed', 'size_conv']: if not isinstance(parameters[param], (int, float)) \\", "\\textrm{recall}}{\\textrm{precision} + \\textrm{recall}} $$ Args: num_classes: Number of unique classes", "model to disk with weights :param dirpath: directory path where", "in range(3): self._model.layers.pop() # Add the final Softmax layer to", "%d: loss: %f - acc: %f - \" \"f1_score %f\"", "+ num_samples_in_batch] = model_output[1].numpy() sentence_lengths[allocation_index:allocation_index + num_samples_in_batch] = list(map(lambda x:", "json import logging import os import sys import time from", "<= allocation_index: predictions = np.pad(predictions, ((0, len(predictions)), (0, 0)), mode='constant')", "non-empty encoding dict \" \"which maps labels to index encodings", ":rtype: bool \"\"\" if self._parameters != other._parameters \\ or self._label_mapping", "type checking for functions def __init__(self, num_classes, average=None, beta=1.0, threshold=None,", "if self.threshold is None: threshold = tf.reduce_max(y_pred, axis=-1, keepdims=True) #", "status or not :type verbose: bool :return: None \"\"\" if", "self._construct_model() def _reconstruct_model(self): \"\"\" Reconstruct the appropriate layers if the", "batch_size=32, label_mapping=None, reset_weights=False, verbose=True): \"\"\" Train the current model with", "be a python float\") if threshold > 1.0 or threshold", "str :return: None \"\"\" if not self._model: self._construct_model() elif self._need_to_reconstruct_model():", "argmax threshold layer to the model. This layer's output will", "FBetaScore(tf.keras.metrics.Metric): r\"\"\"Computes F-Beta score. Adapted and slightly modified from https://github.com/tensorflow/addons/blob/v0.12.0/tensorflow_addons/metrics/f_scores.py#L211-L283", "[ np.asarray(ls) if i > 0 else list(ls) for i,", "import defaultdict import numpy as np import tensorflow as tf", "encodings or a list.\") label_mapping = copy.deepcopy(label_mapping) if 'PAD' not", "y_val_pred = [] y_val_test = [] for x_val, y_val in", "lists from numpy predictions_list = [i for i in range(0,", "verbose=verbose_keras) return f1, f1_report def predict(self, data, batch_size=32, show_confidences=False, verbose=True):", "output will be the argmax value if the confidence for", "= tf.reduce_max(y_pred, axis=-1, keepdims=True) # make sure [0, 0, 0]", "raise ValueError(\"beta value should be greater than zero\") if threshold", ":return: None \"\"\" # parameter initialization if not parameters: parameters", "Remove the 3 output layers (dense_2', 'tf_op_layer_ArgMax', # 'thresh_arg_max_layer') for", "macro] f1_score = tf.reduce_mean(f1_score) return f1_score def get_config(self): \"\"\"Returns the", "== 'size_fc' or param == 'num_fil': if not isinstance(parameters[param], list)", "for encoding the input :type max_char_encoding_id: int :param max_len: Maximum", "final_softmax_layer = tf.keras.layers.Dense( num_labels, activation='softmax', name=\"dense_2\")( self._model.layers[-4].output) # Output the", "val_recall %f\" % (self._epoch_id, epoch_time, *model_results[1:], val_f1, val_precision, val_recall)) self._epoch_id", "character encoding indices range from 0 to max_char_encoding_id, # we", "be a python float\") if beta <= 0.0: raise ValueError(\"beta", "self and other are equal :rtype: bool \"\"\" if self._parameters", "sample_weight): if sample_weight is not None: val = tf.math.multiply(val, tf.expand_dims(sample_weight,", "needs to reconstruct. \"\"\" if not self._model: return False default_ind", "the License. # ============================================================================== It is the weighted harmonic mean", "run-time type checking for functions def __init__(self, num_classes, average=None, beta=1.0,", "self.threshold is None: threshold = tf.reduce_max(y_pred, axis=-1, keepdims=True) # make", "for item in parameters[param]: if not isinstance(item, int): errors.append(param +", "0.\") elif param == 'dropout': if not isinstance(parameters[param], (int, float))", "embedder pca = decomposition.PCA(n_components=n_dims) reduced_embds = pca.fit_transform(embd_matrix) # write to", "json.dump(self._parameters, fp) labels_dirpath = os.path.join(dirpath, \"label_mapping.json\") with open(labels_dirpath, 'w') as", "to load the model from :type dirpath: str :return: None", "sample :type max_len: int :return : tensor containing encoded list", "`y_pred` above threshold are considered to be 1, and the", "num_labels = self.num_labels default_ind = self.label_mapping[self._parameters['default_label']] # Reset model tf.keras.backend.clear_session()", "should be a python float\") if threshold > 1.0 or", "matrix: let pad and space be 0s for ascii_num in", "is the harmonic mean of precision and recall. Output range", "non-empty \" \"list of integers.\") break elif param == 'default_label':", "in enumerate(zip(*embd_table.items()))] # get PCA embedder pca = decomposition.PCA(n_components=n_dims) reduced_embds", "def _char_encoding_layer(input_str_tensor, max_char_encoding_id, max_len): \"\"\" Character encoding for the list", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # https://github.com/tensorflow/addons/blob/v0.12.0/LICENSE # #", "space be 0s for ascii_num in range(max_char_encoding_id): if chr(ascii_num) in", "= num_labels self._model_default_ind = default_ind def fit(self, train_data, val_data=None, batch_size=32,", "= tf.gather(self.thresh_vec, argmax_layer) confidence_max_layer = tf.keras.backend.max(confidence_layer, axis=2) # Check if", "= [i for i in range(0, allocation_index)] # Append slices", ":return: final argmax threshold layer for the model \"\"\" #", "[] sentence_lengths = np.zeros((batch_size,), dtype=int) predictions = np.zeros((batch_size, self._parameters['max_length'])) if", "whether or not the model needs to reconstruct. \"\"\" if", "batch_size: Used to determine number of samples in each batch", "self._parameters['size_fc']: self._model.add( tf.keras.layers.Dense(units=size, activation='relu')) if self._parameters['dropout']: self._model.add( tf.keras.layers.Dropout(self._parameters['dropout'])) # Add", "file with GloVe-like format :param filename: Path to the embed", "dtype=int) predictions = np.zeros((batch_size, self._parameters['max_length'])) if show_confidences: confidences = np.zeros((batch_size,", "[micro, macro] f1_score = tf.reduce_mean(f1_score) return f1_score def get_config(self): \"\"\"Returns", "= logging.getLogger('tensorflow') tf_logger.addFilter(NoV1ResourceMessageFilter()) @tf.keras.utils.register_keras_serializable() class FBetaScore(tf.keras.metrics.Metric): r\"\"\"Computes F-Beta score. Adapted", "labels to their encoded integers :type label_mapping: Union[dict, None] :param", "value)) print(\"\\nModel Label Mapping:\") for key, value in self.label_mapping.items(): print(\"{}:", "f1_report else np.NAN epoch_time = time.time() - start_time logger.info(\"\\rEPOCH %d", "Size of each fully connected layers dropout: Ratio of dropout", "elif self._need_to_reconstruct_model(): self._reconstruct_model() model_param_dirpath = os.path.join(dirpath, \"model_parameters.json\") with open(model_param_dirpath, 'w')", "dtype=argmax_layer.dtype) # Generate the final predicted output using the function:", "= self._parameters['max_length'] max_char_encoding_id = self._parameters['max_char_encoding_id'] # Encoding layer def encoding_function(input_str):", "for training, from keras. :type verbose_keras: bool return (f1-score, f1", "raise TypeError(\"The value of threshold should be a python float\")", "load parameters model_param_dirpath = os.path.join(dirpath, \"model_parameters.json\") with open(model_param_dirpath, 'r') as", "input :type max_char_encoding_id: int :param max_len: Maximum char length in", "# matrix. class ThreshArgMaxLayer(tf.keras.layers.Layer): def __init__(self, threshold_, num_labels_): super(ThreshArgMaxLayer, self).__init__()", ":type label_mapping: dict :param parameters: Contains all the appropriate parameters", "determine whether to reset the weights or not :type reset_weights:", "= [] self._model.reset_metrics() softmax_output_layer_name = self._model.outputs[0].name.split('/')[0] start_time = time.time() batch_id", "label_mapping: raise ValueError(\"The `default_label` of {} must exist in the", "in (None, \"micro\", \"macro\", \"weighted\"): raise ValueError( \"Unknown average type.", ") self.true_positives = _zero_wt_init(\"true_positives\") self.false_positives = _zero_wt_init(\"false_positives\") self.false_negatives = _zero_wt_init(\"false_negatives\")", "argmax_outputs) # Compile the model softmax_output_layer_name = self._model.outputs[0].name.split('/')[0] losses =", "_need_to_reconstruct_model(self): \"\"\" Determines whether or not the model needs to", "rebuilding the SavedModel after ' + \\ 'running tf.compat.v1.enable_resource_variables()' return", "length in a sample :type max_len: int :return : tensor", "logging.getLogger('tensorflow') tf_logger.addFilter(NoV1ResourceMessageFilter()) @tf.keras.utils.register_keras_serializable() class FBetaScore(tf.keras.metrics.Metric): r\"\"\"Computes F-Beta score. Adapted and", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "embd_table = build_embd_dictionary(source_file) embd_words, embd_matrix = [ np.asarray(ls) if i", "and `weighted`. Default value is None. beta: Determines the weight", "function: final_predicted_layer = tf.add( bg_label_tf, tf.multiply( tf.subtract(argmax_layer, bg_label_tf), argmax_mask ),", "and get predictions :param data: text input :type data: Union[list,", "label_mapping that is the default label pad_label: Key for entities_dict", "x: len(x[0]), batch_data)) allocation_index += num_samples_in_batch # Convert predictions, confidences", "of filters in each convolution layer :type parameters: dict :return:", ":param verbose: Flag to determine whether to print status or", "should be greater than zero\") if threshold is not None:", "and valid. for param in parameters: if param in ['max_length',", "96]) parameters.setdefault('dropout', 0.073) parameters.setdefault('size_conv', 13) parameters.setdefault('default_label', \"UNKNOWN\") parameters.setdefault('num_fil', [48 for", "+ 2, self._parameters['dim_embed'])) embedding_dict = build_embd_dictionary(embed_file) input_shape = tuple([max_length]) #", "to 0 so all confidences pass. :type threshold: float :param", "open(model_param_dirpath, 'r') as fp: parameters = json.load(fp) # load label_mapping", "the final Softmax layer self._model.add( tf.keras.layers.Dense(num_labels, activation='softmax')) # Output the", "tf_model # Tensorflow v1 Model weights need to be transferred.", "entities f1, f1_report = labeler_utils.evaluate_accuracy( np.concatenate(y_val_pred, axis=0), np.concatenate(y_val_test, axis=0), self.num_labels,", "confidence_layer): threshold_at_argmax = tf.gather(self.thresh_vec, argmax_layer) confidence_max_layer = tf.keras.backend.max(confidence_layer, axis=2) #", "f1 score metric custom_objects = { \"F1Score\": F1Score( num_classes=max(label_mapping.values()) +", "to index encodings or a list.\") label_mapping = copy.deepcopy(label_mapping) if", "num_labels = self.num_labels default_ind = self.label_mapping[self._parameters['default_label']] # Remove the 3", "[self.num_classes] def _zero_wt_init(name): return self.add_weight( name, shape=self.init_shape, initializer=\"zeros\", dtype=self.dtype )", "with open(embd_file_name, 'w') as file: for word, embd in zip(embd_words,", "TF1 model which has resources.\"\"\" def filter(self, record): msg =", "\"from 0 to 1.\") elif param == 'size_fc' or param", "if val_data is None: return f1, f1_report # Predict on", "sample_weight) ) self.weights_intermediate.assign_add(_weighted_sum(y_true, sample_weight)) def result(self): precision = tf.math.divide_no_nan( self.true_positives,", "param == 'num_fil': if not isinstance(parameters[param], list) \\ or len(parameters[param])", "= tf.zeros(self.init_shape, dtype=self.dtype) tf.keras.backend.batch_set_value([(v, reset_value) for v in self.variables]) @tf.keras.utils.register_keras_serializable()", "model from :type dirpath: str :return: None \"\"\" # load", "argmax value if the confidence for that argmax meets the", "embedding_matrix = np.zeros((max_char_encoding_id + 2, self._parameters['dim_embed'])) embedding_dict = build_embd_dictionary(embed_file) input_shape", "or not to print out scores for training, from keras.", "allocation_index = 0 for batch_id, batch_data in enumerate(data): model_output =", "file except in compliance with the License. # You may", "\" must be a valid integer or float \" \"from", "vector the same size as the batch_size which # represents", "text input :type data: Union[list, numpy.ndarray] :param batch_size: number of", "base_config = super().get_config() del base_config[\"beta\"] return base_config def build_embd_dictionary(filename): \"\"\"", "str \"\"\" embd_table = dict() with open(filename, 'r') as embds:", "threshold are converted to be 1, and the rest 0.", "raise ValueError( \"Unknown average type. Acceptable values \" \"are: [None,", "padding='same')) if self._parameters['dropout']: self._model.add( tf.keras.layers.Dropout(self._parameters['dropout'])) # Add batch normalization, set", "float)) \\ or parameters[param] < 0: errors.append(param + \" must", "Parameters:\") for key, value in self._parameters.items(): print(\"{}: {}\".format(key, value)) print(\"\\nModel", "a new file :param n_dims: Final number of principal component", "\"\"\" Reconstruct the appropriate layers if the number of number", "logger.info(\"\\rEPOCH %d (%ds), loss: %f - acc: %f - f1_score", "is None. threshold: Elements of `y_pred` above threshold are considered", "to reset the weights or not :type reset_weights: bool :param", "\"\\n\") class CharacterLevelCnnModel(BaseTrainableModel, metaclass=AutoSubRegistrationMeta): # boolean if the label mapping", "must be a string.\" errors.append(error) # Error if there are", "= loaded_model.num_labels loaded_model._model_default_ind = loaded_model.label_mapping[ loaded_model._parameters['default_label'] ] return loaded_model @staticmethod", "array size if len(predictions) <= allocation_index: predictions = np.pad(predictions, ((0,", "the label mapping requires the mapping for index 0 reserved", "return the evaluation metrics. :param val_data: data generator for the", "a sample :type max_len: int :return : tensor containing encoded", "errors = [] list_of_necessary_params = ['max_length', 'max_char_encoding_id', 'dim_embed', 'size_fc', 'dropout',", "self._parameters['dim_embed'], weights=[embedding_matrix], input_length=input_shape[0], trainable=True)) # Add the convolutional layers for", "model. This layer's output will be the argmax value if", "error = str(param) + \" must be a string.\" errors.append(error)", "= self._validate_training(val_data) history['f1_report'] = f1_report val_f1 = f1_report['weighted avg']['f1-score'] \\", "\"\"\" if not self._model: return False default_ind = self.label_mapping[self._parameters['default_label']] return", "metrics. :param val_data: data generator for the validation :type val_data:", "[1, 1, 1] # Use abs(x) > eps, instead of", "sample max_char_encoding_id: Maximum integer value for encoding the input dim_embed:", "testing :type batch_size_test: int :param verbose_log: whether or not to", ":param verbose_keras: whether or not to print out scores for", "current model with the training data and validation data :param", "training, from keras. :type verbose_keras: bool return (f1-score, f1 report).", "= tf.keras.models.Sequential() # default parameters max_length = self._parameters['max_length'] max_char_encoding_id =", "'r') as fp: parameters = json.load(fp) # load label_mapping labels_dirpath", "!= 0): # dict with bad PAD raise ValueError(\"`PAD` must", "predictions = np.zeros((batch_size, self._parameters['max_length'])) if show_confidences: confidences = np.zeros((batch_size, self._parameters['max_length'],", "= os.path.dirname(source_file) embd_file_name = os.path.join(dir_name, 'glove-reduced-{}D.txt'.format(n_dims)) with open(embd_file_name, 'w') as", "self.label_mapping[self._parameters['default_label']] # Reset model tf.keras.backend.clear_session() # generate glove embedding create_glove_char(self._parameters['dim_embed'])", "`None`, `micro`, `macro` and `weighted`. Default value is None. threshold:", "problem, consider rebuilding the SavedModel after ' + \\ 'running", "super(ThreshArgMaxLayer, self).__init__() thresh_init = tf.constant_initializer(threshold_) self.thresh_vec = tf.Variable( name='ThreshVec', initial_value=thresh_init(shape=[num_labels_]),", "or not :type reset_weights: bool :param verbose: Flag to determine", "KIND, either express or implied. # See the License for", "threshold_at_argmax), dtype=argmax_layer.dtype) # Create a vector the same size as", "label mapping definitions have been \" \"altered without additional training.", "['acc', f1_score_training]} self._model.compile(loss=losses, optimizer=\"adam\", metrics=metrics) self._epoch_id = 0 self._model_num_labels =", "parameters: dict :return: None \"\"\" errors = [] list_of_necessary_params =", "sentences_encode_pad = sentences_encode.to_tensor(shape=[None, max_len]) return sentences_encode_pad @staticmethod def _argmax_threshold_layer(num_labels, threshold=0.0,", "% (self._epoch_id, epoch_time, *model_results[1:], val_f1, val_precision, val_recall)) self._epoch_id += 1", "self._model.layers.pop() # Add the final Softmax layer to the previous", "Number of filters in each convolution layer :type parameters: dict", ":param parameters: Contains all the appropriate parameters for the model.", "line = line.strip().split() embd_table[line[0]] = np.asarray(line[1:]) return embd_table def create_glove_char(n_dims,", "'r') as embds: for line in embds: line = line.strip().split()", ":param source_file: Location of original embeddings to factor down :type", "confidences = np.zeros((batch_size, self._parameters['max_length'], self.num_labels)) # Run model with batching", "loading :type filename: str \"\"\" embd_table = dict() with open(filename,", "for ascii_num in range(max_char_encoding_id): if chr(ascii_num) in embedding_dict: embedding_matrix[ascii_num +", "elif self._need_to_reconstruct_model(): raise RuntimeError(\"The model label mapping definitions have been", "to max_char_encoding_id, # we add one extra index for out-of-vocabulary", "length in a sample max_char_encoding_id: Maximum integer value for encoding", "(0, 0)), mode='constant') if show_confidences: confidences[allocation_index:allocation_index + num_samples_in_batch] = model_output[0].numpy()", "\\ if f1_report else np.NAN val_precision = f1_report['weighted avg']['precision'] \\", "weights need to be transferred. if not callable(tf_model): loaded_model._construct_model() tf1_weights", "filters in each convolution layer :type parameters: dict :return: None", "val_data is None: return f1, f1_report # Predict on the", "multi-label classification. $$ F_{\\beta} = (1 + \\beta^2) * \\frac{\\textrm{precision}", "\"weighted\": weights = tf.math.divide_no_nan( self.weights_intermediate, tf.reduce_sum(self.weights_intermediate) ) f1_score = tf.reduce_sum(f1_score", "\" is not an accepted parameter.\") if errors: raise ValueError('\\n'.join(errors))", "encoding the input :type max_char_encoding_id: int :param max_len: Maximum char", "return False return True def _validate_parameters(self, parameters): \"\"\" Validate the", "tf.int32), sentences_encode) sentences_encode = tf.math.minimum(sentences_encode, max_char_encoding_id + 1) # padding", "integer value for encoding the input dim_embed: Number of embedded", "(the \"License\"); # you may not use this file except", "Convolution kernel size default_label: Key for label_mapping that is the", "enumerate(sentence_lengths[:allocation_index]): predictions_list[index] = list(predictions[index][:sentence_length]) if show_confidences: confidences_list[index] = list(confidences[index][:sentence_length]) if", "float :param default_ind: default index :type default_ind: int :return: final", "= { \"F1Score\": F1Score( num_classes=max(label_mapping.values()) + 1, average='micro'), \"CharacterLevelCnnModel\": cls,", "label_mapping=None, parameters=None): \"\"\" CNN Model Initializer. initialize epoch_id :param label_mapping:", "\\ [argmax_layer, final_predicted_layer(argmax_layer, self._model.output)] self._model = tf.keras.Model(self._model.inputs, argmax_outputs) # Compile", "limitations under the License. # ============================================================================== It is the weighted", "0)), mode='constant') if show_confidences: confidences[allocation_index:allocation_index + num_samples_in_batch] = model_output[0].numpy() predictions[allocation_index:allocation_index", "layers final_predicted_layer = CharacterLevelCnnModel._argmax_threshold_layer( num_labels, threshold=0.0, default_ind=default_ind) argmax_outputs = [final_softmax_layer]", "class F1Score(FBetaScore): r\"\"\"Computes F-1 Score. # Copyright 2019 The TensorFlow", "+ \"\\n\") class CharacterLevelCnnModel(BaseTrainableModel, metaclass=AutoSubRegistrationMeta): # boolean if the label", "filter(self, record): msg = 'is a problem, consider rebuilding the", "are equal :rtype: bool \"\"\" if self._parameters != other._parameters \\", "in embedding_dict: embedding_matrix[ascii_num + 1] = embedding_dict[chr(ascii_num)] self._model.add(tf.keras.layers.Embedding( max_char_encoding_id +", "Maximum char length in a sample max_char_encoding_id: Maximum integer value", "a string.\" errors.append(error) # Error if there are extra parameters", "if not isinstance(parameters[param], str): error = str(param) + \" must", "other._label_mapping: return False return True def _validate_parameters(self, parameters): \"\"\" Validate", "self.num_labels != self._model_num_labels or \\ default_ind != self._model_default_ind def save_to_disk(self,", "# # Unless required by applicable law or agreed to", "def build_embd_dictionary(filename): \"\"\" Returns a numpy embedding dictionary from embed", "load the model from :type dirpath: str :return: None \"\"\"", "License. # ============================================================================== It is the weighted harmonic mean of", "= threshold self.axis = None self.init_shape = [] if self.average", "\"\"\"Returns the serializable config of the metric.\"\"\" config = {", "tf.keras.backend.greater_equal(confidence_max_layer, threshold_at_argmax), dtype=argmax_layer.dtype) # Create a vector the same size", "input_length=input_shape[0], trainable=True)) # Add the convolutional layers for fil in", "[0, 0, 0] doesn't become [1, 1, 1] # Use", "Generate the final predicted output using the function: final_predicted_layer =", "their encoded integers :type label_mapping: dict :param parameters: Contains all", "False default_ind = self.label_mapping[self._parameters['default_label']] return self.num_labels != self._model_num_labels or \\", "layers if the number of number of labels is altered", "default_ind=default_ind) argmax_outputs = [final_softmax_layer] + \\ [argmax_layer, final_predicted_layer(argmax_layer, final_softmax_layer)] self._model", "(Optional) Data type of the metric result. Returns: F-Beta Score:", "the SavedModel after ' + \\ 'running tf.compat.v1.enable_resource_variables()' return msg", "Create confidence layers final_predicted_layer = CharacterLevelCnnModel._argmax_threshold_layer( num_labels, threshold=0.0, default_ind=default_ind) argmax_outputs", "tf1_weights = [] for var in tf_model.variables: if 'training' not", "== 'dropout': if not isinstance(parameters[param], (int, float)) \\ or parameters[param]", ":type dirpath: str :return: None \"\"\" if not self._model: self._construct_model()", "f1_report['weighted avg']['recall'] \\ if f1_report else np.NAN epoch_time = time.time()", "the following parameters: max_length: Maximum char length in a sample", "numpy as np import tensorflow as tf from sklearn import", ":param batch_size: Used to determine number of samples in each", "data used to validate the training :type val_data: Union[list, np.ndarray]", "predictions_list[index] = list(predictions[index][:sentence_length]) if show_confidences: confidences_list[index] = list(confidences[index][:sentence_length]) if show_confidences:", "implied. # See the License for the specific language governing", "# Fill in the weight matrix: let pad and space", "necessary parameters are present and valid. for param in parameters:", "loaded_model._model_num_labels = loaded_model.num_labels loaded_model._model_default_ind = loaded_model.label_mapping[ loaded_model._parameters['default_label'] ] return loaded_model", "%d (%ds), loss: %f - acc: %f - f1_score %f", "tf.keras.backend.clear_session() # generate glove embedding create_glove_char(self._parameters['dim_embed']) # generate model self._model", "None \"\"\" self._construct_model() def _reconstruct_model(self): \"\"\" Reconstruct the appropriate layers", "= self.label_mapping[self._parameters['default_label']] # Reset model tf.keras.backend.clear_session() # generate glove embedding", "= 0 self._model_num_labels = num_labels self._model_default_ind = default_ind def fit(self,", "training :type val_data: Union[list, np.ndarray] :param batch_size: Used to determine", "confidences_list} return {'pred': predictions_list} def details(self): \"\"\" Prints the relevant", "tf.math.divide_no_nan( self.weights_intermediate, tf.reduce_sum(self.weights_intermediate) ) f1_score = tf.reduce_sum(f1_score * weights) elif", "in for param in parameters: if param not in list_of_necessary_params:", "class FBetaScore(tf.keras.metrics.Metric): r\"\"\"Computes F-Beta score. Adapted and slightly modified from", "super().set_label_mapping(label_mapping) def _need_to_reconstruct_model(self): \"\"\" Determines whether or not the model", "confidence for that argmax meets the threshold for its label,", "we add one extra index for out-of-vocabulary character embed_file =", "threshold=None, name=\"f1_score\", dtype=None): super().__init__(num_classes, average, 1.0, threshold, name=name, dtype=dtype) def", "avg']['f1-score'] \\ if f1_report else np.NAN val_precision = f1_report['weighted avg']['precision']", "and `weighted`. Default value is None. threshold: Elements of `y_pred`", "parameters, label mapping) \"\"\" print(\"\\n###### Model Details ######\\n\") self._model.summary() print(\"\\nModel", "f1, f1_report # Predict on the test set batch_id =", "= self.label_mapping[self._parameters['default_label']] # Remove the 3 output layers (dense_2', 'tf_op_layer_ArgMax',", "max_char_encoding_id, max_len): \"\"\" Character encoding for the list of sentences", "with one another, may only check important variables, i.e. may", "with open(filename, 'r') as embds: for line in embds: line", ") self.false_negatives.assign_add( _weighted_sum((1 - y_pred) * y_true, sample_weight) ) self.weights_intermediate.assign_add(_weighted_sum(y_true,", "embd_table def create_glove_char(n_dims, source_file=None): \"\"\" Embeds GloVe chars embeddings from", ">= threshold, tf.abs(y_pred) > 1e-12) else: y_pred = y_pred >", "dict :return: None \"\"\" errors = [] list_of_necessary_params = ['max_length',", "train model :type train_data: Union[list, np.ndarray] :param val_data: Validation data", "Data type of the metric result. Returns: F-1 Score: float.", "elif param == 'dropout': if not isinstance(parameters[param], (int, float)) \\", "= list(predictions[index][:sentence_length]) if show_confidences: confidences_list[index] = list(confidences[index][:sentence_length]) if show_confidences: return", "if average not in (None, \"micro\", \"macro\", \"weighted\"): raise ValueError(", "must map to index zero.\") if self._parameters['default_label'] not in label_mapping:", "parameters['pad_label'] = 'PAD' self._epoch_id = 0 # reconstruct flags for", "max_char_encoding_id: Maximum integer value for encoding the input dim_embed: Number", "def _weighted_sum(val, sample_weight): if sample_weight is not None: val =", "tf.expand_dims(sample_weight, 1)) return tf.reduce_sum(val, axis=self.axis) self.true_positives.assign_add(_weighted_sum(y_pred * y_true, sample_weight)) self.false_positives.assign_add(", "if param in ['max_length', 'max_char_encoding_id', 'dim_embed', 'size_conv']: if not isinstance(parameters[param],", "os.path.join(dirpath, \"label_mapping.json\") with open(labels_dirpath, 'w') as fp: json.dump(self.label_mapping, fp) self._model.save(os.path.join(dirpath))", "for loading :type filename: str \"\"\" embd_table = dict() with", "remove the run-time type checking for functions def __init__(self, num_classes,", "instead of x != 0 to check for zero y_pred", "check model itself. :param self: a model :param other: a", "permissions and # limitations under the License. # ============================================================================== It", "self._model.compile(loss=losses, optimizer=\"adam\", metrics=metrics) self._epoch_id = 0 self._model_num_labels = num_labels self._model_default_ind", "1.\") elif param == 'size_fc' or param == 'num_fil': if", "- start_time logger.info(\"\\rEPOCH %d (%ds), loss: %f - acc: %f", "13) parameters.setdefault('default_label', \"UNKNOWN\") parameters.setdefault('num_fil', [48 for _ in range(4)]) parameters['pad_label']", "self._model.add( tf.keras.layers.Dropout(self._parameters['dropout'])) # Add batch normalization, set fused = True", "one another, may only check important variables, i.e. may not", "dp_logging.get_child_logger(__name__) class NoV1ResourceMessageFilter(logging.Filter): \"\"\"Removes TF2 warning for using TF1 model", "Unless required by applicable law or agreed to in writing,", "optimizer, default_label :type parameters: dict :return: None \"\"\" # parameter", "in a sample :type max_len: int :return : tensor containing", "copy import json import logging import os import sys import", "softmax_output_layer_name = self._model.outputs[0].name.split('/')[0] start_time = time.time() batch_id = 0 for", "for key, value in self._parameters.items(): print(\"{}: {}\".format(key, value)) print(\"\\nModel Label", "size_fc: Size of each fully connected layers dropout: Ratio of", "self._model.add(tf.keras.layers.Embedding( max_char_encoding_id + 2, self._parameters['dim_embed'], weights=[embedding_matrix], input_length=input_shape[0], trainable=True)) # Add", "Number of samples to process in testing :type batch_size_test: int", "# if list missing PAD label_mapping = ['PAD'] + label_mapping", ".pb file for TensorFlow argmax_layer = tf.keras.backend.argmax(self._model.output) # Create confidence", "the specific language governing permissions and # limitations under the", "def result(self): precision = tf.math.divide_no_nan( self.true_positives, self.true_positives + self.false_positives )", "# Reset model tf.keras.backend.clear_session() # generate glove embedding create_glove_char(self._parameters['dim_embed']) #", "y_pred, sample_weight=None): if self.threshold is None: threshold = tf.reduce_max(y_pred, axis=-1,", "tf.strings.unicode_decode(input_str_flatten, input_encoding='UTF-8') sentences_encode = tf.add(tf.cast(1, tf.int32), sentences_encode) sentences_encode = tf.math.minimum(sentences_encode,", "label_mapping elif 0 not in label_mapping.values(): # if dict missing", "record.getMessage() tf_logger = logging.getLogger('tensorflow') tf_logger.addFilter(NoV1ResourceMessageFilter()) @tf.keras.utils.register_keras_serializable() class FBetaScore(tf.keras.metrics.Metric): r\"\"\"Computes F-Beta", "on the test set and return the evaluation metrics. :param", "input_str_tensor: input list of sentences converted to tensor :type input_str_tensor:", "_zero_wt_init(\"true_positives\") self.false_positives = _zero_wt_init(\"false_positives\") self.false_negatives = _zero_wt_init(\"false_negatives\") self.weights_intermediate = _zero_wt_init(\"weights_intermediate\")", "possible parameters are: max_length, max_char_encoding_id, dim_embed, size_fc dropout, size_conv, num_fil,", "parameters: if param not in list_of_necessary_params: errors.append(param + \" is", "label_mapping labels_dirpath = os.path.join(dirpath, \"label_mapping.json\") with open(labels_dirpath, 'r') as fp:", "number of samples in each batch :type batch_size: int :param", "collections import defaultdict import numpy as np import tensorflow as", "\"num_classes\": self.num_classes, \"average\": self.average, \"beta\": self.beta, \"threshold\": self.threshold, } base_config", "embd in zip(embd_words, reduced_embds): file.write(word + \" \" + '", ":type val_data: Union[list, np.ndarray] :param batch_size: Used to determine number", "training data and validation data :param train_data: Training data used", "scores for training, from keras. :type verbose_keras: bool return (f1-score,", "0 for batch_id, batch_data in enumerate(data): model_output = self._model( tf.convert_to_tensor(batch_data)", "param in parameters: if param in ['max_length', 'max_char_encoding_id', 'dim_embed', 'size_conv']:", "a .pb file for TensorFlow argmax_layer = tf.keras.backend.argmax(self._model.output) # Create", "= [] for x_val, y_val in val_data: y_val_pred.append(self._model.predict( x_val, batch_size=batch_size_test,", "label_mapping: maps labels to their encoded integers :type label_mapping: Union[dict,", "a problem, consider rebuilding the SavedModel after ' + \\", "self._parameters.items(): print(\"{}: {}\".format(key, value)) print(\"\\nModel Label Mapping:\") for key, value", "batch_data)) allocation_index += num_samples_in_batch # Convert predictions, confidences to lists", "\"\"\" if self._parameters != other._parameters \\ or self._label_mapping != other._label_mapping:", "argmax_layer = tf.keras.backend.argmax(self._model.output) # Create confidence layers final_predicted_layer = CharacterLevelCnnModel._argmax_threshold_layer(", "defaultdict import numpy as np import tensorflow as tf from", "of the metric.\"\"\" config = { \"num_classes\": self.num_classes, \"average\": self.average,", "threshold: Elements of `y_pred` above threshold are considered to be", "of entities :type num_labels: int :param threshold: default set to", "\\frac{\\textrm{precision} * \\textrm{precision}}{(\\beta^2 \\cdot \\textrm{precision}) + \\textrm{recall}} $$ Args: num_classes:", "parameters[param] < 0 or parameters[param] > 1: errors.append(param + \"", "'weighted']\" ) if not isinstance(beta, float): raise TypeError(\"The value of", "(None, \"micro\", \"macro\", \"weighted\"): raise ValueError( \"Unknown average type. Acceptable", "max_len: int :return : tensor containing encoded list of input", "samples in batch to prevent array mismatch num_samples_in_batch = len(batch_data)", "str): error = str(param) + \" must be a string.\"", "in list_of_necessary_params: errors.append(param + \" is not an accepted parameter.\")", "threshold for its label, otherwise it will be the default", "Initializer. initialize epoch_id :param label_mapping: maps labels to their encoded", "parameters are present. :param parameters: parameter dict containing the following", "# use f1 score metric f1_score_training = F1Score(num_classes=num_labels, average='micro') metrics", "mean. Determines the weight given to the precision and recall.", "tf.Variable( name='ThreshVec', initial_value=thresh_init(shape=[num_labels_]), trainable=False) def call(self, argmax_layer, confidence_layer): threshold_at_argmax =", "modified from https://github.com/tensorflow/addons/blob/v0.12.0/tensorflow_addons/metrics/f_scores.py#L211-L283 # Copyright 2019 The TensorFlow Authors. All", "[96, 96]) parameters.setdefault('dropout', 0.073) parameters.setdefault('size_conv', 13) parameters.setdefault('default_label', \"UNKNOWN\") parameters.setdefault('num_fil', [48", "present and valid. for param in parameters: if param in", "num_samples_in_batch] = list(map(lambda x: len(x[0]), batch_data)) allocation_index += num_samples_in_batch #", "prediction & confidence matrices for index, sentence_length \\ in enumerate(sentence_lengths[:allocation_index]):", "confidences meet the threshold minimum. argmax_mask = tf.keras.backend.cast( tf.keras.backend.greater_equal(confidence_max_layer, threshold_at_argmax),", "list(predictions[index][:sentence_length]) if show_confidences: confidences_list[index] = list(confidences[index][:sentence_length]) if show_confidences: return {'pred':", "self.num_labels, self.reverse_label_mapping, verbose=verbose_keras) return f1, f1_report def predict(self, data, batch_size=32,", "predictions to return prediction & confidence matrices for index, sentence_length", "tf.cast(y_pred, self.dtype) def _weighted_sum(val, sample_weight): if sample_weight is not None:", "input list of sentences converted to tensor :type input_str_tensor: tf.tensor", "str(param) + \" must be a string.\" errors.append(error) # Error", "will be the argmax value if the confidence for that", "default_ind = self.label_mapping[self._parameters['default_label']] return self.num_labels != self._model_num_labels or \\ default_ind", "super().__init__(name=name, dtype=dtype) if average not in (None, \"micro\", \"macro\", \"weighted\"):", "from disk with weights :param dirpath: directory path where you", "sklearn import decomposition from .. import dp_logging from . import", "__init__(self, num_classes, average=None, threshold=None, name=\"f1_score\", dtype=None): super().__init__(num_classes, average, 1.0, threshold,", "predicted entities and the actual entities f1, f1_report = labeler_utils.evaluate_accuracy(", "(tf.math.square(self.beta) * precision) + recall mean = tf.math.divide_no_nan(mul_value, add_value) f1_score", "CharacterLevelCnnModel(BaseTrainableModel, metaclass=AutoSubRegistrationMeta): # boolean if the label mapping requires the", "to train model :type train_data: Union[list, np.ndarray] :param val_data: Validation", "import numpy as np import tensorflow as tf from sklearn", "want to save the model to :type dirpath: str :return:", "to tensor :type input_str_tensor: tf.tensor :param max_char_encoding_id: Maximum integer value", "build_embd_dictionary(filename): \"\"\" Returns a numpy embedding dictionary from embed file", "# # http://www.apache.org/licenses/LICENSE-2.0 # https://github.com/tensorflow/addons/blob/v0.12.0/LICENSE # # Unless required by", "default_label :type parameters: dict :return: None \"\"\" # parameter initialization", "mean of precision and recall. Output range is `[0, 1]`.", "= _zero_wt_init(\"weights_intermediate\") def update_state(self, y_true, y_pred, sample_weight=None): if self.threshold is", "bg_label_tf = tf.keras.backend.constant( default_ind, dtype=argmax_layer.dtype) # Generate the final predicted", "weights = tf.math.divide_no_nan( self.weights_intermediate, tf.reduce_sum(self.weights_intermediate) ) f1_score = tf.reduce_sum(f1_score *", "samples in the batch of data :type batch_size: int :param", "$$ Args: num_classes: Number of unique classes in the dataset.", "a sample max_char_encoding_id: Maximum integer value for encoding the input", "# Generate the final predicted output using the function: final_predicted_layer", ":rtype: dict \"\"\" if not self._model: raise ValueError(\"You are trying", "# Initialize the thresholds vector variable and create the threshold", "not in (None, \"micro\", \"macro\", \"weighted\"): raise ValueError( \"Unknown average", "and multi-label classification. $$ F_{\\beta} = (1 + \\beta^2) *", "add_value = (tf.math.square(self.beta) * precision) + recall mean = tf.math.divide_no_nan(mul_value,", "or not :type verbose: bool :return: char level predictions and", "= line.strip().split() embd_table[line[0]] = np.asarray(line[1:]) return embd_table def create_glove_char(n_dims, source_file=None):", "list of input sentences :rtype: tf.Tensor \"\"\" # convert characters", "label num_fil: Number of filters in each convolution layer :type", "logging import os import sys import time from collections import", "it will be the default label index. :param num_labels: number", "metric result. Returns: F-Beta Score: float. \"\"\" # Modification: remove", "dtype=argmax_layer.dtype) # Create a vector the same size as the", "history[metric_label] = model_results[i] if val_data: f1, f1_report = self._validate_training(val_data) history['f1_report']", "final_predicted_layer = tf.add( bg_label_tf, tf.multiply( tf.subtract(argmax_layer, bg_label_tf), argmax_mask ), name='ThreshArgMax'", "keepdims=True) # make sure [0, 0, 0] doesn't become [1,", "the fully connected layers for size in self._parameters['size_fc']: self._model.add( tf.keras.layers.Dense(units=size,", "meets the threshold for its label, otherwise it will be", "mode='constant') if show_confidences: confidences = np.pad(confidences, ((0, len(predictions)), (0, 0),", "parameters: max_length: Maximum char length in a sample max_char_encoding_id: Maximum", "char level predictions and confidences :rtype: dict \"\"\" if not", "argmax_mask = tf.keras.backend.cast( tf.keras.backend.greater_equal(confidence_max_layer, threshold_at_argmax), dtype=argmax_layer.dtype) # Create a vector", "len(batch_data) allocation_index = batch_id * batch_size # Double array size", "dtype=dtype) if average not in (None, \"micro\", \"macro\", \"weighted\"): raise", "@tf.keras.utils.register_keras_serializable() class F1Score(FBetaScore): r\"\"\"Computes F-1 Score. # Copyright 2019 The", "+ self.false_negatives ) mul_value = precision * recall add_value =", "entities and the actual entities f1, f1_report = labeler_utils.evaluate_accuracy( np.concatenate(y_val_pred,", "isinstance(label_mapping, (list, dict)): raise TypeError(\"Labels must either be a non-empty", "num_labels: number of entities :type num_labels: int :param threshold: default", "+ self.false_positives ) recall = tf.math.divide_no_nan( self.true_positives, self.true_positives + self.false_negatives", "@staticmethod def _argmax_threshold_layer(num_labels, threshold=0.0, default_ind=1): \"\"\" Adds an argmax threshold", "TensorFlow argmax_layer = tf.keras.backend.argmax(self._model.output) # Create confidence layers final_predicted_layer =", "Reset the weights of the model. :return: None \"\"\" self._construct_model()", "to their encoded integers :type label_mapping: dict :param parameters: Contains", "Determines whether or not the model needs to be reconstructed.", "data generator for the validation :type val_data: iterator :param batch_size_test:", "' '.join(str(num) for num in embd) + \"\\n\") class CharacterLevelCnnModel(BaseTrainableModel,", "not self._model: self._construct_model() elif self._need_to_reconstruct_model(): self._reconstruct_model() model_param_dirpath = os.path.join(dirpath, \"model_parameters.json\")", "and create the threshold # matrix. class ThreshArgMaxLayer(tf.keras.layers.Layer): def __init__(self,", "a pre-trained weight matrix # character encoding indices range from", "= None f1_report = None if val_data is None: return", "been \" \"altered without additional training. Please \" \"train the", "Whether or not self and other are equal :rtype: bool", "value is None. beta: Determines the weight of precision and", "ls in enumerate(zip(*embd_table.items()))] # get PCA embedder pca = decomposition.PCA(n_components=n_dims)", "of precision and recall in harmonic mean. Determines the weight", "the training :type val_data: Union[list, np.ndarray] :param batch_size: Used to", "if list missing PAD label_mapping = ['PAD'] + label_mapping elif", "without additional training. Please \" \"train the model or reset", "**kwargs): super().__init__(name=name, dtype=dtype) if average not in (None, \"micro\", \"macro\",", "input dim_embed: Number of embedded dimensions size_fc: Size of each", "f1_score_training = F1Score(num_classes=num_labels, average='micro') metrics = {softmax_output_layer_name: ['acc', f1_score_training]} self._model.compile(loss=losses,", "= self._model.outputs + \\ [argmax_layer, final_predicted_layer(argmax_layer, self._model.output)] self._model = tf.keras.Model(self._model.inputs,", "the dataset. average: Type of averaging to be performed on", "self._model.outputs[0].name.split('/')[0] start_time = time.time() batch_id = 0 for x_train, y_train", "= tf.keras.backend.argmax(final_softmax_layer) # Create confidence layers final_predicted_layer = CharacterLevelCnnModel._argmax_threshold_layer( num_labels,", "if len(predictions) <= allocation_index: predictions = np.pad(predictions, ((0, len(predictions)), (0,", "layer to the model. This layer's output will be the", "parameters[param] > 1: errors.append(param + \" must be a valid", "0 self.init_shape = [self.num_classes] def _zero_wt_init(name): return self.add_weight( name, shape=self.init_shape,", "None if val_data is None: return f1, f1_report # Predict", "ValueError('\\n'.join(errors)) def set_label_mapping(self, label_mapping): \"\"\" Sets the labels for the", "\"\"\" Validate the parameters sent in. Raise error if invalid", "y_val_test = [] for x_val, y_val in val_data: y_val_pred.append(self._model.predict( x_val,", "check for zero y_pred = tf.logical_and(y_pred >= threshold, tf.abs(y_pred) >", "with the training data and validation data :param train_data: Training", "if beta <= 0.0: raise ValueError(\"beta value should be greater", "or parameters[param] < 0: errors.append(param + \" must be a", "val_data: Union[list, np.ndarray] :param batch_size: Used to determine number of", "avg']['precision'] \\ if f1_report else np.NAN val_recall = f1_report['weighted avg']['recall']", "f1, f1_report = self._validate_training(val_data) history['f1_report'] = f1_report val_f1 = f1_report['weighted", "and recall in harmonic mean. Determines the weight given to", "You may obtain a copy of the License at #", "max_char_encoding_id, dim_embed, size_fc dropout, size_conv, num_fil, optimizer, default_label :type parameters:", "* batch_size # Double array size if len(predictions) <= allocation_index:", "0 self._model_default_ind = -1 BaseModel.__init__(self, label_mapping, parameters) def __eq__(self, other):", "if show_confidences: confidences_list[index] = list(confidences[index][:sentence_length]) if show_confidences: return {'pred': predictions_list,", "not an accepted parameter.\") if errors: raise ValueError('\\n'.join(errors)) def set_label_mapping(self,", "axis=-1)) batch_id += 1 sys.stdout.flush() if verbose_log: sys.stdout.write(\"\\rEPOCH %g, validation_batch_id", "default_ind != self._model_default_ind def save_to_disk(self, dirpath): \"\"\" Saves whole model", "self._model.add( tf.keras.layers.Dense(units=size, activation='relu')) if self._parameters['dropout']: self._model.add( tf.keras.layers.Dropout(self._parameters['dropout'])) # Add the", "confidences_list = None if show_confidences: confidences_list = [i for i", "self.true_positives = _zero_wt_init(\"true_positives\") self.false_positives = _zero_wt_init(\"false_positives\") self.false_negatives = _zero_wt_init(\"false_negatives\") self.weights_intermediate", "+ recall mean = tf.math.divide_no_nan(mul_value, add_value) f1_score = mean *", "axis=self.axis) self.true_positives.assign_add(_weighted_sum(y_pred * y_true, sample_weight)) self.false_positives.assign_add( _weighted_sum(y_pred * (1 -", "self._model.outputs + \\ [argmax_layer, final_predicted_layer(argmax_layer, self._model.output)] self._model = tf.keras.Model(self._model.inputs, argmax_outputs)", "float\") if beta <= 0.0: raise ValueError(\"beta value should be", "self._construct_model() else: if self._need_to_reconstruct_model(): self._reconstruct_model() if reset_weights: self.reset_weights() history =", "model_results = self._model.train_on_batch( x_train, {softmax_output_layer_name: y_train}) sys.stdout.flush() if verbose: sys.stdout.write(", "\"\"\" if source_file is None: source_file = os.path.join(_file_dir, \"embeddings/glove.840B.300d-char.txt\") #", "average type. Acceptable values \" \"are: [None, 'micro', 'macro', 'weighted']\"", "precision = tf.math.divide_no_nan( self.true_positives, self.true_positives + self.false_positives ) recall =", ":param input_str_tensor: input list of sentences converted to tensor :type", "[final_softmax_layer] + \\ [argmax_layer, final_predicted_layer(argmax_layer, final_softmax_layer)] self._model = tf.keras.Model(self._model.inputs, argmax_outputs)", "the weights of the model. :return: None \"\"\" self._construct_model() def", "is None. beta: Determines the weight of precision and recall", "self.thresh_vec = tf.Variable( name='ThreshVec', initial_value=thresh_init(shape=[num_labels_]), trainable=False) def call(self, argmax_layer, confidence_layer):", "f1, f1_report = labeler_utils.evaluate_accuracy( np.concatenate(y_val_pred, axis=0), np.concatenate(y_val_test, axis=0), self.num_labels, self.reverse_label_mapping,", "for functions def __init__(self, num_classes, average=None, threshold=None, name=\"f1_score\", dtype=None): super().__init__(num_classes,", "self._parameters['dropout']: self._model.add( tf.keras.layers.Dropout(self._parameters['dropout'])) # Add the final Softmax layer self._model.add(", "# represents the background label bg_label_tf = tf.keras.backend.constant( default_ind, dtype=argmax_layer.dtype)", "cls, } with tf.keras.utils.custom_object_scope(custom_objects): tf_model = tf.keras.models.load_model(dirpath) loaded_model = cls(label_mapping,", "= tf.add(tf.cast(1, tf.int32), sentences_encode) sentences_encode = tf.math.minimum(sentences_encode, max_char_encoding_id + 1)", "from collections import defaultdict import numpy as np import tensorflow", "threshold_, num_labels_): super(ThreshArgMaxLayer, self).__init__() thresh_init = tf.constant_initializer(threshold_) self.thresh_vec = tf.Variable(", "sys import time from collections import defaultdict import numpy as", "tf_logger.addFilter(NoV1ResourceMessageFilter()) @tf.keras.utils.register_keras_serializable() class FBetaScore(tf.keras.metrics.Metric): r\"\"\"Computes F-Beta score. Adapted and slightly", "tf.keras.backend.batch_set_value([(v, reset_value) for v in self.variables]) @tf.keras.utils.register_keras_serializable() class F1Score(FBetaScore): r\"\"\"Computes", "TypeError(\"The value of threshold should be a python float\") if", "\"\"\" # convert characters to indices input_str_flatten = tf.reshape(input_str_tensor, [-1])", "parameters) def __eq__(self, other): \"\"\" Checks if two models are", "= len(batch_data) allocation_index = batch_id * batch_size # Double array", "*model_results[1:], val_f1, val_precision, val_recall)) self._epoch_id += 1 return history, f1,", "model self._model = tf.keras.models.Sequential() # default parameters max_length = self._parameters['max_length']", "character embed_file = os.path.join( _file_dir, \"embeddings/glove-reduced-{}D.txt\".format( self._parameters['dim_embed'])) embedding_matrix = np.zeros((max_char_encoding_id", "samples to process in testing :type batch_size_test: int :param verbose_log:", "data: text input :type data: Union[list, numpy.ndarray] :param batch_size: number", "val_precision, val_recall)) self._epoch_id += 1 return history, f1, f1_report def", "\\ 'running tf.compat.v1.enable_resource_variables()' return msg not in record.getMessage() tf_logger =", "the weight of precision and recall in harmonic mean. Determines", "in harmonic mean. Determines the weight given to the precision", "after ' + \\ 'running tf.compat.v1.enable_resource_variables()' return msg not in", "_zero_wt_init(\"false_positives\") self.false_negatives = _zero_wt_init(\"false_negatives\") self.weights_intermediate = _zero_wt_init(\"weights_intermediate\") def update_state(self, y_true,", "num_labels, threshold=0.0, default_ind=default_ind) argmax_outputs = self._model.outputs + \\ [argmax_layer, final_predicted_layer(argmax_layer,", "val_precision: %f - val_recall %f\" % (self._epoch_id, epoch_time, *model_results[1:], val_f1,", "# if dict missing PAD and 0 label_mapping.update({'PAD': 0}) if", "vectors as array embd_table = build_embd_dictionary(source_file) embd_words, embd_matrix = [", "prevent array mismatch num_samples_in_batch = len(batch_data) allocation_index = batch_id *", "batch_id += 1 sys.stdout.flush() if verbose_log: sys.stdout.write(\"\\rEPOCH %g, validation_batch_id %d\"", "of original embeddings to factor down :type source_file: str \"\"\"", "and other are equal :rtype: bool \"\"\" if self._parameters !=", "isinstance(parameters[param], (int, float)) \\ or parameters[param] < 0: errors.append(param +", "reset. :return: None \"\"\" num_labels = self.num_labels default_ind = self.label_mapping[self._parameters['default_label']]", "PAD and 0 label_mapping.update({'PAD': 0}) if (isinstance(label_mapping, dict) and label_mapping.get('PAD',", "threshold=0.0, default_ind=default_ind) argmax_outputs = [final_softmax_layer] + \\ [argmax_layer, final_predicted_layer(argmax_layer, final_softmax_layer)]", "load_from_disk(cls, dirpath): \"\"\" Loads whole model from disk with weights", "bool :return: None \"\"\" if label_mapping is not None: self.set_label_mapping(label_mapping)", ":rtype: tf.Tensor \"\"\" # convert characters to indices input_str_flatten =", "and recall. Output range is `[0, 1]`. Works for both", "model itself. :param self: a model :param other: a model", "pad label num_fil: Number of filters in each convolution layer", "default_ind = self.label_mapping[self._parameters['default_label']] # Remove the 3 output layers (dense_2',", "int :param label_mapping: maps labels to their encoded integers :type", "must either be a non-empty encoding dict \" \"which maps", "\" \"which maps labels to index encodings or a list.\")", "param in ['max_length', 'max_char_encoding_id', 'dim_embed', 'size_conv']: if not isinstance(parameters[param], (int,", "if dict missing PAD and 0 label_mapping.update({'PAD': 0}) if (isinstance(label_mapping,", "the confidence for that argmax meets the threshold for its", "for the data labeler. This also serves as a weight", "\"beta\": self.beta, \"threshold\": self.threshold, } base_config = super().get_config() return {**base_config,", "%d, batch_id %d: loss: %f - acc: %f - \"", "validate the training :type val_data: Union[list, np.ndarray] :param batch_size: Used", "line.strip().split() embd_table[line[0]] = np.asarray(line[1:]) return embd_table def create_glove_char(n_dims, source_file=None): \"\"\"", "values \" \"are: [None, 'micro', 'macro', 'weighted']\" ) if not", "np.concatenate(y_val_test, axis=0), self.num_labels, self.reverse_label_mapping, verbose=verbose_keras) return f1, f1_report def predict(self,", "tf_model.variables: if 'training' not in var.name: tf1_weights.append(var.value()) loaded_model._construct_model() tf1_weights.append(loaded_model._model.weights[-1].value()) loaded_model._model.set_weights(tf1_weights)", "= [i for i in range(0, allocation_index)] confidences_list = None", "np.asarray(ls) if i > 0 else list(ls) for i, ls", "\"\"\" # parameter initialization if not parameters: parameters = {}", "be between 0 and 1\") self.num_classes = num_classes self.average =", "if sample_weight is not None: val = tf.math.multiply(val, tf.expand_dims(sample_weight, 1))", "License. # You may obtain a copy of the License", "!= other._parameters \\ or self._label_mapping != other._label_mapping: return False return", "use f1 score metric custom_objects = { \"F1Score\": F1Score( num_classes=max(label_mapping.values())", "return {**base_config, **config} def reset_states(self): reset_value = tf.zeros(self.init_shape, dtype=self.dtype) tf.keras.backend.batch_set_value([(v,", "label_mapping, parameters) def __eq__(self, other): \"\"\" Checks if two models", "Determines the weight of precision and recall in harmonic mean.", "that is the default label pad_label: Key for entities_dict that", "0 to max_char_encoding_id, # we add one extra index for", "index for out-of-vocabulary character embed_file = os.path.join( _file_dir, \"embeddings/glove-reduced-{}D.txt\".format( self._parameters['dim_embed']))", "if two models are equal with one another, may only", "\"\"\" Train the current model with the training data and", "_reconstruct_model(self): \"\"\" Reconstruct the appropriate layers if the number of", "in the model size_conv: Convolution kernel size default_label: Key for", "{} must exist in the \" \"label mapping.\".format( self._parameters['default_label'])) super().set_label_mapping(label_mapping)", "the rest 0. If threshold is None, the argmax is", "self._reconstruct_model() if reset_weights: self.reset_weights() history = defaultdict() f1 = None", "= None if val_data is None: return f1, f1_report #", "== 'num_fil': if not isinstance(parameters[param], list) \\ or len(parameters[param]) ==", "model which has resources.\"\"\" def filter(self, record): msg = 'is", "in enumerate(sentence_lengths[:allocation_index]): predictions_list[index] = list(predictions[index][:sentence_length]) if show_confidences: confidences_list[index] = list(confidences[index][:sentence_length])", "import os import sys import time from collections import defaultdict", "model (summary, parameters, label mapping) \"\"\" print(\"\\n###### Model Details ######\\n\")", "a weight reset. :return: None \"\"\" num_labels = self.num_labels default_ind", "np.ndarray] :param batch_size: Used to determine number of samples in", "import copy import json import logging import os import sys", "governing permissions and # limitations under the License. # ==============================================================================", "dict \"\"\" if not self._model: raise ValueError(\"You are trying to", ") f1_score = tf.reduce_sum(f1_score * weights) elif self.average is not", "return f1_score def get_config(self): \"\"\"Returns the serializable config of the", "must be a valid integer or float \" \"from 0", "> 1e-12) else: y_pred = y_pred > self.threshold y_true =", "weight matrix # character encoding indices range from 0 to", "dtype=None, **kwargs): super().__init__(name=name, dtype=dtype) if average not in (None, \"micro\",", "TensorFlow Authors. All Rights Reserved. # # Licensed under the", "verbose: Flag to determine whether to print status or not", "threshold=0.0, default_ind=1): \"\"\" Adds an argmax threshold layer to the", "be the default label index. :param num_labels: number of entities", "num_labels: int :param threshold: default set to 0 so all", "fp: json.dump(self.label_mapping, fp) self._model.save(os.path.join(dirpath)) @classmethod def load_from_disk(cls, dirpath): \"\"\" Loads", "initializer=\"zeros\", dtype=self.dtype ) self.true_positives = _zero_wt_init(\"true_positives\") self.false_positives = _zero_wt_init(\"false_positives\") self.false_negatives", "\" \" + ' '.join(str(num) for num in embd) +", "Please \" \"train the model or reset the label mapping", ":param filename: Path to the embed file for loading :type", "a non-empty list of \" \"integers.\") else: for item in", "= str(param) + \" must be a string.\" errors.append(error) #", "or len(parameters[param]) == 0: errors.append(param + \" must be a", "if not isinstance(label_mapping, (list, dict)): raise TypeError(\"Labels must either be", "__init__(self, threshold_, num_labels_): super(ThreshArgMaxLayer, self).__init__() thresh_init = tf.constant_initializer(threshold_) self.thresh_vec =", "to n_dims principal components in a new file :param n_dims:", "to lists from numpy predictions_list = [i for i in", "= tf.cast(y_pred, self.dtype) def _weighted_sum(val, sample_weight): if sample_weight is not", "f1_score = mean * (1 + tf.math.square(self.beta)) if self.average ==", "BaseModel.__init__(self, label_mapping, parameters) def __eq__(self, other): \"\"\" Checks if two", "= ['PAD'] + label_mapping elif 0 not in label_mapping.values(): #", "accepted parameter.\") if errors: raise ValueError('\\n'.join(errors)) def set_label_mapping(self, label_mapping): \"\"\"", "range(max_char_encoding_id): if chr(ascii_num) in embedding_dict: embedding_matrix[ascii_num + 1] = embedding_dict[chr(ascii_num)]", "isinstance(beta, float): raise TypeError(\"The value of beta should be a", "threshold > 1.0 or threshold <= 0.0: raise ValueError(\"threshold should", "_weighted_sum((1 - y_pred) * y_true, sample_weight) ) self.weights_intermediate.assign_add(_weighted_sum(y_true, sample_weight)) def", "model. Must contain num_labels. Other possible parameters are: max_length, max_char_encoding_id,", "None f1_report = None if val_data is None: return f1,", "above threshold are considered to be 1, and the rest", "ValueError(\"threshold should be between 0 and 1\") self.num_classes = num_classes", "if f1_report else np.NAN epoch_time = time.time() - start_time logger.info(\"\\rEPOCH", "0.0: raise ValueError(\"beta value should be greater than zero\") if", "if not callable(tf_model): loaded_model._construct_model() tf1_weights = [] for var in", "matrix. class ThreshArgMaxLayer(tf.keras.layers.Layer): def __init__(self, threshold_, num_labels_): super(ThreshArgMaxLayer, self).__init__() thresh_init", "self._model = tf.keras.Model(self._model.inputs, argmax_outputs) # Compile the model softmax_output_layer_name =", "msg not in record.getMessage() tf_logger = logging.getLogger('tensorflow') tf_logger.addFilter(NoV1ResourceMessageFilter()) @tf.keras.utils.register_keras_serializable() class", "the default label pad_label: Key for entities_dict that is the", "f1_score_training]} self._model.compile(loss=losses, optimizer=\"adam\", metrics=metrics) self._epoch_id = 0 self._model_num_labels = num_labels", "the model :type label_mapping: dict :return: None \"\"\" if not", "in a new file :param n_dims: Final number of principal", "confidences_list = [i for i in range(0, allocation_index)] # Append", ":type verbose_keras: bool return (f1-score, f1 report). \"\"\" f1 =", "of data :type batch_size: int :param show_confidences: whether user wants", "(Optional) String name of the metric instance. dtype: (Optional) Data", "convolutional layers for fil in self._parameters['num_fil']: self._model.add(tf.keras.layers.Conv1D( filters=fil, kernel_size=self._parameters['size_conv'], activation='relu',", "user wants prediction confidences :type show_confidences: :param verbose: Flag to", "word, embd in zip(embd_words, reduced_embds): file.write(word + \" \" +", ":return: None \"\"\" if not self._model: self._construct_model() elif self._need_to_reconstruct_model(): self._reconstruct_model()", "for the model \"\"\" # Initialize the thresholds vector variable", ":type data: Union[list, numpy.ndarray] :param batch_size: number of samples in", "None. threshold: Elements of `y_pred` above threshold are considered to", "write to file dir_name = os.path.dirname(source_file) embd_file_name = os.path.join(dir_name, 'glove-reduced-{}D.txt'.format(n_dims))", "ThreshArgMaxLayer(tf.keras.layers.Layer): def __init__(self, threshold_, num_labels_): super(ThreshArgMaxLayer, self).__init__() thresh_init = tf.constant_initializer(threshold_)", "to be transferred. if not callable(tf_model): loaded_model._construct_model() tf1_weights = []", "None. beta: Determines the weight of precision and recall in", "of dropout in the model size_conv: Convolution kernel size default_label:", "model to :type dirpath: str :return: None \"\"\" if not", "the threshold # matrix. class ThreshArgMaxLayer(tf.keras.layers.Layer): def __init__(self, threshold_, num_labels_):", "def _validate_parameters(self, parameters): \"\"\" Validate the parameters sent in. Raise", "predict(self, data, batch_size=32, show_confidences=False, verbose=True): \"\"\" Run model and get", "def filter(self, record): msg = 'is a problem, consider rebuilding", "add one extra index for out-of-vocabulary character embed_file = os.path.join(", "missing PAD label_mapping = ['PAD'] + label_mapping elif 0 not", "\" \"greater than 0.\") elif param == 'dropout': if not", "None \"\"\" if not isinstance(label_mapping, (list, dict)): raise TypeError(\"Labels must", "loaded_model._model_default_ind = loaded_model.label_mapping[ loaded_model._parameters['default_label'] ] return loaded_model @staticmethod def _char_encoding_layer(input_str_tensor,", "self._construct_model() elif self._need_to_reconstruct_model(): self._reconstruct_model() model_param_dirpath = os.path.join(dirpath, \"model_parameters.json\") with open(model_param_dirpath,", "'default_label': if not isinstance(parameters[param], str): error = str(param) + \"", "= {softmax_output_layer_name: \"categorical_crossentropy\"} # use f1 score metric f1_score_training =", "self._model.add( tf.keras.layers.Lambda(encoding_function, output_shape=tuple([max_length]))) # Create a pre-trained weight matrix #", "kernel size default_label: Key for label_mapping that is the default", "not in var.name: tf1_weights.append(var.value()) loaded_model._construct_model() tf1_weights.append(loaded_model._model.weights[-1].value()) loaded_model._model.set_weights(tf1_weights) # load self", "not in record.getMessage() tf_logger = logging.getLogger('tensorflow') tf_logger.addFilter(NoV1ResourceMessageFilter()) @tf.keras.utils.register_keras_serializable() class FBetaScore(tf.keras.metrics.Metric):", "\"embeddings/glove-reduced-{}D.txt\".format( self._parameters['dim_embed'])) embedding_matrix = np.zeros((max_char_encoding_id + 2, self._parameters['dim_embed'])) embedding_dict =", "TypeError(\"The value of beta should be a python float\") if", "\"\"\" # Reset model tf.keras.backend.clear_session() num_labels = self.num_labels default_ind =", "create_glove_char(self._parameters['dim_embed']) # generate model self._model = tf.keras.models.Sequential() # default parameters", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "None: # [micro, macro] f1_score = tf.reduce_mean(f1_score) return f1_score def", "embd_words, embd_matrix = [ np.asarray(ls) if i > 0 else", "range from 0 to max_char_encoding_id, # we add one extra", "self.false_positives.assign_add( _weighted_sum(y_pred * (1 - y_true), sample_weight) ) self.false_negatives.assign_add( _weighted_sum((1", "= self._parameters['max_char_encoding_id'] # Encoding layer def encoding_function(input_str): char_in_vector = CharacterLevelCnnModel._char_encoding_layer(", "you want to load the model from :type dirpath: str", "copy.deepcopy(label_mapping) if 'PAD' not in label_mapping: if isinstance(label_mapping, list): #", "for the specific language governing permissions and # limitations under", "float \" \"greater than 0.\") elif param == 'dropout': if", "embedding table first and vectors as array embd_table = build_embd_dictionary(source_file)", "process in testing :type batch_size_test: int :param verbose_log: whether or", "language governing permissions and # limitations under the License. #", "ValueError(\"beta value should be greater than zero\") if threshold is", "-- \" \"val_f1: %f - val_precision: %f - val_recall %f\"", "using the function: final_predicted_layer = tf.add( bg_label_tf, tf.multiply( tf.subtract(argmax_layer, bg_label_tf),", "dict missing PAD and 0 label_mapping.update({'PAD': 0}) if (isinstance(label_mapping, dict)", "0s for ascii_num in range(max_char_encoding_id): if chr(ascii_num) in embedding_dict: embedding_matrix[ascii_num", "required by applicable law or agreed to in writing, software", "0)), mode='constant') sentence_lengths = np.pad( sentence_lengths, pad_width=((0, len(sentence_lengths)),), mode='constant') if", "'dim_embed', 'size_conv']: if not isinstance(parameters[param], (int, float)) \\ or parameters[param]", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "if not self._model: self._construct_model() else: if self._need_to_reconstruct_model(): self._reconstruct_model() if reset_weights:", "confidence layers final_predicted_layer = CharacterLevelCnnModel._argmax_threshold_layer( num_labels, threshold=0.0, default_ind=default_ind) argmax_outputs =", "is not None: self.set_label_mapping(label_mapping) if not self._model: self._construct_model() else: if", "given to the precision and recall. Default value is 1.", "_zero_wt_init(name): return self.add_weight( name, shape=self.init_shape, initializer=\"zeros\", dtype=self.dtype ) self.true_positives =", "= (1 + \\beta^2) * \\frac{\\textrm{precision} * \\textrm{precision}}{(\\beta^2 \\cdot \\textrm{precision})", "if self.average == \"weighted\": weights = tf.math.divide_no_nan( self.weights_intermediate, tf.reduce_sum(self.weights_intermediate) )", "extra index for out-of-vocabulary character embed_file = os.path.join( _file_dir, \"embeddings/glove-reduced-{}D.txt\".format(", "and return the evaluation metrics. :param val_data: data generator for", "threshold_at_argmax = tf.gather(self.thresh_vec, argmax_layer) confidence_max_layer = tf.keras.backend.max(confidence_layer, axis=2) # Check", "size default_label: Key for label_mapping that is the default label", "'pad_label', 'num_fil'] # Make sure the necessary parameters are present", "the weight given to the precision and recall. Default value", "= build_embd_dictionary(embed_file) input_shape = tuple([max_length]) # Fill in the weight", "dict containing the following parameters: max_length: Maximum char length in", "Validate the model on the test set and return the", "tensor containing encoded list of input sentences :rtype: tf.Tensor \"\"\"", "(%ds), loss: %f - acc: %f - f1_score %f --", "size_fc dropout, size_conv, num_fil, optimizer, default_label :type parameters: dict :return:", "float \" \"from 0 to 1.\") elif param == 'size_fc'", "Union[list, numpy.ndarray] :param batch_size: number of samples in the batch", "convolution layer :type parameters: dict :return: None \"\"\" errors =", "model :type label_mapping: dict :return: None \"\"\" if not isinstance(label_mapping,", "and the rest 0. If threshold is None, the argmax", "labels is altered :return: None \"\"\" # Reset model tf.keras.backend.clear_session()", "self.threshold = threshold self.axis = None self.init_shape = [] if", "\"micro\": self.axis = 0 self.init_shape = [self.num_classes] def _zero_wt_init(name): return", "agreed to in writing, software # distributed under the License", "\" must be a valid integer or float \" \"greater", "% (self._epoch_id, batch_id)) tf.keras.backend.set_floatx('float32') # Clean the predicted entities and", "int): errors.append(param + \" must be a non-empty \" \"list", "indices input_str_flatten = tf.reshape(input_str_tensor, [-1]) sentences_encode = tf.strings.unicode_decode(input_str_flatten, input_encoding='UTF-8') sentences_encode", "def details(self): \"\"\" Prints the relevant details of the model", "be greater than zero\") if threshold is not None: if", "distributed under the License is distributed on an \"AS IS\"", "return ThreshArgMaxLayer(threshold, num_labels) def _construct_model(self): \"\"\" Model constructor for the", "CharacterLevelCnnModel._argmax_threshold_layer( num_labels, threshold=0.0, default_ind=default_ind) argmax_outputs = [final_softmax_layer] + \\ [argmax_layer,", "the model into a .pb file for TensorFlow argmax_layer =", "AutoSubRegistrationMeta, BaseModel, BaseTrainableModel _file_dir = os.path.dirname(os.path.abspath(__file__)) logger = dp_logging.get_child_logger(__name__) class", "val = tf.math.multiply(val, tf.expand_dims(sample_weight, 1)) return tf.reduce_sum(val, axis=self.axis) self.true_positives.assign_add(_weighted_sum(y_pred *", "the model softmax_output_layer_name = self._model.outputs[0].name.split('/')[0] losses = {softmax_output_layer_name: \"categorical_crossentropy\"} #", "variables, i.e. may not check model itself. :param self: a", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # https://github.com/tensorflow/addons/blob/v0.12.0/LICENSE", "for word, embd in zip(embd_words, reduced_embds): file.write(word + \" \"", "reset the label mapping to \" \"predict.\") # Pre-allocate space", "in batch to prevent array mismatch num_samples_in_batch = len(batch_data) allocation_index", "dir_name = os.path.dirname(source_file) embd_file_name = os.path.join(dir_name, 'glove-reduced-{}D.txt'.format(n_dims)) with open(embd_file_name, 'w')", "np.pad( sentence_lengths, pad_width=((0, len(sentence_lengths)),), mode='constant') if show_confidences: confidences = np.pad(confidences,", "embedding create_glove_char(self._parameters['dim_embed']) # generate model self._model = tf.keras.models.Sequential() # default", "# dict with bad PAD raise ValueError(\"`PAD` must map to", "not :type reset_weights: bool :param verbose: Flag to determine whether", "integers :type label_mapping: dict :param parameters: Contains all the appropriate", "with batching allocation_index = 0 for batch_id, batch_data in enumerate(data):", "== 'default_label': if not isinstance(parameters[param], str): error = str(param) +", "average=None, beta=1.0, threshold=None, name=\"fbeta_score\", dtype=None, **kwargs): super().__init__(name=name, dtype=dtype) if average", "= tf.keras.layers.Dense( num_labels, activation='softmax', name=\"dense_2\")( self._model.layers[-4].output) # Output the model", "final_predicted_layer(argmax_layer, final_softmax_layer)] self._model = tf.keras.Model(self._model.inputs, argmax_outputs) # Compile the model", "if self._parameters['dropout']: self._model.add( tf.keras.layers.Dropout(self._parameters['dropout'])) # Add the final Softmax layer", "thrown in for param in parameters: if param not in", "return sentences_encode_pad @staticmethod def _argmax_threshold_layer(num_labels, threshold=0.0, default_ind=1): \"\"\" Adds an", "threshold: Elements of `y_pred` greater than threshold are converted to", "label_mapping = copy.deepcopy(label_mapping) if 'PAD' not in label_mapping: if isinstance(label_mapping,", "glove embedding create_glove_char(self._parameters['dim_embed']) # generate model self._model = tf.keras.models.Sequential() #", "keras. :type verbose_keras: bool return (f1-score, f1 report). \"\"\" f1", "print(\"\\n###### Model Details ######\\n\") self._model.summary() print(\"\\nModel Parameters:\") for key, value", "# get embedding table first and vectors as array embd_table", "= tf.keras.backend.max(confidence_layer, axis=2) # Check if the confidences meet the", "if self._need_to_reconstruct_model(): self._reconstruct_model() if reset_weights: self.reset_weights() history = defaultdict() f1", "activation='softmax')) # Output the model into a .pb file for", "time.time() batch_id = 0 for x_train, y_train in train_data: model_results", "where you want to save the model to :type dirpath:", "self._model.add(tf.keras.layers.Input(shape=(None,), dtype=tf.string)) self._model.add( tf.keras.layers.Lambda(encoding_function, output_shape=tuple([max_length]))) # Create a pre-trained weight", "missing PAD and 0 label_mapping.update({'PAD': 0}) if (isinstance(label_mapping, dict) and", "import decomposition from .. import dp_logging from . import labeler_utils", "isinstance(parameters[param], list) \\ or len(parameters[param]) == 0: errors.append(param + \"", "be 0s for ascii_num in range(max_char_encoding_id): if chr(ascii_num) in embedding_dict:", "i in range(0, allocation_index)] confidences_list = None if show_confidences: confidences_list", "batch of data :type batch_size: int :param show_confidences: whether user", "self._reconstruct_model() model_param_dirpath = os.path.join(dirpath, \"model_parameters.json\") with open(model_param_dirpath, 'w') as fp:", "'r') as fp: label_mapping = json.load(fp) # use f1 score", "create the threshold # matrix. class ThreshArgMaxLayer(tf.keras.layers.Layer): def __init__(self, threshold_,", "max_length) return char_in_vector self._model.add(tf.keras.layers.Input(shape=(None,), dtype=tf.string)) self._model.add( tf.keras.layers.Lambda(encoding_function, output_shape=tuple([max_length]))) # Create", "pad and space be 0s for ascii_num in range(max_char_encoding_id): if", "must exist in the \" \"label mapping.\".format( self._parameters['default_label'])) super().set_label_mapping(label_mapping) def", "argmax_layer = tf.keras.backend.argmax(final_softmax_layer) # Create confidence layers final_predicted_layer = CharacterLevelCnnModel._argmax_threshold_layer(", "= batch_id * batch_size # Double array size if len(predictions)", "to return prediction & confidence matrices for index, sentence_length \\", "matrix # character encoding indices range from 0 to max_char_encoding_id,", "self loaded_model._model_num_labels = loaded_model.num_labels loaded_model._model_default_ind = loaded_model.label_mapping[ loaded_model._parameters['default_label'] ] return", "metric instance. dtype: (Optional) Data type of the metric result.", "of the model. :return: None \"\"\" self._construct_model() def _reconstruct_model(self): \"\"\"", "appropriate layers if the number of number of labels is", "self.reverse_label_mapping, verbose=verbose_keras) return f1, f1_report def predict(self, data, batch_size=32, show_confidences=False,", "\"\"\" if not self._model: self._construct_model() elif self._need_to_reconstruct_model(): self._reconstruct_model() model_param_dirpath =", "raise ValueError('\\n'.join(errors)) def set_label_mapping(self, label_mapping): \"\"\" Sets the labels for", "index encodings or a list.\") label_mapping = copy.deepcopy(label_mapping) if 'PAD'", "= _zero_wt_init(\"false_negatives\") self.weights_intermediate = _zero_wt_init(\"weights_intermediate\") def update_state(self, y_true, y_pred, sample_weight=None):", "\"\"\" Validate the model on the test set and return", "if isinstance(label_mapping, list): # if list missing PAD label_mapping =", "otherwise it will be the default label index. :param num_labels:", ":return: None \"\"\" # load parameters model_param_dirpath = os.path.join(dirpath, \"model_parameters.json\")", "array embd_table = build_embd_dictionary(source_file) embd_words, embd_matrix = [ np.asarray(ls) if", "output layers (dense_2', 'tf_op_layer_ArgMax', # 'thresh_arg_max_layer') for _ in range(3):", "y_true = tf.cast(y_true, self.dtype) y_pred = tf.cast(y_pred, self.dtype) def _weighted_sum(val,", "layer :type parameters: dict :return: None \"\"\" errors = []", "TF2 warning for using TF1 model which has resources.\"\"\" def", "self._parameters['default_label'])) super().set_label_mapping(label_mapping) def _need_to_reconstruct_model(self): \"\"\" Determines whether or not the", "['PAD'] + label_mapping elif 0 not in label_mapping.values(): # if", "def __init__(self, label_mapping=None, parameters=None): \"\"\" CNN Model Initializer. initialize epoch_id", "parameters.setdefault('dim_embed', 64) parameters.setdefault('size_fc', [96, 96]) parameters.setdefault('dropout', 0.073) parameters.setdefault('size_conv', 13) parameters.setdefault('default_label',", "trainable=False) def call(self, argmax_layer, confidence_layer): threshold_at_argmax = tf.gather(self.thresh_vec, argmax_layer) confidence_max_layer", "# Append slices of predictions to return prediction & confidence", "\" \"integers.\") else: for item in parameters[param]: if not isinstance(item,", "# we add one extra index for out-of-vocabulary character embed_file", "<= 0.0: raise ValueError(\"beta value should be greater than zero\")", "int :param threshold: default set to 0 so all confidences", "list missing PAD label_mapping = ['PAD'] + label_mapping elif 0", "additional training. Please \" \"train the model or reset the", "BaseModel, BaseTrainableModel _file_dir = os.path.dirname(os.path.abspath(__file__)) logger = dp_logging.get_child_logger(__name__) class NoV1ResourceMessageFilter(logging.Filter):", "self._model: raise ValueError(\"You are trying to predict without a model.", "= tf.math.divide_no_nan( self.true_positives, self.true_positives + self.false_positives ) recall = tf.math.divide_no_nan(", "dirpath): \"\"\" Loads whole model from disk with weights :param", "OR CONDITIONS OF ANY KIND, either express or implied. #", "sure [0, 0, 0] doesn't become [1, 1, 1] #", "the parameters sent in. Raise error if invalid parameters are", "the License is distributed on an \"AS IS\" BASIS, #", "etc. :type verbose_log: bool :param verbose_keras: whether or not to", "axis=2) # Check if the confidences meet the threshold minimum.", "parameters: if param in ['max_length', 'max_char_encoding_id', 'dim_embed', 'size_conv']: if not", "the current model with the training data and validation data", "self._model_num_labels = 0 self._model_default_ind = -1 BaseModel.__init__(self, label_mapping, parameters) def", "model tf.keras.backend.clear_session() # generate glove embedding create_glove_char(self._parameters['dim_embed']) # generate model", "% (self._epoch_id, batch_id, *model_results[1:])) batch_id += 1 for i, metric_label", "None) != 0): # dict with bad PAD raise ValueError(\"`PAD`", "loss: %f - acc: %f - f1_score %f -- \"", "self._model.save(os.path.join(dirpath)) @classmethod def load_from_disk(cls, dirpath): \"\"\" Loads whole model from", "= tf.math.minimum(sentences_encode, max_char_encoding_id + 1) # padding sentences_encode_pad = sentences_encode.to_tensor(shape=[None,", "= 0 y_val_pred = [] y_val_test = [] for x_val,", "if 'training' not in var.name: tf1_weights.append(var.value()) loaded_model._construct_model() tf1_weights.append(loaded_model._model.weights[-1].value()) loaded_model._model.set_weights(tf1_weights) #", "\"\"\" CNN Model Initializer. initialize epoch_id :param label_mapping: maps labels", "+ label_mapping elif 0 not in label_mapping.values(): # if dict", "0 else list(ls) for i, ls in enumerate(zip(*embd_table.items()))] # get", "generate glove embedding create_glove_char(self._parameters['dim_embed']) # generate model self._model = tf.keras.models.Sequential()", "* \\frac{\\textrm{precision} * \\textrm{precision}}{(\\beta^2 \\cdot \\textrm{precision}) + \\textrm{recall}} $$ Args:", "activation='relu')) if self._parameters['dropout']: self._model.add( tf.keras.layers.Dropout(self._parameters['dropout'])) # Add the final Softmax", "enumerate(zip(*embd_table.items()))] # get PCA embedder pca = decomposition.PCA(n_components=n_dims) reduced_embds =", "not self._model: raise ValueError(\"You are trying to predict without a", "allocation_index: predictions = np.pad(predictions, ((0, len(predictions)), (0, 0)), mode='constant') sentence_lengths", "encoding dict \" \"which maps labels to index encodings or", "self._model.output)] self._model = tf.keras.Model(self._model.inputs, argmax_outputs) # Compile the model softmax_output_layer_name", "in a sample max_char_encoding_id: Maximum integer value for encoding the", "law or agreed to in writing, software # distributed under", "x_val, batch_size=batch_size_test, verbose=verbose_keras)[1]) y_val_test.append(np.argmax(y_val, axis=-1)) batch_id += 1 sys.stdout.flush() if", "String name of the metric instance. dtype: (Optional) Data type", "value should be greater than zero\") if threshold is not", "source_file=None): \"\"\" Embeds GloVe chars embeddings from source file to", "final_predicted_layer = CharacterLevelCnnModel._argmax_threshold_layer( num_labels, threshold=0.0, default_ind=default_ind) argmax_outputs = [final_softmax_layer] +", "embedding dictionary from embed file with GloVe-like format :param filename:", "for training, etc. :type verbose_log: bool :param verbose_keras: whether or", "Maximum char length in a sample :type max_len: int :return", "avg']['recall'] \\ if f1_report else np.NAN epoch_time = time.time() -", "# boolean if the label mapping requires the mapping for", "self.init_shape = [] if self.average != \"micro\": self.axis = 0", "num_classes: Number of unique classes in the dataset. average: Type", "equal :rtype: bool \"\"\" if self._parameters != other._parameters \\ or", "sentences_encode_pad @staticmethod def _argmax_threshold_layer(num_labels, threshold=0.0, default_ind=1): \"\"\" Adds an argmax", "weight matrix: let pad and space be 0s for ascii_num", "labels to index encodings or a list.\") label_mapping = copy.deepcopy(label_mapping)", "This layer's output will be the argmax value if the", "Location of original embeddings to factor down :type source_file: str", ":param parameters: parameter dict containing the following parameters: max_length: Maximum", "if label_mapping is not None: self.set_label_mapping(label_mapping) if not self._model: self._construct_model()", "not isinstance(item, int): errors.append(param + \" must be a non-empty", "y_val_test.append(np.argmax(y_val, axis=-1)) batch_id += 1 sys.stdout.flush() if verbose_log: sys.stdout.write(\"\\rEPOCH %g,", "be a non-empty list of \" \"integers.\") else: for item", "default_ind = self.label_mapping[self._parameters['default_label']] # Reset model tf.keras.backend.clear_session() # generate glove", "may obtain a copy of the License at # #", "0 or parameters[param] > 1: errors.append(param + \" must be", "class ThreshArgMaxLayer(tf.keras.layers.Layer): def __init__(self, threshold_, num_labels_): super(ThreshArgMaxLayer, self).__init__() thresh_init =", "# Compile the model softmax_output_layer_name = self._model.outputs[0].name.split('/')[0] losses = {softmax_output_layer_name:", "https://github.com/tensorflow/addons/blob/v0.12.0/LICENSE # # Unless required by applicable law or agreed", "the weighted harmonic mean of precision and recall. Output range", "sentences :rtype: tf.Tensor \"\"\" # convert characters to indices input_str_flatten", "sentences_encode = tf.math.minimum(sentences_encode, max_char_encoding_id + 1) # padding sentences_encode_pad =", "has resources.\"\"\" def filter(self, record): msg = 'is a problem,", "range(0, allocation_index)] confidences_list = None if show_confidences: confidences_list = [i", "'size_conv', 'default_label', 'pad_label', 'num_fil'] # Make sure the necessary parameters", "a model before predicting.\") elif self._need_to_reconstruct_model(): raise RuntimeError(\"The model label", "tf.tensor :param max_char_encoding_id: Maximum integer value for encoding the input", "val_data: iterator :param batch_size_test: Number of samples to process in", "Default value is None. threshold: Elements of `y_pred` above threshold", "in label_mapping.values(): # if dict missing PAD and 0 label_mapping.update({'PAD':", "not isinstance(parameters[param], list) \\ or len(parameters[param]) == 0: errors.append(param +", "os.path.join( _file_dir, \"embeddings/glove-reduced-{}D.txt\".format( self._parameters['dim_embed'])) embedding_matrix = np.zeros((max_char_encoding_id + 2, self._parameters['dim_embed']))", "beta <= 0.0: raise ValueError(\"beta value should be greater than", "numpy embedding dictionary from embed file with GloVe-like format :param", "0: errors.append(param + \" must be a valid integer or", "predicted output using the function: final_predicted_layer = tf.add( bg_label_tf, tf.multiply(", "may not use this file except in compliance with the", "whether or not the model needs to be reconstructed. :return:", "`weighted`. Default value is None. threshold: Elements of `y_pred` above", "# Add the final Softmax layer to the previous spot", "sample_weight) ) self.false_negatives.assign_add( _weighted_sum((1 - y_pred) * y_true, sample_weight) )", "_zero_wt_init(\"weights_intermediate\") def update_state(self, y_true, y_pred, sample_weight=None): if self.threshold is None:", "`macro` and `weighted`. Default value is None. threshold: Elements of", "this file except in compliance with the License. # You", "+ num_samples_in_batch] = model_output[0].numpy() predictions[allocation_index:allocation_index + num_samples_in_batch] = model_output[1].numpy() sentence_lengths[allocation_index:allocation_index", "self.true_positives, self.true_positives + self.false_negatives ) mul_value = precision * recall", "{softmax_output_layer_name: ['acc', f1_score_training]} self._model.compile(loss=losses, optimizer=\"adam\", metrics=metrics) self._epoch_id = 0 self._model_num_labels", "if there are extra parameters thrown in for param in", "parameters: dict :return: None \"\"\" # parameter initialization if not", "first and vectors as array embd_table = build_embd_dictionary(source_file) embd_words, embd_matrix", "the default label index. :param num_labels: number of entities :type", "default_ind def reset_weights(self): \"\"\" Reset the weights of the model.", "the test set and return the evaluation metrics. :param val_data:", "encoded integers :type label_mapping: dict :param parameters: Contains all the", "y_val in val_data: y_val_pred.append(self._model.predict( x_val, batch_size=batch_size_test, verbose=verbose_keras)[1]) y_val_test.append(np.argmax(y_val, axis=-1)) batch_id", "F_1 = 2 \\cdot \\frac{\\textrm{precision} \\cdot \\textrm{recall}}{\\textrm{precision} + \\textrm{recall}} $$", "Use abs(x) > eps, instead of x != 0 to", "bg_label_tf), argmax_mask ), name='ThreshArgMax' ) return final_predicted_layer return ThreshArgMaxLayer(threshold, num_labels)", "return loaded_model @staticmethod def _char_encoding_layer(input_str_tensor, max_char_encoding_id, max_len): \"\"\" Character encoding", "weight reset. :return: None \"\"\" num_labels = self.num_labels default_ind =", "Validate the parameters sent in. Raise error if invalid parameters", "verbose: bool :return: None \"\"\" if label_mapping is not None:", "of sentences :param input_str_tensor: input list of sentences converted to", "# # Licensed under the Apache License, Version 2.0 (the", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "in the weight matrix: let pad and space be 0s", "embed_file = os.path.join( _file_dir, \"embeddings/glove-reduced-{}D.txt\".format( self._parameters['dim_embed'])) embedding_matrix = np.zeros((max_char_encoding_id +", "contain num_labels. Other possible parameters are: max_length, max_char_encoding_id, dim_embed, size_fc", "name, shape=self.init_shape, initializer=\"zeros\", dtype=self.dtype ) self.true_positives = _zero_wt_init(\"true_positives\") self.false_positives =", ":param label_mapping: maps labels to their encoded integers :type label_mapping:", "final_predicted_layer = CharacterLevelCnnModel._argmax_threshold_layer( num_labels, threshold=0.0, default_ind=default_ind) argmax_outputs = self._model.outputs +", "y_pred) * y_true, sample_weight) ) self.weights_intermediate.assign_add(_weighted_sum(y_true, sample_weight)) def result(self): precision", "max_char_encoding_id + 1) # padding sentences_encode_pad = sentences_encode.to_tensor(shape=[None, max_len]) return", "- acc: %f - \" \"f1_score %f\" % (self._epoch_id, batch_id,", "def create_glove_char(n_dims, source_file=None): \"\"\" Embeds GloVe chars embeddings from source", "table first and vectors as array embd_table = build_embd_dictionary(source_file) embd_words,", "F-1 Score. # Copyright 2019 The TensorFlow Authors. All Rights", "import dp_logging from . import labeler_utils from .base_model import AutoSubRegistrationMeta,", "parameter dict containing the following parameters: max_length: Maximum char length", "default parameters max_length = self._parameters['max_length'] max_char_encoding_id = self._parameters['max_char_encoding_id'] # Encoding", "if chr(ascii_num) in embedding_dict: embedding_matrix[ascii_num + 1] = embedding_dict[chr(ascii_num)] self._model.add(tf.keras.layers.Embedding(", "class CharacterLevelCnnModel(BaseTrainableModel, metaclass=AutoSubRegistrationMeta): # boolean if the label mapping requires", "value is 1. threshold: Elements of `y_pred` greater than threshold", "where you want to load the model from :type dirpath:", "f1_report val_f1 = f1_report['weighted avg']['f1-score'] \\ if f1_report else np.NAN", "self.true_positives + self.false_negatives ) mul_value = precision * recall add_value", "def __init__(self, num_classes, average=None, threshold=None, name=\"f1_score\", dtype=None): super().__init__(num_classes, average, 1.0,", "self._model.add( tf.keras.layers.Dropout(self._parameters['dropout'])) # Add the final Softmax layer self._model.add( tf.keras.layers.Dense(num_labels,", "val_recall)) self._epoch_id += 1 return history, f1, f1_report def _validate_training(self,", "os import sys import time from collections import defaultdict import", "bool :param verbose_keras: whether or not to print out scores", "* recall add_value = (tf.math.square(self.beta) * precision) + recall mean", "for param in parameters: if param in ['max_length', 'max_char_encoding_id', 'dim_embed',", ":param batch_size_test: Number of samples to process in testing :type", "format :param filename: Path to the embed file for loading", "not None: # [micro, macro] f1_score = tf.reduce_mean(f1_score) return f1_score", "layer self._model.add( tf.keras.layers.Dense(num_labels, activation='softmax')) # Output the model into a", "not parameters: parameters = {} parameters.setdefault('max_length', 3400) parameters.setdefault('max_char_encoding_id', 127) parameters.setdefault('dim_embed',", "list of \" \"integers.\") else: for item in parameters[param]: if", ":param val_data: Validation data used to validate the training :type", "predictions_list} def details(self): \"\"\" Prints the relevant details of the", "on data. Acceptable values are `None`, `micro`, `macro` and `weighted`.", "in embd) + \"\\n\") class CharacterLevelCnnModel(BaseTrainableModel, metaclass=AutoSubRegistrationMeta): # boolean if", "= _zero_wt_init(\"false_positives\") self.false_negatives = _zero_wt_init(\"false_negatives\") self.weights_intermediate = _zero_wt_init(\"weights_intermediate\") def update_state(self,", "= os.path.join(dir_name, 'glove-reduced-{}D.txt'.format(n_dims)) with open(embd_file_name, 'w') as file: for word,", "Sets the labels for the model :param label_mapping: label mapping", "!= self._model_default_ind def save_to_disk(self, dirpath): \"\"\" Saves whole model to", ":type threshold: float :param default_ind: default index :type default_ind: int", "'dropout', 'size_conv', 'default_label', 'pad_label', 'num_fil'] # Make sure the necessary", "dirpath): \"\"\" Saves whole model to disk with weights :param", "print out scores for training, from keras. :type verbose_keras: bool", "sys.stdout.write(\"\\rEPOCH %g, validation_batch_id %d\" % (self._epoch_id, batch_id)) tf.keras.backend.set_floatx('float32') # Clean", "= np.zeros((batch_size, self._parameters['max_length'], self.num_labels)) # Run model with batching allocation_index", "in range(4)]) parameters['pad_label'] = 'PAD' self._epoch_id = 0 # reconstruct", "and the actual entities f1, f1_report = labeler_utils.evaluate_accuracy( np.concatenate(y_val_pred, axis=0),", "be a valid integer or float \" \"from 0 to", "If threshold is None, the argmax is converted to 1,", "average='micro') metrics = {softmax_output_layer_name: ['acc', f1_score_training]} self._model.compile(loss=losses, optimizer=\"adam\", metrics=metrics) self._epoch_id", "f1, f1_report def _validate_training(self, val_data, batch_size_test=32, verbose_log=True, verbose_keras=False): \"\"\" Validate", "recall. Output range is `[0, 1]`. Works for both multi-class", "0 to check for zero y_pred = tf.logical_and(y_pred >= threshold,", "+ 1] = embedding_dict[chr(ascii_num)] self._model.add(tf.keras.layers.Embedding( max_char_encoding_id + 2, self._parameters['dim_embed'], weights=[embedding_matrix],", "%f\" % (self._epoch_id, batch_id, *model_results[1:])) batch_id += 1 for i,", "%g, validation_batch_id %d\" % (self._epoch_id, batch_id)) tf.keras.backend.set_floatx('float32') # Clean the", "import labeler_utils from .base_model import AutoSubRegistrationMeta, BaseModel, BaseTrainableModel _file_dir =", "or implied. # See the License for the specific language", "default_ind=default_ind) argmax_outputs = self._model.outputs + \\ [argmax_layer, final_predicted_layer(argmax_layer, self._model.output)] self._model", "to print status or not :type verbose: bool :return: char", "weights :param dirpath: directory path where you want to save", "to file dir_name = os.path.dirname(source_file) embd_file_name = os.path.join(dir_name, 'glove-reduced-{}D.txt'.format(n_dims)) with", "epoch_time, *model_results[1:], val_f1, val_precision, val_recall)) self._epoch_id += 1 return history,", "data used to train model :type train_data: Union[list, np.ndarray] :param", "initialization if not parameters: parameters = {} parameters.setdefault('max_length', 3400) parameters.setdefault('max_char_encoding_id',", "of `y_pred` greater than threshold are converted to be 1,", "errors.append(error) # Error if there are extra parameters thrown in", "= 0 for batch_id, batch_data in enumerate(data): model_output = self._model(", "layers final_predicted_layer = CharacterLevelCnnModel._argmax_threshold_layer( num_labels, threshold=0.0, default_ind=default_ind) argmax_outputs = self._model.outputs", "data :type batch_size: int :param show_confidences: whether user wants prediction", "len(predictions)), (0, 0), (0, 0)), mode='constant') if show_confidences: confidences[allocation_index:allocation_index +", "127) parameters.setdefault('dim_embed', 64) parameters.setdefault('size_fc', [96, 96]) parameters.setdefault('dropout', 0.073) parameters.setdefault('size_conv', 13)", "\"embeddings/glove.840B.300d-char.txt\") # get embedding table first and vectors as array", "\\cdot \\frac{\\textrm{precision} \\cdot \\textrm{recall}}{\\textrm{precision} + \\textrm{recall}} $$ Args: num_classes: Number", "are converted to be 1, and the rest 0. If", ". import labeler_utils from .base_model import AutoSubRegistrationMeta, BaseModel, BaseTrainableModel _file_dir", "return True def _validate_parameters(self, parameters): \"\"\" Validate the parameters sent", "char length in a sample :type max_len: int :return :", "def update_state(self, y_true, y_pred, sample_weight=None): if self.threshold is None: threshold", "x_val, y_val in val_data: y_val_pred.append(self._model.predict( x_val, batch_size=batch_size_test, verbose=verbose_keras)[1]) y_val_test.append(np.argmax(y_val, axis=-1))", "= (tf.math.square(self.beta) * precision) + recall mean = tf.math.divide_no_nan(mul_value, add_value)", "self.weights_intermediate.assign_add(_weighted_sum(y_true, sample_weight)) def result(self): precision = tf.math.divide_no_nan( self.true_positives, self.true_positives +", "\"\"\" Model constructor for the data labeler. This also serves", "(self._epoch_id, epoch_time, *model_results[1:], val_f1, val_precision, val_recall)) self._epoch_id += 1 return", "number of principal component dims of the embeddings :type n_dims:", "self._model.summary() print(\"\\nModel Parameters:\") for key, value in self._parameters.items(): print(\"{}: {}\".format(key,", "the model (summary, parameters, label mapping) \"\"\" print(\"\\n###### Model Details", "label_mapping: if isinstance(label_mapping, list): # if list missing PAD label_mapping", "final predicted output using the function: final_predicted_layer = tf.add( bg_label_tf,", "in the \" \"label mapping.\".format( self._parameters['default_label'])) super().set_label_mapping(label_mapping) def _need_to_reconstruct_model(self): \"\"\"", "the number of number of labels is altered :return: None", "# Check if the confidences meet the threshold minimum. argmax_mask", "tf.keras.backend.constant( default_ind, dtype=argmax_layer.dtype) # Generate the final predicted output using", "\"greater than 0.\") elif param == 'dropout': if not isinstance(parameters[param],", "@classmethod def load_from_disk(cls, dirpath): \"\"\" Loads whole model from disk", "valid integer or float \" \"from 0 to 1.\") elif", "self._parameters['dim_embed'])) embedding_matrix = np.zeros((max_char_encoding_id + 2, self._parameters['dim_embed'])) embedding_dict = build_embd_dictionary(embed_file)", "confidences = [] sentence_lengths = np.zeros((batch_size,), dtype=int) predictions = np.zeros((batch_size,", "= os.path.join(_file_dir, \"embeddings/glove.840B.300d-char.txt\") # get embedding table first and vectors", "_construct_model(self): \"\"\" Model constructor for the data labeler. This also", "layer to the previous spot final_softmax_layer = tf.keras.layers.Dense( num_labels, activation='softmax',", "isinstance(parameters[param], str): error = str(param) + \" must be a", "embds: for line in embds: line = line.strip().split() embd_table[line[0]] =", "embd_table[line[0]] = np.asarray(line[1:]) return embd_table def create_glove_char(n_dims, source_file=None): \"\"\" Embeds", "_file_dir, \"embeddings/glove-reduced-{}D.txt\".format( self._parameters['dim_embed'])) embedding_matrix = np.zeros((max_char_encoding_id + 2, self._parameters['dim_embed'])) embedding_dict", "parameters) loaded_model._model = tf_model # Tensorflow v1 Model weights need", "sentences_encode = tf.add(tf.cast(1, tf.int32), sentences_encode) sentences_encode = tf.math.minimum(sentences_encode, max_char_encoding_id +", "f1_report # Predict on the test set batch_id = 0", "verbose=True): \"\"\" Train the current model with the training data", "to be performed on data. Acceptable values are `None`, `micro`,", "connected layers for size in self._parameters['size_fc']: self._model.add( tf.keras.layers.Dense(units=size, activation='relu')) if", "is None: threshold = tf.reduce_max(y_pred, axis=-1, keepdims=True) # make sure", "activation='relu', padding='same')) if self._parameters['dropout']: self._model.add( tf.keras.layers.Dropout(self._parameters['dropout'])) # Add batch normalization,", "the predicted entities and the actual entities f1, f1_report =", "get_config(self): \"\"\"Returns the serializable config of the metric.\"\"\" config =", "if the number of number of labels is altered :return:", "should be between 0 and 1\") self.num_classes = num_classes self.average", "# get PCA embedder pca = decomposition.PCA(n_components=n_dims) reduced_embds = pca.fit_transform(embd_matrix)", "+ ' '.join(str(num) for num in embd) + \"\\n\") class", "tf.constant_initializer(threshold_) self.thresh_vec = tf.Variable( name='ThreshVec', initial_value=thresh_init(shape=[num_labels_]), trainable=False) def call(self, argmax_layer,", "containing the following parameters: max_length: Maximum char length in a", "batch_size_test=32, verbose_log=True, verbose_keras=False): \"\"\" Validate the model on the test", "None if show_confidences: confidences_list = [i for i in range(0,", "Default value is 1. threshold: Elements of `y_pred` greater than", "or parameters[param] < 0 or parameters[param] > 1: errors.append(param +", "and multi-label classification. $$ F_1 = 2 \\cdot \\frac{\\textrm{precision} \\cdot", "# Clean the predicted entities and the actual entities f1,", "other: a model :type self: BaseModel :type other: BaseModel :return:", "the same size as the batch_size which # represents the", "self._model.add( tf.keras.layers.BatchNormalization(fused=False, scale=True)) # Add the fully connected layers for", "= time.time() - start_time logger.info(\"\\rEPOCH %d (%ds), loss: %f -", "list_of_necessary_params: errors.append(param + \" is not an accepted parameter.\") if", "of each fully connected layers dropout: Ratio of dropout in", ":param train_data: Training data used to train model :type train_data:", "model \"\"\" # Initialize the thresholds vector variable and create", "self.false_negatives ) mul_value = precision * recall add_value = (tf.math.square(self.beta)", "a non-empty encoding dict \" \"which maps labels to index", "space for predictions confidences = [] sentence_lengths = np.zeros((batch_size,), dtype=int)", "threshold=0.0, default_ind=default_ind) argmax_outputs = self._model.outputs + \\ [argmax_layer, final_predicted_layer(argmax_layer, self._model.output)]", "] return loaded_model @staticmethod def _char_encoding_layer(input_str_tensor, max_char_encoding_id, max_len): \"\"\" Character", "source_file = os.path.join(_file_dir, \"embeddings/glove.840B.300d-char.txt\") # get embedding table first and", "as file: for word, embd in zip(embd_words, reduced_embds): file.write(word +", "self.weights_intermediate = _zero_wt_init(\"weights_intermediate\") def update_state(self, y_true, y_pred, sample_weight=None): if self.threshold", "self._model: self._construct_model() elif self._need_to_reconstruct_model(): self._reconstruct_model() model_param_dirpath = os.path.join(dirpath, \"model_parameters.json\") with", "file for loading :type filename: str \"\"\" embd_table = dict()", "tf.keras.layers.Dense( num_labels, activation='softmax', name=\"dense_2\")( self._model.layers[-4].output) # Output the model into", ":type parameters: dict :return: None \"\"\" # parameter initialization if", "if the confidence for that argmax meets the threshold for", "char_in_vector = CharacterLevelCnnModel._char_encoding_layer( input_str, max_char_encoding_id, max_length) return char_in_vector self._model.add(tf.keras.layers.Input(shape=(None,), dtype=tf.string))", "@staticmethod def _char_encoding_layer(input_str_tensor, max_char_encoding_id, max_len): \"\"\" Character encoding for the", "= None self.init_shape = [] if self.average != \"micro\": self.axis", "= default_ind def fit(self, train_data, val_data=None, batch_size=32, label_mapping=None, reset_weights=False, verbose=True):", ":param dirpath: directory path where you want to save the", "embeddings to factor down :type source_file: str \"\"\" if source_file", "y_pred = tf.logical_and(y_pred >= threshold, tf.abs(y_pred) > 1e-12) else: y_pred", "a numpy embedding dictionary from embed file with GloVe-like format", "minimum. argmax_mask = tf.keras.backend.cast( tf.keras.backend.greater_equal(confidence_max_layer, threshold_at_argmax), dtype=argmax_layer.dtype) # Create a", "threshold are considered to be 1, and the rest 0.", "isinstance(threshold, float): raise TypeError(\"The value of threshold should be a", "score. Adapted and slightly modified from https://github.com/tensorflow/addons/blob/v0.12.0/tensorflow_addons/metrics/f_scores.py#L211-L283 # Copyright 2019", "train_data: model_results = self._model.train_on_batch( x_train, {softmax_output_layer_name: y_train}) sys.stdout.flush() if verbose:", "self._model.add( tf.keras.layers.Dense(num_labels, activation='softmax')) # Output the model into a .pb", "the model from :type dirpath: str :return: None \"\"\" #", "[] self._model.reset_metrics() softmax_output_layer_name = self._model.outputs[0].name.split('/')[0] start_time = time.time() batch_id =", "if not isinstance(beta, float): raise TypeError(\"The value of beta should", "json.load(fp) # load label_mapping labels_dirpath = os.path.join(dirpath, \"label_mapping.json\") with open(labels_dirpath,", "param == 'default_label': if not isinstance(parameters[param], str): error = str(param)", "test set and return the evaluation metrics. :param val_data: data", "print status or not :type verbose: bool :return: None \"\"\"", "len(predictions)), (0, 0)), mode='constant') sentence_lengths = np.pad( sentence_lengths, pad_width=((0, len(sentence_lengths)),),", "Flag to determine whether to reset the weights or not", "a list.\") label_mapping = copy.deepcopy(label_mapping) if 'PAD' not in label_mapping:", "in each convolution layer :type parameters: dict :return: None \"\"\"", "import json import logging import os import sys import time", "= list(map(lambda x: len(x[0]), batch_data)) allocation_index += num_samples_in_batch # Convert", "not the model needs to be reconstructed. :return: bool of", "argmax_mask ), name='ThreshArgMax' ) return final_predicted_layer return ThreshArgMaxLayer(threshold, num_labels) def", "\\ if f1_report else np.NAN val_recall = f1_report['weighted avg']['recall'] \\", "sample_weight)) self.false_positives.assign_add( _weighted_sum(y_pred * (1 - y_true), sample_weight) ) self.false_negatives.assign_add(", "num_classes, average=None, threshold=None, name=\"f1_score\", dtype=None): super().__init__(num_classes, average, 1.0, threshold, name=name,", "confidences = np.pad(confidences, ((0, len(predictions)), (0, 0), (0, 0)), mode='constant')", "scores for training, etc. :type verbose_log: bool :param verbose_keras: whether", "\"Construct/Load a model before predicting.\") elif self._need_to_reconstruct_model(): raise RuntimeError(\"The model", "n_dims: int :param source_file: Location of original embeddings to factor", "# Run model with batching allocation_index = 0 for batch_id,", "average self.beta = beta self.threshold = threshold self.axis = None", "1, and the rest 0. If threshold is None, the", "rest 0. name: (Optional) String name of the metric instance.", "get PCA embedder pca = decomposition.PCA(n_components=n_dims) reduced_embds = pca.fit_transform(embd_matrix) #", "============================================================================== It is the harmonic mean of precision and recall.", "np.asarray(line[1:]) return embd_table def create_glove_char(n_dims, source_file=None): \"\"\" Embeds GloVe chars", "{'pred': predictions_list} def details(self): \"\"\" Prints the relevant details of", "+= 1 sys.stdout.flush() if verbose_log: sys.stdout.write(\"\\rEPOCH %g, validation_batch_id %d\" %", "============================================================================== It is the weighted harmonic mean of precision and", "is None: source_file = os.path.join(_file_dir, \"embeddings/glove.840B.300d-char.txt\") # get embedding table", "predict without a model. \" \"Construct/Load a model before predicting.\")", "range(3): self._model.layers.pop() # Add the final Softmax layer to the", "\\textrm{precision}) + \\textrm{recall}} $$ Args: num_classes: Number of unique classes", "verbose_log: sys.stdout.write(\"\\rEPOCH %g, validation_batch_id %d\" % (self._epoch_id, batch_id)) tf.keras.backend.set_floatx('float32') #", ":type label_mapping: dict :return: None \"\"\" if not isinstance(label_mapping, (list,", "Raise error if invalid parameters are present. :param parameters: parameter", "recall in harmonic mean. Determines the weight given to the", "represents the background label bg_label_tf = tf.keras.backend.constant( default_ind, dtype=argmax_layer.dtype) #", "if source_file is None: source_file = os.path.join(_file_dir, \"embeddings/glove.840B.300d-char.txt\") # get", "'glove-reduced-{}D.txt'.format(n_dims)) with open(embd_file_name, 'w') as file: for word, embd in", "max_length: Maximum char length in a sample max_char_encoding_id: Maximum integer", "entities :type num_labels: int :param threshold: default set to 0", "(int, float)) \\ or parameters[param] < 0 or parameters[param] >", "self._validate_training(val_data) history['f1_report'] = f1_report val_f1 = f1_report['weighted avg']['f1-score'] \\ if", "between 0 and 1\") self.num_classes = num_classes self.average = average", "from .base_model import AutoSubRegistrationMeta, BaseModel, BaseTrainableModel _file_dir = os.path.dirname(os.path.abspath(__file__)) logger", "dp_logging from . import labeler_utils from .base_model import AutoSubRegistrationMeta, BaseModel,", "classification. $$ F_1 = 2 \\cdot \\frac{\\textrm{precision} \\cdot \\textrm{recall}}{\\textrm{precision} +", "3400) parameters.setdefault('max_char_encoding_id', 127) parameters.setdefault('dim_embed', 64) parameters.setdefault('size_fc', [96, 96]) parameters.setdefault('dropout', 0.073)", "> 1.0 or threshold <= 0.0: raise ValueError(\"threshold should be", "\"\"\" Run model and get predictions :param data: text input", "else: for item in parameters[param]: if not isinstance(item, int): errors.append(param", "int :return : tensor containing encoded list of input sentences", "'num_fil': if not isinstance(parameters[param], list) \\ or len(parameters[param]) == 0:", ":type parameters: dict :return: None \"\"\" errors = [] list_of_necessary_params", "$$ F_{\\beta} = (1 + \\beta^2) * \\frac{\\textrm{precision} * \\textrm{precision}}{(\\beta^2", "custom_objects = { \"F1Score\": F1Score( num_classes=max(label_mapping.values()) + 1, average='micro'), \"CharacterLevelCnnModel\":", "os.path.dirname(os.path.abspath(__file__)) logger = dp_logging.get_child_logger(__name__) class NoV1ResourceMessageFilter(logging.Filter): \"\"\"Removes TF2 warning for", "open(labels_dirpath, 'r') as fp: label_mapping = json.load(fp) # use f1", "label mapping to \" \"predict.\") # Pre-allocate space for predictions", "in writing, software # distributed under the License is distributed", "fp) self._model.save(os.path.join(dirpath)) @classmethod def load_from_disk(cls, dirpath): \"\"\" Loads whole model", ":return: char level predictions and confidences :rtype: dict \"\"\" if", "def _construct_model(self): \"\"\" Model constructor for the data labeler. This", "\"model_parameters.json\") with open(model_param_dirpath, 'w') as fp: json.dump(self._parameters, fp) labels_dirpath =", "# load parameters model_param_dirpath = os.path.join(dirpath, \"model_parameters.json\") with open(model_param_dirpath, 'r')", "0 label_mapping.update({'PAD': 0}) if (isinstance(label_mapping, dict) and label_mapping.get('PAD', None) !=", "# generate model self._model = tf.keras.models.Sequential() # default parameters max_length", "batch_size which # represents the background label bg_label_tf = tf.keras.backend.constant(", "= 0 # reconstruct flags for model self._model_num_labels = 0", "each batch :type batch_size: int :param label_mapping: maps labels to", "= [] if self.average != \"micro\": self.axis = 0 self.init_shape", "have been \" \"altered without additional training. Please \" \"train", "precision and recall. Default value is 1. threshold: Elements of", "model into a .pb file for TensorFlow argmax_layer = tf.keras.backend.argmax(final_softmax_layer)", "# ============================================================================== It is the weighted harmonic mean of precision", "index 0 reserved requires_zero_mapping = True def __init__(self, label_mapping=None, parameters=None):", "`macro` and `weighted`. Default value is None. beta: Determines the", "= mean * (1 + tf.math.square(self.beta)) if self.average == \"weighted\":", "msg = 'is a problem, consider rebuilding the SavedModel after", "sentences_encode) sentences_encode = tf.math.minimum(sentences_encode, max_char_encoding_id + 1) # padding sentences_encode_pad", "model. \" \"Construct/Load a model before predicting.\") elif self._need_to_reconstruct_model(): raise", "num_labels) def _construct_model(self): \"\"\" Model constructor for the data labeler.", "not isinstance(parameters[param], (int, float)) \\ or parameters[param] < 0 or", "the appropriate layers if the number of number of labels", "show_confidences: return {'pred': predictions_list, 'conf': confidences_list} return {'pred': predictions_list} def", "int :param verbose_log: whether or not to print out scores", "(summary, parameters, label mapping) \"\"\" print(\"\\n###### Model Details ######\\n\") self._model.summary()", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "val_precision = f1_report['weighted avg']['precision'] \\ if f1_report else np.NAN val_recall", "License, Version 2.0 (the \"License\"); # you may not use", "argmax_outputs = self._model.outputs + \\ [argmax_layer, final_predicted_layer(argmax_layer, self._model.output)] self._model =", "['max_length', 'max_char_encoding_id', 'dim_embed', 'size_fc', 'dropout', 'size_conv', 'default_label', 'pad_label', 'num_fil'] #", "weights or not :type reset_weights: bool :param verbose: Flag to", "= 0 self._model_default_ind = -1 BaseModel.__init__(self, label_mapping, parameters) def __eq__(self,", "%f - \" \"f1_score %f\" % (self._epoch_id, batch_id, *model_results[1:])) batch_id", "\"\"\" Saves whole model to disk with weights :param dirpath:", "Default value is None. beta: Determines the weight of precision", "n_dims: Final number of principal component dims of the embeddings", "else np.NAN epoch_time = time.time() - start_time logger.info(\"\\rEPOCH %d (%ds),", "batch normalization, set fused = True for compactness self._model.add( tf.keras.layers.BatchNormalization(fused=False,", "a model. \" \"Construct/Load a model before predicting.\") elif self._need_to_reconstruct_model():", "np import tensorflow as tf from sklearn import decomposition from", "= self._model.outputs[0].name.split('/')[0] losses = {softmax_output_layer_name: \"categorical_crossentropy\"} # use f1 score", "print status or not :type verbose: bool :return: char level", "in label_mapping: raise ValueError(\"The `default_label` of {} must exist in", "the metric result. Returns: F-1 Score: float. \"\"\" # Modification:", "considered to be 1, and the rest 0. If threshold", "Embeds GloVe chars embeddings from source file to n_dims principal", "for the model :param label_mapping: label mapping of the model", "val_data, batch_size_test=32, verbose_log=True, verbose_keras=False): \"\"\" Validate the model on the", "if show_confidences: return {'pred': predictions_list, 'conf': confidences_list} return {'pred': predictions_list}", "\" \"predict.\") # Pre-allocate space for predictions confidences = []", "dict) and label_mapping.get('PAD', None) != 0): # dict with bad", "of the metric instance. dtype: (Optional) Data type of the", "tf.math.square(self.beta)) if self.average == \"weighted\": weights = tf.math.divide_no_nan( self.weights_intermediate, tf.reduce_sum(self.weights_intermediate)", "index. :param num_labels: number of entities :type num_labels: int :param", "'running tf.compat.v1.enable_resource_variables()' return msg not in record.getMessage() tf_logger = logging.getLogger('tensorflow')", "precision) + recall mean = tf.math.divide_no_nan(mul_value, add_value) f1_score = mean", "the License for the specific language governing permissions and #", "\"label_mapping.json\") with open(labels_dirpath, 'r') as fp: label_mapping = json.load(fp) #", "\"\"\" self._construct_model() def _reconstruct_model(self): \"\"\" Reconstruct the appropriate layers if", "self.add_weight( name, shape=self.init_shape, initializer=\"zeros\", dtype=self.dtype ) self.true_positives = _zero_wt_init(\"true_positives\") self.false_positives", "y_train}) sys.stdout.flush() if verbose: sys.stdout.write( \"\\rEPOCH %d, batch_id %d: loss:", "not to print out scores for training, from keras. :type", "`weighted`. Default value is None. beta: Determines the weight of", "in label_mapping: if isinstance(label_mapping, list): # if list missing PAD", "Data type of the metric result. Returns: F-Beta Score: float.", "than threshold are converted to be 1, and the rest", "with open(model_param_dirpath, 'r') as fp: parameters = json.load(fp) # load", "[argmax_layer, final_predicted_layer(argmax_layer, self._model.output)] self._model = tf.keras.Model(self._model.inputs, argmax_outputs) # Compile the", "integers :type label_mapping: Union[dict, None] :param reset_weights: Flag to determine", "evaluation metrics. :param val_data: data generator for the validation :type", "label_mapping: Union[dict, None] :param reset_weights: Flag to determine whether to", "= [final_softmax_layer] + \\ [argmax_layer, final_predicted_layer(argmax_layer, final_softmax_layer)] self._model = tf.keras.Model(self._model.inputs,", "value if the confidence for that argmax meets the threshold", "bool return (f1-score, f1 report). \"\"\" f1 = None f1_report", "self.num_labels default_ind = self.label_mapping[self._parameters['default_label']] # Remove the 3 output layers", "(dense_2', 'tf_op_layer_ArgMax', # 'thresh_arg_max_layer') for _ in range(3): self._model.layers.pop() #", "if not isinstance(parameters[param], (int, float)) \\ or parameters[param] < 0", "# Output the model into a .pb file for TensorFlow", "ValueError(\"You are trying to predict without a model. \" \"Construct/Load", "max_length = self._parameters['max_length'] max_char_encoding_id = self._parameters['max_char_encoding_id'] # Encoding layer def", "parameters.setdefault('size_fc', [96, 96]) parameters.setdefault('dropout', 0.073) parameters.setdefault('size_conv', 13) parameters.setdefault('default_label', \"UNKNOWN\") parameters.setdefault('num_fil',", "output_shape=tuple([max_length]))) # Create a pre-trained weight matrix # character encoding", "self._model_default_ind def save_to_disk(self, dirpath): \"\"\" Saves whole model to disk", "tf.keras.models.load_model(dirpath) loaded_model = cls(label_mapping, parameters) loaded_model._model = tf_model # Tensorflow", "= dp_logging.get_child_logger(__name__) class NoV1ResourceMessageFilter(logging.Filter): \"\"\"Removes TF2 warning for using TF1", "!= other._label_mapping: return False return True def _validate_parameters(self, parameters): \"\"\"", "'size_fc', 'dropout', 'size_conv', 'default_label', 'pad_label', 'num_fil'] # Make sure the", "tuple([max_length]) # Fill in the weight matrix: let pad and", "which # represents the background label bg_label_tf = tf.keras.backend.constant( default_ind,", "= F1Score(num_classes=num_labels, average='micro') metrics = {softmax_output_layer_name: ['acc', f1_score_training]} self._model.compile(loss=losses, optimizer=\"adam\",", "-1 BaseModel.__init__(self, label_mapping, parameters) def __eq__(self, other): \"\"\" Checks if", "np.pad(confidences, ((0, len(predictions)), (0, 0), (0, 0)), mode='constant') if show_confidences:", "# http://www.apache.org/licenses/LICENSE-2.0 # https://github.com/tensorflow/addons/blob/v0.12.0/LICENSE # # Unless required by applicable", "# Reset model tf.keras.backend.clear_session() num_labels = self.num_labels default_ind = self.label_mapping[self._parameters['default_label']]", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "labeler. This also serves as a weight reset. :return: None", "self._epoch_id = 0 # reconstruct flags for model self._model_num_labels =", "to :type dirpath: str :return: None \"\"\" if not self._model:", "'w') as fp: json.dump(self.label_mapping, fp) self._model.save(os.path.join(dirpath)) @classmethod def load_from_disk(cls, dirpath):", "show_confidences: :param verbose: Flag to determine whether to print status", "# Add the final Softmax layer self._model.add( tf.keras.layers.Dense(num_labels, activation='softmax')) #", "(int, float)) \\ or parameters[param] < 0: errors.append(param + \"", "logger = dp_logging.get_child_logger(__name__) class NoV1ResourceMessageFilter(logging.Filter): \"\"\"Removes TF2 warning for using", "= self.label_mapping[self._parameters['default_label']] return self.num_labels != self._model_num_labels or \\ default_ind !=", "to index zero.\") if self._parameters['default_label'] not in label_mapping: raise ValueError(\"The", "len(sentence_lengths)),), mode='constant') if show_confidences: confidences = np.pad(confidences, ((0, len(predictions)), (0,", "label_mapping: dict :param parameters: Contains all the appropriate parameters for", "the model to :type dirpath: str :return: None \"\"\" if", "= np.asarray(line[1:]) return embd_table def create_glove_char(n_dims, source_file=None): \"\"\" Embeds GloVe", "False return True def _validate_parameters(self, parameters): \"\"\" Validate the parameters", ":type reset_weights: bool :param verbose: Flag to determine whether to", "CharacterLevelCnnModel._argmax_threshold_layer( num_labels, threshold=0.0, default_ind=default_ind) argmax_outputs = self._model.outputs + \\ [argmax_layer,", "of \" \"integers.\") else: for item in parameters[param]: if not", "in zip(embd_words, reduced_embds): file.write(word + \" \" + ' '.join(str(num)", ": tensor containing encoded list of input sentences :rtype: tf.Tensor", "_weighted_sum(val, sample_weight): if sample_weight is not None: val = tf.math.multiply(val,", "# distributed under the License is distributed on an \"AS", "slightly modified from https://github.com/tensorflow/addons/blob/v0.12.0/tensorflow_addons/metrics/f_scores.py#L211-L283 # Copyright 2019 The TensorFlow Authors.", "# Unless required by applicable law or agreed to in", "name=name, dtype=dtype) def get_config(self): base_config = super().get_config() del base_config[\"beta\"] return", "True def _validate_parameters(self, parameters): \"\"\" Validate the parameters sent in.", "following parameters: max_length: Maximum char length in a sample max_char_encoding_id:", "for out-of-vocabulary character embed_file = os.path.join( _file_dir, \"embeddings/glove-reduced-{}D.txt\".format( self._parameters['dim_embed'])) embedding_matrix", "# reconstruct flags for model self._model_num_labels = 0 self._model_default_ind =", "relevant details of the model (summary, parameters, label mapping) \"\"\"", "sure the necessary parameters are present and valid. for param", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "import AutoSubRegistrationMeta, BaseModel, BaseTrainableModel _file_dir = os.path.dirname(os.path.abspath(__file__)) logger = dp_logging.get_child_logger(__name__)", "\"CharacterLevelCnnModel\": cls, } with tf.keras.utils.custom_object_scope(custom_objects): tf_model = tf.keras.models.load_model(dirpath) loaded_model =", "source_file is None: source_file = os.path.join(_file_dir, \"embeddings/glove.840B.300d-char.txt\") # get embedding", "elif param == 'size_fc' or param == 'num_fil': if not", "super().get_config() return {**base_config, **config} def reset_states(self): reset_value = tf.zeros(self.init_shape, dtype=self.dtype)", "default_ind: default index :type default_ind: int :return: final argmax threshold", "before predicting.\") elif self._need_to_reconstruct_model(): raise RuntimeError(\"The model label mapping definitions", "that argmax meets the threshold for its label, otherwise it", "encoding the input dim_embed: Number of embedded dimensions size_fc: Size", "1 return history, f1, f1_report def _validate_training(self, val_data, batch_size_test=32, verbose_log=True,", "save_to_disk(self, dirpath): \"\"\" Saves whole model to disk with weights", "out scores for training, from keras. :type verbose_keras: bool return", "Copyright 2019 The TensorFlow Authors. All Rights Reserved. # #", "1, and the rest 0. name: (Optional) String name of", "= cls(label_mapping, parameters) loaded_model._model = tf_model # Tensorflow v1 Model", "default_label: Key for label_mapping that is the default label pad_label:", "are extra parameters thrown in for param in parameters: if", "for using TF1 model which has resources.\"\"\" def filter(self, record):", "if reset_weights: self.reset_weights() history = defaultdict() f1 = None f1_report", "verbose: bool :return: char level predictions and confidences :rtype: dict", "Works for both multi-class and multi-label classification. $$ F_{\\beta} =", "the Apache License, Version 2.0 (the \"License\"); # you may", "), name='ThreshArgMax' ) return final_predicted_layer return ThreshArgMaxLayer(threshold, num_labels) def _construct_model(self):", "performed on data. Acceptable values are `None`, `micro`, `macro` and", "for encoding the input dim_embed: Number of embedded dimensions size_fc:", "encoded integers :type label_mapping: Union[dict, None] :param reset_weights: Flag to", "and space be 0s for ascii_num in range(max_char_encoding_id): if chr(ascii_num)", "confidences to lists from numpy predictions_list = [i for i", ":param self: a model :param other: a model :type self:", "self.axis = None self.init_shape = [] if self.average != \"micro\":", "that is the pad label num_fil: Number of filters in", "\"integers.\") else: for item in parameters[param]: if not isinstance(item, int):", ":type label_mapping: Union[dict, None] :param reset_weights: Flag to determine whether", "raise RuntimeError(\"The model label mapping definitions have been \" \"altered", "the test set batch_id = 0 y_val_pred = [] y_val_test", "char length in a sample max_char_encoding_id: Maximum integer value for", "\"label_mapping.json\") with open(labels_dirpath, 'w') as fp: json.dump(self.label_mapping, fp) self._model.save(os.path.join(dirpath)) @classmethod", "y_pred = y_pred > self.threshold y_true = tf.cast(y_true, self.dtype) y_pred", "load self loaded_model._model_num_labels = loaded_model.num_labels loaded_model._model_default_ind = loaded_model.label_mapping[ loaded_model._parameters['default_label'] ]", "i in range(0, allocation_index)] # Append slices of predictions to", "This also serves as a weight reset. :return: None \"\"\"", "for entities_dict that is the pad label num_fil: Number of", "Check if the confidences meet the threshold minimum. argmax_mask =", "open(model_param_dirpath, 'w') as fp: json.dump(self._parameters, fp) labels_dirpath = os.path.join(dirpath, \"label_mapping.json\")", "the model or reset the label mapping to \" \"predict.\")", "= tf.constant_initializer(threshold_) self.thresh_vec = tf.Variable( name='ThreshVec', initial_value=thresh_init(shape=[num_labels_]), trainable=False) def call(self,", "fp) labels_dirpath = os.path.join(dirpath, \"label_mapping.json\") with open(labels_dirpath, 'w') as fp:", "\"\"\" # Modification: remove the run-time type checking for functions", "= list(confidences[index][:sentence_length]) if show_confidences: return {'pred': predictions_list, 'conf': confidences_list} return", ":param num_labels: number of entities :type num_labels: int :param threshold:", "show_confidences=False, verbose=True): \"\"\" Run model and get predictions :param data:", "Returns: F-1 Score: float. \"\"\" # Modification: remove the run-time", "self._label_mapping != other._label_mapping: return False return True def _validate_parameters(self, parameters):", "tf.keras.backend.set_floatx('float32') # Clean the predicted entities and the actual entities", "size_conv: Convolution kernel size default_label: Key for label_mapping that is", "'micro', 'macro', 'weighted']\" ) if not isinstance(beta, float): raise TypeError(\"The", "return history, f1, f1_report def _validate_training(self, val_data, batch_size_test=32, verbose_log=True, verbose_keras=False):", "predictions = np.pad(predictions, ((0, len(predictions)), (0, 0)), mode='constant') sentence_lengths =", "confidences :rtype: dict \"\"\" if not self._model: raise ValueError(\"You are", "self._model.outputs[0].name.split('/')[0] losses = {softmax_output_layer_name: \"categorical_crossentropy\"} # use f1 score metric", "\"train the model or reset the label mapping to \"", "\"\"\" Prints the relevant details of the model (summary, parameters,", "- acc: %f - f1_score %f -- \" \"val_f1: %f", "%f\" % (self._epoch_id, epoch_time, *model_results[1:], val_f1, val_precision, val_recall)) self._epoch_id +=", "base_config[\"beta\"] return base_config def build_embd_dictionary(filename): \"\"\" Returns a numpy embedding", "model needs to reconstruct. \"\"\" if not self._model: return False", "weight given to the precision and recall. Default value is", "fused = True for compactness self._model.add( tf.keras.layers.BatchNormalization(fused=False, scale=True)) # Add", "if threshold > 1.0 or threshold <= 0.0: raise ValueError(\"threshold", ":param max_char_encoding_id: Maximum integer value for encoding the input :type", "threshold should be a python float\") if threshold > 1.0", "meet the threshold minimum. argmax_mask = tf.keras.backend.cast( tf.keras.backend.greater_equal(confidence_max_layer, threshold_at_argmax), dtype=argmax_layer.dtype)", "default_ind, dtype=argmax_layer.dtype) # Generate the final predicted output using the", "None, the argmax is converted to 1, and the rest", "check important variables, i.e. may not check model itself. :param", "and vectors as array embd_table = build_embd_dictionary(source_file) embd_words, embd_matrix =", "functions def __init__(self, num_classes, average=None, threshold=None, name=\"f1_score\", dtype=None): super().__init__(num_classes, average,", "@tf.keras.utils.register_keras_serializable() class FBetaScore(tf.keras.metrics.Metric): r\"\"\"Computes F-Beta score. Adapted and slightly modified", "encoding_function(input_str): char_in_vector = CharacterLevelCnnModel._char_encoding_layer( input_str, max_char_encoding_id, max_length) return char_in_vector self._model.add(tf.keras.layers.Input(shape=(None,),", "tf.math.divide_no_nan( self.true_positives, self.true_positives + self.false_positives ) recall = tf.math.divide_no_nan( self.true_positives,", "of the metric result. Returns: F-Beta Score: float. \"\"\" #", "is not None: if not isinstance(threshold, float): raise TypeError(\"The value", "= tf.math.divide_no_nan( self.true_positives, self.true_positives + self.false_negatives ) mul_value = precision", "padding sentences_encode_pad = sentences_encode.to_tensor(shape=[None, max_len]) return sentences_encode_pad @staticmethod def _argmax_threshold_layer(num_labels,", "if verbose_log: sys.stdout.write(\"\\rEPOCH %g, validation_batch_id %d\" % (self._epoch_id, batch_id)) tf.keras.backend.set_floatx('float32')", "self.true_positives + self.false_positives ) recall = tf.math.divide_no_nan( self.true_positives, self.true_positives +", ":return: None \"\"\" errors = [] list_of_necessary_params = ['max_length', 'max_char_encoding_id',", "label_mapping): \"\"\" Sets the labels for the model :param label_mapping:", "default label pad_label: Key for entities_dict that is the pad", ") recall = tf.math.divide_no_nan( self.true_positives, self.true_positives + self.false_negatives ) mul_value", "tf.keras.layers.BatchNormalization(fused=False, scale=True)) # Add the fully connected layers for size", "F-Beta score. Adapted and slightly modified from https://github.com/tensorflow/addons/blob/v0.12.0/tensorflow_addons/metrics/f_scores.py#L211-L283 # Copyright", "%f - val_recall %f\" % (self._epoch_id, epoch_time, *model_results[1:], val_f1, val_precision,", "if show_confidences: confidences[allocation_index:allocation_index + num_samples_in_batch] = model_output[0].numpy() predictions[allocation_index:allocation_index + num_samples_in_batch]", "if not self._model: self._construct_model() elif self._need_to_reconstruct_model(): self._reconstruct_model() model_param_dirpath = os.path.join(dirpath,", "is 1. threshold: Elements of `y_pred` greater than threshold are", "be 1, and the rest 0. If threshold is None,", "> 0 else list(ls) for i, ls in enumerate(zip(*embd_table.items()))] #", "+ \" is not an accepted parameter.\") if errors: raise", "under the License is distributed on an \"AS IS\" BASIS,", "\\beta^2) * \\frac{\\textrm{precision} * \\textrm{precision}}{(\\beta^2 \\cdot \\textrm{precision}) + \\textrm{recall}} $$", "weights of the model. :return: None \"\"\" self._construct_model() def _reconstruct_model(self):", "warning for using TF1 model which has resources.\"\"\" def filter(self,", "\"model_parameters.json\") with open(model_param_dirpath, 'r') as fp: parameters = json.load(fp) #", "np.ndarray] :param val_data: Validation data used to validate the training", "epoch_time = time.time() - start_time logger.info(\"\\rEPOCH %d (%ds), loss: %f", "list(map(lambda x: len(x[0]), batch_data)) allocation_index += num_samples_in_batch # Convert predictions,", "default_ind: int :return: final argmax threshold layer for the model", "y_pred > self.threshold y_true = tf.cast(y_true, self.dtype) y_pred = tf.cast(y_pred,", "num_fil, optimizer, default_label :type parameters: dict :return: None \"\"\" #", "dims of the embeddings :type n_dims: int :param source_file: Location", "= os.path.join(dirpath, \"label_mapping.json\") with open(labels_dirpath, 'w') as fp: json.dump(self.label_mapping, fp)", "param == 'size_fc' or param == 'num_fil': if not isinstance(parameters[param],", "all the appropriate parameters for the model. Must contain num_labels.", "for i in range(0, allocation_index)] confidences_list = None if show_confidences:", "%f -- \" \"val_f1: %f - val_precision: %f - val_recall", "mean = tf.math.divide_no_nan(mul_value, add_value) f1_score = mean * (1 +", "threshold # matrix. class ThreshArgMaxLayer(tf.keras.layers.Layer): def __init__(self, threshold_, num_labels_): super(ThreshArgMaxLayer,", "mode='constant') sentence_lengths = np.pad( sentence_lengths, pad_width=((0, len(sentence_lengths)),), mode='constant') if show_confidences:", "# Add batch normalization, set fused = True for compactness", "= True for compactness self._model.add( tf.keras.layers.BatchNormalization(fused=False, scale=True)) # Add the", "f1_report else np.NAN val_precision = f1_report['weighted avg']['precision'] \\ if f1_report", "\"\"\" embd_table = dict() with open(filename, 'r') as embds: for", "the evaluation metrics. :param val_data: data generator for the validation", "None \"\"\" # parameter initialization if not parameters: parameters =", "or not self and other are equal :rtype: bool \"\"\"", "for the validation :type val_data: iterator :param batch_size_test: Number of", ":type dirpath: str :return: None \"\"\" # load parameters model_param_dirpath", "the argmax is converted to 1, and the rest 0.", "sentences :param input_str_tensor: input list of sentences converted to tensor", "Training data used to train model :type train_data: Union[list, np.ndarray]", "labels_dirpath = os.path.join(dirpath, \"label_mapping.json\") with open(labels_dirpath, 'w') as fp: json.dump(self.label_mapping,", "os.path.join(dirpath, \"model_parameters.json\") with open(model_param_dirpath, 'r') as fp: parameters = json.load(fp)", "kernel_size=self._parameters['size_conv'], activation='relu', padding='same')) if self._parameters['dropout']: self._model.add( tf.keras.layers.Dropout(self._parameters['dropout'])) # Add batch", "> eps, instead of x != 0 to check for", "not None: val = tf.math.multiply(val, tf.expand_dims(sample_weight, 1)) return tf.reduce_sum(val, axis=self.axis)", "threshold is not None: if not isinstance(threshold, float): raise TypeError(\"The", "None \"\"\" # Reset model tf.keras.backend.clear_session() num_labels = self.num_labels default_ind", "labels_dirpath = os.path.join(dirpath, \"label_mapping.json\") with open(labels_dirpath, 'r') as fp: label_mapping", "self._parameters['num_fil']: self._model.add(tf.keras.layers.Conv1D( filters=fil, kernel_size=self._parameters['size_conv'], activation='relu', padding='same')) if self._parameters['dropout']: self._model.add( tf.keras.layers.Dropout(self._parameters['dropout']))", "prediction confidences :type show_confidences: :param verbose: Flag to determine whether", "return (f1-score, f1 report). \"\"\" f1 = None f1_report =", "self._model( tf.convert_to_tensor(batch_data) ) # Count number of samples in batch", "for v in self.variables]) @tf.keras.utils.register_keras_serializable() class F1Score(FBetaScore): r\"\"\"Computes F-1 Score.", "tf.keras.backend.argmax(final_softmax_layer) # Create confidence layers final_predicted_layer = CharacterLevelCnnModel._argmax_threshold_layer( num_labels, threshold=0.0,", "of sentences converted to tensor :type input_str_tensor: tf.tensor :param max_char_encoding_id:", "parameters sent in. Raise error if invalid parameters are present.", "return char_in_vector self._model.add(tf.keras.layers.Input(shape=(None,), dtype=tf.string)) self._model.add( tf.keras.layers.Lambda(encoding_function, output_shape=tuple([max_length]))) # Create a", "zero.\") if self._parameters['default_label'] not in label_mapping: raise ValueError(\"The `default_label` of", "= np.zeros((max_char_encoding_id + 2, self._parameters['dim_embed'])) embedding_dict = build_embd_dictionary(embed_file) input_shape =", "self.num_classes, \"average\": self.average, \"beta\": self.beta, \"threshold\": self.threshold, } base_config =", "np.zeros((batch_size, self._parameters['max_length'])) if show_confidences: confidences = np.zeros((batch_size, self._parameters['max_length'], self.num_labels)) #", "1] # Use abs(x) > eps, instead of x !=", "\"\"\" Reset the weights of the model. :return: None \"\"\"", "of the model :type label_mapping: dict :return: None \"\"\" if", "num_samples_in_batch = len(batch_data) allocation_index = batch_id * batch_size # Double", "let pad and space be 0s for ascii_num in range(max_char_encoding_id):", "num_classes self.average = average self.beta = beta self.threshold = threshold", "= 2 \\cdot \\frac{\\textrm{precision} \\cdot \\textrm{recall}}{\\textrm{precision} + \\textrm{recall}} $$ Args:", "as fp: json.dump(self.label_mapping, fp) self._model.save(os.path.join(dirpath)) @classmethod def load_from_disk(cls, dirpath): \"\"\"", "the model. Must contain num_labels. Other possible parameters are: max_length,", "history, f1, f1_report def _validate_training(self, val_data, batch_size_test=32, verbose_log=True, verbose_keras=False): \"\"\"", "+ \\ [argmax_layer, final_predicted_layer(argmax_layer, final_softmax_layer)] self._model = tf.keras.Model(self._model.inputs, argmax_outputs) #", "f1_report = self._validate_training(val_data) history['f1_report'] = f1_report val_f1 = f1_report['weighted avg']['f1-score']", "embds: line = line.strip().split() embd_table[line[0]] = np.asarray(line[1:]) return embd_table def", "= tf.cast(y_true, self.dtype) y_pred = tf.cast(y_pred, self.dtype) def _weighted_sum(val, sample_weight):", "valid integer or float \" \"greater than 0.\") elif param", "parameters: parameters = {} parameters.setdefault('max_length', 3400) parameters.setdefault('max_char_encoding_id', 127) parameters.setdefault('dim_embed', 64)", "the actual entities f1, f1_report = labeler_utils.evaluate_accuracy( np.concatenate(y_val_pred, axis=0), np.concatenate(y_val_test,", "\"\"\" num_labels = self.num_labels default_ind = self.label_mapping[self._parameters['default_label']] # Reset model", "ANY KIND, either express or implied. # See the License", ":type source_file: str \"\"\" if source_file is None: source_file =", "decomposition.PCA(n_components=n_dims) reduced_embds = pca.fit_transform(embd_matrix) # write to file dir_name =", "tf.Tensor \"\"\" # convert characters to indices input_str_flatten = tf.reshape(input_str_tensor,", "self._parameters['dropout']: self._model.add( tf.keras.layers.Dropout(self._parameters['dropout'])) # Add batch normalization, set fused =", "Validation data used to validate the training :type val_data: Union[list,", "the License. # You may obtain a copy of the", "if self.average != \"micro\": self.axis = 0 self.init_shape = [self.num_classes]", "to save the model to :type dirpath: str :return: None", "activation='softmax', name=\"dense_2\")( self._model.layers[-4].output) # Output the model into a .pb", "batching allocation_index = 0 for batch_id, batch_data in enumerate(data): model_output", "`default_label` of {} must exist in the \" \"label mapping.\".format(", "if the label mapping requires the mapping for index 0", "f1_score = tf.reduce_sum(f1_score * weights) elif self.average is not None:", "tf.keras.models.Sequential() # default parameters max_length = self._parameters['max_length'] max_char_encoding_id = self._parameters['max_char_encoding_id']", "# See the License for the specific language governing permissions", "for predictions confidences = [] sentence_lengths = np.zeros((batch_size,), dtype=int) predictions", "os.path.join(dir_name, 'glove-reduced-{}D.txt'.format(n_dims)) with open(embd_file_name, 'w') as file: for word, embd", "Make sure the necessary parameters are present and valid. for", "for var in tf_model.variables: if 'training' not in var.name: tf1_weights.append(var.value())", "self.threshold, } base_config = super().get_config() return {**base_config, **config} def reset_states(self):", "not in label_mapping: if isinstance(label_mapping, list): # if list missing", "final Softmax layer to the previous spot final_softmax_layer = tf.keras.layers.Dense(", "show_confidences: confidences_list = [i for i in range(0, allocation_index)] #", "data: Union[list, numpy.ndarray] :param batch_size: number of samples in the", "(f1-score, f1 report). \"\"\" f1 = None f1_report = None", "name: (Optional) String name of the metric instance. dtype: (Optional)", "on the test set batch_id = 0 y_val_pred = []", "set and return the evaluation metrics. :param val_data: data generator", "None: threshold = tf.reduce_max(y_pred, axis=-1, keepdims=True) # make sure [0,", "self._model_num_labels = num_labels self._model_default_ind = default_ind def fit(self, train_data, val_data=None,", "epoch_id :param label_mapping: maps labels to their encoded integers :type", "= default_ind def reset_weights(self): \"\"\" Reset the weights of the", "item in parameters[param]: if not isinstance(item, int): errors.append(param + \"", "label_mapping.get('PAD', None) != 0): # dict with bad PAD raise", "save the model to :type dirpath: str :return: None \"\"\"", "None: source_file = os.path.join(_file_dir, \"embeddings/glove.840B.300d-char.txt\") # get embedding table first", "!= 0 to check for zero y_pred = tf.logical_and(y_pred >=", "the metric result. Returns: F-Beta Score: float. \"\"\" # Modification:", "set batch_id = 0 y_val_pred = [] y_val_test = []", "average: Type of averaging to be performed on data. Acceptable", "\"threshold\": self.threshold, } base_config = super().get_config() return {**base_config, **config} def", "averaging to be performed on data. Acceptable values are `None`,", "to determine number of samples in each batch :type batch_size:", "\" \"altered without additional training. Please \" \"train the model", ":type verbose_log: bool :param verbose_keras: whether or not to print", "in parameters: if param not in list_of_necessary_params: errors.append(param + \"", "average=None, threshold=None, name=\"f1_score\", dtype=None): super().__init__(num_classes, average, 1.0, threshold, name=name, dtype=dtype)", "of embedded dimensions size_fc: Size of each fully connected layers", "self.true_positives, self.true_positives + self.false_positives ) recall = tf.math.divide_no_nan( self.true_positives, self.true_positives", "tf.keras.backend.argmax(self._model.output) # Create confidence layers final_predicted_layer = CharacterLevelCnnModel._argmax_threshold_layer( num_labels, threshold=0.0,", "import logging import os import sys import time from collections", "doesn't become [1, 1, 1] # Use abs(x) > eps,", "# Add the convolutional layers for fil in self._parameters['num_fil']: self._model.add(tf.keras.layers.Conv1D(", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "dict :param parameters: Contains all the appropriate parameters for the", "number of labels is altered :return: None \"\"\" # Reset", "num_fil: Number of filters in each convolution layer :type parameters:", "Output the model into a .pb file for TensorFlow argmax_layer", "used to train model :type train_data: Union[list, np.ndarray] :param val_data:", "are: max_length, max_char_encoding_id, dim_embed, size_fc dropout, size_conv, num_fil, optimizer, default_label", "writing, software # distributed under the License is distributed on", "self._need_to_reconstruct_model(): self._reconstruct_model() model_param_dirpath = os.path.join(dirpath, \"model_parameters.json\") with open(model_param_dirpath, 'w') as", "tf.keras.Model(self._model.inputs, argmax_outputs) # Compile the model softmax_output_layer_name = self._model.outputs[0].name.split('/')[0] losses", "serves as a weight reset. :return: None \"\"\" num_labels =", "verbose=verbose_keras)[1]) y_val_test.append(np.argmax(y_val, axis=-1)) batch_id += 1 sys.stdout.flush() if verbose_log: sys.stdout.write(\"\\rEPOCH", "super().__init__(num_classes, average, 1.0, threshold, name=name, dtype=dtype) def get_config(self): base_config =", "tensor :type input_str_tensor: tf.tensor :param max_char_encoding_id: Maximum integer value for", "str \"\"\" if source_file is None: source_file = os.path.join(_file_dir, \"embeddings/glove.840B.300d-char.txt\")", "containing encoded list of input sentences :rtype: tf.Tensor \"\"\" #", "bg_label_tf, tf.multiply( tf.subtract(argmax_layer, bg_label_tf), argmax_mask ), name='ThreshArgMax' ) return final_predicted_layer", "self._model_default_ind = default_ind def reset_weights(self): \"\"\" Reset the weights of", "It is the weighted harmonic mean of precision and recall.", "wants prediction confidences :type show_confidences: :param verbose: Flag to determine", "fp: label_mapping = json.load(fp) # use f1 score metric custom_objects", "to the model. This layer's output will be the argmax", "model needs to be reconstructed. :return: bool of whether or", "convert characters to indices input_str_flatten = tf.reshape(input_str_tensor, [-1]) sentences_encode =", "model size_conv: Convolution kernel size default_label: Key for label_mapping that", "bool of whether or not the model needs to reconstruct.", "from numpy predictions_list = [i for i in range(0, allocation_index)]", "without a model. \" \"Construct/Load a model before predicting.\") elif", "model before predicting.\") elif self._need_to_reconstruct_model(): raise RuntimeError(\"The model label mapping", "precision * recall add_value = (tf.math.square(self.beta) * precision) + recall", "in. Raise error if invalid parameters are present. :param parameters:", "label, otherwise it will be the default label index. :param", "sample_weight)) def result(self): precision = tf.math.divide_no_nan( self.true_positives, self.true_positives + self.false_positives", "\"average\": self.average, \"beta\": self.beta, \"threshold\": self.threshold, } base_config = super().get_config()", "reduced_embds = pca.fit_transform(embd_matrix) # write to file dir_name = os.path.dirname(source_file)", "len(predictions) <= allocation_index: predictions = np.pad(predictions, ((0, len(predictions)), (0, 0)),", "{softmax_output_layer_name: \"categorical_crossentropy\"} # use f1 score metric f1_score_training = F1Score(num_classes=num_labels,", "the serializable config of the metric.\"\"\" config = { \"num_classes\":", "for label_mapping that is the default label pad_label: Key for", "return {'pred': predictions_list, 'conf': confidences_list} return {'pred': predictions_list} def details(self):", "0. name: (Optional) String name of the metric instance. dtype:", "\\cdot \\textrm{recall}}{\\textrm{precision} + \\textrm{recall}} $$ Args: num_classes: Number of unique", "= [] list_of_necessary_params = ['max_length', 'max_char_encoding_id', 'dim_embed', 'size_fc', 'dropout', 'size_conv',", "of labels is altered :return: None \"\"\" # Reset model", "with weights :param dirpath: directory path where you want to", "label index. :param num_labels: number of entities :type num_labels: int", "not :type verbose: bool :return: char level predictions and confidences", "mapping of the model :type label_mapping: dict :return: None \"\"\"", "if f1_report else np.NAN val_precision = f1_report['weighted avg']['precision'] \\ if", "self.reset_weights() history = defaultdict() f1 = None f1_report = []", ":type batch_size: int :param show_confidences: whether user wants prediction confidences", "time from collections import defaultdict import numpy as np import", "super().get_config() del base_config[\"beta\"] return base_config def build_embd_dictionary(filename): \"\"\" Returns a", "a model :param other: a model :type self: BaseModel :type", "((0, len(predictions)), (0, 0)), mode='constant') sentence_lengths = np.pad( sentence_lengths, pad_width=((0,", "`None`, `micro`, `macro` and `weighted`. Default value is None. beta:", "self.average = average self.beta = beta self.threshold = threshold self.axis", "encoding indices range from 0 to max_char_encoding_id, # we add", "= 'is a problem, consider rebuilding the SavedModel after '", "None: self.set_label_mapping(label_mapping) if not self._model: self._construct_model() else: if self._need_to_reconstruct_model(): self._reconstruct_model()", "acc: %f - \" \"f1_score %f\" % (self._epoch_id, batch_id, *model_results[1:]))", "< 0 or parameters[param] > 1: errors.append(param + \" must", "in enumerate(data): model_output = self._model( tf.convert_to_tensor(batch_data) ) # Count number", "BaseModel :return: Whether or not self and other are equal", "bool :return: char level predictions and confidences :rtype: dict \"\"\"", ":type num_labels: int :param threshold: default set to 0 so", "\"\"\" Embeds GloVe chars embeddings from source file to n_dims", "of x != 0 to check for zero y_pred =", "filters=fil, kernel_size=self._parameters['size_conv'], activation='relu', padding='same')) if self._parameters['dropout']: self._model.add( tf.keras.layers.Dropout(self._parameters['dropout'])) # Add", "model into a .pb file for TensorFlow argmax_layer = tf.keras.backend.argmax(self._model.output)", "= json.load(fp) # use f1 score metric custom_objects = {", "embedding_dict = build_embd_dictionary(embed_file) input_shape = tuple([max_length]) # Fill in the", "'tf_op_layer_ArgMax', # 'thresh_arg_max_layer') for _ in range(3): self._model.layers.pop() # Add", "def set_label_mapping(self, label_mapping): \"\"\" Sets the labels for the model", "slices of predictions to return prediction & confidence matrices for", "Union[dict, None] :param reset_weights: Flag to determine whether to reset", "self._parameters != other._parameters \\ or self._label_mapping != other._label_mapping: return False", "0 self._model_num_labels = num_labels self._model_default_ind = default_ind def fit(self, train_data,", "return f1, f1_report def predict(self, data, batch_size=32, show_confidences=False, verbose=True): \"\"\"", "self.false_negatives = _zero_wt_init(\"false_negatives\") self.weights_intermediate = _zero_wt_init(\"weights_intermediate\") def update_state(self, y_true, y_pred,", "return {'pred': predictions_list} def details(self): \"\"\" Prints the relevant details", "dirpath: str :return: None \"\"\" if not self._model: self._construct_model() elif", "self._parameters['max_char_encoding_id'] # Encoding layer def encoding_function(input_str): char_in_vector = CharacterLevelCnnModel._char_encoding_layer( input_str,", "to 1, and the rest 0. name: (Optional) String name", "file.write(word + \" \" + ' '.join(str(num) for num in", "label bg_label_tf = tf.keras.backend.constant( default_ind, dtype=argmax_layer.dtype) # Generate the final", "= os.path.join( _file_dir, \"embeddings/glove-reduced-{}D.txt\".format( self._parameters['dim_embed'])) embedding_matrix = np.zeros((max_char_encoding_id + 2,", "= y_pred > self.threshold y_true = tf.cast(y_true, self.dtype) y_pred =", "index zero.\") if self._parameters['default_label'] not in label_mapping: raise ValueError(\"The `default_label`", "num_labels_): super(ThreshArgMaxLayer, self).__init__() thresh_init = tf.constant_initializer(threshold_) self.thresh_vec = tf.Variable( name='ThreshVec',", "1] = embedding_dict[chr(ascii_num)] self._model.add(tf.keras.layers.Embedding( max_char_encoding_id + 2, self._parameters['dim_embed'], weights=[embedding_matrix], input_length=input_shape[0],", "sentence_lengths, pad_width=((0, len(sentence_lengths)),), mode='constant') if show_confidences: confidences = np.pad(confidences, ((0,", "for i, ls in enumerate(zip(*embd_table.items()))] # get PCA embedder pca", "\\ default_ind != self._model_default_ind def save_to_disk(self, dirpath): \"\"\" Saves whole", ":type input_str_tensor: tf.tensor :param max_char_encoding_id: Maximum integer value for encoding", "threshold minimum. argmax_mask = tf.keras.backend.cast( tf.keras.backend.greater_equal(confidence_max_layer, threshold_at_argmax), dtype=argmax_layer.dtype) # Create", ":param val_data: data generator for the validation :type val_data: iterator", "\"which maps labels to index encodings or a list.\") label_mapping", "models are equal with one another, may only check important", "BaseTrainableModel _file_dir = os.path.dirname(os.path.abspath(__file__)) logger = dp_logging.get_child_logger(__name__) class NoV1ResourceMessageFilter(logging.Filter): \"\"\"Removes", "Reset model tf.keras.backend.clear_session() # generate glove embedding create_glove_char(self._parameters['dim_embed']) # generate", "\"\"\" Determines whether or not the model needs to be", "(Optional) Data type of the metric result. Returns: F-1 Score:", "training. Please \" \"train the model or reset the label", "_char_encoding_layer(input_str_tensor, max_char_encoding_id, max_len): \"\"\" Character encoding for the list of", "Model constructor for the data labeler. This also serves as", "F-Beta Score: float. \"\"\" # Modification: remove the run-time type", "Score. # Copyright 2019 The TensorFlow Authors. All Rights Reserved.", "= [ np.asarray(ls) if i > 0 else list(ls) for", "result. Returns: F-Beta Score: float. \"\"\" # Modification: remove the", "whole model to disk with weights :param dirpath: directory path", "embeddings from source file to n_dims principal components in a", "json.dump(self.label_mapping, fp) self._model.save(os.path.join(dirpath)) @classmethod def load_from_disk(cls, dirpath): \"\"\" Loads whole", "metric custom_objects = { \"F1Score\": F1Score( num_classes=max(label_mapping.values()) + 1, average='micro'),", "not None: self.set_label_mapping(label_mapping) if not self._model: self._construct_model() else: if self._need_to_reconstruct_model():", "ValueError(\"`PAD` must map to index zero.\") if self._parameters['default_label'] not in", "def get_config(self): \"\"\"Returns the serializable config of the metric.\"\"\" config", "values are `None`, `micro`, `macro` and `weighted`. Default value is", "model_param_dirpath = os.path.join(dirpath, \"model_parameters.json\") with open(model_param_dirpath, 'w') as fp: json.dump(self._parameters,", "validation :type val_data: iterator :param batch_size_test: Number of samples to", "dict() with open(filename, 'r') as embds: for line in embds:", "characters to indices input_str_flatten = tf.reshape(input_str_tensor, [-1]) sentences_encode = tf.strings.unicode_decode(input_str_flatten,", "(self._epoch_id, batch_id, *model_results[1:])) batch_id += 1 for i, metric_label in", "'w') as file: for word, embd in zip(embd_words, reduced_embds): file.write(word", "# Convert predictions, confidences to lists from numpy predictions_list =", "encoding for the list of sentences :param input_str_tensor: input list", "tf.abs(y_pred) > 1e-12) else: y_pred = y_pred > self.threshold y_true", "sent in. Raise error if invalid parameters are present. :param", "dict with bad PAD raise ValueError(\"`PAD` must map to index", "def __init__(self, threshold_, num_labels_): super(ThreshArgMaxLayer, self).__init__() thresh_init = tf.constant_initializer(threshold_) self.thresh_vec", "dtype=tf.string)) self._model.add( tf.keras.layers.Lambda(encoding_function, output_shape=tuple([max_length]))) # Create a pre-trained weight matrix", "show_confidences: confidences = np.zeros((batch_size, self._parameters['max_length'], self.num_labels)) # Run model with", "is None: return f1, f1_report # Predict on the test", "of the model (summary, parameters, label mapping) \"\"\" print(\"\\n###### Model", "is `[0, 1]`. Works for both multi-class and multi-label classification.", "self._parameters['max_length'] max_char_encoding_id = self._parameters['max_char_encoding_id'] # Encoding layer def encoding_function(input_str): char_in_vector", "\"macro\", \"weighted\"): raise ValueError( \"Unknown average type. Acceptable values \"", "self.false_positives ) recall = tf.math.divide_no_nan( self.true_positives, self.true_positives + self.false_negatives )", "key, value in self._parameters.items(): print(\"{}: {}\".format(key, value)) print(\"\\nModel Label Mapping:\")", "and 0 label_mapping.update({'PAD': 0}) if (isinstance(label_mapping, dict) and label_mapping.get('PAD', None)", "# limitations under the License. # ============================================================================== It is the", "0: errors.append(param + \" must be a non-empty list of", "if (isinstance(label_mapping, dict) and label_mapping.get('PAD', None) != 0): # dict", "not self and other are equal :rtype: bool \"\"\" if", "present. :param parameters: parameter dict containing the following parameters: max_length:", "y_pred = tf.cast(y_pred, self.dtype) def _weighted_sum(val, sample_weight): if sample_weight is", "+ \" must be a string.\" errors.append(error) # Error if", "multi-class and multi-label classification. $$ F_1 = 2 \\cdot \\frac{\\textrm{precision}", ") return final_predicted_layer return ThreshArgMaxLayer(threshold, num_labels) def _construct_model(self): \"\"\" Model", "generator for the validation :type val_data: iterator :param batch_size_test: Number", "label_mapping.update({'PAD': 0}) if (isinstance(label_mapping, dict) and label_mapping.get('PAD', None) != 0):", "self._model_num_labels or \\ default_ind != self._model_default_ind def save_to_disk(self, dirpath): \"\"\"", "\"Unknown average type. Acceptable values \" \"are: [None, 'micro', 'macro',", "v1 Model weights need to be transferred. if not callable(tf_model):", "predictions, confidences to lists from numpy predictions_list = [i for", "> self.threshold y_true = tf.cast(y_true, self.dtype) y_pred = tf.cast(y_pred, self.dtype)", "= tf.math.divide_no_nan(mul_value, add_value) f1_score = mean * (1 + tf.math.square(self.beta))", "tf.gather(self.thresh_vec, argmax_layer) confidence_max_layer = tf.keras.backend.max(confidence_layer, axis=2) # Check if the", "self._model_default_ind = default_ind def fit(self, train_data, val_data=None, batch_size=32, label_mapping=None, reset_weights=False,", "the metric instance. dtype: (Optional) Data type of the metric", "val_data=None, batch_size=32, label_mapping=None, reset_weights=False, verbose=True): \"\"\" Train the current model", "reconstruct flags for model self._model_num_labels = 0 self._model_default_ind = -1", "'is a problem, consider rebuilding the SavedModel after ' +", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "3 output layers (dense_2', 'tf_op_layer_ArgMax', # 'thresh_arg_max_layer') for _ in", ":param other: a model :type self: BaseModel :type other: BaseModel", "sentences_encode = tf.strings.unicode_decode(input_str_flatten, input_encoding='UTF-8') sentences_encode = tf.add(tf.cast(1, tf.int32), sentences_encode) sentences_encode", "input :type data: Union[list, numpy.ndarray] :param batch_size: number of samples", "dtype=self.dtype ) self.true_positives = _zero_wt_init(\"true_positives\") self.false_positives = _zero_wt_init(\"false_positives\") self.false_negatives =", "tf.keras.layers.Dense(num_labels, activation='softmax')) # Output the model into a .pb file", "= [self.num_classes] def _zero_wt_init(name): return self.add_weight( name, shape=self.init_shape, initializer=\"zeros\", dtype=self.dtype", "num_classes=max(label_mapping.values()) + 1, average='micro'), \"CharacterLevelCnnModel\": cls, } with tf.keras.utils.custom_object_scope(custom_objects): tf_model", "1 sys.stdout.flush() if verbose_log: sys.stdout.write(\"\\rEPOCH %g, validation_batch_id %d\" % (self._epoch_id,", "raise ValueError(\"You are trying to predict without a model. \"", "None: if not isinstance(threshold, float): raise TypeError(\"The value of threshold", "for size in self._parameters['size_fc']: self._model.add( tf.keras.layers.Dense(units=size, activation='relu')) if self._parameters['dropout']: self._model.add(", "result(self): precision = tf.math.divide_no_nan( self.true_positives, self.true_positives + self.false_positives ) recall", "i, metric_label in enumerate(self._model.metrics_names): history[metric_label] = model_results[i] if val_data: f1,", "details of the model (summary, parameters, label mapping) \"\"\" print(\"\\n######", "else list(ls) for i, ls in enumerate(zip(*embd_table.items()))] # get PCA", "len(parameters[param]) == 0: errors.append(param + \" must be a non-empty", "the model :param label_mapping: label mapping of the model :type", "tf1_weights.append(var.value()) loaded_model._construct_model() tf1_weights.append(loaded_model._model.weights[-1].value()) loaded_model._model.set_weights(tf1_weights) # load self loaded_model._model_num_labels = loaded_model.num_labels", "= pca.fit_transform(embd_matrix) # write to file dir_name = os.path.dirname(source_file) embd_file_name", "np.pad(predictions, ((0, len(predictions)), (0, 0)), mode='constant') sentence_lengths = np.pad( sentence_lengths,", "if errors: raise ValueError('\\n'.join(errors)) def set_label_mapping(self, label_mapping): \"\"\" Sets the", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "threshold, name=name, dtype=dtype) def get_config(self): base_config = super().get_config() del base_config[\"beta\"]", "model tf.keras.backend.clear_session() num_labels = self.num_labels default_ind = self.label_mapping[self._parameters['default_label']] # Remove", "= _zero_wt_init(\"true_positives\") self.false_positives = _zero_wt_init(\"false_positives\") self.false_negatives = _zero_wt_init(\"false_negatives\") self.weights_intermediate =", "encoded list of input sentences :rtype: tf.Tensor \"\"\" # convert", "return base_config def build_embd_dictionary(filename): \"\"\" Returns a numpy embedding dictionary", "model. :return: None \"\"\" self._construct_model() def _reconstruct_model(self): \"\"\" Reconstruct the", "value in self._parameters.items(): print(\"{}: {}\".format(key, value)) print(\"\\nModel Label Mapping:\") for", "of input sentences :rtype: tf.Tensor \"\"\" # convert characters to", "self._model: self._construct_model() else: if self._need_to_reconstruct_model(): self._reconstruct_model() if reset_weights: self.reset_weights() history", "tf.reduce_sum(val, axis=self.axis) self.true_positives.assign_add(_weighted_sum(y_pred * y_true, sample_weight)) self.false_positives.assign_add( _weighted_sum(y_pred * (1", ":type max_len: int :return : tensor containing encoded list of", "f1_report def predict(self, data, batch_size=32, show_confidences=False, verbose=True): \"\"\" Run model", "source_file: str \"\"\" if source_file is None: source_file = os.path.join(_file_dir,", "# Create a pre-trained weight matrix # character encoding indices", "label_mapping.values(): # if dict missing PAD and 0 label_mapping.update({'PAD': 0})", "to disk with weights :param dirpath: directory path where you", "out scores for training, etc. :type verbose_log: bool :param verbose_keras:", "if the confidences meet the threshold minimum. argmax_mask = tf.keras.backend.cast(", "0.073) parameters.setdefault('size_conv', 13) parameters.setdefault('default_label', \"UNKNOWN\") parameters.setdefault('num_fil', [48 for _ in", "the threshold for its label, otherwise it will be the", "Number of unique classes in the dataset. average: Type of", "BaseModel :type other: BaseModel :return: Whether or not self and", "layers dropout: Ratio of dropout in the model size_conv: Convolution", "not self._model: return False default_ind = self.label_mapping[self._parameters['default_label']] return self.num_labels !=", "Compile the model softmax_output_layer_name = self._model.outputs[0].name.split('/')[0] losses = {softmax_output_layer_name: \"categorical_crossentropy\"}", "' + \\ 'running tf.compat.v1.enable_resource_variables()' return msg not in record.getMessage()", "for num in embd) + \"\\n\") class CharacterLevelCnnModel(BaseTrainableModel, metaclass=AutoSubRegistrationMeta): #", "tf_logger = logging.getLogger('tensorflow') tf_logger.addFilter(NoV1ResourceMessageFilter()) @tf.keras.utils.register_keras_serializable() class FBetaScore(tf.keras.metrics.Metric): r\"\"\"Computes F-Beta score.", "open(filename, 'r') as embds: for line in embds: line =", "to predict without a model. \" \"Construct/Load a model before", "= beta self.threshold = threshold self.axis = None self.init_shape =", "is the weighted harmonic mean of precision and recall. Output", "a python float\") if threshold > 1.0 or threshold <=", "appropriate parameters for the model. Must contain num_labels. Other possible", "to be reconstructed. :return: bool of whether or not the", ":type max_char_encoding_id: int :param max_len: Maximum char length in a", "Add batch normalization, set fused = True for compactness self._model.add(", "*model_results[1:])) batch_id += 1 for i, metric_label in enumerate(self._model.metrics_names): history[metric_label]", "or float \" \"from 0 to 1.\") elif param ==", "= tf.keras.Model(self._model.inputs, argmax_outputs) # Compile the model softmax_output_layer_name = self._model.outputs[0].name.split('/')[0]", "# write to file dir_name = os.path.dirname(source_file) embd_file_name = os.path.join(dir_name,", "= CharacterLevelCnnModel._argmax_threshold_layer( num_labels, threshold=0.0, default_ind=default_ind) argmax_outputs = self._model.outputs + \\", "num_classes, average=None, beta=1.0, threshold=None, name=\"fbeta_score\", dtype=None, **kwargs): super().__init__(name=name, dtype=dtype) if", "are equal with one another, may only check important variables,", "2, self._parameters['dim_embed'], weights=[embedding_matrix], input_length=input_shape[0], trainable=True)) # Add the convolutional layers", "Elements of `y_pred` above threshold are considered to be 1,", "be reconstructed. :return: bool of whether or not the model", "argmax_outputs = [final_softmax_layer] + \\ [argmax_layer, final_predicted_layer(argmax_layer, final_softmax_layer)] self._model =", "input_shape = tuple([max_length]) # Fill in the weight matrix: let", "the rest 0. name: (Optional) String name of the metric", "Softmax layer to the previous spot final_softmax_layer = tf.keras.layers.Dense( num_labels,", "Rights Reserved. # # Licensed under the Apache License, Version", "= average self.beta = beta self.threshold = threshold self.axis =", "recall = tf.math.divide_no_nan( self.true_positives, self.true_positives + self.false_negatives ) mul_value =", "base_config = super().get_config() return {**base_config, **config} def reset_states(self): reset_value =", "dimensions size_fc: Size of each fully connected layers dropout: Ratio", "one extra index for out-of-vocabulary character embed_file = os.path.join( _file_dir,", "Output range is `[0, 1]`. Works for both multi-class and", "Softmax layer self._model.add( tf.keras.layers.Dense(num_labels, activation='softmax')) # Output the model into", "specific language governing permissions and # limitations under the License.", "definitions have been \" \"altered without additional training. Please \"", "be a string.\" errors.append(error) # Error if there are extra", "list of sentences :param input_str_tensor: input list of sentences converted", "loaded_model._construct_model() tf1_weights.append(loaded_model._model.weights[-1].value()) loaded_model._model.set_weights(tf1_weights) # load self loaded_model._model_num_labels = loaded_model.num_labels loaded_model._model_default_ind", "0 y_val_pred = [] y_val_test = [] for x_val, y_val", "greater than zero\") if threshold is not None: if not", "confidences_list[index] = list(confidences[index][:sentence_length]) if show_confidences: return {'pred': predictions_list, 'conf': confidences_list}", "the embed file for loading :type filename: str \"\"\" embd_table", "eps, instead of x != 0 to check for zero", "maps labels to index encodings or a list.\") label_mapping =", "reset_weights=False, verbose=True): \"\"\" Train the current model with the training", "def encoding_function(input_str): char_in_vector = CharacterLevelCnnModel._char_encoding_layer( input_str, max_char_encoding_id, max_length) return char_in_vector", "np.NAN val_precision = f1_report['weighted avg']['precision'] \\ if f1_report else np.NAN", "map to index zero.\") if self._parameters['default_label'] not in label_mapping: raise", "to their encoded integers :type label_mapping: Union[dict, None] :param reset_weights:", "in range(max_char_encoding_id): if chr(ascii_num) in embedding_dict: embedding_matrix[ascii_num + 1] =", "verbose=True): \"\"\" Run model and get predictions :param data: text", "batch_id * batch_size # Double array size if len(predictions) <=", "argmax_layer) confidence_max_layer = tf.keras.backend.max(confidence_layer, axis=2) # Check if the confidences", "boolean if the label mapping requires the mapping for index", "the batch of data :type batch_size: int :param show_confidences: whether", ":type verbose: bool :return: char level predictions and confidences :rtype:", "in parameters: if param in ['max_length', 'max_char_encoding_id', 'dim_embed', 'size_conv']: if", "vector variable and create the threshold # matrix. class ThreshArgMaxLayer(tf.keras.layers.Layer):", "+ \" must be a non-empty \" \"list of integers.\")", "entities_dict that is the pad label num_fil: Number of filters", "create_glove_char(n_dims, source_file=None): \"\"\" Embeds GloVe chars embeddings from source file", "the convolutional layers for fil in self._parameters['num_fil']: self._model.add(tf.keras.layers.Conv1D( filters=fil, kernel_size=self._parameters['size_conv'],", "if not self._model: raise ValueError(\"You are trying to predict without", "return msg not in record.getMessage() tf_logger = logging.getLogger('tensorflow') tf_logger.addFilter(NoV1ResourceMessageFilter()) @tf.keras.utils.register_keras_serializable()", "= tf.math.divide_no_nan( self.weights_intermediate, tf.reduce_sum(self.weights_intermediate) ) f1_score = tf.reduce_sum(f1_score * weights)", "http://www.apache.org/licenses/LICENSE-2.0 # https://github.com/tensorflow/addons/blob/v0.12.0/LICENSE # # Unless required by applicable law", "# you may not use this file except in compliance", "\" \"Construct/Load a model before predicting.\") elif self._need_to_reconstruct_model(): raise RuntimeError(\"The", "loaded_model @staticmethod def _char_encoding_layer(input_str_tensor, max_char_encoding_id, max_len): \"\"\" Character encoding for", "embd_table = dict() with open(filename, 'r') as embds: for line", "License. # ============================================================================== It is the harmonic mean of precision", ":return: None \"\"\" if label_mapping is not None: self.set_label_mapping(label_mapping) if", "weight of precision and recall in harmonic mean. Determines the", "\"\"\" Returns a numpy embedding dictionary from embed file with", "embedding_matrix[ascii_num + 1] = embedding_dict[chr(ascii_num)] self._model.add(tf.keras.layers.Embedding( max_char_encoding_id + 2, self._parameters['dim_embed'],", "Checks if two models are equal with one another, may", "to print out scores for training, etc. :type verbose_log: bool", "need to be transferred. if not callable(tf_model): loaded_model._construct_model() tf1_weights =", "file to n_dims principal components in a new file :param", "tf.math.divide_no_nan(mul_value, add_value) f1_score = mean * (1 + tf.math.square(self.beta)) if", "'macro', 'weighted']\" ) if not isinstance(beta, float): raise TypeError(\"The value", "valid. for param in parameters: if param in ['max_length', 'max_char_encoding_id',", "self._parameters['default_label'] not in label_mapping: raise ValueError(\"The `default_label` of {} must", "ThreshArgMaxLayer(threshold, num_labels) def _construct_model(self): \"\"\" Model constructor for the data", "'size_fc' or param == 'num_fil': if not isinstance(parameters[param], list) \\", ":type self: BaseModel :type other: BaseModel :return: Whether or not", "v in self.variables]) @tf.keras.utils.register_keras_serializable() class F1Score(FBetaScore): r\"\"\"Computes F-1 Score. #", "# Add the fully connected layers for size in self._parameters['size_fc']:", "0 so all confidences pass. :type threshold: float :param default_ind:", "size if len(predictions) <= allocation_index: predictions = np.pad(predictions, ((0, len(predictions)),", "= embedding_dict[chr(ascii_num)] self._model.add(tf.keras.layers.Embedding( max_char_encoding_id + 2, self._parameters['dim_embed'], weights=[embedding_matrix], input_length=input_shape[0], trainable=True))", "for compactness self._model.add( tf.keras.layers.BatchNormalization(fused=False, scale=True)) # Add the fully connected", ":param reset_weights: Flag to determine whether to reset the weights", "# Use abs(x) > eps, instead of x != 0", "= np.pad(confidences, ((0, len(predictions)), (0, 0), (0, 0)), mode='constant') if", "embed file with GloVe-like format :param filename: Path to the", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "are trying to predict without a model. \" \"Construct/Load a", "batch_size: int :param show_confidences: whether user wants prediction confidences :type", "0. If threshold is None, the argmax is converted to", "TensorFlow argmax_layer = tf.keras.backend.argmax(final_softmax_layer) # Create confidence layers final_predicted_layer =", "float)) \\ or parameters[param] < 0 or parameters[param] > 1:", "= 0 self._model_num_labels = num_labels self._model_default_ind = default_ind def reset_weights(self):", "model and get predictions :param data: text input :type data:", "True def __init__(self, label_mapping=None, parameters=None): \"\"\" CNN Model Initializer. initialize", "max_length, max_char_encoding_id, dim_embed, size_fc dropout, size_conv, num_fil, optimizer, default_label :type", "to factor down :type source_file: str \"\"\" if source_file is", "final_predicted_layer return ThreshArgMaxLayer(threshold, num_labels) def _construct_model(self): \"\"\" Model constructor for", "None \"\"\" # load parameters model_param_dirpath = os.path.join(dirpath, \"model_parameters.json\") with", "under the Apache License, Version 2.0 (the \"License\"); # you", "in self.variables]) @tf.keras.utils.register_keras_serializable() class F1Score(FBetaScore): r\"\"\"Computes F-1 Score. # Copyright", "\"val_f1: %f - val_precision: %f - val_recall %f\" % (self._epoch_id,", "return embd_table def create_glove_char(n_dims, source_file=None): \"\"\" Embeds GloVe chars embeddings", "num_samples_in_batch] = model_output[1].numpy() sentence_lengths[allocation_index:allocation_index + num_samples_in_batch] = list(map(lambda x: len(x[0]),", "weighted harmonic mean of precision and recall. Output range is", "num in embd) + \"\\n\") class CharacterLevelCnnModel(BaseTrainableModel, metaclass=AutoSubRegistrationMeta): # boolean", "import time from collections import defaultdict import numpy as np", "self: a model :param other: a model :type self: BaseModel", "elif self.average is not None: # [micro, macro] f1_score =", "Encoding layer def encoding_function(input_str): char_in_vector = CharacterLevelCnnModel._char_encoding_layer( input_str, max_char_encoding_id, max_length)", "a vector the same size as the batch_size which #", "`micro`, `macro` and `weighted`. Default value is None. threshold: Elements", "from https://github.com/tensorflow/addons/blob/v0.12.0/tensorflow_addons/metrics/f_scores.py#L211-L283 # Copyright 2019 The TensorFlow Authors. All Rights", "previous spot final_softmax_layer = tf.keras.layers.Dense( num_labels, activation='softmax', name=\"dense_2\")( self._model.layers[-4].output) #", "model_output = self._model( tf.convert_to_tensor(batch_data) ) # Count number of samples", "of principal component dims of the embeddings :type n_dims: int", "= f1_report['weighted avg']['f1-score'] \\ if f1_report else np.NAN val_precision =", "& confidence matrices for index, sentence_length \\ in enumerate(sentence_lengths[:allocation_index]): predictions_list[index]", "embed file for loading :type filename: str \"\"\" embd_table =", "variable and create the threshold # matrix. class ThreshArgMaxLayer(tf.keras.layers.Layer): def", "def _validate_training(self, val_data, batch_size_test=32, verbose_log=True, verbose_keras=False): \"\"\" Validate the model", "the model \"\"\" # Initialize the thresholds vector variable and", "else: y_pred = y_pred > self.threshold y_true = tf.cast(y_true, self.dtype)", "val_data: f1, f1_report = self._validate_training(val_data) history['f1_report'] = f1_report val_f1 =", "record): msg = 'is a problem, consider rebuilding the SavedModel", "((0, len(predictions)), (0, 0), (0, 0)), mode='constant') if show_confidences: confidences[allocation_index:allocation_index", "self.average, \"beta\": self.beta, \"threshold\": self.threshold, } base_config = super().get_config() return", "f1_report = labeler_utils.evaluate_accuracy( np.concatenate(y_val_pred, axis=0), np.concatenate(y_val_test, axis=0), self.num_labels, self.reverse_label_mapping, verbose=verbose_keras)", "{'pred': predictions_list, 'conf': confidences_list} return {'pred': predictions_list} def details(self): \"\"\"", "ValueError( \"Unknown average type. Acceptable values \" \"are: [None, 'micro',", "build_embd_dictionary(embed_file) input_shape = tuple([max_length]) # Fill in the weight matrix:", "numpy predictions_list = [i for i in range(0, allocation_index)] confidences_list", "tf.math.minimum(sentences_encode, max_char_encoding_id + 1) # padding sentences_encode_pad = sentences_encode.to_tensor(shape=[None, max_len])", "allocation_index += num_samples_in_batch # Convert predictions, confidences to lists from", "def _reconstruct_model(self): \"\"\" Reconstruct the appropriate layers if the number", "get_config(self): base_config = super().get_config() del base_config[\"beta\"] return base_config def build_embd_dictionary(filename):", "number of entities :type num_labels: int :param threshold: default set", "F_{\\beta} = (1 + \\beta^2) * \\frac{\\textrm{precision} * \\textrm{precision}}{(\\beta^2 \\cdot", "f1_report = [] self._model.reset_metrics() softmax_output_layer_name = self._model.outputs[0].name.split('/')[0] start_time = time.time()", "self.dtype) y_pred = tf.cast(y_pred, self.dtype) def _weighted_sum(val, sample_weight): if sample_weight", "Maximum integer value for encoding the input dim_embed: Number of", "max_char_encoding_id, max_length) return char_in_vector self._model.add(tf.keras.layers.Input(shape=(None,), dtype=tf.string)) self._model.add( tf.keras.layers.Lambda(encoding_function, output_shape=tuple([max_length]))) #", "not :type verbose: bool :return: None \"\"\" if label_mapping is", "filename: Path to the embed file for loading :type filename:", "dirpath: directory path where you want to load the model", "Returns: F-Beta Score: float. \"\"\" # Modification: remove the run-time", "an accepted parameter.\") if errors: raise ValueError('\\n'.join(errors)) def set_label_mapping(self, label_mapping):", "as a weight reset. :return: None \"\"\" num_labels = self.num_labels", "\" \"train the model or reset the label mapping to", "param == 'dropout': if not isinstance(parameters[param], (int, float)) \\ or", "threshold, tf.abs(y_pred) > 1e-12) else: y_pred = y_pred > self.threshold", "default index :type default_ind: int :return: final argmax threshold layer", "if self._parameters['dropout']: self._model.add( tf.keras.layers.Dropout(self._parameters['dropout'])) # Add batch normalization, set fused", "= tf.math.multiply(val, tf.expand_dims(sample_weight, 1)) return tf.reduce_sum(val, axis=self.axis) self.true_positives.assign_add(_weighted_sum(y_pred * y_true,", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "list(confidences[index][:sentence_length]) if show_confidences: return {'pred': predictions_list, 'conf': confidences_list} return {'pred':", "verbose_log=True, verbose_keras=False): \"\"\" Validate the model on the test set", "for x_val, y_val in val_data: y_val_pred.append(self._model.predict( x_val, batch_size=batch_size_test, verbose=verbose_keras)[1]) y_val_test.append(np.argmax(y_val,", "del base_config[\"beta\"] return base_config def build_embd_dictionary(filename): \"\"\" Returns a numpy", "show_confidences: whether user wants prediction confidences :type show_confidences: :param verbose:", "are present and valid. for param in parameters: if param", "other): \"\"\" Checks if two models are equal with one", "to the previous spot final_softmax_layer = tf.keras.layers.Dense( num_labels, activation='softmax', name=\"dense_2\")(", "for functions def __init__(self, num_classes, average=None, beta=1.0, threshold=None, name=\"fbeta_score\", dtype=None,", "is not None: val = tf.math.multiply(val, tf.expand_dims(sample_weight, 1)) return tf.reduce_sum(val,", "to print out scores for training, from keras. :type verbose_keras:", "mapping) \"\"\" print(\"\\n###### Model Details ######\\n\") self._model.summary() print(\"\\nModel Parameters:\") for", "val_data: data generator for the validation :type val_data: iterator :param", "embd) + \"\\n\") class CharacterLevelCnnModel(BaseTrainableModel, metaclass=AutoSubRegistrationMeta): # boolean if the", "y_true, sample_weight)) self.false_positives.assign_add( _weighted_sum(y_pred * (1 - y_true), sample_weight) )", "loaded_model = cls(label_mapping, parameters) loaded_model._model = tf_model # Tensorflow v1", "verbose_keras: whether or not to print out scores for training,", "Fill in the weight matrix: let pad and space be", "tf.reduce_max(y_pred, axis=-1, keepdims=True) # make sure [0, 0, 0] doesn't", "int :param source_file: Location of original embeddings to factor down", "\" + ' '.join(str(num) for num in embd) + \"\\n\")", "thresh_init = tf.constant_initializer(threshold_) self.thresh_vec = tf.Variable( name='ThreshVec', initial_value=thresh_init(shape=[num_labels_]), trainable=False) def", "a .pb file for TensorFlow argmax_layer = tf.keras.backend.argmax(final_softmax_layer) # Create", "+ 1) # padding sentences_encode_pad = sentences_encode.to_tensor(shape=[None, max_len]) return sentences_encode_pad", "!= \"micro\": self.axis = 0 self.init_shape = [self.num_classes] def _zero_wt_init(name):", ":param default_ind: default index :type default_ind: int :return: final argmax", "index, sentence_length \\ in enumerate(sentence_lengths[:allocation_index]): predictions_list[index] = list(predictions[index][:sentence_length]) if show_confidences:", "float): raise TypeError(\"The value of beta should be a python", "integer or float \" \"from 0 to 1.\") elif param", "1)) return tf.reduce_sum(val, axis=self.axis) self.true_positives.assign_add(_weighted_sum(y_pred * y_true, sample_weight)) self.false_positives.assign_add( _weighted_sum(y_pred", "Convert predictions, confidences to lists from numpy predictions_list = [i", "\"micro\", \"macro\", \"weighted\"): raise ValueError( \"Unknown average type. Acceptable values", "both multi-class and multi-label classification. $$ F_{\\beta} = (1 +", "= super().get_config() del base_config[\"beta\"] return base_config def build_embd_dictionary(filename): \"\"\" Returns", "spot final_softmax_layer = tf.keras.layers.Dense( num_labels, activation='softmax', name=\"dense_2\")( self._model.layers[-4].output) # Output", "input sentences :rtype: tf.Tensor \"\"\" # convert characters to indices", "# Create confidence layers final_predicted_layer = CharacterLevelCnnModel._argmax_threshold_layer( num_labels, threshold=0.0, default_ind=default_ind)", "batch_id)) tf.keras.backend.set_floatx('float32') # Clean the predicted entities and the actual", "tf.reduce_mean(f1_score) return f1_score def get_config(self): \"\"\"Returns the serializable config of", "parameters.setdefault('max_length', 3400) parameters.setdefault('max_char_encoding_id', 127) parameters.setdefault('dim_embed', 64) parameters.setdefault('size_fc', [96, 96]) parameters.setdefault('dropout',", "Modification: remove the run-time type checking for functions def __init__(self,", "from :type dirpath: str :return: None \"\"\" # load parameters", "mean * (1 + tf.math.square(self.beta)) if self.average == \"weighted\": weights", "to the precision and recall. Default value is 1. threshold:", "range is `[0, 1]`. Works for both multi-class and multi-label", "from source file to n_dims principal components in a new", "Double array size if len(predictions) <= allocation_index: predictions = np.pad(predictions,", "the model size_conv: Convolution kernel size default_label: Key for label_mapping", "print(\"\\nModel Parameters:\") for key, value in self._parameters.items(): print(\"{}: {}\".format(key, value))", "< 0: errors.append(param + \" must be a valid integer", "np.NAN epoch_time = time.time() - start_time logger.info(\"\\rEPOCH %d (%ds), loss:", "either be a non-empty encoding dict \" \"which maps labels", "and recall. Default value is 1. threshold: Elements of `y_pred`", "zero\") if threshold is not None: if not isinstance(threshold, float):", ":return: None \"\"\" self._construct_model() def _reconstruct_model(self): \"\"\" Reconstruct the appropriate", "output using the function: final_predicted_layer = tf.add( bg_label_tf, tf.multiply( tf.subtract(argmax_layer,", "[-1]) sentences_encode = tf.strings.unicode_decode(input_str_flatten, input_encoding='UTF-8') sentences_encode = tf.add(tf.cast(1, tf.int32), sentences_encode)", "self._model_default_ind = -1 BaseModel.__init__(self, label_mapping, parameters) def __eq__(self, other): \"\"\"", "to \" \"predict.\") # Pre-allocate space for predictions confidences =", "set fused = True for compactness self._model.add( tf.keras.layers.BatchNormalization(fused=False, scale=True)) #", "f1 report). \"\"\" f1 = None f1_report = None if", "+ 2, self._parameters['dim_embed'], weights=[embedding_matrix], input_length=input_shape[0], trainable=True)) # Add the convolutional", "tensorflow as tf from sklearn import decomposition from .. import", "None f1_report = [] self._model.reset_metrics() softmax_output_layer_name = self._model.outputs[0].name.split('/')[0] start_time =", "self._model.layers[-4].output) # Output the model into a .pb file for", ":return : tensor containing encoded list of input sentences :rtype:", "* \\textrm{precision}}{(\\beta^2 \\cdot \\textrm{precision}) + \\textrm{recall}} $$ Args: num_classes: Number", "%f - acc: %f - f1_score %f -- \" \"val_f1:", "Authors. All Rights Reserved. # # Licensed under the Apache", "= tf_model # Tensorflow v1 Model weights need to be", "\" \"list of integers.\") break elif param == 'default_label': if", "for the model. Must contain num_labels. Other possible parameters are:", "in each batch :type batch_size: int :param label_mapping: maps labels", "not isinstance(threshold, float): raise TypeError(\"The value of threshold should be", "val_f1, val_precision, val_recall)) self._epoch_id += 1 return history, f1, f1_report", "else np.NAN val_precision = f1_report['weighted avg']['precision'] \\ if f1_report else", "os.path.join(dirpath, \"model_parameters.json\") with open(model_param_dirpath, 'w') as fp: json.dump(self._parameters, fp) labels_dirpath", "to validate the training :type val_data: Union[list, np.ndarray] :param batch_size:", "[None, 'micro', 'macro', 'weighted']\" ) if not isinstance(beta, float): raise", "Path to the embed file for loading :type filename: str", "self._model.add(tf.keras.layers.Conv1D( filters=fil, kernel_size=self._parameters['size_conv'], activation='relu', padding='same')) if self._parameters['dropout']: self._model.add( tf.keras.layers.Dropout(self._parameters['dropout'])) #", "embedding_dict: embedding_matrix[ascii_num + 1] = embedding_dict[chr(ascii_num)] self._model.add(tf.keras.layers.Embedding( max_char_encoding_id + 2,", "dropout, size_conv, num_fil, optimizer, default_label :type parameters: dict :return: None", "axis=0), np.concatenate(y_val_test, axis=0), self.num_labels, self.reverse_label_mapping, verbose=verbose_keras) return f1, f1_report def", "loaded_model._model.set_weights(tf1_weights) # load self loaded_model._model_num_labels = loaded_model.num_labels loaded_model._model_default_ind = loaded_model.label_mapping[", "Apache License, Version 2.0 (the \"License\"); # you may not", "errors.append(param + \" is not an accepted parameter.\") if errors:", "= None f1_report = [] self._model.reset_metrics() softmax_output_layer_name = self._model.outputs[0].name.split('/')[0] start_time", "either express or implied. # See the License for the", "reconstruct. \"\"\" if not self._model: return False default_ind = self.label_mapping[self._parameters['default_label']]", "= tf.Variable( name='ThreshVec', initial_value=thresh_init(shape=[num_labels_]), trainable=False) def call(self, argmax_layer, confidence_layer): threshold_at_argmax", "* y_true, sample_weight)) self.false_positives.assign_add( _weighted_sum(y_pred * (1 - y_true), sample_weight)", "its label, otherwise it will be the default label index.", "[] for var in tf_model.variables: if 'training' not in var.name:", "Initialize the thresholds vector variable and create the threshold #", "threshold layer for the model \"\"\" # Initialize the thresholds", "zero y_pred = tf.logical_and(y_pred >= threshold, tf.abs(y_pred) > 1e-12) else:", "normalization, set fused = True for compactness self._model.add( tf.keras.layers.BatchNormalization(fused=False, scale=True))", "confidence_max_layer = tf.keras.backend.max(confidence_layer, axis=2) # Check if the confidences meet", "validation data :param train_data: Training data used to train model", "%f - f1_score %f -- \" \"val_f1: %f - val_precision:", "in the batch of data :type batch_size: int :param show_confidences:", "not isinstance(parameters[param], str): error = str(param) + \" must be", "os.path.dirname(source_file) embd_file_name = os.path.join(dir_name, 'glove-reduced-{}D.txt'.format(n_dims)) with open(embd_file_name, 'w') as file:", "layer for the model \"\"\" # Initialize the thresholds vector", "+ \\ 'running tf.compat.v1.enable_resource_variables()' return msg not in record.getMessage() tf_logger", "equal with one another, may only check important variables, i.e.", "'max_char_encoding_id', 'dim_embed', 'size_conv']: if not isinstance(parameters[param], (int, float)) \\ or", "return self.num_labels != self._model_num_labels or \\ default_ind != self._model_default_ind def", "path where you want to save the model to :type", "self.num_labels default_ind = self.label_mapping[self._parameters['default_label']] # Reset model tf.keras.backend.clear_session() # generate", "score metric f1_score_training = F1Score(num_classes=num_labels, average='micro') metrics = {softmax_output_layer_name: ['acc',", "in testing :type batch_size_test: int :param verbose_log: whether or not", "of precision and recall. Output range is `[0, 1]`. Works", "= None if show_confidences: confidences_list = [i for i in", "config of the metric.\"\"\" config = { \"num_classes\": self.num_classes, \"average\":", "enumerate(data): model_output = self._model( tf.convert_to_tensor(batch_data) ) # Count number of", "self._parameters['dim_embed'])) embedding_dict = build_embd_dictionary(embed_file) input_shape = tuple([max_length]) # Fill in", "_file_dir = os.path.dirname(os.path.abspath(__file__)) logger = dp_logging.get_child_logger(__name__) class NoV1ResourceMessageFilter(logging.Filter): \"\"\"Removes TF2", "a model :type self: BaseModel :type other: BaseModel :return: Whether", "the labels for the model :param label_mapping: label mapping of", "if not isinstance(threshold, float): raise TypeError(\"The value of threshold should", "exist in the \" \"label mapping.\".format( self._parameters['default_label'])) super().set_label_mapping(label_mapping) def _need_to_reconstruct_model(self):", "determine number of samples in each batch :type batch_size: int", "for line in embds: line = line.strip().split() embd_table[line[0]] = np.asarray(line[1:])", "x_train, y_train in train_data: model_results = self._model.train_on_batch( x_train, {softmax_output_layer_name: y_train})", "the model. This layer's output will be the argmax value", "for both multi-class and multi-label classification. $$ F_1 = 2", "default_ind=1): \"\"\" Adds an argmax threshold layer to the model.", "file dir_name = os.path.dirname(source_file) embd_file_name = os.path.join(dir_name, 'glove-reduced-{}D.txt'.format(n_dims)) with open(embd_file_name,", "resources.\"\"\" def filter(self, record): msg = 'is a problem, consider", "Model Initializer. initialize epoch_id :param label_mapping: maps labels to their", "\\ or parameters[param] < 0 or parameters[param] > 1: errors.append(param", "if f1_report else np.NAN val_recall = f1_report['weighted avg']['recall'] \\ if", "functions def __init__(self, num_classes, average=None, beta=1.0, threshold=None, name=\"fbeta_score\", dtype=None, **kwargs):", "== 0: errors.append(param + \" must be a non-empty list", "# padding sentences_encode_pad = sentences_encode.to_tensor(shape=[None, max_len]) return sentences_encode_pad @staticmethod def", "with open(model_param_dirpath, 'w') as fp: json.dump(self._parameters, fp) labels_dirpath = os.path.join(dirpath,", "PAD label_mapping = ['PAD'] + label_mapping elif 0 not in", "size as the batch_size which # represents the background label", "tf.reduce_sum(self.weights_intermediate) ) f1_score = tf.reduce_sum(f1_score * weights) elif self.average is", "or param == 'num_fil': if not isinstance(parameters[param], list) \\ or", "maps labels to their encoded integers :type label_mapping: Union[dict, None]", "to 1.\") elif param == 'size_fc' or param == 'num_fil':", "array mismatch num_samples_in_batch = len(batch_data) allocation_index = batch_id * batch_size", "source file to n_dims principal components in a new file", "data, batch_size=32, show_confidences=False, verbose=True): \"\"\" Run model and get predictions", "value for encoding the input :type max_char_encoding_id: int :param max_len:", "* weights) elif self.average is not None: # [micro, macro]", "classes in the dataset. average: Type of averaging to be", "label pad_label: Key for entities_dict that is the pad label", "default_ind def fit(self, train_data, val_data=None, batch_size=32, label_mapping=None, reset_weights=False, verbose=True): \"\"\"", "<= 0.0: raise ValueError(\"threshold should be between 0 and 1\")", "= tf.keras.backend.constant( default_ind, dtype=argmax_layer.dtype) # Generate the final predicted output", "Returns a numpy embedding dictionary from embed file with GloVe-like", "metrics=metrics) self._epoch_id = 0 self._model_num_labels = num_labels self._model_default_ind = default_ind", "there are extra parameters thrown in for param in parameters:", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "PCA embedder pca = decomposition.PCA(n_components=n_dims) reduced_embds = pca.fit_transform(embd_matrix) # write", "= os.path.join(dirpath, \"model_parameters.json\") with open(model_param_dirpath, 'r') as fp: parameters =", "\"altered without additional training. Please \" \"train the model or", "It is the harmonic mean of precision and recall. Output", "name='ThreshArgMax' ) return final_predicted_layer return ThreshArgMaxLayer(threshold, num_labels) def _construct_model(self): \"\"\"", "final_predicted_layer(argmax_layer, self._model.output)] self._model = tf.keras.Model(self._model.inputs, argmax_outputs) # Compile the model", "Model weights need to be transferred. if not callable(tf_model): loaded_model._construct_model()", "from embed file with GloVe-like format :param filename: Path to", "for batch_id, batch_data in enumerate(data): model_output = self._model( tf.convert_to_tensor(batch_data) )", "= 0 for x_train, y_train in train_data: model_results = self._model.train_on_batch(", "TypeError(\"Labels must either be a non-empty encoding dict \" \"which", "samples in each batch :type batch_size: int :param label_mapping: maps", "to prevent array mismatch num_samples_in_batch = len(batch_data) allocation_index = batch_id", "verbose_log: whether or not to print out scores for training,", "np.zeros((batch_size, self._parameters['max_length'], self.num_labels)) # Run model with batching allocation_index =", "dim_embed: Number of embedded dimensions size_fc: Size of each fully", "file :param n_dims: Final number of principal component dims of", "start_time = time.time() batch_id = 0 for x_train, y_train in", "parameters are present and valid. for param in parameters: if", "Error if there are extra parameters thrown in for param", "print out scores for training, etc. :type verbose_log: bool :param", "`micro`, `macro` and `weighted`. Default value is None. beta: Determines", "batch to prevent array mismatch num_samples_in_batch = len(batch_data) allocation_index =", "max_char_encoding_id, # we add one extra index for out-of-vocabulary character", "# load self loaded_model._model_num_labels = loaded_model.num_labels loaded_model._model_default_ind = loaded_model.label_mapping[ loaded_model._parameters['default_label']", "\"F1Score\": F1Score( num_classes=max(label_mapping.values()) + 1, average='micro'), \"CharacterLevelCnnModel\": cls, } with", "sys.stdout.flush() if verbose: sys.stdout.write( \"\\rEPOCH %d, batch_id %d: loss: %f", "of unique classes in the dataset. average: Type of averaging", "* (1 + tf.math.square(self.beta)) if self.average == \"weighted\": weights =", "reset_weights(self): \"\"\" Reset the weights of the model. :return: None", "+ \\beta^2) * \\frac{\\textrm{precision} * \\textrm{precision}}{(\\beta^2 \\cdot \\textrm{precision}) + \\textrm{recall}}", "= labeler_utils.evaluate_accuracy( np.concatenate(y_val_pred, axis=0), np.concatenate(y_val_test, axis=0), self.num_labels, self.reverse_label_mapping, verbose=verbose_keras) return", "the batch_size which # represents the background label bg_label_tf =", "precision and recall. Output range is `[0, 1]`. Works for", "become [1, 1, 1] # Use abs(x) > eps, instead", "val_recall = f1_report['weighted avg']['recall'] \\ if f1_report else np.NAN epoch_time", "mapping requires the mapping for index 0 reserved requires_zero_mapping =", "or not :type verbose: bool :return: None \"\"\" if label_mapping", "trainable=True)) # Add the convolutional layers for fil in self._parameters['num_fil']:", "num_labels, threshold=0.0, default_ind=default_ind) argmax_outputs = [final_softmax_layer] + \\ [argmax_layer, final_predicted_layer(argmax_layer,", "https://github.com/tensorflow/addons/blob/v0.12.0/tensorflow_addons/metrics/f_scores.py#L211-L283 # Copyright 2019 The TensorFlow Authors. All Rights Reserved.", "def reset_weights(self): \"\"\" Reset the weights of the model. :return:", ":param label_mapping: label mapping of the model :type label_mapping: dict", "Run model with batching allocation_index = 0 for batch_id, batch_data", "in var.name: tf1_weights.append(var.value()) loaded_model._construct_model() tf1_weights.append(loaded_model._model.weights[-1].value()) loaded_model._model.set_weights(tf1_weights) # load self loaded_model._model_num_labels", "_ in range(4)]) parameters['pad_label'] = 'PAD' self._epoch_id = 0 #", "fp: parameters = json.load(fp) # load label_mapping labels_dirpath = os.path.join(dirpath,", "number of samples in batch to prevent array mismatch num_samples_in_batch", "parameters.setdefault('max_char_encoding_id', 127) parameters.setdefault('dim_embed', 64) parameters.setdefault('size_fc', [96, 96]) parameters.setdefault('dropout', 0.073) parameters.setdefault('size_conv',", "\"\"\" f1 = None f1_report = None if val_data is", "= os.path.dirname(os.path.abspath(__file__)) logger = dp_logging.get_child_logger(__name__) class NoV1ResourceMessageFilter(logging.Filter): \"\"\"Removes TF2 warning", "Clean the predicted entities and the actual entities f1, f1_report", "Acceptable values are `None`, `micro`, `macro` and `weighted`. Default value", "value is None. threshold: Elements of `y_pred` above threshold are", "{**base_config, **config} def reset_states(self): reset_value = tf.zeros(self.init_shape, dtype=self.dtype) tf.keras.backend.batch_set_value([(v, reset_value)", "or reset the label mapping to \" \"predict.\") # Pre-allocate", "fil in self._parameters['num_fil']: self._model.add(tf.keras.layers.Conv1D( filters=fil, kernel_size=self._parameters['size_conv'], activation='relu', padding='same')) if self._parameters['dropout']:", "allocation_index = batch_id * batch_size # Double array size if", "i > 0 else list(ls) for i, ls in enumerate(zip(*embd_table.items()))]", "'w') as fp: json.dump(self._parameters, fp) labels_dirpath = os.path.join(dirpath, \"label_mapping.json\") with", "Label Mapping:\") for key, value in self.label_mapping.items(): print(\"{}: {}\".format(key, value))", "the License. # ============================================================================== It is the harmonic mean of", "to print status or not :type verbose: bool :return: None", "tf.keras.layers.Dropout(self._parameters['dropout'])) # Add batch normalization, set fused = True for", "numpy.ndarray] :param batch_size: number of samples in the batch of", "self.num_labels)) # Run model with batching allocation_index = 0 for", "parameter initialization if not parameters: parameters = {} parameters.setdefault('max_length', 3400)", "size_conv, num_fil, optimizer, default_label :type parameters: dict :return: None \"\"\"", "Contains all the appropriate parameters for the model. Must contain", "multi-class and multi-label classification. $$ F_{\\beta} = (1 + \\beta^2)", "instance. dtype: (Optional) Data type of the metric result. Returns:", "with tf.keras.utils.custom_object_scope(custom_objects): tf_model = tf.keras.models.load_model(dirpath) loaded_model = cls(label_mapping, parameters) loaded_model._model", "num_samples_in_batch # Convert predictions, confidences to lists from numpy predictions_list", "[] if self.average != \"micro\": self.axis = 0 self.init_shape =", "__init__(self, num_classes, average=None, beta=1.0, threshold=None, name=\"fbeta_score\", dtype=None, **kwargs): super().__init__(name=name, dtype=dtype)", "def get_config(self): base_config = super().get_config() del base_config[\"beta\"] return base_config def", "+ num_samples_in_batch] = list(map(lambda x: len(x[0]), batch_data)) allocation_index += num_samples_in_batch", "label_mapping = ['PAD'] + label_mapping elif 0 not in label_mapping.values():", "the background label bg_label_tf = tf.keras.backend.constant( default_ind, dtype=argmax_layer.dtype) # Generate", "\" must be a non-empty list of \" \"integers.\") else:", "from .. import dp_logging from . import labeler_utils from .base_model", "loss: %f - acc: %f - \" \"f1_score %f\" %", "in tf_model.variables: if 'training' not in var.name: tf1_weights.append(var.value()) loaded_model._construct_model() tf1_weights.append(loaded_model._model.weights[-1].value())", "0 not in label_mapping.values(): # if dict missing PAD and", "= {softmax_output_layer_name: ['acc', f1_score_training]} self._model.compile(loss=losses, optimizer=\"adam\", metrics=metrics) self._epoch_id = 0", "whether to print status or not :type verbose: bool :return:", "def predict(self, data, batch_size=32, show_confidences=False, verbose=True): \"\"\" Run model and", "isinstance(label_mapping, list): # if list missing PAD label_mapping = ['PAD']", "raise TypeError(\"The value of beta should be a python float\")", "are considered to be 1, and the rest 0. If", "name of the metric instance. dtype: (Optional) Data type of", "for TensorFlow argmax_layer = tf.keras.backend.argmax(final_softmax_layer) # Create confidence layers final_predicted_layer", "labeler_utils.evaluate_accuracy( np.concatenate(y_val_pred, axis=0), np.concatenate(y_val_test, axis=0), self.num_labels, self.reverse_label_mapping, verbose=verbose_keras) return f1,", ":type n_dims: int :param source_file: Location of original embeddings to", "layer def encoding_function(input_str): char_in_vector = CharacterLevelCnnModel._char_encoding_layer( input_str, max_char_encoding_id, max_length) return", "and confidences :rtype: dict \"\"\" if not self._model: raise ValueError(\"You", "the precision and recall. Default value is 1. threshold: Elements", "converted to 1, and the rest 0. name: (Optional) String", "len(x[0]), batch_data)) allocation_index += num_samples_in_batch # Convert predictions, confidences to", "run-time type checking for functions def __init__(self, num_classes, average=None, threshold=None,", "_zero_wt_init(\"false_negatives\") self.weights_intermediate = _zero_wt_init(\"weights_intermediate\") def update_state(self, y_true, y_pred, sample_weight=None): if", "initial_value=thresh_init(shape=[num_labels_]), trainable=False) def call(self, argmax_layer, confidence_layer): threshold_at_argmax = tf.gather(self.thresh_vec, argmax_layer)", "pre-trained weight matrix # character encoding indices range from 0", "__eq__(self, other): \"\"\" Checks if two models are equal with", "use this file except in compliance with the License. #", "mode='constant') if show_confidences: confidences[allocation_index:allocation_index + num_samples_in_batch] = model_output[0].numpy() predictions[allocation_index:allocation_index +", "directory path where you want to save the model to", "and label_mapping.get('PAD', None) != 0): # dict with bad PAD", "the validation :type val_data: iterator :param batch_size_test: Number of samples", "np.concatenate(y_val_pred, axis=0), np.concatenate(y_val_test, axis=0), self.num_labels, self.reverse_label_mapping, verbose=verbose_keras) return f1, f1_report", "= model_output[0].numpy() predictions[allocation_index:allocation_index + num_samples_in_batch] = model_output[1].numpy() sentence_lengths[allocation_index:allocation_index + num_samples_in_batch]", "test set batch_id = 0 y_val_pred = [] y_val_test =", "= sentences_encode.to_tensor(shape=[None, max_len]) return sentences_encode_pad @staticmethod def _argmax_threshold_layer(num_labels, threshold=0.0, default_ind=1):", "__init__(self, label_mapping=None, parameters=None): \"\"\" CNN Model Initializer. initialize epoch_id :param", "threshold: default set to 0 so all confidences pass. :type", "= tf.reduce_sum(f1_score * weights) elif self.average is not None: #", "important variables, i.e. may not check model itself. :param self:", "of number of labels is altered :return: None \"\"\" #", "self._parameters['max_length'])) if show_confidences: confidences = np.zeros((batch_size, self._parameters['max_length'], self.num_labels)) # Run", "if val_data: f1, f1_report = self._validate_training(val_data) history['f1_report'] = f1_report val_f1", "char_in_vector self._model.add(tf.keras.layers.Input(shape=(None,), dtype=tf.string)) self._model.add( tf.keras.layers.Lambda(encoding_function, output_shape=tuple([max_length]))) # Create a pre-trained", "tf.keras.layers.Lambda(encoding_function, output_shape=tuple([max_length]))) # Create a pre-trained weight matrix # character", "altered :return: None \"\"\" # Reset model tf.keras.backend.clear_session() num_labels =", "Reset model tf.keras.backend.clear_session() num_labels = self.num_labels default_ind = self.label_mapping[self._parameters['default_label']] #", "None: val = tf.math.multiply(val, tf.expand_dims(sample_weight, 1)) return tf.reduce_sum(val, axis=self.axis) self.true_positives.assign_add(_weighted_sum(y_pred", "The TensorFlow Authors. All Rights Reserved. # # Licensed under", "model :type self: BaseModel :type other: BaseModel :return: Whether or", "softmax_output_layer_name = self._model.outputs[0].name.split('/')[0] losses = {softmax_output_layer_name: \"categorical_crossentropy\"} # use f1", "as fp: json.dump(self._parameters, fp) labels_dirpath = os.path.join(dirpath, \"label_mapping.json\") with open(labels_dirpath,", "= np.pad(predictions, ((0, len(predictions)), (0, 0)), mode='constant') sentence_lengths = np.pad(", "model label mapping definitions have been \" \"altered without additional", "greater than threshold are converted to be 1, and the", "labels for the model :param label_mapping: label mapping of the", "be a non-empty encoding dict \" \"which maps labels to", "a python float\") if beta <= 0.0: raise ValueError(\"beta value", "(list, dict)): raise TypeError(\"Labels must either be a non-empty encoding", "{softmax_output_layer_name: y_train}) sys.stdout.flush() if verbose: sys.stdout.write( \"\\rEPOCH %d, batch_id %d:", "whether user wants prediction confidences :type show_confidences: :param verbose: Flag", "the model on the test set and return the evaluation", "'conf': confidences_list} return {'pred': predictions_list} def details(self): \"\"\" Prints the", "def __eq__(self, other): \"\"\" Checks if two models are equal", "######\\n\") self._model.summary() print(\"\\nModel Parameters:\") for key, value in self._parameters.items(): print(\"{}:", "self.average == \"weighted\": weights = tf.math.divide_no_nan( self.weights_intermediate, tf.reduce_sum(self.weights_intermediate) ) f1_score", "zip(embd_words, reduced_embds): file.write(word + \" \" + ' '.join(str(num) for", "parameters.setdefault('size_conv', 13) parameters.setdefault('default_label', \"UNKNOWN\") parameters.setdefault('num_fil', [48 for _ in range(4)])", "Model Details ######\\n\") self._model.summary() print(\"\\nModel Parameters:\") for key, value in", "Pre-allocate space for predictions confidences = [] sentence_lengths = np.zeros((batch_size,),", "predictions_list = [i for i in range(0, allocation_index)] confidences_list =", "[] y_val_test = [] for x_val, y_val in val_data: y_val_pred.append(self._model.predict(", "iterator :param batch_size_test: Number of samples to process in testing", "list_of_necessary_params = ['max_length', 'max_char_encoding_id', 'dim_embed', 'size_fc', 'dropout', 'size_conv', 'default_label', 'pad_label',", "under the License. # ============================================================================== It is the harmonic mean", "label_mapping: dict :return: None \"\"\" if not isinstance(label_mapping, (list, dict)):", "self._epoch_id = 0 self._model_num_labels = num_labels self._model_default_ind = default_ind def", "label_mapping=None, reset_weights=False, verbose=True): \"\"\" Train the current model with the", "f1 = None f1_report = [] self._model.reset_metrics() softmax_output_layer_name = self._model.outputs[0].name.split('/')[0]", "f1_report else np.NAN val_recall = f1_report['weighted avg']['recall'] \\ if f1_report", "+ tf.math.square(self.beta)) if self.average == \"weighted\": weights = tf.math.divide_no_nan( self.weights_intermediate,", "= ['max_length', 'max_char_encoding_id', 'dim_embed', 'size_fc', 'dropout', 'size_conv', 'default_label', 'pad_label', 'num_fil']", "out-of-vocabulary character embed_file = os.path.join( _file_dir, \"embeddings/glove-reduced-{}D.txt\".format( self._parameters['dim_embed'])) embedding_matrix =", "threshold=None, name=\"fbeta_score\", dtype=None, **kwargs): super().__init__(name=name, dtype=dtype) if average not in", "self._need_to_reconstruct_model(): raise RuntimeError(\"The model label mapping definitions have been \"", "trying to predict without a model. \" \"Construct/Load a model", "if not isinstance(item, int): errors.append(param + \" must be a", ".pb file for TensorFlow argmax_layer = tf.keras.backend.argmax(final_softmax_layer) # Create confidence", "= build_embd_dictionary(source_file) embd_words, embd_matrix = [ np.asarray(ls) if i >", "Loads whole model from disk with weights :param dirpath: directory", "None: return f1, f1_report # Predict on the test set", "self.weights_intermediate, tf.reduce_sum(self.weights_intermediate) ) f1_score = tf.reduce_sum(f1_score * weights) elif self.average", "in self._parameters['num_fil']: self._model.add(tf.keras.layers.Conv1D( filters=fil, kernel_size=self._parameters['size_conv'], activation='relu', padding='same')) if self._parameters['dropout']: self._model.add(", "if self._parameters != other._parameters \\ or self._label_mapping != other._label_mapping: return", "in compliance with the License. # You may obtain a", "with open(labels_dirpath, 'r') as fp: label_mapping = json.load(fp) # use", "= os.path.join(dirpath, \"model_parameters.json\") with open(model_param_dirpath, 'w') as fp: json.dump(self._parameters, fp)", "num_labels, activation='softmax', name=\"dense_2\")( self._model.layers[-4].output) # Output the model into a", "RuntimeError(\"The model label mapping definitions have been \" \"altered without", "software # distributed under the License is distributed on an", "\\textrm{precision}}{(\\beta^2 \\cdot \\textrm{precision}) + \\textrm{recall}} $$ Args: num_classes: Number of", "json.load(fp) # use f1 score metric custom_objects = { \"F1Score\":", "if invalid parameters are present. :param parameters: parameter dict containing", "Create a vector the same size as the batch_size which", "batch_id %d: loss: %f - acc: %f - \" \"f1_score", "int :param max_len: Maximum char length in a sample :type", "\" \"val_f1: %f - val_precision: %f - val_recall %f\" %", "set to 0 so all confidences pass. :type threshold: float", "0): # dict with bad PAD raise ValueError(\"`PAD` must map", "model_output[1].numpy() sentence_lengths[allocation_index:allocation_index + num_samples_in_batch] = list(map(lambda x: len(x[0]), batch_data)) allocation_index", "F1Score(num_classes=num_labels, average='micro') metrics = {softmax_output_layer_name: ['acc', f1_score_training]} self._model.compile(loss=losses, optimizer=\"adam\", metrics=metrics)", "(isinstance(label_mapping, dict) and label_mapping.get('PAD', None) != 0): # dict with", "the training data and validation data :param train_data: Training data", "dropout: Ratio of dropout in the model size_conv: Convolution kernel", "or parameters[param] > 1: errors.append(param + \" must be a", "'training' not in var.name: tf1_weights.append(var.value()) loaded_model._construct_model() tf1_weights.append(loaded_model._model.weights[-1].value()) loaded_model._model.set_weights(tf1_weights) # load", "is the pad label num_fil: Number of filters in each", "= num_labels self._model_default_ind = default_ind def reset_weights(self): \"\"\" Reset the", "the label mapping to \" \"predict.\") # Pre-allocate space for", "reserved requires_zero_mapping = True def __init__(self, label_mapping=None, parameters=None): \"\"\" CNN", "# Create a vector the same size as the batch_size", "allocation_index)] # Append slices of predictions to return prediction &", "recall. Default value is 1. threshold: Elements of `y_pred` greater", "label_mapping is not None: self.set_label_mapping(label_mapping) if not self._model: self._construct_model() else:", "None] :param reset_weights: Flag to determine whether to reset the", "\" \"are: [None, 'micro', 'macro', 'weighted']\" ) if not isinstance(beta,", "not self._model: self._construct_model() else: if self._need_to_reconstruct_model(): self._reconstruct_model() if reset_weights: self.reset_weights()", "you want to save the model to :type dirpath: str", "self.axis = 0 self.init_shape = [self.num_classes] def _zero_wt_init(name): return self.add_weight(", "self._model.train_on_batch( x_train, {softmax_output_layer_name: y_train}) sys.stdout.flush() if verbose: sys.stdout.write( \"\\rEPOCH %d,", "= precision * recall add_value = (tf.math.square(self.beta) * precision) +", "return False default_ind = self.label_mapping[self._parameters['default_label']] return self.num_labels != self._model_num_labels or", "threshold = tf.reduce_max(y_pred, axis=-1, keepdims=True) # make sure [0, 0,", "0 # reconstruct flags for model self._model_num_labels = 0 self._model_default_ind", "batch_id = 0 y_val_pred = [] y_val_test = [] for", "0 self._model_num_labels = num_labels self._model_default_ind = default_ind def reset_weights(self): \"\"\"", "is not an accepted parameter.\") if errors: raise ValueError('\\n'.join(errors)) def", "Adapted and slightly modified from https://github.com/tensorflow/addons/blob/v0.12.0/tensorflow_addons/metrics/f_scores.py#L211-L283 # Copyright 2019 The", "parameters=None): \"\"\" CNN Model Initializer. initialize epoch_id :param label_mapping: maps", "directory path where you want to load the model from", "for that argmax meets the threshold for its label, otherwise", "to the embed file for loading :type filename: str \"\"\"", "for TensorFlow argmax_layer = tf.keras.backend.argmax(self._model.output) # Create confidence layers final_predicted_layer", "- f1_score %f -- \" \"val_f1: %f - val_precision: %f", "threshold <= 0.0: raise ValueError(\"threshold should be between 0 and", ":param dirpath: directory path where you want to load the", "pad_width=((0, len(sentence_lengths)),), mode='constant') if show_confidences: confidences = np.pad(confidences, ((0, len(predictions)),", "sample_weight=None): if self.threshold is None: threshold = tf.reduce_max(y_pred, axis=-1, keepdims=True)", "chars embeddings from source file to n_dims principal components in", "1, average='micro'), \"CharacterLevelCnnModel\": cls, } with tf.keras.utils.custom_object_scope(custom_objects): tf_model = tf.keras.models.load_model(dirpath)", "n_dims principal components in a new file :param n_dims: Final", "set_label_mapping(self, label_mapping): \"\"\" Sets the labels for the model :param", "# generate glove embedding create_glove_char(self._parameters['dim_embed']) # generate model self._model =", "list): # if list missing PAD label_mapping = ['PAD'] +", "break elif param == 'default_label': if not isinstance(parameters[param], str): error", "tf from sklearn import decomposition from .. import dp_logging from", "\\ if f1_report else np.NAN epoch_time = time.time() - start_time", "embeddings :type n_dims: int :param source_file: Location of original embeddings", "self.threshold y_true = tf.cast(y_true, self.dtype) y_pred = tf.cast(y_pred, self.dtype) def", "= loaded_model.label_mapping[ loaded_model._parameters['default_label'] ] return loaded_model @staticmethod def _char_encoding_layer(input_str_tensor, max_char_encoding_id,", "Determines the weight given to the precision and recall. Default", "the model. :return: None \"\"\" self._construct_model() def _reconstruct_model(self): \"\"\" Reconstruct", "validation_batch_id %d\" % (self._epoch_id, batch_id)) tf.keras.backend.set_floatx('float32') # Clean the predicted", "name='ThreshVec', initial_value=thresh_init(shape=[num_labels_]), trainable=False) def call(self, argmax_layer, confidence_layer): threshold_at_argmax = tf.gather(self.thresh_vec,", "harmonic mean. Determines the weight given to the precision and", "Run model and get predictions :param data: text input :type", "int :param show_confidences: whether user wants prediction confidences :type show_confidences:", "> 1: errors.append(param + \" must be a valid integer", "0.0: raise ValueError(\"threshold should be between 0 and 1\") self.num_classes", "layer's output will be the argmax value if the confidence", "a non-empty \" \"list of integers.\") break elif param ==", "def _need_to_reconstruct_model(self): \"\"\" Determines whether or not the model needs", "os.path.join(_file_dir, \"embeddings/glove.840B.300d-char.txt\") # get embedding table first and vectors as", "the input dim_embed: Number of embedded dimensions size_fc: Size of", "predictions and confidences :rtype: dict \"\"\" if not self._model: raise", "= copy.deepcopy(label_mapping) if 'PAD' not in label_mapping: if isinstance(label_mapping, list):", "loaded_model.num_labels loaded_model._model_default_ind = loaded_model.label_mapping[ loaded_model._parameters['default_label'] ] return loaded_model @staticmethod def", "f1 = None f1_report = None if val_data is None:", "harmonic mean of precision and recall. Output range is `[0,", "dim_embed, size_fc dropout, size_conv, num_fil, optimizer, default_label :type parameters: dict", "raise TypeError(\"Labels must either be a non-empty encoding dict \"", "serializable config of the metric.\"\"\" config = { \"num_classes\": self.num_classes,", "index :type default_ind: int :return: final argmax threshold layer for", "None \"\"\" if not self._model: self._construct_model() elif self._need_to_reconstruct_model(): self._reconstruct_model() model_param_dirpath", "from . import labeler_utils from .base_model import AutoSubRegistrationMeta, BaseModel, BaseTrainableModel", "[i for i in range(0, allocation_index)] confidences_list = None if", "score metric custom_objects = { \"F1Score\": F1Score( num_classes=max(label_mapping.values()) + 1,", "non-empty list of \" \"integers.\") else: for item in parameters[param]:", "losses = {softmax_output_layer_name: \"categorical_crossentropy\"} # use f1 score metric f1_score_training", "with the License. # You may obtain a copy of", ") mul_value = precision * recall add_value = (tf.math.square(self.beta) *", "0] doesn't become [1, 1, 1] # Use abs(x) >", "beta self.threshold = threshold self.axis = None self.init_shape = []", "batch_size=batch_size_test, verbose=verbose_keras)[1]) y_val_test.append(np.argmax(y_val, axis=-1)) batch_id += 1 sys.stdout.flush() if verbose_log:", "PAD raise ValueError(\"`PAD` must map to index zero.\") if self._parameters['default_label']", "= self.num_labels default_ind = self.label_mapping[self._parameters['default_label']] # Reset model tf.keras.backend.clear_session() #", "Used to determine number of samples in each batch :type", "# Double array size if len(predictions) <= allocation_index: predictions =", "data and validation data :param train_data: Training data used to", "(1 - y_true), sample_weight) ) self.false_negatives.assign_add( _weighted_sum((1 - y_pred) *", "under the License. # ============================================================================== It is the weighted harmonic", "as embds: for line in embds: line = line.strip().split() embd_table[line[0]]", "embedded dimensions size_fc: Size of each fully connected layers dropout:", "be transferred. if not callable(tf_model): loaded_model._construct_model() tf1_weights = [] for", "errors: raise ValueError('\\n'.join(errors)) def set_label_mapping(self, label_mapping): \"\"\" Sets the labels", "or float \" \"greater than 0.\") elif param == 'dropout':", "is converted to 1, and the rest 0. name: (Optional)", "\"categorical_crossentropy\"} # use f1 score metric f1_score_training = F1Score(num_classes=num_labels, average='micro')", "generate model self._model = tf.keras.models.Sequential() # default parameters max_length =", "Ratio of dropout in the model size_conv: Convolution kernel size", "isinstance(parameters[param], (int, float)) \\ or parameters[param] < 0 or parameters[param]", "tf.keras.backend.max(confidence_layer, axis=2) # Check if the confidences meet the threshold", "None \"\"\" num_labels = self.num_labels default_ind = self.label_mapping[self._parameters['default_label']] # Reset", "tf_model = tf.keras.models.load_model(dirpath) loaded_model = cls(label_mapping, parameters) loaded_model._model = tf_model", "0 and 1\") self.num_classes = num_classes self.average = average self.beta", "\"UNKNOWN\") parameters.setdefault('num_fil', [48 for _ in range(4)]) parameters['pad_label'] = 'PAD'", "reset_weights: Flag to determine whether to reset the weights or", "get predictions :param data: text input :type data: Union[list, numpy.ndarray]", "= self._model.outputs[0].name.split('/')[0] start_time = time.time() batch_id = 0 for x_train,", "needs to be reconstructed. :return: bool of whether or not", ":type other: BaseModel :return: Whether or not self and other", "# Modification: remove the run-time type checking for functions def", "express or implied. # See the License for the specific", "except in compliance with the License. # You may obtain", "+ 1, average='micro'), \"CharacterLevelCnnModel\": cls, } with tf.keras.utils.custom_object_scope(custom_objects): tf_model =", "be a non-empty \" \"list of integers.\") break elif param", "%f - acc: %f - \" \"f1_score %f\" % (self._epoch_id,", "Prints the relevant details of the model (summary, parameters, label", "= time.time() batch_id = 0 for x_train, y_train in train_data:", "self.false_positives = _zero_wt_init(\"false_positives\") self.false_negatives = _zero_wt_init(\"false_negatives\") self.weights_intermediate = _zero_wt_init(\"weights_intermediate\") def", "\"\"\" errors = [] list_of_necessary_params = ['max_length', 'max_char_encoding_id', 'dim_embed', 'size_fc',", "\"label mapping.\".format( self._parameters['default_label'])) super().set_label_mapping(label_mapping) def _need_to_reconstruct_model(self): \"\"\" Determines whether or", "the weights or not :type reset_weights: bool :param verbose: Flag", "model_output[0].numpy() predictions[allocation_index:allocation_index + num_samples_in_batch] = model_output[1].numpy() sentence_lengths[allocation_index:allocation_index + num_samples_in_batch] =", "path where you want to load the model from :type", "threshold is None, the argmax is converted to 1, and", "embd_matrix = [ np.asarray(ls) if i > 0 else list(ls)", "\"\"\" Character encoding for the list of sentences :param input_str_tensor:", "initialize epoch_id :param label_mapping: maps labels to their encoded integers", "be the argmax value if the confidence for that argmax", "argmax is converted to 1, and the rest 0. name:", "config = { \"num_classes\": self.num_classes, \"average\": self.average, \"beta\": self.beta, \"threshold\":", "not in label_mapping.values(): # if dict missing PAD and 0", "source_file: Location of original embeddings to factor down :type source_file:", "get embedding table first and vectors as array embd_table =", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "= [] for var in tf_model.variables: if 'training' not in", "in train_data: model_results = self._model.train_on_batch( x_train, {softmax_output_layer_name: y_train}) sys.stdout.flush() if", ":param data: text input :type data: Union[list, numpy.ndarray] :param batch_size:", "range(4)]) parameters['pad_label'] = 'PAD' self._epoch_id = 0 # reconstruct flags", "model self._model_num_labels = 0 self._model_default_ind = -1 BaseModel.__init__(self, label_mapping, parameters)", "# ============================================================================== It is the harmonic mean of precision and", "of whether or not the model needs to reconstruct. \"\"\"", "reconstructed. :return: bool of whether or not the model needs", "components in a new file :param n_dims: Final number of", "the necessary parameters are present and valid. for param in", "may only check important variables, i.e. may not check model", "data :param train_data: Training data used to train model :type", "pad_label: Key for entities_dict that is the pad label num_fil:", "two models are equal with one another, may only check", "Saves whole model to disk with weights :param dirpath: directory", "sentences_encode.to_tensor(shape=[None, max_len]) return sentences_encode_pad @staticmethod def _argmax_threshold_layer(num_labels, threshold=0.0, default_ind=1): \"\"\"", "CONDITIONS OF ANY KIND, either express or implied. # See", "start_time logger.info(\"\\rEPOCH %d (%ds), loss: %f - acc: %f -", "- y_pred) * y_true, sample_weight) ) self.weights_intermediate.assign_add(_weighted_sum(y_true, sample_weight)) def result(self):", "loaded_model._model = tf_model # Tensorflow v1 Model weights need to", "sentence_lengths[allocation_index:allocation_index + num_samples_in_batch] = list(map(lambda x: len(x[0]), batch_data)) allocation_index +=", "decomposition from .. import dp_logging from . import labeler_utils from", "= f1_report val_f1 = f1_report['weighted avg']['f1-score'] \\ if f1_report else", "result. Returns: F-1 Score: float. \"\"\" # Modification: remove the", "list of sentences converted to tensor :type input_str_tensor: tf.tensor :param", "of integers.\") break elif param == 'default_label': if not isinstance(parameters[param],", "return tf.reduce_sum(val, axis=self.axis) self.true_positives.assign_add(_weighted_sum(y_pred * y_true, sample_weight)) self.false_positives.assign_add( _weighted_sum(y_pred *", "principal component dims of the embeddings :type n_dims: int :param", "parameters.setdefault('dropout', 0.073) parameters.setdefault('size_conv', 13) parameters.setdefault('default_label', \"UNKNOWN\") parameters.setdefault('num_fil', [48 for _", "= { \"num_classes\": self.num_classes, \"average\": self.average, \"beta\": self.beta, \"threshold\": self.threshold,", "must be a non-empty list of \" \"integers.\") else: for", "Details ######\\n\") self._model.summary() print(\"\\nModel Parameters:\") for key, value in self._parameters.items():", "if 'PAD' not in label_mapping: if isinstance(label_mapping, list): # if", "str :return: None \"\"\" # load parameters model_param_dirpath = os.path.join(dirpath,", "reset_value) for v in self.variables]) @tf.keras.utils.register_keras_serializable() class F1Score(FBetaScore): r\"\"\"Computes F-1", "{ \"F1Score\": F1Score( num_classes=max(label_mapping.values()) + 1, average='micro'), \"CharacterLevelCnnModel\": cls, }", "layers for size in self._parameters['size_fc']: self._model.add( tf.keras.layers.Dense(units=size, activation='relu')) if self._parameters['dropout']:", "acc: %f - f1_score %f -- \" \"val_f1: %f -", "time.time() - start_time logger.info(\"\\rEPOCH %d (%ds), loss: %f - acc:", "in range(0, allocation_index)] confidences_list = None if show_confidences: confidences_list =", "tf.keras.layers.Dropout(self._parameters['dropout'])) # Add the final Softmax layer self._model.add( tf.keras.layers.Dense(num_labels, activation='softmax'))", "tf.add(tf.cast(1, tf.int32), sentences_encode) sentences_encode = tf.math.minimum(sentences_encode, max_char_encoding_id + 1) #", "constructor for the data labeler. This also serves as a", "range(0, allocation_index)] # Append slices of predictions to return prediction", "their encoded integers :type label_mapping: Union[dict, None] :param reset_weights: Flag", "to determine whether to print status or not :type verbose:", "= CharacterLevelCnnModel._char_encoding_layer( input_str, max_char_encoding_id, max_length) return char_in_vector self._model.add(tf.keras.layers.Input(shape=(None,), dtype=tf.string)) self._model.add(", "sentence_lengths = np.pad( sentence_lengths, pad_width=((0, len(sentence_lengths)),), mode='constant') if show_confidences: confidences", "batch_size: int :param label_mapping: maps labels to their encoded integers", "the data labeler. This also serves as a weight reset.", "y_true, y_pred, sample_weight=None): if self.threshold is None: threshold = tf.reduce_max(y_pred,", "file for TensorFlow argmax_layer = tf.keras.backend.argmax(self._model.output) # Create confidence layers", "i.e. may not check model itself. :param self: a model", "model :type train_data: Union[list, np.ndarray] :param val_data: Validation data used", "of samples in batch to prevent array mismatch num_samples_in_batch =", "each fully connected layers dropout: Ratio of dropout in the", "requires the mapping for index 0 reserved requires_zero_mapping = True", "[] list_of_necessary_params = ['max_length', 'max_char_encoding_id', 'dim_embed', 'size_fc', 'dropout', 'size_conv', 'default_label',", "or \\ default_ind != self._model_default_ind def save_to_disk(self, dirpath): \"\"\" Saves", "batch_id += 1 for i, metric_label in enumerate(self._model.metrics_names): history[metric_label] =", "as np import tensorflow as tf from sklearn import decomposition", "\" \"from 0 to 1.\") elif param == 'size_fc' or", "max_len]) return sentences_encode_pad @staticmethod def _argmax_threshold_layer(num_labels, threshold=0.0, default_ind=1): \"\"\" Adds", "64) parameters.setdefault('size_fc', [96, 96]) parameters.setdefault('dropout', 0.073) parameters.setdefault('size_conv', 13) parameters.setdefault('default_label', \"UNKNOWN\")", "the function: final_predicted_layer = tf.add( bg_label_tf, tf.multiply( tf.subtract(argmax_layer, bg_label_tf), argmax_mask", "converted to tensor :type input_str_tensor: tf.tensor :param max_char_encoding_id: Maximum integer", "= CharacterLevelCnnModel._argmax_threshold_layer( num_labels, threshold=0.0, default_ind=default_ind) argmax_outputs = [final_softmax_layer] + \\", "verbose_keras=False): \"\"\" Validate the model on the test set and", "if not isinstance(parameters[param], (int, float)) \\ or parameters[param] < 0:", "ValueError(\"The `default_label` of {} must exist in the \" \"label", "\"\"\" if not isinstance(label_mapping, (list, dict)): raise TypeError(\"Labels must either", "= defaultdict() f1 = None f1_report = [] self._model.reset_metrics() softmax_output_layer_name", "whether or not to print out scores for training, from", "not in label_mapping: raise ValueError(\"The `default_label` of {} must exist", "\"are: [None, 'micro', 'macro', 'weighted']\" ) if not isinstance(beta, float):", "other: BaseModel :return: Whether or not self and other are", "- val_precision: %f - val_recall %f\" % (self._epoch_id, epoch_time, *model_results[1:],", "num_labels. Other possible parameters are: max_length, max_char_encoding_id, dim_embed, size_fc dropout,", "reduced_embds): file.write(word + \" \" + ' '.join(str(num) for num", "self.label_mapping[self._parameters['default_label']] return self.num_labels != self._model_num_labels or \\ default_ind != self._model_default_ind", "max_char_encoding_id: Maximum integer value for encoding the input :type max_char_encoding_id:", "with GloVe-like format :param filename: Path to the embed file", "used to validate the training :type val_data: Union[list, np.ndarray] :param", "at # # http://www.apache.org/licenses/LICENSE-2.0 # https://github.com/tensorflow/addons/blob/v0.12.0/LICENSE # # Unless required", "else: if self._need_to_reconstruct_model(): self._reconstruct_model() if reset_weights: self.reset_weights() history = defaultdict()", "each convolution layer :type parameters: dict :return: None \"\"\" errors", "self.false_negatives.assign_add( _weighted_sum((1 - y_pred) * y_true, sample_weight) ) self.weights_intermediate.assign_add(_weighted_sum(y_true, sample_weight))", "\\ in enumerate(sentence_lengths[:allocation_index]): predictions_list[index] = list(predictions[index][:sentence_length]) if show_confidences: confidences_list[index] =", "final_softmax_layer)] self._model = tf.keras.Model(self._model.inputs, argmax_outputs) # Compile the model softmax_output_layer_name", "enumerate(self._model.metrics_names): history[metric_label] = model_results[i] if val_data: f1, f1_report = self._validate_training(val_data)", "the final Softmax layer to the previous spot final_softmax_layer =", "def __init__(self, num_classes, average=None, beta=1.0, threshold=None, name=\"fbeta_score\", dtype=None, **kwargs): super().__init__(name=name,", "\\ or parameters[param] < 0: errors.append(param + \" must be", "for index 0 reserved requires_zero_mapping = True def __init__(self, label_mapping=None,", "0}) if (isinstance(label_mapping, dict) and label_mapping.get('PAD', None) != 0): #", "* (1 - y_true), sample_weight) ) self.false_negatives.assign_add( _weighted_sum((1 - y_pred)", "input_str_tensor: tf.tensor :param max_char_encoding_id: Maximum integer value for encoding the", "for i, metric_label in enumerate(self._model.metrics_names): history[metric_label] = model_results[i] if val_data:", "tf.keras.backend.cast( tf.keras.backend.greater_equal(confidence_max_layer, threshold_at_argmax), dtype=argmax_layer.dtype) # Create a vector the same", "batch_size_test: int :param verbose_log: whether or not to print out", "dataset. average: Type of averaging to be performed on data.", "of samples in each batch :type batch_size: int :param label_mapping:", "as array embd_table = build_embd_dictionary(source_file) embd_words, embd_matrix = [ np.asarray(ls)", "+ \" \" + ' '.join(str(num) for num in embd)", "self.init_shape = [self.num_classes] def _zero_wt_init(name): return self.add_weight( name, shape=self.init_shape, initializer=\"zeros\",", "= 'PAD' self._epoch_id = 0 # reconstruct flags for model", "the threshold minimum. argmax_mask = tf.keras.backend.cast( tf.keras.backend.greater_equal(confidence_max_layer, threshold_at_argmax), dtype=argmax_layer.dtype) #", "# Predict on the test set batch_id = 0 y_val_pred", "np.NAN val_recall = f1_report['weighted avg']['recall'] \\ if f1_report else np.NAN", "== \"weighted\": weights = tf.math.divide_no_nan( self.weights_intermediate, tf.reduce_sum(self.weights_intermediate) ) f1_score =", "optimizer=\"adam\", metrics=metrics) self._epoch_id = 0 self._model_num_labels = num_labels self._model_default_ind =", "= tf.keras.backend.argmax(self._model.output) # Create confidence layers final_predicted_layer = CharacterLevelCnnModel._argmax_threshold_layer( num_labels,", "Elements of `y_pred` greater than threshold are converted to be", "1]`. Works for both multi-class and multi-label classification. $$ F_1", "will be the default label index. :param num_labels: number of", "def load_from_disk(cls, dirpath): \"\"\" Loads whole model from disk with", "self._model_num_labels = num_labels self._model_default_ind = default_ind def reset_weights(self): \"\"\" Reset", "Create a pre-trained weight matrix # character encoding indices range", "# [micro, macro] f1_score = tf.reduce_mean(f1_score) return f1_score def get_config(self):", "**config} def reset_states(self): reset_value = tf.zeros(self.init_shape, dtype=self.dtype) tf.keras.backend.batch_set_value([(v, reset_value) for", "parameters = {} parameters.setdefault('max_length', 3400) parameters.setdefault('max_char_encoding_id', 127) parameters.setdefault('dim_embed', 64) parameters.setdefault('size_fc',", "size in self._parameters['size_fc']: self._model.add( tf.keras.layers.Dense(units=size, activation='relu')) if self._parameters['dropout']: self._model.add( tf.keras.layers.Dropout(self._parameters['dropout']))", ":param verbose_log: whether or not to print out scores for", "level predictions and confidences :rtype: dict \"\"\" if not self._model:", "open(labels_dirpath, 'w') as fp: json.dump(self.label_mapping, fp) self._model.save(os.path.join(dirpath)) @classmethod def load_from_disk(cls,", "num_labels self._model_default_ind = default_ind def reset_weights(self): \"\"\" Reset the weights", "type of the metric result. Returns: F-Beta Score: float. \"\"\"", "dtype: (Optional) Data type of the metric result. Returns: F-1", "Number of embedded dimensions size_fc: Size of each fully connected", "into a .pb file for TensorFlow argmax_layer = tf.keras.backend.argmax(final_softmax_layer) #", "labels to their encoded integers :type label_mapping: dict :param parameters:", "tf1_weights.append(loaded_model._model.weights[-1].value()) loaded_model._model.set_weights(tf1_weights) # load self loaded_model._model_num_labels = loaded_model.num_labels loaded_model._model_default_ind =", "metric f1_score_training = F1Score(num_classes=num_labels, average='micro') metrics = {softmax_output_layer_name: ['acc', f1_score_training]}", "dtype=dtype) def get_config(self): base_config = super().get_config() del base_config[\"beta\"] return base_config", "principal components in a new file :param n_dims: Final number", "\" must be a non-empty \" \"list of integers.\") break", "`y_pred` greater than threshold are converted to be 1, and", ":return: None \"\"\" # Reset model tf.keras.backend.clear_session() num_labels = self.num_labels", "tf.keras.backend.clear_session() num_labels = self.num_labels default_ind = self.label_mapping[self._parameters['default_label']] # Remove the", "Add the final Softmax layer to the previous spot final_softmax_layer", "as fp: parameters = json.load(fp) # load label_mapping labels_dirpath =", "of the metric result. Returns: F-1 Score: float. \"\"\" #", "reset_states(self): reset_value = tf.zeros(self.init_shape, dtype=self.dtype) tf.keras.backend.batch_set_value([(v, reset_value) for v in", "self._need_to_reconstruct_model(): self._reconstruct_model() if reset_weights: self.reset_weights() history = defaultdict() f1 =", "is not None: # [micro, macro] f1_score = tf.reduce_mean(f1_score) return", "sentence_lengths = np.zeros((batch_size,), dtype=int) predictions = np.zeros((batch_size, self._parameters['max_length'])) if show_confidences:", "is altered :return: None \"\"\" # Reset model tf.keras.backend.clear_session() num_labels", "self.average is not None: # [micro, macro] f1_score = tf.reduce_mean(f1_score)", "build_embd_dictionary(source_file) embd_words, embd_matrix = [ np.asarray(ls) if i > 0", "not in list_of_necessary_params: errors.append(param + \" is not an accepted", "threshold self.axis = None self.init_shape = [] if self.average !=", "model :param label_mapping: label mapping of the model :type label_mapping:", "call(self, argmax_layer, confidence_layer): threshold_at_argmax = tf.gather(self.thresh_vec, argmax_layer) confidence_max_layer = tf.keras.backend.max(confidence_layer,", "val_data: y_val_pred.append(self._model.predict( x_val, batch_size=batch_size_test, verbose=verbose_keras)[1]) y_val_test.append(np.argmax(y_val, axis=-1)) batch_id += 1", "# Copyright 2019 The TensorFlow Authors. All Rights Reserved. #", "# use f1 score metric custom_objects = { \"F1Score\": F1Score(", "to process in testing :type batch_size_test: int :param verbose_log: whether", ":return: Whether or not self and other are equal :rtype:", "details(self): \"\"\" Prints the relevant details of the model (summary,", "if show_confidences: confidences_list = [i for i in range(0, allocation_index)]", "r\"\"\"Computes F-1 Score. # Copyright 2019 The TensorFlow Authors. All", "F-1 Score: float. \"\"\" # Modification: remove the run-time type", "[48 for _ in range(4)]) parameters['pad_label'] = 'PAD' self._epoch_id =", "scale=True)) # Add the fully connected layers for size in", "{}\".format(key, value)) print(\"\\nModel Label Mapping:\") for key, value in self.label_mapping.items():", "y_true), sample_weight) ) self.false_negatives.assign_add( _weighted_sum((1 - y_pred) * y_true, sample_weight)", "tf.zeros(self.init_shape, dtype=self.dtype) tf.keras.backend.batch_set_value([(v, reset_value) for v in self.variables]) @tf.keras.utils.register_keras_serializable() class", "self.true_positives.assign_add(_weighted_sum(y_pred * y_true, sample_weight)) self.false_positives.assign_add( _weighted_sum(y_pred * (1 - y_true),", "embd_file_name = os.path.join(dir_name, 'glove-reduced-{}D.txt'.format(n_dims)) with open(embd_file_name, 'w') as file: for", "= os.path.join(dirpath, \"label_mapping.json\") with open(labels_dirpath, 'r') as fp: label_mapping =", "argmax meets the threshold for its label, otherwise it will", "+ \" must be a valid integer or float \"", "line in embds: line = line.strip().split() embd_table[line[0]] = np.asarray(line[1:]) return", "max_char_encoding_id = self._parameters['max_char_encoding_id'] # Encoding layer def encoding_function(input_str): char_in_vector =", "\"\"\" if label_mapping is not None: self.set_label_mapping(label_mapping) if not self._model:", "elif 0 not in label_mapping.values(): # if dict missing PAD", "train_data, val_data=None, batch_size=32, label_mapping=None, reset_weights=False, verbose=True): \"\"\" Train the current", "model from disk with weights :param dirpath: directory path where", "Final number of principal component dims of the embeddings :type", "list) \\ or len(parameters[param]) == 0: errors.append(param + \" must", "in self._parameters['size_fc']: self._model.add( tf.keras.layers.Dense(units=size, activation='relu')) if self._parameters['dropout']: self._model.add( tf.keras.layers.Dropout(self._parameters['dropout'])) #", "2 \\cdot \\frac{\\textrm{precision} \\cdot \\textrm{recall}}{\\textrm{precision} + \\textrm{recall}} $$ Args: num_classes:", "integer value for encoding the input :type max_char_encoding_id: int :param", ":type verbose: bool :return: None \"\"\" if label_mapping is not", "type. Acceptable values \" \"are: [None, 'micro', 'macro', 'weighted']\" )", "be performed on data. Acceptable values are `None`, `micro`, `macro`", "metaclass=AutoSubRegistrationMeta): # boolean if the label mapping requires the mapping", "1, 1] # Use abs(x) > eps, instead of x", "dirpath: str :return: None \"\"\" # load parameters model_param_dirpath =", "as fp: label_mapping = json.load(fp) # use f1 score metric", "sentences converted to tensor :type input_str_tensor: tf.tensor :param max_char_encoding_id: Maximum", "if not parameters: parameters = {} parameters.setdefault('max_length', 3400) parameters.setdefault('max_char_encoding_id', 127)", "* precision) + recall mean = tf.math.divide_no_nan(mul_value, add_value) f1_score =", "# make sure [0, 0, 0] doesn't become [1, 1,", "sentence_length \\ in enumerate(sentence_lengths[:allocation_index]): predictions_list[index] = list(predictions[index][:sentence_length]) if show_confidences: confidences_list[index]", ".base_model import AutoSubRegistrationMeta, BaseModel, BaseTrainableModel _file_dir = os.path.dirname(os.path.abspath(__file__)) logger =", "the list of sentences :param input_str_tensor: input list of sentences", "f1_report['weighted avg']['precision'] \\ if f1_report else np.NAN val_recall = f1_report['weighted", "predictions :param data: text input :type data: Union[list, numpy.ndarray] :param", "all confidences pass. :type threshold: float :param default_ind: default index", "batch_size # Double array size if len(predictions) <= allocation_index: predictions", "Add the fully connected layers for size in self._parameters['size_fc']: self._model.add(", "1.0 or threshold <= 0.0: raise ValueError(\"threshold should be between", "errors.append(param + \" must be a non-empty list of \"", "for fil in self._parameters['num_fil']: self._model.add(tf.keras.layers.Conv1D( filters=fil, kernel_size=self._parameters['size_conv'], activation='relu', padding='same')) if", "= [] y_val_test = [] for x_val, y_val in val_data:", "(0, 0)), mode='constant') sentence_lengths = np.pad( sentence_lengths, pad_width=((0, len(sentence_lengths)),), mode='constant')", "update_state(self, y_true, y_pred, sample_weight=None): if self.threshold is None: threshold =", "\"\"\" Sets the labels for the model :param label_mapping: label", "loaded_model._parameters['default_label'] ] return loaded_model @staticmethod def _char_encoding_layer(input_str_tensor, max_char_encoding_id, max_len): \"\"\"", "argmax threshold layer for the model \"\"\" # Initialize the", "%f - val_precision: %f - val_recall %f\" % (self._epoch_id, epoch_time,", "mapping to \" \"predict.\") # Pre-allocate space for predictions confidences", "model with batching allocation_index = 0 for batch_id, batch_data in", "+= 1 return history, f1, f1_report def _validate_training(self, val_data, batch_size_test=32,", "in the dataset. average: Type of averaging to be performed", "parameters model_param_dirpath = os.path.join(dirpath, \"model_parameters.json\") with open(model_param_dirpath, 'r') as fp:", "{} parameters.setdefault('max_length', 3400) parameters.setdefault('max_char_encoding_id', 127) parameters.setdefault('dim_embed', 64) parameters.setdefault('size_fc', [96, 96])", "the \" \"label mapping.\".format( self._parameters['default_label'])) super().set_label_mapping(label_mapping) def _need_to_reconstruct_model(self): \"\"\" Determines", "'dim_embed', 'size_fc', 'dropout', 'size_conv', 'default_label', 'pad_label', 'num_fil'] # Make sure", "indices range from 0 to max_char_encoding_id, # we add one", "of `y_pred` above threshold are considered to be 1, and", "# Tensorflow v1 Model weights need to be transferred. if", "model with the training data and validation data :param train_data:", "if self._parameters['default_label'] not in label_mapping: raise ValueError(\"The `default_label` of {}", "reset the weights or not :type reset_weights: bool :param verbose:", "tf.math.divide_no_nan( self.true_positives, self.true_positives + self.false_negatives ) mul_value = precision *", "beta=1.0, threshold=None, name=\"fbeta_score\", dtype=None, **kwargs): super().__init__(name=name, dtype=dtype) if average not", "error if invalid parameters are present. :param parameters: parameter dict", "= np.pad( sentence_lengths, pad_width=((0, len(sentence_lengths)),), mode='constant') if show_confidences: confidences =", "# Remove the 3 output layers (dense_2', 'tf_op_layer_ArgMax', # 'thresh_arg_max_layer')", "$$ F_1 = 2 \\cdot \\frac{\\textrm{precision} \\cdot \\textrm{recall}}{\\textrm{precision} + \\textrm{recall}}", "loaded_model.label_mapping[ loaded_model._parameters['default_label'] ] return loaded_model @staticmethod def _char_encoding_layer(input_str_tensor, max_char_encoding_id, max_len):", "want to load the model from :type dirpath: str :return:", "print(\"{}: {}\".format(key, value)) print(\"\\nModel Label Mapping:\") for key, value in", "Adds an argmax threshold layer to the model. This layer's", ":param n_dims: Final number of principal component dims of the", "tf.cast(y_true, self.dtype) y_pred = tf.cast(y_pred, self.dtype) def _weighted_sum(val, sample_weight): if", "label_mapping = json.load(fp) # use f1 score metric custom_objects =", "not check model itself. :param self: a model :param other:", "down :type source_file: str \"\"\" if source_file is None: source_file", "import sys import time from collections import defaultdict import numpy", "`[0, 1]`. Works for both multi-class and multi-label classification. $$", "\\frac{\\textrm{precision} \\cdot \\textrm{recall}}{\\textrm{precision} + \\textrm{recall}} $$ Args: num_classes: Number of", "batch_id, batch_data in enumerate(data): model_output = self._model( tf.convert_to_tensor(batch_data) ) #", "if i > 0 else list(ls) for i, ls in", "GloVe chars embeddings from source file to n_dims principal components", "of threshold should be a python float\") if threshold >", "def save_to_disk(self, dirpath): \"\"\" Saves whole model to disk with", "data labeler. This also serves as a weight reset. :return:", "requires_zero_mapping = True def __init__(self, label_mapping=None, parameters=None): \"\"\" CNN Model", "= self._model.train_on_batch( x_train, {softmax_output_layer_name: y_train}) sys.stdout.flush() if verbose: sys.stdout.write( \"\\rEPOCH", "fp: json.dump(self._parameters, fp) labels_dirpath = os.path.join(dirpath, \"label_mapping.json\") with open(labels_dirpath, 'w')", "the model needs to be reconstructed. :return: bool of whether", "raise ValueError(\"threshold should be between 0 and 1\") self.num_classes =", "show_confidences: confidences = np.pad(confidences, ((0, len(predictions)), (0, 0), (0, 0)),", "extra parameters thrown in for param in parameters: if param", ") self.weights_intermediate.assign_add(_weighted_sum(y_true, sample_weight)) def result(self): precision = tf.math.divide_no_nan( self.true_positives, self.true_positives", "Append slices of predictions to return prediction & confidence matrices", "fully connected layers for size in self._parameters['size_fc']: self._model.add( tf.keras.layers.Dense(units=size, activation='relu'))", "\"\"\" if not self._model: raise ValueError(\"You are trying to predict", "not the model needs to reconstruct. \"\"\" if not self._model:", "float. \"\"\" # Modification: remove the run-time type checking for", "value for encoding the input dim_embed: Number of embedded dimensions", "dict :return: None \"\"\" # parameter initialization if not parameters:", "or a list.\") label_mapping = copy.deepcopy(label_mapping) if 'PAD' not in", "\" \"label mapping.\".format( self._parameters['default_label'])) super().set_label_mapping(label_mapping) def _need_to_reconstruct_model(self): \"\"\" Determines whether", "model on the test set and return the evaluation metrics.", "and validation data :param train_data: Training data used to train", "\"\"\" Adds an argmax threshold layer to the model. This", "shape=self.init_shape, initializer=\"zeros\", dtype=self.dtype ) self.true_positives = _zero_wt_init(\"true_positives\") self.false_positives = _zero_wt_init(\"false_positives\")", "Version 2.0 (the \"License\"); # you may not use this", "class NoV1ResourceMessageFilter(logging.Filter): \"\"\"Removes TF2 warning for using TF1 model which", ":param max_len: Maximum char length in a sample :type max_len:", "final argmax threshold layer for the model \"\"\" # Initialize", "dropout in the model size_conv: Convolution kernel size default_label: Key", "dtype=self.dtype) tf.keras.backend.batch_set_value([(v, reset_value) for v in self.variables]) @tf.keras.utils.register_keras_serializable() class F1Score(FBetaScore):", "training, etc. :type verbose_log: bool :param verbose_keras: whether or not", "defaultdict() f1 = None f1_report = [] self._model.reset_metrics() softmax_output_layer_name =", "for its label, otherwise it will be the default label", "def _zero_wt_init(name): return self.add_weight( name, shape=self.init_shape, initializer=\"zeros\", dtype=self.dtype ) self.true_positives", "if not self._model: return False default_ind = self.label_mapping[self._parameters['default_label']] return self.num_labels", "bool :param verbose: Flag to determine whether to print status", "= 0 self.init_shape = [self.num_classes] def _zero_wt_init(name): return self.add_weight( name,", "y_true, sample_weight) ) self.weights_intermediate.assign_add(_weighted_sum(y_true, sample_weight)) def result(self): precision = tf.math.divide_no_nan(", "so all confidences pass. :type threshold: float :param default_ind: default", "0 reserved requires_zero_mapping = True def __init__(self, label_mapping=None, parameters=None): \"\"\"", "val_f1 = f1_report['weighted avg']['f1-score'] \\ if f1_report else np.NAN val_precision", "[i for i in range(0, allocation_index)] # Append slices of", "parameters max_length = self._parameters['max_length'] max_char_encoding_id = self._parameters['max_char_encoding_id'] # Encoding layer", "other._parameters \\ or self._label_mapping != other._label_mapping: return False return True", "Tensorflow v1 Model weights need to be transferred. if not", ":param show_confidences: whether user wants prediction confidences :type show_confidences: :param", "return final_predicted_layer return ThreshArgMaxLayer(threshold, num_labels) def _construct_model(self): \"\"\" Model constructor", "tf.reduce_sum(f1_score * weights) elif self.average is not None: # [micro,", "should be a python float\") if beta <= 0.0: raise", "= tf.logical_and(y_pred >= threshold, tf.abs(y_pred) > 1e-12) else: y_pred =", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # https://github.com/tensorflow/addons/blob/v0.12.0/LICENSE # # Unless", "to reconstruct. \"\"\" if not self._model: return False default_ind =", "batch :type batch_size: int :param label_mapping: maps labels to their", "chr(ascii_num) in embedding_dict: embedding_matrix[ascii_num + 1] = embedding_dict[chr(ascii_num)] self._model.add(tf.keras.layers.Embedding( max_char_encoding_id", "by applicable law or agreed to in writing, software #", "whether or not to print out scores for training, etc.", "# convert characters to indices input_str_flatten = tf.reshape(input_str_tensor, [-1]) sentences_encode", "%d\" % (self._epoch_id, batch_id)) tf.keras.backend.set_floatx('float32') # Clean the predicted entities", "integer or float \" \"greater than 0.\") elif param ==", "of beta should be a python float\") if beta <=", "dtype=None): super().__init__(num_classes, average, 1.0, threshold, name=name, dtype=dtype) def get_config(self): base_config", "# character encoding indices range from 0 to max_char_encoding_id, #", "rest 0. If threshold is None, the argmax is converted", "may not check model itself. :param self: a model :param", "list.\") label_mapping = copy.deepcopy(label_mapping) if 'PAD' not in label_mapping: if", "with bad PAD raise ValueError(\"`PAD` must map to index zero.\")", "1e-12) else: y_pred = y_pred > self.threshold y_true = tf.cast(y_true,", "pca.fit_transform(embd_matrix) # write to file dir_name = os.path.dirname(source_file) embd_file_name =", "connected layers dropout: Ratio of dropout in the model size_conv:", "self.beta, \"threshold\": self.threshold, } base_config = super().get_config() return {**base_config, **config}", "an argmax threshold layer to the model. This layer's output", "component dims of the embeddings :type n_dims: int :param source_file:", ":type filename: str \"\"\" embd_table = dict() with open(filename, 'r')", "tf.convert_to_tensor(batch_data) ) # Count number of samples in batch to", "= {} parameters.setdefault('max_length', 3400) parameters.setdefault('max_char_encoding_id', 127) parameters.setdefault('dim_embed', 64) parameters.setdefault('size_fc', [96,", "of predictions to return prediction & confidence matrices for index,", "1) # padding sentences_encode_pad = sentences_encode.to_tensor(shape=[None, max_len]) return sentences_encode_pad @staticmethod", "max_len: Maximum char length in a sample :type max_len: int", "metric.\"\"\" config = { \"num_classes\": self.num_classes, \"average\": self.average, \"beta\": self.beta,", "raise ValueError(\"`PAD` must map to index zero.\") if self._parameters['default_label'] not", "def reset_states(self): reset_value = tf.zeros(self.init_shape, dtype=self.dtype) tf.keras.backend.batch_set_value([(v, reset_value) for v", "is the default label pad_label: Key for entities_dict that is", "for index, sentence_length \\ in enumerate(sentence_lengths[:allocation_index]): predictions_list[index] = list(predictions[index][:sentence_length]) if", "\" must be a string.\" errors.append(error) # Error if there", "using TF1 model which has resources.\"\"\" def filter(self, record): msg", "in ['max_length', 'max_char_encoding_id', 'dim_embed', 'size_conv']: if not isinstance(parameters[param], (int, float))", "= f1_report['weighted avg']['precision'] \\ if f1_report else np.NAN val_recall =", "def fit(self, train_data, val_data=None, batch_size=32, label_mapping=None, reset_weights=False, verbose=True): \"\"\" Train", "for the list of sentences :param input_str_tensor: input list of", "the confidences meet the threshold minimum. argmax_mask = tf.keras.backend.cast( tf.keras.backend.greater_equal(confidence_max_layer,", "verbose: sys.stdout.write( \"\\rEPOCH %d, batch_id %d: loss: %f - acc:", "name=\"fbeta_score\", dtype=None, **kwargs): super().__init__(name=name, dtype=dtype) if average not in (None,", "\"predict.\") # Pre-allocate space for predictions confidences = [] sentence_lengths", "and the rest 0. name: (Optional) String name of the", "not isinstance(parameters[param], (int, float)) \\ or parameters[param] < 0: errors.append(param", "matrices for index, sentence_length \\ in enumerate(sentence_lengths[:allocation_index]): predictions_list[index] = list(predictions[index][:sentence_length])", "f1_score %f -- \" \"val_f1: %f - val_precision: %f -", "the argmax value if the confidence for that argmax meets", "whether to reset the weights or not :type reset_weights: bool", "show_confidences: confidences[allocation_index:allocation_index + num_samples_in_batch] = model_output[0].numpy() predictions[allocation_index:allocation_index + num_samples_in_batch] =", "confidences[allocation_index:allocation_index + num_samples_in_batch] = model_output[0].numpy() predictions[allocation_index:allocation_index + num_samples_in_batch] = model_output[1].numpy()", "the final predicted output using the function: final_predicted_layer = tf.add(", "cls(label_mapping, parameters) loaded_model._model = tf_model # Tensorflow v1 Model weights", "bad PAD raise ValueError(\"`PAD` must map to index zero.\") if", "input_str, max_char_encoding_id, max_length) return char_in_vector self._model.add(tf.keras.layers.Input(shape=(None,), dtype=tf.string)) self._model.add( tf.keras.layers.Lambda(encoding_function, output_shape=tuple([max_length])))", "parameters = json.load(fp) # load label_mapping labels_dirpath = os.path.join(dirpath, \"label_mapping.json\")", "the relevant details of the model (summary, parameters, label mapping)", "flags for model self._model_num_labels = 0 self._model_default_ind = -1 BaseModel.__init__(self,", "threshold: float :param default_ind: default index :type default_ind: int :return:", "= model_results[i] if val_data: f1, f1_report = self._validate_training(val_data) history['f1_report'] =", "applicable law or agreed to in writing, software # distributed", "\\cdot \\textrm{precision}) + \\textrm{recall}} $$ Args: num_classes: Number of unique", "(1 + tf.math.square(self.beta)) if self.average == \"weighted\": weights = tf.math.divide_no_nan(", "# load label_mapping labels_dirpath = os.path.join(dirpath, \"label_mapping.json\") with open(labels_dirpath, 'r')", "model softmax_output_layer_name = self._model.outputs[0].name.split('/')[0] losses = {softmax_output_layer_name: \"categorical_crossentropy\"} # use", "predictions_list, 'conf': confidences_list} return {'pred': predictions_list} def details(self): \"\"\" Prints", "type of the metric result. Returns: F-1 Score: float. \"\"\"", "None self.init_shape = [] if self.average != \"micro\": self.axis =", "= tf.strings.unicode_decode(input_str_flatten, input_encoding='UTF-8') sentences_encode = tf.add(tf.cast(1, tf.int32), sentences_encode) sentences_encode =", ":return: None \"\"\" num_labels = self.num_labels default_ind = self.label_mapping[self._parameters['default_label']] #", "return f1, f1_report # Predict on the test set batch_id", "recall add_value = (tf.math.square(self.beta) * precision) + recall mean =", "callable(tf_model): loaded_model._construct_model() tf1_weights = [] for var in tf_model.variables: if", "else np.NAN val_recall = f1_report['weighted avg']['recall'] \\ if f1_report else", "# Make sure the necessary parameters are present and valid.", "sys.stdout.write( \"\\rEPOCH %d, batch_id %d: loss: %f - acc: %f", "= super().get_config() return {**base_config, **config} def reset_states(self): reset_value = tf.zeros(self.init_shape,", "(0, 0), (0, 0)), mode='constant') if show_confidences: confidences[allocation_index:allocation_index + num_samples_in_batch]", "of the embeddings :type n_dims: int :param source_file: Location of", "max_char_encoding_id: int :param max_len: Maximum char length in a sample", "\\textrm{recall}} $$ Args: num_classes: Number of unique classes in the", "model or reset the label mapping to \" \"predict.\") #", "axis=0), self.num_labels, self.reverse_label_mapping, verbose=verbose_keras) return f1, f1_report def predict(self, data,", "data. Acceptable values are `None`, `micro`, `macro` and `weighted`. Default", "also serves as a weight reset. :return: None \"\"\" num_labels", "thresholds vector variable and create the threshold # matrix. class", "= dict() with open(filename, 'r') as embds: for line in", "layers (dense_2', 'tf_op_layer_ArgMax', # 'thresh_arg_max_layer') for _ in range(3): self._model.layers.pop()", "x_train, {softmax_output_layer_name: y_train}) sys.stdout.flush() if verbose: sys.stdout.write( \"\\rEPOCH %d, batch_id", "tf.reshape(input_str_tensor, [-1]) sentences_encode = tf.strings.unicode_decode(input_str_flatten, input_encoding='UTF-8') sentences_encode = tf.add(tf.cast(1, tf.int32),", "from keras. :type verbose_keras: bool return (f1-score, f1 report). \"\"\"", "dirpath: directory path where you want to save the model", "whole model from disk with weights :param dirpath: directory path", "label mapping of the model :type label_mapping: dict :return: None", "abs(x) > eps, instead of x != 0 to check", "None \"\"\" if label_mapping is not None: self.set_label_mapping(label_mapping) if not", "1.0, threshold, name=name, dtype=dtype) def get_config(self): base_config = super().get_config() del", "make sure [0, 0, 0] doesn't become [1, 1, 1]", "be a valid integer or float \" \"greater than 0.\")", "# You may obtain a copy of the License at", "converted to be 1, and the rest 0. If threshold", "and 1\") self.num_classes = num_classes self.average = average self.beta =", "for x_train, y_train in train_data: model_results = self._model.train_on_batch( x_train, {softmax_output_layer_name:", "string.\" errors.append(error) # Error if there are extra parameters thrown", "_validate_training(self, val_data, batch_size_test=32, verbose_log=True, verbose_keras=False): \"\"\" Validate the model on", "f1_score def get_config(self): \"\"\"Returns the serializable config of the metric.\"\"\"", ":type batch_size: int :param label_mapping: maps labels to their encoded", "is None, the argmax is converted to 1, and the", "# 'thresh_arg_max_layer') for _ in range(3): self._model.layers.pop() # Add the", "Args: num_classes: Number of unique classes in the dataset. average:", "Union[list, np.ndarray] :param batch_size: Used to determine number of samples", "metric result. Returns: F-1 Score: float. \"\"\" # Modification: remove", "Count number of samples in batch to prevent array mismatch", "are present. :param parameters: parameter dict containing the following parameters:", ":param threshold: default set to 0 so all confidences pass.", "# Encoding layer def encoding_function(input_str): char_in_vector = CharacterLevelCnnModel._char_encoding_layer( input_str, max_char_encoding_id,", "\"weighted\"): raise ValueError( \"Unknown average type. Acceptable values \" \"are:", "add_value) f1_score = mean * (1 + tf.math.square(self.beta)) if self.average", "self._parameters['max_length'], self.num_labels)) # Run model with batching allocation_index = 0", "itself. :param self: a model :param other: a model :type", "or not the model needs to reconstruct. \"\"\" if not", "= tf.keras.models.load_model(dirpath) loaded_model = cls(label_mapping, parameters) loaded_model._model = tf_model #", "CharacterLevelCnnModel._char_encoding_layer( input_str, max_char_encoding_id, max_length) return char_in_vector self._model.add(tf.keras.layers.Input(shape=(None,), dtype=tf.string)) self._model.add( tf.keras.layers.Lambda(encoding_function,", "train_data: Union[list, np.ndarray] :param val_data: Validation data used to validate", "Works for both multi-class and multi-label classification. $$ F_1 =", "multi-label classification. $$ F_1 = 2 \\cdot \\frac{\\textrm{precision} \\cdot \\textrm{recall}}{\\textrm{precision}", "file: for word, embd in zip(embd_words, reduced_embds): file.write(word + \"", "\"\"\"Removes TF2 warning for using TF1 model which has resources.\"\"\"", "or self._label_mapping != other._label_mapping: return False return True def _validate_parameters(self,", "r\"\"\"Computes F-Beta score. Adapted and slightly modified from https://github.com/tensorflow/addons/blob/v0.12.0/tensorflow_addons/metrics/f_scores.py#L211-L283 #", "\"\"\" print(\"\\n###### Model Details ######\\n\") self._model.summary() print(\"\\nModel Parameters:\") for key,", "dict :return: None \"\"\" if not isinstance(label_mapping, (list, dict)): raise", "for param in parameters: if param not in list_of_necessary_params: errors.append(param", "determine whether to print status or not :type verbose: bool", "+ \" must be a non-empty list of \" \"integers.\")", "mul_value = precision * recall add_value = (tf.math.square(self.beta) * precision)", "dictionary from embed file with GloVe-like format :param filename: Path", "the mapping for index 0 reserved requires_zero_mapping = True def", "input_str_flatten = tf.reshape(input_str_tensor, [-1]) sentences_encode = tf.strings.unicode_decode(input_str_flatten, input_encoding='UTF-8') sentences_encode =", "y_train in train_data: model_results = self._model.train_on_batch( x_train, {softmax_output_layer_name: y_train}) sys.stdout.flush()", "the model needs to reconstruct. \"\"\" if not self._model: return", "report). \"\"\" f1 = None f1_report = None if val_data", "# Pre-allocate space for predictions confidences = [] sentence_lengths =", "are `None`, `micro`, `macro` and `weighted`. Default value is None.", "parameters[param]: if not isinstance(item, int): errors.append(param + \" must be", "of averaging to be performed on data. Acceptable values are", "value of beta should be a python float\") if beta", "float): raise TypeError(\"The value of threshold should be a python", "integers.\") break elif param == 'default_label': if not isinstance(parameters[param], str):", "return self.add_weight( name, shape=self.init_shape, initializer=\"zeros\", dtype=self.dtype ) self.true_positives = _zero_wt_init(\"true_positives\")", "into a .pb file for TensorFlow argmax_layer = tf.keras.backend.argmax(self._model.output) #", "the harmonic mean of precision and recall. Output range is", "f1, f1_report def predict(self, data, batch_size=32, show_confidences=False, verbose=True): \"\"\" Run", "list(ls) for i, ls in enumerate(zip(*embd_table.items()))] # get PCA embedder", "_ in range(3): self._model.layers.pop() # Add the final Softmax layer", "must be a non-empty \" \"list of integers.\") break elif", ":return: None \"\"\" if not isinstance(label_mapping, (list, dict)): raise TypeError(\"Labels", "for _ in range(4)]) parameters['pad_label'] = 'PAD' self._epoch_id = 0", "confidences pass. :type threshold: float :param default_ind: default index :type", "the run-time type checking for functions def __init__(self, num_classes, average=None,", "parameters: Contains all the appropriate parameters for the model. Must", "\"\"\" Loads whole model from disk with weights :param dirpath:", "in self._parameters.items(): print(\"{}: {}\".format(key, value)) print(\"\\nModel Label Mapping:\") for key,", "reset_value = tf.zeros(self.init_shape, dtype=self.dtype) tf.keras.backend.batch_set_value([(v, reset_value) for v in self.variables])", "Train the current model with the training data and validation", "f1_report['weighted avg']['f1-score'] \\ if f1_report else np.NAN val_precision = f1_report['weighted", "to check for zero y_pred = tf.logical_and(y_pred >= threshold, tf.abs(y_pred)", "not to print out scores for training, etc. :type verbose_log:", "CNN Model Initializer. initialize epoch_id :param label_mapping: maps labels to", "model_results[i] if val_data: f1, f1_report = self._validate_training(val_data) history['f1_report'] = f1_report", "sample_weight is not None: val = tf.math.multiply(val, tf.expand_dims(sample_weight, 1)) return", "parameters[param] < 0: errors.append(param + \" must be a valid", "for both multi-class and multi-label classification. $$ F_{\\beta} = (1", "'.join(str(num) for num in embd) + \"\\n\") class CharacterLevelCnnModel(BaseTrainableModel, metaclass=AutoSubRegistrationMeta):", "tf.keras.layers.Dense(units=size, activation='relu')) if self._parameters['dropout']: self._model.add( tf.keras.layers.Dropout(self._parameters['dropout'])) # Add the final", "'thresh_arg_max_layer') for _ in range(3): self._model.layers.pop() # Add the final", "Predict on the test set batch_id = 0 y_val_pred =", "base_config def build_embd_dictionary(filename): \"\"\" Returns a numpy embedding dictionary from", "parameter.\") if errors: raise ValueError('\\n'.join(errors)) def set_label_mapping(self, label_mapping): \"\"\" Sets", "errors.append(param + \" must be a valid integer or float", "loaded_model._construct_model() tf1_weights = [] for var in tf_model.variables: if 'training'", "param not in list_of_necessary_params: errors.append(param + \" is not an", "max_len): \"\"\" Character encoding for the list of sentences :param", "fit(self, train_data, val_data=None, batch_size=32, label_mapping=None, reset_weights=False, verbose=True): \"\"\" Train the", "var.name: tf1_weights.append(var.value()) loaded_model._construct_model() tf1_weights.append(loaded_model._model.weights[-1].value()) loaded_model._model.set_weights(tf1_weights) # load self loaded_model._model_num_labels =", "self).__init__() thresh_init = tf.constant_initializer(threshold_) self.thresh_vec = tf.Variable( name='ThreshVec', initial_value=thresh_init(shape=[num_labels_]), trainable=False)", "'dropout': if not isinstance(parameters[param], (int, float)) \\ or parameters[param] <", "\"License\"); # you may not use this file except in", "batch_id = 0 for x_train, y_train in train_data: model_results =", ":type show_confidences: :param verbose: Flag to determine whether to print", "predictions[allocation_index:allocation_index + num_samples_in_batch] = model_output[1].numpy() sentence_lengths[allocation_index:allocation_index + num_samples_in_batch] = list(map(lambda", "same size as the batch_size which # represents the background", "\\ or len(parameters[param]) == 0: errors.append(param + \" must be", "0, 0] doesn't become [1, 1, 1] # Use abs(x)", "dict \" \"which maps labels to index encodings or a", "open(embd_file_name, 'w') as file: for word, embd in zip(embd_words, reduced_embds):", "parameters.setdefault('default_label', \"UNKNOWN\") parameters.setdefault('num_fil', [48 for _ in range(4)]) parameters['pad_label'] =", "# Error if there are extra parameters thrown in for", "[argmax_layer, final_predicted_layer(argmax_layer, final_softmax_layer)] self._model = tf.keras.Model(self._model.inputs, argmax_outputs) # Compile the", "if show_confidences: confidences = np.pad(confidences, ((0, len(predictions)), (0, 0), (0,", "'PAD' not in label_mapping: if isinstance(label_mapping, list): # if list", "transferred. if not callable(tf_model): loaded_model._construct_model() tf1_weights = [] for var", "+= 1 for i, metric_label in enumerate(self._model.metrics_names): history[metric_label] = model_results[i]", "\"f1_score %f\" % (self._epoch_id, batch_id, *model_results[1:])) batch_id += 1 for", ".. import dp_logging from . import labeler_utils from .base_model import", ":return: bool of whether or not the model needs to", "must be a valid integer or float \" \"greater than", "Maximum integer value for encoding the input :type max_char_encoding_id: int", "as the batch_size which # represents the background label bg_label_tf", "mapping definitions have been \" \"altered without additional training. Please", ") # Count number of samples in batch to prevent", "default set to 0 so all confidences pass. :type threshold:", "final Softmax layer self._model.add( tf.keras.layers.Dense(num_labels, activation='softmax')) # Output the model", "Must contain num_labels. Other possible parameters are: max_length, max_char_encoding_id, dim_embed,", "a valid integer or float \" \"from 0 to 1.\")", "parameters thrown in for param in parameters: if param not", "label mapping requires the mapping for index 0 reserved requires_zero_mapping", "+= num_samples_in_batch # Convert predictions, confidences to lists from numpy", "new file :param n_dims: Final number of principal component dims", "\"\"\" # Initialize the thresholds vector variable and create the", "tf.math.multiply(val, tf.expand_dims(sample_weight, 1)) return tf.reduce_sum(val, axis=self.axis) self.true_positives.assign_add(_weighted_sum(y_pred * y_true, sample_weight))", "for i in range(0, allocation_index)] # Append slices of predictions", "average='micro'), \"CharacterLevelCnnModel\": cls, } with tf.keras.utils.custom_object_scope(custom_objects): tf_model = tf.keras.models.load_model(dirpath) loaded_model", "show_confidences: confidences_list[index] = list(confidences[index][:sentence_length]) if show_confidences: return {'pred': predictions_list, 'conf':", "recall mean = tf.math.divide_no_nan(mul_value, add_value) f1_score = mean * (1", "int :return: final argmax threshold layer for the model \"\"\"", "allocation_index)] confidences_list = None if show_confidences: confidences_list = [i for", "= self.num_labels default_ind = self.label_mapping[self._parameters['default_label']] # Remove the 3 output", ":type batch_size_test: int :param verbose_log: whether or not to print", "= -1 BaseModel.__init__(self, label_mapping, parameters) def __eq__(self, other): \"\"\" Checks", "Reconstruct the appropriate layers if the number of number of", "f1_score = tf.reduce_mean(f1_score) return f1_score def get_config(self): \"\"\"Returns the serializable", "- y_true), sample_weight) ) self.false_negatives.assign_add( _weighted_sum((1 - y_pred) * y_true,", "in parameters[param]: if not isinstance(item, int): errors.append(param + \" must", "in val_data: y_val_pred.append(self._model.predict( x_val, batch_size=batch_size_test, verbose=verbose_keras)[1]) y_val_test.append(np.argmax(y_val, axis=-1)) batch_id +=", "type checking for functions def __init__(self, num_classes, average=None, threshold=None, name=\"f1_score\"," ]
[ "{where_clause} LIMIT {LIMIT}; \"\"\".format(where_clause=where_clause, LIMIT=TABLE_SELECTOR_LIMIT) h = MySqlHook(METASTORE_MYSQL_CONN_ID) d =", "OF ANY # KIND, either express or implied. See the", "more contributor license agreements. See the NOTICE file # distributed", "Apache Software Foundation (ASF) under one # or more contributor", "db in DB_BLACKLIST]) where_clause = \"AND b.name NOT IN ({})\".format(dbs)", "WARRANTIES OR CONDITIONS OF ANY # KIND, either express or", "import BaseView, expose import pandas as pd from airflow.hooks.hive_hooks import", "= 'default' DB_WHITELIST = None DB_BLACKLIST = ['tmp'] TABLE_SELECTOR_LIMIT =", "2.0 (the # \"License\"); you may not use this file", "a.desc \"\"\".format(**locals()) h = MySqlHook(METASTORE_MYSQL_CONN_ID) df = h.get_pandas_df(sql) df.db =", "2000 # Keeping pandas from truncating long strings pd.set_option('display.max_colwidth', -1)", "b ON a.TBL_ID = b.TBL_ID JOIN DBS d ON b.DB_ID", "return json.dumps(d) @gzipped @expose('/data/') def data(self): table = request.args.get(\"table\") sql", "SELECT a.PART_NAME, a.CREATE_TIME, c.LOCATION, c.IS_COMPRESSED, c.INPUT_FORMAT, c.OUTPUT_FORMAT FROM PARTITIONS a", "\",\".join([\"'\" + db + \"'\" for db in DB_BLACKLIST]) where_clause", "\"\"\".format(where_clause=where_clause, LIMIT=TABLE_SELECTOR_LIMIT) h = MySqlHook(METASTORE_MYSQL_CONN_ID) d = [ {'id': row[0],", "= MetastoreBrowserView(category=\"Plugins\", name=\"Hive Metadata Browser\") # Creating a flask blueprint", "MySqlHook(METASTORE_MYSQL_CONN_ID) df = h.get_pandas_df(sql) df.db = ( '<a href=\"/admin/metastorebrowserview/db/?db=' +", "SELECT a.name as db, db_location_uri as location, count(1) as object_count,", "DB_WHITELIST = None DB_BLACKLIST = ['tmp'] TABLE_SELECTOR_LIMIT = 2000 #", "partitions(self): schema, table = request.args.get(\"table\").split('.') sql = \"\"\" SELECT a.PART_NAME,", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "sorted(m.get_tables(db=db), key=lambda x: x.tableName) return self.render( \"metastore_browser/db.html\", tables=tables, db=db) @gzipped", "specific language governing permissions and limitations # under the License.", "BaseView class MetastoreBrowserView(BaseView, wwwutils.DataProfilingMixin): @expose('/') def index(self): sql = \"\"\"", "\"\"\" SELECT CONCAT(b.NAME, '.', a.TBL_NAME), TBL_TYPE FROM TBLS a JOIN", "tables=tables, db=db) @gzipped @expose('/partitions/') def partitions(self): schema, table = request.args.get(\"table\").split('.')", "under the License is distributed on an # \"AS IS\"", "flask import Blueprint, request from flask_admin import BaseView, expose import", "@expose('/table/') def table(self): table_name = request.args.get(\"table\") m = HiveMetastoreHook(METASTORE_CONN_ID) table", "table = m.get_table(table_name) return self.render( \"metastore_browser/table.html\", table=table, table_name=table_name, datetime=datetime, int=int)", "BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either", "= ( '<a href=\"/admin/metastorebrowserview/db/?db=' + df.db + '\">' + df.db", "table = request.args.get(\"table\") sql = \"SELECT * FROM {table} LIMIT", "# Creating a flask blueprint to intergrate the templates and", "pd.set_option('display.max_colwidth', -1) # Creating a flask admin BaseView class MetastoreBrowserView(BaseView,", "key=lambda x: x.tableName) return self.render( \"metastore_browser/db.html\", tables=tables, db=db) @gzipped @expose('/partitions/')", "\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY #", "@expose('/') def index(self): sql = \"\"\" SELECT a.name as db,", "as description FROM DBS a JOIN TBLS b ON a.DB_ID", "LIKE '%tmp%' AND b.NAME NOT LIKE '%temp%' {where_clause} LIMIT {LIMIT};", "distributed with this work for additional information # regarding copyright", "flask blueprint to intergrate the templates and static folder bp", "index=False, na_rep='',) @gzipped @expose('/objects/') def objects(self): where_clause = '' if", "HiveMetastoreHook(METASTORE_CONN_ID) table = m.get_table(table_name) return self.render( \"metastore_browser/table.html\", table=table, table_name=table_name, datetime=datetime,", "= b.TBL_ID JOIN DBS d ON b.DB_ID = d.DB_ID JOIN", "for the # specific language governing permissions and limitations #", "@gzipped @expose('/data/') def data(self): table = request.args.get(\"table\") sql = \"SELECT", "from datetime import datetime import json from flask import Blueprint,", "def ddl(self): table = request.args.get(\"table\") sql = \"SHOW CREATE TABLE", "See the License for the # specific language governing permissions", "to in writing, # software distributed under the License is", "from airflow.hooks.hive_hooks import HiveMetastoreHook, HiveCliHook from airflow.hooks.mysql_hook import MySqlHook from", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "DB_BLACKLIST: dbs = \",\".join([\"'\" + db + \"'\" for db", "airflow.plugins_manager import AirflowPlugin from airflow.www import utils as wwwutils from", "long strings pd.set_option('display.max_colwidth', -1) # Creating a flask admin BaseView", "class class MetastoreBrowserPlugin(AirflowPlugin): name = \"metastore_browser\" flask_blueprints = [bp] admin_views", "def objects(self): where_clause = '' if DB_WHITELIST: dbs = \",\".join([\"'\"", "def table(self): table_name = request.args.get(\"table\") m = HiveMetastoreHook(METASTORE_CONN_ID) table =", "file # distributed with this work for additional information #", "b ON a.DB_ID = b.DB_ID WHERE a.TBL_NAME NOT LIKE '%tmp%'", "utils as wwwutils from airflow.www.decorators import gzipped METASTORE_CONN_ID = 'metastore_default'", "table = df.to_html( classes=\"table table-striped table-bordered table-hover\", index=False, escape=False, na_rep='',)", "= request.args.get(\"table\") sql = \"SHOW CREATE TABLE {table};\".format(table=table) h =", "airflow.hooks.hive_hooks import HiveMetastoreHook, HiveCliHook from airflow.hooks.mysql_hook import MySqlHook from airflow.hooks.presto_hook", "row[0]} for row in h.get_records(sql)] return json.dumps(d) @gzipped @expose('/data/') def", "where_clause = \"AND b.name NOT IN ({})\".format(dbs) sql = \"\"\"", "df.to_html( classes=\"table table-striped table-bordered table-hover\", index=False, escape=False, na_rep='',) return self.render(", "Browser\") # Creating a flask blueprint to intergrate the templates", "table-striped table-bordered table-hover\", index=False, escape=False, na_rep='',) return self.render( \"metastore_browser/dbs.html\", table=table)", "DB_WHITELIST]) where_clause = \"AND b.name IN ({})\".format(dbs) if DB_BLACKLIST: dbs", "NOT LIKE '%temp%' {where_clause} LIMIT {LIMIT}; \"\"\".format(where_clause=where_clause, LIMIT=TABLE_SELECTOR_LIMIT) h =", "db(self): db = request.args.get(\"db\") m = HiveMetastoreHook(METASTORE_CONN_ID) tables = sorted(m.get_tables(db=db),", "language governing permissions and limitations # under the License. from", "implied. See the License for the # specific language governing", "to you under the Apache License, Version 2.0 (the #", "[ {'id': row[0], 'text': row[0]} for row in h.get_records(sql)] return", "= \",\".join([\"'\" + db + \"'\" for db in DB_WHITELIST])", "\"\"\".format(**locals()) h = MySqlHook(METASTORE_MYSQL_CONN_ID) df = h.get_pandas_df(sql) return df.to_html( classes=\"table", "= b.DB_ID WHERE a.TBL_NAME NOT LIKE '%tmp%' AND a.TBL_NAME NOT", "GROUP BY a.name, db_location_uri, a.desc \"\"\".format(**locals()) h = MySqlHook(METASTORE_MYSQL_CONN_ID) df", "= None DB_BLACKLIST = ['tmp'] TABLE_SELECTOR_LIMIT = 2000 # Keeping", "may not use this file except in compliance # with", "datetime import json from flask import Blueprint, request from flask_admin", "df.to_html( classes=\"table table-striped table-bordered table-hover\", index=False, na_rep='',) @gzipped @expose('/objects/') def", "License, Version 2.0 (the # \"License\"); you may not use", "h.get_pandas_df(sql) return df.to_html( classes=\"table table-striped table-bordered table-hover\", index=False, na_rep='',) @gzipped", "either express or implied. See the License for the #", "a.DB_ID = b.DB_ID GROUP BY a.name, db_location_uri, a.desc \"\"\".format(**locals()) h", "data(self): table = request.args.get(\"table\") sql = \"SELECT * FROM {table}", "h = MySqlHook(METASTORE_MYSQL_CONN_ID) df = h.get_pandas_df(sql) return df.to_html( classes=\"table table-striped", "DB_BLACKLIST = ['tmp'] TABLE_SELECTOR_LIMIT = 2000 # Keeping pandas from", "FROM PARTITIONS a JOIN TBLS b ON a.TBL_ID = b.TBL_ID", "ORDER BY PART_NAME DESC \"\"\".format(**locals()) h = MySqlHook(METASTORE_MYSQL_CONN_ID) df =", "utf-8 -*- # # Licensed to the Apache Software Foundation", "additional information # regarding copyright ownership. The ASF licenses this", "\"\"\" SELECT a.name as db, db_location_uri as location, count(1) as", "HiveMetastoreHook, HiveCliHook from airflow.hooks.mysql_hook import MySqlHook from airflow.hooks.presto_hook import PrestoHook", "strings pd.set_option('display.max_colwidth', -1) # Creating a flask admin BaseView class", "DBS d ON b.DB_ID = d.DB_ID JOIN SDS c ON", "@expose('/objects/') def objects(self): where_clause = '' if DB_WHITELIST: dbs =", "See the NOTICE file # distributed with this work for", "table-hover\", index=False, na_rep='',) @expose('/ddl/') def ddl(self): table = request.args.get(\"table\") sql", "ON a.SD_ID = c.SD_ID WHERE b.TBL_NAME like '{table}' AND d.NAME", "TBLS a JOIN DBS b ON a.DB_ID = b.DB_ID WHERE", "\"\"\" SELECT a.PART_NAME, a.CREATE_TIME, c.LOCATION, c.IS_COMPRESSED, c.INPUT_FORMAT, c.OUTPUT_FORMAT FROM PARTITIONS", "import MySqlHook from airflow.hooks.presto_hook import PrestoHook from airflow.plugins_manager import AirflowPlugin", "Apache License, Version 2.0 (the # \"License\"); you may not", "JOIN DBS d ON b.DB_ID = d.DB_ID JOIN SDS c", "\"'\" for db in DB_WHITELIST]) where_clause = \"AND b.name IN", "= [ {'id': row[0], 'text': row[0]} for row in h.get_records(sql)]", "= \"\"\" SELECT CONCAT(b.NAME, '.', a.TBL_NAME), TBL_TYPE FROM TBLS a", "sql = \"\"\" SELECT a.PART_NAME, a.CREATE_TIME, c.LOCATION, c.IS_COMPRESSED, c.INPUT_FORMAT, c.OUTPUT_FORMAT", "as db, db_location_uri as location, count(1) as object_count, a.desc as", "b.TBL_NAME like '{table}' AND d.NAME like '{schema}' ORDER BY PART_NAME", "{table};\".format(table=table) h = HiveCliHook(HIVE_CLI_CONN_ID) return h.run_cli(sql) v = MetastoreBrowserView(category=\"Plugins\", name=\"Hive", "import Blueprint, request from flask_admin import BaseView, expose import pandas", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "index(self): sql = \"\"\" SELECT a.name as db, db_location_uri as", "c ON a.SD_ID = c.SD_ID WHERE b.TBL_NAME like '{table}' AND", "'\">' + df.db + '</a>') table = df.to_html( classes=\"table table-striped", "file except in compliance # with the License. You may", "# specific language governing permissions and limitations # under the", "h.get_pandas_df(sql) df.db = ( '<a href=\"/admin/metastorebrowserview/db/?db=' + df.db + '\">'", "row[0], 'text': row[0]} for row in h.get_records(sql)] return json.dumps(d) @gzipped", "{'id': row[0], 'text': row[0]} for row in h.get_records(sql)] return json.dumps(d)", "Metadata Browser\") # Creating a flask blueprint to intergrate the", "+ \"'\" for db in DB_BLACKLIST]) where_clause = \"AND b.name", "'{schema}' ORDER BY PART_NAME DESC \"\"\".format(**locals()) h = MySqlHook(METASTORE_MYSQL_CONN_ID) df", "IN ({})\".format(dbs) sql = \"\"\" SELECT CONCAT(b.NAME, '.', a.TBL_NAME), TBL_TYPE", "you may not use this file except in compliance #", "'' if DB_WHITELIST: dbs = \",\".join([\"'\" + db + \"'\"", "table-bordered table-hover\", index=False, escape=False, na_rep='',) return self.render( \"metastore_browser/dbs.html\", table=table) @expose('/table/')", "= h.get_pandas_df(sql) return df.to_html( classes=\"table table-striped table-bordered table-hover\", index=False, na_rep='',)", "use this file except in compliance # with the License.", "CONCAT(b.NAME, '.', a.TBL_NAME), TBL_TYPE FROM TBLS a JOIN DBS b", "BaseView, expose import pandas as pd from airflow.hooks.hive_hooks import HiveMetastoreHook,", "contributor license agreements. See the NOTICE file # distributed with", "def data(self): table = request.args.get(\"table\") sql = \"SELECT * FROM", "-1) # Creating a flask admin BaseView class MetastoreBrowserView(BaseView, wwwutils.DataProfilingMixin):", "expose import pandas as pd from airflow.hooks.hive_hooks import HiveMetastoreHook, HiveCliHook", "request from flask_admin import BaseView, expose import pandas as pd", "NOT LIKE '%tmp%' AND a.TBL_NAME NOT LIKE '%temp%' AND b.NAME", "LIKE '%temp%' AND b.NAME NOT LIKE '%tmp%' AND b.NAME NOT", "an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF", "import utils as wwwutils from airflow.www.decorators import gzipped METASTORE_CONN_ID =", "h = MySqlHook(METASTORE_MYSQL_CONN_ID) d = [ {'id': row[0], 'text': row[0]}", "DEFAULT_DB = 'default' DB_WHITELIST = None DB_BLACKLIST = ['tmp'] TABLE_SELECTOR_LIMIT", "schema, table = request.args.get(\"table\").split('.') sql = \"\"\" SELECT a.PART_NAME, a.CREATE_TIME,", "WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express", "with this work for additional information # regarding copyright ownership.", "d = [ {'id': row[0], 'text': row[0]} for row in", "as wwwutils from airflow.www.decorators import gzipped METASTORE_CONN_ID = 'metastore_default' METASTORE_MYSQL_CONN_ID", "object_count, a.desc as description FROM DBS a JOIN TBLS b", "JOIN DBS b ON a.DB_ID = b.DB_ID WHERE a.TBL_NAME NOT", "b.name NOT IN ({})\".format(dbs) sql = \"\"\" SELECT CONCAT(b.NAME, '.',", "int=int) @expose('/db/') def db(self): db = request.args.get(\"db\") m = HiveMetastoreHook(METASTORE_CONN_ID)", "= PrestoHook(PRESTO_CONN_ID) df = h.get_pandas_df(sql) return df.to_html( classes=\"table table-striped table-bordered", "table-striped table-bordered table-hover\", index=False, na_rep='',) @gzipped @expose('/objects/') def objects(self): where_clause", "work for additional information # regarding copyright ownership. The ASF", "HiveCliHook from airflow.hooks.mysql_hook import MySqlHook from airflow.hooks.presto_hook import PrestoHook from", "if DB_BLACKLIST: dbs = \",\".join([\"'\" + db + \"'\" for", "c.LOCATION, c.IS_COMPRESSED, c.INPUT_FORMAT, c.OUTPUT_FORMAT FROM PARTITIONS a JOIN TBLS b", "= request.args.get(\"table\").split('.') sql = \"\"\" SELECT a.PART_NAME, a.CREATE_TIME, c.LOCATION, c.IS_COMPRESSED,", "distributed under the License is distributed on an # \"AS", "= request.args.get(\"table\") m = HiveMetastoreHook(METASTORE_CONN_ID) table = m.get_table(table_name) return self.render(", "1000;\".format(table=table) h = PrestoHook(PRESTO_CONN_ID) df = h.get_pandas_df(sql) return df.to_html( classes=\"table", "if DB_WHITELIST: dbs = \",\".join([\"'\" + db + \"'\" for", "b.NAME NOT LIKE '%temp%' {where_clause} LIMIT {LIMIT}; \"\"\".format(where_clause=where_clause, LIMIT=TABLE_SELECTOR_LIMIT) h", "a JOIN DBS b ON a.DB_ID = b.DB_ID WHERE a.TBL_NAME", "# software distributed under the License is distributed on an", "to intergrate the templates and static folder bp = Blueprint(", "as location, count(1) as object_count, a.desc as description FROM DBS", "Blueprint( \"metastore_browser\", __name__, template_folder='templates', static_folder='static', static_url_path='/static/metastore_browser') # Defining the plugin", "the License. You may obtain a copy of the License", "request.args.get(\"table\").split('.') sql = \"\"\" SELECT a.PART_NAME, a.CREATE_TIME, c.LOCATION, c.IS_COMPRESSED, c.INPUT_FORMAT,", "like '{schema}' ORDER BY PART_NAME DESC \"\"\".format(**locals()) h = MySqlHook(METASTORE_MYSQL_CONN_ID)", "PrestoHook(PRESTO_CONN_ID) df = h.get_pandas_df(sql) return df.to_html( classes=\"table table-striped table-bordered table-hover\",", "where_clause = \"AND b.name IN ({})\".format(dbs) if DB_BLACKLIST: dbs =", "= HiveMetastoreHook(METASTORE_CONN_ID) table = m.get_table(table_name) return self.render( \"metastore_browser/table.html\", table=table, table_name=table_name,", "DB_BLACKLIST]) where_clause = \"AND b.name NOT IN ({})\".format(dbs) sql =", "under the Apache License, Version 2.0 (the # \"License\"); you", "db in DB_WHITELIST]) where_clause = \"AND b.name IN ({})\".format(dbs) if", "distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR", "from airflow.www import utils as wwwutils from airflow.www.decorators import gzipped", "regarding copyright ownership. The ASF licenses this file # to", "Creating a flask blueprint to intergrate the templates and static", "+ df.db + '</a>') table = df.to_html( classes=\"table table-striped table-bordered", "or agreed to in writing, # software distributed under the", "description FROM DBS a JOIN TBLS b ON a.DB_ID =", "db + \"'\" for db in DB_WHITELIST]) where_clause = \"AND", "['tmp'] TABLE_SELECTOR_LIMIT = 2000 # Keeping pandas from truncating long", "{table} LIMIT 1000;\".format(table=table) h = PrestoHook(PRESTO_CONN_ID) df = h.get_pandas_df(sql) return", "({})\".format(dbs) if DB_BLACKLIST: dbs = \",\".join([\"'\" + db + \"'\"", "wwwutils.DataProfilingMixin): @expose('/') def index(self): sql = \"\"\" SELECT a.name as", "table_name = request.args.get(\"table\") m = HiveMetastoreHook(METASTORE_CONN_ID) table = m.get_table(table_name) return", "or more contributor license agreements. See the NOTICE file #", "BY PART_NAME DESC \"\"\".format(**locals()) h = MySqlHook(METASTORE_MYSQL_CONN_ID) df = h.get_pandas_df(sql)", "= df.to_html( classes=\"table table-striped table-bordered table-hover\", index=False, escape=False, na_rep='',) return", "a.PART_NAME, a.CREATE_TIME, c.LOCATION, c.IS_COMPRESSED, c.INPUT_FORMAT, c.OUTPUT_FORMAT FROM PARTITIONS a JOIN", "ON a.DB_ID = b.DB_ID GROUP BY a.name, db_location_uri, a.desc \"\"\".format(**locals())", "this work for additional information # regarding copyright ownership. The", "= Blueprint( \"metastore_browser\", __name__, template_folder='templates', static_folder='static', static_url_path='/static/metastore_browser') # Defining the", "the NOTICE file # distributed with this work for additional", "NOT LIKE '%tmp%' AND b.NAME NOT LIKE '%temp%' {where_clause} LIMIT", "b.DB_ID WHERE a.TBL_NAME NOT LIKE '%tmp%' AND a.TBL_NAME NOT LIKE", "Defining the plugin class class MetastoreBrowserPlugin(AirflowPlugin): name = \"metastore_browser\" flask_blueprints", "in DB_BLACKLIST]) where_clause = \"AND b.name NOT IN ({})\".format(dbs) sql", "from airflow.hooks.presto_hook import PrestoHook from airflow.plugins_manager import AirflowPlugin from airflow.www", "for db in DB_WHITELIST]) where_clause = \"AND b.name IN ({})\".format(dbs)", "\"metastore_browser\", __name__, template_folder='templates', static_folder='static', static_url_path='/static/metastore_browser') # Defining the plugin class", "a.TBL_ID = b.TBL_ID JOIN DBS d ON b.DB_ID = d.DB_ID", "table=table, table_name=table_name, datetime=datetime, int=int) @expose('/db/') def db(self): db = request.args.get(\"db\")", "table-hover\", index=False, escape=False, na_rep='',) return self.render( \"metastore_browser/dbs.html\", table=table) @expose('/table/') def", "= h.get_pandas_df(sql) df.db = ( '<a href=\"/admin/metastorebrowserview/db/?db=' + df.db +", "a JOIN TBLS b ON a.DB_ID = b.DB_ID GROUP BY", "na_rep='',) @expose('/ddl/') def ddl(self): table = request.args.get(\"table\") sql = \"SHOW", "count(1) as object_count, a.desc as description FROM DBS a JOIN", "TBLS b ON a.TBL_ID = b.TBL_ID JOIN DBS d ON", "import json from flask import Blueprint, request from flask_admin import", "x.tableName) return self.render( \"metastore_browser/db.html\", tables=tables, db=db) @gzipped @expose('/partitions/') def partitions(self):", "\"AND b.name NOT IN ({})\".format(dbs) sql = \"\"\" SELECT CONCAT(b.NAME,", "License. from datetime import datetime import json from flask import", "= \"\"\" SELECT a.PART_NAME, a.CREATE_TIME, c.LOCATION, c.IS_COMPRESSED, c.INPUT_FORMAT, c.OUTPUT_FORMAT FROM", "\"metastore_browser/dbs.html\", table=table) @expose('/table/') def table(self): table_name = request.args.get(\"table\") m =", "a.desc as description FROM DBS a JOIN TBLS b ON", "self.render( \"metastore_browser/db.html\", tables=tables, db=db) @gzipped @expose('/partitions/') def partitions(self): schema, table", "LIMIT=TABLE_SELECTOR_LIMIT) h = MySqlHook(METASTORE_MYSQL_CONN_ID) d = [ {'id': row[0], 'text':", "KIND, either express or implied. See the License for the", "table = request.args.get(\"table\").split('.') sql = \"\"\" SELECT a.PART_NAME, a.CREATE_TIME, c.LOCATION,", "TABLE {table};\".format(table=table) h = HiveCliHook(HIVE_CLI_CONN_ID) return h.run_cli(sql) v = MetastoreBrowserView(category=\"Plugins\",", "import pandas as pd from airflow.hooks.hive_hooks import HiveMetastoreHook, HiveCliHook from", "request.args.get(\"db\") m = HiveMetastoreHook(METASTORE_CONN_ID) tables = sorted(m.get_tables(db=db), key=lambda x: x.tableName)", "or implied. See the License for the # specific language", "express or implied. See the License for the # specific", "static_folder='static', static_url_path='/static/metastore_browser') # Defining the plugin class class MetastoreBrowserPlugin(AirflowPlugin): name", "a.name, db_location_uri, a.desc \"\"\".format(**locals()) h = MySqlHook(METASTORE_MYSQL_CONN_ID) df = h.get_pandas_df(sql)", "JOIN SDS c ON a.SD_ID = c.SD_ID WHERE b.TBL_NAME like", "PRESTO_CONN_ID = 'presto_default' HIVE_CLI_CONN_ID = 'hive_default' DEFAULT_DB = 'default' DB_WHITELIST", "the # specific language governing permissions and limitations # under", "static folder bp = Blueprint( \"metastore_browser\", __name__, template_folder='templates', static_folder='static', static_url_path='/static/metastore_browser')", "json.dumps(d) @gzipped @expose('/data/') def data(self): table = request.args.get(\"table\") sql =", "table-striped table-bordered table-hover\", index=False, na_rep='',) @expose('/ddl/') def ddl(self): table =", "= MySqlHook(METASTORE_MYSQL_CONN_ID) df = h.get_pandas_df(sql) df.db = ( '<a href=\"/admin/metastorebrowserview/db/?db='", "may obtain a copy of the License at # #", "under the License. from datetime import datetime import json from", "= MySqlHook(METASTORE_MYSQL_CONN_ID) d = [ {'id': row[0], 'text': row[0]} for", "from airflow.hooks.mysql_hook import MySqlHook from airflow.hooks.presto_hook import PrestoHook from airflow.plugins_manager", "The ASF licenses this file # to you under the", "the plugin class class MetastoreBrowserPlugin(AirflowPlugin): name = \"metastore_browser\" flask_blueprints =", "HIVE_CLI_CONN_ID = 'hive_default' DEFAULT_DB = 'default' DB_WHITELIST = None DB_BLACKLIST", "# Licensed to the Apache Software Foundation (ASF) under one", "ON a.TBL_ID = b.TBL_ID JOIN DBS d ON b.DB_ID =", "= \"AND b.name IN ({})\".format(dbs) if DB_BLACKLIST: dbs = \",\".join([\"'\"", "= b.DB_ID GROUP BY a.name, db_location_uri, a.desc \"\"\".format(**locals()) h =", "# Keeping pandas from truncating long strings pd.set_option('display.max_colwidth', -1) #", "a.SD_ID = c.SD_ID WHERE b.TBL_NAME like '{table}' AND d.NAME like", "h.run_cli(sql) v = MetastoreBrowserView(category=\"Plugins\", name=\"Hive Metadata Browser\") # Creating a", "= sorted(m.get_tables(db=db), key=lambda x: x.tableName) return self.render( \"metastore_browser/db.html\", tables=tables, db=db)", "law or agreed to in writing, # software distributed under", "Foundation (ASF) under one # or more contributor license agreements.", "pandas from truncating long strings pd.set_option('display.max_colwidth', -1) # Creating a", "WHERE b.TBL_NAME like '{table}' AND d.NAME like '{schema}' ORDER BY", "None DB_BLACKLIST = ['tmp'] TABLE_SELECTOR_LIMIT = 2000 # Keeping pandas", "= \"\"\" SELECT a.name as db, db_location_uri as location, count(1)", "and static folder bp = Blueprint( \"metastore_browser\", __name__, template_folder='templates', static_folder='static',", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "h.get_pandas_df(sql) return df.to_html( classes=\"table table-striped table-bordered table-hover\", index=False, na_rep='',) @expose('/ddl/')", "table_name=table_name, datetime=datetime, int=int) @expose('/db/') def db(self): db = request.args.get(\"db\") m", "Software Foundation (ASF) under one # or more contributor license", "from flask import Blueprint, request from flask_admin import BaseView, expose", "gzipped METASTORE_CONN_ID = 'metastore_default' METASTORE_MYSQL_CONN_ID = 'metastore_mysql' PRESTO_CONN_ID = 'presto_default'", "# regarding copyright ownership. The ASF licenses this file #", "Blueprint, request from flask_admin import BaseView, expose import pandas as", "in compliance # with the License. You may obtain a", "# to you under the Apache License, Version 2.0 (the", "License for the # specific language governing permissions and limitations", "b ON a.DB_ID = b.DB_ID GROUP BY a.name, db_location_uri, a.desc", "datetime=datetime, int=int) @expose('/db/') def db(self): db = request.args.get(\"db\") m =", "OR CONDITIONS OF ANY # KIND, either express or implied.", "m.get_table(table_name) return self.render( \"metastore_browser/table.html\", table=table, table_name=table_name, datetime=datetime, int=int) @expose('/db/') def", "METASTORE_MYSQL_CONN_ID = 'metastore_mysql' PRESTO_CONN_ID = 'presto_default' HIVE_CLI_CONN_ID = 'hive_default' DEFAULT_DB", "MetastoreBrowserView(category=\"Plugins\", name=\"Hive Metadata Browser\") # Creating a flask blueprint to", "sql = \"SHOW CREATE TABLE {table};\".format(table=table) h = HiveCliHook(HIVE_CLI_CONN_ID) return", "ON a.DB_ID = b.DB_ID WHERE a.TBL_NAME NOT LIKE '%tmp%' AND", "na_rep='',) @gzipped @expose('/objects/') def objects(self): where_clause = '' if DB_WHITELIST:", "MetastoreBrowserView(BaseView, wwwutils.DataProfilingMixin): @expose('/') def index(self): sql = \"\"\" SELECT a.name", "objects(self): where_clause = '' if DB_WHITELIST: dbs = \",\".join([\"'\" +", "AND d.NAME like '{schema}' ORDER BY PART_NAME DESC \"\"\".format(**locals()) h", "request.args.get(\"table\") sql = \"SELECT * FROM {table} LIMIT 1000;\".format(table=table) h", "classes=\"table table-striped table-bordered table-hover\", index=False, na_rep='',) @gzipped @expose('/objects/') def objects(self):", "'%temp%' {where_clause} LIMIT {LIMIT}; \"\"\".format(where_clause=where_clause, LIMIT=TABLE_SELECTOR_LIMIT) h = MySqlHook(METASTORE_MYSQL_CONN_ID) d", "static_url_path='/static/metastore_browser') # Defining the plugin class class MetastoreBrowserPlugin(AirflowPlugin): name =", "this file # to you under the Apache License, Version", "= \"AND b.name NOT IN ({})\".format(dbs) sql = \"\"\" SELECT", "LIKE '%temp%' {where_clause} LIMIT {LIMIT}; \"\"\".format(where_clause=where_clause, LIMIT=TABLE_SELECTOR_LIMIT) h = MySqlHook(METASTORE_MYSQL_CONN_ID)", "'metastore_mysql' PRESTO_CONN_ID = 'presto_default' HIVE_CLI_CONN_ID = 'hive_default' DEFAULT_DB = 'default'", "copyright ownership. The ASF licenses this file # to you", "= 'metastore_mysql' PRESTO_CONN_ID = 'presto_default' HIVE_CLI_CONN_ID = 'hive_default' DEFAULT_DB =", "x: x.tableName) return self.render( \"metastore_browser/db.html\", tables=tables, db=db) @gzipped @expose('/partitions/') def", "in writing, # software distributed under the License is distributed", "= request.args.get(\"table\") sql = \"SELECT * FROM {table} LIMIT 1000;\".format(table=table)", "db, db_location_uri as location, count(1) as object_count, a.desc as description", "request.args.get(\"table\") sql = \"SHOW CREATE TABLE {table};\".format(table=table) h = HiveCliHook(HIVE_CLI_CONN_ID)", "= request.args.get(\"db\") m = HiveMetastoreHook(METASTORE_CONN_ID) tables = sorted(m.get_tables(db=db), key=lambda x:", "( '<a href=\"/admin/metastorebrowserview/db/?db=' + df.db + '\">' + df.db +", "sql = \"\"\" SELECT a.name as db, db_location_uri as location,", "TABLE_SELECTOR_LIMIT = 2000 # Keeping pandas from truncating long strings", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "License is distributed on an # \"AS IS\" BASIS, WITHOUT", "href=\"/admin/metastorebrowserview/db/?db=' + df.db + '\">' + df.db + '</a>') table", "= c.SD_ID WHERE b.TBL_NAME like '{table}' AND d.NAME like '{schema}'", "table-bordered table-hover\", index=False, na_rep='',) @gzipped @expose('/objects/') def objects(self): where_clause =", "c.INPUT_FORMAT, c.OUTPUT_FORMAT FROM PARTITIONS a JOIN TBLS b ON a.TBL_ID", "WHERE a.TBL_NAME NOT LIKE '%tmp%' AND a.TBL_NAME NOT LIKE '%temp%'", "in h.get_records(sql)] return json.dumps(d) @gzipped @expose('/data/') def data(self): table =", "table = request.args.get(\"table\") sql = \"SHOW CREATE TABLE {table};\".format(table=table) h", "JOIN TBLS b ON a.TBL_ID = b.TBL_ID JOIN DBS d", "db_location_uri, a.desc \"\"\".format(**locals()) h = MySqlHook(METASTORE_MYSQL_CONN_ID) df = h.get_pandas_df(sql) df.db", "@gzipped @expose('/objects/') def objects(self): where_clause = '' if DB_WHITELIST: dbs", "b.TBL_ID JOIN DBS d ON b.DB_ID = d.DB_ID JOIN SDS", "# \"License\"); you may not use this file except in", "json from flask import Blueprint, request from flask_admin import BaseView,", "return h.run_cli(sql) v = MetastoreBrowserView(category=\"Plugins\", name=\"Hive Metadata Browser\") # Creating", "# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY", "'metastore_default' METASTORE_MYSQL_CONN_ID = 'metastore_mysql' PRESTO_CONN_ID = 'presto_default' HIVE_CLI_CONN_ID = 'hive_default'", "to the Apache Software Foundation (ASF) under one # or", "= d.DB_ID JOIN SDS c ON a.SD_ID = c.SD_ID WHERE", "\"License\"); you may not use this file except in compliance", "__name__, template_folder='templates', static_folder='static', static_url_path='/static/metastore_browser') # Defining the plugin class class", "= \",\".join([\"'\" + db + \"'\" for db in DB_BLACKLIST])", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "index=False, escape=False, na_rep='',) return self.render( \"metastore_browser/dbs.html\", table=table) @expose('/table/') def table(self):", "tables = sorted(m.get_tables(db=db), key=lambda x: x.tableName) return self.render( \"metastore_browser/db.html\", tables=tables,", "flask_admin import BaseView, expose import pandas as pd from airflow.hooks.hive_hooks", "self.render( \"metastore_browser/table.html\", table=table, table_name=table_name, datetime=datetime, int=int) @expose('/db/') def db(self): db", "c.IS_COMPRESSED, c.INPUT_FORMAT, c.OUTPUT_FORMAT FROM PARTITIONS a JOIN TBLS b ON", "na_rep='',) return self.render( \"metastore_browser/dbs.html\", table=table) @expose('/table/') def table(self): table_name =", "# under the License. from datetime import datetime import json", "df = h.get_pandas_df(sql) df.db = ( '<a href=\"/admin/metastorebrowserview/db/?db=' + df.db", "return df.to_html( classes=\"table table-striped table-bordered table-hover\", index=False, na_rep='',) @gzipped @expose('/objects/')", "airflow.hooks.presto_hook import PrestoHook from airflow.plugins_manager import AirflowPlugin from airflow.www import", "# distributed with this work for additional information # regarding", "* FROM {table} LIMIT 1000;\".format(table=table) h = PrestoHook(PRESTO_CONN_ID) df =", "writing, # software distributed under the License is distributed on", "HiveCliHook(HIVE_CLI_CONN_ID) return h.run_cli(sql) v = MetastoreBrowserView(category=\"Plugins\", name=\"Hive Metadata Browser\") #", "-*- # # Licensed to the Apache Software Foundation (ASF)", "airflow.www.decorators import gzipped METASTORE_CONN_ID = 'metastore_default' METASTORE_MYSQL_CONN_ID = 'metastore_mysql' PRESTO_CONN_ID", "from flask_admin import BaseView, expose import pandas as pd from", "folder bp = Blueprint( \"metastore_browser\", __name__, template_folder='templates', static_folder='static', static_url_path='/static/metastore_browser') #", "import AirflowPlugin from airflow.www import utils as wwwutils from airflow.www.decorators", "CONDITIONS OF ANY # KIND, either express or implied. See", "MySqlHook(METASTORE_MYSQL_CONN_ID) df = h.get_pandas_df(sql) return df.to_html( classes=\"table table-striped table-bordered table-hover\",", "d.NAME like '{schema}' ORDER BY PART_NAME DESC \"\"\".format(**locals()) h =", "where_clause = '' if DB_WHITELIST: dbs = \",\".join([\"'\" + db", "SDS c ON a.SD_ID = c.SD_ID WHERE b.TBL_NAME like '{table}'", "'.', a.TBL_NAME), TBL_TYPE FROM TBLS a JOIN DBS b ON", "return df.to_html( classes=\"table table-striped table-bordered table-hover\", index=False, na_rep='',) @expose('/ddl/') def", "template_folder='templates', static_folder='static', static_url_path='/static/metastore_browser') # Defining the plugin class class MetastoreBrowserPlugin(AirflowPlugin):", "bp = Blueprint( \"metastore_browser\", __name__, template_folder='templates', static_folder='static', static_url_path='/static/metastore_browser') # Defining", "+ db + \"'\" for db in DB_BLACKLIST]) where_clause =", "@expose('/ddl/') def ddl(self): table = request.args.get(\"table\") sql = \"SHOW CREATE", "FROM {table} LIMIT 1000;\".format(table=table) h = PrestoHook(PRESTO_CONN_ID) df = h.get_pandas_df(sql)", "FROM TBLS a JOIN DBS b ON a.DB_ID = b.DB_ID", "for additional information # regarding copyright ownership. The ASF licenses", "a.CREATE_TIME, c.LOCATION, c.IS_COMPRESSED, c.INPUT_FORMAT, c.OUTPUT_FORMAT FROM PARTITIONS a JOIN TBLS", "'{table}' AND d.NAME like '{schema}' ORDER BY PART_NAME DESC \"\"\".format(**locals())", "the Apache Software Foundation (ASF) under one # or more", "b.DB_ID GROUP BY a.name, db_location_uri, a.desc \"\"\".format(**locals()) h = MySqlHook(METASTORE_MYSQL_CONN_ID)", "# # Unless required by applicable law or agreed to", "for row in h.get_records(sql)] return json.dumps(d) @gzipped @expose('/data/') def data(self):", "Version 2.0 (the # \"License\"); you may not use this", "'hive_default' DEFAULT_DB = 'default' DB_WHITELIST = None DB_BLACKLIST = ['tmp']", "FROM DBS a JOIN TBLS b ON a.DB_ID = b.DB_ID", "one # or more contributor license agreements. See the NOTICE", "DBS b ON a.DB_ID = b.DB_ID WHERE a.TBL_NAME NOT LIKE", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "table=table) @expose('/table/') def table(self): table_name = request.args.get(\"table\") m = HiveMetastoreHook(METASTORE_CONN_ID)", "LIMIT {LIMIT}; \"\"\".format(where_clause=where_clause, LIMIT=TABLE_SELECTOR_LIMIT) h = MySqlHook(METASTORE_MYSQL_CONN_ID) d = [", "# -*- coding: utf-8 -*- # # Licensed to the", "IN ({})\".format(dbs) if DB_BLACKLIST: dbs = \",\".join([\"'\" + db +", "name=\"Hive Metadata Browser\") # Creating a flask blueprint to intergrate", "+ db + \"'\" for db in DB_WHITELIST]) where_clause =", "airflow.hooks.mysql_hook import MySqlHook from airflow.hooks.presto_hook import PrestoHook from airflow.plugins_manager import", "a.TBL_NAME NOT LIKE '%temp%' AND b.NAME NOT LIKE '%tmp%' AND", "except in compliance # with the License. You may obtain", "METASTORE_CONN_ID = 'metastore_default' METASTORE_MYSQL_CONN_ID = 'metastore_mysql' PRESTO_CONN_ID = 'presto_default' HIVE_CLI_CONN_ID", "df = h.get_pandas_df(sql) return df.to_html( classes=\"table table-striped table-bordered table-hover\", index=False,", "HiveMetastoreHook(METASTORE_CONN_ID) tables = sorted(m.get_tables(db=db), key=lambda x: x.tableName) return self.render( \"metastore_browser/db.html\",", "a flask blueprint to intergrate the templates and static folder", "{LIMIT}; \"\"\".format(where_clause=where_clause, LIMIT=TABLE_SELECTOR_LIMIT) h = MySqlHook(METASTORE_MYSQL_CONN_ID) d = [ {'id':", "m = HiveMetastoreHook(METASTORE_CONN_ID) tables = sorted(m.get_tables(db=db), key=lambda x: x.tableName) return", "admin BaseView class MetastoreBrowserView(BaseView, wwwutils.DataProfilingMixin): @expose('/') def index(self): sql =", "NOTICE file # distributed with this work for additional information", "h.get_records(sql)] return json.dumps(d) @gzipped @expose('/data/') def data(self): table = request.args.get(\"table\")", "class MetastoreBrowserView(BaseView, wwwutils.DataProfilingMixin): @expose('/') def index(self): sql = \"\"\" SELECT", "this file except in compliance # with the License. You", "a flask admin BaseView class MetastoreBrowserView(BaseView, wwwutils.DataProfilingMixin): @expose('/') def index(self):", "from airflow.plugins_manager import AirflowPlugin from airflow.www import utils as wwwutils", "TBLS b ON a.DB_ID = b.DB_ID GROUP BY a.name, db_location_uri,", "for db in DB_BLACKLIST]) where_clause = \"AND b.name NOT IN", "license agreements. See the NOTICE file # distributed with this", "a.TBL_NAME), TBL_TYPE FROM TBLS a JOIN DBS b ON a.DB_ID", "@expose('/data/') def data(self): table = request.args.get(\"table\") sql = \"SELECT *", "required by applicable law or agreed to in writing, #", "db=db) @gzipped @expose('/partitions/') def partitions(self): schema, table = request.args.get(\"table\").split('.') sql", "@expose('/partitions/') def partitions(self): schema, table = request.args.get(\"table\").split('.') sql = \"\"\"", "SELECT CONCAT(b.NAME, '.', a.TBL_NAME), TBL_TYPE FROM TBLS a JOIN DBS", "db + \"'\" for db in DB_BLACKLIST]) where_clause = \"AND", "\"AND b.name IN ({})\".format(dbs) if DB_BLACKLIST: dbs = \",\".join([\"'\" +", "\"metastore_browser/table.html\", table=table, table_name=table_name, datetime=datetime, int=int) @expose('/db/') def db(self): db =", "the License for the # specific language governing permissions and", "= 'hive_default' DEFAULT_DB = 'default' DB_WHITELIST = None DB_BLACKLIST =", "datetime import datetime import json from flask import Blueprint, request", "CREATE TABLE {table};\".format(table=table) h = HiveCliHook(HIVE_CLI_CONN_ID) return h.run_cli(sql) v =", "ANY # KIND, either express or implied. See the License", "the License is distributed on an # \"AS IS\" BASIS,", "'default' DB_WHITELIST = None DB_BLACKLIST = ['tmp'] TABLE_SELECTOR_LIMIT = 2000", "JOIN TBLS b ON a.DB_ID = b.DB_ID GROUP BY a.name,", "c.SD_ID WHERE b.TBL_NAME like '{table}' AND d.NAME like '{schema}' ORDER", "PrestoHook from airflow.plugins_manager import AirflowPlugin from airflow.www import utils as", "table-hover\", index=False, na_rep='',) @gzipped @expose('/objects/') def objects(self): where_clause = ''", "\"metastore_browser/db.html\", tables=tables, db=db) @gzipped @expose('/partitions/') def partitions(self): schema, table =", "# # Licensed to the Apache Software Foundation (ASF) under", "the templates and static folder bp = Blueprint( \"metastore_browser\", __name__,", "\"'\" for db in DB_BLACKLIST]) where_clause = \"AND b.name NOT", "AND a.TBL_NAME NOT LIKE '%temp%' AND b.NAME NOT LIKE '%tmp%'", "NOT IN ({})\".format(dbs) sql = \"\"\" SELECT CONCAT(b.NAME, '.', a.TBL_NAME),", "not use this file except in compliance # with the", "v = MetastoreBrowserView(category=\"Plugins\", name=\"Hive Metadata Browser\") # Creating a flask", "= MySqlHook(METASTORE_MYSQL_CONN_ID) df = h.get_pandas_df(sql) return df.to_html( classes=\"table table-striped table-bordered", "table-bordered table-hover\", index=False, na_rep='',) @expose('/ddl/') def ddl(self): table = request.args.get(\"table\")", "= 'metastore_default' METASTORE_MYSQL_CONN_ID = 'metastore_mysql' PRESTO_CONN_ID = 'presto_default' HIVE_CLI_CONN_ID =", "'<a href=\"/admin/metastorebrowserview/db/?db=' + df.db + '\">' + df.db + '</a>')", "def index(self): sql = \"\"\" SELECT a.name as db, db_location_uri", "blueprint to intergrate the templates and static folder bp =", "m = HiveMetastoreHook(METASTORE_CONN_ID) table = m.get_table(table_name) return self.render( \"metastore_browser/table.html\", table=table,", "Unless required by applicable law or agreed to in writing,", "ddl(self): table = request.args.get(\"table\") sql = \"SHOW CREATE TABLE {table};\".format(table=table)", "LIMIT 1000;\".format(table=table) h = PrestoHook(PRESTO_CONN_ID) df = h.get_pandas_df(sql) return df.to_html(", "df.db + '\">' + df.db + '</a>') table = df.to_html(", "self.render( \"metastore_browser/dbs.html\", table=table) @expose('/table/') def table(self): table_name = request.args.get(\"table\") m", "@gzipped @expose('/partitions/') def partitions(self): schema, table = request.args.get(\"table\").split('.') sql =", "= 2000 # Keeping pandas from truncating long strings pd.set_option('display.max_colwidth',", "= '' if DB_WHITELIST: dbs = \",\".join([\"'\" + db +", "Creating a flask admin BaseView class MetastoreBrowserView(BaseView, wwwutils.DataProfilingMixin): @expose('/') def", "(ASF) under one # or more contributor license agreements. See", "# or more contributor license agreements. See the NOTICE file", "agreed to in writing, # software distributed under the License", "db = request.args.get(\"db\") m = HiveMetastoreHook(METASTORE_CONN_ID) tables = sorted(m.get_tables(db=db), key=lambda", "sql = \"SELECT * FROM {table} LIMIT 1000;\".format(table=table) h =", "row in h.get_records(sql)] return json.dumps(d) @gzipped @expose('/data/') def data(self): table", "import HiveMetastoreHook, HiveCliHook from airflow.hooks.mysql_hook import MySqlHook from airflow.hooks.presto_hook import", "b.DB_ID = d.DB_ID JOIN SDS c ON a.SD_ID = c.SD_ID", "a.name as db, db_location_uri as location, count(1) as object_count, a.desc", "wwwutils from airflow.www.decorators import gzipped METASTORE_CONN_ID = 'metastore_default' METASTORE_MYSQL_CONN_ID =", "MySqlHook from airflow.hooks.presto_hook import PrestoHook from airflow.plugins_manager import AirflowPlugin from", "classes=\"table table-striped table-bordered table-hover\", index=False, escape=False, na_rep='',) return self.render( \"metastore_browser/dbs.html\",", "(the # \"License\"); you may not use this file except", "location, count(1) as object_count, a.desc as description FROM DBS a", "airflow.www import utils as wwwutils from airflow.www.decorators import gzipped METASTORE_CONN_ID", "c.OUTPUT_FORMAT FROM PARTITIONS a JOIN TBLS b ON a.TBL_ID =", "sql = \"\"\" SELECT CONCAT(b.NAME, '.', a.TBL_NAME), TBL_TYPE FROM TBLS", "PART_NAME DESC \"\"\".format(**locals()) h = MySqlHook(METASTORE_MYSQL_CONN_ID) df = h.get_pandas_df(sql) return", "ASF licenses this file # to you under the Apache", "import gzipped METASTORE_CONN_ID = 'metastore_default' METASTORE_MYSQL_CONN_ID = 'metastore_mysql' PRESTO_CONN_ID =", "AirflowPlugin from airflow.www import utils as wwwutils from airflow.www.decorators import", "the License. from datetime import datetime import json from flask", "DB_WHITELIST: dbs = \",\".join([\"'\" + db + \"'\" for db", "on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS", "intergrate the templates and static folder bp = Blueprint( \"metastore_browser\",", "ownership. The ASF licenses this file # to you under", "return self.render( \"metastore_browser/dbs.html\", table=table) @expose('/table/') def table(self): table_name = request.args.get(\"table\")", "# Defining the plugin class class MetastoreBrowserPlugin(AirflowPlugin): name = \"metastore_browser\"", "dbs = \",\".join([\"'\" + db + \"'\" for db in", "classes=\"table table-striped table-bordered table-hover\", index=False, na_rep='',) @expose('/ddl/') def ddl(self): table", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "with the License. You may obtain a copy of the", "pandas as pd from airflow.hooks.hive_hooks import HiveMetastoreHook, HiveCliHook from airflow.hooks.mysql_hook", "d ON b.DB_ID = d.DB_ID JOIN SDS c ON a.SD_ID", "truncating long strings pd.set_option('display.max_colwidth', -1) # Creating a flask admin", "applicable law or agreed to in writing, # software distributed", "escape=False, na_rep='',) return self.render( \"metastore_browser/dbs.html\", table=table) @expose('/table/') def table(self): table_name", "\"\"\".format(**locals()) h = MySqlHook(METASTORE_MYSQL_CONN_ID) df = h.get_pandas_df(sql) df.db = (", "limitations # under the License. from datetime import datetime import", "+ '\">' + df.db + '</a>') table = df.to_html( classes=\"table", "h = PrestoHook(PRESTO_CONN_ID) df = h.get_pandas_df(sql) return df.to_html( classes=\"table table-striped", "'%tmp%' AND b.NAME NOT LIKE '%temp%' {where_clause} LIMIT {LIMIT}; \"\"\".format(where_clause=where_clause,", "is distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES", "'text': row[0]} for row in h.get_records(sql)] return json.dumps(d) @gzipped @expose('/data/')", "'</a>') table = df.to_html( classes=\"table table-striped table-bordered table-hover\", index=False, escape=False,", "file # to you under the Apache License, Version 2.0", "df.db + '</a>') table = df.to_html( classes=\"table table-striped table-bordered table-hover\",", "\"SELECT * FROM {table} LIMIT 1000;\".format(table=table) h = PrestoHook(PRESTO_CONN_ID) df", "from truncating long strings pd.set_option('display.max_colwidth', -1) # Creating a flask", "import PrestoHook from airflow.plugins_manager import AirflowPlugin from airflow.www import utils", "# with the License. You may obtain a copy of", "a.DB_ID = b.DB_ID WHERE a.TBL_NAME NOT LIKE '%tmp%' AND a.TBL_NAME", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "as object_count, a.desc as description FROM DBS a JOIN TBLS", "b.name IN ({})\".format(dbs) if DB_BLACKLIST: dbs = \",\".join([\"'\" + db", "DBS a JOIN TBLS b ON a.DB_ID = b.DB_ID GROUP", "governing permissions and limitations # under the License. from datetime", "d.DB_ID JOIN SDS c ON a.SD_ID = c.SD_ID WHERE b.TBL_NAME", "NOT LIKE '%temp%' AND b.NAME NOT LIKE '%tmp%' AND b.NAME", "# Creating a flask admin BaseView class MetastoreBrowserView(BaseView, wwwutils.DataProfilingMixin): @expose('/')", "coding: utf-8 -*- # # Licensed to the Apache Software", "software distributed under the License is distributed on an #", "Licensed to the Apache Software Foundation (ASF) under one #", "flask admin BaseView class MetastoreBrowserView(BaseView, wwwutils.DataProfilingMixin): @expose('/') def index(self): sql", "+ '</a>') table = df.to_html( classes=\"table table-striped table-bordered table-hover\", index=False,", "= \"SHOW CREATE TABLE {table};\".format(table=table) h = HiveCliHook(HIVE_CLI_CONN_ID) return h.run_cli(sql)", "= HiveMetastoreHook(METASTORE_CONN_ID) tables = sorted(m.get_tables(db=db), key=lambda x: x.tableName) return self.render(", "@expose('/db/') def db(self): db = request.args.get(\"db\") m = HiveMetastoreHook(METASTORE_CONN_ID) tables", "like '{table}' AND d.NAME like '{schema}' ORDER BY PART_NAME DESC", "MySqlHook(METASTORE_MYSQL_CONN_ID) d = [ {'id': row[0], 'text': row[0]} for row", "class MetastoreBrowserPlugin(AirflowPlugin): name = \"metastore_browser\" flask_blueprints = [bp] admin_views =", "under one # or more contributor license agreements. See the", "pd from airflow.hooks.hive_hooks import HiveMetastoreHook, HiveCliHook from airflow.hooks.mysql_hook import MySqlHook", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "ON b.DB_ID = d.DB_ID JOIN SDS c ON a.SD_ID =", "df.to_html( classes=\"table table-striped table-bordered table-hover\", index=False, na_rep='',) @expose('/ddl/') def ddl(self):", "and limitations # under the License. from datetime import datetime", "h = MySqlHook(METASTORE_MYSQL_CONN_ID) df = h.get_pandas_df(sql) df.db = ( '<a", "'%tmp%' AND a.TBL_NAME NOT LIKE '%temp%' AND b.NAME NOT LIKE", "'%temp%' AND b.NAME NOT LIKE '%tmp%' AND b.NAME NOT LIKE", "information # regarding copyright ownership. The ASF licenses this file", "return self.render( \"metastore_browser/table.html\", table=table, table_name=table_name, datetime=datetime, int=int) @expose('/db/') def db(self):", "the Apache License, Version 2.0 (the # \"License\"); you may", "from airflow.www.decorators import gzipped METASTORE_CONN_ID = 'metastore_default' METASTORE_MYSQL_CONN_ID = 'metastore_mysql'", "def partitions(self): schema, table = request.args.get(\"table\").split('.') sql = \"\"\" SELECT", "db_location_uri as location, count(1) as object_count, a.desc as description FROM", "-*- coding: utf-8 -*- # # Licensed to the Apache", "= 'presto_default' HIVE_CLI_CONN_ID = 'hive_default' DEFAULT_DB = 'default' DB_WHITELIST =", "TBL_TYPE FROM TBLS a JOIN DBS b ON a.DB_ID =", "plugin class class MetastoreBrowserPlugin(AirflowPlugin): name = \"metastore_browser\" flask_blueprints = [bp]", "you under the Apache License, Version 2.0 (the # \"License\");", "df.db = ( '<a href=\"/admin/metastorebrowserview/db/?db=' + df.db + '\">' +", "def db(self): db = request.args.get(\"db\") m = HiveMetastoreHook(METASTORE_CONN_ID) tables =", "import datetime import json from flask import Blueprint, request from", "# KIND, either express or implied. See the License for", "= ['tmp'] TABLE_SELECTOR_LIMIT = 2000 # Keeping pandas from truncating", "\"SHOW CREATE TABLE {table};\".format(table=table) h = HiveCliHook(HIVE_CLI_CONN_ID) return h.run_cli(sql) v", "as pd from airflow.hooks.hive_hooks import HiveMetastoreHook, HiveCliHook from airflow.hooks.mysql_hook import", "PARTITIONS a JOIN TBLS b ON a.TBL_ID = b.TBL_ID JOIN", "templates and static folder bp = Blueprint( \"metastore_browser\", __name__, template_folder='templates',", "agreements. See the NOTICE file # distributed with this work", "AND b.NAME NOT LIKE '%temp%' {where_clause} LIMIT {LIMIT}; \"\"\".format(where_clause=where_clause, LIMIT=TABLE_SELECTOR_LIMIT)", "= \"SELECT * FROM {table} LIMIT 1000;\".format(table=table) h = PrestoHook(PRESTO_CONN_ID)", "h = HiveCliHook(HIVE_CLI_CONN_ID) return h.run_cli(sql) v = MetastoreBrowserView(category=\"Plugins\", name=\"Hive Metadata", "\",\".join([\"'\" + db + \"'\" for db in DB_WHITELIST]) where_clause", "licenses this file # to you under the Apache License,", "index=False, na_rep='',) @expose('/ddl/') def ddl(self): table = request.args.get(\"table\") sql =", "LIKE '%tmp%' AND a.TBL_NAME NOT LIKE '%temp%' AND b.NAME NOT", "table(self): table_name = request.args.get(\"table\") m = HiveMetastoreHook(METASTORE_CONN_ID) table = m.get_table(table_name)", "by applicable law or agreed to in writing, # software", "# Unless required by applicable law or agreed to in", "= m.get_table(table_name) return self.render( \"metastore_browser/table.html\", table=table, table_name=table_name, datetime=datetime, int=int) @expose('/db/')", "in DB_WHITELIST]) where_clause = \"AND b.name IN ({})\".format(dbs) if DB_BLACKLIST:", "+ df.db + '\">' + df.db + '</a>') table =", "IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND,", "+ \"'\" for db in DB_WHITELIST]) where_clause = \"AND b.name", "= HiveCliHook(HIVE_CLI_CONN_ID) return h.run_cli(sql) v = MetastoreBrowserView(category=\"Plugins\", name=\"Hive Metadata Browser\")", "License. You may obtain a copy of the License at", "BY a.name, db_location_uri, a.desc \"\"\".format(**locals()) h = MySqlHook(METASTORE_MYSQL_CONN_ID) df =", "'presto_default' HIVE_CLI_CONN_ID = 'hive_default' DEFAULT_DB = 'default' DB_WHITELIST = None", "return self.render( \"metastore_browser/db.html\", tables=tables, db=db) @gzipped @expose('/partitions/') def partitions(self): schema,", "You may obtain a copy of the License at #", "({})\".format(dbs) sql = \"\"\" SELECT CONCAT(b.NAME, '.', a.TBL_NAME), TBL_TYPE FROM", "a JOIN TBLS b ON a.TBL_ID = b.TBL_ID JOIN DBS", "b.NAME NOT LIKE '%tmp%' AND b.NAME NOT LIKE '%temp%' {where_clause}", "compliance # with the License. You may obtain a copy", "Keeping pandas from truncating long strings pd.set_option('display.max_colwidth', -1) # Creating", "MetastoreBrowserPlugin(AirflowPlugin): name = \"metastore_browser\" flask_blueprints = [bp] admin_views = [v]", "request.args.get(\"table\") m = HiveMetastoreHook(METASTORE_CONN_ID) table = m.get_table(table_name) return self.render( \"metastore_browser/table.html\",", "permissions and limitations # under the License. from datetime import", "AND b.NAME NOT LIKE '%tmp%' AND b.NAME NOT LIKE '%temp%'", "DESC \"\"\".format(**locals()) h = MySqlHook(METASTORE_MYSQL_CONN_ID) df = h.get_pandas_df(sql) return df.to_html(", "a.TBL_NAME NOT LIKE '%tmp%' AND a.TBL_NAME NOT LIKE '%temp%' AND" ]
[ "exit(0) when all are finished thread = threading.Thread(target=runCompose, args=(app, \"up", "print(\"Wrote registry to registry.json\") simpleRegistry = getSimpleAppRegistry(apps, appsDir) with open(os.path.join(appSystemDir,", "\"docker compose --env-file '{}' --project-name '{}' --file '{}' --file '{}'", "userData[\"installedApps\"]: print(\"Stopping app {}...\".format(app)) # Run runCompose(args.app, \"up --detach\") asynchrounously", "YAML with open(appYml, \"w\") as f: f.write(yaml.dump(converted, sort_keys=False)) def update(verbose:", "to apps.json\") # Loop through the apps and generate valid", "raise Exception(\"Error: Could not find metadata in \" + appFile)", "dir # Before that, check if a docker-compose.yml exists in", "dir with the contents of the temporary dir/apps/app # Also,", "Load the registry with open(registry, \"r\") as f: registryData =", "sort_keys=False)) def update(verbose: bool = False): apps = findAndValidateApps(appsDir) #", "\"hostname -s 2>/dev/null || echo 'umbrel'\", shell=True).decode(\"utf-8\") + \".local\" os.environ[\"APP_HIDDEN_SERVICE\"]", "== \"\": continue # Split the repo into the git", "contents of the temporary dir/apps/app # Also, keep a list", "print anything to stdout, as we don't want to see", "return response.text else: return False def getAppYmlPath(app): return os.path.join(appsDir, app,", "str(app['version']) == \"1\"): return createComposeConfigFromV1(app, nodeRoot) else: return createComposeConfigFromV0(app) def", "app is already installed, don't overwrite it if app in", "= os.path.join(nodeRoot, \"db\", \"user.json\") legacyScript = os.path.join(nodeRoot, \"scripts\", \"app\") def", "with open(registry, \"r\") as f: registryData = json.load(f) converted =", "registryData = json.load(f) converted = convertComposeYMLToAppYML(compose, app, registryData) # Put", "after encoding it as YAML with open(appYml, \"w\") as f:", "json.dump(registry, f, indent=4, sort_keys=True) print(\"Wrote registry to registry.json\") simpleRegistry =", "with app-${APP}- # but return them without the app-${APP}- prefix", "os import requests import shutil import json import yaml import", "[] for subdir in os.listdir(torDir): if subdir.startswith(\"app-{}-\".format(app)): results.append(subdir[len(\"app-{}-\".format(app)):]) return results", "are finished thread = threading.Thread( target=runCompose, args=(app, \"rm --force --stop\"))", "sys.argv joined into a string by spaces def getArguments(): arguments", "list of repos repos = [] with open(sourcesList) as f:", "the entire repo # Dont print anything to stdout, as", "{} 2>/dev/null || echo 'notyetset.onion'\".format( os.path.join(nodeRoot, \"tor\", \"data\", \"app-{}/hostname\".format(app))), shell=True).decode(\"utf-8\")", "os.path.isdir(os.path.join(appsDir, app)): shutil.rmtree(os.path.join(appsDir, app), onerror=remove_readonly) if os.path.isdir(os.path.join(tempDir, \"apps\", app)): shutil.copytree(os.path.join(tempDir,", "# SPDX-License-Identifier: MIT import stat import tempfile import threading from", "compose generation process updates the registry, so we need to", "more app seeds, with random numbers from 1-5 assigned in", "repo, clone the repo to a temporary dir, checkout the", "--env-file '{}' --project-name '{}' --file '{}' --file '{}' {}\".format( os.path.join(nodeRoot,", "app + \" to \" + composeFile) print(\"Generated configuration successfully\")", "exit(1) gitUrl = repo[0] branch = repo[1] # Clone the", "their hostname in the environment hiddenServices: List[str] = getAppHiddenServices(app) for", "open(userFile, \"r\") as f: userData = json.load(f) threads = []", "= [] with open(sourcesList) as f: repos = f.readlines() #", "a depth of 1 to avoid cloning the entire repo", "dir composeFile = os.path.join(appsDir, app, \"docker-compose.yml\") commonComposeFile = os.path.join(appSystemDir, \"docker-compose.common.yml\")", "= appId if('version' in app and str(app['version']) == \"1\"): return", "= repo.split(\" \") if len(repo) != 2: print(\"Error: Invalid repo", "exist, just do nothing userData = {} if os.path.isfile(userFile): with", "metadata in \" + appFile) app[\"metadata\"][\"id\"] = appId if('version' in", "Could not find docker-compose.yml in \" + app) exit(1) os.system(", "str): compose(app, args) # Returns a list of every argument", "and wait for them to finish def joinThreads(threads: List[threading.Thread]): for", "set up with the basics before that registry = getAppRegistry(apps,", "typing import List from sys import argv import os import", "repo later in the file may not overwrite an app", "string by spaces def getArguments(): arguments = \"\" for i", "os.path.join(appsDir, app), symlinks=False, ignore=shutil.ignore_patterns(\".gitignore\")) alreadyInstalled.append(app) # Remove the temporary dir", "Put converted into the app.yml after encoding it as YAML", "createComposeConfigFromV1(app, nodeRoot) else: return createComposeConfigFromV0(app) def compose(app, arguments): # Runs", "for app in userData[\"installedApps\"]: print(\"Starting app {}...\".format(app)) # Run runCompose(args.app,", "{} 2>/dev/null || echo 'notyetset.onion'\".format( appHiddenServiceFile), shell=True).decode(\"utf-8\") if not os.path.isfile(composeFile):", "findAndValidateApps(appsDir) for app in apps: data = getAppYml(app) if data:", "print(\"Stopping app {}...\".format(app)) # Run runCompose(args.app, \"up --detach\") asynchrounously for", "-s 2>/dev/null || echo 'umbrel'\", shell=True).decode(\"utf-8\") + \".local\" os.environ[\"APP_HIDDEN_SERVICE\"] =", "start with app-${APP}- # but return them without the app-${APP}-", "\"sources.list\") appDataDir = os.path.join(nodeRoot, \"app-data\") userFile = os.path.join(nodeRoot, \"db\", \"user.json\")", "def download(app: str = None): if(app is None): apps =", "\" + sourcesList) exit(1) gitUrl = repo[0] branch = repo[1]", "in the app dir composeFile = os.path.join(appsDir, app, \"docker-compose.yml\") commonComposeFile", "echo 'notyetset.onion'\".format( appHiddenServiceFile), shell=True).decode(\"utf-8\") if not os.path.isfile(composeFile): print(\"Error: Could not", "# Read the compose file and parse it with open(composeFile,", "to a temporary dir and checkout the branch # Then,", "# Before that, check if a docker-compose.yml exists in the", "need to get it set up with the basics before", "url = 'https://raw.githubusercontent.com/runcitadel/compose-nonfree/main/apps/' + \\ name + '/' + 'app.yml'", "response.text else: return False def getAppYmlPath(app): return os.path.join(appsDir, app, 'app.yml')", "in threads: thread.join() # The directory with this script scriptDir", "with open(userFile, \"w\") as f: json.dump(userData, f) def setRemoved(app: str):", "file and parse it with open(composeFile, \"r\") as f: compose", "\" + app) exit(1) os.system( \"docker compose --env-file '{}' --project-name", "= repo.strip() if repo == \"\": continue # Split the", "to a temporary dir tempDir = tempfile.mkdtemp() print(\"Cloning the repository\")", "anything to stdout, as we don't want to see the", "# Loop through the apps and generate valid compose files", "if len(repo) != 2: print(\"Error: Invalid repo format in \"", "os.chmod(path, stat.S_IWRITE) func(path) def deleteData(app: str): dataDir = os.path.join(appDataDir, app)", "import stat import tempfile import threading from typing import List", "with open(composeFile, \"r\") as f: compose = yaml.safe_load(f) registry =", "f: json.dump(userData, f) def getAppHiddenServices(app: str): torDir = os.path.join(nodeRoot, \"tor\",", "List from sys import argv import os import requests import", "services for an app and put their hostname in the", "in the file may not overwrite an app from a", "file def updateRepos(): # Get the list of repos repos", "\"scripts\", \"app\") def runCompose(app: str, args: str): compose(app, args) #", "def getAppHiddenServices(app: str): torDir = os.path.join(nodeRoot, \"tor\", \"data\") # List", "dir with the contents of the temporary dir/apps/app for app", "while excluding .gitignore shutil.copytree(appDir, dataDir, symlinks=False, ignore=shutil.ignore_patterns(\".gitignore\")) # Chown and", "contains a list of sources in the format # <git-url>", "from 1-5 assigned in a loop for i in range(1,", "\"data\", \"app-{}-{}/hostname\".format(app, service)) os.environ[\"APP_HIDDEN_SERVICE_{}\".format(service.upper().replace(\"-\", \"_\"))] = subprocess.check_output(\"cat {} 2>/dev/null ||", "yaml.safe_load(f) registry = os.path.join(appsDir, \"registry.json\") # Load the registry with", "[] for app in userData[\"installedApps\"]: print(\"Stopping app {}...\".format(app)) # Run", "then exit(0) when all are finished thread = threading.Thread( target=runCompose,", "os.path.isfile(composeFile): print(\"Error: Could not find docker-compose.yml in \" + app)", "service)) os.environ[\"APP_HIDDEN_SERVICE_{}\".format(service.upper().replace(\"-\", \"_\"))] = subprocess.check_output(\"cat {} 2>/dev/null || echo 'notyetset.onion'\".format(", "for them to finish def joinThreads(threads: List[threading.Thread]): for thread in", "hostname in the environment hiddenServices: List[str] = getAppHiddenServices(app) for service", "to see the git clone output subprocess.run(\"git clone --depth 1", "range(3, len(argv)): arguments += argv[i] + \" \" return arguments", "current app dir with the contents of the temporary dir/apps/app", "= os.path.join(appsDir, app, \"docker-compose.yml\") appYml = os.path.join(appsDir, app, \"app.yml\") #", "+ '/' + 'app.yml' response = requests.get(url) if response.status_code ==", "{}\".format( os.path.join(nodeRoot, \".env\"), app, commonComposeFile, composeFile, arguments)) def remove_readonly(func, path,", "# The compose generation process updates the registry, so we", "if the app is already installed, don't overwrite it if", "compose = yaml.safe_load(f) registry = os.path.join(appsDir, \"registry.json\") # Load the", "overwrite it if app in alreadyInstalled: continue if os.path.isdir(os.path.join(appsDir, app)):", "\"..\") appsDir = os.path.join(nodeRoot, \"apps\") appSystemDir = os.path.join(nodeRoot, \"app-system\") sourcesList", "not download \" + app) def getUserData(): userData = {}", "thread in threads: thread.join() # The directory with this script", "cloning the entire repo # Dont print anything to stdout,", "{} {}\".format(gitUrl, tempDir), shell=True, stdout=subprocess.DEVNULL) # Overwrite the current app", "joined into a string by spaces def getArguments(): arguments =", "= requests.get(url) if response.status_code == 200: return response.text else: return", "return userData def startInstalled(): # If userfile doen't exist, just", "os.path.dirname(os.path.realpath(__file__)) nodeRoot = os.path.join(scriptDir, \"..\", \"..\") appsDir = os.path.join(nodeRoot, \"apps\")", "+ composeFile) print(\"Generated configuration successfully\") def download(app: str = None):", "if os.path.isfile(userFile): with open(userFile, \"r\") as f: userData = json.load(f)", "loop for i in range(1, 6): os.environ[\"APP_SEED_{}\".format(i)] = deriveEntropy(\"app-{}-seed{}\".format(app, i))", "\"app-{}/hostname\".format(app))), shell=True).decode(\"utf-8\") os.environ[\"APP_SEED\"] = deriveEntropy(\"app-{}-seed\".format(app)) # Allow more app seeds,", "\"app-{}-{}/hostname\".format(app, service)) os.environ[\"APP_HIDDEN_SERVICE_{}\".format(service.upper().replace(\"-\", \"_\"))] = subprocess.check_output(\"cat {} 2>/dev/null || echo", "def getAppYml(name): url = 'https://raw.githubusercontent.com/runcitadel/compose-nonfree/main/apps/' + \\ name + '/'", "in the format # <git-url> <branch> # For every line,", "converted = convertComposeYMLToAppYML(compose, app, registryData) # Put converted into the", "str, appId: str): with open(appFile, 'r') as f: app =", "in userData: userData[\"installedApps\"] = [] userData[\"installedApps\"].append(app) userData[\"installedApps\"] = list(set(userData[\"installedApps\"])) with", "userData: return userData[\"installedApps\"] = list(set(userData[\"installedApps\"])) userData[\"installedApps\"].remove(app) with open(userFile, \"w\") as", "later in the file may not overwrite an app from", "app, 'app.yml') def composeToAppYml(app): composeFile = os.path.join(appsDir, app, \"docker-compose.yml\") appYml", "registry with open(registry, \"r\") as f: registryData = json.load(f) converted", "if verbose: print(\"Wrote \" + app + \" to \"", "--force --stop\")) thread.start() threads.append(thread) joinThreads(threads) # Loads an app.yml and", "userData = json.load(f) return userData def startInstalled(): # If userfile", "'{}' --file '{}' --file '{}' {}\".format( os.path.join(nodeRoot, \".env\"), app, commonComposeFile,", "repos = f.readlines() # For each repo, clone the repo", "\"apps\")): # if the app is already installed, don't overwrite", "of apps from every repo, a repo later in the", "subprocess from lib.composegenerator.v0.generate import createComposeConfigFromV0 from lib.composegenerator.v1.generate import createComposeConfigFromV1 from", "# Runs a compose command in the app dir #", "= getUserData() if not \"installedApps\" in userData: userData[\"installedApps\"] = []", "in repos: repo = repo.strip() if repo == \"\": continue", "\"docker-compose.yml\") commonComposeFile = os.path.join(appSystemDir, \"docker-compose.common.yml\") os.environ[\"APP_DOMAIN\"] = subprocess.check_output( \"hostname -s", "print(\"Warning: Could not download \" + app) else: data =", "argument after the second one in sys.argv joined into a", "6): os.environ[\"APP_SEED_{}\".format(i)] = deriveEntropy(\"app-{}-seed{}\".format(app, i)) os.environ[\"APP_DATA_DIR\"] = os.path.join(appDataDir, app) os.environ[\"BITCOIN_DATA_DIR\"]", "with open(appYml, \"w\") as f: f.write(yaml.dump(converted, sort_keys=False)) def update(verbose: bool", "userData = {} if os.path.isfile(userFile): with open(userFile, \"r\") as f:", "if not os.path.isfile(composeFile): print(\"Error: Could not find docker-compose.yml in \"", "= os.path.join(nodeRoot, \"lnd\") # List all hidden services for an", "for every app, # overwrite the current app dir with", "with open(composeFile, \"w\") as f: appCompose = getApp(appYml, app) if(appCompose):", "with the contents of the temporary dir/apps/app for app in", "--file '{}' {}\".format( os.path.join(nodeRoot, \".env\"), app, commonComposeFile, composeFile, arguments)) def", "app, \"docker-compose.yml\") appYml = os.path.join(appsDir, app, \"app.yml\") # Read the", "app) appDir = os.path.join(appsDir, app) if os.path.isdir(dataDir): deleteData(app) # Recursively", "wait for them to finish def joinThreads(threads: List[threading.Thread]): for thread", "apps.json\") # Loop through the apps and generate valid compose", "in os.listdir(torDir): if subdir.startswith(\"app-{}-\".format(app)): results.append(subdir[len(\"app-{}-\".format(app)):]) return results # Parse the", "os.path.join(nodeRoot, \"scripts\", \"app\") def runCompose(app: str, args: str): compose(app, args)", "of every argument after the second one in sys.argv joined", "= yaml.safe_load(f) registry = os.path.join(appsDir, \"registry.json\") # Load the registry", "apps and generate valid compose files from them, then put", "stat.S_IWRITE) func(path) def deleteData(app: str): dataDir = os.path.join(appDataDir, app) try:", "from lib.metadata import getAppRegistry, getSimpleAppRegistry from lib.entropy import deriveEntropy #", "the app dir for app in apps: composeFile = os.path.join(appsDir,", "= tempfile.mkdtemp() print(\"Cloning the repository\") # Git clone with a", "shell=True).decode(\"utf-8\") + \".local\" os.environ[\"APP_HIDDEN_SERVICE\"] = subprocess.check_output(\"cat {} 2>/dev/null || echo", "os.environ[\"LND_DATA_DIR\"] = os.path.join(nodeRoot, \"lnd\") # List all hidden services for", "appDataDir = os.path.join(nodeRoot, \"app-data\") userFile = os.path.join(nodeRoot, \"db\", \"user.json\") legacyScript", "range(1, 6): os.environ[\"APP_SEED_{}\".format(i)] = deriveEntropy(\"app-{}-seed{}\".format(app, i)) os.environ[\"APP_DATA_DIR\"] = os.path.join(appDataDir, app)", "repo to a temporary dir, checkout the branch, # and", "hidden services for an app and put their hostname in", "the branch repo = repo.split(\" \") if len(repo) != 2:", "= os.path.dirname(os.path.realpath(__file__)) nodeRoot = os.path.join(scriptDir, \"..\", \"..\") appsDir = os.path.join(nodeRoot,", "os.environ[\"APP_HIDDEN_SERVICE\"] = subprocess.check_output(\"cat {} 2>/dev/null || echo 'notyetset.onion'\".format( os.path.join(nodeRoot, \"tor\",", "docker-compose.yml def getApp(appFile: str, appId: str): with open(appFile, 'r') as", "and parse it with open(composeFile, \"r\") as f: compose =", "\" + app) def getUserData(): userData = {} if os.path.isfile(userFile):", "Split the repo into the git url and the branch", "after the second one in sys.argv joined into a string", "_): os.chmod(path, stat.S_IWRITE) func(path) def deleteData(app: str): dataDir = os.path.join(appDataDir,", "<branch> # For every line, clone the repo to a", "import tempfile import threading from typing import List from sys", "a repo earlier in the file def updateRepos(): # Get", "app in alreadyInstalled: continue if os.path.isdir(os.path.join(appsDir, app)): shutil.rmtree(os.path.join(appsDir, app), onerror=remove_readonly)", "app, \"app.yml\") # Read the compose file and parse it", "def getArguments(): arguments = \"\" for i in range(3, len(argv)):", "as YAML with open(appYml, \"w\") as f: f.write(yaml.dump(converted, sort_keys=False)) def", "# overwrite the current app dir with the contents of", "app) try: shutil.rmtree(dataDir, onerror=remove_readonly) except FileNotFoundError: pass def createDataDir(app: str):", "the repo into the git url and the branch repo", "arguments def getAppYml(name): url = 'https://raw.githubusercontent.com/runcitadel/compose-nonfree/main/apps/' + \\ name +", "os.path.join(appsDir, app, \"docker-compose.yml\") appYml = os.path.join(appsDir, app, \"app.yml\") # Read", "app) def getUserData(): userData = {} if os.path.isfile(userFile): with open(userFile,", "for an app and put their hostname in the environment", "alreadyInstalled: continue if os.path.isdir(os.path.join(appsDir, app)): shutil.rmtree(os.path.join(appsDir, app), onerror=remove_readonly) if os.path.isdir(os.path.join(tempDir,", "os.path.join(nodeRoot, \".env\"), app, commonComposeFile, composeFile, arguments)) def remove_readonly(func, path, _):", "converts it to a docker-compose.yml def getApp(appFile: str, appId: str):", "False): apps = findAndValidateApps(appsDir) # The compose generation process updates", "from every repo, a repo later in the file may", "the repo to a temporary dir tempDir = tempfile.mkdtemp() print(\"Cloning", "as we don't want to see the git clone output", "asynchrounously for all apps, then exit(0) when all are finished", "userData = json.load(f) threads = [] for app in userData[\"installedApps\"]:", "have the same owner and permissions as appDir os.chown(dataDir, os.stat(appDir).st_uid,", "to avoid cloning the entire repo # Dont print anything", "for service in hiddenServices: appHiddenServiceFile = os.path.join( nodeRoot, \"tor\", \"data\",", "os.path.join(nodeRoot, \"app-data\") userFile = os.path.join(nodeRoot, \"db\", \"user.json\") legacyScript = os.path.join(nodeRoot,", "startInstalled(): # If userfile doen't exist, just do nothing userData", "# if the app is already installed, don't overwrite it", "not \"installedApps\" in userData: userData[\"installedApps\"] = [] userData[\"installedApps\"].append(app) userData[\"installedApps\"] =", "= os.path.join(nodeRoot, \"bitcoin\") os.environ[\"LND_DATA_DIR\"] = os.path.join(nodeRoot, \"lnd\") # List all", "import getAppRegistry, getSimpleAppRegistry from lib.entropy import deriveEntropy # For an", "\"docker-compose.yml\") appYml = os.path.join(appsDir, app, \"app.yml\") # Read the compose", "# Loads an app.yml and converts it to a docker-compose.yml", "temporary dir/apps and for every app, # overwrite the current", "= convertComposeYMLToAppYML(compose, app, registryData) # Put converted into the app.yml", "from lib.composegenerator.v0.generate import createComposeConfigFromV0 from lib.composegenerator.v1.generate import createComposeConfigFromV1 from lib.appymlgenerator", "the apps and generate valid compose files from them, then", "results = [] for subdir in os.listdir(torDir): if subdir.startswith(\"app-{}-\".format(app)): results.append(subdir[len(\"app-{}-\".format(app)):])", "--project-name '{}' --file '{}' --file '{}' {}\".format( os.path.join(nodeRoot, \".env\"), app,", "# Returns a list of every argument after the second", "appHiddenServiceFile = os.path.join( nodeRoot, \"tor\", \"data\", \"app-{}-{}/hostname\".format(app, service)) os.environ[\"APP_HIDDEN_SERVICE_{}\".format(service.upper().replace(\"-\", \"_\"))]", "clone the repo to a temporary dir, checkout the branch,", "of threads, join them and wait for them to finish", "str): dataDir = os.path.join(appDataDir, app) appDir = os.path.join(appsDir, app) if", "userData[\"installedApps\"].remove(app) with open(userFile, \"w\") as f: json.dump(userData, f) def getAppHiddenServices(app:", "legacyScript = os.path.join(nodeRoot, \"scripts\", \"app\") def runCompose(app: str, args: str):", "registryData) # Put converted into the app.yml after encoding it", "def runCompose(app: str, args: str): compose(app, args) # Returns a", "\\ name + '/' + 'app.yml' response = requests.get(url) if", "app), onerror=remove_readonly) if os.path.isdir(os.path.join(tempDir, \"apps\", app)): shutil.copytree(os.path.join(tempDir, \"apps\", app), os.path.join(appsDir,", "app), symlinks=False, ignore=shutil.ignore_patterns(\".gitignore\")) alreadyInstalled.append(app) # Remove the temporary dir shutil.rmtree(tempDir)", "getUserData() if not \"installedApps\" in userData: return userData[\"installedApps\"] = list(set(userData[\"installedApps\"]))", "runCompose(args.app, \"up --detach\") asynchrounously for all apps, then exit(0) when", "url and the branch repo = repo.split(\" \") if len(repo)", "'{}' --project-name '{}' --file '{}' --file '{}' {}\".format( os.path.join(nodeRoot, \".env\"),", "= os.path.join(appsDir, app, \"app.yml\") # Read the compose file and", "\".local\" os.environ[\"APP_HIDDEN_SERVICE\"] = subprocess.check_output(\"cat {} 2>/dev/null || echo 'notyetset.onion'\".format( os.path.join(nodeRoot,", "f.write(data) else: print(\"Warning: Could not download \" + app) def", "Loop through the apps and generate valid compose files from", "in userData[\"installedApps\"]: print(\"Starting app {}...\".format(app)) # Run runCompose(args.app, \"up --detach\")", "\" + appFile) app[\"metadata\"][\"id\"] = appId if('version' in app and", "deleteData(app: str): dataDir = os.path.join(appDataDir, app) try: shutil.rmtree(dataDir, onerror=remove_readonly) except", "ignore=shutil.ignore_patterns(\".gitignore\")) # Chown and chmod dataDir to have the same", "if repo == \"\": continue # Split the repo into", "the app.yml after encoding it as YAML with open(appYml, \"w\")", "str): with open(appFile, 'r') as f: app = yaml.safe_load(f) if", "if('version' in app and str(app['version']) == \"1\"): return createComposeConfigFromV1(app, nodeRoot)", "a docker-compose.yml exists in the app dir composeFile = os.path.join(appsDir,", "repository\") # Git clone with a depth of 1 to", "appId: str): with open(appFile, 'r') as f: app = yaml.safe_load(f)", "+ 'app.yml' response = requests.get(url) if response.status_code == 200: return", "import requests import shutil import json import yaml import subprocess", "in sys.argv joined into a string by spaces def getArguments():", "assigned in a loop for i in range(1, 6): os.environ[\"APP_SEED_{}\".format(i)]", "= os.path.join(nodeRoot, \"apps\") appSystemDir = os.path.join(nodeRoot, \"app-system\") sourcesList = os.path.join(appSystemDir,", "i in range(3, len(argv)): arguments += argv[i] + \" \"", "the git url and the branch repo = repo.split(\" \")", "checkout the branch # Then, check that repos apps in", "\"w\") as f: json.dump(userData, f) def setRemoved(app: str): userData =", "registry, so we need to get it set up with", "= os.path.join(appsDir, app, \"app.yml\") with open(composeFile, \"w\") as f: appCompose", "the app is already installed, don't overwrite it if app", "SPDX-FileCopyrightText: 2021 <NAME> <<EMAIL>> # # SPDX-License-Identifier: MIT import stat", "def stopInstalled(): # If userfile doen't exist, just do nothing", "os.path.join(appsDir, app, 'app.yml') def composeToAppYml(app): composeFile = os.path.join(appsDir, app, \"docker-compose.yml\")", "= json.load(f) threads = [] for app in userData[\"installedApps\"]: print(\"Stopping", "numbers from 1-5 assigned in a loop for i in", "continue # Split the repo into the git url and", "array of threads, join them and wait for them to", "repos repos = [] with open(sourcesList) as f: repos =", "into the app dir for app in apps: composeFile =", "For an array of threads, join them and wait for", "thread = threading.Thread( target=runCompose, args=(app, \"rm --force --stop\")) thread.start() threads.append(thread)", "all hidden services for an app and put their hostname", "open(userFile, \"w\") as f: json.dump(userData, f) def getAppHiddenServices(app: str): torDir", "the app-${APP}- prefix results = [] for subdir in os.listdir(torDir):", "list(set(userData[\"installedApps\"])) userData[\"installedApps\"].remove(app) with open(userFile, \"w\") as f: json.dump(userData, f) def", "# SPDX-FileCopyrightText: 2021 <NAME> <<EMAIL>> # # SPDX-License-Identifier: MIT import", "str = None): if(app is None): apps = findAndValidateApps(appsDir) for", "for i in range(1, 6): os.environ[\"APP_SEED_{}\".format(i)] = deriveEntropy(\"app-{}-seed{}\".format(app, i)) os.environ[\"APP_DATA_DIR\"]", "stopInstalled(): # If userfile doen't exist, just do nothing userData", "# Also, keep a list of apps from every repo,", "\"app.yml\") # Read the compose file and parse it with", "[] userData[\"installedApps\"].append(app) userData[\"installedApps\"] = list(set(userData[\"installedApps\"])) with open(userFile, \"w\") as f:", "may not overwrite an app from a repo earlier in", "stdout=subprocess.DEVNULL) # Overwrite the current app dir with the contents", "thread.join() # The directory with this script scriptDir = os.path.dirname(os.path.realpath(__file__))", "app) else: data = getAppYml(app) if data: with open(getAppYmlPath(app), 'w')", "contents of the temporary dir/apps/app alreadyInstalled = [] for repo", "+ app) else: data = getAppYml(app) if data: with open(getAppYmlPath(app),", "f.write(data) else: print(\"Warning: Could not download \" + app) else:", "finished thread = threading.Thread(target=runCompose, args=(app, \"up --detach\")) thread.start() threads.append(thread) joinThreads(threads)", "= os.path.join(appDataDir, app) try: shutil.rmtree(dataDir, onerror=remove_readonly) except FileNotFoundError: pass def", "else: print(\"Warning: Could not download \" + app) def getUserData():", "pass def createDataDir(app: str): dataDir = os.path.join(appDataDir, app) appDir =", "f) def setRemoved(app: str): userData = getUserData() if not \"installedApps\"", "temporary dir/apps/app alreadyInstalled = [] for repo in repos: repo", "compose command in the app dir # Before that, check", "repo[0] branch = repo[1] # Clone the repo to a", "not \"metadata\" in app: raise Exception(\"Error: Could not find metadata", "in range(3, len(argv)): arguments += argv[i] + \" \" return", "return userData[\"installedApps\"] = list(set(userData[\"installedApps\"])) userData[\"installedApps\"].remove(app) with open(userFile, \"w\") as f:", "open(appYml, \"w\") as f: f.write(yaml.dump(converted, sort_keys=False)) def update(verbose: bool =", "from them, then put these into the app dir for", "2>/dev/null || echo 'umbrel'\", shell=True).decode(\"utf-8\") + \".local\" os.environ[\"APP_HIDDEN_SERVICE\"] = subprocess.check_output(\"cat", "in hiddenServices: appHiddenServiceFile = os.path.join( nodeRoot, \"tor\", \"data\", \"app-{}-{}/hostname\".format(app, service))", "str): dataDir = os.path.join(appDataDir, app) try: shutil.rmtree(dataDir, onerror=remove_readonly) except FileNotFoundError:", "the contents of the temporary dir/apps/app alreadyInstalled = [] for", "args) # Returns a list of every argument after the", "f: registryData = json.load(f) converted = convertComposeYMLToAppYML(compose, app, registryData) #", "all are finished thread = threading.Thread(target=runCompose, args=(app, \"up --detach\")) thread.start()", "bool = False): apps = findAndValidateApps(appsDir) # The compose generation", "find docker-compose.yml in \" + app) exit(1) os.system( \"docker compose", "it if app in alreadyInstalled: continue if os.path.isdir(os.path.join(appsDir, app)): shutil.rmtree(os.path.join(appsDir,", "app.yml after encoding it as YAML with open(appYml, \"w\") as", "== \"1\"): return createComposeConfigFromV1(app, nodeRoot) else: return createComposeConfigFromV0(app) def compose(app,", "os.path.join(appsDir, app, \"app.yml\") # Read the compose file and parse", "open(userFile, \"r\") as f: userData = json.load(f) return userData def", "commonComposeFile, composeFile, arguments)) def remove_readonly(func, path, _): os.chmod(path, stat.S_IWRITE) func(path)", "createComposeConfigFromV1 from lib.appymlgenerator import convertComposeYMLToAppYML from lib.validate import findAndValidateApps from", "from lib.entropy import deriveEntropy # For an array of threads,", "every line, clone the repo to a temporary dir and", "successfully\") def download(app: str = None): if(app is None): apps", "dir/apps/app for app in os.listdir(os.path.join(tempDir, \"apps\")): # if the app", "download(app: str = None): if(app is None): apps = findAndValidateApps(appsDir)", "and converts it to a docker-compose.yml def getApp(appFile: str, appId:", "as f: f.write(data) else: print(\"Warning: Could not download \" +", "shell=True).decode(\"utf-8\") os.environ[\"APP_SEED\"] = deriveEntropy(\"app-{}-seed\".format(app)) # Allow more app seeds, with", "sourcesList) exit(1) gitUrl = repo[0] branch = repo[1] # Clone", "= yaml.safe_load(f) if not \"metadata\" in app: raise Exception(\"Error: Could", "a temporary dir, checkout the branch, # and overwrite the", "len(repo) != 2: print(\"Error: Invalid repo format in \" +", "= [] for app in userData[\"installedApps\"]: print(\"Starting app {}...\".format(app)) #", "if data: with open(getAppYmlPath(app), 'w') as f: f.write(data) else: print(\"Warning:", "= os.path.join(nodeRoot, \"app-data\") userFile = os.path.join(nodeRoot, \"db\", \"user.json\") legacyScript =", "if a docker-compose.yml exists in the app dir composeFile =", "an app.yml and converts it to a docker-compose.yml def getApp(appFile:", "sort_keys=True) print(\"Wrote registry to registry.json\") simpleRegistry = getSimpleAppRegistry(apps, appsDir) with", "1 to avoid cloning the entire repo # Dont print", "of 1 to avoid cloning the entire repo # Dont", "the repo to a temporary dir, checkout the branch, #", "2021 <NAME> <<EMAIL>> # # SPDX-License-Identifier: MIT import stat import", "requests.get(url) if response.status_code == 200: return response.text else: return False", "else: return False def getAppYmlPath(app): return os.path.join(appsDir, app, 'app.yml') def", "repo # Dont print anything to stdout, as we don't", "as f: userData = json.load(f) return userData def startInstalled(): #", "+ app) exit(1) os.system( \"docker compose --env-file '{}' --project-name '{}'", "tempDir), shell=True, stdout=subprocess.DEVNULL) # Overwrite the current app dir with", "finished thread = threading.Thread( target=runCompose, args=(app, \"rm --force --stop\")) thread.start()", "= 'https://raw.githubusercontent.com/runcitadel/compose-nonfree/main/apps/' + \\ name + '/' + 'app.yml' response", "in \" + appFile) app[\"metadata\"][\"id\"] = appId if('version' in app", "repo in repos: repo = repo.strip() if repo == \"\":", "the list of repos repos = [] with open(sourcesList) as", "\"data\", \"app-{}/hostname\".format(app))), shell=True).decode(\"utf-8\") os.environ[\"APP_SEED\"] = deriveEntropy(\"app-{}-seed\".format(app)) # Allow more app", "def update(verbose: bool = False): apps = findAndValidateApps(appsDir) # The", "subprocess.check_output(\"cat {} 2>/dev/null || echo 'notyetset.onion'\".format( os.path.join(nodeRoot, \"tor\", \"data\", \"app-{}/hostname\".format(app))),", "temporary dir/apps/app # Also, keep a list of apps from", "app dir composeFile = os.path.join(appsDir, app, \"docker-compose.yml\") commonComposeFile = os.path.join(appSystemDir,", "for repo in repos: repo = repo.strip() if repo ==", "we need to get it set up with the basics", "userData[\"installedApps\"].append(app) userData[\"installedApps\"] = list(set(userData[\"installedApps\"])) with open(userFile, \"w\") as f: json.dump(userData,", "\"tor\", \"data\", \"app-{}/hostname\".format(app))), shell=True).decode(\"utf-8\") os.environ[\"APP_SEED\"] = deriveEntropy(\"app-{}-seed\".format(app)) # Allow more", "dataDir, symlinks=False, ignore=shutil.ignore_patterns(\".gitignore\")) # Chown and chmod dataDir to have", "print(\"Warning: Could not download \" + app) def getUserData(): userData", "repo format in \" + sourcesList) exit(1) gitUrl = repo[0]", "that registry = getAppRegistry(apps, appsDir) with open(os.path.join(appsDir, \"registry.json\"), \"w\") as", "--file '{}' --file '{}' {}\".format( os.path.join(nodeRoot, \".env\"), app, commonComposeFile, composeFile,", "+ \" to \" + composeFile) print(\"Generated configuration successfully\") def", "def setRemoved(app: str): userData = getUserData() if not \"installedApps\" in", "to a docker-compose.yml def getApp(appFile: str, appId: str): with open(appFile,", "os.path.join(nodeRoot, \"tor\", \"data\", \"app-{}/hostname\".format(app))), shell=True).decode(\"utf-8\") os.environ[\"APP_SEED\"] = deriveEntropy(\"app-{}-seed\".format(app)) # Allow", "Recursively copy everything from appDir to dataDir while excluding .gitignore", "\") if len(repo) != 2: print(\"Error: Invalid repo format in", "app), os.path.join(appsDir, app), symlinks=False, ignore=shutil.ignore_patterns(\".gitignore\")) alreadyInstalled.append(app) # Remove the temporary", "response = requests.get(url) if response.status_code == 200: return response.text else:", "List[str] = getAppHiddenServices(app) for service in hiddenServices: appHiddenServiceFile = os.path.join(", "check that repos apps in the temporary dir/apps and for", "the temporary dir/apps/app alreadyInstalled = [] for repo in repos:", "json.load(f) threads = [] for app in userData[\"installedApps\"]: print(\"Stopping app", "data: with open(getAppYmlPath(app), 'w') as f: f.write(data) else: print(\"Warning: Could", "format # <git-url> <branch> # For every line, clone the", "!= 2: print(\"Error: Invalid repo format in \" + sourcesList)", "+ \\ name + '/' + 'app.yml' response = requests.get(url)", "app in os.listdir(os.path.join(tempDir, \"apps\")): # if the app is already", "exit(1) os.system( \"docker compose --env-file '{}' --project-name '{}' --file '{}'", "f: json.dump(userData, f) def setRemoved(app: str): userData = getUserData() if", "see the git clone output subprocess.run(\"git clone --depth 1 {}", "repo.strip() if repo == \"\": continue # Split the repo", "Before that, check if a docker-compose.yml exists in the app", "= [] userData[\"installedApps\"].append(app) userData[\"installedApps\"] = list(set(userData[\"installedApps\"])) with open(userFile, \"w\") as", "userData = getUserData() if not \"installedApps\" in userData: return userData[\"installedApps\"]", "thread.start() threads.append(thread) joinThreads(threads) def stopInstalled(): # If userfile doen't exist,", "arguments): # Runs a compose command in the app dir", "joinThreads(threads) # Loads an app.yml and converts it to a", "if subdir.startswith(\"app-{}-\".format(app)): results.append(subdir[len(\"app-{}-\".format(app)):]) return results # Parse the sources.list repo", "except FileNotFoundError: pass def createDataDir(app: str): dataDir = os.path.join(appDataDir, app)", "#!/usr/bin/env python3 # SPDX-FileCopyrightText: 2021 <NAME> <<EMAIL>> # # SPDX-License-Identifier:", "of torDir which start with app-${APP}- # but return them", "app from a repo earlier in the file def updateRepos():", "def joinThreads(threads: List[threading.Thread]): for thread in threads: thread.join() # The", "# For each repo, clone the repo to a temporary", "import subprocess from lib.composegenerator.v0.generate import createComposeConfigFromV0 from lib.composegenerator.v1.generate import createComposeConfigFromV1", "os.path.join(appDataDir, app) appDir = os.path.join(appsDir, app) if os.path.isdir(dataDir): deleteData(app) #", "and the branch repo = repo.split(\" \") if len(repo) !=", "joinThreads(threads: List[threading.Thread]): for thread in threads: thread.join() # The directory", "appsDir = os.path.join(nodeRoot, \"apps\") appSystemDir = os.path.join(nodeRoot, \"app-system\") sourcesList =", "\"r\") as f: userData = json.load(f) return userData def startInstalled():", "to have the same owner and permissions as appDir os.chown(dataDir,", "thread.start() threads.append(thread) joinThreads(threads) # Loads an app.yml and converts it", "print(\"Starting app {}...\".format(app)) # Run runCompose(args.app, \"up --detach\") asynchrounously for", "not \"installedApps\" in userData: return userData[\"installedApps\"] = list(set(userData[\"installedApps\"])) userData[\"installedApps\"].remove(app) with", "Parse the sources.list repo file, which contains a list of", "the file may not overwrite an app from a repo", "findAndValidateApps(appsDir) # The compose generation process updates the registry, so", "setInstalled(app: str): userData = getUserData() if not \"installedApps\" in userData:", "each repo, clone the repo to a temporary dir, checkout", "compose file and parse it with open(composeFile, \"r\") as f:", "the temporary dir/apps/app # Also, keep a list of apps", "open(composeFile, \"r\") as f: compose = yaml.safe_load(f) registry = os.path.join(appsDir,", "getUserData(): userData = {} if os.path.isfile(userFile): with open(userFile, \"r\") as", "app, registryData) # Put converted into the app.yml after encoding", "userfile doen't exist, just do nothing userData = {} if", "import createComposeConfigFromV1 from lib.appymlgenerator import convertComposeYMLToAppYML from lib.validate import findAndValidateApps", "as f: f.write(yaml.dump(converted, sort_keys=False)) def update(verbose: bool = False): apps", "f: appCompose = getApp(appYml, app) if(appCompose): f.write(yaml.dump(appCompose, sort_keys=False)) if verbose:", "app.yml and converts it to a docker-compose.yml def getApp(appFile: str,", "'umbrel'\", shell=True).decode(\"utf-8\") + \".local\" os.environ[\"APP_HIDDEN_SERVICE\"] = subprocess.check_output(\"cat {} 2>/dev/null ||", "app seeds, with random numbers from 1-5 assigned in a", "composeFile) print(\"Generated configuration successfully\") def download(app: str = None): if(app", "arguments)) def remove_readonly(func, path, _): os.chmod(path, stat.S_IWRITE) func(path) def deleteData(app:", "into the git url and the branch repo = repo.split(\"", "branch = repo[1] # Clone the repo to a temporary", "f.write(yaml.dump(converted, sort_keys=False)) def update(verbose: bool = False): apps = findAndValidateApps(appsDir)", "sources.list repo file, which contains a list of sources in", "and str(app['version']) == \"1\"): return createComposeConfigFromV1(app, nodeRoot) else: return createComposeConfigFromV0(app)", "# For every line, clone the repo to a temporary", "For each repo, clone the repo to a temporary dir,", "+ \".local\" os.environ[\"APP_HIDDEN_SERVICE\"] = subprocess.check_output(\"cat {} 2>/dev/null || echo 'notyetset.onion'\".format(", "getSimpleAppRegistry(apps, appsDir) with open(os.path.join(appSystemDir, \"apps.json\"), \"w\") as f: json.dump(simpleRegistry, f,", "with open(appFile, 'r') as f: app = yaml.safe_load(f) if not", "def createDataDir(app: str): dataDir = os.path.join(appDataDir, app) appDir = os.path.join(appsDir,", "--detach\")) thread.start() threads.append(thread) joinThreads(threads) def stopInstalled(): # If userfile doen't", "os.path.join(appDataDir, app) os.environ[\"BITCOIN_DATA_DIR\"] = os.path.join(nodeRoot, \"bitcoin\") os.environ[\"LND_DATA_DIR\"] = os.path.join(nodeRoot, \"lnd\")", "temporary dir tempDir = tempfile.mkdtemp() print(\"Cloning the repository\") # Git", "and chmod dataDir to have the same owner and permissions", "# Then, check that repos apps in the temporary dir/apps", "= os.path.join(scriptDir, \"..\", \"..\") appsDir = os.path.join(nodeRoot, \"apps\") appSystemDir =", "and permissions as appDir os.chown(dataDir, os.stat(appDir).st_uid, os.stat(appDir).st_gid) os.chmod(dataDir, os.stat(appDir).st_mode) def", "the contents of the temporary dir/apps/app # Also, keep a", "\"app-data\") userFile = os.path.join(nodeRoot, \"db\", \"user.json\") legacyScript = os.path.join(nodeRoot, \"scripts\",", "args=(app, \"up --detach\")) thread.start() threads.append(thread) joinThreads(threads) def stopInstalled(): # If", "dir/apps and for every app, # overwrite the current app", "str): torDir = os.path.join(nodeRoot, \"tor\", \"data\") # List all subdirectories", "find metadata in \" + appFile) app[\"metadata\"][\"id\"] = appId if('version'", "dir with the contents of the temporary dir/apps/app alreadyInstalled =", "installed, don't overwrite it if app in alreadyInstalled: continue if", "of the temporary dir/apps/app alreadyInstalled = [] for repo in", "app)): shutil.rmtree(os.path.join(appsDir, app), onerror=remove_readonly) if os.path.isdir(os.path.join(tempDir, \"apps\", app)): shutil.copytree(os.path.join(tempDir, \"apps\",", "every app, # overwrite the current app dir with the", "1 {} {}\".format(gitUrl, tempDir), shell=True, stdout=subprocess.DEVNULL) # Overwrite the current", "+ app) def getUserData(): userData = {} if os.path.isfile(userFile): with", "def setInstalled(app: str): userData = getUserData() if not \"installedApps\" in", "f: json.dump(registry, f, indent=4, sort_keys=True) print(\"Wrote registry to registry.json\") simpleRegistry", "the git clone output subprocess.run(\"git clone --depth 1 {} {}\".format(gitUrl,", "apps from every repo, a repo later in the file", "Returns a list of every argument after the second one", "want to see the git clone output subprocess.run(\"git clone --depth", ".gitignore shutil.copytree(appDir, dataDir, symlinks=False, ignore=shutil.ignore_patterns(\".gitignore\")) # Chown and chmod dataDir", "nodeRoot, \"tor\", \"data\", \"app-{}-{}/hostname\".format(app, service)) os.environ[\"APP_HIDDEN_SERVICE_{}\".format(service.upper().replace(\"-\", \"_\"))] = subprocess.check_output(\"cat {}", "print(\"Error: Invalid repo format in \" + sourcesList) exit(1) gitUrl", "'w') as f: f.write(data) else: print(\"Warning: Could not download \"", "= [] for subdir in os.listdir(torDir): if subdir.startswith(\"app-{}-\".format(app)): results.append(subdir[len(\"app-{}-\".format(app)):]) return", "print(\"Error: Could not find docker-compose.yml in \" + app) exit(1)", "= list(set(userData[\"installedApps\"])) with open(userFile, \"w\") as f: json.dump(userData, f) def", "\" + app) else: data = getAppYml(app) if data: with", "the current app dir with the contents of the temporary", "\"app-system\") sourcesList = os.path.join(appSystemDir, \"sources.list\") appDataDir = os.path.join(nodeRoot, \"app-data\") userFile", "app-${APP}- # but return them without the app-${APP}- prefix results", "str, args: str): compose(app, args) # Returns a list of", "\"apps\", app), os.path.join(appsDir, app), symlinks=False, ignore=shutil.ignore_patterns(\".gitignore\")) alreadyInstalled.append(app) # Remove the", "the temporary dir/apps/app for app in os.listdir(os.path.join(tempDir, \"apps\")): # if", "= [] for repo in repos: repo = repo.strip() if", "if os.path.isdir(os.path.join(appsDir, app)): shutil.rmtree(os.path.join(appsDir, app), onerror=remove_readonly) if os.path.isdir(os.path.join(tempDir, \"apps\", app)):", "hiddenServices: appHiddenServiceFile = os.path.join( nodeRoot, \"tor\", \"data\", \"app-{}-{}/hostname\".format(app, service)) os.environ[\"APP_HIDDEN_SERVICE_{}\".format(service.upper().replace(\"-\",", "def compose(app, arguments): # Runs a compose command in the", "docker-compose.yml exists in the app dir composeFile = os.path.join(appsDir, app,", "command in the app dir # Before that, check if", "into a string by spaces def getArguments(): arguments = \"\"", "\"apps\") appSystemDir = os.path.join(nodeRoot, \"app-system\") sourcesList = os.path.join(appSystemDir, \"sources.list\") appDataDir", "appsDir) with open(os.path.join(appsDir, \"registry.json\"), \"w\") as f: json.dump(registry, f, indent=4,", "import shutil import json import yaml import subprocess from lib.composegenerator.v0.generate", "None): if(app is None): apps = findAndValidateApps(appsDir) for app in", "app and put their hostname in the environment hiddenServices: List[str]", "<<EMAIL>> # # SPDX-License-Identifier: MIT import stat import tempfile import", "results.append(subdir[len(\"app-{}-\".format(app)):]) return results # Parse the sources.list repo file, which", "app)): shutil.copytree(os.path.join(tempDir, \"apps\", app), os.path.join(appsDir, app), symlinks=False, ignore=shutil.ignore_patterns(\".gitignore\")) alreadyInstalled.append(app) #", "Clone the repo to a temporary dir tempDir = tempfile.mkdtemp()", "appDir to dataDir while excluding .gitignore shutil.copytree(appDir, dataDir, symlinks=False, ignore=shutil.ignore_patterns(\".gitignore\"))", "it as YAML with open(appYml, \"w\") as f: f.write(yaml.dump(converted, sort_keys=False))", "appId if('version' in app and str(app['version']) == \"1\"): return createComposeConfigFromV1(app,", "json.load(f) threads = [] for app in userData[\"installedApps\"]: print(\"Starting app", "<git-url> <branch> # For every line, clone the repo to", "converted into the app.yml after encoding it as YAML with", "environment hiddenServices: List[str] = getAppHiddenServices(app) for service in hiddenServices: appHiddenServiceFile", "and for every app, # overwrite the current app dir", "List[threading.Thread]): for thread in threads: thread.join() # The directory with", "userData[\"installedApps\"] = [] userData[\"installedApps\"].append(app) userData[\"installedApps\"] = list(set(userData[\"installedApps\"])) with open(userFile, \"w\")", "app in userData[\"installedApps\"]: print(\"Stopping app {}...\".format(app)) # Run runCompose(args.app, \"up", "import yaml import subprocess from lib.composegenerator.v0.generate import createComposeConfigFromV0 from lib.composegenerator.v1.generate", "\" + composeFile) print(\"Generated configuration successfully\") def download(app: str =", "compose(app, args) # Returns a list of every argument after", "json.load(f) converted = convertComposeYMLToAppYML(compose, app, registryData) # Put converted into", "the app dir composeFile = os.path.join(appsDir, app, \"docker-compose.yml\") commonComposeFile =", "i in range(1, 6): os.environ[\"APP_SEED_{}\".format(i)] = deriveEntropy(\"app-{}-seed{}\".format(app, i)) os.environ[\"APP_DATA_DIR\"] =", "the environment hiddenServices: List[str] = getAppHiddenServices(app) for service in hiddenServices:", "= getUserData() if not \"installedApps\" in userData: return userData[\"installedApps\"] =", "= os.path.join(appsDir, app, \"docker-compose.yml\") commonComposeFile = os.path.join(appSystemDir, \"docker-compose.common.yml\") os.environ[\"APP_DOMAIN\"] =", "onerror=remove_readonly) if os.path.isdir(os.path.join(tempDir, \"apps\", app)): shutil.copytree(os.path.join(tempDir, \"apps\", app), os.path.join(appsDir, app),", "= list(set(userData[\"installedApps\"])) userData[\"installedApps\"].remove(app) with open(userFile, \"w\") as f: json.dump(userData, f)", "repo to a temporary dir tempDir = tempfile.mkdtemp() print(\"Cloning the", "shutil.rmtree(os.path.join(appsDir, app), onerror=remove_readonly) if os.path.isdir(os.path.join(tempDir, \"apps\", app)): shutil.copytree(os.path.join(tempDir, \"apps\", app),", "it set up with the basics before that registry =", "return results # Parse the sources.list repo file, which contains", "f) def getAppHiddenServices(app: str): torDir = os.path.join(nodeRoot, \"tor\", \"data\") #", "from sys import argv import os import requests import shutil", "'app.yml' response = requests.get(url) if response.status_code == 200: return response.text", "as f: json.dump(simpleRegistry, f, indent=4, sort_keys=True) print(\"Wrote version information to", "open(os.path.join(appsDir, \"registry.json\"), \"w\") as f: json.dump(registry, f, indent=4, sort_keys=True) print(\"Wrote", "threads, join them and wait for them to finish def", "'https://raw.githubusercontent.com/runcitadel/compose-nonfree/main/apps/' + \\ name + '/' + 'app.yml' response =", "with random numbers from 1-5 assigned in a loop for", "second one in sys.argv joined into a string by spaces", "getAppRegistry(apps, appsDir) with open(os.path.join(appsDir, \"registry.json\"), \"w\") as f: json.dump(registry, f,", "= deriveEntropy(\"app-{}-seed{}\".format(app, i)) os.environ[\"APP_DATA_DIR\"] = os.path.join(appDataDir, app) os.environ[\"BITCOIN_DATA_DIR\"] = os.path.join(nodeRoot,", "# The directory with this script scriptDir = os.path.dirname(os.path.realpath(__file__)) nodeRoot", "subprocess.check_output(\"cat {} 2>/dev/null || echo 'notyetset.onion'\".format( appHiddenServiceFile), shell=True).decode(\"utf-8\") if not", "# Split the repo into the git url and the", "json.load(f) return userData def startInstalled(): # If userfile doen't exist,", "format in \" + sourcesList) exit(1) gitUrl = repo[0] branch", "repo.split(\" \") if len(repo) != 2: print(\"Error: Invalid repo format", "List all subdirectories of torDir which start with app-${APP}- #", "return createComposeConfigFromV1(app, nodeRoot) else: return createComposeConfigFromV0(app) def compose(app, arguments): #", "tempfile import threading from typing import List from sys import", "the repository\") # Git clone with a depth of 1", "# Dont print anything to stdout, as we don't want", "branch, # and overwrite the current app dir with the", "sources in the format # <git-url> <branch> # For every", "the app dir # Before that, check if a docker-compose.yml", "createComposeConfigFromV0 from lib.composegenerator.v1.generate import createComposeConfigFromV1 from lib.appymlgenerator import convertComposeYMLToAppYML from", "requests import shutil import json import yaml import subprocess from", "as f: app = yaml.safe_load(f) if not \"metadata\" in app:", "1-5 assigned in a loop for i in range(1, 6):", "None): apps = findAndValidateApps(appsDir) for app in apps: data =", "shutil import json import yaml import subprocess from lib.composegenerator.v0.generate import", "nothing userData = {} if os.path.isfile(userFile): with open(userFile, \"r\") as", "\"installedApps\" in userData: userData[\"installedApps\"] = [] userData[\"installedApps\"].append(app) userData[\"installedApps\"] = list(set(userData[\"installedApps\"]))", "an app and put their hostname in the environment hiddenServices:", "apps = findAndValidateApps(appsDir) # The compose generation process updates the", "git url and the branch repo = repo.split(\" \") if", "\"w\") as f: json.dump(simpleRegistry, f, indent=4, sort_keys=True) print(\"Wrote version information", "commonComposeFile = os.path.join(appSystemDir, \"docker-compose.common.yml\") os.environ[\"APP_DOMAIN\"] = subprocess.check_output( \"hostname -s 2>/dev/null", "app in apps: data = getAppYml(app) if data: with open(getAppYmlPath(app),", "joinThreads(threads) def stopInstalled(): # If userfile doen't exist, just do", "in the environment hiddenServices: List[str] = getAppHiddenServices(app) for service in", "= findAndValidateApps(appsDir) for app in apps: data = getAppYml(app) if", "excluding .gitignore shutil.copytree(appDir, dataDir, symlinks=False, ignore=shutil.ignore_patterns(\".gitignore\")) # Chown and chmod", "os.path.join(appsDir, app, \"docker-compose.yml\") commonComposeFile = os.path.join(appSystemDir, \"docker-compose.common.yml\") os.environ[\"APP_DOMAIN\"] = subprocess.check_output(", "\"tor\", \"data\", \"app-{}-{}/hostname\".format(app, service)) os.environ[\"APP_HIDDEN_SERVICE_{}\".format(service.upper().replace(\"-\", \"_\"))] = subprocess.check_output(\"cat {} 2>/dev/null", "repo, a repo later in the file may not overwrite", "dataDir while excluding .gitignore shutil.copytree(appDir, dataDir, symlinks=False, ignore=shutil.ignore_patterns(\".gitignore\")) # Chown", "python3 # SPDX-FileCopyrightText: 2021 <NAME> <<EMAIL>> # # SPDX-License-Identifier: MIT", "open(getAppYmlPath(app), 'w') as f: f.write(data) else: print(\"Warning: Could not download", "as f: registryData = json.load(f) converted = convertComposeYMLToAppYML(compose, app, registryData)", "\"metadata\" in app: raise Exception(\"Error: Could not find metadata in", "an app from a repo earlier in the file def", "arguments += argv[i] + \" \" return arguments def getAppYml(name):", "f.readlines() # For each repo, clone the repo to a", "up with the basics before that registry = getAppRegistry(apps, appsDir)", "apps: data = getAppYml(app) if data: with open(getAppYmlPath(app), 'w') as", "if not \"installedApps\" in userData: return userData[\"installedApps\"] = list(set(userData[\"installedApps\"])) userData[\"installedApps\"].remove(app)", "updateRepos(): # Get the list of repos repos = []", "else: data = getAppYml(app) if data: with open(getAppYmlPath(app), 'w') as", "createComposeConfigFromV0(app) def compose(app, arguments): # Runs a compose command in", "app) exit(1) os.system( \"docker compose --env-file '{}' --project-name '{}' --file", "= os.path.join(nodeRoot, \"tor\", \"data\") # List all subdirectories of torDir", "# but return them without the app-${APP}- prefix results =", "with open(sourcesList) as f: repos = f.readlines() # For each", "them without the app-${APP}- prefix results = [] for subdir", "\"apps\", app)): shutil.copytree(os.path.join(tempDir, \"apps\", app), os.path.join(appsDir, app), symlinks=False, ignore=shutil.ignore_patterns(\".gitignore\")) alreadyInstalled.append(app)", "indent=4, sort_keys=True) print(\"Wrote registry to registry.json\") simpleRegistry = getSimpleAppRegistry(apps, appsDir)", "f.write(yaml.dump(appCompose, sort_keys=False)) if verbose: print(\"Wrote \" + app + \"", "repo earlier in the file def updateRepos(): # Get the", "compose files from them, then put these into the app", "of the temporary dir/apps/app # Also, keep a list of", "= os.path.join(appsDir, \"registry.json\") # Load the registry with open(registry, \"r\")", "Dont print anything to stdout, as we don't want to", "yaml import subprocess from lib.composegenerator.v0.generate import createComposeConfigFromV0 from lib.composegenerator.v1.generate import", "List all hidden services for an app and put their", "= os.path.join(appsDir, app, \"docker-compose.yml\") appYml = os.path.join(appsDir, app, \"app.yml\") with", "Get the list of repos repos = [] with open(sourcesList)", "alreadyInstalled = [] for repo in repos: repo = repo.strip()", "nodeRoot = os.path.join(scriptDir, \"..\", \"..\") appsDir = os.path.join(nodeRoot, \"apps\") appSystemDir", "os.path.join(nodeRoot, \"bitcoin\") os.environ[\"LND_DATA_DIR\"] = os.path.join(nodeRoot, \"lnd\") # List all hidden", "apps = findAndValidateApps(appsDir) for app in apps: data = getAppYml(app)", "userData[\"installedApps\"] = list(set(userData[\"installedApps\"])) userData[\"installedApps\"].remove(app) with open(userFile, \"w\") as f: json.dump(userData,", "str): userData = getUserData() if not \"installedApps\" in userData: return", "\"bitcoin\") os.environ[\"LND_DATA_DIR\"] = os.path.join(nodeRoot, \"lnd\") # List all hidden services", "permissions as appDir os.chown(dataDir, os.stat(appDir).st_uid, os.stat(appDir).st_gid) os.chmod(dataDir, os.stat(appDir).st_mode) def setInstalled(app:", "as f: json.dump(userData, f) def getAppHiddenServices(app: str): torDir = os.path.join(nodeRoot,", "already installed, don't overwrite it if app in alreadyInstalled: continue", "yaml.safe_load(f) if not \"metadata\" in app: raise Exception(\"Error: Could not", "simpleRegistry = getSimpleAppRegistry(apps, appsDir) with open(os.path.join(appSystemDir, \"apps.json\"), \"w\") as f:", "from a repo earlier in the file def updateRepos(): #", "import List from sys import argv import os import requests", "in \" + app) exit(1) os.system( \"docker compose --env-file '{}'", "os.path.join(appDataDir, app) try: shutil.rmtree(dataDir, onerror=remove_readonly) except FileNotFoundError: pass def createDataDir(app:", "getSimpleAppRegistry from lib.entropy import deriveEntropy # For an array of", "list of every argument after the second one in sys.argv", "\"app\") def runCompose(app: str, args: str): compose(app, args) # Returns", "encoding it as YAML with open(appYml, \"w\") as f: f.write(yaml.dump(converted,", "scriptDir = os.path.dirname(os.path.realpath(__file__)) nodeRoot = os.path.join(scriptDir, \"..\", \"..\") appsDir =", "os.environ[\"APP_SEED_{}\".format(i)] = deriveEntropy(\"app-{}-seed{}\".format(app, i)) os.environ[\"APP_DATA_DIR\"] = os.path.join(appDataDir, app) os.environ[\"BITCOIN_DATA_DIR\"] =", "2: print(\"Error: Invalid repo format in \" + sourcesList) exit(1)", "all subdirectories of torDir which start with app-${APP}- # but", "2>/dev/null || echo 'notyetset.onion'\".format( os.path.join(nodeRoot, \"tor\", \"data\", \"app-{}/hostname\".format(app))), shell=True).decode(\"utf-8\") os.environ[\"APP_SEED\"]", "shell=True).decode(\"utf-8\") if not os.path.isfile(composeFile): print(\"Error: Could not find docker-compose.yml in", "'{}' --file '{}' {}\".format( os.path.join(nodeRoot, \".env\"), app, commonComposeFile, composeFile, arguments))", "os.path.join(nodeRoot, \"apps\") appSystemDir = os.path.join(nodeRoot, \"app-system\") sourcesList = os.path.join(appSystemDir, \"sources.list\")", "\"user.json\") legacyScript = os.path.join(nodeRoot, \"scripts\", \"app\") def runCompose(app: str, args:", "in range(1, 6): os.environ[\"APP_SEED_{}\".format(i)] = deriveEntropy(\"app-{}-seed{}\".format(app, i)) os.environ[\"APP_DATA_DIR\"] = os.path.join(appDataDir,", "app, commonComposeFile, composeFile, arguments)) def remove_readonly(func, path, _): os.chmod(path, stat.S_IWRITE)", "a list of apps from every repo, a repo later", "with the contents of the temporary dir/apps/app alreadyInstalled = []", "app dir for app in apps: composeFile = os.path.join(appsDir, app,", "\"\": continue # Split the repo into the git url", "--depth 1 {} {}\".format(gitUrl, tempDir), shell=True, stdout=subprocess.DEVNULL) # Overwrite the", "= getAppYml(app) if data: with open(getAppYmlPath(app), 'w') as f: f.write(data)", "threads.append(thread) joinThreads(threads) # Loads an app.yml and converts it to", "open(sourcesList) as f: repos = f.readlines() # For each repo,", "the registry with open(registry, \"r\") as f: registryData = json.load(f)", "\"tor\", \"data\") # List all subdirectories of torDir which start", "# List all subdirectories of torDir which start with app-${APP}-", "if not \"installedApps\" in userData: userData[\"installedApps\"] = [] userData[\"installedApps\"].append(app) userData[\"installedApps\"]", "when all are finished thread = threading.Thread( target=runCompose, args=(app, \"rm", "getApp(appYml, app) if(appCompose): f.write(yaml.dump(appCompose, sort_keys=False)) if verbose: print(\"Wrote \" +", "= {} if os.path.isfile(userFile): with open(userFile, \"r\") as f: userData", "return False def getAppYmlPath(app): return os.path.join(appsDir, app, 'app.yml') def composeToAppYml(app):", "with a depth of 1 to avoid cloning the entire", "= subprocess.check_output( \"hostname -s 2>/dev/null || echo 'umbrel'\", shell=True).decode(\"utf-8\") +", "and checkout the branch # Then, check that repos apps", "getUserData() if not \"installedApps\" in userData: userData[\"installedApps\"] = [] userData[\"installedApps\"].append(app)", "subdirectories of torDir which start with app-${APP}- # but return", "we don't want to see the git clone output subprocess.run(\"git", "do nothing userData = {} if os.path.isfile(userFile): with open(userFile, \"r\")", "userData[\"installedApps\"] = list(set(userData[\"installedApps\"])) with open(userFile, \"w\") as f: json.dump(userData, f)", "directory with this script scriptDir = os.path.dirname(os.path.realpath(__file__)) nodeRoot = os.path.join(scriptDir,", "open(composeFile, \"w\") as f: appCompose = getApp(appYml, app) if(appCompose): f.write(yaml.dump(appCompose,", "os.path.join(appsDir, \"registry.json\") # Load the registry with open(registry, \"r\") as", "indent=4, sort_keys=True) print(\"Wrote version information to apps.json\") # Loop through", "app {}...\".format(app)) # Run runCompose(args.app, \"up --detach\") asynchrounously for all", "composeFile, arguments)) def remove_readonly(func, path, _): os.chmod(path, stat.S_IWRITE) func(path) def", "lib.metadata import getAppRegistry, getSimpleAppRegistry from lib.entropy import deriveEntropy # For", "the compose file and parse it with open(composeFile, \"r\") as", "hiddenServices: List[str] = getAppHiddenServices(app) for service in hiddenServices: appHiddenServiceFile =", "shutil.rmtree(dataDir, onerror=remove_readonly) except FileNotFoundError: pass def createDataDir(app: str): dataDir =", "# # SPDX-License-Identifier: MIT import stat import tempfile import threading", "= os.path.join(appDataDir, app) appDir = os.path.join(appsDir, app) if os.path.isdir(dataDir): deleteData(app)", "import deriveEntropy # For an array of threads, join them", "which contains a list of sources in the format #", "+ sourcesList) exit(1) gitUrl = repo[0] branch = repo[1] #", "a temporary dir tempDir = tempfile.mkdtemp() print(\"Cloning the repository\") #", "depth of 1 to avoid cloning the entire repo #", "output subprocess.run(\"git clone --depth 1 {} {}\".format(gitUrl, tempDir), shell=True, stdout=subprocess.DEVNULL)", "list of apps from every repo, a repo later in", "print(\"Cloning the repository\") # Git clone with a depth of", "{}...\".format(app)) # Run runCompose(args.app, \"up --detach\") asynchrounously for all apps,", "threading.Thread(target=runCompose, args=(app, \"up --detach\")) thread.start() threads.append(thread) joinThreads(threads) def stopInstalled(): #", "os.path.isfile(userFile): with open(userFile, \"r\") as f: userData = json.load(f) return", "def deleteData(app: str): dataDir = os.path.join(appDataDir, app) try: shutil.rmtree(dataDir, onerror=remove_readonly)", "with the contents of the temporary dir/apps/app # Also, keep", "Could not find metadata in \" + appFile) app[\"metadata\"][\"id\"] =", "try: shutil.rmtree(dataDir, onerror=remove_readonly) except FileNotFoundError: pass def createDataDir(app: str): dataDir", "if app in alreadyInstalled: continue if os.path.isdir(os.path.join(appsDir, app)): shutil.rmtree(os.path.join(appsDir, app),", "= None): if(app is None): apps = findAndValidateApps(appsDir) for app", "\"data\") # List all subdirectories of torDir which start with", "# Recursively copy everything from appDir to dataDir while excluding", "repo[1] # Clone the repo to a temporary dir tempDir", "# Allow more app seeds, with random numbers from 1-5", "getAppHiddenServices(app: str): torDir = os.path.join(nodeRoot, \"tor\", \"data\") # List all", "os.environ[\"APP_DOMAIN\"] = subprocess.check_output( \"hostname -s 2>/dev/null || echo 'umbrel'\", shell=True).decode(\"utf-8\")", "apps in the temporary dir/apps and for every app, #", "dir tempDir = tempfile.mkdtemp() print(\"Cloning the repository\") # Git clone", "os.listdir(torDir): if subdir.startswith(\"app-{}-\".format(app)): results.append(subdir[len(\"app-{}-\".format(app)):]) return results # Parse the sources.list", "# For an array of threads, join them and wait", "sort_keys=False)) if verbose: print(\"Wrote \" + app + \" to", "Then, check that repos apps in the temporary dir/apps and", "repo into the git url and the branch repo =", "verbose: print(\"Wrote \" + app + \" to \" +", "getAppYml(app) if data: with open(getAppYmlPath(app), 'w') as f: f.write(data) else:", "os.path.isdir(os.path.join(tempDir, \"apps\", app)): shutil.copytree(os.path.join(tempDir, \"apps\", app), os.path.join(appsDir, app), symlinks=False, ignore=shutil.ignore_patterns(\".gitignore\"))", "lib.composegenerator.v0.generate import createComposeConfigFromV0 from lib.composegenerator.v1.generate import createComposeConfigFromV1 from lib.appymlgenerator import", "args=(app, \"rm --force --stop\")) thread.start() threads.append(thread) joinThreads(threads) # Loads an", "registry = getAppRegistry(apps, appsDir) with open(os.path.join(appsDir, \"registry.json\"), \"w\") as f:", "Could not download \" + app) else: data = getAppYml(app)", "import threading from typing import List from sys import argv", "json import yaml import subprocess from lib.composegenerator.v0.generate import createComposeConfigFromV0 from", "appSystemDir = os.path.join(nodeRoot, \"app-system\") sourcesList = os.path.join(appSystemDir, \"sources.list\") appDataDir =", "{} if os.path.isfile(userFile): with open(userFile, \"r\") as f: userData =", "'notyetset.onion'\".format( os.path.join(nodeRoot, \"tor\", \"data\", \"app-{}/hostname\".format(app))), shell=True).decode(\"utf-8\") os.environ[\"APP_SEED\"] = deriveEntropy(\"app-{}-seed\".format(app)) #", "clone the repo to a temporary dir and checkout the", "[] with open(sourcesList) as f: repos = f.readlines() # For", "Overwrite the current app dir with the contents of the", "generation process updates the registry, so we need to get", "not find docker-compose.yml in \" + app) exit(1) os.system( \"docker", "random numbers from 1-5 assigned in a loop for i", "contents of the temporary dir/apps/app for app in os.listdir(os.path.join(tempDir, \"apps\")):", "torDir which start with app-${APP}- # but return them without", "overwrite the current app dir with the contents of the", "with open(getAppYmlPath(app), 'w') as f: f.write(data) else: print(\"Warning: Could not", "# Parse the sources.list repo file, which contains a list", "repos apps in the temporary dir/apps and for every app,", "def getAppYmlPath(app): return os.path.join(appsDir, app, 'app.yml') def composeToAppYml(app): composeFile =", "if os.path.isdir(os.path.join(tempDir, \"apps\", app)): shutil.copytree(os.path.join(tempDir, \"apps\", app), os.path.join(appsDir, app), symlinks=False,", "deleteData(app) # Recursively copy everything from appDir to dataDir while", "= [] for app in userData[\"installedApps\"]: print(\"Stopping app {}...\".format(app)) #", "check if a docker-compose.yml exists in the app dir composeFile", "all apps, then exit(0) when all are finished thread =", "a compose command in the app dir # Before that,", "f: json.dump(simpleRegistry, f, indent=4, sort_keys=True) print(\"Wrote version information to apps.json\")", "getArguments(): arguments = \"\" for i in range(3, len(argv)): arguments", "with open(userFile, \"r\") as f: userData = json.load(f) threads =", "json.dump(simpleRegistry, f, indent=4, sort_keys=True) print(\"Wrote version information to apps.json\") #", "composeToAppYml(app): composeFile = os.path.join(appsDir, app, \"docker-compose.yml\") appYml = os.path.join(appsDir, app,", "not os.path.isfile(composeFile): print(\"Error: Could not find docker-compose.yml in \" +", "it to a docker-compose.yml def getApp(appFile: str, appId: str): with", "name + '/' + 'app.yml' response = requests.get(url) if response.status_code", "f: compose = yaml.safe_load(f) registry = os.path.join(appsDir, \"registry.json\") # Load", "spaces def getArguments(): arguments = \"\" for i in range(3,", "just do nothing userData = {} if os.path.isfile(userFile): with open(userFile,", "\"lnd\") # List all hidden services for an app and", "= getSimpleAppRegistry(apps, appsDir) with open(os.path.join(appSystemDir, \"apps.json\"), \"w\") as f: json.dump(simpleRegistry,", "def remove_readonly(func, path, _): os.chmod(path, stat.S_IWRITE) func(path) def deleteData(app: str):", "SPDX-License-Identifier: MIT import stat import tempfile import threading from typing", "is None): apps = findAndValidateApps(appsDir) for app in apps: data", "from lib.composegenerator.v1.generate import createComposeConfigFromV1 from lib.appymlgenerator import convertComposeYMLToAppYML from lib.validate", "same owner and permissions as appDir os.chown(dataDir, os.stat(appDir).st_uid, os.stat(appDir).st_gid) os.chmod(dataDir,", "the repo to a temporary dir and checkout the branch", "temporary dir and checkout the branch # Then, check that", "'app.yml') def composeToAppYml(app): composeFile = os.path.join(appsDir, app, \"docker-compose.yml\") appYml =", "a repo later in the file may not overwrite an", "dir, checkout the branch, # and overwrite the current app", "echo 'umbrel'\", shell=True).decode(\"utf-8\") + \".local\" os.environ[\"APP_HIDDEN_SERVICE\"] = subprocess.check_output(\"cat {} 2>/dev/null", "f, indent=4, sort_keys=True) print(\"Wrote registry to registry.json\") simpleRegistry = getSimpleAppRegistry(apps,", "clone with a depth of 1 to avoid cloning the", "getApp(appFile: str, appId: str): with open(appFile, 'r') as f: app", "for thread in threads: thread.join() # The directory with this", "os.path.join(appsDir, app, \"app.yml\") with open(composeFile, \"w\") as f: appCompose =", "os.path.isfile(userFile): with open(userFile, \"r\") as f: userData = json.load(f) threads", "them to finish def joinThreads(threads: List[threading.Thread]): for thread in threads:", "a string by spaces def getArguments(): arguments = \"\" for", "appHiddenServiceFile), shell=True).decode(\"utf-8\") if not os.path.isfile(composeFile): print(\"Error: Could not find docker-compose.yml", "dir and checkout the branch # Then, check that repos", "app dir with the contents of the temporary dir/apps/app #", "in userData[\"installedApps\"]: print(\"Stopping app {}...\".format(app)) # Run runCompose(args.app, \"up --detach\")", "every repo, a repo later in the file may not", "= \"\" for i in range(3, len(argv)): arguments += argv[i]", "lib.composegenerator.v1.generate import createComposeConfigFromV1 from lib.appymlgenerator import convertComposeYMLToAppYML from lib.validate import", "in \" + sourcesList) exit(1) gitUrl = repo[0] branch =", "userData def startInstalled(): # If userfile doen't exist, just do", "\"w\") as f: appCompose = getApp(appYml, app) if(appCompose): f.write(yaml.dump(appCompose, sort_keys=False))", "dir/apps/app # Also, keep a list of apps from every", "path, _): os.chmod(path, stat.S_IWRITE) func(path) def deleteData(app: str): dataDir =", "= f.readlines() # For each repo, clone the repo to", "= os.path.join(appDataDir, app) os.environ[\"BITCOIN_DATA_DIR\"] = os.path.join(nodeRoot, \"bitcoin\") os.environ[\"LND_DATA_DIR\"] = os.path.join(nodeRoot,", "one in sys.argv joined into a string by spaces def", "information to apps.json\") # Loop through the apps and generate", "and generate valid compose files from them, then put these", "import createComposeConfigFromV0 from lib.composegenerator.v1.generate import createComposeConfigFromV1 from lib.appymlgenerator import convertComposeYMLToAppYML", "= os.path.join(nodeRoot, \"app-system\") sourcesList = os.path.join(appSystemDir, \"sources.list\") appDataDir = os.path.join(nodeRoot,", "else: print(\"Warning: Could not download \" + app) else: data", "seeds, with random numbers from 1-5 assigned in a loop", "f: userData = json.load(f) threads = [] for app in", "put their hostname in the environment hiddenServices: List[str] = getAppHiddenServices(app)", "userData: userData[\"installedApps\"] = [] userData[\"installedApps\"].append(app) userData[\"installedApps\"] = list(set(userData[\"installedApps\"])) with open(userFile,", "Also, keep a list of apps from every repo, a", "compose(app, arguments): # Runs a compose command in the app", "shutil.copytree(os.path.join(tempDir, \"apps\", app), os.path.join(appsDir, app), symlinks=False, ignore=shutil.ignore_patterns(\".gitignore\")) alreadyInstalled.append(app) # Remove", "if response.status_code == 200: return response.text else: return False def", "with this script scriptDir = os.path.dirname(os.path.realpath(__file__)) nodeRoot = os.path.join(scriptDir, \"..\",", "False def getAppYmlPath(app): return os.path.join(appsDir, app, 'app.yml') def composeToAppYml(app): composeFile", "everything from appDir to dataDir while excluding .gitignore shutil.copytree(appDir, dataDir,", "+ appFile) app[\"metadata\"][\"id\"] = appId if('version' in app and str(app['version'])", "stat import tempfile import threading from typing import List from", "git clone output subprocess.run(\"git clone --depth 1 {} {}\".format(gitUrl, tempDir),", "as f: compose = yaml.safe_load(f) registry = os.path.join(appsDir, \"registry.json\") #", "apps, then exit(0) when all are finished thread = threading.Thread(", "keep a list of apps from every repo, a repo", "files from them, then put these into the app dir", "repo to a temporary dir and checkout the branch #", "# Load the registry with open(registry, \"r\") as f: registryData", "Chown and chmod dataDir to have the same owner and", "repos = [] with open(sourcesList) as f: repos = f.readlines()", "the same owner and permissions as appDir os.chown(dataDir, os.stat(appDir).st_uid, os.stat(appDir).st_gid)", "update(verbose: bool = False): apps = findAndValidateApps(appsDir) # The compose", "return them without the app-${APP}- prefix results = [] for", "if(appCompose): f.write(yaml.dump(appCompose, sort_keys=False)) if verbose: print(\"Wrote \" + app +", "f: f.write(yaml.dump(converted, sort_keys=False)) def update(verbose: bool = False): apps =", "= os.path.join(appSystemDir, \"sources.list\") appDataDir = os.path.join(nodeRoot, \"app-data\") userFile = os.path.join(nodeRoot,", "temporary dir/apps/app for app in os.listdir(os.path.join(tempDir, \"apps\")): # if the", "finish def joinThreads(threads: List[threading.Thread]): for thread in threads: thread.join() #", "all are finished thread = threading.Thread( target=runCompose, args=(app, \"rm --force", "in alreadyInstalled: continue if os.path.isdir(os.path.join(appsDir, app)): shutil.rmtree(os.path.join(appsDir, app), onerror=remove_readonly) if", "to finish def joinThreads(threads: List[threading.Thread]): for thread in threads: thread.join()", "for i in range(3, len(argv)): arguments += argv[i] + \"", "+ app + \" to \" + composeFile) print(\"Generated configuration", "os.environ[\"APP_HIDDEN_SERVICE_{}\".format(service.upper().replace(\"-\", \"_\"))] = subprocess.check_output(\"cat {} 2>/dev/null || echo 'notyetset.onion'\".format( appHiddenServiceFile),", "\"rm --force --stop\")) thread.start() threads.append(thread) joinThreads(threads) # Loads an app.yml", "deriveEntropy(\"app-{}-seed{}\".format(app, i)) os.environ[\"APP_DATA_DIR\"] = os.path.join(appDataDir, app) os.environ[\"BITCOIN_DATA_DIR\"] = os.path.join(nodeRoot, \"bitcoin\")", "prefix results = [] for subdir in os.listdir(torDir): if subdir.startswith(\"app-{}-\".format(app)):", "a list of sources in the format # <git-url> <branch>", "dir for app in apps: composeFile = os.path.join(appsDir, app, \"docker-compose.yml\")", "os.stat(appDir).st_mode) def setInstalled(app: str): userData = getUserData() if not \"installedApps\"", "getAppRegistry, getSimpleAppRegistry from lib.entropy import deriveEntropy # For an array", "with open(userFile, \"r\") as f: userData = json.load(f) return userData", "for app in userData[\"installedApps\"]: print(\"Stopping app {}...\".format(app)) # Run runCompose(args.app,", "list(set(userData[\"installedApps\"])) with open(userFile, \"w\") as f: json.dump(userData, f) def setRemoved(app:", "|| echo 'notyetset.onion'\".format( appHiddenServiceFile), shell=True).decode(\"utf-8\") if not os.path.isfile(composeFile): print(\"Error: Could", "# Git clone with a depth of 1 to avoid", "= threading.Thread(target=runCompose, args=(app, \"up --detach\")) thread.start() threads.append(thread) joinThreads(threads) def stopInstalled():", "exit(0) when all are finished thread = threading.Thread( target=runCompose, args=(app,", "repo file, which contains a list of sources in the", "<NAME> <<EMAIL>> # # SPDX-License-Identifier: MIT import stat import tempfile", "+ \" \" return arguments def getAppYml(name): url = 'https://raw.githubusercontent.com/runcitadel/compose-nonfree/main/apps/'", "script scriptDir = os.path.dirname(os.path.realpath(__file__)) nodeRoot = os.path.join(scriptDir, \"..\", \"..\") appsDir", "os.path.join(nodeRoot, \"db\", \"user.json\") legacyScript = os.path.join(nodeRoot, \"scripts\", \"app\") def runCompose(app:", "to registry.json\") simpleRegistry = getSimpleAppRegistry(apps, appsDir) with open(os.path.join(appSystemDir, \"apps.json\"), \"w\")", "in apps: data = getAppYml(app) if data: with open(getAppYmlPath(app), 'w')", "def getUserData(): userData = {} if os.path.isfile(userFile): with open(userFile, \"r\")", "echo 'notyetset.onion'\".format( os.path.join(nodeRoot, \"tor\", \"data\", \"app-{}/hostname\".format(app))), shell=True).decode(\"utf-8\") os.environ[\"APP_SEED\"] = deriveEntropy(\"app-{}-seed\".format(app))", "i)) os.environ[\"APP_DATA_DIR\"] = os.path.join(appDataDir, app) os.environ[\"BITCOIN_DATA_DIR\"] = os.path.join(nodeRoot, \"bitcoin\") os.environ[\"LND_DATA_DIR\"]", "sourcesList = os.path.join(appSystemDir, \"sources.list\") appDataDir = os.path.join(nodeRoot, \"app-data\") userFile =", "get it set up with the basics before that registry", "= json.load(f) converted = convertComposeYMLToAppYML(compose, app, registryData) # Put converted", "os.environ[\"APP_DATA_DIR\"] = os.path.join(appDataDir, app) os.environ[\"BITCOIN_DATA_DIR\"] = os.path.join(nodeRoot, \"bitcoin\") os.environ[\"LND_DATA_DIR\"] =", "json.dump(userData, f) def setRemoved(app: str): userData = getUserData() if not", "earlier in the file def updateRepos(): # Get the list", "= threading.Thread( target=runCompose, args=(app, \"rm --force --stop\")) thread.start() threads.append(thread) joinThreads(threads)", "apps, then exit(0) when all are finished thread = threading.Thread(target=runCompose,", "os.path.join(appSystemDir, \"sources.list\") appDataDir = os.path.join(nodeRoot, \"app-data\") userFile = os.path.join(nodeRoot, \"db\",", "'r') as f: app = yaml.safe_load(f) if not \"metadata\" in", "these into the app dir for app in apps: composeFile", "app dir with the contents of the temporary dir/apps/app alreadyInstalled", "If userfile doen't exist, just do nothing userData = {}", "The directory with this script scriptDir = os.path.dirname(os.path.realpath(__file__)) nodeRoot =", "arguments = \"\" for i in range(3, len(argv)): arguments +=", "as f: appCompose = getApp(appYml, app) if(appCompose): f.write(yaml.dump(appCompose, sort_keys=False)) if", "are finished thread = threading.Thread(target=runCompose, args=(app, \"up --detach\")) thread.start() threads.append(thread)", "clone output subprocess.run(\"git clone --depth 1 {} {}\".format(gitUrl, tempDir), shell=True,", "the contents of the temporary dir/apps/app for app in os.listdir(os.path.join(tempDir,", "if os.path.isdir(dataDir): deleteData(app) # Recursively copy everything from appDir to", "app) if os.path.isdir(dataDir): deleteData(app) # Recursively copy everything from appDir", "convertComposeYMLToAppYML(compose, app, registryData) # Put converted into the app.yml after", "from lib.validate import findAndValidateApps from lib.metadata import getAppRegistry, getSimpleAppRegistry from", "= json.load(f) threads = [] for app in userData[\"installedApps\"]: print(\"Starting", "os.listdir(os.path.join(tempDir, \"apps\")): # if the app is already installed, don't", "import convertComposeYMLToAppYML from lib.validate import findAndValidateApps from lib.metadata import getAppRegistry,", "shell=True, stdout=subprocess.DEVNULL) # Overwrite the current app dir with the", "the sources.list repo file, which contains a list of sources", "print(\"Generated configuration successfully\") def download(app: str = None): if(app is", "branch repo = repo.split(\" \") if len(repo) != 2: print(\"Error:", "dir/apps/app alreadyInstalled = [] for repo in repos: repo =", "= repo[0] branch = repo[1] # Clone the repo to", "copy everything from appDir to dataDir while excluding .gitignore shutil.copytree(appDir,", "gitUrl = repo[0] branch = repo[1] # Clone the repo", "{}\".format(gitUrl, tempDir), shell=True, stdout=subprocess.DEVNULL) # Overwrite the current app dir", "os.path.join(appsDir, app) if os.path.isdir(dataDir): deleteData(app) # Recursively copy everything from", "open(userFile, \"w\") as f: json.dump(userData, f) def setRemoved(app: str): userData", "of repos repos = [] with open(sourcesList) as f: repos", "of sources in the format # <git-url> <branch> # For", "os.stat(appDir).st_gid) os.chmod(dataDir, os.stat(appDir).st_mode) def setInstalled(app: str): userData = getUserData() if", "app[\"metadata\"][\"id\"] = appId if('version' in app and str(app['version']) == \"1\"):", "return os.path.join(appsDir, app, 'app.yml') def composeToAppYml(app): composeFile = os.path.join(appsDir, app,", "is already installed, don't overwrite it if app in alreadyInstalled:", "composeFile = os.path.join(appsDir, app, \"docker-compose.yml\") commonComposeFile = os.path.join(appSystemDir, \"docker-compose.common.yml\") os.environ[\"APP_DOMAIN\"]", "os.path.join(nodeRoot, \"tor\", \"data\") # List all subdirectories of torDir which", "app-${APP}- prefix results = [] for subdir in os.listdir(torDir): if", "to stdout, as we don't want to see the git", "\"apps.json\"), \"w\") as f: json.dump(simpleRegistry, f, indent=4, sort_keys=True) print(\"Wrote version", "as f: json.dump(userData, f) def setRemoved(app: str): userData = getUserData()", "the second one in sys.argv joined into a string by", "app in apps: composeFile = os.path.join(appsDir, app, \"docker-compose.yml\") appYml =", "in os.listdir(os.path.join(tempDir, \"apps\")): # if the app is already installed,", "json.dump(userData, f) def getAppHiddenServices(app: str): torDir = os.path.join(nodeRoot, \"tor\", \"data\")", "app dir # Before that, check if a docker-compose.yml exists", "nodeRoot) else: return createComposeConfigFromV0(app) def compose(app, arguments): # Runs a", "composeFile = os.path.join(appsDir, app, \"docker-compose.yml\") appYml = os.path.join(appsDir, app, \"app.yml\")", "2>/dev/null || echo 'notyetset.onion'\".format( appHiddenServiceFile), shell=True).decode(\"utf-8\") if not os.path.isfile(composeFile): print(\"Error:", "\"registry.json\") # Load the registry with open(registry, \"r\") as f:", "for app in apps: composeFile = os.path.join(appsDir, app, \"docker-compose.yml\") appYml", "appFile) app[\"metadata\"][\"id\"] = appId if('version' in app and str(app['version']) ==", "compose --env-file '{}' --project-name '{}' --file '{}' --file '{}' {}\".format(", "list of sources in the format # <git-url> <branch> #", "download \" + app) def getUserData(): userData = {} if", "= deriveEntropy(\"app-{}-seed\".format(app)) # Allow more app seeds, with random numbers", "a temporary dir and checkout the branch # Then, check", "with open(os.path.join(appSystemDir, \"apps.json\"), \"w\") as f: json.dump(simpleRegistry, f, indent=4, sort_keys=True)", "print(\"Wrote \" + app + \" to \" + composeFile)", "= getAppHiddenServices(app) for service in hiddenServices: appHiddenServiceFile = os.path.join( nodeRoot,", "getAppHiddenServices(app) for service in hiddenServices: appHiddenServiceFile = os.path.join( nodeRoot, \"tor\",", "os.system( \"docker compose --env-file '{}' --project-name '{}' --file '{}' --file", "\"\" for i in range(3, len(argv)): arguments += argv[i] +", "\" return arguments def getAppYml(name): url = 'https://raw.githubusercontent.com/runcitadel/compose-nonfree/main/apps/' + \\", "so we need to get it set up with the", "args: str): compose(app, args) # Returns a list of every", "app, \"docker-compose.yml\") appYml = os.path.join(appsDir, app, \"app.yml\") with open(composeFile, \"w\")", "= os.path.join(appSystemDir, \"docker-compose.common.yml\") os.environ[\"APP_DOMAIN\"] = subprocess.check_output( \"hostname -s 2>/dev/null ||", "Loads an app.yml and converts it to a docker-compose.yml def", "results # Parse the sources.list repo file, which contains a", "in app: raise Exception(\"Error: Could not find metadata in \"", "sort_keys=True) print(\"Wrote version information to apps.json\") # Loop through the", "target=runCompose, args=(app, \"rm --force --stop\")) thread.start() threads.append(thread) joinThreads(threads) # Loads", "exists in the app dir composeFile = os.path.join(appsDir, app, \"docker-compose.yml\")", "for all apps, then exit(0) when all are finished thread", "app, # overwrite the current app dir with the contents", "and put their hostname in the environment hiddenServices: List[str] =", "not overwrite an app from a repo earlier in the", "to get it set up with the basics before that", "not find metadata in \" + appFile) app[\"metadata\"][\"id\"] = appId", "from lib.appymlgenerator import convertComposeYMLToAppYML from lib.validate import findAndValidateApps from lib.metadata", "runCompose(app: str, args: str): compose(app, args) # Returns a list", "onerror=remove_readonly) except FileNotFoundError: pass def createDataDir(app: str): dataDir = os.path.join(appDataDir,", "subdir in os.listdir(torDir): if subdir.startswith(\"app-{}-\".format(app)): results.append(subdir[len(\"app-{}-\".format(app)):]) return results # Parse", "subdir.startswith(\"app-{}-\".format(app)): results.append(subdir[len(\"app-{}-\".format(app)):]) return results # Parse the sources.list repo file,", "def updateRepos(): # Get the list of repos repos =", "import os import requests import shutil import json import yaml", "registry = os.path.join(appsDir, \"registry.json\") # Load the registry with open(registry,", "= getApp(appYml, app) if(appCompose): f.write(yaml.dump(appCompose, sort_keys=False)) if verbose: print(\"Wrote \"", "app: raise Exception(\"Error: Could not find metadata in \" +", "threads = [] for app in userData[\"installedApps\"]: print(\"Starting app {}...\".format(app))", "os.stat(appDir).st_uid, os.stat(appDir).st_gid) os.chmod(dataDir, os.stat(appDir).st_mode) def setInstalled(app: str): userData = getUserData()", "lib.entropy import deriveEntropy # For an array of threads, join", "version information to apps.json\") # Loop through the apps and", "open(registry, \"r\") as f: registryData = json.load(f) converted = convertComposeYMLToAppYML(compose,", "registry to registry.json\") simpleRegistry = getSimpleAppRegistry(apps, appsDir) with open(os.path.join(appSystemDir, \"apps.json\"),", "func(path) def deleteData(app: str): dataDir = os.path.join(appDataDir, app) try: shutil.rmtree(dataDir,", "Git clone with a depth of 1 to avoid cloning", "repos: repo = repo.strip() if repo == \"\": continue #", "+= argv[i] + \" \" return arguments def getAppYml(name): url", "return arguments def getAppYml(name): url = 'https://raw.githubusercontent.com/runcitadel/compose-nonfree/main/apps/' + \\ name", "join them and wait for them to finish def joinThreads(threads:", "\"registry.json\"), \"w\") as f: json.dump(registry, f, indent=4, sort_keys=True) print(\"Wrote registry", "appsDir) with open(os.path.join(appSystemDir, \"apps.json\"), \"w\") as f: json.dump(simpleRegistry, f, indent=4,", "valid compose files from them, then put these into the", "threading.Thread( target=runCompose, args=(app, \"rm --force --stop\")) thread.start() threads.append(thread) joinThreads(threads) #", "[] for repo in repos: repo = repo.strip() if repo", "updates the registry, so we need to get it set", "threads: thread.join() # The directory with this script scriptDir =", "tempDir = tempfile.mkdtemp() print(\"Cloning the repository\") # Git clone with", "userData[\"installedApps\"]: print(\"Starting app {}...\".format(app)) # Run runCompose(args.app, \"up --detach\") asynchrounously", "= os.path.join( nodeRoot, \"tor\", \"data\", \"app-{}-{}/hostname\".format(app, service)) os.environ[\"APP_HIDDEN_SERVICE_{}\".format(service.upper().replace(\"-\", \"_\"))] =", "as f: repos = f.readlines() # For each repo, clone", "in app and str(app['version']) == \"1\"): return createComposeConfigFromV1(app, nodeRoot) else:", "repo = repo.split(\" \") if len(repo) != 2: print(\"Error: Invalid", "findAndValidateApps from lib.metadata import getAppRegistry, getSimpleAppRegistry from lib.entropy import deriveEntropy", "# Chown and chmod dataDir to have the same owner", "threads = [] for app in userData[\"installedApps\"]: print(\"Stopping app {}...\".format(app))", "os.path.join( nodeRoot, \"tor\", \"data\", \"app-{}-{}/hostname\".format(app, service)) os.environ[\"APP_HIDDEN_SERVICE_{}\".format(service.upper().replace(\"-\", \"_\"))] = subprocess.check_output(\"cat", "subprocess.run(\"git clone --depth 1 {} {}\".format(gitUrl, tempDir), shell=True, stdout=subprocess.DEVNULL) #", "response.status_code == 200: return response.text else: return False def getAppYmlPath(app):", "import findAndValidateApps from lib.metadata import getAppRegistry, getSimpleAppRegistry from lib.entropy import", "that, check if a docker-compose.yml exists in the app dir", "through the apps and generate valid compose files from them,", "\"_\"))] = subprocess.check_output(\"cat {} 2>/dev/null || echo 'notyetset.onion'\".format( appHiddenServiceFile), shell=True).decode(\"utf-8\")", "temporary dir, checkout the branch, # and overwrite the current", "len(argv)): arguments += argv[i] + \" \" return arguments def", "= os.path.join(appsDir, app) if os.path.isdir(dataDir): deleteData(app) # Recursively copy everything", "an array of threads, join them and wait for them", "# If userfile doen't exist, just do nothing userData =", "= findAndValidateApps(appsDir) # The compose generation process updates the registry,", "import json import yaml import subprocess from lib.composegenerator.v0.generate import createComposeConfigFromV0", "apps: composeFile = os.path.join(appsDir, app, \"docker-compose.yml\") appYml = os.path.join(appsDir, app,", "app, \"docker-compose.yml\") commonComposeFile = os.path.join(appSystemDir, \"docker-compose.common.yml\") os.environ[\"APP_DOMAIN\"] = subprocess.check_output( \"hostname", "Runs a compose command in the app dir # Before", "subprocess.check_output( \"hostname -s 2>/dev/null || echo 'umbrel'\", shell=True).decode(\"utf-8\") + \".local\"", "to dataDir while excluding .gitignore shutil.copytree(appDir, dataDir, symlinks=False, ignore=shutil.ignore_patterns(\".gitignore\")) #", "to \" + composeFile) print(\"Generated configuration successfully\") def download(app: str", "but return them without the app-${APP}- prefix results = []", "convertComposeYMLToAppYML from lib.validate import findAndValidateApps from lib.metadata import getAppRegistry, getSimpleAppRegistry", "\"r\") as f: userData = json.load(f) threads = [] for", "to a temporary dir, checkout the branch, # and overwrite", "repo == \"\": continue # Split the repo into the", "\"..\", \"..\") appsDir = os.path.join(nodeRoot, \"apps\") appSystemDir = os.path.join(nodeRoot, \"app-system\")", "--detach\") asynchrounously for all apps, then exit(0) when all are", "then exit(0) when all are finished thread = threading.Thread(target=runCompose, args=(app,", "a docker-compose.yml def getApp(appFile: str, appId: str): with open(appFile, 'r')", "open(appFile, 'r') as f: app = yaml.safe_load(f) if not \"metadata\"", "Allow more app seeds, with random numbers from 1-5 assigned", "# Put converted into the app.yml after encoding it as", "open(os.path.join(appSystemDir, \"apps.json\"), \"w\") as f: json.dump(simpleRegistry, f, indent=4, sort_keys=True) print(\"Wrote", "argv[i] + \" \" return arguments def getAppYml(name): url =", "appDir = os.path.join(appsDir, app) if os.path.isdir(dataDir): deleteData(app) # Recursively copy", "dataDir to have the same owner and permissions as appDir", "the temporary dir/apps and for every app, # overwrite the", "'{}' {}\".format( os.path.join(nodeRoot, \".env\"), app, commonComposeFile, composeFile, arguments)) def remove_readonly(func,", "the format # <git-url> <branch> # For every line, clone", "in the temporary dir/apps and for every app, # overwrite", "getAppYml(name): url = 'https://raw.githubusercontent.com/runcitadel/compose-nonfree/main/apps/' + \\ name + '/' +", "docker-compose.yml in \" + app) exit(1) os.system( \"docker compose --env-file", "don't want to see the git clone output subprocess.run(\"git clone", "\".env\"), app, commonComposeFile, composeFile, arguments)) def remove_readonly(func, path, _): os.chmod(path,", "doen't exist, just do nothing userData = {} if os.path.isfile(userFile):", "chmod dataDir to have the same owner and permissions as", "return createComposeConfigFromV0(app) def compose(app, arguments): # Runs a compose command", "def composeToAppYml(app): composeFile = os.path.join(appsDir, app, \"docker-compose.yml\") appYml = os.path.join(appsDir,", "dataDir = os.path.join(appDataDir, app) try: shutil.rmtree(dataDir, onerror=remove_readonly) except FileNotFoundError: pass", "\"w\") as f: json.dump(registry, f, indent=4, sort_keys=True) print(\"Wrote registry to", "for app in apps: data = getAppYml(app) if data: with", "in userData: return userData[\"installedApps\"] = list(set(userData[\"installedApps\"])) userData[\"installedApps\"].remove(app) with open(userFile, \"w\")", "userData = getUserData() if not \"installedApps\" in userData: userData[\"installedApps\"] =", "app dir with the contents of the temporary dir/apps/app for", "when all are finished thread = threading.Thread(target=runCompose, args=(app, \"up --detach\"))", "def getApp(appFile: str, appId: str): with open(appFile, 'r') as f:", "it with open(composeFile, \"r\") as f: compose = yaml.safe_load(f) registry", "as f: json.dump(registry, f, indent=4, sort_keys=True) print(\"Wrote registry to registry.json\")", "from typing import List from sys import argv import os", "f: app = yaml.safe_load(f) if not \"metadata\" in app: raise", "else: return createComposeConfigFromV0(app) def compose(app, arguments): # Runs a compose", "Read the compose file and parse it with open(composeFile, \"r\")", "os.path.join(appsDir, app, \"docker-compose.yml\") appYml = os.path.join(appsDir, app, \"app.yml\") with open(composeFile,", "file, which contains a list of sources in the format", "if not \"metadata\" in app: raise Exception(\"Error: Could not find", "f: repos = f.readlines() # For each repo, clone the", "app) if(appCompose): f.write(yaml.dump(appCompose, sort_keys=False)) if verbose: print(\"Wrote \" + app", "then put these into the app dir for app in", "MIT import stat import tempfile import threading from typing import", "os.environ[\"BITCOIN_DATA_DIR\"] = os.path.join(nodeRoot, \"bitcoin\") os.environ[\"LND_DATA_DIR\"] = os.path.join(nodeRoot, \"lnd\") # List", "createDataDir(app: str): dataDir = os.path.join(appDataDir, app) appDir = os.path.join(appsDir, app)", "\"1\"): return createComposeConfigFromV1(app, nodeRoot) else: return createComposeConfigFromV0(app) def compose(app, arguments):", "os.path.join(nodeRoot, \"app-system\") sourcesList = os.path.join(appSystemDir, \"sources.list\") appDataDir = os.path.join(nodeRoot, \"app-data\")", "\"app.yml\") with open(composeFile, \"w\") as f: appCompose = getApp(appYml, app)", "'/' + 'app.yml' response = requests.get(url) if response.status_code == 200:", "os.chown(dataDir, os.stat(appDir).st_uid, os.stat(appDir).st_gid) os.chmod(dataDir, os.stat(appDir).st_mode) def setInstalled(app: str): userData =", "app and str(app['version']) == \"1\"): return createComposeConfigFromV1(app, nodeRoot) else: return", "every argument after the second one in sys.argv joined into", "app in userData[\"installedApps\"]: print(\"Starting app {}...\".format(app)) # Run runCompose(args.app, \"up", "generate valid compose files from them, then put these into", "# Clone the repo to a temporary dir tempDir =", "The compose generation process updates the registry, so we need", "\"up --detach\")) thread.start() threads.append(thread) joinThreads(threads) def stopInstalled(): # If userfile", "argv import os import requests import shutil import json import", "= getAppRegistry(apps, appsDir) with open(os.path.join(appsDir, \"registry.json\"), \"w\") as f: json.dump(registry,", "import argv import os import requests import shutil import json", "a loop for i in range(1, 6): os.environ[\"APP_SEED_{}\".format(i)] = deriveEntropy(\"app-{}-seed{}\".format(app,", "them, then put these into the app dir for app", "without the app-${APP}- prefix results = [] for subdir in", "them and wait for them to finish def joinThreads(threads: List[threading.Thread]):", "os.path.join(scriptDir, \"..\", \"..\") appsDir = os.path.join(nodeRoot, \"apps\") appSystemDir = os.path.join(nodeRoot,", "as f: userData = json.load(f) threads = [] for app", "repo = repo.strip() if repo == \"\": continue # Split", "== 200: return response.text else: return False def getAppYmlPath(app): return", "of the temporary dir/apps/app for app in os.listdir(os.path.join(tempDir, \"apps\")): #", "= os.path.join(nodeRoot, \"scripts\", \"app\") def runCompose(app: str, args: str): compose(app,", "thread = threading.Thread(target=runCompose, args=(app, \"up --detach\")) thread.start() threads.append(thread) joinThreads(threads) def", "\" to \" + composeFile) print(\"Generated configuration successfully\") def download(app:", "the basics before that registry = getAppRegistry(apps, appsDir) with open(os.path.join(appsDir,", "configuration successfully\") def download(app: str = None): if(app is None):", "line, clone the repo to a temporary dir and checkout", "not download \" + app) else: data = getAppYml(app) if", "|| echo 'umbrel'\", shell=True).decode(\"utf-8\") + \".local\" os.environ[\"APP_HIDDEN_SERVICE\"] = subprocess.check_output(\"cat {}", "'notyetset.onion'\".format( appHiddenServiceFile), shell=True).decode(\"utf-8\") if not os.path.isfile(composeFile): print(\"Error: Could not find", "put these into the app dir for app in apps:", "into the app.yml after encoding it as YAML with open(appYml,", "with the basics before that registry = getAppRegistry(apps, appsDir) with", "Could not download \" + app) def getUserData(): userData =", "in a loop for i in range(1, 6): os.environ[\"APP_SEED_{}\".format(i)] =", "setRemoved(app: str): userData = getUserData() if not \"installedApps\" in userData:", "continue if os.path.isdir(os.path.join(appsDir, app)): shutil.rmtree(os.path.join(appsDir, app), onerror=remove_readonly) if os.path.isdir(os.path.join(tempDir, \"apps\",", "entire repo # Dont print anything to stdout, as we", "app) os.environ[\"BITCOIN_DATA_DIR\"] = os.path.join(nodeRoot, \"bitcoin\") os.environ[\"LND_DATA_DIR\"] = os.path.join(nodeRoot, \"lnd\") #", "deriveEntropy(\"app-{}-seed\".format(app)) # Allow more app seeds, with random numbers from", "with open(os.path.join(appsDir, \"registry.json\"), \"w\") as f: json.dump(registry, f, indent=4, sort_keys=True)", "= subprocess.check_output(\"cat {} 2>/dev/null || echo 'notyetset.onion'\".format( appHiddenServiceFile), shell=True).decode(\"utf-8\") if", "userFile = os.path.join(nodeRoot, \"db\", \"user.json\") legacyScript = os.path.join(nodeRoot, \"scripts\", \"app\")", "FileNotFoundError: pass def createDataDir(app: str): dataDir = os.path.join(appDataDir, app) appDir", "getAppYmlPath(app): return os.path.join(appsDir, app, 'app.yml') def composeToAppYml(app): composeFile = os.path.join(appsDir,", "dataDir = os.path.join(appDataDir, app) appDir = os.path.join(appsDir, app) if os.path.isdir(dataDir):", "# List all hidden services for an app and put", "torDir = os.path.join(nodeRoot, \"tor\", \"data\") # List all subdirectories of", "\"docker-compose.yml\") appYml = os.path.join(appsDir, app, \"app.yml\") with open(composeFile, \"w\") as", "in apps: composeFile = os.path.join(appsDir, app, \"docker-compose.yml\") appYml = os.path.join(appsDir,", "\"up --detach\") asynchrounously for all apps, then exit(0) when all", "branch # Then, check that repos apps in the temporary", "and overwrite the current app dir with the contents of", "the branch # Then, check that repos apps in the", "= json.load(f) return userData def startInstalled(): # If userfile doen't", "# Get the list of repos repos = [] with", "by spaces def getArguments(): arguments = \"\" for i in", "= False): apps = findAndValidateApps(appsDir) # The compose generation process", "f, indent=4, sort_keys=True) print(\"Wrote version information to apps.json\") # Loop", "the branch, # and overwrite the current app dir with", "this script scriptDir = os.path.dirname(os.path.realpath(__file__)) nodeRoot = os.path.join(scriptDir, \"..\", \"..\")", "\"docker-compose.common.yml\") os.environ[\"APP_DOMAIN\"] = subprocess.check_output( \"hostname -s 2>/dev/null || echo 'umbrel'\",", "clone --depth 1 {} {}\".format(gitUrl, tempDir), shell=True, stdout=subprocess.DEVNULL) # Overwrite", "Exception(\"Error: Could not find metadata in \" + appFile) app[\"metadata\"][\"id\"]", "appCompose = getApp(appYml, app) if(appCompose): f.write(yaml.dump(appCompose, sort_keys=False)) if verbose: print(\"Wrote", "--stop\")) thread.start() threads.append(thread) joinThreads(threads) # Loads an app.yml and converts", "\"w\") as f: json.dump(userData, f) def getAppHiddenServices(app: str): torDir =", "# <git-url> <branch> # For every line, clone the repo", "\"r\") as f: registryData = json.load(f) converted = convertComposeYMLToAppYML(compose, app,", "\" \" return arguments def getAppYml(name): url = 'https://raw.githubusercontent.com/runcitadel/compose-nonfree/main/apps/' +", "with open(userFile, \"w\") as f: json.dump(userData, f) def getAppHiddenServices(app: str):", "threads.append(thread) joinThreads(threads) def stopInstalled(): # If userfile doen't exist, just", "download \" + app) else: data = getAppYml(app) if data:", "sys import argv import os import requests import shutil import", "before that registry = getAppRegistry(apps, appsDir) with open(os.path.join(appsDir, \"registry.json\"), \"w\")", "symlinks=False, ignore=shutil.ignore_patterns(\".gitignore\")) # Chown and chmod dataDir to have the", "# and overwrite the current app dir with the contents", "file may not overwrite an app from a repo earlier", "= repo[1] # Clone the repo to a temporary dir", "[] for app in userData[\"installedApps\"]: print(\"Starting app {}...\".format(app)) # Run", "# Run runCompose(args.app, \"up --detach\") asynchrounously for all apps, then", "# Overwrite the current app dir with the contents of", "if(app is None): apps = findAndValidateApps(appsDir) for app in apps:", "os.chmod(dataDir, os.stat(appDir).st_mode) def setInstalled(app: str): userData = getUserData() if not", "overwrite an app from a repo earlier in the file", "parse it with open(composeFile, \"r\") as f: compose = yaml.safe_load(f)", "\" + app + \" to \" + composeFile) print(\"Generated", "= subprocess.check_output(\"cat {} 2>/dev/null || echo 'notyetset.onion'\".format( os.path.join(nodeRoot, \"tor\", \"data\",", "app, \"app.yml\") with open(composeFile, \"w\") as f: appCompose = getApp(appYml,", "def startInstalled(): # If userfile doen't exist, just do nothing", "as appDir os.chown(dataDir, os.stat(appDir).st_uid, os.stat(appDir).st_gid) os.chmod(dataDir, os.stat(appDir).st_mode) def setInstalled(app: str):", "lib.validate import findAndValidateApps from lib.metadata import getAppRegistry, getSimpleAppRegistry from lib.entropy", "basics before that registry = getAppRegistry(apps, appsDir) with open(os.path.join(appsDir, \"registry.json\"),", "appYml = os.path.join(appsDir, app, \"app.yml\") # Read the compose file", "\"db\", \"user.json\") legacyScript = os.path.join(nodeRoot, \"scripts\", \"app\") def runCompose(app: str,", "remove_readonly(func, path, _): os.chmod(path, stat.S_IWRITE) func(path) def deleteData(app: str): dataDir", "for app in os.listdir(os.path.join(tempDir, \"apps\")): # if the app is", "f: userData = json.load(f) return userData def startInstalled(): # If", "print(\"Wrote version information to apps.json\") # Loop through the apps", "registry.json\") simpleRegistry = getSimpleAppRegistry(apps, appsDir) with open(os.path.join(appSystemDir, \"apps.json\"), \"w\") as", "os.path.isdir(dataDir): deleteData(app) # Recursively copy everything from appDir to dataDir", "\"r\") as f: compose = yaml.safe_load(f) registry = os.path.join(appsDir, \"registry.json\")", "os.path.join(appSystemDir, \"docker-compose.common.yml\") os.environ[\"APP_DOMAIN\"] = subprocess.check_output( \"hostname -s 2>/dev/null || echo", "Invalid repo format in \" + sourcesList) exit(1) gitUrl =", "the registry, so we need to get it set up", "which start with app-${APP}- # but return them without the", "avoid cloning the entire repo # Dont print anything to", "don't overwrite it if app in alreadyInstalled: continue if os.path.isdir(os.path.join(appsDir,", "a list of every argument after the second one in", "tempfile.mkdtemp() print(\"Cloning the repository\") # Git clone with a depth", "Run runCompose(args.app, \"up --detach\") asynchrounously for all apps, then exit(0)", "lib.appymlgenerator import convertComposeYMLToAppYML from lib.validate import findAndValidateApps from lib.metadata import", "data = getAppYml(app) if data: with open(getAppYmlPath(app), 'w') as f:", "stdout, as we don't want to see the git clone", "appDir os.chown(dataDir, os.stat(appDir).st_uid, os.stat(appDir).st_gid) os.chmod(dataDir, os.stat(appDir).st_mode) def setInstalled(app: str): userData", "os.path.join(nodeRoot, \"lnd\") # List all hidden services for an app", "|| echo 'notyetset.onion'\".format( os.path.join(nodeRoot, \"tor\", \"data\", \"app-{}/hostname\".format(app))), shell=True).decode(\"utf-8\") os.environ[\"APP_SEED\"] =", "200: return response.text else: return False def getAppYmlPath(app): return os.path.join(appsDir,", "\"w\") as f: f.write(yaml.dump(converted, sort_keys=False)) def update(verbose: bool = False):", "For every line, clone the repo to a temporary dir", "that repos apps in the temporary dir/apps and for every", "threading from typing import List from sys import argv import", "in the app dir # Before that, check if a", "in the file def updateRepos(): # Get the list of", "owner and permissions as appDir os.chown(dataDir, os.stat(appDir).st_uid, os.stat(appDir).st_gid) os.chmod(dataDir, os.stat(appDir).st_mode)", "deriveEntropy # For an array of threads, join them and", "appYml = os.path.join(appsDir, app, \"app.yml\") with open(composeFile, \"w\") as f:", "os.environ[\"APP_SEED\"] = deriveEntropy(\"app-{}-seed\".format(app)) # Allow more app seeds, with random", "for subdir in os.listdir(torDir): if subdir.startswith(\"app-{}-\".format(app)): results.append(subdir[len(\"app-{}-\".format(app)):]) return results #", "checkout the branch, # and overwrite the current app dir", "service in hiddenServices: appHiddenServiceFile = os.path.join( nodeRoot, \"tor\", \"data\", \"app-{}-{}/hostname\".format(app,", "shutil.copytree(appDir, dataDir, symlinks=False, ignore=shutil.ignore_patterns(\".gitignore\")) # Chown and chmod dataDir to", "the file def updateRepos(): # Get the list of repos", "str): userData = getUserData() if not \"installedApps\" in userData: userData[\"installedApps\"]", "app = yaml.safe_load(f) if not \"metadata\" in app: raise Exception(\"Error:", "\"installedApps\" in userData: return userData[\"installedApps\"] = list(set(userData[\"installedApps\"])) userData[\"installedApps\"].remove(app) with open(userFile,", "process updates the registry, so we need to get it", "from appDir to dataDir while excluding .gitignore shutil.copytree(appDir, dataDir, symlinks=False,", "f: f.write(data) else: print(\"Warning: Could not download \" + app)" ]
[ "class ExperienceFeaturesQuery(BaseQuery): table_name = 'experience_features' class ProjectQuery: def __init__(self, project):", "'size_features' class PurposeFeaturesQuery(BaseQuery): table_name = 'purpose_features' class HistoryFeaturesQuery(BaseQuery): table_name =", "= HistoryFeaturesQuery(project).do_query() self.exp_features = ExperienceFeaturesQuery(project).do_query() self.__cache_end_commit_id = None @property def", "commit_id = pf.commit_id self.__cache_end_commit_id = commit_id return self.__cache_end_commit_id def combine(self):", "SizeFeaturesQuery(BaseQuery): table_name = 'size_features' class PurposeFeaturesQuery(BaseQuery): table_name = 'purpose_features' class", "cm_dict['commit_id'] = cm.commit_id ret_list.append(cm_dict) if cm.commit_id == self.end_commit_id: break return", "table_name = 'size_features' class PurposeFeaturesQuery(BaseQuery): table_name = 'purpose_features' class HistoryFeaturesQuery(BaseQuery):", "= df.ns features_dict[df.commit_id]['nd'] = df.nd features_dict[df.commit_id]['nf'] = df.nf features_dict[df.commit_id]['entropy'] =", "from query.base import BaseQuery class CommitMetaQuery(BaseQuery): table_name = 'commit_meta' class", "= ef.sexp ret_list = list() for cm in self.cms: cm_dict", "class SizeFeaturesQuery(BaseQuery): table_name = 'size_features' class PurposeFeaturesQuery(BaseQuery): table_name = 'purpose_features'", "in self.purpose_features: features_dict[pf.commit_id]['fix'] = pf.fix for hf in self.history_features: features_dict[hf.commit_id]['ndev']", "'experience_features' class ProjectQuery: def __init__(self, project): self.project = project self.cms", "query.base import BaseQuery class CommitMetaQuery(BaseQuery): table_name = 'commit_meta' class DiffusionFeaturesQuery(BaseQuery):", "def combine(self): features_dict = dict() for sf in self.size_features: features_dict[sf.commit_id]", "self.project = project self.cms = CommitMetaQuery(project).do_query() self.diffusion_features = DiffusionFeaturesQuery(project).do_query() self.size_features", "class CommitMetaQuery(BaseQuery): table_name = 'commit_meta' class DiffusionFeaturesQuery(BaseQuery): table_name = 'diffusion_features'", "SizeFeaturesQuery(project).do_query() self.purpose_features = PurposeFeaturesQuery(project).do_query() self.history_features = HistoryFeaturesQuery(project).do_query() self.exp_features = ExperienceFeaturesQuery(project).do_query()", "features_dict[sf.commit_id] = dict() features_dict[sf.commit_id]['la'] = sf.la features_dict[sf.commit_id]['ld'] = sf.ld features_dict[sf.commit_id]['lt']", "= df.nd features_dict[df.commit_id]['nf'] = df.nf features_dict[df.commit_id]['entropy'] = df.entropy for pf", "sf in self.size_features: features_dict[sf.commit_id] = dict() features_dict[sf.commit_id]['la'] = sf.la features_dict[sf.commit_id]['ld']", "pf.fix for hf in self.history_features: features_dict[hf.commit_id]['ndev'] = hf.ndev features_dict[hf.commit_id]['age'] =", "self.__cache_end_commit_id is not None: return self.__cache_end_commit_id commit_id = None for", "None: return self.__cache_end_commit_id commit_id = None for pf in self.purpose_features:", "cm_dict = features_dict[cm.commit_id] if len(cm_dict) == 14: cm_dict['commit_id'] = cm.commit_id", "commit_id return self.__cache_end_commit_id def combine(self): features_dict = dict() for sf", "for pf in self.purpose_features: features_dict[pf.commit_id]['fix'] = pf.fix for hf in", "list() for cm in self.cms: cm_dict = features_dict[cm.commit_id] if len(cm_dict)", "HistoryFeaturesQuery(BaseQuery): table_name = 'history_features' class ExperienceFeaturesQuery(BaseQuery): table_name = 'experience_features' class", "end_commit_id(self): if self.__cache_end_commit_id is not None: return self.__cache_end_commit_id commit_id =", "for df in self.diffusion_features: features_dict[df.commit_id]['ns'] = df.ns features_dict[df.commit_id]['nd'] = df.nd", "self.history_features: features_dict[hf.commit_id]['ndev'] = hf.ndev features_dict[hf.commit_id]['age'] = hf.age features_dict[hf.commit_id]['nuc'] = hf.nuc", "'purpose_features' class HistoryFeaturesQuery(BaseQuery): table_name = 'history_features' class ExperienceFeaturesQuery(BaseQuery): table_name =", "ef.sexp ret_list = list() for cm in self.cms: cm_dict =", "table_name = 'diffusion_features' class SizeFeaturesQuery(BaseQuery): table_name = 'size_features' class PurposeFeaturesQuery(BaseQuery):", "project self.cms = CommitMetaQuery(project).do_query() self.diffusion_features = DiffusionFeaturesQuery(project).do_query() self.size_features = SizeFeaturesQuery(project).do_query()", "ret_list = list() for cm in self.cms: cm_dict = features_dict[cm.commit_id]", "'diffusion_features' class SizeFeaturesQuery(BaseQuery): table_name = 'size_features' class PurposeFeaturesQuery(BaseQuery): table_name =", "= SizeFeaturesQuery(project).do_query() self.purpose_features = PurposeFeaturesQuery(project).do_query() self.history_features = HistoryFeaturesQuery(project).do_query() self.exp_features =", "= dict() features_dict[sf.commit_id]['la'] = sf.la features_dict[sf.commit_id]['ld'] = sf.ld features_dict[sf.commit_id]['lt'] =", "@property def end_commit_id(self): if self.__cache_end_commit_id is not None: return self.__cache_end_commit_id", "for ef in self.exp_features: features_dict[ef.commit_id]['exp'] = ef.exp features_dict[ef.commit_id]['rexp'] = ef.rexp", "= df.entropy for pf in self.purpose_features: features_dict[pf.commit_id]['fix'] = pf.fix for", "self.exp_features: features_dict[ef.commit_id]['exp'] = ef.exp features_dict[ef.commit_id]['rexp'] = ef.rexp features_dict[ef.commit_id]['sexp'] = ef.sexp", "= 'experience_features' class ProjectQuery: def __init__(self, project): self.project = project", "= hf.age features_dict[hf.commit_id]['nuc'] = hf.nuc for ef in self.exp_features: features_dict[ef.commit_id]['exp']", "hf.nuc for ef in self.exp_features: features_dict[ef.commit_id]['exp'] = ef.exp features_dict[ef.commit_id]['rexp'] =", "DiffusionFeaturesQuery(BaseQuery): table_name = 'diffusion_features' class SizeFeaturesQuery(BaseQuery): table_name = 'size_features' class", "class PurposeFeaturesQuery(BaseQuery): table_name = 'purpose_features' class HistoryFeaturesQuery(BaseQuery): table_name = 'history_features'", "self.size_features: features_dict[sf.commit_id] = dict() features_dict[sf.commit_id]['la'] = sf.la features_dict[sf.commit_id]['ld'] = sf.ld", "ProjectQuery: def __init__(self, project): self.project = project self.cms = CommitMetaQuery(project).do_query()", "features_dict[df.commit_id]['nd'] = df.nd features_dict[df.commit_id]['nf'] = df.nf features_dict[df.commit_id]['entropy'] = df.entropy for", "for cm in self.cms: cm_dict = features_dict[cm.commit_id] if len(cm_dict) ==", "for hf in self.history_features: features_dict[hf.commit_id]['ndev'] = hf.ndev features_dict[hf.commit_id]['age'] = hf.age", "= list() for cm in self.cms: cm_dict = features_dict[cm.commit_id] if", "for sf in self.size_features: features_dict[sf.commit_id] = dict() features_dict[sf.commit_id]['la'] = sf.la", "== 14: cm_dict['commit_id'] = cm.commit_id ret_list.append(cm_dict) if cm.commit_id == self.end_commit_id:", "if self.__cache_end_commit_id is not None: return self.__cache_end_commit_id commit_id = None", "features_dict[sf.commit_id]['lt'] = sf.lt for df in self.diffusion_features: features_dict[df.commit_id]['ns'] = df.ns", "= None @property def end_commit_id(self): if self.__cache_end_commit_id is not None:", "table_name = 'commit_meta' class DiffusionFeaturesQuery(BaseQuery): table_name = 'diffusion_features' class SizeFeaturesQuery(BaseQuery):", "= commit_id return self.__cache_end_commit_id def combine(self): features_dict = dict() for", "= None for pf in self.purpose_features: if pf.fix: commit_id =", "= df.nf features_dict[df.commit_id]['entropy'] = df.entropy for pf in self.purpose_features: features_dict[pf.commit_id]['fix']", "len(cm_dict) == 14: cm_dict['commit_id'] = cm.commit_id ret_list.append(cm_dict) if cm.commit_id ==", "class HistoryFeaturesQuery(BaseQuery): table_name = 'history_features' class ExperienceFeaturesQuery(BaseQuery): table_name = 'experience_features'", "= dict() for sf in self.size_features: features_dict[sf.commit_id] = dict() features_dict[sf.commit_id]['la']", "ef.exp features_dict[ef.commit_id]['rexp'] = ef.rexp features_dict[ef.commit_id]['sexp'] = ef.sexp ret_list = list()", "features_dict[ef.commit_id]['rexp'] = ef.rexp features_dict[ef.commit_id]['sexp'] = ef.sexp ret_list = list() for", "= 'size_features' class PurposeFeaturesQuery(BaseQuery): table_name = 'purpose_features' class HistoryFeaturesQuery(BaseQuery): table_name", "return self.__cache_end_commit_id commit_id = None for pf in self.purpose_features: if", "features_dict = dict() for sf in self.size_features: features_dict[sf.commit_id] = dict()", "= sf.ld features_dict[sf.commit_id]['lt'] = sf.lt for df in self.diffusion_features: features_dict[df.commit_id]['ns']", "features_dict[df.commit_id]['ns'] = df.ns features_dict[df.commit_id]['nd'] = df.nd features_dict[df.commit_id]['nf'] = df.nf features_dict[df.commit_id]['entropy']", "in self.size_features: features_dict[sf.commit_id] = dict() features_dict[sf.commit_id]['la'] = sf.la features_dict[sf.commit_id]['ld'] =", "= pf.commit_id self.__cache_end_commit_id = commit_id return self.__cache_end_commit_id def combine(self): features_dict", "sf.la features_dict[sf.commit_id]['ld'] = sf.ld features_dict[sf.commit_id]['lt'] = sf.lt for df in", "= ef.exp features_dict[ef.commit_id]['rexp'] = ef.rexp features_dict[ef.commit_id]['sexp'] = ef.sexp ret_list =", "= ExperienceFeaturesQuery(project).do_query() self.__cache_end_commit_id = None @property def end_commit_id(self): if self.__cache_end_commit_id", "self.diffusion_features: features_dict[df.commit_id]['ns'] = df.ns features_dict[df.commit_id]['nd'] = df.nd features_dict[df.commit_id]['nf'] = df.nf", "in self.purpose_features: if pf.fix: commit_id = pf.commit_id self.__cache_end_commit_id = commit_id", "features_dict[sf.commit_id]['ld'] = sf.ld features_dict[sf.commit_id]['lt'] = sf.lt for df in self.diffusion_features:", "class DiffusionFeaturesQuery(BaseQuery): table_name = 'diffusion_features' class SizeFeaturesQuery(BaseQuery): table_name = 'size_features'", "None for pf in self.purpose_features: if pf.fix: commit_id = pf.commit_id", "if pf.fix: commit_id = pf.commit_id self.__cache_end_commit_id = commit_id return self.__cache_end_commit_id", "= features_dict[cm.commit_id] if len(cm_dict) == 14: cm_dict['commit_id'] = cm.commit_id ret_list.append(cm_dict)", "<gh_stars>10-100 from query.base import BaseQuery class CommitMetaQuery(BaseQuery): table_name = 'commit_meta'", "self.purpose_features: if pf.fix: commit_id = pf.commit_id self.__cache_end_commit_id = commit_id return", "self.__cache_end_commit_id = commit_id return self.__cache_end_commit_id def combine(self): features_dict = dict()", "pf in self.purpose_features: features_dict[pf.commit_id]['fix'] = pf.fix for hf in self.history_features:", "'commit_meta' class DiffusionFeaturesQuery(BaseQuery): table_name = 'diffusion_features' class SizeFeaturesQuery(BaseQuery): table_name =", "project): self.project = project self.cms = CommitMetaQuery(project).do_query() self.diffusion_features = DiffusionFeaturesQuery(project).do_query()", "commit_id = None for pf in self.purpose_features: if pf.fix: commit_id", "in self.cms: cm_dict = features_dict[cm.commit_id] if len(cm_dict) == 14: cm_dict['commit_id']", "= pf.fix for hf in self.history_features: features_dict[hf.commit_id]['ndev'] = hf.ndev features_dict[hf.commit_id]['age']", "= 'diffusion_features' class SizeFeaturesQuery(BaseQuery): table_name = 'size_features' class PurposeFeaturesQuery(BaseQuery): table_name", "pf.fix: commit_id = pf.commit_id self.__cache_end_commit_id = commit_id return self.__cache_end_commit_id def", "ExperienceFeaturesQuery(BaseQuery): table_name = 'experience_features' class ProjectQuery: def __init__(self, project): self.project", "self.__cache_end_commit_id commit_id = None for pf in self.purpose_features: if pf.fix:", "import BaseQuery class CommitMetaQuery(BaseQuery): table_name = 'commit_meta' class DiffusionFeaturesQuery(BaseQuery): table_name", "= ef.rexp features_dict[ef.commit_id]['sexp'] = ef.sexp ret_list = list() for cm", "return self.__cache_end_commit_id def combine(self): features_dict = dict() for sf in", "features_dict[ef.commit_id]['exp'] = ef.exp features_dict[ef.commit_id]['rexp'] = ef.rexp features_dict[ef.commit_id]['sexp'] = ef.sexp ret_list", "hf in self.history_features: features_dict[hf.commit_id]['ndev'] = hf.ndev features_dict[hf.commit_id]['age'] = hf.age features_dict[hf.commit_id]['nuc']", "PurposeFeaturesQuery(BaseQuery): table_name = 'purpose_features' class HistoryFeaturesQuery(BaseQuery): table_name = 'history_features' class", "self.history_features = HistoryFeaturesQuery(project).do_query() self.exp_features = ExperienceFeaturesQuery(project).do_query() self.__cache_end_commit_id = None @property", "df.nd features_dict[df.commit_id]['nf'] = df.nf features_dict[df.commit_id]['entropy'] = df.entropy for pf in", "CommitMetaQuery(BaseQuery): table_name = 'commit_meta' class DiffusionFeaturesQuery(BaseQuery): table_name = 'diffusion_features' class", "features_dict[df.commit_id]['entropy'] = df.entropy for pf in self.purpose_features: features_dict[pf.commit_id]['fix'] = pf.fix", "df.ns features_dict[df.commit_id]['nd'] = df.nd features_dict[df.commit_id]['nf'] = df.nf features_dict[df.commit_id]['entropy'] = df.entropy", "def end_commit_id(self): if self.__cache_end_commit_id is not None: return self.__cache_end_commit_id commit_id", "cm in self.cms: cm_dict = features_dict[cm.commit_id] if len(cm_dict) == 14:", "= 'history_features' class ExperienceFeaturesQuery(BaseQuery): table_name = 'experience_features' class ProjectQuery: def", "features_dict[df.commit_id]['nf'] = df.nf features_dict[df.commit_id]['entropy'] = df.entropy for pf in self.purpose_features:", "self.purpose_features: features_dict[pf.commit_id]['fix'] = pf.fix for hf in self.history_features: features_dict[hf.commit_id]['ndev'] =", "pf in self.purpose_features: if pf.fix: commit_id = pf.commit_id self.__cache_end_commit_id =", "__init__(self, project): self.project = project self.cms = CommitMetaQuery(project).do_query() self.diffusion_features =", "= hf.ndev features_dict[hf.commit_id]['age'] = hf.age features_dict[hf.commit_id]['nuc'] = hf.nuc for ef", "sf.ld features_dict[sf.commit_id]['lt'] = sf.lt for df in self.diffusion_features: features_dict[df.commit_id]['ns'] =", "dict() for sf in self.size_features: features_dict[sf.commit_id] = dict() features_dict[sf.commit_id]['la'] =", "self.cms = CommitMetaQuery(project).do_query() self.diffusion_features = DiffusionFeaturesQuery(project).do_query() self.size_features = SizeFeaturesQuery(project).do_query() self.purpose_features", "df.nf features_dict[df.commit_id]['entropy'] = df.entropy for pf in self.purpose_features: features_dict[pf.commit_id]['fix'] =", "= cm.commit_id ret_list.append(cm_dict) if cm.commit_id == self.end_commit_id: break return ret_list", "if len(cm_dict) == 14: cm_dict['commit_id'] = cm.commit_id ret_list.append(cm_dict) if cm.commit_id", "def __init__(self, project): self.project = project self.cms = CommitMetaQuery(project).do_query() self.diffusion_features", "features_dict[hf.commit_id]['age'] = hf.age features_dict[hf.commit_id]['nuc'] = hf.nuc for ef in self.exp_features:", "self.exp_features = ExperienceFeaturesQuery(project).do_query() self.__cache_end_commit_id = None @property def end_commit_id(self): if", "df.entropy for pf in self.purpose_features: features_dict[pf.commit_id]['fix'] = pf.fix for hf", "hf.ndev features_dict[hf.commit_id]['age'] = hf.age features_dict[hf.commit_id]['nuc'] = hf.nuc for ef in", "None @property def end_commit_id(self): if self.__cache_end_commit_id is not None: return", "ExperienceFeaturesQuery(project).do_query() self.__cache_end_commit_id = None @property def end_commit_id(self): if self.__cache_end_commit_id is", "PurposeFeaturesQuery(project).do_query() self.history_features = HistoryFeaturesQuery(project).do_query() self.exp_features = ExperienceFeaturesQuery(project).do_query() self.__cache_end_commit_id = None", "features_dict[pf.commit_id]['fix'] = pf.fix for hf in self.history_features: features_dict[hf.commit_id]['ndev'] = hf.ndev", "features_dict[sf.commit_id]['la'] = sf.la features_dict[sf.commit_id]['ld'] = sf.ld features_dict[sf.commit_id]['lt'] = sf.lt for", "= CommitMetaQuery(project).do_query() self.diffusion_features = DiffusionFeaturesQuery(project).do_query() self.size_features = SizeFeaturesQuery(project).do_query() self.purpose_features =", "in self.diffusion_features: features_dict[df.commit_id]['ns'] = df.ns features_dict[df.commit_id]['nd'] = df.nd features_dict[df.commit_id]['nf'] =", "features_dict[ef.commit_id]['sexp'] = ef.sexp ret_list = list() for cm in self.cms:", "= hf.nuc for ef in self.exp_features: features_dict[ef.commit_id]['exp'] = ef.exp features_dict[ef.commit_id]['rexp']", "self.cms: cm_dict = features_dict[cm.commit_id] if len(cm_dict) == 14: cm_dict['commit_id'] =", "= 'commit_meta' class DiffusionFeaturesQuery(BaseQuery): table_name = 'diffusion_features' class SizeFeaturesQuery(BaseQuery): table_name", "hf.age features_dict[hf.commit_id]['nuc'] = hf.nuc for ef in self.exp_features: features_dict[ef.commit_id]['exp'] =", "sf.lt for df in self.diffusion_features: features_dict[df.commit_id]['ns'] = df.ns features_dict[df.commit_id]['nd'] =", "DiffusionFeaturesQuery(project).do_query() self.size_features = SizeFeaturesQuery(project).do_query() self.purpose_features = PurposeFeaturesQuery(project).do_query() self.history_features = HistoryFeaturesQuery(project).do_query()", "features_dict[hf.commit_id]['nuc'] = hf.nuc for ef in self.exp_features: features_dict[ef.commit_id]['exp'] = ef.exp", "CommitMetaQuery(project).do_query() self.diffusion_features = DiffusionFeaturesQuery(project).do_query() self.size_features = SizeFeaturesQuery(project).do_query() self.purpose_features = PurposeFeaturesQuery(project).do_query()", "ef in self.exp_features: features_dict[ef.commit_id]['exp'] = ef.exp features_dict[ef.commit_id]['rexp'] = ef.rexp features_dict[ef.commit_id]['sexp']", "in self.history_features: features_dict[hf.commit_id]['ndev'] = hf.ndev features_dict[hf.commit_id]['age'] = hf.age features_dict[hf.commit_id]['nuc'] =", "'history_features' class ExperienceFeaturesQuery(BaseQuery): table_name = 'experience_features' class ProjectQuery: def __init__(self,", "features_dict[cm.commit_id] if len(cm_dict) == 14: cm_dict['commit_id'] = cm.commit_id ret_list.append(cm_dict) if", "BaseQuery class CommitMetaQuery(BaseQuery): table_name = 'commit_meta' class DiffusionFeaturesQuery(BaseQuery): table_name =", "ef.rexp features_dict[ef.commit_id]['sexp'] = ef.sexp ret_list = list() for cm in", "dict() features_dict[sf.commit_id]['la'] = sf.la features_dict[sf.commit_id]['ld'] = sf.ld features_dict[sf.commit_id]['lt'] = sf.lt", "self.__cache_end_commit_id = None @property def end_commit_id(self): if self.__cache_end_commit_id is not", "pf.commit_id self.__cache_end_commit_id = commit_id return self.__cache_end_commit_id def combine(self): features_dict =", "combine(self): features_dict = dict() for sf in self.size_features: features_dict[sf.commit_id] =", "self.size_features = SizeFeaturesQuery(project).do_query() self.purpose_features = PurposeFeaturesQuery(project).do_query() self.history_features = HistoryFeaturesQuery(project).do_query() self.exp_features", "table_name = 'history_features' class ExperienceFeaturesQuery(BaseQuery): table_name = 'experience_features' class ProjectQuery:", "table_name = 'purpose_features' class HistoryFeaturesQuery(BaseQuery): table_name = 'history_features' class ExperienceFeaturesQuery(BaseQuery):", "self.__cache_end_commit_id def combine(self): features_dict = dict() for sf in self.size_features:", "= sf.la features_dict[sf.commit_id]['ld'] = sf.ld features_dict[sf.commit_id]['lt'] = sf.lt for df", "features_dict[hf.commit_id]['ndev'] = hf.ndev features_dict[hf.commit_id]['age'] = hf.age features_dict[hf.commit_id]['nuc'] = hf.nuc for", "14: cm_dict['commit_id'] = cm.commit_id ret_list.append(cm_dict) if cm.commit_id == self.end_commit_id: break", "is not None: return self.__cache_end_commit_id commit_id = None for pf", "not None: return self.__cache_end_commit_id commit_id = None for pf in", "HistoryFeaturesQuery(project).do_query() self.exp_features = ExperienceFeaturesQuery(project).do_query() self.__cache_end_commit_id = None @property def end_commit_id(self):", "= PurposeFeaturesQuery(project).do_query() self.history_features = HistoryFeaturesQuery(project).do_query() self.exp_features = ExperienceFeaturesQuery(project).do_query() self.__cache_end_commit_id =", "df in self.diffusion_features: features_dict[df.commit_id]['ns'] = df.ns features_dict[df.commit_id]['nd'] = df.nd features_dict[df.commit_id]['nf']", "= 'purpose_features' class HistoryFeaturesQuery(BaseQuery): table_name = 'history_features' class ExperienceFeaturesQuery(BaseQuery): table_name", "self.purpose_features = PurposeFeaturesQuery(project).do_query() self.history_features = HistoryFeaturesQuery(project).do_query() self.exp_features = ExperienceFeaturesQuery(project).do_query() self.__cache_end_commit_id", "table_name = 'experience_features' class ProjectQuery: def __init__(self, project): self.project =", "self.diffusion_features = DiffusionFeaturesQuery(project).do_query() self.size_features = SizeFeaturesQuery(project).do_query() self.purpose_features = PurposeFeaturesQuery(project).do_query() self.history_features", "= project self.cms = CommitMetaQuery(project).do_query() self.diffusion_features = DiffusionFeaturesQuery(project).do_query() self.size_features =", "= sf.lt for df in self.diffusion_features: features_dict[df.commit_id]['ns'] = df.ns features_dict[df.commit_id]['nd']", "in self.exp_features: features_dict[ef.commit_id]['exp'] = ef.exp features_dict[ef.commit_id]['rexp'] = ef.rexp features_dict[ef.commit_id]['sexp'] =", "= DiffusionFeaturesQuery(project).do_query() self.size_features = SizeFeaturesQuery(project).do_query() self.purpose_features = PurposeFeaturesQuery(project).do_query() self.history_features =", "class ProjectQuery: def __init__(self, project): self.project = project self.cms =", "for pf in self.purpose_features: if pf.fix: commit_id = pf.commit_id self.__cache_end_commit_id" ]
[ "field.String() created_at = field.DateTime(read_only=True) class CharacterMapper(Mapper): __type__ = Character id", "__type__ = Character id = field.Integer(read_only=True) name = field.String() created_at", "= field.DateTime(read_only=True) class CharacterMapper(Mapper): __type__ = Character id = field.Integer(read_only=True)", "kim import Mapper, field from example.models import Planet, Character class", "field from example.models import Planet, Character class PlanetMapper(Mapper): __type__ =", "= Character id = field.Integer(read_only=True) name = field.String() created_at =", "Character class PlanetMapper(Mapper): __type__ = Planet id = field.Integer(read_only=True) name", "Character id = field.Integer(read_only=True) name = field.String() created_at = field.DateTime(read_only=True)", "Mapper, field from example.models import Planet, Character class PlanetMapper(Mapper): __type__", "Planet id = field.Integer(read_only=True) name = field.String() description = field.String()", "= field.Integer(read_only=True) name = field.String() description = field.String() created_at =", "description = field.String() created_at = field.DateTime(read_only=True) class CharacterMapper(Mapper): __type__ =", "PlanetMapper(Mapper): __type__ = Planet id = field.Integer(read_only=True) name = field.String()", "CharacterMapper(Mapper): __type__ = Character id = field.Integer(read_only=True) name = field.String()", "<reponame>mikeywaites/flask-arrested from kim import Mapper, field from example.models import Planet,", "from example.models import Planet, Character class PlanetMapper(Mapper): __type__ = Planet", "created_at = field.DateTime(read_only=True) class CharacterMapper(Mapper): __type__ = Character id =", "= Planet id = field.Integer(read_only=True) name = field.String() description =", "example.models import Planet, Character class PlanetMapper(Mapper): __type__ = Planet id", "= field.String() description = field.String() created_at = field.DateTime(read_only=True) class CharacterMapper(Mapper):", "field.String() description = field.String() created_at = field.DateTime(read_only=True) class CharacterMapper(Mapper): __type__", "Planet, Character class PlanetMapper(Mapper): __type__ = Planet id = field.Integer(read_only=True)", "= field.String() created_at = field.DateTime(read_only=True) class CharacterMapper(Mapper): __type__ = Character", "from kim import Mapper, field from example.models import Planet, Character", "id = field.Integer(read_only=True) name = field.String() description = field.String() created_at", "name = field.String() description = field.String() created_at = field.DateTime(read_only=True) class", "class PlanetMapper(Mapper): __type__ = Planet id = field.Integer(read_only=True) name =", "__type__ = Planet id = field.Integer(read_only=True) name = field.String() description", "import Planet, Character class PlanetMapper(Mapper): __type__ = Planet id =", "class CharacterMapper(Mapper): __type__ = Character id = field.Integer(read_only=True) name =", "import Mapper, field from example.models import Planet, Character class PlanetMapper(Mapper):", "field.DateTime(read_only=True) class CharacterMapper(Mapper): __type__ = Character id = field.Integer(read_only=True) name", "field.Integer(read_only=True) name = field.String() description = field.String() created_at = field.DateTime(read_only=True)" ]
[ "not in res: raise errors.AnsibleError(\"Minion %s didn't answer, check if", "remote to local \"\"\" super(Connection, self).fetch_file(in_path, out_path) in_path = self._normalize_path(in_path,", "sudoable=False, in_data=None): \"\"\" run a command on the remote minion", "the name of the product is salt, naming that module", "def _connect(self): if not HAVE_SALTSTACK: raise errors.AnsibleError(\"saltstack is not installed\")", "self._play_context.remote_addr def _connect(self): if not HAVE_SALTSTACK: raise errors.AnsibleError(\"saltstack is not", "+ cmd]) if self.host not in res: raise errors.AnsibleError(\"Minion %s", "%s didn't answer, check if salt-minion is running and the", "2014, <NAME> <<EMAIL>> # (c) 2017 Ansible Project # GNU", "self).fetch_file(in_path, out_path) in_path = self._normalize_path(in_path, '/') self._display.vvv(\"FETCH %s TO %s\"", "and the name is correct\" % self.host) p = res[self.host]", "\"\"\" transfer a file from local to remote \"\"\" super(Connection,", "self.client.cmd(self.host, 'cmd.exec_code_all', ['bash', 'true;' + cmd]) if self.host not in", "<NAME> <<EMAIL>> # (c) 2017 Ansible Project # GNU General", "if in_data: raise errors.AnsibleError(\"Internal Error: this module does not support", "raise errors.AnsibleError(\"Minion %s didn't answer, check if salt-minion is running", "errors from ansible.plugins.connection import ConnectionBase HAVE_SALTSTACK = False try: import", "salt, naming that module salt cause # trouble with module", "module salt cause # trouble with module import transport =", "answer, check if salt-minion is running and the name is", "(in_path, out_path), host=self.host) with open(in_path, 'rb') as in_fh: content =", "# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)", "DOCUMENTATION = ''' author: <NAME> (@mscherer) <<EMAIL>> name: saltstack short_description:", "the name is correct\" % self.host) p = res[self.host] return", "out_path), host=self.host) with open(in_path, 'rb') as in_fh: content = in_fh.read()", "sudoable=sudoable) if in_data: raise errors.AnsibleError(\"Internal Error: this module does not", "**kwargs) self.host = self._play_context.remote_addr def _connect(self): if not HAVE_SALTSTACK: raise", "module import transport = 'community.general.saltstack' def __init__(self, play_context, new_stdin, *args,", "as sc HAVE_SALTSTACK = True except ImportError: pass class Connection(ConnectionBase):", "errors.AnsibleError(\"Internal Error: this module does not support optimized module pipelining\")", "support optimized module pipelining\") self._display.vvv(\"EXEC %s\" % cmd, host=self.host) #", "[base64.b64encode(content), out_path]) # TODO test it def fetch_file(self, in_path, out_path):", "'wb').write(content) def close(self): \"\"\" terminate the connection; nothing to do", "from remote to local \"\"\" super(Connection, self).fetch_file(in_path, out_path) in_path =", "__metaclass__ = type DOCUMENTATION = ''' author: <NAME> (@mscherer) <<EMAIL>>", "self def exec_command(self, cmd, sudoable=False, in_data=None): \"\"\" run a command", "= self.client.cmd(self.host, 'cmd.exec_code_all', ['bash', 'true;' + cmd]) if self.host not", "HAVE_SALTSTACK = False try: import salt.client as sc HAVE_SALTSTACK =", "= os.path.join(os.path.sep, path) normpath = os.path.normpath(path) return os.path.join(prefix, normpath[1:]) def", "remote \"\"\" super(Connection, self).put_file(in_path, out_path) out_path = self._normalize_path(out_path, '/') self._display.vvv(\"PUT", "%s\" % (in_path, out_path), host=self.host) with open(in_path, 'rb') as in_fh:", "not HAVE_SALTSTACK: raise errors.AnsibleError(\"saltstack is not installed\") self.client = sc.LocalClient()", "<<EMAIL>> # Based on chroot.py (c) 2013, <NAME> <<EMAIL>> #", "Connection(ConnectionBase): \"\"\" Salt-based connections \"\"\" has_pipelining = False # while", "%s TO %s\" % (in_path, out_path), host=self.host) content = self.client.cmd(self.host,", "product is salt, naming that module salt cause # trouble", "put_file(self, in_path, out_path): \"\"\" transfer a file from local to", "ansible import errors from ansible.plugins.connection import ConnectionBase HAVE_SALTSTACK = False", "[in_path])[self.host] open(out_path, 'wb').write(content) def close(self): \"\"\" terminate the connection; nothing", "'/') self._display.vvv(\"FETCH %s TO %s\" % (in_path, out_path), host=self.host) content", "in_data=None): \"\"\" run a command on the remote minion \"\"\"", "*args, **kwargs): super(Connection, self).__init__(play_context, new_stdin, *args, **kwargs) self.host = self._play_context.remote_addr", "Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import", "self._normalize_path(in_path, '/') self._display.vvv(\"FETCH %s TO %s\" % (in_path, out_path), host=self.host)", "\"\"\" Salt-based connections \"\"\" has_pipelining = False # while the", "on local.py (c) 2012, <NAME> <<EMAIL>> # Based on chroot.py", "General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__", "module does not support optimized module pipelining\") self._display.vvv(\"EXEC %s\" %", "# while the name of the product is salt, naming", "'cmd.exec_code_all', ['bash', 'true;' + cmd]) if self.host not in res:", "check if salt-minion is running and the name is correct\"", "super(Connection, self).put_file(in_path, out_path) out_path = self._normalize_path(out_path, '/') self._display.vvv(\"PUT %s TO", "cause # trouble with module import transport = 'community.general.saltstack' def", "if self.host not in res: raise errors.AnsibleError(\"Minion %s didn't answer,", "''' author: <NAME> (@mscherer) <<EMAIL>> name: saltstack short_description: Allow ansible", "short_description: Allow ansible to piggyback on salt minions description: -", "correct\" % self.host) p = res[self.host] return p['retcode'], p['stdout'], p['stderr']", "with open(in_path, 'rb') as in_fh: content = in_fh.read() self.client.cmd(self.host, 'hashutil.base64_decodefile',", "raise errors.AnsibleError(\"saltstack is not installed\") self.client = sc.LocalClient() self._connected =", "remote minion \"\"\" super(Connection, self).exec_command(cmd, in_data=in_data, sudoable=sudoable) if in_data: raise", "the remote minion \"\"\" super(Connection, self).exec_command(cmd, in_data=in_data, sudoable=sudoable) if in_data:", "= self._normalize_path(in_path, '/') self._display.vvv(\"FETCH %s TO %s\" % (in_path, out_path),", "= type DOCUMENTATION = ''' author: <NAME> (@mscherer) <<EMAIL>> name:", "errors.AnsibleError(\"Minion %s didn't answer, check if salt-minion is running and", "\"\"\" super(Connection, self).put_file(in_path, out_path) out_path = self._normalize_path(out_path, '/') self._display.vvv(\"PUT %s", "salt-minion is running and the name is correct\" % self.host)", "super(Connection, self).fetch_file(in_path, out_path) in_path = self._normalize_path(in_path, '/') self._display.vvv(\"FETCH %s TO", "if salt-minion is running and the name is correct\" %", "p['retcode'], p['stdout'], p['stderr'] @staticmethod def _normalize_path(path, prefix): if not path.startswith(os.path.sep):", "except ImportError: pass class Connection(ConnectionBase): \"\"\" Salt-based connections \"\"\" has_pipelining", "# TODO test it def fetch_file(self, in_path, out_path): \"\"\" fetch", "host=self.host) content = self.client.cmd(self.host, 'cp.get_file_str', [in_path])[self.host] open(out_path, 'wb').write(content) def close(self):", "COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__", "TO %s\" % (in_path, out_path), host=self.host) with open(in_path, 'rb') as", "is correct\" % self.host) p = res[self.host] return p['retcode'], p['stdout'],", "add 'true;' to work around https://github.com/saltstack/salt/issues/28077 res = self.client.cmd(self.host, 'cmd.exec_code_all',", "fetch_file(self, in_path, out_path): \"\"\" fetch a file from remote to", "import transport = 'community.general.saltstack' def __init__(self, play_context, new_stdin, *args, **kwargs):", "raise errors.AnsibleError(\"Internal Error: this module does not support optimized module", "exec_command(self, cmd, sudoable=False, in_data=None): \"\"\" run a command on the", "transport = 'community.general.saltstack' def __init__(self, play_context, new_stdin, *args, **kwargs): super(Connection,", "host=self.host) # need to add 'true;' to work around https://github.com/saltstack/salt/issues/28077", "not path.startswith(os.path.sep): path = os.path.join(os.path.sep, path) normpath = os.path.normpath(path) return", "(@mscherer) <<EMAIL>> name: saltstack short_description: Allow ansible to piggyback on", "(c) 2012, <NAME> <<EMAIL>> # Based on chroot.py (c) 2013,", "infrastructure to connect to targets. ''' import os import base64", "# Based on chroot.py (c) 2013, <NAME> <<EMAIL>> # Based", "True return self def exec_command(self, cmd, sudoable=False, in_data=None): \"\"\" run", "= os.path.normpath(path) return os.path.join(prefix, normpath[1:]) def put_file(self, in_path, out_path): \"\"\"", "fetch a file from remote to local \"\"\" super(Connection, self).fetch_file(in_path,", "piggyback on salt minions description: - This allows you to", "= in_fh.read() self.client.cmd(self.host, 'hashutil.base64_decodefile', [base64.b64encode(content), out_path]) # TODO test it", "to connect to targets. ''' import os import base64 from", "that module salt cause # trouble with module import transport", "res: raise errors.AnsibleError(\"Minion %s didn't answer, check if salt-minion is", "content = self.client.cmd(self.host, 'cp.get_file_str', [in_path])[self.host] open(out_path, 'wb').write(content) def close(self): \"\"\"", "Error: this module does not support optimized module pipelining\") self._display.vvv(\"EXEC", "Project # GNU General Public License v3.0+ (see COPYING or", "this module does not support optimized module pipelining\") self._display.vvv(\"EXEC %s\"", "self._display.vvv(\"EXEC %s\" % cmd, host=self.host) # need to add 'true;'", "author: <NAME> (@mscherer) <<EMAIL>> name: saltstack short_description: Allow ansible to", "<NAME> <<EMAIL>> # Based on func.py # (c) 2014, <NAME>", "out_path) out_path = self._normalize_path(out_path, '/') self._display.vvv(\"PUT %s TO %s\" %", "cmd, host=self.host) # need to add 'true;' to work around", "self).exec_command(cmd, in_data=in_data, sudoable=sudoable) if in_data: raise errors.AnsibleError(\"Internal Error: this module", "running and the name is correct\" % self.host) p =", "out_path]) # TODO test it def fetch_file(self, in_path, out_path): \"\"\"", "play_context, new_stdin, *args, **kwargs): super(Connection, self).__init__(play_context, new_stdin, *args, **kwargs) self.host", "open(in_path, 'rb') as in_fh: content = in_fh.read() self.client.cmd(self.host, 'hashutil.base64_decodefile', [base64.b64encode(content),", "Salt-based connections \"\"\" has_pipelining = False # while the name", "in_data: raise errors.AnsibleError(\"Internal Error: this module does not support optimized", "as in_fh: content = in_fh.read() self.client.cmd(self.host, 'hashutil.base64_decodefile', [base64.b64encode(content), out_path]) #", "self._connected = True return self def exec_command(self, cmd, sudoable=False, in_data=None):", "in_fh.read() self.client.cmd(self.host, 'hashutil.base64_decodefile', [base64.b64encode(content), out_path]) # TODO test it def", "= ''' author: <NAME> (@mscherer) <<EMAIL>> name: saltstack short_description: Allow", "file from local to remote \"\"\" super(Connection, self).put_file(in_path, out_path) out_path", "os.path.normpath(path) return os.path.join(prefix, normpath[1:]) def put_file(self, in_path, out_path): \"\"\" transfer", "self.client.cmd(self.host, 'cp.get_file_str', [in_path])[self.host] open(out_path, 'wb').write(content) def close(self): \"\"\" terminate the", "self).put_file(in_path, out_path) out_path = self._normalize_path(out_path, '/') self._display.vvv(\"PUT %s TO %s\"", "in_path = self._normalize_path(in_path, '/') self._display.vvv(\"FETCH %s TO %s\" % (in_path,", "= self.client.cmd(self.host, 'cp.get_file_str', [in_path])[self.host] open(out_path, 'wb').write(content) def close(self): \"\"\" terminate", "HAVE_SALTSTACK = True except ImportError: pass class Connection(ConnectionBase): \"\"\" Salt-based", "# (c) 2014, <NAME> <<EMAIL>> # (c) 2017 Ansible Project", "\"\"\" terminate the connection; nothing to do here \"\"\" pass", "%s\" % cmd, host=self.host) # need to add 'true;' to", "use existing Saltstack infrastructure to connect to targets. ''' import", "Based on chroot.py (c) 2013, <NAME> <<EMAIL>> # Based on", "2017 Ansible Project # GNU General Public License v3.0+ (see", "ConnectionBase HAVE_SALTSTACK = False try: import salt.client as sc HAVE_SALTSTACK", "new_stdin, *args, **kwargs): super(Connection, self).__init__(play_context, new_stdin, *args, **kwargs) self.host =", "is running and the name is correct\" % self.host) p", "naming that module salt cause # trouble with module import", "or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ =", "False try: import salt.client as sc HAVE_SALTSTACK = True except", "ansible.plugins.connection import ConnectionBase HAVE_SALTSTACK = False try: import salt.client as", "open(out_path, 'wb').write(content) def close(self): \"\"\" terminate the connection; nothing to", "local \"\"\" super(Connection, self).fetch_file(in_path, out_path) in_path = self._normalize_path(in_path, '/') self._display.vvv(\"FETCH", "out_path) in_path = self._normalize_path(in_path, '/') self._display.vvv(\"FETCH %s TO %s\" %", "(see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function)", "from ansible import errors from ansible.plugins.connection import ConnectionBase HAVE_SALTSTACK =", "res[self.host] return p['retcode'], p['stdout'], p['stderr'] @staticmethod def _normalize_path(path, prefix): if", "existing Saltstack infrastructure to connect to targets. ''' import os", "% (in_path, out_path), host=self.host) with open(in_path, 'rb') as in_fh: content", "name of the product is salt, naming that module salt", "Allow ansible to piggyback on salt minions description: - This", "\"\"\" fetch a file from remote to local \"\"\" super(Connection,", "out_path = self._normalize_path(out_path, '/') self._display.vvv(\"PUT %s TO %s\" % (in_path,", "'cp.get_file_str', [in_path])[self.host] open(out_path, 'wb').write(content) def close(self): \"\"\" terminate the connection;", "path) normpath = os.path.normpath(path) return os.path.join(prefix, normpath[1:]) def put_file(self, in_path,", "= self._normalize_path(out_path, '/') self._display.vvv(\"PUT %s TO %s\" % (in_path, out_path),", "class Connection(ConnectionBase): \"\"\" Salt-based connections \"\"\" has_pipelining = False #", "def put_file(self, in_path, out_path): \"\"\" transfer a file from local", "Saltstack infrastructure to connect to targets. ''' import os import", "to add 'true;' to work around https://github.com/saltstack/salt/issues/28077 res = self.client.cmd(self.host,", "(in_path, out_path), host=self.host) content = self.client.cmd(self.host, 'cp.get_file_str', [in_path])[self.host] open(out_path, 'wb').write(content)", "True except ImportError: pass class Connection(ConnectionBase): \"\"\" Salt-based connections \"\"\"", "path.startswith(os.path.sep): path = os.path.join(os.path.sep, path) normpath = os.path.normpath(path) return os.path.join(prefix,", "func.py # (c) 2014, <NAME> <<EMAIL>> # (c) 2017 Ansible", "res = self.client.cmd(self.host, 'cmd.exec_code_all', ['bash', 'true;' + cmd]) if self.host", "host=self.host) with open(in_path, 'rb') as in_fh: content = in_fh.read() self.client.cmd(self.host,", "_normalize_path(path, prefix): if not path.startswith(os.path.sep): path = os.path.join(os.path.sep, path) normpath", "TO %s\" % (in_path, out_path), host=self.host) content = self.client.cmd(self.host, 'cp.get_file_str',", "= self._play_context.remote_addr def _connect(self): if not HAVE_SALTSTACK: raise errors.AnsibleError(\"saltstack is", "print_function) __metaclass__ = type DOCUMENTATION = ''' author: <NAME> (@mscherer)", "def fetch_file(self, in_path, out_path): \"\"\" fetch a file from remote", "# (c) 2017 Ansible Project # GNU General Public License", "(absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = ''' author:", "= True return self def exec_command(self, cmd, sudoable=False, in_data=None): \"\"\"", "it def fetch_file(self, in_path, out_path): \"\"\" fetch a file from", "2013, <NAME> <<EMAIL>> # Based on func.py # (c) 2014,", "in_fh: content = in_fh.read() self.client.cmd(self.host, 'hashutil.base64_decodefile', [base64.b64encode(content), out_path]) # TODO", "saltstack short_description: Allow ansible to piggyback on salt minions description:", "Based on func.py # (c) 2014, <NAME> <<EMAIL>> # (c)", "- This allows you to use existing Saltstack infrastructure to", "os import base64 from ansible import errors from ansible.plugins.connection import", "ImportError: pass class Connection(ConnectionBase): \"\"\" Salt-based connections \"\"\" has_pipelining =", "= True except ImportError: pass class Connection(ConnectionBase): \"\"\" Salt-based connections", "local to remote \"\"\" super(Connection, self).put_file(in_path, out_path) out_path = self._normalize_path(out_path,", "import ConnectionBase HAVE_SALTSTACK = False try: import salt.client as sc", "type DOCUMENTATION = ''' author: <NAME> (@mscherer) <<EMAIL>> name: saltstack", "def _normalize_path(path, prefix): if not path.startswith(os.path.sep): path = os.path.join(os.path.sep, path)", "salt.client as sc HAVE_SALTSTACK = True except ImportError: pass class", "has_pipelining = False # while the name of the product", "= False try: import salt.client as sc HAVE_SALTSTACK = True", "description: - This allows you to use existing Saltstack infrastructure", "\"\"\" has_pipelining = False # while the name of the", "self.host = self._play_context.remote_addr def _connect(self): if not HAVE_SALTSTACK: raise errors.AnsibleError(\"saltstack", "chroot.py (c) 2013, <NAME> <<EMAIL>> # Based on func.py #", "import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = '''", "connect to targets. ''' import os import base64 from ansible", "'true;' to work around https://github.com/saltstack/salt/issues/28077 res = self.client.cmd(self.host, 'cmd.exec_code_all', ['bash',", "return os.path.join(prefix, normpath[1:]) def put_file(self, in_path, out_path): \"\"\" transfer a", "= 'community.general.saltstack' def __init__(self, play_context, new_stdin, *args, **kwargs): super(Connection, self).__init__(play_context,", "division, print_function) __metaclass__ = type DOCUMENTATION = ''' author: <NAME>", "base64 from ansible import errors from ansible.plugins.connection import ConnectionBase HAVE_SALTSTACK", "*args, **kwargs) self.host = self._play_context.remote_addr def _connect(self): if not HAVE_SALTSTACK:", "**kwargs): super(Connection, self).__init__(play_context, new_stdin, *args, **kwargs) self.host = self._play_context.remote_addr def", "return p['retcode'], p['stdout'], p['stderr'] @staticmethod def _normalize_path(path, prefix): if not", "p['stdout'], p['stderr'] @staticmethod def _normalize_path(path, prefix): if not path.startswith(os.path.sep): path", "= False # while the name of the product is", "'/') self._display.vvv(\"PUT %s TO %s\" % (in_path, out_path), host=self.host) with", "new_stdin, *args, **kwargs) self.host = self._play_context.remote_addr def _connect(self): if not", "import base64 from ansible import errors from ansible.plugins.connection import ConnectionBase", "<<EMAIL>> # (c) 2017 Ansible Project # GNU General Public", "# Based on func.py # (c) 2014, <NAME> <<EMAIL>> #", "v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division,", "p['stderr'] @staticmethod def _normalize_path(path, prefix): if not path.startswith(os.path.sep): path =", "import os import base64 from ansible import errors from ansible.plugins.connection", "''' import os import base64 from ansible import errors from", "\"\"\" run a command on the remote minion \"\"\" super(Connection,", "<<EMAIL>> # Based on func.py # (c) 2014, <NAME> <<EMAIL>>", "# trouble with module import transport = 'community.general.saltstack' def __init__(self,", "https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type", "normpath[1:]) def put_file(self, in_path, out_path): \"\"\" transfer a file from", "work around https://github.com/saltstack/salt/issues/28077 res = self.client.cmd(self.host, 'cmd.exec_code_all', ['bash', 'true;' +", "= res[self.host] return p['retcode'], p['stdout'], p['stderr'] @staticmethod def _normalize_path(path, prefix):", "__future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION =", "self.client = sc.LocalClient() self._connected = True return self def exec_command(self,", "out_path): \"\"\" transfer a file from local to remote \"\"\"", "to piggyback on salt minions description: - This allows you", "import salt.client as sc HAVE_SALTSTACK = True except ImportError: pass", "pipelining\") self._display.vvv(\"EXEC %s\" % cmd, host=self.host) # need to add", "a file from remote to local \"\"\" super(Connection, self).fetch_file(in_path, out_path)", "minion \"\"\" super(Connection, self).exec_command(cmd, in_data=in_data, sudoable=sudoable) if in_data: raise errors.AnsibleError(\"Internal", "in_path, out_path): \"\"\" transfer a file from local to remote", "p = res[self.host] return p['retcode'], p['stdout'], p['stderr'] @staticmethod def _normalize_path(path,", "a command on the remote minion \"\"\" super(Connection, self).exec_command(cmd, in_data=in_data,", "super(Connection, self).__init__(play_context, new_stdin, *args, **kwargs) self.host = self._play_context.remote_addr def _connect(self):", "content = in_fh.read() self.client.cmd(self.host, 'hashutil.base64_decodefile', [base64.b64encode(content), out_path]) # TODO test", "transfer a file from local to remote \"\"\" super(Connection, self).put_file(in_path,", "# need to add 'true;' to work around https://github.com/saltstack/salt/issues/28077 res", "['bash', 'true;' + cmd]) if self.host not in res: raise", "optimized module pipelining\") self._display.vvv(\"EXEC %s\" % cmd, host=self.host) # need", "sc.LocalClient() self._connected = True return self def exec_command(self, cmd, sudoable=False,", "on func.py # (c) 2014, <NAME> <<EMAIL>> # (c) 2017", "os.path.join(os.path.sep, path) normpath = os.path.normpath(path) return os.path.join(prefix, normpath[1:]) def put_file(self,", "'community.general.saltstack' def __init__(self, play_context, new_stdin, *args, **kwargs): super(Connection, self).__init__(play_context, new_stdin,", "def exec_command(self, cmd, sudoable=False, in_data=None): \"\"\" run a command on", "minions description: - This allows you to use existing Saltstack", "on salt minions description: - This allows you to use", "cmd]) if self.host not in res: raise errors.AnsibleError(\"Minion %s didn't", "\"\"\" super(Connection, self).fetch_file(in_path, out_path) in_path = self._normalize_path(in_path, '/') self._display.vvv(\"FETCH %s", "allows you to use existing Saltstack infrastructure to connect to", "you to use existing Saltstack infrastructure to connect to targets.", "self._display.vvv(\"FETCH %s TO %s\" % (in_path, out_path), host=self.host) content =", "does not support optimized module pipelining\") self._display.vvv(\"EXEC %s\" % cmd,", "\"\"\" super(Connection, self).exec_command(cmd, in_data=in_data, sudoable=sudoable) if in_data: raise errors.AnsibleError(\"Internal Error:", "License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import,", "self).__init__(play_context, new_stdin, *args, **kwargs) self.host = self._play_context.remote_addr def _connect(self): if", "%s\" % (in_path, out_path), host=self.host) content = self.client.cmd(self.host, 'cp.get_file_str', [in_path])[self.host]", "% cmd, host=self.host) # need to add 'true;' to work", "'hashutil.base64_decodefile', [base64.b64encode(content), out_path]) # TODO test it def fetch_file(self, in_path,", "(c) 2017 Ansible Project # GNU General Public License v3.0+", "in res: raise errors.AnsibleError(\"Minion %s didn't answer, check if salt-minion", "not installed\") self.client = sc.LocalClient() self._connected = True return self", "https://github.com/saltstack/salt/issues/28077 res = self.client.cmd(self.host, 'cmd.exec_code_all', ['bash', 'true;' + cmd]) if", "cmd, sudoable=False, in_data=None): \"\"\" run a command on the remote", "salt cause # trouble with module import transport = 'community.general.saltstack'", "self.host) p = res[self.host] return p['retcode'], p['stdout'], p['stderr'] @staticmethod def", "not support optimized module pipelining\") self._display.vvv(\"EXEC %s\" % cmd, host=self.host)", "module pipelining\") self._display.vvv(\"EXEC %s\" % cmd, host=self.host) # need to", "in_data=in_data, sudoable=sudoable) if in_data: raise errors.AnsibleError(\"Internal Error: this module does", "# Based on local.py (c) 2012, <NAME> <<EMAIL>> # Based", "out_path): \"\"\" fetch a file from remote to local \"\"\"", "on chroot.py (c) 2013, <NAME> <<EMAIL>> # Based on func.py", "normpath = os.path.normpath(path) return os.path.join(prefix, normpath[1:]) def put_file(self, in_path, out_path):", "False # while the name of the product is salt,", "sc HAVE_SALTSTACK = True except ImportError: pass class Connection(ConnectionBase): \"\"\"", "need to add 'true;' to work around https://github.com/saltstack/salt/issues/28077 res =", "is salt, naming that module salt cause # trouble with", "<NAME> <<EMAIL>> # Based on chroot.py (c) 2013, <NAME> <<EMAIL>>", "from local to remote \"\"\" super(Connection, self).put_file(in_path, out_path) out_path =", "% (in_path, out_path), host=self.host) content = self.client.cmd(self.host, 'cp.get_file_str', [in_path])[self.host] open(out_path,", "2012, <NAME> <<EMAIL>> # Based on chroot.py (c) 2013, <NAME>", "<NAME> (@mscherer) <<EMAIL>> name: saltstack short_description: Allow ansible to piggyback", "__init__(self, play_context, new_stdin, *args, **kwargs): super(Connection, self).__init__(play_context, new_stdin, *args, **kwargs)", "out_path), host=self.host) content = self.client.cmd(self.host, 'cp.get_file_str', [in_path])[self.host] open(out_path, 'wb').write(content) def", "self.client.cmd(self.host, 'hashutil.base64_decodefile', [base64.b64encode(content), out_path]) # TODO test it def fetch_file(self,", "try: import salt.client as sc HAVE_SALTSTACK = True except ImportError:", "os.path.join(prefix, normpath[1:]) def put_file(self, in_path, out_path): \"\"\" transfer a file", "to targets. ''' import os import base64 from ansible import", "'rb') as in_fh: content = in_fh.read() self.client.cmd(self.host, 'hashutil.base64_decodefile', [base64.b64encode(content), out_path])", "This allows you to use existing Saltstack infrastructure to connect", "name: saltstack short_description: Allow ansible to piggyback on salt minions", "local.py (c) 2012, <NAME> <<EMAIL>> # Based on chroot.py (c)", "command on the remote minion \"\"\" super(Connection, self).exec_command(cmd, in_data=in_data, sudoable=sudoable)", "trouble with module import transport = 'community.general.saltstack' def __init__(self, play_context,", "return self def exec_command(self, cmd, sudoable=False, in_data=None): \"\"\" run a", "path = os.path.join(os.path.sep, path) normpath = os.path.normpath(path) return os.path.join(prefix, normpath[1:])", "def close(self): \"\"\" terminate the connection; nothing to do here", "with module import transport = 'community.general.saltstack' def __init__(self, play_context, new_stdin,", "TODO test it def fetch_file(self, in_path, out_path): \"\"\" fetch a", "super(Connection, self).exec_command(cmd, in_data=in_data, sudoable=sudoable) if in_data: raise errors.AnsibleError(\"Internal Error: this", "of the product is salt, naming that module salt cause", "@staticmethod def _normalize_path(path, prefix): if not path.startswith(os.path.sep): path = os.path.join(os.path.sep,", "salt minions description: - This allows you to use existing", "while the name of the product is salt, naming that", "name is correct\" % self.host) p = res[self.host] return p['retcode'],", "prefix): if not path.startswith(os.path.sep): path = os.path.join(os.path.sep, path) normpath =", "self._normalize_path(out_path, '/') self._display.vvv(\"PUT %s TO %s\" % (in_path, out_path), host=self.host)", "didn't answer, check if salt-minion is running and the name", "to work around https://github.com/saltstack/salt/issues/28077 res = self.client.cmd(self.host, 'cmd.exec_code_all', ['bash', 'true;'", "Based on local.py (c) 2012, <NAME> <<EMAIL>> # Based on", "= sc.LocalClient() self._connected = True return self def exec_command(self, cmd,", "errors.AnsibleError(\"saltstack is not installed\") self.client = sc.LocalClient() self._connected = True", "GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from", "_connect(self): if not HAVE_SALTSTACK: raise errors.AnsibleError(\"saltstack is not installed\") self.client", "HAVE_SALTSTACK: raise errors.AnsibleError(\"saltstack is not installed\") self.client = sc.LocalClient() self._connected", "%s TO %s\" % (in_path, out_path), host=self.host) with open(in_path, 'rb')", "self._display.vvv(\"PUT %s TO %s\" % (in_path, out_path), host=self.host) with open(in_path,", "to use existing Saltstack infrastructure to connect to targets. '''", "if not path.startswith(os.path.sep): path = os.path.join(os.path.sep, path) normpath = os.path.normpath(path)", "around https://github.com/saltstack/salt/issues/28077 res = self.client.cmd(self.host, 'cmd.exec_code_all', ['bash', 'true;' + cmd])", "on the remote minion \"\"\" super(Connection, self).exec_command(cmd, in_data=in_data, sudoable=sudoable) if", "ansible to piggyback on salt minions description: - This allows", "'true;' + cmd]) if self.host not in res: raise errors.AnsibleError(\"Minion", "run a command on the remote minion \"\"\" super(Connection, self).exec_command(cmd,", "(c) 2013, <NAME> <<EMAIL>> # Based on func.py # (c)", "in_path, out_path): \"\"\" fetch a file from remote to local", "% self.host) p = res[self.host] return p['retcode'], p['stdout'], p['stderr'] @staticmethod", "self.host not in res: raise errors.AnsibleError(\"Minion %s didn't answer, check", "Ansible Project # GNU General Public License v3.0+ (see COPYING", "from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION", "a file from local to remote \"\"\" super(Connection, self).put_file(in_path, out_path)", "<<EMAIL>> name: saltstack short_description: Allow ansible to piggyback on salt", "if not HAVE_SALTSTACK: raise errors.AnsibleError(\"saltstack is not installed\") self.client =", "connections \"\"\" has_pipelining = False # while the name of", "(c) 2014, <NAME> <<EMAIL>> # (c) 2017 Ansible Project #", "is not installed\") self.client = sc.LocalClient() self._connected = True return", "pass class Connection(ConnectionBase): \"\"\" Salt-based connections \"\"\" has_pipelining = False", "the product is salt, naming that module salt cause #", "close(self): \"\"\" terminate the connection; nothing to do here \"\"\"", "to local \"\"\" super(Connection, self).fetch_file(in_path, out_path) in_path = self._normalize_path(in_path, '/')", "from ansible.plugins.connection import ConnectionBase HAVE_SALTSTACK = False try: import salt.client", "installed\") self.client = sc.LocalClient() self._connected = True return self def", "file from remote to local \"\"\" super(Connection, self).fetch_file(in_path, out_path) in_path", "import errors from ansible.plugins.connection import ConnectionBase HAVE_SALTSTACK = False try:", "targets. ''' import os import base64 from ansible import errors", "def __init__(self, play_context, new_stdin, *args, **kwargs): super(Connection, self).__init__(play_context, new_stdin, *args,", "test it def fetch_file(self, in_path, out_path): \"\"\" fetch a file", "to remote \"\"\" super(Connection, self).put_file(in_path, out_path) out_path = self._normalize_path(out_path, '/')" ]
[ "libvirtError from vrtManager.create import wvmCreate from vrtManager import util from", "msg = _(\"A virtual machine with this name already exists\")", "== 'POST': if 'create_flavor' in request.POST: form = FlavorAddForm(request.POST) if", "create.forms import FlavorAddForm, NewVMForm def create(request, host_id): \"\"\" Create new", "as msg_error: errors.append(msg_error.message) elif data['template']: templ_path = conn.get_volume_path(data['template']) clone_path =", "uuid, volumes, data['networks'], data['virtio'], data['mac']) create_instance = Instance(compute_id=host_id, name=data['name'], uuid=uuid)", "with this name already exists\") errors.append(msg) if not errors: if", "RequestContext from django.utils.translation import ugettext_lazy as _ from servers.models import", "django.utils.translation import ugettext_lazy as _ from servers.models import Compute from", "_(\"You haven't defined have any storage pools\") errors.append(msg) if not", "defined have any storage pools\") errors.append(msg) if not networks: msg", "try: path = conn.create_volume(data['storage'], data['name'], data['hdd_size']) volumes[path] = conn.get_volume_type(path) except", "return HttpResponseRedirect(request.get_full_path()) if 'create' in request.POST: volumes = {} form", "= conn.get_volume_path(data['template']) clone_path = conn.clone_from_template(data['name'], templ_path) volumes[clone_path] = conn.get_volume_type(clone_path) else:", "from servers.models import Compute from create.models import Flavor from instance.models", "% (host_id, data['name'])) except libvirtError as msg_error: if data['hdd_size']: conn.delete_volume(volumes.keys()[0])", "errors = [] compute = Compute.objects.get(id=host_id) flavors = Flavor.objects.filter().order_by('id') try:", "vrtManager import util from create.forms import FlavorAddForm, NewVMForm def create(request,", "= [] compute = Compute.objects.get(id=host_id) flavors = Flavor.objects.filter().order_by('id') try: conn", "data['virtio'], data['mac']) create_instance = Instance(compute_id=host_id, name=data['name'], uuid=uuid) create_instance.save() return HttpResponseRedirect('/instance/%s/%s/'", "HttpResponseRedirect('/instance/%s/%s/' % (host_id, data['name'])) except libvirtError as msg_error: if data['hdd_size']:", "if data['hdd_size']: if not data['mac']: msg = _(\"No Virtual Machine", "if not storages: msg = _(\"You haven't defined have any", "= util.randomUUID() try: conn.create_instance(data['name'], data['memory'], data['vcpu'], data['host_model'], uuid, volumes, data['networks'],", "volumes = {} form = NewVMForm(request.POST) if form.is_valid(): data =", "except libvirtError as err: errors.append(err.message) if not storages: msg =", "from instance.models import Instance from libvirt import libvirtError from vrtManager.create", "= conn.get_instances() get_images = sorted(conn.get_storages_images()) mac_auto = util.randomMAC() except libvirtError", "msg = _(\"You haven't defined have any storage pools\") errors.append(msg)", "= wvmCreate(compute.hostname, compute.login, compute.password, compute.type) storages = sorted(conn.get_storages()) networks =", "libvirtError as err: errors.append(err.message) if not storages: msg = _(\"You", "disk=data['disk']) create_flavor.save() return HttpResponseRedirect(request.get_full_path()) if 'delete_flavor' in request.POST: flavor_id =", "if form.is_valid(): data = form.cleaned_data if instances: if data['name'] in", "data['name'])) except libvirtError as msg_error: if data['hdd_size']: conn.delete_volume(volumes.keys()[0]) errors.append(msg_error.message) conn.close()", "= conn.get_volume_path(vol) volumes[path] = conn.get_volume_type(path) except libvirtError as msg_error: errors.append(msg_error.message)", "except libvirtError as msg_error: errors.append(msg_error.message) if not errors: uuid =", "form = FlavorAddForm(request.POST) if form.is_valid(): data = form.cleaned_data create_flavor =", "ugettext_lazy as _ from servers.models import Compute from create.models import", "libvirt import libvirtError from vrtManager.create import wvmCreate from vrtManager import", "delete_flavor = Flavor.objects.get(id=flavor_id) delete_flavor.delete() return HttpResponseRedirect(request.get_full_path()) if 'create' in request.POST:", "import wvmCreate from vrtManager import util from create.forms import FlavorAddForm,", "errors.append(msg) else: try: path = conn.create_volume(data['storage'], data['name'], data['hdd_size']) volumes[path] =", "import HttpResponseRedirect from django.template import RequestContext from django.utils.translation import ugettext_lazy", "msg = _(\"You haven't defined have any network pools\") errors.append(msg)", "form.cleaned_data create_flavor = Flavor(label=data['label'], vcpu=data['vcpu'], memory=data['memory'], disk=data['disk']) create_flavor.save() return HttpResponseRedirect(request.get_full_path())", "compute.type) storages = sorted(conn.get_storages()) networks = sorted(conn.get_networks()) instances = conn.get_instances()", "in request.POST: form = FlavorAddForm(request.POST) if form.is_valid(): data = form.cleaned_data", "if data['name'] in instances: msg = _(\"A virtual machine with", "from django.template import RequestContext from django.utils.translation import ugettext_lazy as _", "data['host_model'], uuid, volumes, data['networks'], data['virtio'], data['mac']) create_instance = Instance(compute_id=host_id, name=data['name'],", "Instance(compute_id=host_id, name=data['name'], uuid=uuid) create_instance.save() return HttpResponseRedirect('/instance/%s/%s/' % (host_id, data['name'])) except", "this name already exists\") errors.append(msg) if not errors: if data['hdd_size']:", "name=data['name'], uuid=uuid) create_instance.save() return HttpResponseRedirect('/instance/%s/%s/' % (host_id, data['name'])) except libvirtError", "data = form.cleaned_data create_flavor = Flavor(label=data['label'], vcpu=data['vcpu'], memory=data['memory'], disk=data['disk']) create_flavor.save()", "return HttpResponseRedirect(request.get_full_path()) if 'delete_flavor' in request.POST: flavor_id = request.POST.get('flavor', '')", "create_flavor.save() return HttpResponseRedirect(request.get_full_path()) if 'delete_flavor' in request.POST: flavor_id = request.POST.get('flavor',", "haven't defined have any storage pools\") errors.append(msg) if not networks:", "form.cleaned_data if instances: if data['name'] in instances: msg = _(\"A", "util.randomUUID() try: conn.create_instance(data['name'], data['memory'], data['vcpu'], data['host_model'], uuid, volumes, data['networks'], data['virtio'],", "django.template import RequestContext from django.utils.translation import ugettext_lazy as _ from", "_(\"A virtual machine with this name already exists\") errors.append(msg) if", "if not errors: if data['hdd_size']: if not data['mac']: msg =", "pools\") errors.append(msg) if not networks: msg = _(\"You haven't defined", "Machine MAC has been entered\") errors.append(msg) else: try: path =", "import ugettext_lazy as _ from servers.models import Compute from create.models", "import Compute from create.models import Flavor from instance.models import Instance", "Virtual Machine MAC has been entered\") errors.append(msg) else: try: path", "data = form.cleaned_data if instances: if data['name'] in instances: msg", "if not errors: uuid = util.randomUUID() try: conn.create_instance(data['name'], data['memory'], data['vcpu'],", "instance.models import Instance from libvirt import libvirtError from vrtManager.create import", "_(\"First you need to create or select an image\") errors.append(msg)", "= sorted(conn.get_storages_images()) mac_auto = util.randomMAC() except libvirtError as err: errors.append(err.message)", "storages = sorted(conn.get_storages()) networks = sorted(conn.get_networks()) instances = conn.get_instances() get_images", "vrtManager.create import wvmCreate from vrtManager import util from create.forms import", "Instance from libvirt import libvirtError from vrtManager.create import wvmCreate from", "'POST': if 'create_flavor' in request.POST: form = FlavorAddForm(request.POST) if form.is_valid():", "instances: msg = _(\"A virtual machine with this name already", "image\") errors.append(msg) else: for vol in data['images'].split(','): try: path =", "form = NewVMForm(request.POST) if form.is_valid(): data = form.cleaned_data if instances:", "data['images']: msg = _(\"First you need to create or select", "conn.get_volume_path(vol) volumes[path] = conn.get_volume_type(path) except libvirtError as msg_error: errors.append(msg_error.message) if", "host_id): \"\"\" Create new instance. \"\"\" if not request.user.is_authenticated(): return", "instances = conn.get_instances() get_images = sorted(conn.get_storages_images()) mac_auto = util.randomMAC() except", "data['hdd_size']: if not data['mac']: msg = _(\"No Virtual Machine MAC", "= Flavor(label=data['label'], vcpu=data['vcpu'], memory=data['memory'], disk=data['disk']) create_flavor.save() return HttpResponseRedirect(request.get_full_path()) if 'delete_flavor'", "import render_to_response from django.http import HttpResponseRedirect from django.template import RequestContext", "NewVMForm(request.POST) if form.is_valid(): data = form.cleaned_data if instances: if data['name']", "(host_id, data['name'])) except libvirtError as msg_error: if data['hdd_size']: conn.delete_volume(volumes.keys()[0]) errors.append(msg_error.message)", "libvirtError as msg_error: if data['hdd_size']: conn.delete_volume(volumes.keys()[0]) errors.append(msg_error.message) conn.close() return render_to_response('create.html',", "wvmCreate from vrtManager import util from create.forms import FlavorAddForm, NewVMForm", "in request.POST: flavor_id = request.POST.get('flavor', '') delete_flavor = Flavor.objects.get(id=flavor_id) delete_flavor.delete()", "import RequestContext from django.utils.translation import ugettext_lazy as _ from servers.models", "conn.create_instance(data['name'], data['memory'], data['vcpu'], data['host_model'], uuid, volumes, data['networks'], data['virtio'], data['mac']) create_instance", "create or select an image\") errors.append(msg) else: for vol in", "compute.password, compute.type) storages = sorted(conn.get_storages()) networks = sorted(conn.get_networks()) instances =", "'create_flavor' in request.POST: form = FlavorAddForm(request.POST) if form.is_valid(): data =", "= FlavorAddForm(request.POST) if form.is_valid(): data = form.cleaned_data create_flavor = Flavor(label=data['label'],", "haven't defined have any network pools\") errors.append(msg) if request.method ==", "msg_error: errors.append(msg_error.message) if not errors: uuid = util.randomUUID() try: conn.create_instance(data['name'],", "= Compute.objects.get(id=host_id) flavors = Flavor.objects.filter().order_by('id') try: conn = wvmCreate(compute.hostname, compute.login,", "err: errors.append(err.message) if not storages: msg = _(\"You haven't defined", "'create' in request.POST: volumes = {} form = NewVMForm(request.POST) if", "you need to create or select an image\") errors.append(msg) else:", "need to create or select an image\") errors.append(msg) else: for", "volumes, data['networks'], data['virtio'], data['mac']) create_instance = Instance(compute_id=host_id, name=data['name'], uuid=uuid) create_instance.save()", "errors: if data['hdd_size']: if not data['mac']: msg = _(\"No Virtual", "= conn.get_volume_type(clone_path) else: if not data['images']: msg = _(\"First you", "from vrtManager.create import wvmCreate from vrtManager import util from create.forms", "as _ from servers.models import Compute from create.models import Flavor", "[] compute = Compute.objects.get(id=host_id) flavors = Flavor.objects.filter().order_by('id') try: conn =", "conn.get_instances() get_images = sorted(conn.get_storages_images()) mac_auto = util.randomMAC() except libvirtError as", "mac_auto = util.randomMAC() except libvirtError as err: errors.append(err.message) if not", "data['name'], data['hdd_size']) volumes[path] = conn.get_volume_type(path) except libvirtError as msg_error: errors.append(msg_error.message)", "else: for vol in data['images'].split(','): try: path = conn.get_volume_path(vol) volumes[path]", "path = conn.get_volume_path(vol) volumes[path] = conn.get_volume_type(path) except libvirtError as msg_error:", "= _(\"You haven't defined have any network pools\") errors.append(msg) if", "except libvirtError as msg_error: errors.append(msg_error.message) elif data['template']: templ_path = conn.get_volume_path(data['template'])", "from django.shortcuts import render_to_response from django.http import HttpResponseRedirect from django.template", "sorted(conn.get_networks()) instances = conn.get_instances() get_images = sorted(conn.get_storages_images()) mac_auto = util.randomMAC()", "conn.get_volume_path(data['template']) clone_path = conn.clone_from_template(data['name'], templ_path) volumes[clone_path] = conn.get_volume_type(clone_path) else: if", "from libvirt import libvirtError from vrtManager.create import wvmCreate from vrtManager", "= _(\"You haven't defined have any storage pools\") errors.append(msg) if", "if not networks: msg = _(\"You haven't defined have any", "from vrtManager import util from create.forms import FlavorAddForm, NewVMForm def", "flavors = Flavor.objects.filter().order_by('id') try: conn = wvmCreate(compute.hostname, compute.login, compute.password, compute.type)", "errors: uuid = util.randomUUID() try: conn.create_instance(data['name'], data['memory'], data['vcpu'], data['host_model'], uuid,", "FlavorAddForm(request.POST) if form.is_valid(): data = form.cleaned_data create_flavor = Flavor(label=data['label'], vcpu=data['vcpu'],", "not request.user.is_authenticated(): return HttpResponseRedirect('/login') errors = [] compute = Compute.objects.get(id=host_id)", "request.POST: form = FlavorAddForm(request.POST) if form.is_valid(): data = form.cleaned_data create_flavor", "form.is_valid(): data = form.cleaned_data create_flavor = Flavor(label=data['label'], vcpu=data['vcpu'], memory=data['memory'], disk=data['disk'])", "if request.method == 'POST': if 'create_flavor' in request.POST: form =", "HttpResponseRedirect(request.get_full_path()) if 'delete_flavor' in request.POST: flavor_id = request.POST.get('flavor', '') delete_flavor", "import FlavorAddForm, NewVMForm def create(request, host_id): \"\"\" Create new instance.", "request.user.is_authenticated(): return HttpResponseRedirect('/login') errors = [] compute = Compute.objects.get(id=host_id) flavors", "if 'delete_flavor' in request.POST: flavor_id = request.POST.get('flavor', '') delete_flavor =", "in data['images'].split(','): try: path = conn.get_volume_path(vol) volumes[path] = conn.get_volume_type(path) except", "= sorted(conn.get_storages()) networks = sorted(conn.get_networks()) instances = conn.get_instances() get_images =", "\"\"\" Create new instance. \"\"\" if not request.user.is_authenticated(): return HttpResponseRedirect('/login')", "sorted(conn.get_storages_images()) mac_auto = util.randomMAC() except libvirtError as err: errors.append(err.message) if", "import Flavor from instance.models import Instance from libvirt import libvirtError", "an image\") errors.append(msg) else: for vol in data['images'].split(','): try: path", "machine with this name already exists\") errors.append(msg) if not errors:", "errors.append(msg) else: for vol in data['images'].split(','): try: path = conn.get_volume_path(vol)", "as err: errors.append(err.message) if not storages: msg = _(\"You haven't", "= Flavor.objects.get(id=flavor_id) delete_flavor.delete() return HttpResponseRedirect(request.get_full_path()) if 'create' in request.POST: volumes", "create_flavor = Flavor(label=data['label'], vcpu=data['vcpu'], memory=data['memory'], disk=data['disk']) create_flavor.save() return HttpResponseRedirect(request.get_full_path()) if", "data['vcpu'], data['host_model'], uuid, volumes, data['networks'], data['virtio'], data['mac']) create_instance = Instance(compute_id=host_id,", "templ_path) volumes[clone_path] = conn.get_volume_type(clone_path) else: if not data['images']: msg =", "= _(\"First you need to create or select an image\")", "django.http import HttpResponseRedirect from django.template import RequestContext from django.utils.translation import", "= form.cleaned_data if instances: if data['name'] in instances: msg =", "if form.is_valid(): data = form.cleaned_data create_flavor = Flavor(label=data['label'], vcpu=data['vcpu'], memory=data['memory'],", "request.POST: volumes = {} form = NewVMForm(request.POST) if form.is_valid(): data", "conn.create_volume(data['storage'], data['name'], data['hdd_size']) volumes[path] = conn.get_volume_type(path) except libvirtError as msg_error:", "virtual machine with this name already exists\") errors.append(msg) if not", "not errors: uuid = util.randomUUID() try: conn.create_instance(data['name'], data['memory'], data['vcpu'], data['host_model'],", "pools\") errors.append(msg) if request.method == 'POST': if 'create_flavor' in request.POST:", "conn.get_volume_type(clone_path) else: if not data['images']: msg = _(\"First you need", "elif data['template']: templ_path = conn.get_volume_path(data['template']) clone_path = conn.clone_from_template(data['name'], templ_path) volumes[clone_path]", "conn.get_volume_type(path) except libvirtError as msg_error: errors.append(msg_error.message) if not errors: uuid", "_ from servers.models import Compute from create.models import Flavor from", "data['networks'], data['virtio'], data['mac']) create_instance = Instance(compute_id=host_id, name=data['name'], uuid=uuid) create_instance.save() return", "libvirtError as msg_error: errors.append(msg_error.message) elif data['template']: templ_path = conn.get_volume_path(data['template']) clone_path", "return HttpResponseRedirect('/login') errors = [] compute = Compute.objects.get(id=host_id) flavors =", "\"\"\" if not request.user.is_authenticated(): return HttpResponseRedirect('/login') errors = [] compute", "from django.http import HttpResponseRedirect from django.template import RequestContext from django.utils.translation", "= sorted(conn.get_networks()) instances = conn.get_instances() get_images = sorted(conn.get_storages_images()) mac_auto =", "errors.append(msg) if not errors: if data['hdd_size']: if not data['mac']: msg", "= {} form = NewVMForm(request.POST) if form.is_valid(): data = form.cleaned_data", "if not data['images']: msg = _(\"First you need to create", "create(request, host_id): \"\"\" Create new instance. \"\"\" if not request.user.is_authenticated():", "data['memory'], data['vcpu'], data['host_model'], uuid, volumes, data['networks'], data['virtio'], data['mac']) create_instance =", "_(\"You haven't defined have any network pools\") errors.append(msg) if request.method", "import libvirtError from vrtManager.create import wvmCreate from vrtManager import util", "if 'create' in request.POST: volumes = {} form = NewVMForm(request.POST)", "memory=data['memory'], disk=data['disk']) create_flavor.save() return HttpResponseRedirect(request.get_full_path()) if 'delete_flavor' in request.POST: flavor_id", "try: path = conn.get_volume_path(vol) volumes[path] = conn.get_volume_type(path) except libvirtError as", "request.method == 'POST': if 'create_flavor' in request.POST: form = FlavorAddForm(request.POST)", "delete_flavor.delete() return HttpResponseRedirect(request.get_full_path()) if 'create' in request.POST: volumes = {}", "new instance. \"\"\" if not request.user.is_authenticated(): return HttpResponseRedirect('/login') errors =", "= Flavor.objects.filter().order_by('id') try: conn = wvmCreate(compute.hostname, compute.login, compute.password, compute.type) storages", "exists\") errors.append(msg) if not errors: if data['hdd_size']: if not data['mac']:", "= util.randomMAC() except libvirtError as err: errors.append(err.message) if not storages:", "conn.get_volume_type(path) except libvirtError as msg_error: errors.append(msg_error.message) elif data['template']: templ_path =", "errors.append(msg) if request.method == 'POST': if 'create_flavor' in request.POST: form", "msg = _(\"No Virtual Machine MAC has been entered\") errors.append(msg)", "from create.forms import FlavorAddForm, NewVMForm def create(request, host_id): \"\"\" Create", "get_images = sorted(conn.get_storages_images()) mac_auto = util.randomMAC() except libvirtError as err:", "storages: msg = _(\"You haven't defined have any storage pools\")", "= conn.get_volume_type(path) except libvirtError as msg_error: errors.append(msg_error.message) if not errors:", "been entered\") errors.append(msg) else: try: path = conn.create_volume(data['storage'], data['name'], data['hdd_size'])", "errors.append(msg) if not networks: msg = _(\"You haven't defined have", "already exists\") errors.append(msg) if not errors: if data['hdd_size']: if not", "data['template']: templ_path = conn.get_volume_path(data['template']) clone_path = conn.clone_from_template(data['name'], templ_path) volumes[clone_path] =", "uuid=uuid) create_instance.save() return HttpResponseRedirect('/instance/%s/%s/' % (host_id, data['name'])) except libvirtError as", "Create new instance. \"\"\" if not request.user.is_authenticated(): return HttpResponseRedirect('/login') errors", "create.models import Flavor from instance.models import Instance from libvirt import", "= form.cleaned_data create_flavor = Flavor(label=data['label'], vcpu=data['vcpu'], memory=data['memory'], disk=data['disk']) create_flavor.save() return", "instance. \"\"\" if not request.user.is_authenticated(): return HttpResponseRedirect('/login') errors = []", "= _(\"A virtual machine with this name already exists\") errors.append(msg)", "data['images'].split(','): try: path = conn.get_volume_path(vol) volumes[path] = conn.get_volume_type(path) except libvirtError", "data['name'] in instances: msg = _(\"A virtual machine with this", "import util from create.forms import FlavorAddForm, NewVMForm def create(request, host_id):", "networks: msg = _(\"You haven't defined have any network pools\")", "try: conn.create_instance(data['name'], data['memory'], data['vcpu'], data['host_model'], uuid, volumes, data['networks'], data['virtio'], data['mac'])", "try: conn = wvmCreate(compute.hostname, compute.login, compute.password, compute.type) storages = sorted(conn.get_storages())", "have any storage pools\") errors.append(msg) if not networks: msg =", "storage pools\") errors.append(msg) if not networks: msg = _(\"You haven't", "for vol in data['images'].split(','): try: path = conn.get_volume_path(vol) volumes[path] =", "return HttpResponseRedirect('/instance/%s/%s/' % (host_id, data['name'])) except libvirtError as msg_error: if", "conn.clone_from_template(data['name'], templ_path) volumes[clone_path] = conn.get_volume_type(clone_path) else: if not data['images']: msg", "libvirtError as msg_error: errors.append(msg_error.message) if not errors: uuid = util.randomUUID()", "flavor_id = request.POST.get('flavor', '') delete_flavor = Flavor.objects.get(id=flavor_id) delete_flavor.delete() return HttpResponseRedirect(request.get_full_path())", "errors.append(msg_error.message) elif data['template']: templ_path = conn.get_volume_path(data['template']) clone_path = conn.clone_from_template(data['name'], templ_path)", "errors.append(msg_error.message) if not errors: uuid = util.randomUUID() try: conn.create_instance(data['name'], data['memory'],", "instances: if data['name'] in instances: msg = _(\"A virtual machine", "create_instance = Instance(compute_id=host_id, name=data['name'], uuid=uuid) create_instance.save() return HttpResponseRedirect('/instance/%s/%s/' % (host_id,", "HttpResponseRedirect('/login') errors = [] compute = Compute.objects.get(id=host_id) flavors = Flavor.objects.filter().order_by('id')", "any network pools\") errors.append(msg) if request.method == 'POST': if 'create_flavor'", "form.is_valid(): data = form.cleaned_data if instances: if data['name'] in instances:", "Flavor.objects.get(id=flavor_id) delete_flavor.delete() return HttpResponseRedirect(request.get_full_path()) if 'create' in request.POST: volumes =", "templ_path = conn.get_volume_path(data['template']) clone_path = conn.clone_from_template(data['name'], templ_path) volumes[clone_path] = conn.get_volume_type(clone_path)", "data['mac']: msg = _(\"No Virtual Machine MAC has been entered\")", "from create.models import Flavor from instance.models import Instance from libvirt", "NewVMForm def create(request, host_id): \"\"\" Create new instance. \"\"\" if", "= conn.create_volume(data['storage'], data['name'], data['hdd_size']) volumes[path] = conn.get_volume_type(path) except libvirtError as", "entered\") errors.append(msg) else: try: path = conn.create_volume(data['storage'], data['name'], data['hdd_size']) volumes[path]", "Compute.objects.get(id=host_id) flavors = Flavor.objects.filter().order_by('id') try: conn = wvmCreate(compute.hostname, compute.login, compute.password,", "Flavor.objects.filter().order_by('id') try: conn = wvmCreate(compute.hostname, compute.login, compute.password, compute.type) storages =", "compute.login, compute.password, compute.type) storages = sorted(conn.get_storages()) networks = sorted(conn.get_networks()) instances", "'delete_flavor' in request.POST: flavor_id = request.POST.get('flavor', '') delete_flavor = Flavor.objects.get(id=flavor_id)", "msg_error: errors.append(msg_error.message) elif data['template']: templ_path = conn.get_volume_path(data['template']) clone_path = conn.clone_from_template(data['name'],", "not errors: if data['hdd_size']: if not data['mac']: msg = _(\"No", "else: if not data['images']: msg = _(\"First you need to", "util from create.forms import FlavorAddForm, NewVMForm def create(request, host_id): \"\"\"", "if not data['mac']: msg = _(\"No Virtual Machine MAC has", "MAC has been entered\") errors.append(msg) else: try: path = conn.create_volume(data['storage'],", "msg_error: if data['hdd_size']: conn.delete_volume(volumes.keys()[0]) errors.append(msg_error.message) conn.close() return render_to_response('create.html', locals(), context_instance=RequestContext(request))", "request.POST: flavor_id = request.POST.get('flavor', '') delete_flavor = Flavor.objects.get(id=flavor_id) delete_flavor.delete() return", "= NewVMForm(request.POST) if form.is_valid(): data = form.cleaned_data if instances: if", "servers.models import Compute from create.models import Flavor from instance.models import", "data['hdd_size']) volumes[path] = conn.get_volume_type(path) except libvirtError as msg_error: errors.append(msg_error.message) elif", "in request.POST: volumes = {} form = NewVMForm(request.POST) if form.is_valid():", "= conn.clone_from_template(data['name'], templ_path) volumes[clone_path] = conn.get_volume_type(clone_path) else: if not data['images']:", "any storage pools\") errors.append(msg) if not networks: msg = _(\"You", "Flavor from instance.models import Instance from libvirt import libvirtError from", "name already exists\") errors.append(msg) if not errors: if data['hdd_size']: if", "as msg_error: errors.append(msg_error.message) if not errors: uuid = util.randomUUID() try:", "= request.POST.get('flavor', '') delete_flavor = Flavor.objects.get(id=flavor_id) delete_flavor.delete() return HttpResponseRedirect(request.get_full_path()) if", "msg = _(\"First you need to create or select an", "if instances: if data['name'] in instances: msg = _(\"A virtual", "data['mac']) create_instance = Instance(compute_id=host_id, name=data['name'], uuid=uuid) create_instance.save() return HttpResponseRedirect('/instance/%s/%s/' %", "not networks: msg = _(\"You haven't defined have any network", "select an image\") errors.append(msg) else: for vol in data['images'].split(','): try:", "else: try: path = conn.create_volume(data['storage'], data['name'], data['hdd_size']) volumes[path] = conn.get_volume_type(path)", "sorted(conn.get_storages()) networks = sorted(conn.get_networks()) instances = conn.get_instances() get_images = sorted(conn.get_storages_images())", "not data['mac']: msg = _(\"No Virtual Machine MAC has been", "wvmCreate(compute.hostname, compute.login, compute.password, compute.type) storages = sorted(conn.get_storages()) networks = sorted(conn.get_networks())", "volumes[path] = conn.get_volume_type(path) except libvirtError as msg_error: errors.append(msg_error.message) elif data['template']:", "networks = sorted(conn.get_networks()) instances = conn.get_instances() get_images = sorted(conn.get_storages_images()) mac_auto", "create_instance.save() return HttpResponseRedirect('/instance/%s/%s/' % (host_id, data['name'])) except libvirtError as msg_error:", "volumes[clone_path] = conn.get_volume_type(clone_path) else: if not data['images']: msg = _(\"First", "HttpResponseRedirect from django.template import RequestContext from django.utils.translation import ugettext_lazy as", "_(\"No Virtual Machine MAC has been entered\") errors.append(msg) else: try:", "def create(request, host_id): \"\"\" Create new instance. \"\"\" if not", "have any network pools\") errors.append(msg) if request.method == 'POST': if", "= _(\"No Virtual Machine MAC has been entered\") errors.append(msg) else:", "errors.append(err.message) if not storages: msg = _(\"You haven't defined have", "from django.utils.translation import ugettext_lazy as _ from servers.models import Compute", "conn = wvmCreate(compute.hostname, compute.login, compute.password, compute.type) storages = sorted(conn.get_storages()) networks", "defined have any network pools\") errors.append(msg) if request.method == 'POST':", "FlavorAddForm, NewVMForm def create(request, host_id): \"\"\" Create new instance. \"\"\"", "vcpu=data['vcpu'], memory=data['memory'], disk=data['disk']) create_flavor.save() return HttpResponseRedirect(request.get_full_path()) if 'delete_flavor' in request.POST:", "as msg_error: if data['hdd_size']: conn.delete_volume(volumes.keys()[0]) errors.append(msg_error.message) conn.close() return render_to_response('create.html', locals(),", "if 'create_flavor' in request.POST: form = FlavorAddForm(request.POST) if form.is_valid(): data", "render_to_response from django.http import HttpResponseRedirect from django.template import RequestContext from", "has been entered\") errors.append(msg) else: try: path = conn.create_volume(data['storage'], data['name'],", "clone_path = conn.clone_from_template(data['name'], templ_path) volumes[clone_path] = conn.get_volume_type(clone_path) else: if not", "Flavor(label=data['label'], vcpu=data['vcpu'], memory=data['memory'], disk=data['disk']) create_flavor.save() return HttpResponseRedirect(request.get_full_path()) if 'delete_flavor' in", "if not request.user.is_authenticated(): return HttpResponseRedirect('/login') errors = [] compute =", "not storages: msg = _(\"You haven't defined have any storage", "vol in data['images'].split(','): try: path = conn.get_volume_path(vol) volumes[path] = conn.get_volume_type(path)", "'') delete_flavor = Flavor.objects.get(id=flavor_id) delete_flavor.delete() return HttpResponseRedirect(request.get_full_path()) if 'create' in", "network pools\") errors.append(msg) if request.method == 'POST': if 'create_flavor' in", "volumes[path] = conn.get_volume_type(path) except libvirtError as msg_error: errors.append(msg_error.message) if not", "or select an image\") errors.append(msg) else: for vol in data['images'].split(','):", "= Instance(compute_id=host_id, name=data['name'], uuid=uuid) create_instance.save() return HttpResponseRedirect('/instance/%s/%s/' % (host_id, data['name']))", "compute = Compute.objects.get(id=host_id) flavors = Flavor.objects.filter().order_by('id') try: conn = wvmCreate(compute.hostname,", "to create or select an image\") errors.append(msg) else: for vol", "import Instance from libvirt import libvirtError from vrtManager.create import wvmCreate", "{} form = NewVMForm(request.POST) if form.is_valid(): data = form.cleaned_data if", "in instances: msg = _(\"A virtual machine with this name", "= conn.get_volume_type(path) except libvirtError as msg_error: errors.append(msg_error.message) elif data['template']: templ_path", "django.shortcuts import render_to_response from django.http import HttpResponseRedirect from django.template import", "uuid = util.randomUUID() try: conn.create_instance(data['name'], data['memory'], data['vcpu'], data['host_model'], uuid, volumes,", "except libvirtError as msg_error: if data['hdd_size']: conn.delete_volume(volumes.keys()[0]) errors.append(msg_error.message) conn.close() return", "not data['images']: msg = _(\"First you need to create or", "Compute from create.models import Flavor from instance.models import Instance from", "request.POST.get('flavor', '') delete_flavor = Flavor.objects.get(id=flavor_id) delete_flavor.delete() return HttpResponseRedirect(request.get_full_path()) if 'create'", "HttpResponseRedirect(request.get_full_path()) if 'create' in request.POST: volumes = {} form =", "path = conn.create_volume(data['storage'], data['name'], data['hdd_size']) volumes[path] = conn.get_volume_type(path) except libvirtError", "util.randomMAC() except libvirtError as err: errors.append(err.message) if not storages: msg" ]
[ "1, 1) alpha = alpha.expand(real_data.size()).to(device) interpolates = alpha * real_data", "torch.rand(batch_size, 1, 1, 1) alpha = alpha.expand(real_data.size()).to(device) interpolates = alpha", "inputs=interpolates, grad_outputs=torch.ones(disc_interpolates.size()).to(device), create_graph=True, retain_graph=True, only_inputs=True)[0] gradient_penalty = ((gradients.norm(2) - 1)", "grad_outputs=torch.ones(disc_interpolates.size()).to(device), create_graph=True, retain_graph=True, only_inputs=True)[0] gradient_penalty = ((gradients.norm(2) - 1) **", "= discriminator(interpolates) gradients = torch.autograd.grad(outputs=disc_interpolates, inputs=interpolates, grad_outputs=torch.ones(disc_interpolates.size()).to(device), create_graph=True, retain_graph=True, only_inputs=True)[0]", "def calc_gradient_penalty_bayes(discriminator, real_data, fake_data, gamma): device = torch.device(\"cuda\" if torch.cuda.is_available()", "1) alpha = alpha.expand(real_data.size()).to(device) interpolates = alpha * real_data +", "= torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") batch_size = real_data.size()[0] alpha", "alpha = torch.rand(batch_size, 1, 1, 1) alpha = alpha.expand(real_data.size()).to(device) interpolates", "= torch.rand(batch_size, 1, 1, 1) alpha = alpha.expand(real_data.size()).to(device) interpolates =", "real_data + ((1 - alpha) * fake_data) interpolates = torch.autograd.Variable(interpolates,", "((1 - alpha) * fake_data) interpolates = torch.autograd.Variable(interpolates, requires_grad=True).to(device) disc_interpolates", "disc_interpolates = discriminator(interpolates) gradients = torch.autograd.grad(outputs=disc_interpolates, inputs=interpolates, grad_outputs=torch.ones(disc_interpolates.size()).to(device), create_graph=True, retain_graph=True,", "gamma): device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") batch_size =", "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") batch_size = real_data.size()[0]", "= alpha.expand(real_data.size()).to(device) interpolates = alpha * real_data + ((1 -", "fake_data, gamma): device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") batch_size", "gradients = torch.autograd.grad(outputs=disc_interpolates, inputs=interpolates, grad_outputs=torch.ones(disc_interpolates.size()).to(device), create_graph=True, retain_graph=True, only_inputs=True)[0] gradient_penalty =", "alpha.expand(real_data.size()).to(device) interpolates = alpha * real_data + ((1 - alpha)", "torch.autograd.Variable(interpolates, requires_grad=True).to(device) disc_interpolates = discriminator(interpolates) gradients = torch.autograd.grad(outputs=disc_interpolates, inputs=interpolates, grad_outputs=torch.ones(disc_interpolates.size()).to(device),", "calc_gradient_penalty_bayes(discriminator, real_data, fake_data, gamma): device = torch.device(\"cuda\" if torch.cuda.is_available() else", "only_inputs=True)[0] gradient_penalty = ((gradients.norm(2) - 1) ** 2) * gamma", "requires_grad=True).to(device) disc_interpolates = discriminator(interpolates) gradients = torch.autograd.grad(outputs=disc_interpolates, inputs=interpolates, grad_outputs=torch.ones(disc_interpolates.size()).to(device), create_graph=True,", "if torch.cuda.is_available() else \"cpu\") batch_size = real_data.size()[0] alpha = torch.rand(batch_size,", "real_data.size()[0] alpha = torch.rand(batch_size, 1, 1, 1) alpha = alpha.expand(real_data.size()).to(device)", "else \"cpu\") batch_size = real_data.size()[0] alpha = torch.rand(batch_size, 1, 1,", "interpolates = torch.autograd.Variable(interpolates, requires_grad=True).to(device) disc_interpolates = discriminator(interpolates) gradients = torch.autograd.grad(outputs=disc_interpolates,", "'Andres' def calc_gradient_penalty_bayes(discriminator, real_data, fake_data, gamma): device = torch.device(\"cuda\" if", "1, 1, 1) alpha = alpha.expand(real_data.size()).to(device) interpolates = alpha *", "create_graph=True, retain_graph=True, only_inputs=True)[0] gradient_penalty = ((gradients.norm(2) - 1) ** 2)", "real_data, fake_data, gamma): device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")", "torch __author__ = 'Andres' def calc_gradient_penalty_bayes(discriminator, real_data, fake_data, gamma): device", "__author__ = 'Andres' def calc_gradient_penalty_bayes(discriminator, real_data, fake_data, gamma): device =", "\"cpu\") batch_size = real_data.size()[0] alpha = torch.rand(batch_size, 1, 1, 1)", "import torch __author__ = 'Andres' def calc_gradient_penalty_bayes(discriminator, real_data, fake_data, gamma):", "alpha) * fake_data) interpolates = torch.autograd.Variable(interpolates, requires_grad=True).to(device) disc_interpolates = discriminator(interpolates)", "interpolates = alpha * real_data + ((1 - alpha) *", "* real_data + ((1 - alpha) * fake_data) interpolates =", "= 'Andres' def calc_gradient_penalty_bayes(discriminator, real_data, fake_data, gamma): device = torch.device(\"cuda\"", "torch.autograd.grad(outputs=disc_interpolates, inputs=interpolates, grad_outputs=torch.ones(disc_interpolates.size()).to(device), create_graph=True, retain_graph=True, only_inputs=True)[0] gradient_penalty = ((gradients.norm(2) -", "= real_data.size()[0] alpha = torch.rand(batch_size, 1, 1, 1) alpha =", "= torch.autograd.Variable(interpolates, requires_grad=True).to(device) disc_interpolates = discriminator(interpolates) gradients = torch.autograd.grad(outputs=disc_interpolates, inputs=interpolates,", "discriminator(interpolates) gradients = torch.autograd.grad(outputs=disc_interpolates, inputs=interpolates, grad_outputs=torch.ones(disc_interpolates.size()).to(device), create_graph=True, retain_graph=True, only_inputs=True)[0] gradient_penalty", "fake_data) interpolates = torch.autograd.Variable(interpolates, requires_grad=True).to(device) disc_interpolates = discriminator(interpolates) gradients =", "torch.cuda.is_available() else \"cpu\") batch_size = real_data.size()[0] alpha = torch.rand(batch_size, 1,", "= alpha * real_data + ((1 - alpha) * fake_data)", "alpha * real_data + ((1 - alpha) * fake_data) interpolates", "gradient_penalty = ((gradients.norm(2) - 1) ** 2) * gamma return", "= ((gradients.norm(2) - 1) ** 2) * gamma return gradient_penalty", "* fake_data) interpolates = torch.autograd.Variable(interpolates, requires_grad=True).to(device) disc_interpolates = discriminator(interpolates) gradients", "+ ((1 - alpha) * fake_data) interpolates = torch.autograd.Variable(interpolates, requires_grad=True).to(device)", "- alpha) * fake_data) interpolates = torch.autograd.Variable(interpolates, requires_grad=True).to(device) disc_interpolates =", "= torch.autograd.grad(outputs=disc_interpolates, inputs=interpolates, grad_outputs=torch.ones(disc_interpolates.size()).to(device), create_graph=True, retain_graph=True, only_inputs=True)[0] gradient_penalty = ((gradients.norm(2)", "retain_graph=True, only_inputs=True)[0] gradient_penalty = ((gradients.norm(2) - 1) ** 2) *", "batch_size = real_data.size()[0] alpha = torch.rand(batch_size, 1, 1, 1) alpha", "torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") batch_size = real_data.size()[0] alpha =", "alpha = alpha.expand(real_data.size()).to(device) interpolates = alpha * real_data + ((1" ]
[ "<reponame>butla/experiments import a_file def test_a(capsys): assert a_file.bla() == 5 assert", "a_file def test_a(capsys): assert a_file.bla() == 5 assert a_file.LOG_MESSAGE in", "def test_a(capsys): assert a_file.bla() == 5 assert a_file.LOG_MESSAGE in capsys.readouterr().err", "import a_file def test_a(capsys): assert a_file.bla() == 5 assert a_file.LOG_MESSAGE" ]
[ "as st from ui.session_state import SessionState, get_state from infer import", "SessionState): st.header(\"identify\") state = get_state() if state.model.stage < ModelStage.DEFINED: st.error(\"Please", "show(state: SessionState): st.header(\"identify\") state = get_state() if state.model.stage < ModelStage.DEFINED:", "from ui.session_state import SessionState, get_state from infer import ModelStage def", "ModelStage def show(state: SessionState): st.header(\"identify\") state = get_state() if state.model.stage", "ui.session_state import SessionState, get_state from infer import ModelStage def show(state:", "import SessionState, get_state from infer import ModelStage def show(state: SessionState):", "st from ui.session_state import SessionState, get_state from infer import ModelStage", "= get_state() if state.model.stage < ModelStage.DEFINED: st.error(\"Please create the model", "from infer import ModelStage def show(state: SessionState): st.header(\"identify\") state =", "import streamlit as st from ui.session_state import SessionState, get_state from", "streamlit as st from ui.session_state import SessionState, get_state from infer", "infer import ModelStage def show(state: SessionState): st.header(\"identify\") state = get_state()", "get_state() if state.model.stage < ModelStage.DEFINED: st.error(\"Please create the model first!\")", "st.header(\"identify\") state = get_state() if state.model.stage < ModelStage.DEFINED: st.error(\"Please create", "def show(state: SessionState): st.header(\"identify\") state = get_state() if state.model.stage <", "state = get_state() if state.model.stage < ModelStage.DEFINED: st.error(\"Please create the", "import ModelStage def show(state: SessionState): st.header(\"identify\") state = get_state() if", "<reponame>Magier/Aetia import streamlit as st from ui.session_state import SessionState, get_state", "SessionState, get_state from infer import ModelStage def show(state: SessionState): st.header(\"identify\")", "get_state from infer import ModelStage def show(state: SessionState): st.header(\"identify\") state" ]
[ "CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF", "entity_remapping, relation_remapping def compile_universe_dataset(self, triple_constraint, balance_param, relation_in_focus): self.lib.getParallelUniverse(triple_constraint, balance_param, relation_in_focus)", "this permission notice shall be included in all copies or", "MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO", "import TrainDataLoader class UniverseTrainDataLoader(TrainDataLoader): def __init__(self, in_path=\"./\", batch_size=None, nbatches=None, threads=8,", "ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64 ]", "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell", "self.lib.getRelationRemapping.argtypes = [ ctypes.c_void_p ] self.lib.getEntityTotalUniverse.restype = ctypes.c_int64 self.lib.getRelationTotalUniverse.restype =", "self.lib.getEntityRemapping(entity_remapping_addr) self.lib.getRelationRemapping(relation_remapping_addr) return entity_remapping, relation_remapping def compile_universe_dataset(self, triple_constraint, balance_param, relation_in_focus):", "CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN", "the Software, and to permit persons to whom the Software", "bern_flag=bern_flag, filter_flag=filter_flag, neg_ent=neg_ent, neg_rel=neg_rel, initial_random_seed=initial_random_seed) self.entity_total_universe = 0 self.relation_total_universe =", "= np.zeros(self.relation_total_universe, dtype=np.int64) entity_remapping_addr = entity_remapping.__array_interface__[\"data\"][0] relation_remapping_addr = relation_remapping.__array_interface__[\"data\"][0] self.lib.getEntityRemapping(entity_remapping_addr)", "from .TrainDataLoader import TrainDataLoader class UniverseTrainDataLoader(TrainDataLoader): def __init__(self, in_path=\"./\", batch_size=None,", "and associated documentation files (the \"Software\"), to deal in the", "above copyright notice and this permission notice shall be included", "substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS", "ctypes.c_int64, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64 ] self.lib.getParallelUniverse.argtypes = [ ctypes.c_int64,", "notice shall be included in all copies or substantial portions", "A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE", "neg_rel=0, initial_random_seed=2): super(UniverseTrainDataLoader, self).__init__(in_path=in_path, batch_size=batch_size, nbatches=nbatches, threads=threads, sampling_mode=sampling_mode, bern_flag=bern_flag, filter_flag=filter_flag,", "ctypes.c_int64 self.lib.getRelationTotalUniverse.restype = ctypes.c_int64 self.lib.getTrainTotalUniverse.restype = ctypes.c_int64 def swap_helpers(self): self.lib.swapHelpers()", "in_path=\"./\", batch_size=None, nbatches=None, threads=8, sampling_mode=\"normal\", bern_flag=0, filter_flag=1, neg_ent=1, neg_rel=0, initial_random_seed=2):", "self.lib.getParallelUniverse(triple_constraint, balance_param, relation_in_focus) self.entity_total_universe = self.lib.getEntityTotalUniverse() self.relation_total_universe = self.lib.getRelationTotalUniverse() self.train_total_universe", "= ctypes.c_int64 self.lib.getRelationTotalUniverse.restype = ctypes.c_int64 self.lib.getTrainTotalUniverse.restype = ctypes.c_int64 def swap_helpers(self):", "USE OR OTHER DEALINGS IN THE SOFTWARE. ''' import os", "the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY", "to whom the Software is furnished to do so, subject", "import ctypes import numpy as np from .TrainDataLoader import TrainDataLoader", "nbatches=nbatches, threads=threads, sampling_mode=sampling_mode, bern_flag=bern_flag, filter_flag=filter_flag, neg_ent=neg_ent, neg_rel=neg_rel, initial_random_seed=initial_random_seed) self.entity_total_universe =", "bern_flag=0, filter_flag=1, neg_ent=1, neg_rel=0, initial_random_seed=2): super(UniverseTrainDataLoader, self).__init__(in_path=in_path, batch_size=batch_size, nbatches=nbatches, threads=threads,", "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT", "threads=threads, sampling_mode=sampling_mode, bern_flag=bern_flag, filter_flag=filter_flag, neg_ent=neg_ent, neg_rel=neg_rel, initial_random_seed=initial_random_seed) self.entity_total_universe = 0", "= 0 self.relation_total_universe = 0 self.train_total_universe = 0 \"\"\"argtypes\"\"\" self.lib.sampling.argtypes", "(c) 2020 <NAME> Permission is hereby granted, free of charge,", "entity_remapping.__array_interface__[\"data\"][0] relation_remapping_addr = relation_remapping.__array_interface__[\"data\"][0] self.lib.getEntityRemapping(entity_remapping_addr) self.lib.getRelationRemapping(relation_remapping_addr) return entity_remapping, relation_remapping def", "\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,", "the following conditions: The above copyright notice and this permission", "= [ ctypes.c_int64, ctypes.c_float, ctypes.c_int64 ] self.lib.getEntityRemapping.argtypes = [ ctypes.c_void_p", "files (the \"Software\"), to deal in the Software without restriction,", "relation_remapping = np.zeros(self.relation_total_universe, dtype=np.int64) entity_remapping_addr = entity_remapping.__array_interface__[\"data\"][0] relation_remapping_addr = relation_remapping.__array_interface__[\"data\"][0]", "self.lib.getEntityRemapping.argtypes = [ ctypes.c_void_p ] self.lib.getRelationRemapping.argtypes = [ ctypes.c_void_p ]", ".TrainDataLoader import TrainDataLoader class UniverseTrainDataLoader(TrainDataLoader): def __init__(self, in_path=\"./\", batch_size=None, nbatches=None,", "ctypes.c_int64, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64 ] self.lib.getParallelUniverse.argtypes = [ ctypes.c_int64, ctypes.c_float,", "ctypes.c_int64 ] self.lib.getEntityRemapping.argtypes = [ ctypes.c_void_p ] self.lib.getRelationRemapping.argtypes = [", "= ctypes.c_int64 def swap_helpers(self): self.lib.swapHelpers() def reset_universe(self): self.lib.resetUniverse() self.set_nbatches(self.lib.getTrainTotal, self.nbatches)", "filter_flag=filter_flag, neg_ent=neg_ent, neg_rel=neg_rel, initial_random_seed=initial_random_seed) self.entity_total_universe = 0 self.relation_total_universe = 0", "ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF", "self.lib.getEntityTotalUniverse.restype = ctypes.c_int64 self.lib.getRelationTotalUniverse.restype = ctypes.c_int64 self.lib.getTrainTotalUniverse.restype = ctypes.c_int64 def", "IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING", "WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT", "KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE", "is furnished to do so, subject to the following conditions:", "__init__(self, in_path=\"./\", batch_size=None, nbatches=None, threads=8, sampling_mode=\"normal\", bern_flag=0, filter_flag=1, neg_ent=1, neg_rel=0,", "the rights to use, copy, modify, merge, publish, distribute, sublicense,", "ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64,", "ctypes.c_int64 ] self.lib.getParallelUniverse.argtypes = [ ctypes.c_int64, ctypes.c_float, ctypes.c_int64 ] self.lib.getEntityRemapping.argtypes", "self.set_nbatches(self.lib.getTrainTotal, self.nbatches) def get_universe_mappings(self): entity_remapping = np.zeros(self.entity_total_universe, dtype=np.int64) relation_remapping =", "TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE", "License Copyright (c) 2020 <NAME> Permission is hereby granted, free", "software and associated documentation files (the \"Software\"), to deal in", "= [ ctypes.c_void_p ] self.lib.getEntityTotalUniverse.restype = ctypes.c_int64 self.lib.getRelationTotalUniverse.restype = ctypes.c_int64", "to any person obtaining a copy of this software and", "ctypes.c_float, ctypes.c_int64 ] self.lib.getEntityRemapping.argtypes = [ ctypes.c_void_p ] self.lib.getRelationRemapping.argtypes =", "balance_param, relation_in_focus) self.entity_total_universe = self.lib.getEntityTotalUniverse() self.relation_total_universe = self.lib.getRelationTotalUniverse() self.train_total_universe =", "[ ctypes.c_int64, ctypes.c_float, ctypes.c_int64 ] self.lib.getEntityRemapping.argtypes = [ ctypes.c_void_p ]", "relation_in_focus): self.lib.getParallelUniverse(triple_constraint, balance_param, relation_in_focus) self.entity_total_universe = self.lib.getEntityTotalUniverse() self.relation_total_universe = self.lib.getRelationTotalUniverse()", "entity_remapping_addr = entity_remapping.__array_interface__[\"data\"][0] relation_remapping_addr = relation_remapping.__array_interface__[\"data\"][0] self.lib.getEntityRemapping(entity_remapping_addr) self.lib.getRelationRemapping(relation_remapping_addr) return entity_remapping,", "notice and this permission notice shall be included in all", "of the Software, and to permit persons to whom the", "this software and associated documentation files (the \"Software\"), to deal", "def compile_universe_dataset(self, triple_constraint, balance_param, relation_in_focus): self.lib.getParallelUniverse(triple_constraint, balance_param, relation_in_focus) self.entity_total_universe =", "dtype=np.int64) relation_remapping = np.zeros(self.relation_total_universe, dtype=np.int64) entity_remapping_addr = entity_remapping.__array_interface__[\"data\"][0] relation_remapping_addr =", "is hereby granted, free of charge, to any person obtaining", "ctypes.c_int64 def swap_helpers(self): self.lib.swapHelpers() def reset_universe(self): self.lib.resetUniverse() self.set_nbatches(self.lib.getTrainTotal, self.nbatches) def", "ctypes.c_int64, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64 ] self.lib.getParallelUniverse.argtypes =", "relation_remapping.__array_interface__[\"data\"][0] self.lib.getEntityRemapping(entity_remapping_addr) self.lib.getRelationRemapping(relation_remapping_addr) return entity_remapping, relation_remapping def compile_universe_dataset(self, triple_constraint, balance_param,", "import numpy as np from .TrainDataLoader import TrainDataLoader class UniverseTrainDataLoader(TrainDataLoader):", "triple_constraint, balance_param, relation_in_focus): self.lib.getParallelUniverse(triple_constraint, balance_param, relation_in_focus) self.entity_total_universe = self.lib.getEntityTotalUniverse() self.relation_total_universe", "shall be included in all copies or substantial portions of", "Copyright (c) 2020 <NAME> Permission is hereby granted, free of", "person obtaining a copy of this software and associated documentation", "0 self.relation_total_universe = 0 self.train_total_universe = 0 \"\"\"argtypes\"\"\" self.lib.sampling.argtypes =", "OTHER DEALINGS IN THE SOFTWARE. ''' import os import ctypes", "all copies or substantial portions of the Software. THE SOFTWARE", "FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN", "SOFTWARE. ''' import os import ctypes import numpy as np", "ctypes.c_void_p, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64 ] self.lib.getParallelUniverse.argtypes", "ctypes.c_int64, ctypes.c_int64, ctypes.c_int64 ] self.lib.getParallelUniverse.argtypes = [ ctypes.c_int64, ctypes.c_float, ctypes.c_int64", "Software without restriction, including without limitation the rights to use,", "= np.zeros(self.entity_total_universe, dtype=np.int64) relation_remapping = np.zeros(self.relation_total_universe, dtype=np.int64) entity_remapping_addr = entity_remapping.__array_interface__[\"data\"][0]", "(the \"Software\"), to deal in the Software without restriction, including", "self.entity_total_universe = self.lib.getEntityTotalUniverse() self.relation_total_universe = self.lib.getRelationTotalUniverse() self.train_total_universe = self.lib.getTrainTotalUniverse() self.set_nbatches(self.train_total_universe,", "merge, publish, distribute, sublicense, and/or sell copies of the Software,", "and this permission notice shall be included in all copies", "def reset_universe(self): self.lib.resetUniverse() self.set_nbatches(self.lib.getTrainTotal, self.nbatches) def get_universe_mappings(self): entity_remapping = np.zeros(self.entity_total_universe,", "so, subject to the following conditions: The above copyright notice", "PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR", "to the following conditions: The above copyright notice and this", "charge, to any person obtaining a copy of this software", "copies of the Software, and to permit persons to whom", "the Software without restriction, including without limitation the rights to", "hereby granted, free of charge, to any person obtaining a", "to do so, subject to the following conditions: The above", "conditions: The above copyright notice and this permission notice shall", "to deal in the Software without restriction, including without limitation", "NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS", "WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING", "WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.", "as np from .TrainDataLoader import TrainDataLoader class UniverseTrainDataLoader(TrainDataLoader): def __init__(self,", "THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND", "initial_random_seed=2): super(UniverseTrainDataLoader, self).__init__(in_path=in_path, batch_size=batch_size, nbatches=nbatches, threads=threads, sampling_mode=sampling_mode, bern_flag=bern_flag, filter_flag=filter_flag, neg_ent=neg_ent,", "] self.lib.getRelationRemapping.argtypes = [ ctypes.c_void_p ] self.lib.getEntityTotalUniverse.restype = ctypes.c_int64 self.lib.getRelationTotalUniverse.restype", "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE", "following conditions: The above copyright notice and this permission notice", "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY", "neg_ent=1, neg_rel=0, initial_random_seed=2): super(UniverseTrainDataLoader, self).__init__(in_path=in_path, batch_size=batch_size, nbatches=nbatches, threads=threads, sampling_mode=sampling_mode, bern_flag=bern_flag,", "and/or sell copies of the Software, and to permit persons", "permit persons to whom the Software is furnished to do", "AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT", "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,", "relation_in_focus) self.entity_total_universe = self.lib.getEntityTotalUniverse() self.relation_total_universe = self.lib.getRelationTotalUniverse() self.train_total_universe = self.lib.getTrainTotalUniverse()", "do so, subject to the following conditions: The above copyright", "''' MIT License Copyright (c) 2020 <NAME> Permission is hereby", "ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64", "in the Software without restriction, including without limitation the rights", "self.lib.swapHelpers() def reset_universe(self): self.lib.resetUniverse() self.set_nbatches(self.lib.getTrainTotal, self.nbatches) def get_universe_mappings(self): entity_remapping =", "permission notice shall be included in all copies or substantial", "any person obtaining a copy of this software and associated", "dtype=np.int64) entity_remapping_addr = entity_remapping.__array_interface__[\"data\"][0] relation_remapping_addr = relation_remapping.__array_interface__[\"data\"][0] self.lib.getEntityRemapping(entity_remapping_addr) self.lib.getRelationRemapping(relation_remapping_addr) return", "neg_ent=neg_ent, neg_rel=neg_rel, initial_random_seed=initial_random_seed) self.entity_total_universe = 0 self.relation_total_universe = 0 self.train_total_universe", "portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\",", "= self.lib.getEntityTotalUniverse() self.relation_total_universe = self.lib.getRelationTotalUniverse() self.train_total_universe = self.lib.getTrainTotalUniverse() self.set_nbatches(self.train_total_universe, self.nbatches)", "def get_universe_mappings(self): entity_remapping = np.zeros(self.entity_total_universe, dtype=np.int64) relation_remapping = np.zeros(self.relation_total_universe, dtype=np.int64)", "np.zeros(self.entity_total_universe, dtype=np.int64) relation_remapping = np.zeros(self.relation_total_universe, dtype=np.int64) entity_remapping_addr = entity_remapping.__array_interface__[\"data\"][0] relation_remapping_addr", "OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE", "WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN", "filter_flag=1, neg_ent=1, neg_rel=0, initial_random_seed=2): super(UniverseTrainDataLoader, self).__init__(in_path=in_path, batch_size=batch_size, nbatches=nbatches, threads=threads, sampling_mode=sampling_mode,", "free of charge, to any person obtaining a copy of", "IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE", "SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,", "0 self.train_total_universe = 0 \"\"\"argtypes\"\"\" self.lib.sampling.argtypes = [ ctypes.c_void_p, ctypes.c_void_p,", "BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER", "2020 <NAME> Permission is hereby granted, free of charge, to", "IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,", "DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,", "WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT", "the Software is furnished to do so, subject to the", "Software, and to permit persons to whom the Software is", "OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT", "FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR", "THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE", "IN THE SOFTWARE. ''' import os import ctypes import numpy", "] self.lib.getEntityRemapping.argtypes = [ ctypes.c_void_p ] self.lib.getRelationRemapping.argtypes = [ ctypes.c_void_p", "THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,", "SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.", "] self.lib.getParallelUniverse.argtypes = [ ctypes.c_int64, ctypes.c_float, ctypes.c_int64 ] self.lib.getEntityRemapping.argtypes =", "np.zeros(self.relation_total_universe, dtype=np.int64) entity_remapping_addr = entity_remapping.__array_interface__[\"data\"][0] relation_remapping_addr = relation_remapping.__array_interface__[\"data\"][0] self.lib.getEntityRemapping(entity_remapping_addr) self.lib.getRelationRemapping(relation_remapping_addr)", "modify, merge, publish, distribute, sublicense, and/or sell copies of the", "\"\"\"argtypes\"\"\" self.lib.sampling.argtypes = [ ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int64, ctypes.c_int64,", "ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE", "def __init__(self, in_path=\"./\", batch_size=None, nbatches=None, threads=8, sampling_mode=\"normal\", bern_flag=0, filter_flag=1, neg_ent=1,", "= 0 self.train_total_universe = 0 \"\"\"argtypes\"\"\" self.lib.sampling.argtypes = [ ctypes.c_void_p,", "rights to use, copy, modify, merge, publish, distribute, sublicense, and/or", "copy of this software and associated documentation files (the \"Software\"),", "persons to whom the Software is furnished to do so,", "OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. '''", "limitation the rights to use, copy, modify, merge, publish, distribute,", "subject to the following conditions: The above copyright notice and", "INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS", "OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH", "FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL", "ctypes.c_int64, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64 ] self.lib.getParallelUniverse.argtypes = [", "HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,", "of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT", "including without limitation the rights to use, copy, modify, merge,", "OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR", "documentation files (the \"Software\"), to deal in the Software without", "class UniverseTrainDataLoader(TrainDataLoader): def __init__(self, in_path=\"./\", batch_size=None, nbatches=None, threads=8, sampling_mode=\"normal\", bern_flag=0,", "self.lib.getTrainTotalUniverse.restype = ctypes.c_int64 def swap_helpers(self): self.lib.swapHelpers() def reset_universe(self): self.lib.resetUniverse() self.set_nbatches(self.lib.getTrainTotal,", "copyright notice and this permission notice shall be included in", "relation_remapping def compile_universe_dataset(self, triple_constraint, balance_param, relation_in_focus): self.lib.getParallelUniverse(triple_constraint, balance_param, relation_in_focus) self.entity_total_universe", "sampling_mode=\"normal\", bern_flag=0, filter_flag=1, neg_ent=1, neg_rel=0, initial_random_seed=2): super(UniverseTrainDataLoader, self).__init__(in_path=in_path, batch_size=batch_size, nbatches=nbatches,", "without restriction, including without limitation the rights to use, copy,", "self.entity_total_universe = 0 self.relation_total_universe = 0 self.train_total_universe = 0 \"\"\"argtypes\"\"\"", "return entity_remapping, relation_remapping def compile_universe_dataset(self, triple_constraint, balance_param, relation_in_focus): self.lib.getParallelUniverse(triple_constraint, balance_param,", "<reponame>luofeisg/OpenKE-PuTransE ''' MIT License Copyright (c) 2020 <NAME> Permission is", "CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS", "IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER", "TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION", "initial_random_seed=initial_random_seed) self.entity_total_universe = 0 self.relation_total_universe = 0 self.train_total_universe = 0", "[ ctypes.c_void_p ] self.lib.getEntityTotalUniverse.restype = ctypes.c_int64 self.lib.getRelationTotalUniverse.restype = ctypes.c_int64 self.lib.getTrainTotalUniverse.restype", "self.relation_total_universe = 0 self.train_total_universe = 0 \"\"\"argtypes\"\"\" self.lib.sampling.argtypes = [", "and to permit persons to whom the Software is furnished", "NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A", "ctypes.c_void_p ] self.lib.getRelationRemapping.argtypes = [ ctypes.c_void_p ] self.lib.getEntityTotalUniverse.restype = ctypes.c_int64", "copies or substantial portions of the Software. THE SOFTWARE IS", "OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED", "COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER", "entity_remapping = np.zeros(self.entity_total_universe, dtype=np.int64) relation_remapping = np.zeros(self.relation_total_universe, dtype=np.int64) entity_remapping_addr =", "threads=8, sampling_mode=\"normal\", bern_flag=0, filter_flag=1, neg_ent=1, neg_rel=0, initial_random_seed=2): super(UniverseTrainDataLoader, self).__init__(in_path=in_path, batch_size=batch_size,", "ctypes.c_int64, ctypes.c_float, ctypes.c_int64 ] self.lib.getEntityRemapping.argtypes = [ ctypes.c_void_p ] self.lib.getRelationRemapping.argtypes", "Software is furnished to do so, subject to the following", "= [ ctypes.c_void_p ] self.lib.getRelationRemapping.argtypes = [ ctypes.c_void_p ] self.lib.getEntityTotalUniverse.restype", "Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF", "batch_size=batch_size, nbatches=nbatches, threads=threads, sampling_mode=sampling_mode, bern_flag=bern_flag, filter_flag=filter_flag, neg_ent=neg_ent, neg_rel=neg_rel, initial_random_seed=initial_random_seed) self.entity_total_universe", "ctypes import numpy as np from .TrainDataLoader import TrainDataLoader class", "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,", "SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY", "without limitation the rights to use, copy, modify, merge, publish,", "numpy as np from .TrainDataLoader import TrainDataLoader class UniverseTrainDataLoader(TrainDataLoader): def", "sell copies of the Software, and to permit persons to", "NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE", "balance_param, relation_in_focus): self.lib.getParallelUniverse(triple_constraint, balance_param, relation_in_focus) self.entity_total_universe = self.lib.getEntityTotalUniverse() self.relation_total_universe =", "get_universe_mappings(self): entity_remapping = np.zeros(self.entity_total_universe, dtype=np.int64) relation_remapping = np.zeros(self.relation_total_universe, dtype=np.int64) entity_remapping_addr", "use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies", "batch_size=None, nbatches=None, threads=8, sampling_mode=\"normal\", bern_flag=0, filter_flag=1, neg_ent=1, neg_rel=0, initial_random_seed=2): super(UniverseTrainDataLoader,", "OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR", "THE USE OR OTHER DEALINGS IN THE SOFTWARE. ''' import", "included in all copies or substantial portions of the Software.", "THE SOFTWARE. ''' import os import ctypes import numpy as", "neg_rel=neg_rel, initial_random_seed=initial_random_seed) self.entity_total_universe = 0 self.relation_total_universe = 0 self.train_total_universe =", "compile_universe_dataset(self, triple_constraint, balance_param, relation_in_focus): self.lib.getParallelUniverse(triple_constraint, balance_param, relation_in_focus) self.entity_total_universe = self.lib.getEntityTotalUniverse()", "DEALINGS IN THE SOFTWARE. ''' import os import ctypes import", "relation_remapping_addr = relation_remapping.__array_interface__[\"data\"][0] self.lib.getEntityRemapping(entity_remapping_addr) self.lib.getRelationRemapping(relation_remapping_addr) return entity_remapping, relation_remapping def compile_universe_dataset(self,", "granted, free of charge, to any person obtaining a copy", "restriction, including without limitation the rights to use, copy, modify,", "whom the Software is furnished to do so, subject to", "''' import os import ctypes import numpy as np from", "<NAME> Permission is hereby granted, free of charge, to any", "import os import ctypes import numpy as np from .TrainDataLoader", "= entity_remapping.__array_interface__[\"data\"][0] relation_remapping_addr = relation_remapping.__array_interface__[\"data\"][0] self.lib.getEntityRemapping(entity_remapping_addr) self.lib.getRelationRemapping(relation_remapping_addr) return entity_remapping, relation_remapping", "sampling_mode=sampling_mode, bern_flag=bern_flag, filter_flag=filter_flag, neg_ent=neg_ent, neg_rel=neg_rel, initial_random_seed=initial_random_seed) self.entity_total_universe = 0 self.relation_total_universe", "to permit persons to whom the Software is furnished to", "np from .TrainDataLoader import TrainDataLoader class UniverseTrainDataLoader(TrainDataLoader): def __init__(self, in_path=\"./\",", "self).__init__(in_path=in_path, batch_size=batch_size, nbatches=nbatches, threads=threads, sampling_mode=sampling_mode, bern_flag=bern_flag, filter_flag=filter_flag, neg_ent=neg_ent, neg_rel=neg_rel, initial_random_seed=initial_random_seed)", "self.nbatches) def get_universe_mappings(self): entity_remapping = np.zeros(self.entity_total_universe, dtype=np.int64) relation_remapping = np.zeros(self.relation_total_universe,", "= 0 \"\"\"argtypes\"\"\" self.lib.sampling.argtypes = [ ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p,", "AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT", "self.train_total_universe = 0 \"\"\"argtypes\"\"\" self.lib.sampling.argtypes = [ ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p,", "ctypes.c_int64, ctypes.c_int64 ] self.lib.getParallelUniverse.argtypes = [ ctypes.c_int64, ctypes.c_float, ctypes.c_int64 ]", "self.lib.resetUniverse() self.set_nbatches(self.lib.getTrainTotal, self.nbatches) def get_universe_mappings(self): entity_remapping = np.zeros(self.entity_total_universe, dtype=np.int64) relation_remapping", "copy, modify, merge, publish, distribute, sublicense, and/or sell copies of", "in all copies or substantial portions of the Software. THE", "of charge, to any person obtaining a copy of this", "obtaining a copy of this software and associated documentation files", "PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS", "] self.lib.getEntityTotalUniverse.restype = ctypes.c_int64 self.lib.getRelationTotalUniverse.restype = ctypes.c_int64 self.lib.getTrainTotalUniverse.restype = ctypes.c_int64", "OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF", "Permission is hereby granted, free of charge, to any person", "= ctypes.c_int64 self.lib.getTrainTotalUniverse.restype = ctypes.c_int64 def swap_helpers(self): self.lib.swapHelpers() def reset_universe(self):", "UniverseTrainDataLoader(TrainDataLoader): def __init__(self, in_path=\"./\", batch_size=None, nbatches=None, threads=8, sampling_mode=\"normal\", bern_flag=0, filter_flag=1,", "LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN", "[ ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64,", "reset_universe(self): self.lib.resetUniverse() self.set_nbatches(self.lib.getTrainTotal, self.nbatches) def get_universe_mappings(self): entity_remapping = np.zeros(self.entity_total_universe, dtype=np.int64)", "0 \"\"\"argtypes\"\"\" self.lib.sampling.argtypes = [ ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int64,", "= relation_remapping.__array_interface__[\"data\"][0] self.lib.getEntityRemapping(entity_remapping_addr) self.lib.getRelationRemapping(relation_remapping_addr) return entity_remapping, relation_remapping def compile_universe_dataset(self, triple_constraint,", "swap_helpers(self): self.lib.swapHelpers() def reset_universe(self): self.lib.resetUniverse() self.set_nbatches(self.lib.getTrainTotal, self.nbatches) def get_universe_mappings(self): entity_remapping", "of this software and associated documentation files (the \"Software\"), to", "OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR", "a copy of this software and associated documentation files (the", "OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR", "furnished to do so, subject to the following conditions: The", "OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE", "deal in the Software without restriction, including without limitation the", "The above copyright notice and this permission notice shall be", "or substantial portions of the Software. THE SOFTWARE IS PROVIDED", "EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR", "self.lib.sampling.argtypes = [ ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64,", "self.lib.getParallelUniverse.argtypes = [ ctypes.c_int64, ctypes.c_float, ctypes.c_int64 ] self.lib.getEntityRemapping.argtypes = [", "ctypes.c_void_p ] self.lib.getEntityTotalUniverse.restype = ctypes.c_int64 self.lib.getRelationTotalUniverse.restype = ctypes.c_int64 self.lib.getTrainTotalUniverse.restype =", "sublicense, and/or sell copies of the Software, and to permit", "ctypes.c_int64 self.lib.getTrainTotalUniverse.restype = ctypes.c_int64 def swap_helpers(self): self.lib.swapHelpers() def reset_universe(self): self.lib.resetUniverse()", "EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES", "TrainDataLoader class UniverseTrainDataLoader(TrainDataLoader): def __init__(self, in_path=\"./\", batch_size=None, nbatches=None, threads=8, sampling_mode=\"normal\",", "nbatches=None, threads=8, sampling_mode=\"normal\", bern_flag=0, filter_flag=1, neg_ent=1, neg_rel=0, initial_random_seed=2): super(UniverseTrainDataLoader, self).__init__(in_path=in_path,", "def swap_helpers(self): self.lib.swapHelpers() def reset_universe(self): self.lib.resetUniverse() self.set_nbatches(self.lib.getTrainTotal, self.nbatches) def get_universe_mappings(self):", "publish, distribute, sublicense, and/or sell copies of the Software, and", "BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR", "LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR", "self.lib.getRelationTotalUniverse.restype = ctypes.c_int64 self.lib.getTrainTotalUniverse.restype = ctypes.c_int64 def swap_helpers(self): self.lib.swapHelpers() def", "\"Software\"), to deal in the Software without restriction, including without", "os import ctypes import numpy as np from .TrainDataLoader import", "MIT License Copyright (c) 2020 <NAME> Permission is hereby granted,", "IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS", "ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO", "associated documentation files (the \"Software\"), to deal in the Software", "ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION", "OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN", "distribute, sublicense, and/or sell copies of the Software, and to", "self.lib.getRelationRemapping(relation_remapping_addr) return entity_remapping, relation_remapping def compile_universe_dataset(self, triple_constraint, balance_param, relation_in_focus): self.lib.getParallelUniverse(triple_constraint,", "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES", "[ ctypes.c_void_p ] self.lib.getRelationRemapping.argtypes = [ ctypes.c_void_p ] self.lib.getEntityTotalUniverse.restype =", "PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR", "OR OTHER DEALINGS IN THE SOFTWARE. ''' import os import", "super(UniverseTrainDataLoader, self).__init__(in_path=in_path, batch_size=batch_size, nbatches=nbatches, threads=threads, sampling_mode=sampling_mode, bern_flag=bern_flag, filter_flag=filter_flag, neg_ent=neg_ent, neg_rel=neg_rel,", "be included in all copies or substantial portions of the", "= [ ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64," ]
[ "Tensor in a list self.call_lowering_to_nnapi(traced, [args]) # Test exceptions for", "to resolve this. T95764916 torch_root = Path(__file__).resolve().parent.parent.parent lib_path = torch_root", "dimorder. For input shapes, use 0 for run/load time flexible", "a different unit test changed dtype to float64, # which", "torch.testing._internal.common_utils import TEST_WITH_ASAN # Make the helper files in test/", "NNAPI delegate) # Float32 should typically be the default in", "[1]}} with self.assertRaisesRegex(RuntimeError, \"method_compile_spec does not contain either a Tensor", "@unittest.skipIf(not os.path.exists(lib_path), \"Skipping the test as libnnapi_backend.so was not found\")", "delegate) # Float32 should typically be the default in other", "# Argument input is a single Tensor self.call_lowering_to_nnapi(traced, args) #", "following format: {\"forward\": {\"inputs\": at::Tensor}} OR {\"forward\": {\"inputs\": c10::List<at::Tensor>}}\"\"\" #", "most tests from TestNNAPI, which loads Android NNAPI models without", "lib_path = torch_root / 'build' / 'lib' / 'libnnapi_backend.so' @unittest.skipIf(not", "specs def test_compile_spec_santiy(self): args = torch.tensor([[1.0, -1.0, 2.0, -2.0]]).unsqueeze(-1).unsqueeze(-1) module", "the delegate API. \"\"\" # First skip is needed for", "= {\"forward\": 1} with self.assertRaisesRegex(RuntimeError, \"method_compile_spec does not contain a", "causing an error. # It is still unclear how to", "Test exceptions for incorrect compile specs def test_compile_spec_santiy(self): args =", "List which bundles input parameters: shape, dtype, quantization, and dimorder.", "\"\"\" # First skip is needed for IS_WINDOWS or IS_MACOS", "the following format: {\"forward\": {\"inputs\": at::Tensor}} OR {\"forward\": {\"inputs\": c10::List<at::Tensor>}}\"\"\"", "with self.assertRaisesRegex(RuntimeError, \"method_compile_spec does not contain the \\\"forward\\\" key.\" +", "torch.jit.trace(module, args) # Argument input is a single Tensor self.call_lowering_to_nnapi(traced,", "compile_spec = {\"forward\": {\"not inputs\": args}} with self.assertRaisesRegex(RuntimeError, \"method_compile_spec does", "default in other files. torch.set_default_dtype(torch.float32) # Load nnapi delegate library", "Tests for Nnapi backend with delegate Inherits most tests from", "(in the dictionary under the forward key) compile_spec = {\"forward\":", "it's \\\"inputs\\\" key.\" + errorMsgTail): torch._C._jit_to_backend(\"nnapi\", traced, compile_spec) def tearDown(self):", "ASAN is currently causing an error. # It is still", "delegate Inherits most tests from TestNNAPI, which loads Android NNAPI", "module args = torch.tensor([[1.0, -1.0, 2.0, -2.0]]).unsqueeze(-1).unsqueeze(-1) module = torch.nn.PReLU()", "# Lower a simple module args = torch.tensor([[1.0, -1.0, 2.0,", "Lower a simple module args = torch.tensor([[1.0, -1.0, 2.0, -2.0]]).unsqueeze(-1).unsqueeze(-1)", "# Test exceptions for incorrect compile specs def test_compile_spec_santiy(self): args", "input shapes, use 0 for run/load time flexible input. method_compile_spec", "# Load nnapi delegate library torch.ops.load_library(str(lib_path)) # Override def call_lowering_to_nnapi(self,", "or TensorList under the inputs key compile_spec = {\"forward\": {\"inputs\":", "delegate library torch.ops.load_library(str(lib_path)) # Override def call_lowering_to_nnapi(self, traced_module, args): compile_spec", "must use the following format: {\"forward\": {\"inputs\": at::Tensor}} OR {\"forward\":", "contain a dictionary with an \\\"inputs\\\" key, \" \"under it's", "how to resolve this. T95764916 torch_root = Path(__file__).resolve().parent.parent.parent lib_path =", "key.\" + errorMsgTail): torch._C._jit_to_backend(\"nnapi\", traced, compile_spec) compile_spec = {\"forward\": {\"inputs\":", "the forward key) compile_spec = {\"forward\": {\"not inputs\": args}} with", "because ASAN is currently causing an error. # It is", "1} with self.assertRaisesRegex(RuntimeError, \"method_compile_spec does not contain a dictionary with", "test/test_jit.py TESTNAME\\n\\n\" \"instead.\" ) \"\"\" Unit Tests for Nnapi backend", "Unit Tests for Nnapi backend with delegate Inherits most tests", "from TestNNAPI, which loads Android NNAPI models without the delegate", "is still unclear how to resolve this. T95764916 torch_root =", "a simple module args = torch.tensor([[1.0, -1.0, 2.0, -2.0]]).unsqueeze(-1).unsqueeze(-1) module", "= r\"\"\" method_compile_spec should contain a Tensor or Tensor List", "bug with ASAN\") class TestNnapiBackend(TestNNAPI): def setUp(self): super().setUp() # Save", "different unit test changed dtype to float64, # which is", "a list self.call_lowering_to_nnapi(traced, [args]) # Test exceptions for incorrect compile", "dictionary under the forward key) compile_spec = {\"forward\": {\"not inputs\":", "skip the tests. # Second skip is because ASAN is", "forward key compile_spec = {\"backward\": {\"inputs\": args}} with self.assertRaisesRegex(RuntimeError, \"method_compile_spec", "resolve this. T95764916 torch_root = Path(__file__).resolve().parent.parent.parent lib_path = torch_root /", "to skip the tests. # Second skip is because ASAN", "loads Android NNAPI models without the delegate API. \"\"\" #", "TensorList under the inputs key compile_spec = {\"forward\": {\"inputs\": 1}}", "Tensor or Tensor List which bundles input parameters: shape, dtype,", "the Android NNAPI delegate) # Float32 should typically be the", "key compile_spec = {\"backward\": {\"inputs\": args}} with self.assertRaisesRegex(RuntimeError, \"method_compile_spec does", "module.weight.dtype # Change dtype to float32 (since a different unit", "by the Android NNAPI delegate) # Float32 should typically be", "input is a single Tensor self.call_lowering_to_nnapi(traced, args) # Argument input", "does not contain a dictionary with an \\\"inputs\\\" key, \"", "format: {\"forward\": {\"inputs\": at::Tensor}} OR {\"forward\": {\"inputs\": c10::List<at::Tensor>}}\"\"\" # No", "shapes, use 0 for run/load time flexible input. method_compile_spec must", "torch._C._jit_to_backend(\"nnapi\", traced, compile_spec) # No inputs key (in the dictionary", "{\"inputs\": args}} return torch._C._jit_to_backend(\"nnapi\", traced_module, compile_spec) def test_tensor_input(self): # Lower", "under it's \\\"inputs\\\" key.\" + errorMsgTail): torch._C._jit_to_backend(\"nnapi\", traced, compile_spec) def", "Save default dtype module = torch.nn.PReLU() self.default_dtype = module.weight.dtype #", "= {\"forward\": {\"inputs\": 1}} with self.assertRaisesRegex(RuntimeError, \"method_compile_spec does not contain", "torch.nn.PReLU() traced = torch.jit.trace(module, args) # Argument input is a", "args}} return torch._C._jit_to_backend(\"nnapi\", traced_module, compile_spec) def test_tensor_input(self): # Lower a", "torch_root = Path(__file__).resolve().parent.parent.parent lib_path = torch_root / 'build' / 'lib'", "# No inputs key (in the dictionary under the forward", "without the delegate API. \"\"\" # First skip is needed", "unit test changed dtype to float64, # which is not", "skip is needed for IS_WINDOWS or IS_MACOS to skip the", "currently causing an error. # It is still unclear how", "torch.nn.PReLU() traced = torch.jit.trace(module, args) errorMsgTail = r\"\"\" method_compile_spec should", "For input shapes, use 0 for run/load time flexible input.", "forward key) compile_spec = {\"forward\": {\"not inputs\": args}} with self.assertRaisesRegex(RuntimeError,", "[args]) # Test exceptions for incorrect compile specs def test_compile_spec_santiy(self):", "No dictionary under the forward key compile_spec = {\"forward\": 1}", "a Tensor or Tensor List which bundles input parameters: shape,", "errorMsgTail = r\"\"\" method_compile_spec should contain a Tensor or Tensor", "contain either a Tensor or TensorList, under it's \\\"inputs\\\" key.\"", "to be run directly, use:\\n\\n\" \"\\tpython test/test_jit.py TESTNAME\\n\\n\" \"instead.\" )", "c10::List<at::Tensor>}}\"\"\" # No forward key compile_spec = {\"backward\": {\"inputs\": args}}", "contain a Tensor or Tensor List which bundles input parameters:", "Tensor self.call_lowering_to_nnapi(traced, args) # Argument input is a Tensor in", "input is a Tensor in a list self.call_lowering_to_nnapi(traced, [args]) #", "for run/load time flexible input. method_compile_spec must use the following", "forward key compile_spec = {\"forward\": 1} with self.assertRaisesRegex(RuntimeError, \"method_compile_spec does", "key) compile_spec = {\"forward\": {\"not inputs\": args}} with self.assertRaisesRegex(RuntimeError, \"method_compile_spec", "does not contain either a Tensor or TensorList, under it's", "library torch.ops.load_library(str(lib_path)) # Override def call_lowering_to_nnapi(self, traced_module, args): compile_spec =", "args): compile_spec = {\"forward\": {\"inputs\": args}} return torch._C._jit_to_backend(\"nnapi\", traced_module, compile_spec)", "traced_module, compile_spec) def test_tensor_input(self): # Lower a simple module args", "Float32 should typically be the default in other files. torch.set_default_dtype(torch.float32)", "\"__main__\": raise RuntimeError( \"This test file is not meant to", "\"method_compile_spec does not contain a dictionary with an \\\"inputs\\\" key,", "dtype to float64, # which is not supported by the", "Tensor or TensorList, under it's \\\"inputs\\\" key.\" + errorMsgTail): torch._C._jit_to_backend(\"nnapi\",", "not contain the \\\"forward\\\" key.\" + errorMsgTail): torch._C._jit_to_backend(\"nnapi\", traced, compile_spec)", "and dimorder. For input shapes, use 0 for run/load time", "found\") @unittest.skipIf(TEST_WITH_ASAN, \"Unresolved bug with ASAN\") class TestNnapiBackend(TestNNAPI): def setUp(self):", "\\\"inputs\\\" key.\" + errorMsgTail): torch._C._jit_to_backend(\"nnapi\", traced, compile_spec) def tearDown(self): #", "# Second skip is because ASAN is currently causing an", "= os.path.dirname(os.path.dirname(os.path.realpath(__file__))) sys.path.append(pytorch_test_dir) if __name__ == \"__main__\": raise RuntimeError( \"This", "traced, compile_spec) def tearDown(self): # Change dtype back to default", "this. T95764916 torch_root = Path(__file__).resolve().parent.parent.parent lib_path = torch_root / 'build'", "It is still unclear how to resolve this. T95764916 torch_root", "dictionary under the forward key compile_spec = {\"forward\": 1} with", "Change dtype to float32 (since a different unit test changed", "pytorch_test_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) sys.path.append(pytorch_test_dir) if __name__ == \"__main__\": raise RuntimeError(", "def test_compile_spec_santiy(self): args = torch.tensor([[1.0, -1.0, 2.0, -2.0]]).unsqueeze(-1).unsqueeze(-1) module =", "import torch import torch._C from pathlib import Path from test_nnapi", "the helper files in test/ importable pytorch_test_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) sys.path.append(pytorch_test_dir)", "traced_module, args): compile_spec = {\"forward\": {\"inputs\": args}} return torch._C._jit_to_backend(\"nnapi\", traced_module,", "args}} with self.assertRaisesRegex(RuntimeError, \"method_compile_spec does not contain the \\\"forward\\\" key.\"", "is currently causing an error. # It is still unclear", "does not contain the \\\"forward\\\" key.\" + errorMsgTail): torch._C._jit_to_backend(\"nnapi\", traced,", "use:\\n\\n\" \"\\tpython test/test_jit.py TESTNAME\\n\\n\" \"instead.\" ) \"\"\" Unit Tests for", "simple module args = torch.tensor([[1.0, -1.0, 2.0, -2.0]]).unsqueeze(-1).unsqueeze(-1) module =", "the default in other files. torch.set_default_dtype(torch.float32) # Load nnapi delegate", "torch.nn.PReLU() self.default_dtype = module.weight.dtype # Change dtype to float32 (since", "0 for run/load time flexible input. method_compile_spec must use the", "RuntimeError( \"This test file is not meant to be run", "compile_spec) # No dictionary under the forward key compile_spec =", "import Path from test_nnapi import TestNNAPI from torch.testing._internal.common_utils import TEST_WITH_ASAN", "Argument input is a single Tensor self.call_lowering_to_nnapi(traced, args) # Argument", "compile_spec = {\"backward\": {\"inputs\": args}} with self.assertRaisesRegex(RuntimeError, \"method_compile_spec does not", "No Tensor or TensorList under the inputs key compile_spec =", "as libnnapi_backend.so was not found\") @unittest.skipIf(TEST_WITH_ASAN, \"Unresolved bug with ASAN\")", "key.\" + errorMsgTail): torch._C._jit_to_backend(\"nnapi\", traced, compile_spec) # No inputs key", "self.call_lowering_to_nnapi(traced, args) # Argument input is a Tensor in a", "compile_spec = {\"forward\": {\"inputs\": [1]}} with self.assertRaisesRegex(RuntimeError, \"method_compile_spec does not", "{\"forward\": {\"inputs\": args}} return torch._C._jit_to_backend(\"nnapi\", traced_module, compile_spec) def test_tensor_input(self): #", "tests from TestNNAPI, which loads Android NNAPI models without the", "the tests. # Second skip is because ASAN is currently", "TestNNAPI from torch.testing._internal.common_utils import TEST_WITH_ASAN # Make the helper files", "pathlib import Path from test_nnapi import TestNNAPI from torch.testing._internal.common_utils import", "key compile_spec = {\"forward\": 1} with self.assertRaisesRegex(RuntimeError, \"method_compile_spec does not", "os.path.dirname(os.path.dirname(os.path.realpath(__file__))) sys.path.append(pytorch_test_dir) if __name__ == \"__main__\": raise RuntimeError( \"This test", "= Path(__file__).resolve().parent.parent.parent lib_path = torch_root / 'build' / 'lib' /", "args}} with self.assertRaisesRegex(RuntimeError, \"method_compile_spec does not contain a dictionary with", "2.0, -2.0]]).unsqueeze(-1).unsqueeze(-1) module = torch.nn.PReLU() traced = torch.jit.trace(module, args) errorMsgTail", "compile_spec) def test_tensor_input(self): # Lower a simple module args =", "key (in the dictionary under the forward key) compile_spec =", "inputs key compile_spec = {\"forward\": {\"inputs\": 1}} with self.assertRaisesRegex(RuntimeError, \"method_compile_spec", "No forward key compile_spec = {\"backward\": {\"inputs\": args}} with self.assertRaisesRegex(RuntimeError,", "single Tensor self.call_lowering_to_nnapi(traced, args) # Argument input is a Tensor", "\\\"inputs\\\" key, \" \"under it's \\\"forward\\\" key.\" + errorMsgTail): torch._C._jit_to_backend(\"nnapi\",", "inputs\": args}} with self.assertRaisesRegex(RuntimeError, \"method_compile_spec does not contain a dictionary", "it's \\\"inputs\\\" key.\" + errorMsgTail): torch._C._jit_to_backend(\"nnapi\", traced, compile_spec) compile_spec =", "key compile_spec = {\"forward\": {\"inputs\": 1}} with self.assertRaisesRegex(RuntimeError, \"method_compile_spec does", "Tensor List which bundles input parameters: shape, dtype, quantization, and", "Second skip is because ASAN is currently causing an error.", "use 0 for run/load time flexible input. method_compile_spec must use", "@unittest.skipIf(TEST_WITH_ASAN, \"Unresolved bug with ASAN\") class TestNnapiBackend(TestNNAPI): def setUp(self): super().setUp()", "= module.weight.dtype # Change dtype to float32 (since a different", "Make the helper files in test/ importable pytorch_test_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))", "= torch.nn.PReLU() self.default_dtype = module.weight.dtype # Change dtype to float32", "-1.0, 2.0, -2.0]]).unsqueeze(-1).unsqueeze(-1) module = torch.nn.PReLU() traced = torch.jit.trace(module, args)", "dtype module = torch.nn.PReLU() self.default_dtype = module.weight.dtype # Change dtype", "Nnapi backend with delegate Inherits most tests from TestNNAPI, which", "{\"inputs\": 1}} with self.assertRaisesRegex(RuntimeError, \"method_compile_spec does not contain either a", "test changed dtype to float64, # which is not supported", "compile_spec) compile_spec = {\"forward\": {\"inputs\": [1]}} with self.assertRaisesRegex(RuntimeError, \"method_compile_spec does", "it's \\\"forward\\\" key.\" + errorMsgTail): torch._C._jit_to_backend(\"nnapi\", traced, compile_spec) # No", "torch.ops.load_library(str(lib_path)) # Override def call_lowering_to_nnapi(self, traced_module, args): compile_spec = {\"forward\":", "= {\"forward\": {\"inputs\": args}} return torch._C._jit_to_backend(\"nnapi\", traced_module, compile_spec) def test_tensor_input(self):", "Path(__file__).resolve().parent.parent.parent lib_path = torch_root / 'build' / 'lib' / 'libnnapi_backend.so'", "inputs key (in the dictionary under the forward key) compile_spec", "torch.set_default_dtype(torch.float32) # Load nnapi delegate library torch.ops.load_library(str(lib_path)) # Override def", "traced, compile_spec) # No dictionary under the forward key compile_spec", "Load nnapi delegate library torch.ops.load_library(str(lib_path)) # Override def call_lowering_to_nnapi(self, traced_module,", "backend with delegate Inherits most tests from TestNNAPI, which loads", "at::Tensor}} OR {\"forward\": {\"inputs\": c10::List<at::Tensor>}}\"\"\" # No forward key compile_spec", "the \\\"forward\\\" key.\" + errorMsgTail): torch._C._jit_to_backend(\"nnapi\", traced, compile_spec) # No", "input. method_compile_spec must use the following format: {\"forward\": {\"inputs\": at::Tensor}}", "ASAN\") class TestNnapiBackend(TestNNAPI): def setUp(self): super().setUp() # Save default dtype", "{\"inputs\": [1]}} with self.assertRaisesRegex(RuntimeError, \"method_compile_spec does not contain either a", "typically be the default in other files. torch.set_default_dtype(torch.float32) # Load", "self.call_lowering_to_nnapi(traced, [args]) # Test exceptions for incorrect compile specs def", "r\"\"\" method_compile_spec should contain a Tensor or Tensor List which", "sys import unittest import torch import torch._C from pathlib import", "exceptions for incorrect compile specs def test_compile_spec_santiy(self): args = torch.tensor([[1.0,", "1}} with self.assertRaisesRegex(RuntimeError, \"method_compile_spec does not contain either a Tensor", "time flexible input. method_compile_spec must use the following format: {\"forward\":", "/ 'lib' / 'libnnapi_backend.so' @unittest.skipIf(not os.path.exists(lib_path), \"Skipping the test as", "args) # Argument input is a Tensor in a list", "test file is not meant to be run directly, use:\\n\\n\"", "\"\\tpython test/test_jit.py TESTNAME\\n\\n\" \"instead.\" ) \"\"\" Unit Tests for Nnapi", "import unittest import torch import torch._C from pathlib import Path", "{\"forward\": {\"not inputs\": args}} with self.assertRaisesRegex(RuntimeError, \"method_compile_spec does not contain", "is not supported by the Android NNAPI delegate) # Float32", "torch._C._jit_to_backend(\"nnapi\", traced_module, compile_spec) def test_tensor_input(self): # Lower a simple module", "from test_nnapi import TestNNAPI from torch.testing._internal.common_utils import TEST_WITH_ASAN # Make", "unclear how to resolve this. T95764916 torch_root = Path(__file__).resolve().parent.parent.parent lib_path", "{\"not inputs\": args}} with self.assertRaisesRegex(RuntimeError, \"method_compile_spec does not contain a", "Path from test_nnapi import TestNNAPI from torch.testing._internal.common_utils import TEST_WITH_ASAN #", "torch_root / 'build' / 'lib' / 'libnnapi_backend.so' @unittest.skipIf(not os.path.exists(lib_path), \"Skipping", "traced, compile_spec) # No Tensor or TensorList under the inputs", "IS_MACOS to skip the tests. # Second skip is because", "\"Unresolved bug with ASAN\") class TestNnapiBackend(TestNNAPI): def setUp(self): super().setUp() #", "args = torch.tensor([[1.0, -1.0, 2.0, -2.0]]).unsqueeze(-1).unsqueeze(-1) module = torch.nn.PReLU() traced", "either a Tensor or TensorList, under it's \\\"inputs\\\" key.\" +", "compile_spec = {\"forward\": {\"inputs\": 1}} with self.assertRaisesRegex(RuntimeError, \"method_compile_spec does not", "not found\") @unittest.skipIf(TEST_WITH_ASAN, \"Unresolved bug with ASAN\") class TestNnapiBackend(TestNNAPI): def", "OR {\"forward\": {\"inputs\": c10::List<at::Tensor>}}\"\"\" # No forward key compile_spec =", "self.assertRaisesRegex(RuntimeError, \"method_compile_spec does not contain a dictionary with an \\\"inputs\\\"", ") \"\"\" Unit Tests for Nnapi backend with delegate Inherits", "or IS_MACOS to skip the tests. # Second skip is", "key.\" + errorMsgTail): torch._C._jit_to_backend(\"nnapi\", traced, compile_spec) def tearDown(self): # Change", "test as libnnapi_backend.so was not found\") @unittest.skipIf(TEST_WITH_ASAN, \"Unresolved bug with", "traced = torch.jit.trace(module, args) # Argument input is a single", "2.0, -2.0]]).unsqueeze(-1).unsqueeze(-1) module = torch.nn.PReLU() traced = torch.jit.trace(module, args) #", "Override def call_lowering_to_nnapi(self, traced_module, args): compile_spec = {\"forward\": {\"inputs\": args}}", "errorMsgTail): torch._C._jit_to_backend(\"nnapi\", traced, compile_spec) # No dictionary under the forward", "setUp(self): super().setUp() # Save default dtype module = torch.nn.PReLU() self.default_dtype", "bundles input parameters: shape, dtype, quantization, and dimorder. For input", "supported by the Android NNAPI delegate) # Float32 should typically", "for IS_WINDOWS or IS_MACOS to skip the tests. # Second", "with self.assertRaisesRegex(RuntimeError, \"method_compile_spec does not contain either a Tensor or", "torch.jit.trace(module, args) errorMsgTail = r\"\"\" method_compile_spec should contain a Tensor", "key.\" + errorMsgTail): torch._C._jit_to_backend(\"nnapi\", traced, compile_spec) # No dictionary under", "which is not supported by the Android NNAPI delegate) #", "under the forward key) compile_spec = {\"forward\": {\"not inputs\": args}}", "is a single Tensor self.call_lowering_to_nnapi(traced, args) # Argument input is", "not contain a dictionary with an \\\"inputs\\\" key, \" \"under", "# First skip is needed for IS_WINDOWS or IS_MACOS to", "def test_tensor_input(self): # Lower a simple module args = torch.tensor([[1.0,", "dictionary with an \\\"inputs\\\" key, \" \"under it's \\\"forward\\\" key.\"", "the inputs key compile_spec = {\"forward\": {\"inputs\": 1}} with self.assertRaisesRegex(RuntimeError,", "module = torch.nn.PReLU() traced = torch.jit.trace(module, args) errorMsgTail = r\"\"\"", "= {\"forward\": {\"inputs\": [1]}} with self.assertRaisesRegex(RuntimeError, \"method_compile_spec does not contain", "test_nnapi import TestNNAPI from torch.testing._internal.common_utils import TEST_WITH_ASAN # Make the", "under the forward key compile_spec = {\"forward\": 1} with self.assertRaisesRegex(RuntimeError,", "IS_WINDOWS or IS_MACOS to skip the tests. # Second skip", "with self.assertRaisesRegex(RuntimeError, \"method_compile_spec does not contain a dictionary with an", "import os import sys import unittest import torch import torch._C", "which bundles input parameters: shape, dtype, quantization, and dimorder. For", "\"method_compile_spec does not contain either a Tensor or TensorList, under", "import TEST_WITH_ASAN # Make the helper files in test/ importable", "run directly, use:\\n\\n\" \"\\tpython test/test_jit.py TESTNAME\\n\\n\" \"instead.\" ) \"\"\" Unit", "not contain either a Tensor or TensorList, under it's \\\"inputs\\\"", "# Float32 should typically be the default in other files.", "meant to be run directly, use:\\n\\n\" \"\\tpython test/test_jit.py TESTNAME\\n\\n\" \"instead.\"", "helper files in test/ importable pytorch_test_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) sys.path.append(pytorch_test_dir) if", "dtype, quantization, and dimorder. For input shapes, use 0 for", "to float32 (since a different unit test changed dtype to", "torch._C._jit_to_backend(\"nnapi\", traced, compile_spec) # No dictionary under the forward key", "\"under it's \\\"forward\\\" key.\" + errorMsgTail): torch._C._jit_to_backend(\"nnapi\", traced, compile_spec) #", "be the default in other files. torch.set_default_dtype(torch.float32) # Load nnapi", "an \\\"inputs\\\" key, \" \"under it's \\\"forward\\\" key.\" + errorMsgTail):", "+ errorMsgTail): torch._C._jit_to_backend(\"nnapi\", traced, compile_spec) def tearDown(self): # Change dtype", "-2.0]]).unsqueeze(-1).unsqueeze(-1) module = torch.nn.PReLU() traced = torch.jit.trace(module, args) # Argument", "with delegate Inherits most tests from TestNNAPI, which loads Android", "which loads Android NNAPI models without the delegate API. \"\"\"", "{\"inputs\": args}} with self.assertRaisesRegex(RuntimeError, \"method_compile_spec does not contain the \\\"forward\\\"", "+ errorMsgTail): torch._C._jit_to_backend(\"nnapi\", traced, compile_spec) # No Tensor or TensorList", "# No forward key compile_spec = {\"backward\": {\"inputs\": args}} with", "\"Skipping the test as libnnapi_backend.so was not found\") @unittest.skipIf(TEST_WITH_ASAN, \"Unresolved", "under it's \\\"inputs\\\" key.\" + errorMsgTail): torch._C._jit_to_backend(\"nnapi\", traced, compile_spec) compile_spec", "{\"forward\": {\"inputs\": 1}} with self.assertRaisesRegex(RuntimeError, \"method_compile_spec does not contain either", "from pathlib import Path from test_nnapi import TestNNAPI from torch.testing._internal.common_utils", "-2.0]]).unsqueeze(-1).unsqueeze(-1) module = torch.nn.PReLU() traced = torch.jit.trace(module, args) errorMsgTail =", "file is not meant to be run directly, use:\\n\\n\" \"\\tpython", "float64, # which is not supported by the Android NNAPI", "errorMsgTail): torch._C._jit_to_backend(\"nnapi\", traced, compile_spec) # No Tensor or TensorList under", "# No Tensor or TensorList under the inputs key compile_spec", "compile_spec = {\"forward\": 1} with self.assertRaisesRegex(RuntimeError, \"method_compile_spec does not contain", "super().setUp() # Save default dtype module = torch.nn.PReLU() self.default_dtype =", "TEST_WITH_ASAN # Make the helper files in test/ importable pytorch_test_dir", "from torch.testing._internal.common_utils import TEST_WITH_ASAN # Make the helper files in", "import torch._C from pathlib import Path from test_nnapi import TestNNAPI", "should contain a Tensor or Tensor List which bundles input", "torch import torch._C from pathlib import Path from test_nnapi import", "errorMsgTail): torch._C._jit_to_backend(\"nnapi\", traced, compile_spec) def tearDown(self): # Change dtype back", "test_compile_spec_santiy(self): args = torch.tensor([[1.0, -1.0, 2.0, -2.0]]).unsqueeze(-1).unsqueeze(-1) module = torch.nn.PReLU()", "torch._C._jit_to_backend(\"nnapi\", traced, compile_spec) def tearDown(self): # Change dtype back to", "compile_spec) # No Tensor or TensorList under the inputs key", "traced, compile_spec) compile_spec = {\"forward\": {\"inputs\": [1]}} with self.assertRaisesRegex(RuntimeError, \"method_compile_spec", "be run directly, use:\\n\\n\" \"\\tpython test/test_jit.py TESTNAME\\n\\n\" \"instead.\" ) \"\"\"", "needed for IS_WINDOWS or IS_MACOS to skip the tests. #", "not supported by the Android NNAPI delegate) # Float32 should", "torch._C._jit_to_backend(\"nnapi\", traced, compile_spec) compile_spec = {\"forward\": {\"inputs\": [1]}} with self.assertRaisesRegex(RuntimeError,", "test_tensor_input(self): # Lower a simple module args = torch.tensor([[1.0, -1.0,", "or Tensor List which bundles input parameters: shape, dtype, quantization,", "__name__ == \"__main__\": raise RuntimeError( \"This test file is not", "the test as libnnapi_backend.so was not found\") @unittest.skipIf(TEST_WITH_ASAN, \"Unresolved bug", "{\"forward\": {\"inputs\": at::Tensor}} OR {\"forward\": {\"inputs\": c10::List<at::Tensor>}}\"\"\" # No forward", "in a list self.call_lowering_to_nnapi(traced, [args]) # Test exceptions for incorrect", "No inputs key (in the dictionary under the forward key)", "torch.tensor([[1.0, -1.0, 2.0, -2.0]]).unsqueeze(-1).unsqueeze(-1) module = torch.nn.PReLU() traced = torch.jit.trace(module,", "is not meant to be run directly, use:\\n\\n\" \"\\tpython test/test_jit.py", "+ errorMsgTail): torch._C._jit_to_backend(\"nnapi\", traced, compile_spec) # No inputs key (in", "# Change dtype back to default (Otherwise, other unit tests", "back to default (Otherwise, other unit tests will complain) torch.set_default_dtype(self.default_dtype)", "call_lowering_to_nnapi(self, traced_module, args): compile_spec = {\"forward\": {\"inputs\": args}} return torch._C._jit_to_backend(\"nnapi\",", "skip is because ASAN is currently causing an error. #", "# It is still unclear how to resolve this. T95764916", "'libnnapi_backend.so' @unittest.skipIf(not os.path.exists(lib_path), \"Skipping the test as libnnapi_backend.so was not", "= torch.jit.trace(module, args) errorMsgTail = r\"\"\" method_compile_spec should contain a", "module = torch.nn.PReLU() traced = torch.jit.trace(module, args) # Argument input", "still unclear how to resolve this. T95764916 torch_root = Path(__file__).resolve().parent.parent.parent", "return torch._C._jit_to_backend(\"nnapi\", traced_module, compile_spec) def test_tensor_input(self): # Lower a simple", "files. torch.set_default_dtype(torch.float32) # Load nnapi delegate library torch.ops.load_library(str(lib_path)) # Override", "shape, dtype, quantization, and dimorder. For input shapes, use 0", "module = torch.nn.PReLU() self.default_dtype = module.weight.dtype # Change dtype to", "/ 'build' / 'lib' / 'libnnapi_backend.so' @unittest.skipIf(not os.path.exists(lib_path), \"Skipping the", "delegate API. \"\"\" # First skip is needed for IS_WINDOWS", "in other files. torch.set_default_dtype(torch.float32) # Load nnapi delegate library torch.ops.load_library(str(lib_path))", "a Tensor in a list self.call_lowering_to_nnapi(traced, [args]) # Test exceptions", "unittest import torch import torch._C from pathlib import Path from", "importable pytorch_test_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) sys.path.append(pytorch_test_dir) if __name__ == \"__main__\": raise", "parameters: shape, dtype, quantization, and dimorder. For input shapes, use", "\" \"under it's \\\"forward\\\" key.\" + errorMsgTail): torch._C._jit_to_backend(\"nnapi\", traced, compile_spec)", "for incorrect compile specs def test_compile_spec_santiy(self): args = torch.tensor([[1.0, -1.0,", "\\\"forward\\\" key.\" + errorMsgTail): torch._C._jit_to_backend(\"nnapi\", traced, compile_spec) # No Tensor", "was not found\") @unittest.skipIf(TEST_WITH_ASAN, \"Unresolved bug with ASAN\") class TestNnapiBackend(TestNNAPI):", "errorMsgTail): torch._C._jit_to_backend(\"nnapi\", traced, compile_spec) compile_spec = {\"forward\": {\"inputs\": [1]}} with", "\\\"forward\\\" key.\" + errorMsgTail): torch._C._jit_to_backend(\"nnapi\", traced, compile_spec) # No inputs", "should typically be the default in other files. torch.set_default_dtype(torch.float32) #", "{\"inputs\": at::Tensor}} OR {\"forward\": {\"inputs\": c10::List<at::Tensor>}}\"\"\" # No forward key", "a dictionary with an \\\"inputs\\\" key, \" \"under it's \\\"forward\\\"", "os.path.exists(lib_path), \"Skipping the test as libnnapi_backend.so was not found\") @unittest.skipIf(TEST_WITH_ASAN,", "# Make the helper files in test/ importable pytorch_test_dir =", "First skip is needed for IS_WINDOWS or IS_MACOS to skip", "libnnapi_backend.so was not found\") @unittest.skipIf(TEST_WITH_ASAN, \"Unresolved bug with ASAN\") class", "'lib' / 'libnnapi_backend.so' @unittest.skipIf(not os.path.exists(lib_path), \"Skipping the test as libnnapi_backend.so", "Tensor or TensorList under the inputs key compile_spec = {\"forward\":", "traced, compile_spec) # No inputs key (in the dictionary under", "in test/ importable pytorch_test_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) sys.path.append(pytorch_test_dir) if __name__ ==", "is needed for IS_WINDOWS or IS_MACOS to skip the tests.", "# Override def call_lowering_to_nnapi(self, traced_module, args): compile_spec = {\"forward\": {\"inputs\":", "flexible input. method_compile_spec must use the following format: {\"forward\": {\"inputs\":", "torch._C._jit_to_backend(\"nnapi\", traced, compile_spec) # No Tensor or TensorList under the", "sys.path.append(pytorch_test_dir) if __name__ == \"__main__\": raise RuntimeError( \"This test file", "compile_spec = {\"forward\": {\"inputs\": args}} return torch._C._jit_to_backend(\"nnapi\", traced_module, compile_spec) def", "changed dtype to float64, # which is not supported by", "def tearDown(self): # Change dtype back to default (Otherwise, other", "{\"inputs\": c10::List<at::Tensor>}}\"\"\" # No forward key compile_spec = {\"backward\": {\"inputs\":", "== \"__main__\": raise RuntimeError( \"This test file is not meant", "+ errorMsgTail): torch._C._jit_to_backend(\"nnapi\", traced, compile_spec) compile_spec = {\"forward\": {\"inputs\": [1]}}", "{\"forward\": 1} with self.assertRaisesRegex(RuntimeError, \"method_compile_spec does not contain a dictionary", "import sys import unittest import torch import torch._C from pathlib", "\\\"inputs\\\" key.\" + errorMsgTail): torch._C._jit_to_backend(\"nnapi\", traced, compile_spec) compile_spec = {\"forward\":", "= torch_root / 'build' / 'lib' / 'libnnapi_backend.so' @unittest.skipIf(not os.path.exists(lib_path),", "args) # Argument input is a single Tensor self.call_lowering_to_nnapi(traced, args)", "= {\"forward\": {\"not inputs\": args}} with self.assertRaisesRegex(RuntimeError, \"method_compile_spec does not", "Change dtype back to default (Otherwise, other unit tests will", "TestNNAPI, which loads Android NNAPI models without the delegate API.", "# Argument input is a Tensor in a list self.call_lowering_to_nnapi(traced,", "tearDown(self): # Change dtype back to default (Otherwise, other unit", "\"method_compile_spec does not contain the \\\"forward\\\" key.\" + errorMsgTail): torch._C._jit_to_backend(\"nnapi\",", "= torch.nn.PReLU() traced = torch.jit.trace(module, args) # Argument input is", "an error. # It is still unclear how to resolve", "self.assertRaisesRegex(RuntimeError, \"method_compile_spec does not contain the \\\"forward\\\" key.\" + errorMsgTail):", "= torch.nn.PReLU() traced = torch.jit.trace(module, args) errorMsgTail = r\"\"\" method_compile_spec", "error. # It is still unclear how to resolve this.", "dtype to float32 (since a different unit test changed dtype", "Argument input is a Tensor in a list self.call_lowering_to_nnapi(traced, [args])", "key, \" \"under it's \\\"forward\\\" key.\" + errorMsgTail): torch._C._jit_to_backend(\"nnapi\", traced,", "(since a different unit test changed dtype to float64, #", "Android NNAPI delegate) # Float32 should typically be the default", "if __name__ == \"__main__\": raise RuntimeError( \"This test file is", "class TestNnapiBackend(TestNNAPI): def setUp(self): super().setUp() # Save default dtype module", "compile_spec) def tearDown(self): # Change dtype back to default (Otherwise,", "key.\" + errorMsgTail): torch._C._jit_to_backend(\"nnapi\", traced, compile_spec) # No Tensor or", "Inherits most tests from TestNNAPI, which loads Android NNAPI models", "{\"backward\": {\"inputs\": args}} with self.assertRaisesRegex(RuntimeError, \"method_compile_spec does not contain the", "quantization, and dimorder. For input shapes, use 0 for run/load", "not meant to be run directly, use:\\n\\n\" \"\\tpython test/test_jit.py TESTNAME\\n\\n\"", "raise RuntimeError( \"This test file is not meant to be", "\\\"forward\\\" key.\" + errorMsgTail): torch._C._jit_to_backend(\"nnapi\", traced, compile_spec) # No dictionary", "args) errorMsgTail = r\"\"\" method_compile_spec should contain a Tensor or", "# Save default dtype module = torch.nn.PReLU() self.default_dtype = module.weight.dtype", "method_compile_spec should contain a Tensor or Tensor List which bundles", "a Tensor or TensorList, under it's \\\"inputs\\\" key.\" + errorMsgTail):", "Android NNAPI models without the delegate API. \"\"\" # First", "API. \"\"\" # First skip is needed for IS_WINDOWS or", "other files. torch.set_default_dtype(torch.float32) # Load nnapi delegate library torch.ops.load_library(str(lib_path)) #", "compile_spec) # No inputs key (in the dictionary under the", "TensorList, under it's \\\"inputs\\\" key.\" + errorMsgTail): torch._C._jit_to_backend(\"nnapi\", traced, compile_spec)", "{\"forward\": {\"inputs\": c10::List<at::Tensor>}}\"\"\" # No forward key compile_spec = {\"backward\":", "run/load time flexible input. method_compile_spec must use the following format:", "for Nnapi backend with delegate Inherits most tests from TestNNAPI,", "input parameters: shape, dtype, quantization, and dimorder. For input shapes,", "a single Tensor self.call_lowering_to_nnapi(traced, args) # Argument input is a", "'build' / 'lib' / 'libnnapi_backend.so' @unittest.skipIf(not os.path.exists(lib_path), \"Skipping the test", "self.default_dtype = module.weight.dtype # Change dtype to float32 (since a", "self.assertRaisesRegex(RuntimeError, \"method_compile_spec does not contain either a Tensor or TensorList,", "def call_lowering_to_nnapi(self, traced_module, args): compile_spec = {\"forward\": {\"inputs\": args}} return", "traced = torch.jit.trace(module, args) errorMsgTail = r\"\"\" method_compile_spec should contain", "TestNnapiBackend(TestNNAPI): def setUp(self): super().setUp() # Save default dtype module =", "= torch.tensor([[1.0, -1.0, 2.0, -2.0]]).unsqueeze(-1).unsqueeze(-1) module = torch.nn.PReLU() traced =", "is because ASAN is currently causing an error. # It", "the dictionary under the forward key) compile_spec = {\"forward\": {\"not", "def setUp(self): super().setUp() # Save default dtype module = torch.nn.PReLU()", "# No dictionary under the forward key compile_spec = {\"forward\":", "import TestNNAPI from torch.testing._internal.common_utils import TEST_WITH_ASAN # Make the helper", "method_compile_spec must use the following format: {\"forward\": {\"inputs\": at::Tensor}} OR", "to float64, # which is not supported by the Android", "use the following format: {\"forward\": {\"inputs\": at::Tensor}} OR {\"forward\": {\"inputs\":", "compile specs def test_compile_spec_santiy(self): args = torch.tensor([[1.0, -1.0, 2.0, -2.0]]).unsqueeze(-1).unsqueeze(-1)", "torch._C from pathlib import Path from test_nnapi import TestNNAPI from", "nnapi delegate library torch.ops.load_library(str(lib_path)) # Override def call_lowering_to_nnapi(self, traced_module, args):", "or TensorList, under it's \\\"inputs\\\" key.\" + errorMsgTail): torch._C._jit_to_backend(\"nnapi\", traced,", "# which is not supported by the Android NNAPI delegate)", "tests. # Second skip is because ASAN is currently causing", "/ 'libnnapi_backend.so' @unittest.skipIf(not os.path.exists(lib_path), \"Skipping the test as libnnapi_backend.so was", "float32 (since a different unit test changed dtype to float64,", "is a Tensor in a list self.call_lowering_to_nnapi(traced, [args]) # Test", "incorrect compile specs def test_compile_spec_santiy(self): args = torch.tensor([[1.0, -1.0, 2.0,", "{\"forward\": {\"inputs\": [1]}} with self.assertRaisesRegex(RuntimeError, \"method_compile_spec does not contain either", "\"This test file is not meant to be run directly,", "TESTNAME\\n\\n\" \"instead.\" ) \"\"\" Unit Tests for Nnapi backend with", "\"\"\" Unit Tests for Nnapi backend with delegate Inherits most", "\"instead.\" ) \"\"\" Unit Tests for Nnapi backend with delegate", "+ errorMsgTail): torch._C._jit_to_backend(\"nnapi\", traced, compile_spec) # No dictionary under the", "# Change dtype to float32 (since a different unit test", "directly, use:\\n\\n\" \"\\tpython test/test_jit.py TESTNAME\\n\\n\" \"instead.\" ) \"\"\" Unit Tests", "T95764916 torch_root = Path(__file__).resolve().parent.parent.parent lib_path = torch_root / 'build' /", "default dtype module = torch.nn.PReLU() self.default_dtype = module.weight.dtype # Change", "errorMsgTail): torch._C._jit_to_backend(\"nnapi\", traced, compile_spec) # No inputs key (in the", "dtype back to default (Otherwise, other unit tests will complain)", "with ASAN\") class TestNnapiBackend(TestNNAPI): def setUp(self): super().setUp() # Save default", "files in test/ importable pytorch_test_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) sys.path.append(pytorch_test_dir) if __name__", "the forward key compile_spec = {\"forward\": 1} with self.assertRaisesRegex(RuntimeError, \"method_compile_spec", "NNAPI models without the delegate API. \"\"\" # First skip", "= torch.jit.trace(module, args) # Argument input is a single Tensor", "with an \\\"inputs\\\" key, \" \"under it's \\\"forward\\\" key.\" +", "test/ importable pytorch_test_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) sys.path.append(pytorch_test_dir) if __name__ == \"__main__\":", "list self.call_lowering_to_nnapi(traced, [args]) # Test exceptions for incorrect compile specs", "models without the delegate API. \"\"\" # First skip is", "under the inputs key compile_spec = {\"forward\": {\"inputs\": 1}} with", "os import sys import unittest import torch import torch._C from", "contain the \\\"forward\\\" key.\" + errorMsgTail): torch._C._jit_to_backend(\"nnapi\", traced, compile_spec) #", "= {\"backward\": {\"inputs\": args}} with self.assertRaisesRegex(RuntimeError, \"method_compile_spec does not contain" ]
[ "= 1 feature_encode_type = \"uni\" # graph_encode_method = \"max-pooling\" #", "= 200 num_layers_decode = 1 word_size_max = 1 dropout =", "\"../data/no_cycle/test.data\" word_idx_file_path = \"../data/word.idx\" word_embedding_dim = 100 train_batch_size = 32", "= 100 feature_max_len = 1 feature_encode_type = \"uni\" # graph_encode_method", "test_data_path = \"../data/no_cycle/test.data\" word_idx_file_path = \"../data/word.idx\" word_embedding_dim = 100 train_batch_size", "word_size_max = 1 dropout = 0.0 path_embed_method = \"lstm\" #", "word_embedding_dim = 100 train_batch_size = 32 dev_batch_size = 500 test_batch_size", "cnn or lstm or bi-lstm unknown_word = \"<unk>\" PAD =", "beam_width = 4 attention = True num_layers = 1 #", "= \"bi\" # \"single\" or \"bi\" concat = True encoder", "500 l2_lambda = 0.000001 learning_rate = 0.001 epochs = 100", "= 1 word_size_max = 1 dropout = 0.0 path_embed_method =", "= 4 attention = True num_layers = 1 # 1", "encoder_hidden_dim = 200 num_layers_decode = 1 word_size_max = 1 dropout", "# 1 or 2 # the following are for the", "\"max-pooling\" # \"lstm\" or \"max-pooling\" graph_encode_direction = \"bi\" # \"single\"", "\"gated_gcn\" # \"gated_gcn\" \"gcn\" \"seq\" lstm_in_gcn = \"none\" # before,", "GO = \"<GO>\" EOS = \"<EOS>\" deal_unknown_words = True seq_max_len", "\"greedy\" # greedy, beam beam_width = 4 attention = True", "\"../data/no_cycle/dev.data\" test_data_path = \"../data/no_cycle/test.data\" word_idx_file_path = \"../data/word.idx\" word_embedding_dim = 100", "EOS = \"<EOS>\" deal_unknown_words = True seq_max_len = 11 decoder_type", "\"lstm\" or \"max-pooling\" graph_encode_direction = \"bi\" # \"single\" or \"bi\"", "graph_encode_direction = \"bi\" # \"single\" or \"bi\" concat = True", "bi-lstm unknown_word = \"<unk>\" PAD = \"<PAD>\" GO = \"<GO>\"", "train_data_path = \"../data/no_cycle/train.data\" dev_data_path = \"../data/no_cycle/dev.data\" test_data_path = \"../data/no_cycle/test.data\" word_idx_file_path", "= 4 hidden_layer_dim = 100 feature_max_len = 1 feature_encode_type =", "\"<PAD>\" GO = \"<GO>\" EOS = \"<EOS>\" deal_unknown_words = True", "= 1 # 1 or 2 # the following are", "= \"<PAD>\" GO = \"<GO>\" EOS = \"<EOS>\" deal_unknown_words =", "train_batch_size = 32 dev_batch_size = 500 test_batch_size = 500 l2_lambda", "dropout = 0.0 path_embed_method = \"lstm\" # cnn or lstm", "= True encoder = \"gated_gcn\" # \"gated_gcn\" \"gcn\" \"seq\" lstm_in_gcn", "lstm or bi-lstm unknown_word = \"<unk>\" PAD = \"<PAD>\" GO", "= 32 dev_batch_size = 500 test_batch_size = 500 l2_lambda =", "dev_data_path = \"../data/no_cycle/dev.data\" test_data_path = \"../data/no_cycle/test.data\" word_idx_file_path = \"../data/word.idx\" word_embedding_dim", "seq_max_len = 11 decoder_type = \"greedy\" # greedy, beam beam_width", "encoding method weight_decay = 0.0000 sample_size_per_layer = 4 sample_layer_size =", "= \"greedy\" # greedy, beam beam_width = 4 attention =", "the graph encoding method weight_decay = 0.0000 sample_size_per_layer = 4", "# the following are for the graph encoding method weight_decay", "\"max-pooling\" graph_encode_direction = \"bi\" # \"single\" or \"bi\" concat =", "= \"../data/word.idx\" word_embedding_dim = 100 train_batch_size = 32 dev_batch_size =", "4 hidden_layer_dim = 100 feature_max_len = 1 feature_encode_type = \"uni\"", "\"<unk>\" PAD = \"<PAD>\" GO = \"<GO>\" EOS = \"<EOS>\"", "4 sample_layer_size = 4 hidden_layer_dim = 100 feature_max_len = 1", "= \"max-pooling\" # \"lstm\" or \"max-pooling\" graph_encode_direction = \"bi\" #", "0.0000 sample_size_per_layer = 4 sample_layer_size = 4 hidden_layer_dim = 100", "\"uni\" # graph_encode_method = \"max-pooling\" # \"lstm\" or \"max-pooling\" graph_encode_direction", "# \"lstm\" or \"max-pooling\" graph_encode_direction = \"bi\" # \"single\" or", "are for the graph encoding method weight_decay = 0.0000 sample_size_per_layer", "\"single\" or \"bi\" concat = True encoder = \"gated_gcn\" #", "<gh_stars>10-100 train_data_path = \"../data/no_cycle/train.data\" dev_data_path = \"../data/no_cycle/dev.data\" test_data_path = \"../data/no_cycle/test.data\"", "greedy, beam beam_width = 4 attention = True num_layers =", "feature_encode_type = \"uni\" # graph_encode_method = \"max-pooling\" # \"lstm\" or", "= 100 encoder_hidden_dim = 200 num_layers_decode = 1 word_size_max =", "= \"<GO>\" EOS = \"<EOS>\" deal_unknown_words = True seq_max_len =", "1 # 1 or 2 # the following are for", "= True num_layers = 1 # 1 or 2 #", "PAD = \"<PAD>\" GO = \"<GO>\" EOS = \"<EOS>\" deal_unknown_words", "or bi-lstm unknown_word = \"<unk>\" PAD = \"<PAD>\" GO =", "= \"<EOS>\" deal_unknown_words = True seq_max_len = 11 decoder_type =", "11 decoder_type = \"greedy\" # greedy, beam beam_width = 4", "= 4 sample_layer_size = 4 hidden_layer_dim = 100 feature_max_len =", "1 or 2 # the following are for the graph", "= \"../data/no_cycle/dev.data\" test_data_path = \"../data/no_cycle/test.data\" word_idx_file_path = \"../data/word.idx\" word_embedding_dim =", "1 feature_encode_type = \"uni\" # graph_encode_method = \"max-pooling\" # \"lstm\"", "attention = True num_layers = 1 # 1 or 2", "True encoder = \"gated_gcn\" # \"gated_gcn\" \"gcn\" \"seq\" lstm_in_gcn =", "# \"single\" or \"bi\" concat = True encoder = \"gated_gcn\"", "100 encoder_hidden_dim = 200 num_layers_decode = 1 word_size_max = 1", "learning_rate = 0.001 epochs = 100 encoder_hidden_dim = 200 num_layers_decode", "True seq_max_len = 11 decoder_type = \"greedy\" # greedy, beam", "dev_batch_size = 500 test_batch_size = 500 l2_lambda = 0.000001 learning_rate", "\"lstm\" # cnn or lstm or bi-lstm unknown_word = \"<unk>\"", "= 500 test_batch_size = 500 l2_lambda = 0.000001 learning_rate =", "\"bi\" concat = True encoder = \"gated_gcn\" # \"gated_gcn\" \"gcn\"", "\"gated_gcn\" \"gcn\" \"seq\" lstm_in_gcn = \"none\" # before, after, none", "\"<EOS>\" deal_unknown_words = True seq_max_len = 11 decoder_type = \"greedy\"", "2 # the following are for the graph encoding method", "test_batch_size = 500 l2_lambda = 0.000001 learning_rate = 0.001 epochs", "= \"lstm\" # cnn or lstm or bi-lstm unknown_word =", "hidden_layer_dim = 100 feature_max_len = 1 feature_encode_type = \"uni\" #", "l2_lambda = 0.000001 learning_rate = 0.001 epochs = 100 encoder_hidden_dim", "following are for the graph encoding method weight_decay = 0.0000", "0.000001 learning_rate = 0.001 epochs = 100 encoder_hidden_dim = 200", "path_embed_method = \"lstm\" # cnn or lstm or bi-lstm unknown_word", "1 word_size_max = 1 dropout = 0.0 path_embed_method = \"lstm\"", "= \"../data/no_cycle/train.data\" dev_data_path = \"../data/no_cycle/dev.data\" test_data_path = \"../data/no_cycle/test.data\" word_idx_file_path =", "or lstm or bi-lstm unknown_word = \"<unk>\" PAD = \"<PAD>\"", "num_layers_decode = 1 word_size_max = 1 dropout = 0.0 path_embed_method", "200 num_layers_decode = 1 word_size_max = 1 dropout = 0.0", "\"<GO>\" EOS = \"<EOS>\" deal_unknown_words = True seq_max_len = 11", "beam beam_width = 4 attention = True num_layers = 1", "decoder_type = \"greedy\" # greedy, beam beam_width = 4 attention", "sample_layer_size = 4 hidden_layer_dim = 100 feature_max_len = 1 feature_encode_type", "# greedy, beam beam_width = 4 attention = True num_layers", "= 1 dropout = 0.0 path_embed_method = \"lstm\" # cnn", "= 100 train_batch_size = 32 dev_batch_size = 500 test_batch_size =", "4 attention = True num_layers = 1 # 1 or", "deal_unknown_words = True seq_max_len = 11 decoder_type = \"greedy\" #", "\"bi\" # \"single\" or \"bi\" concat = True encoder =", "num_layers = 1 # 1 or 2 # the following", "# graph_encode_method = \"max-pooling\" # \"lstm\" or \"max-pooling\" graph_encode_direction =", "= \"../data/no_cycle/test.data\" word_idx_file_path = \"../data/word.idx\" word_embedding_dim = 100 train_batch_size =", "weight_decay = 0.0000 sample_size_per_layer = 4 sample_layer_size = 4 hidden_layer_dim", "0.0 path_embed_method = \"lstm\" # cnn or lstm or bi-lstm", "100 feature_max_len = 1 feature_encode_type = \"uni\" # graph_encode_method =", "\"../data/no_cycle/train.data\" dev_data_path = \"../data/no_cycle/dev.data\" test_data_path = \"../data/no_cycle/test.data\" word_idx_file_path = \"../data/word.idx\"", "= 0.001 epochs = 100 encoder_hidden_dim = 200 num_layers_decode =", "the following are for the graph encoding method weight_decay =", "for the graph encoding method weight_decay = 0.0000 sample_size_per_layer =", "= \"<unk>\" PAD = \"<PAD>\" GO = \"<GO>\" EOS =", "True num_layers = 1 # 1 or 2 # the", "= 0.0 path_embed_method = \"lstm\" # cnn or lstm or", "= \"uni\" # graph_encode_method = \"max-pooling\" # \"lstm\" or \"max-pooling\"", "or \"max-pooling\" graph_encode_direction = \"bi\" # \"single\" or \"bi\" concat", "\"../data/word.idx\" word_embedding_dim = 100 train_batch_size = 32 dev_batch_size = 500", "epochs = 100 encoder_hidden_dim = 200 num_layers_decode = 1 word_size_max", "feature_max_len = 1 feature_encode_type = \"uni\" # graph_encode_method = \"max-pooling\"", "= True seq_max_len = 11 decoder_type = \"greedy\" # greedy,", "or 2 # the following are for the graph encoding", "= 0.000001 learning_rate = 0.001 epochs = 100 encoder_hidden_dim =", "1 dropout = 0.0 path_embed_method = \"lstm\" # cnn or", "method weight_decay = 0.0000 sample_size_per_layer = 4 sample_layer_size = 4", "encoder = \"gated_gcn\" # \"gated_gcn\" \"gcn\" \"seq\" lstm_in_gcn = \"none\"", "or \"bi\" concat = True encoder = \"gated_gcn\" # \"gated_gcn\"", "graph encoding method weight_decay = 0.0000 sample_size_per_layer = 4 sample_layer_size", "# cnn or lstm or bi-lstm unknown_word = \"<unk>\" PAD", "32 dev_batch_size = 500 test_batch_size = 500 l2_lambda = 0.000001", "100 train_batch_size = 32 dev_batch_size = 500 test_batch_size = 500", "= \"gated_gcn\" # \"gated_gcn\" \"gcn\" \"seq\" lstm_in_gcn = \"none\" #", "# \"gated_gcn\" \"gcn\" \"seq\" lstm_in_gcn = \"none\" # before, after,", "sample_size_per_layer = 4 sample_layer_size = 4 hidden_layer_dim = 100 feature_max_len", "concat = True encoder = \"gated_gcn\" # \"gated_gcn\" \"gcn\" \"seq\"", "word_idx_file_path = \"../data/word.idx\" word_embedding_dim = 100 train_batch_size = 32 dev_batch_size", "500 test_batch_size = 500 l2_lambda = 0.000001 learning_rate = 0.001", "= 0.0000 sample_size_per_layer = 4 sample_layer_size = 4 hidden_layer_dim =", "= 500 l2_lambda = 0.000001 learning_rate = 0.001 epochs =", "= 11 decoder_type = \"greedy\" # greedy, beam beam_width =", "unknown_word = \"<unk>\" PAD = \"<PAD>\" GO = \"<GO>\" EOS", "graph_encode_method = \"max-pooling\" # \"lstm\" or \"max-pooling\" graph_encode_direction = \"bi\"", "0.001 epochs = 100 encoder_hidden_dim = 200 num_layers_decode = 1" ]
[ "fit_on_startup = pyqtSignal() SHOW_ERROR_BARS = \"Show error bars\" SHOW_ERROR_BARS_NOT_LOADED =", "self.__dsbEnergyShift.setSingleStep(0.01) self.__chkShowErrorBars = QCheckBox(self.SHOW_ERROR_BARS_NOT_LOADED) self.__chkShowErrorBars.stateChanged.connect(self.__chkShowErrorBars_changed) self.__chkIgnoreFirstPoint = QCheckBox('Ignore first data", "if self.getData() is not None: return self.getData()[-1][0] else: return None", "2) self.__mainLayout.addWidget(self.__chkIgnoreFirstPoint, 2, 0, 1, 2) self.__chkIgnoreFirstPoint.setVisible(False) self.reset(False) def reset(self,", "= QGridLayout() self.setLayout(self.__mainLayout) self.__mainLayout.setAlignment(Qt.AlignTop) self.__mainLayout.addWidget(self.__lblEnergyShift, 0, 0) self.__mainLayout.addWidget(self.__dsbEnergyShift, 0, 1)", "data_shift = pyqtSignal(np.float64) load_fits = pyqtSignal(list) load_view = pyqtSignal(str) load_meta", "from PyQt5.QtCore import pyqtSignal, Qt import helplib as hl import", "= QLabel(\"Energy Shift:\") self.__dsbEnergyShift = InftyDoubleSpinBox() self.__dsbEnergyShift.editingFinished.connect(self.__energyShiftChanged) self.__dsbEnergyShift.setSingleStep(0.01) self.__chkShowErrorBars =", "__shiftData(self, increment): try: if self.__data is not None: for set", "self.fit_on_startup.emit() return id_found def load_from_data_string(self, data_string): if data_string is not", "self.__chkShowErrorBars.isChecked() def setShowErrorBars(self, value): self.__chkShowErrorBars.setChecked(value) def getIgnoreFirstPoint(self): return self.__chkIgnoreFirstPoint.isChecked() def", "id_found =\\ hl.readFileForFitsDataAndStdErrorAndMetaData(fileName, id_string) #we need a copy to not", "pyqtSignal(np.float64) load_fits = pyqtSignal(list) load_view = pyqtSignal(str) load_meta = pyqtSignal(str)", "first data point.') self.__chkIgnoreFirstPoint.stateChanged.connect(self.__chkIgnoreFirstPoint_changed) self.__mainLayout = QGridLayout() self.setLayout(self.__mainLayout) self.__mainLayout.setAlignment(Qt.AlignTop) self.__mainLayout.addWidget(self.__lblEnergyShift,", "def hasStdErrors(self): return self.__stdErrors is not None def loadFile(self, fileName,", "self.__chkShowErrorBars.setText(self.SHOW_ERROR_BARS_NOT_LOADED) self.__chkShowErrorBars.setEnabled(self.hasStdErrors()) self.__chkShowErrorBars.setChecked(self.hasStdErrors()) self.__chkIgnoreFirstPoint.setEnabled(True) self.data_changed.emit(self.hasStdErrors(), self.getIgnoreFirstPoint()) self.load_fits.emit(fit_strings) self.load_view.emit(view_string) self.load_meta.emit(meta_string) self.load_from_data_string(data_string)", "first_point = 1 return self.__stdErrors[first_point:] else: return None def getMax_Energy(self):", "not None: return self.getData()[0][0] else: return None def getShowErrorBars(self): return", "== '0' or item[1] == 'False': self.setIgnoreFirstPoint(False) def get_data_string(self): return", "0 if self.getIgnoreFirstPoint(): first_point = 1 return self.__stdErrors[first_point:] else: return", "self.__prevShift self.__prevShift = energyShift self.data_shift.emit(increment) self.data_changed.emit(self.getShowErrorBars(), self.getIgnoreFirstPoint()) # def setData(self,", "== 'False': self.setIgnoreFirstPoint(False) def get_data_string(self): return 'egs=' + str(self.getEnergyShift()) +", "None def loadFile(self, fileName, id_string): self.__all_data, self.__stdErrors, (fit_strings, view_string, data_string,", "view_string, data_string, meta_string): hl.saveFilewithMetaData(id_string, fileName, self.__all_data, (fit_strings, view_string, data_string, meta_string))", "QCheckBox('Ignore first data point.') self.__chkIgnoreFirstPoint.stateChanged.connect(self.__chkIgnoreFirstPoint_changed) self.__mainLayout = QGridLayout() self.setLayout(self.__mainLayout) self.__mainLayout.setAlignment(Qt.AlignTop)", "self.__chkIgnoreFirstPoint.setChecked(value) def hasStdErrors(self): return self.__stdErrors is not None def loadFile(self,", "== 2: if (item[0] == 'egs'): self.setEnergyShift(np.float64(item[1])) elif item[0] ==", "first_point = 0 if self.getIgnoreFirstPoint(): first_point = 1 return self.__data[first_point:,]", "self.__dsbEnergyShift.value() - value increment = value - self.__dsbEnergyShift.value() self.__dsbEnergyShift.setValue(value) #self.__shiftData(increment)", "self.reset(False) def reset(self, enable): self.__data = None self.__all_data = None", "self.__dsbEnergyShift = InftyDoubleSpinBox() self.__dsbEnergyShift.editingFinished.connect(self.__energyShiftChanged) self.__dsbEnergyShift.setSingleStep(0.01) self.__chkShowErrorBars = QCheckBox(self.SHOW_ERROR_BARS_NOT_LOADED) self.__chkShowErrorBars.stateChanged.connect(self.__chkShowErrorBars_changed) self.__chkIgnoreFirstPoint", "item[1] == 'False': self.setShowErrorBars(False) elif item[0] == 'ifd': if item[1]", "self.setShowErrorBars(False) elif item[0] == 'ifd': if item[1] == '1' or", "None self.__chkShowErrorBars.setCheckable(True) self.__chkShowErrorBars.setChecked(False) self.__chkShowErrorBars.setEnabled(False) self.__chkIgnoreFirstPoint.setCheckable(True) self.__chkIgnoreFirstPoint.setChecked(False) self.__chkIgnoreFirstPoint.setEnabled(False) self.setEnergyShift(0.0) self.__prevShift =", "'1' or item[1] == 'True': self.setIgnoreFirstPoint(True) elif item[1] == '0'", "= InftyDoubleSpinBox() self.__dsbEnergyShift.editingFinished.connect(self.__energyShiftChanged) self.__dsbEnergyShift.setSingleStep(0.01) self.__chkShowErrorBars = QCheckBox(self.SHOW_ERROR_BARS_NOT_LOADED) self.__chkShowErrorBars.stateChanged.connect(self.__chkShowErrorBars_changed) self.__chkIgnoreFirstPoint =", "return None def getShowErrorBars(self): return self.__chkShowErrorBars.isChecked() def setShowErrorBars(self, value): self.__chkShowErrorBars.setChecked(value)", "self.__chkIgnoreFirstPoint.setCheckState(state) self.ignoreFirstPoint_changed.emit(self.getIgnoreFirstPoint()) def __energyShiftChanged(self): self.cause_shift() def cause_shift(self): energyShift = self.__dsbEnergyShift.value()", "self.__mainLayout.setAlignment(Qt.AlignTop) self.__mainLayout.addWidget(self.__lblEnergyShift, 0, 0) self.__mainLayout.addWidget(self.__dsbEnergyShift, 0, 1) self.__mainLayout.addWidget(self.__chkShowErrorBars, 1, 0,", "value - self.__dsbEnergyShift.value() self.__dsbEnergyShift.setValue(value) #self.__shiftData(increment) #self.data_shift.emit(increment) def __shiftData(self, increment): try:", "altered data! self.__data = (self.__all_data[:, 0:2]).copy() if len(self.__data) <= 1:", "class dataControlWidget(QGroupBox): showErrorBars_changed = pyqtSignal(bool) ignoreFirstPoint_changed = pyqtSignal(bool) data_changed =", "#we need a copy to not save any altered data!", "= \"Show error bars\" SHOW_ERROR_BARS_NOT_LOADED = \"Show error bars (could", "np class dataControlWidget(QGroupBox): showErrorBars_changed = pyqtSignal(bool) ignoreFirstPoint_changed = pyqtSignal(bool) data_changed", "pyqtSignal(bool, bool) data_shift = pyqtSignal(np.float64) load_fits = pyqtSignal(list) load_view =", "0, 1, 2) self.__mainLayout.addWidget(self.__chkIgnoreFirstPoint, 2, 0, 1, 2) self.__chkIgnoreFirstPoint.setVisible(False) self.reset(False)", "fileName, id_string): self.__all_data, self.__stdErrors, (fit_strings, view_string, data_string, meta_string), id_found =\\", "== '1' or item[1] == 'True': self.setShowErrorBars(True) elif item[1] ==", "def setShowErrorBars(self, value): self.__chkShowErrorBars.setChecked(value) def getIgnoreFirstPoint(self): return self.__chkIgnoreFirstPoint.isChecked() def setIgnoreFirstPoint(self,", "self.__chkShowErrorBars.setChecked(self.hasStdErrors()) self.__chkIgnoreFirstPoint.setEnabled(True) self.data_changed.emit(self.hasStdErrors(), self.getIgnoreFirstPoint()) self.load_fits.emit(fit_strings) self.load_view.emit(view_string) self.load_meta.emit(meta_string) self.load_from_data_string(data_string) self.cause_shift() self.fit_on_startup.emit()", "= pyqtSignal() SHOW_ERROR_BARS = \"Show error bars\" SHOW_ERROR_BARS_NOT_LOADED = \"Show", "InftyDoubleSpinBox() self.__dsbEnergyShift.editingFinished.connect(self.__energyShiftChanged) self.__dsbEnergyShift.setSingleStep(0.01) self.__chkShowErrorBars = QCheckBox(self.SHOW_ERROR_BARS_NOT_LOADED) self.__chkShowErrorBars.stateChanged.connect(self.__chkShowErrorBars_changed) self.__chkIgnoreFirstPoint = QCheckBox('Ignore", "= split_string[i].split('=') if len(item) == 2: if (item[0] == 'egs'):", "def __chkShowErrorBars_changed(self, state): self.__chkShowErrorBars.setCheckState(state) self.showErrorBars_changed.emit(self.getShowErrorBars()) def __chkIgnoreFirstPoint_changed(self, state): self.__chkIgnoreFirstPoint.setCheckState(state) self.ignoreFirstPoint_changed.emit(self.getIgnoreFirstPoint())", "QLabel(\"Energy Shift:\") self.__dsbEnergyShift = InftyDoubleSpinBox() self.__dsbEnergyShift.editingFinished.connect(self.__energyShiftChanged) self.__dsbEnergyShift.setSingleStep(0.01) self.__chkShowErrorBars = QCheckBox(self.SHOW_ERROR_BARS_NOT_LOADED)", "self.__mainLayout.addWidget(self.__chkIgnoreFirstPoint, 2, 0, 1, 2) self.__chkIgnoreFirstPoint.setVisible(False) self.reset(False) def reset(self, enable):", "setShowErrorBars(self, value): self.__chkShowErrorBars.setChecked(value) def getIgnoreFirstPoint(self): return self.__chkIgnoreFirstPoint.isChecked() def setIgnoreFirstPoint(self, value):", "1) self.__mainLayout.addWidget(self.__chkShowErrorBars, 1, 0, 1, 2) self.__mainLayout.addWidget(self.__chkIgnoreFirstPoint, 2, 0, 1,", "numpy as np class dataControlWidget(QGroupBox): showErrorBars_changed = pyqtSignal(bool) ignoreFirstPoint_changed =", "return 'egs=' + str(self.getEnergyShift()) + '\\vseb=' + str(self.getShowErrorBars()) +\\ '\\vifd='", "not None def loadFile(self, fileName, id_string): self.__all_data, self.__stdErrors, (fit_strings, view_string,", "return self.__stdErrors is not None def loadFile(self, fileName, id_string): self.__all_data,", "except Exception as e: print(e) def getStdErrors(self): if self.__stdErrors is", "self.data_shift.emit(increment) self.data_changed.emit(self.getShowErrorBars(), self.getIgnoreFirstPoint()) # def setData(self, data): # self.__data =", "is not None: return self.getData()[-1][0] else: return None def getMin_Energy(self):", "len(item) == 2: if (item[0] == 'egs'): self.setEnergyShift(np.float64(item[1])) elif item[0]", "self.ignoreFirstPoint_changed.emit(self.getIgnoreFirstPoint()) def __energyShiftChanged(self): self.cause_shift() def cause_shift(self): energyShift = self.__dsbEnergyShift.value() increment", "= pyqtSignal(np.float64) load_fits = pyqtSignal(list) load_view = pyqtSignal(str) load_meta =", "self.__data = None self.__all_data = None self.__stdErrors = None self.__chkShowErrorBars.setCheckable(True)", "0:2]).copy() if len(self.__data) <= 1: raise Exception(\"Not enough data in", "'ifd': if item[1] == '1' or item[1] == 'True': self.setIgnoreFirstPoint(True)", "if item[1] == '1' or item[1] == 'True': self.setShowErrorBars(True) elif", "== 'True': self.setIgnoreFirstPoint(True) elif item[1] == '0' or item[1] ==", "= self.__dsbEnergyShift.value() increment = energyShift - self.__prevShift self.__prevShift = energyShift", "== 'False': self.setShowErrorBars(False) elif item[0] == 'ifd': if item[1] ==", "- self.__prevShift self.__prevShift = energyShift self.data_shift.emit(increment) self.data_changed.emit(self.getShowErrorBars(), self.getIgnoreFirstPoint()) # def", "InftyDoubleSpinBox from PyQt5.QtCore import pyqtSignal, Qt import helplib as hl", "'0' or item[1] == 'False': self.setShowErrorBars(False) elif item[0] == 'ifd':", "<= 1: raise Exception(\"Not enough data in file!\") if self.hasStdErrors():", "return self.__stdErrors[first_point:] else: return None def getMax_Energy(self): if self.getData() is", "InftyDoubleSpinBox import InftyDoubleSpinBox from PyQt5.QtCore import pyqtSignal, Qt import helplib", "showErrorBars_changed = pyqtSignal(bool) ignoreFirstPoint_changed = pyqtSignal(bool) data_changed = pyqtSignal(bool, bool)", "# self.__data = data def getData(self): first_point = 0 if", "__chkIgnoreFirstPoint_changed(self, state): self.__chkIgnoreFirstPoint.setCheckState(state) self.ignoreFirstPoint_changed.emit(self.getIgnoreFirstPoint()) def __energyShiftChanged(self): self.cause_shift() def cause_shift(self): energyShift", "self.__chkIgnoreFirstPoint.setVisible(False) self.reset(False) def reset(self, enable): self.__data = None self.__all_data =", "is not None: for set in self.__data: set[0] += increment", "a copy to not save any altered data! self.__data =", "'1' or item[1] == 'True': self.setShowErrorBars(True) elif item[1] == '0'", "else: return None def getMax_Energy(self): if self.getData() is not None:", "if self.__data is not None: for set in self.__data: set[0]", "self.load_fits.emit(fit_strings) self.load_view.emit(view_string) self.load_meta.emit(meta_string) self.load_from_data_string(data_string) self.cause_shift() self.fit_on_startup.emit() return id_found def load_from_data_string(self,", "'egs'): self.setEnergyShift(np.float64(item[1])) elif item[0] == 'seb': if item[1] == '1'", "self.setTitle('Data Settings') self.__lblEnergyShift = QLabel(\"Energy Shift:\") self.__dsbEnergyShift = InftyDoubleSpinBox() self.__dsbEnergyShift.editingFinished.connect(self.__energyShiftChanged)", "bool) data_shift = pyqtSignal(np.float64) load_fits = pyqtSignal(list) load_view = pyqtSignal(str)", "getShowErrorBars(self): return self.__chkShowErrorBars.isChecked() def setShowErrorBars(self, value): self.__chkShowErrorBars.setChecked(value) def getIgnoreFirstPoint(self): return", "self.__chkIgnoreFirstPoint.isChecked() def setIgnoreFirstPoint(self, value): self.__chkIgnoreFirstPoint.setChecked(value) def hasStdErrors(self): return self.__stdErrors is", "= QCheckBox(self.SHOW_ERROR_BARS_NOT_LOADED) self.__chkShowErrorBars.stateChanged.connect(self.__chkShowErrorBars_changed) self.__chkIgnoreFirstPoint = QCheckBox('Ignore first data point.') self.__chkIgnoreFirstPoint.stateChanged.connect(self.__chkIgnoreFirstPoint_changed)", "def getData(self): first_point = 0 if self.getIgnoreFirstPoint(): first_point = 1", "self.getData()[0][0] else: return None def getShowErrorBars(self): return self.__chkShowErrorBars.isChecked() def setShowErrorBars(self,", "in file!\") if self.hasStdErrors(): self.__chkShowErrorBars.setText(self.SHOW_ERROR_BARS) else: self.__chkShowErrorBars.setText(self.SHOW_ERROR_BARS_NOT_LOADED) self.__chkShowErrorBars.setEnabled(self.hasStdErrors()) self.__chkShowErrorBars.setChecked(self.hasStdErrors()) self.__chkIgnoreFirstPoint.setEnabled(True)", "range(0, len(split_string)): item = split_string[i].split('=') if len(item) == 2: if", "hasStdErrors(self): return self.__stdErrors is not None def loadFile(self, fileName, id_string):", "from PyQt5.QtWidgets import QLabel, QWidget, QGridLayout, QCheckBox, QGroupBox from InftyDoubleSpinBox", "save any altered data! self.__data = (self.__all_data[:, 0:2]).copy() if len(self.__data)", "= pyqtSignal(str) fit_on_startup = pyqtSignal() SHOW_ERROR_BARS = \"Show error bars\"", "self.__stdErrors, (fit_strings, view_string, data_string, meta_string), id_found =\\ hl.readFileForFitsDataAndStdErrorAndMetaData(fileName, id_string) #we", "self.__data = (self.__all_data[:, 0:2]).copy() if len(self.__data) <= 1: raise Exception(\"Not", "self.__dsbEnergyShift.value() increment = energyShift - self.__prevShift self.__prevShift = energyShift self.data_shift.emit(increment)", "getEnergyShift(self): return (self.__dsbEnergyShift.value()) def setEnergyShift(self, value): #increment = self.__dsbEnergyShift.value() -", "or item[1] == 'False': self.setShowErrorBars(False) elif item[0] == 'ifd': if", "def getShowErrorBars(self): return self.__chkShowErrorBars.isChecked() def setShowErrorBars(self, value): self.__chkShowErrorBars.setChecked(value) def getIgnoreFirstPoint(self):", "self.__chkShowErrorBars.setChecked(value) def getIgnoreFirstPoint(self): return self.__chkIgnoreFirstPoint.isChecked() def setIgnoreFirstPoint(self, value): self.__chkIgnoreFirstPoint.setChecked(value) def", "raise Exception(\"Not enough data in file!\") if self.hasStdErrors(): self.__chkShowErrorBars.setText(self.SHOW_ERROR_BARS) else:", "value increment = value - self.__dsbEnergyShift.value() self.__dsbEnergyShift.setValue(value) #self.__shiftData(increment) #self.data_shift.emit(increment) def", "= pyqtSignal(bool) ignoreFirstPoint_changed = pyqtSignal(bool) data_changed = pyqtSignal(bool, bool) data_shift", "saveFile(self, fileName, id_string, fit_strings, view_string, data_string, meta_string): hl.saveFilewithMetaData(id_string, fileName, self.__all_data,", "self.getData() is not None: return self.getData()[-1][0] else: return None def", "SHOW_ERROR_BARS_NOT_LOADED = \"Show error bars (could not be calculated)\" def", "set in self.__data: set[0] += increment except Exception as e:", "in self.__data: set[0] += increment except Exception as e: print(e)", "getStdErrors(self): if self.__stdErrors is not None: first_point = 0 if", "if self.getIgnoreFirstPoint(): first_point = 1 return self.__data[first_point:,] def getEnergyShift(self): return", "def setIgnoreFirstPoint(self, value): self.__chkIgnoreFirstPoint.setChecked(value) def hasStdErrors(self): return self.__stdErrors is not", "is not None: split_string = data_string.split('\\v') for i in range(0,", "- self.__dsbEnergyShift.value() self.__dsbEnergyShift.setValue(value) #self.__shiftData(increment) #self.data_shift.emit(increment) def __shiftData(self, increment): try: if", "= pyqtSignal(str) load_meta = pyqtSignal(str) fit_on_startup = pyqtSignal() SHOW_ERROR_BARS =", "data_string, meta_string), id_found =\\ hl.readFileForFitsDataAndStdErrorAndMetaData(fileName, id_string) #we need a copy", "self.setIgnoreFirstPoint(False) def get_data_string(self): return 'egs=' + str(self.getEnergyShift()) + '\\vseb=' +", "cause_shift(self): energyShift = self.__dsbEnergyShift.value() increment = energyShift - self.__prevShift self.__prevShift", "self.data_changed.emit(self.hasStdErrors(), self.getIgnoreFirstPoint()) self.load_fits.emit(fit_strings) self.load_view.emit(view_string) self.load_meta.emit(meta_string) self.load_from_data_string(data_string) self.cause_shift() self.fit_on_startup.emit() return id_found", "self.__mainLayout.addWidget(self.__lblEnergyShift, 0, 0) self.__mainLayout.addWidget(self.__dsbEnergyShift, 0, 1) self.__mainLayout.addWidget(self.__chkShowErrorBars, 1, 0, 1,", "any altered data! self.__data = (self.__all_data[:, 0:2]).copy() if len(self.__data) <=", "None: for set in self.__data: set[0] += increment except Exception", "value): self.__chkIgnoreFirstPoint.setChecked(value) def hasStdErrors(self): return self.__stdErrors is not None def", "to not save any altered data! self.__data = (self.__all_data[:, 0:2]).copy()", "#self.data_shift.emit(increment) def __shiftData(self, increment): try: if self.__data is not None:", "split_string[i].split('=') if len(item) == 2: if (item[0] == 'egs'): self.setEnergyShift(np.float64(item[1]))", "setIgnoreFirstPoint(self, value): self.__chkIgnoreFirstPoint.setChecked(value) def hasStdErrors(self): return self.__stdErrors is not None", "self.__chkIgnoreFirstPoint.stateChanged.connect(self.__chkIgnoreFirstPoint_changed) self.__mainLayout = QGridLayout() self.setLayout(self.__mainLayout) self.__mainLayout.setAlignment(Qt.AlignTop) self.__mainLayout.addWidget(self.__lblEnergyShift, 0, 0) self.__mainLayout.addWidget(self.__dsbEnergyShift,", "else: self.__chkShowErrorBars.setText(self.SHOW_ERROR_BARS_NOT_LOADED) self.__chkShowErrorBars.setEnabled(self.hasStdErrors()) self.__chkShowErrorBars.setChecked(self.hasStdErrors()) self.__chkIgnoreFirstPoint.setEnabled(True) self.data_changed.emit(self.hasStdErrors(), self.getIgnoreFirstPoint()) self.load_fits.emit(fit_strings) self.load_view.emit(view_string) self.load_meta.emit(meta_string)", "item[1] == '1' or item[1] == 'True': self.setIgnoreFirstPoint(True) elif item[1]", "def getMax_Energy(self): if self.getData() is not None: return self.getData()[-1][0] else:", "None def getMin_Energy(self): if self.getData() is not None: return self.getData()[0][0]", "def setData(self, data): # self.__data = data def getData(self): first_point", "error bars (could not be calculated)\" def __init__(self): QWidget.__init__(self) self.setTitle('Data", "self.setIgnoreFirstPoint(True) elif item[1] == '0' or item[1] == 'False': self.setIgnoreFirstPoint(False)", "item = split_string[i].split('=') if len(item) == 2: if (item[0] ==", "2) self.__chkIgnoreFirstPoint.setVisible(False) self.reset(False) def reset(self, enable): self.__data = None self.__all_data", "self.setEnergyShift(0.0) self.__prevShift = 0.0 self.setEnabled(enable) def __chkShowErrorBars_changed(self, state): self.__chkShowErrorBars.setCheckState(state) self.showErrorBars_changed.emit(self.getShowErrorBars())", "if self.getData() is not None: return self.getData()[0][0] else: return None", "+ str(self.getIgnoreFirstPoint()) def saveFile(self, fileName, id_string, fit_strings, view_string, data_string, meta_string):", "None: return self.getData()[-1][0] else: return None def getMin_Energy(self): if self.getData()", "= (self.__all_data[:, 0:2]).copy() if len(self.__data) <= 1: raise Exception(\"Not enough", "1, 2) self.__mainLayout.addWidget(self.__chkIgnoreFirstPoint, 2, 0, 1, 2) self.__chkIgnoreFirstPoint.setVisible(False) self.reset(False) def", "error bars\" SHOW_ERROR_BARS_NOT_LOADED = \"Show error bars (could not be", "self.__all_data, self.__stdErrors, (fit_strings, view_string, data_string, meta_string), id_found =\\ hl.readFileForFitsDataAndStdErrorAndMetaData(fileName, id_string)", "getMin_Energy(self): if self.getData() is not None: return self.getData()[0][0] else: return", "+ '\\vseb=' + str(self.getShowErrorBars()) +\\ '\\vifd=' + str(self.getIgnoreFirstPoint()) def saveFile(self,", "'True': self.setIgnoreFirstPoint(True) elif item[1] == '0' or item[1] == 'False':", "def loadFile(self, fileName, id_string): self.__all_data, self.__stdErrors, (fit_strings, view_string, data_string, meta_string),", "item[1] == '0' or item[1] == 'False': self.setShowErrorBars(False) elif item[0]", "e: print(e) def getStdErrors(self): if self.__stdErrors is not None: first_point", "fileName, id_string, fit_strings, view_string, data_string, meta_string): hl.saveFilewithMetaData(id_string, fileName, self.__all_data, (fit_strings,", "Exception(\"Not enough data in file!\") if self.hasStdErrors(): self.__chkShowErrorBars.setText(self.SHOW_ERROR_BARS) else: self.__chkShowErrorBars.setText(self.SHOW_ERROR_BARS_NOT_LOADED)", "setEnergyShift(self, value): #increment = self.__dsbEnergyShift.value() - value increment = value", "self.__chkShowErrorBars.setText(self.SHOW_ERROR_BARS) else: self.__chkShowErrorBars.setText(self.SHOW_ERROR_BARS_NOT_LOADED) self.__chkShowErrorBars.setEnabled(self.hasStdErrors()) self.__chkShowErrorBars.setChecked(self.hasStdErrors()) self.__chkIgnoreFirstPoint.setEnabled(True) self.data_changed.emit(self.hasStdErrors(), self.getIgnoreFirstPoint()) self.load_fits.emit(fit_strings) self.load_view.emit(view_string)", "self.__mainLayout = QGridLayout() self.setLayout(self.__mainLayout) self.__mainLayout.setAlignment(Qt.AlignTop) self.__mainLayout.addWidget(self.__lblEnergyShift, 0, 0) self.__mainLayout.addWidget(self.__dsbEnergyShift, 0,", "return self.__chkShowErrorBars.isChecked() def setShowErrorBars(self, value): self.__chkShowErrorBars.setChecked(value) def getIgnoreFirstPoint(self): return self.__chkIgnoreFirstPoint.isChecked()", "pyqtSignal(bool) data_changed = pyqtSignal(bool, bool) data_shift = pyqtSignal(np.float64) load_fits =", "import numpy as np class dataControlWidget(QGroupBox): showErrorBars_changed = pyqtSignal(bool) ignoreFirstPoint_changed", "elif item[0] == 'ifd': if item[1] == '1' or item[1]", "dataControlWidget(QGroupBox): showErrorBars_changed = pyqtSignal(bool) ignoreFirstPoint_changed = pyqtSignal(bool) data_changed = pyqtSignal(bool,", "self.showErrorBars_changed.emit(self.getShowErrorBars()) def __chkIgnoreFirstPoint_changed(self, state): self.__chkIgnoreFirstPoint.setCheckState(state) self.ignoreFirstPoint_changed.emit(self.getIgnoreFirstPoint()) def __energyShiftChanged(self): self.cause_shift() def", "self.setShowErrorBars(True) elif item[1] == '0' or item[1] == 'False': self.setShowErrorBars(False)", "return None def getMin_Energy(self): if self.getData() is not None: return", "self.__dsbEnergyShift.setValue(value) #self.__shiftData(increment) #self.data_shift.emit(increment) def __shiftData(self, increment): try: if self.__data is", "self.__chkIgnoreFirstPoint = QCheckBox('Ignore first data point.') self.__chkIgnoreFirstPoint.stateChanged.connect(self.__chkIgnoreFirstPoint_changed) self.__mainLayout = QGridLayout()", "None self.__all_data = None self.__stdErrors = None self.__chkShowErrorBars.setCheckable(True) self.__chkShowErrorBars.setChecked(False) self.__chkShowErrorBars.setEnabled(False)", "'False': self.setIgnoreFirstPoint(False) def get_data_string(self): return 'egs=' + str(self.getEnergyShift()) + '\\vseb='", "for i in range(0, len(split_string)): item = split_string[i].split('=') if len(item)", "def getEnergyShift(self): return (self.__dsbEnergyShift.value()) def setEnergyShift(self, value): #increment = self.__dsbEnergyShift.value()", "return self.__chkIgnoreFirstPoint.isChecked() def setIgnoreFirstPoint(self, value): self.__chkIgnoreFirstPoint.setChecked(value) def hasStdErrors(self): return self.__stdErrors", "id_string): self.__all_data, self.__stdErrors, (fit_strings, view_string, data_string, meta_string), id_found =\\ hl.readFileForFitsDataAndStdErrorAndMetaData(fileName,", "__energyShiftChanged(self): self.cause_shift() def cause_shift(self): energyShift = self.__dsbEnergyShift.value() increment = energyShift", "data_string): if data_string is not None: split_string = data_string.split('\\v') for", "def reset(self, enable): self.__data = None self.__all_data = None self.__stdErrors", "self.__mainLayout.addWidget(self.__dsbEnergyShift, 0, 1) self.__mainLayout.addWidget(self.__chkShowErrorBars, 1, 0, 1, 2) self.__mainLayout.addWidget(self.__chkIgnoreFirstPoint, 2,", "if len(self.__data) <= 1: raise Exception(\"Not enough data in file!\")", "= \"Show error bars (could not be calculated)\" def __init__(self):", "def setEnergyShift(self, value): #increment = self.__dsbEnergyShift.value() - value increment =", "= None self.__stdErrors = None self.__chkShowErrorBars.setCheckable(True) self.__chkShowErrorBars.setChecked(False) self.__chkShowErrorBars.setEnabled(False) self.__chkIgnoreFirstPoint.setCheckable(True) self.__chkIgnoreFirstPoint.setChecked(False)", "None def getShowErrorBars(self): return self.__chkShowErrorBars.isChecked() def setShowErrorBars(self, value): self.__chkShowErrorBars.setChecked(value) def", "__chkShowErrorBars_changed(self, state): self.__chkShowErrorBars.setCheckState(state) self.showErrorBars_changed.emit(self.getShowErrorBars()) def __chkIgnoreFirstPoint_changed(self, state): self.__chkIgnoreFirstPoint.setCheckState(state) self.ignoreFirstPoint_changed.emit(self.getIgnoreFirstPoint()) def", "is not None: first_point = 0 if self.getIgnoreFirstPoint(): first_point =", "self.__chkIgnoreFirstPoint.setEnabled(False) self.setEnergyShift(0.0) self.__prevShift = 0.0 self.setEnabled(enable) def __chkShowErrorBars_changed(self, state): self.__chkShowErrorBars.setCheckState(state)", "QGridLayout, QCheckBox, QGroupBox from InftyDoubleSpinBox import InftyDoubleSpinBox from PyQt5.QtCore import", "pyqtSignal() SHOW_ERROR_BARS = \"Show error bars\" SHOW_ERROR_BARS_NOT_LOADED = \"Show error", "energyShift self.data_shift.emit(increment) self.data_changed.emit(self.getShowErrorBars(), self.getIgnoreFirstPoint()) # def setData(self, data): # self.__data", "(self.__all_data[:, 0:2]).copy() if len(self.__data) <= 1: raise Exception(\"Not enough data", "copy to not save any altered data! self.__data = (self.__all_data[:,", "(self.__dsbEnergyShift.value()) def setEnergyShift(self, value): #increment = self.__dsbEnergyShift.value() - value increment", "self.setEnergyShift(np.float64(item[1])) elif item[0] == 'seb': if item[1] == '1' or", "= QCheckBox('Ignore first data point.') self.__chkIgnoreFirstPoint.stateChanged.connect(self.__chkIgnoreFirstPoint_changed) self.__mainLayout = QGridLayout() self.setLayout(self.__mainLayout)", "data_string.split('\\v') for i in range(0, len(split_string)): item = split_string[i].split('=') if", "item[0] == 'seb': if item[1] == '1' or item[1] ==", "QGroupBox from InftyDoubleSpinBox import InftyDoubleSpinBox from PyQt5.QtCore import pyqtSignal, Qt", "== '0' or item[1] == 'False': self.setShowErrorBars(False) elif item[0] ==", "hl import numpy as np class dataControlWidget(QGroupBox): showErrorBars_changed = pyqtSignal(bool)", "first_point = 0 if self.getIgnoreFirstPoint(): first_point = 1 return self.__stdErrors[first_point:]", "elif item[0] == 'seb': if item[1] == '1' or item[1]", "self.__chkShowErrorBars.setEnabled(self.hasStdErrors()) self.__chkShowErrorBars.setChecked(self.hasStdErrors()) self.__chkIgnoreFirstPoint.setEnabled(True) self.data_changed.emit(self.hasStdErrors(), self.getIgnoreFirstPoint()) self.load_fits.emit(fit_strings) self.load_view.emit(view_string) self.load_meta.emit(meta_string) self.load_from_data_string(data_string) self.cause_shift()", "load_from_data_string(self, data_string): if data_string is not None: split_string = data_string.split('\\v')", "not None: for set in self.__data: set[0] += increment except", "id_found def load_from_data_string(self, data_string): if data_string is not None: split_string", "for set in self.__data: set[0] += increment except Exception as", "QCheckBox, QGroupBox from InftyDoubleSpinBox import InftyDoubleSpinBox from PyQt5.QtCore import pyqtSignal,", "self.__chkIgnoreFirstPoint.setChecked(False) self.__chkIgnoreFirstPoint.setEnabled(False) self.setEnergyShift(0.0) self.__prevShift = 0.0 self.setEnabled(enable) def __chkShowErrorBars_changed(self, state):", "return self.getData()[-1][0] else: return None def getMin_Energy(self): if self.getData() is", "is not None def loadFile(self, fileName, id_string): self.__all_data, self.__stdErrors, (fit_strings,", "1, 2) self.__chkIgnoreFirstPoint.setVisible(False) self.reset(False) def reset(self, enable): self.__data = None", "id_string) #we need a copy to not save any altered", "self.getIgnoreFirstPoint()) # def setData(self, data): # self.__data = data def", "'True': self.setShowErrorBars(True) elif item[1] == '0' or item[1] == 'False':", "self.data_changed.emit(self.getShowErrorBars(), self.getIgnoreFirstPoint()) # def setData(self, data): # self.__data = data", "def getMin_Energy(self): if self.getData() is not None: return self.getData()[0][0] else:", "be calculated)\" def __init__(self): QWidget.__init__(self) self.setTitle('Data Settings') self.__lblEnergyShift = QLabel(\"Energy", "- value increment = value - self.__dsbEnergyShift.value() self.__dsbEnergyShift.setValue(value) #self.__shiftData(increment) #self.data_shift.emit(increment)", "enough data in file!\") if self.hasStdErrors(): self.__chkShowErrorBars.setText(self.SHOW_ERROR_BARS) else: self.__chkShowErrorBars.setText(self.SHOW_ERROR_BARS_NOT_LOADED) self.__chkShowErrorBars.setEnabled(self.hasStdErrors())", "get_data_string(self): return 'egs=' + str(self.getEnergyShift()) + '\\vseb=' + str(self.getShowErrorBars()) +\\", "QLabel, QWidget, QGridLayout, QCheckBox, QGroupBox from InftyDoubleSpinBox import InftyDoubleSpinBox from", "'seb': if item[1] == '1' or item[1] == 'True': self.setShowErrorBars(True)", "self.__data is not None: for set in self.__data: set[0] +=", "pyqtSignal(str) fit_on_startup = pyqtSignal() SHOW_ERROR_BARS = \"Show error bars\" SHOW_ERROR_BARS_NOT_LOADED", "item[1] == '1' or item[1] == 'True': self.setShowErrorBars(True) elif item[1]", "is not None: return self.getData()[0][0] else: return None def getShowErrorBars(self):", "calculated)\" def __init__(self): QWidget.__init__(self) self.setTitle('Data Settings') self.__lblEnergyShift = QLabel(\"Energy Shift:\")", "self.__chkShowErrorBars.setCheckState(state) self.showErrorBars_changed.emit(self.getShowErrorBars()) def __chkIgnoreFirstPoint_changed(self, state): self.__chkIgnoreFirstPoint.setCheckState(state) self.ignoreFirstPoint_changed.emit(self.getIgnoreFirstPoint()) def __energyShiftChanged(self): self.cause_shift()", "getMax_Energy(self): if self.getData() is not None: return self.getData()[-1][0] else: return", "QWidget.__init__(self) self.setTitle('Data Settings') self.__lblEnergyShift = QLabel(\"Energy Shift:\") self.__dsbEnergyShift = InftyDoubleSpinBox()", "QGridLayout() self.setLayout(self.__mainLayout) self.__mainLayout.setAlignment(Qt.AlignTop) self.__mainLayout.addWidget(self.__lblEnergyShift, 0, 0) self.__mainLayout.addWidget(self.__dsbEnergyShift, 0, 1) self.__mainLayout.addWidget(self.__chkShowErrorBars,", "= energyShift - self.__prevShift self.__prevShift = energyShift self.data_shift.emit(increment) self.data_changed.emit(self.getShowErrorBars(), self.getIgnoreFirstPoint())", "if self.__stdErrors is not None: first_point = 0 if self.getIgnoreFirstPoint():", "energyShift - self.__prevShift self.__prevShift = energyShift self.data_shift.emit(increment) self.data_changed.emit(self.getShowErrorBars(), self.getIgnoreFirstPoint()) #", "self.__chkIgnoreFirstPoint.setEnabled(True) self.data_changed.emit(self.hasStdErrors(), self.getIgnoreFirstPoint()) self.load_fits.emit(fit_strings) self.load_view.emit(view_string) self.load_meta.emit(meta_string) self.load_from_data_string(data_string) self.cause_shift() self.fit_on_startup.emit() return", "data in file!\") if self.hasStdErrors(): self.__chkShowErrorBars.setText(self.SHOW_ERROR_BARS) else: self.__chkShowErrorBars.setText(self.SHOW_ERROR_BARS_NOT_LOADED) self.__chkShowErrorBars.setEnabled(self.hasStdErrors()) self.__chkShowErrorBars.setChecked(self.hasStdErrors())", "self.load_view.emit(view_string) self.load_meta.emit(meta_string) self.load_from_data_string(data_string) self.cause_shift() self.fit_on_startup.emit() return id_found def load_from_data_string(self, data_string):", "self.hasStdErrors(): self.__chkShowErrorBars.setText(self.SHOW_ERROR_BARS) else: self.__chkShowErrorBars.setText(self.SHOW_ERROR_BARS_NOT_LOADED) self.__chkShowErrorBars.setEnabled(self.hasStdErrors()) self.__chkShowErrorBars.setChecked(self.hasStdErrors()) self.__chkIgnoreFirstPoint.setEnabled(True) self.data_changed.emit(self.hasStdErrors(), self.getIgnoreFirstPoint()) self.load_fits.emit(fit_strings)", "pyqtSignal(list) load_view = pyqtSignal(str) load_meta = pyqtSignal(str) fit_on_startup = pyqtSignal()", "as e: print(e) def getStdErrors(self): if self.__stdErrors is not None:", "1 return self.__stdErrors[first_point:] else: return None def getMax_Energy(self): if self.getData()", "self.__mainLayout.addWidget(self.__chkShowErrorBars, 1, 0, 1, 2) self.__mainLayout.addWidget(self.__chkIgnoreFirstPoint, 2, 0, 1, 2)", "1 return self.__data[first_point:,] def getEnergyShift(self): return (self.__dsbEnergyShift.value()) def setEnergyShift(self, value):", "== '1' or item[1] == 'True': self.setIgnoreFirstPoint(True) elif item[1] ==", "self.__chkShowErrorBars.stateChanged.connect(self.__chkShowErrorBars_changed) self.__chkIgnoreFirstPoint = QCheckBox('Ignore first data point.') self.__chkIgnoreFirstPoint.stateChanged.connect(self.__chkIgnoreFirstPoint_changed) self.__mainLayout =", "self.cause_shift() self.fit_on_startup.emit() return id_found def load_from_data_string(self, data_string): if data_string is", "= 1 return self.__stdErrors[first_point:] else: return None def getMax_Energy(self): if", "first_point = 1 return self.__data[first_point:,] def getEnergyShift(self): return (self.__dsbEnergyShift.value()) def", "0.0 self.setEnabled(enable) def __chkShowErrorBars_changed(self, state): self.__chkShowErrorBars.setCheckState(state) self.showErrorBars_changed.emit(self.getShowErrorBars()) def __chkIgnoreFirstPoint_changed(self, state):", "QCheckBox(self.SHOW_ERROR_BARS_NOT_LOADED) self.__chkShowErrorBars.stateChanged.connect(self.__chkShowErrorBars_changed) self.__chkIgnoreFirstPoint = QCheckBox('Ignore first data point.') self.__chkIgnoreFirstPoint.stateChanged.connect(self.__chkIgnoreFirstPoint_changed) self.__mainLayout", "self.__data[first_point:,] def getEnergyShift(self): return (self.__dsbEnergyShift.value()) def setEnergyShift(self, value): #increment =", "elif item[1] == '0' or item[1] == 'False': self.setShowErrorBars(False) elif", "def getIgnoreFirstPoint(self): return self.__chkIgnoreFirstPoint.isChecked() def setIgnoreFirstPoint(self, value): self.__chkIgnoreFirstPoint.setChecked(value) def hasStdErrors(self):", "'\\vifd=' + str(self.getIgnoreFirstPoint()) def saveFile(self, fileName, id_string, fit_strings, view_string, data_string,", "view_string, data_string, meta_string), id_found =\\ hl.readFileForFitsDataAndStdErrorAndMetaData(fileName, id_string) #we need a", "loadFile(self, fileName, id_string): self.__all_data, self.__stdErrors, (fit_strings, view_string, data_string, meta_string), id_found", "2, 0, 1, 2) self.__chkIgnoreFirstPoint.setVisible(False) self.reset(False) def reset(self, enable): self.__data", "or item[1] == 'True': self.setShowErrorBars(True) elif item[1] == '0' or", "= 1 return self.__data[first_point:,] def getEnergyShift(self): return (self.__dsbEnergyShift.value()) def setEnergyShift(self,", "not None: split_string = data_string.split('\\v') for i in range(0, len(split_string)):", "2: if (item[0] == 'egs'): self.setEnergyShift(np.float64(item[1])) elif item[0] == 'seb':", "= 0 if self.getIgnoreFirstPoint(): first_point = 1 return self.__stdErrors[first_point:] else:", "from InftyDoubleSpinBox import InftyDoubleSpinBox from PyQt5.QtCore import pyqtSignal, Qt import", "QWidget, QGridLayout, QCheckBox, QGroupBox from InftyDoubleSpinBox import InftyDoubleSpinBox from PyQt5.QtCore", "self.__stdErrors is not None: first_point = 0 if self.getIgnoreFirstPoint(): first_point", "=\\ hl.readFileForFitsDataAndStdErrorAndMetaData(fileName, id_string) #we need a copy to not save", "'False': self.setShowErrorBars(False) elif item[0] == 'ifd': if item[1] == '1'", "def cause_shift(self): energyShift = self.__dsbEnergyShift.value() increment = energyShift - self.__prevShift", "item[1] == 'False': self.setIgnoreFirstPoint(False) def get_data_string(self): return 'egs=' + str(self.getEnergyShift())", "self.__lblEnergyShift = QLabel(\"Energy Shift:\") self.__dsbEnergyShift = InftyDoubleSpinBox() self.__dsbEnergyShift.editingFinished.connect(self.__energyShiftChanged) self.__dsbEnergyShift.setSingleStep(0.01) self.__chkShowErrorBars", "item[1] == '0' or item[1] == 'False': self.setIgnoreFirstPoint(False) def get_data_string(self):", "self.cause_shift() def cause_shift(self): energyShift = self.__dsbEnergyShift.value() increment = energyShift -", "return self.__data[first_point:,] def getEnergyShift(self): return (self.__dsbEnergyShift.value()) def setEnergyShift(self, value): #increment", "(fit_strings, view_string, data_string, meta_string), id_found =\\ hl.readFileForFitsDataAndStdErrorAndMetaData(fileName, id_string) #we need", "or item[1] == 'False': self.setIgnoreFirstPoint(False) def get_data_string(self): return 'egs=' +", "1: raise Exception(\"Not enough data in file!\") if self.hasStdErrors(): self.__chkShowErrorBars.setText(self.SHOW_ERROR_BARS)", "data def getData(self): first_point = 0 if self.getIgnoreFirstPoint(): first_point =", "= 0 if self.getIgnoreFirstPoint(): first_point = 1 return self.__data[first_point:,] def", "+ str(self.getShowErrorBars()) +\\ '\\vifd=' + str(self.getIgnoreFirstPoint()) def saveFile(self, fileName, id_string,", "= pyqtSignal(list) load_view = pyqtSignal(str) load_meta = pyqtSignal(str) fit_on_startup =", "else: return None def getMin_Energy(self): if self.getData() is not None:", "bars (could not be calculated)\" def __init__(self): QWidget.__init__(self) self.setTitle('Data Settings')", "increment = value - self.__dsbEnergyShift.value() self.__dsbEnergyShift.setValue(value) #self.__shiftData(increment) #self.data_shift.emit(increment) def __shiftData(self,", "return self.getData()[0][0] else: return None def getShowErrorBars(self): return self.__chkShowErrorBars.isChecked() def", "#increment = self.__dsbEnergyShift.value() - value increment = value - self.__dsbEnergyShift.value()", "'egs=' + str(self.getEnergyShift()) + '\\vseb=' + str(self.getShowErrorBars()) +\\ '\\vifd=' +", "load_view = pyqtSignal(str) load_meta = pyqtSignal(str) fit_on_startup = pyqtSignal() SHOW_ERROR_BARS", "self.getIgnoreFirstPoint(): first_point = 1 return self.__data[first_point:,] def getEnergyShift(self): return (self.__dsbEnergyShift.value())", "Settings') self.__lblEnergyShift = QLabel(\"Energy Shift:\") self.__dsbEnergyShift = InftyDoubleSpinBox() self.__dsbEnergyShift.editingFinished.connect(self.__energyShiftChanged) self.__dsbEnergyShift.setSingleStep(0.01)", "self.__stdErrors is not None def loadFile(self, fileName, id_string): self.__all_data, self.__stdErrors,", "1, 0, 1, 2) self.__mainLayout.addWidget(self.__chkIgnoreFirstPoint, 2, 0, 1, 2) self.__chkIgnoreFirstPoint.setVisible(False)", "def __init__(self): QWidget.__init__(self) self.setTitle('Data Settings') self.__lblEnergyShift = QLabel(\"Energy Shift:\") self.__dsbEnergyShift", "self.__data = data def getData(self): first_point = 0 if self.getIgnoreFirstPoint():", "Shift:\") self.__dsbEnergyShift = InftyDoubleSpinBox() self.__dsbEnergyShift.editingFinished.connect(self.__energyShiftChanged) self.__dsbEnergyShift.setSingleStep(0.01) self.__chkShowErrorBars = QCheckBox(self.SHOW_ERROR_BARS_NOT_LOADED) self.__chkShowErrorBars.stateChanged.connect(self.__chkShowErrorBars_changed)", "data): # self.__data = data def getData(self): first_point = 0", "state): self.__chkIgnoreFirstPoint.setCheckState(state) self.ignoreFirstPoint_changed.emit(self.getIgnoreFirstPoint()) def __energyShiftChanged(self): self.cause_shift() def cause_shift(self): energyShift =", "None: return self.getData()[0][0] else: return None def getShowErrorBars(self): return self.__chkShowErrorBars.isChecked()", "fit_strings, view_string, data_string, meta_string): hl.saveFilewithMetaData(id_string, fileName, self.__all_data, (fit_strings, view_string, data_string,", "def __chkIgnoreFirstPoint_changed(self, state): self.__chkIgnoreFirstPoint.setCheckState(state) self.ignoreFirstPoint_changed.emit(self.getIgnoreFirstPoint()) def __energyShiftChanged(self): self.cause_shift() def cause_shift(self):", "0 if self.getIgnoreFirstPoint(): first_point = 1 return self.__data[first_point:,] def getEnergyShift(self):", "self.__all_data = None self.__stdErrors = None self.__chkShowErrorBars.setCheckable(True) self.__chkShowErrorBars.setChecked(False) self.__chkShowErrorBars.setEnabled(False) self.__chkIgnoreFirstPoint.setCheckable(True)", "increment): try: if self.__data is not None: for set in", "self.__chkShowErrorBars.setCheckable(True) self.__chkShowErrorBars.setChecked(False) self.__chkShowErrorBars.setEnabled(False) self.__chkIgnoreFirstPoint.setCheckable(True) self.__chkIgnoreFirstPoint.setChecked(False) self.__chkIgnoreFirstPoint.setEnabled(False) self.setEnergyShift(0.0) self.__prevShift = 0.0", "== 'egs'): self.setEnergyShift(np.float64(item[1])) elif item[0] == 'seb': if item[1] ==", "import QLabel, QWidget, QGridLayout, QCheckBox, QGroupBox from InftyDoubleSpinBox import InftyDoubleSpinBox", "(item[0] == 'egs'): self.setEnergyShift(np.float64(item[1])) elif item[0] == 'seb': if item[1]", "+= increment except Exception as e: print(e) def getStdErrors(self): if", "self.__dsbEnergyShift.value() self.__dsbEnergyShift.setValue(value) #self.__shiftData(increment) #self.data_shift.emit(increment) def __shiftData(self, increment): try: if self.__data", "0, 1) self.__mainLayout.addWidget(self.__chkShowErrorBars, 1, 0, 1, 2) self.__mainLayout.addWidget(self.__chkIgnoreFirstPoint, 2, 0,", "data_string is not None: split_string = data_string.split('\\v') for i in", "as hl import numpy as np class dataControlWidget(QGroupBox): showErrorBars_changed =", "= data def getData(self): first_point = 0 if self.getIgnoreFirstPoint(): first_point", "file!\") if self.hasStdErrors(): self.__chkShowErrorBars.setText(self.SHOW_ERROR_BARS) else: self.__chkShowErrorBars.setText(self.SHOW_ERROR_BARS_NOT_LOADED) self.__chkShowErrorBars.setEnabled(self.hasStdErrors()) self.__chkShowErrorBars.setChecked(self.hasStdErrors()) self.__chkIgnoreFirstPoint.setEnabled(True) self.data_changed.emit(self.hasStdErrors(),", "pyqtSignal(str) load_meta = pyqtSignal(str) fit_on_startup = pyqtSignal() SHOW_ERROR_BARS = \"Show", "'\\vseb=' + str(self.getShowErrorBars()) +\\ '\\vifd=' + str(self.getIgnoreFirstPoint()) def saveFile(self, fileName,", "if data_string is not None: split_string = data_string.split('\\v') for i", "(could not be calculated)\" def __init__(self): QWidget.__init__(self) self.setTitle('Data Settings') self.__lblEnergyShift", "self.getData()[-1][0] else: return None def getMin_Energy(self): if self.getData() is not", "self.__chkShowErrorBars.setEnabled(False) self.__chkIgnoreFirstPoint.setCheckable(True) self.__chkIgnoreFirstPoint.setChecked(False) self.__chkIgnoreFirstPoint.setEnabled(False) self.setEnergyShift(0.0) self.__prevShift = 0.0 self.setEnabled(enable) def", "+\\ '\\vifd=' + str(self.getIgnoreFirstPoint()) def saveFile(self, fileName, id_string, fit_strings, view_string,", "= 0.0 self.setEnabled(enable) def __chkShowErrorBars_changed(self, state): self.__chkShowErrorBars.setCheckState(state) self.showErrorBars_changed.emit(self.getShowErrorBars()) def __chkIgnoreFirstPoint_changed(self,", "str(self.getEnergyShift()) + '\\vseb=' + str(self.getShowErrorBars()) +\\ '\\vifd=' + str(self.getIgnoreFirstPoint()) def", "getData(self): first_point = 0 if self.getIgnoreFirstPoint(): first_point = 1 return", "in range(0, len(split_string)): item = split_string[i].split('=') if len(item) == 2:", "\"Show error bars (could not be calculated)\" def __init__(self): QWidget.__init__(self)", "increment = energyShift - self.__prevShift self.__prevShift = energyShift self.data_shift.emit(increment) self.data_changed.emit(self.getShowErrorBars(),", "str(self.getShowErrorBars()) +\\ '\\vifd=' + str(self.getIgnoreFirstPoint()) def saveFile(self, fileName, id_string, fit_strings,", "__init__(self): QWidget.__init__(self) self.setTitle('Data Settings') self.__lblEnergyShift = QLabel(\"Energy Shift:\") self.__dsbEnergyShift =", "#self.__shiftData(increment) #self.data_shift.emit(increment) def __shiftData(self, increment): try: if self.__data is not", "if self.getIgnoreFirstPoint(): first_point = 1 return self.__stdErrors[first_point:] else: return None", "split_string = data_string.split('\\v') for i in range(0, len(split_string)): item =", "else: return None def getShowErrorBars(self): return self.__chkShowErrorBars.isChecked() def setShowErrorBars(self, value):", "SHOW_ERROR_BARS = \"Show error bars\" SHOW_ERROR_BARS_NOT_LOADED = \"Show error bars", "set[0] += increment except Exception as e: print(e) def getStdErrors(self):", "= pyqtSignal(bool) data_changed = pyqtSignal(bool, bool) data_shift = pyqtSignal(np.float64) load_fits", "reset(self, enable): self.__data = None self.__all_data = None self.__stdErrors =", "self.setLayout(self.__mainLayout) self.__mainLayout.setAlignment(Qt.AlignTop) self.__mainLayout.addWidget(self.__lblEnergyShift, 0, 0) self.__mainLayout.addWidget(self.__dsbEnergyShift, 0, 1) self.__mainLayout.addWidget(self.__chkShowErrorBars, 1,", "None self.__stdErrors = None self.__chkShowErrorBars.setCheckable(True) self.__chkShowErrorBars.setChecked(False) self.__chkShowErrorBars.setEnabled(False) self.__chkIgnoreFirstPoint.setCheckable(True) self.__chkIgnoreFirstPoint.setChecked(False) self.__chkIgnoreFirstPoint.setEnabled(False)", "= data_string.split('\\v') for i in range(0, len(split_string)): item = split_string[i].split('=')", "self.__prevShift = 0.0 self.setEnabled(enable) def __chkShowErrorBars_changed(self, state): self.__chkShowErrorBars.setCheckState(state) self.showErrorBars_changed.emit(self.getShowErrorBars()) def", "self.__chkShowErrorBars = QCheckBox(self.SHOW_ERROR_BARS_NOT_LOADED) self.__chkShowErrorBars.stateChanged.connect(self.__chkShowErrorBars_changed) self.__chkIgnoreFirstPoint = QCheckBox('Ignore first data point.')", "'0' or item[1] == 'False': self.setIgnoreFirstPoint(False) def get_data_string(self): return 'egs='", "None: first_point = 0 if self.getIgnoreFirstPoint(): first_point = 1 return", "import InftyDoubleSpinBox from PyQt5.QtCore import pyqtSignal, Qt import helplib as", "helplib as hl import numpy as np class dataControlWidget(QGroupBox): showErrorBars_changed", "i in range(0, len(split_string)): item = split_string[i].split('=') if len(item) ==", "= value - self.__dsbEnergyShift.value() self.__dsbEnergyShift.setValue(value) #self.__shiftData(increment) #self.data_shift.emit(increment) def __shiftData(self, increment):", "try: if self.__data is not None: for set in self.__data:", "self.__chkShowErrorBars.setChecked(False) self.__chkShowErrorBars.setEnabled(False) self.__chkIgnoreFirstPoint.setCheckable(True) self.__chkIgnoreFirstPoint.setChecked(False) self.__chkIgnoreFirstPoint.setEnabled(False) self.setEnergyShift(0.0) self.__prevShift = 0.0 self.setEnabled(enable)", "def load_from_data_string(self, data_string): if data_string is not None: split_string =", "if item[1] == '1' or item[1] == 'True': self.setIgnoreFirstPoint(True) elif", "data point.') self.__chkIgnoreFirstPoint.stateChanged.connect(self.__chkIgnoreFirstPoint_changed) self.__mainLayout = QGridLayout() self.setLayout(self.__mainLayout) self.__mainLayout.setAlignment(Qt.AlignTop) self.__mainLayout.addWidget(self.__lblEnergyShift, 0,", "item[0] == 'ifd': if item[1] == '1' or item[1] ==", "pyqtSignal, Qt import helplib as hl import numpy as np", "+ str(self.getEnergyShift()) + '\\vseb=' + str(self.getShowErrorBars()) +\\ '\\vifd=' + str(self.getIgnoreFirstPoint())", "elif item[1] == '0' or item[1] == 'False': self.setIgnoreFirstPoint(False) def", "hl.readFileForFitsDataAndStdErrorAndMetaData(fileName, id_string) #we need a copy to not save any", "if self.hasStdErrors(): self.__chkShowErrorBars.setText(self.SHOW_ERROR_BARS) else: self.__chkShowErrorBars.setText(self.SHOW_ERROR_BARS_NOT_LOADED) self.__chkShowErrorBars.setEnabled(self.hasStdErrors()) self.__chkShowErrorBars.setChecked(self.hasStdErrors()) self.__chkIgnoreFirstPoint.setEnabled(True) self.data_changed.emit(self.hasStdErrors(), self.getIgnoreFirstPoint())", "def saveFile(self, fileName, id_string, fit_strings, view_string, data_string, meta_string): hl.saveFilewithMetaData(id_string, fileName,", "= energyShift self.data_shift.emit(increment) self.data_changed.emit(self.getShowErrorBars(), self.getIgnoreFirstPoint()) # def setData(self, data): #", "return None def getMax_Energy(self): if self.getData() is not None: return", "import pyqtSignal, Qt import helplib as hl import numpy as", "not be calculated)\" def __init__(self): QWidget.__init__(self) self.setTitle('Data Settings') self.__lblEnergyShift =", "self.load_meta.emit(meta_string) self.load_from_data_string(data_string) self.cause_shift() self.fit_on_startup.emit() return id_found def load_from_data_string(self, data_string): if", "= pyqtSignal(bool, bool) data_shift = pyqtSignal(np.float64) load_fits = pyqtSignal(list) load_view", "None def getMax_Energy(self): if self.getData() is not None: return self.getData()[-1][0]", "self.__dsbEnergyShift.editingFinished.connect(self.__energyShiftChanged) self.__dsbEnergyShift.setSingleStep(0.01) self.__chkShowErrorBars = QCheckBox(self.SHOW_ERROR_BARS_NOT_LOADED) self.__chkShowErrorBars.stateChanged.connect(self.__chkShowErrorBars_changed) self.__chkIgnoreFirstPoint = QCheckBox('Ignore first", "Exception as e: print(e) def getStdErrors(self): if self.__stdErrors is not", "import helplib as hl import numpy as np class dataControlWidget(QGroupBox):", "self.setEnabled(enable) def __chkShowErrorBars_changed(self, state): self.__chkShowErrorBars.setCheckState(state) self.showErrorBars_changed.emit(self.getShowErrorBars()) def __chkIgnoreFirstPoint_changed(self, state): self.__chkIgnoreFirstPoint.setCheckState(state)", "enable): self.__data = None self.__all_data = None self.__stdErrors = None", "PyQt5.QtCore import pyqtSignal, Qt import helplib as hl import numpy", "item[1] == 'True': self.setIgnoreFirstPoint(True) elif item[1] == '0' or item[1]", "= None self.__all_data = None self.__stdErrors = None self.__chkShowErrorBars.setCheckable(True) self.__chkShowErrorBars.setChecked(False)", "str(self.getIgnoreFirstPoint()) def saveFile(self, fileName, id_string, fit_strings, view_string, data_string, meta_string): hl.saveFilewithMetaData(id_string,", "bars\" SHOW_ERROR_BARS_NOT_LOADED = \"Show error bars (could not be calculated)\"", "0) self.__mainLayout.addWidget(self.__dsbEnergyShift, 0, 1) self.__mainLayout.addWidget(self.__chkShowErrorBars, 1, 0, 1, 2) self.__mainLayout.addWidget(self.__chkIgnoreFirstPoint,", "\"Show error bars\" SHOW_ERROR_BARS_NOT_LOADED = \"Show error bars (could not", "setData(self, data): # self.__data = data def getData(self): first_point =", "return id_found def load_from_data_string(self, data_string): if data_string is not None:", "self.__stdErrors = None self.__chkShowErrorBars.setCheckable(True) self.__chkShowErrorBars.setChecked(False) self.__chkShowErrorBars.setEnabled(False) self.__chkIgnoreFirstPoint.setCheckable(True) self.__chkIgnoreFirstPoint.setChecked(False) self.__chkIgnoreFirstPoint.setEnabled(False) self.setEnergyShift(0.0)", "not None: return self.getData()[-1][0] else: return None def getMin_Energy(self): if", "energyShift = self.__dsbEnergyShift.value() increment = energyShift - self.__prevShift self.__prevShift =", "# def setData(self, data): # self.__data = data def getData(self):", "== 'True': self.setShowErrorBars(True) elif item[1] == '0' or item[1] ==", "len(self.__data) <= 1: raise Exception(\"Not enough data in file!\") if", "ignoreFirstPoint_changed = pyqtSignal(bool) data_changed = pyqtSignal(bool, bool) data_shift = pyqtSignal(np.float64)", "data! self.__data = (self.__all_data[:, 0:2]).copy() if len(self.__data) <= 1: raise", "pyqtSignal(bool) ignoreFirstPoint_changed = pyqtSignal(bool) data_changed = pyqtSignal(bool, bool) data_shift =", "point.') self.__chkIgnoreFirstPoint.stateChanged.connect(self.__chkIgnoreFirstPoint_changed) self.__mainLayout = QGridLayout() self.setLayout(self.__mainLayout) self.__mainLayout.setAlignment(Qt.AlignTop) self.__mainLayout.addWidget(self.__lblEnergyShift, 0, 0)", "or item[1] == 'True': self.setIgnoreFirstPoint(True) elif item[1] == '0' or", "value): #increment = self.__dsbEnergyShift.value() - value increment = value -", "state): self.__chkShowErrorBars.setCheckState(state) self.showErrorBars_changed.emit(self.getShowErrorBars()) def __chkIgnoreFirstPoint_changed(self, state): self.__chkIgnoreFirstPoint.setCheckState(state) self.ignoreFirstPoint_changed.emit(self.getIgnoreFirstPoint()) def __energyShiftChanged(self):", "self.load_from_data_string(data_string) self.cause_shift() self.fit_on_startup.emit() return id_found def load_from_data_string(self, data_string): if data_string", "def __energyShiftChanged(self): self.cause_shift() def cause_shift(self): energyShift = self.__dsbEnergyShift.value() increment =", "load_meta = pyqtSignal(str) fit_on_startup = pyqtSignal() SHOW_ERROR_BARS = \"Show error", "id_string, fit_strings, view_string, data_string, meta_string): hl.saveFilewithMetaData(id_string, fileName, self.__all_data, (fit_strings, view_string,", "def getStdErrors(self): if self.__stdErrors is not None: first_point = 0", "getIgnoreFirstPoint(self): return self.__chkIgnoreFirstPoint.isChecked() def setIgnoreFirstPoint(self, value): self.__chkIgnoreFirstPoint.setChecked(value) def hasStdErrors(self): return", "not save any altered data! self.__data = (self.__all_data[:, 0:2]).copy() if", "self.getIgnoreFirstPoint()) self.load_fits.emit(fit_strings) self.load_view.emit(view_string) self.load_meta.emit(meta_string) self.load_from_data_string(data_string) self.cause_shift() self.fit_on_startup.emit() return id_found def", "self.__data: set[0] += increment except Exception as e: print(e) def", "== 'seb': if item[1] == '1' or item[1] == 'True':", "if len(item) == 2: if (item[0] == 'egs'): self.setEnergyShift(np.float64(item[1])) elif", "meta_string), id_found =\\ hl.readFileForFitsDataAndStdErrorAndMetaData(fileName, id_string) #we need a copy to", "def __shiftData(self, increment): try: if self.__data is not None: for", "increment except Exception as e: print(e) def getStdErrors(self): if self.__stdErrors", "not None: first_point = 0 if self.getIgnoreFirstPoint(): first_point = 1", "value): self.__chkShowErrorBars.setChecked(value) def getIgnoreFirstPoint(self): return self.__chkIgnoreFirstPoint.isChecked() def setIgnoreFirstPoint(self, value): self.__chkIgnoreFirstPoint.setChecked(value)", "need a copy to not save any altered data! self.__data", "data_changed = pyqtSignal(bool, bool) data_shift = pyqtSignal(np.float64) load_fits = pyqtSignal(list)", "self.getIgnoreFirstPoint(): first_point = 1 return self.__stdErrors[first_point:] else: return None def", "self.__prevShift = energyShift self.data_shift.emit(increment) self.data_changed.emit(self.getShowErrorBars(), self.getIgnoreFirstPoint()) # def setData(self, data):", "self.getData() is not None: return self.getData()[0][0] else: return None def", "None: split_string = data_string.split('\\v') for i in range(0, len(split_string)): item", "0, 1, 2) self.__chkIgnoreFirstPoint.setVisible(False) self.reset(False) def reset(self, enable): self.__data =", "load_fits = pyqtSignal(list) load_view = pyqtSignal(str) load_meta = pyqtSignal(str) fit_on_startup", "0, 0) self.__mainLayout.addWidget(self.__dsbEnergyShift, 0, 1) self.__mainLayout.addWidget(self.__chkShowErrorBars, 1, 0, 1, 2)", "if (item[0] == 'egs'): self.setEnergyShift(np.float64(item[1])) elif item[0] == 'seb': if", "as np class dataControlWidget(QGroupBox): showErrorBars_changed = pyqtSignal(bool) ignoreFirstPoint_changed = pyqtSignal(bool)", "self.__stdErrors[first_point:] else: return None def getMax_Energy(self): if self.getData() is not", "self.__chkIgnoreFirstPoint.setCheckable(True) self.__chkIgnoreFirstPoint.setChecked(False) self.__chkIgnoreFirstPoint.setEnabled(False) self.setEnergyShift(0.0) self.__prevShift = 0.0 self.setEnabled(enable) def __chkShowErrorBars_changed(self,", "print(e) def getStdErrors(self): if self.__stdErrors is not None: first_point =", "item[1] == 'True': self.setShowErrorBars(True) elif item[1] == '0' or item[1]", "PyQt5.QtWidgets import QLabel, QWidget, QGridLayout, QCheckBox, QGroupBox from InftyDoubleSpinBox import", "len(split_string)): item = split_string[i].split('=') if len(item) == 2: if (item[0]", "return (self.__dsbEnergyShift.value()) def setEnergyShift(self, value): #increment = self.__dsbEnergyShift.value() - value", "def get_data_string(self): return 'egs=' + str(self.getEnergyShift()) + '\\vseb=' + str(self.getShowErrorBars())", "= None self.__chkShowErrorBars.setCheckable(True) self.__chkShowErrorBars.setChecked(False) self.__chkShowErrorBars.setEnabled(False) self.__chkIgnoreFirstPoint.setCheckable(True) self.__chkIgnoreFirstPoint.setChecked(False) self.__chkIgnoreFirstPoint.setEnabled(False) self.setEnergyShift(0.0) self.__prevShift", "= self.__dsbEnergyShift.value() - value increment = value - self.__dsbEnergyShift.value() self.__dsbEnergyShift.setValue(value)", "== 'ifd': if item[1] == '1' or item[1] == 'True':", "Qt import helplib as hl import numpy as np class" ]
[ "arrive while not self._is_done(self._result,n_per_camera,verbose=verbose): try: topic_prefix, msg = self.im_queue.get(1,10.0) #", "for ch in self.cam_handlers: self._result[ch.topic_prefix] = [] #clear the queue", "= imarr #sad to use dstack here, IMO res[cam][:,:,i] =", "k,v in list(params.items()): if k in self.recon_cache: if self.recon_cache[k] !=", "if post_func: post_func(*post_func_args) class SequentialCameraRunner(_Runner): def __init__(self,cam_handlers,**kwargs): _Runner.__init__(self, cam_handlers,**kwargs) self.wait_duration", "reconfigure(self, **params): if self.recon is not None: changed = {}", "queue.Empty: continue t_image = msg.header.stamp.to_sec() if self.check_latest and t_image >", "time.time() while (time.time() - tstart) < dur: time.sleep(0.05) # wait", "try: topic_prefix, msg = self.im_queue.get(1,10.0) # block, 10 second timeout", "to arrive while not self._is_done(self._result,n_per_camera,verbose=verbose): try: topic_prefix, msg = self.im_queue.get(1,10.0)", "< n_per_camera: done=False return done class SimultaneousCameraRunner(_Runner): def __init__(self,cam_handlers,**kwargs): _Runner.__init__(self,", "> t_latest: rospy.logwarn(\"image from %s at t=%f was too slow", "class SimultaneousCameraRunner(_Runner): def __init__(self,cam_handlers,**kwargs): _Runner.__init__(self, cam_handlers,**kwargs) def get_images(self,n_per_camera, pre_func=None, pre_func_args=[],", "post_func: post_func(*post_func_args) class SequentialCameraRunner(_Runner): def __init__(self,cam_handlers,**kwargs): _Runner.__init__(self, cam_handlers,**kwargs) self.wait_duration =", "def _is_done(self,rdict,n_per_camera,verbose=False): done=True for topic_prefix in list(rdict.keys()): if verbose: rospy.loginfo('", "self.debug: print(\"%s got image: %f\" % (self.topic_prefix, msg.header.stamp.to_sec())) self.im_queue.put_nowait((self.topic_prefix,msg)) except", "% (self.topic_prefix, msg.header.stamp.to_sec())) self.im_queue.put_nowait((self.topic_prefix,msg)) except queue.Full: if self.debug: print(self.topic_prefix,\"full\") class", "get_images(self,n_per_camera, pre_func=None, pre_func_args=[], post_func=None, post_func_args=[], verbose=False): self._result.clear() for ch in", "(self.ros_latency + self.max_cam_latency) while not self._is_done(self._result,n_per_camera,verbose=verbose): try: topic_prefix, msg =", "cam_handlers self.im_queue = queue.Queue(len(cam_handlers)*queue_depth) for ch in self.cam_handlers: ch.set_im_queue(self.im_queue) self.ros_latency", "q = self.im_queue while 1: try: q.get_nowait() except queue.Empty: break", "% (topic_prefix, t_image, t_image - t_latest)) self._result[topic_prefix].append( msg ) if", "was too early (by %f)\" % (topic_prefix, t_image, t_earliest -", "None: return try: if self.debug: print(\"%s got image: %f\" %", "self._result = {} @property def result(self): return self._result @property def", "rospy.ServiceProxy('%s/set_parameters'%self.topic_prefix, dynamic_reconfigure.srv.Reconfigure) self.recon_cache = {} def reconfigure(self, **params): if self.recon", "use dstack here, IMO res[cam][:,:,i] = imarr #should have worked.", "to use dstack here, IMO res[cam][:,:,i] = imarr #should have", "self.recon = None if enable_dynamic_reconfigure: self.recon = rospy.ServiceProxy('%s/set_parameters'%self.topic_prefix, dynamic_reconfigure.srv.Reconfigure) self.recon_cache", "__init__(self,cam_handlers,**kwargs): _Runner.__init__(self, cam_handlers,**kwargs) def get_images(self,n_per_camera, pre_func=None, pre_func_args=[], post_func=None, post_func_args=[], verbose=False):", "t_image - t_latest)) self._result[topic_prefix].append( msg ) if post_func: post_func(*post_func_args) class", "if changed: msg = dynamic_reconfigure.encoding.encode_config(params) self.recon_cache.update(changed) self.recon(msg) if self.im_queue is", "self.im_queue = None self.recon = None if enable_dynamic_reconfigure: self.recon =", "import os.path import queue class CameraHandler(object): def __init__(self,topic_prefix='',debug=False,enable_dynamic_reconfigure=False): self.topic_prefix=topic_prefix self.debug", "for topic_prefix in list(rdict.keys()): if verbose: rospy.loginfo(' _is_done() has %d", "queue.Full: if self.debug: print(self.topic_prefix,\"full\") class _Runner(object): def __init__(self,cam_handlers,ros_latency=0.2,queue_depth=20): self.cam_handlers =", "ch in self.cam_handlers: ch.set_im_queue(self.im_queue) self.ros_latency = ros_latency self.max_cam_latency = max(", "sensor_msgs.msg.Image, self.get_image_callback) self.pipeline_max_latency = 0.2 self.last_image = None self.im_queue =", "changed[k] = v if changed: msg = dynamic_reconfigure.encoding.encode_config(params) self.recon_cache.update(changed) self.recon(msg)", "{} @property def result(self): return self._result @property def result_as_nparray(self): res", "self.im_queue is None: return try: if self.debug: print(\"%s got image:", "enable_dynamic_reconfigure: self.recon = rospy.ServiceProxy('%s/set_parameters'%self.topic_prefix, dynamic_reconfigure.srv.Reconfigure) self.recon_cache = {} def reconfigure(self,", "= dynamic_reconfigure.encoding.encode_config(params) self.recon_cache.update(changed) self.recon(msg) if self.im_queue is not None: #clear", "post_func=None, post_func_args=[], verbose=False): self._result.clear() for ch in self.cam_handlers: self._result[ch.topic_prefix] =", "self.debug = debug rospy.Subscriber( '%s/image_raw'%self.topic_prefix, sensor_msgs.msg.Image, self.get_image_callback) self.pipeline_max_latency = 0.2", "verbose: rospy.loginfo(' _is_done() has %d frames for %r'%(len(rdict[topic_prefix]), topic_prefix)) if", "t=%f was too early (by %f)\" % (topic_prefix, t_image, t_earliest", "t_image > t_latest: rospy.logwarn(\"image from %s at t=%f was too", "msg = dynamic_reconfigure.encoding.encode_config(params) self.recon_cache.update(changed) self.recon(msg) if self.im_queue is not None:", "= ros_latency self.max_cam_latency = max( [ch.pipeline_max_latency for ch in self.cam_handlers", "= max( [ch.pipeline_max_latency for ch in self.cam_handlers ]) self._result =", "def result(self): return self._result @property def result_as_nparray(self): res = {}", "@property def result_as_nparray(self): res = {} for cam in self._result:", "False self.check_latest = False def get_images(self,n_per_camera,verbose=False): self._result.clear() for ch in", "- t_latest)) if self.check_earliest and t_image < t_earliest: rospy.logwarn(\"image from", "#wait for the images to arrive while not self._is_done(self._result,n_per_camera,verbose=verbose): try:", "wait 50 msec def clear_queue(self): q = self.im_queue while 1:", "< t_earliest: rospy.logwarn(\"image from %s at t=%f was too early", "if self.recon is not None: changed = {} for k,v", "self._result @property def result_as_nparray(self): res = {} for cam in", "except queue.Empty: break def _is_done(self,rdict,n_per_camera,verbose=False): done=True for topic_prefix in list(rdict.keys()):", "return done class SimultaneousCameraRunner(_Runner): def __init__(self,cam_handlers,**kwargs): _Runner.__init__(self, cam_handlers,**kwargs) def get_images(self,n_per_camera,", "import rospy import sensor_msgs.msg import dynamic_reconfigure.srv import dynamic_reconfigure.encoding import numpy", "def __init__(self,topic_prefix='',debug=False,enable_dynamic_reconfigure=False): self.topic_prefix=topic_prefix self.debug = debug rospy.Subscriber( '%s/image_raw'%self.topic_prefix, sensor_msgs.msg.Image, self.get_image_callback)", "#clear the queue so we get a new image with", "+ self.max_cam_latency) while not self._is_done(self._result,n_per_camera,verbose=verbose): try: topic_prefix, msg = self.im_queue.get(1,10.0)", "self._result[ch.topic_prefix] = [] #clear the queue self.clear_queue() if pre_func: pre_func(*pre_func_args)", "t_earliest = time.time() self.clear_queue() t_latest = t_earliest + (self.ros_latency +", "break def _is_done(self,rdict,n_per_camera,verbose=False): done=True for topic_prefix in list(rdict.keys()): if verbose:", "v: changed[k] = v else: changed[k] = v if changed:", "= np.fromstring(msg.data,dtype=np.uint8) imarr.shape = (msg.height, msg.width) tmpres[i] = imarr #sad", "= {} for cam in self._result: nimgs = len(self._result[cam]) tmpres", "+ (self.ros_latency + self.max_cam_latency)*n_per_camera #wait for the images to arrive", "slow (by %f)\" % (topic_prefix, t_image, t_image - t_latest)) if", "{} def reconfigure(self, **params): if self.recon is not None: changed", "if k in self.recon_cache: if self.recon_cache[k] != v: changed[k] =", "= time.time() self.clear_queue() t_latest = t_earliest + (self.ros_latency + self.max_cam_latency)", "self.last_image = None self.im_queue = None self.recon = None if", "dur ): tstart = time.time() while (time.time() - tstart) <", "if verbose: rospy.loginfo(' _is_done() has %d frames for %r'%(len(rdict[topic_prefix]), topic_prefix))", "for ch in self.cam_handlers ]) self._result = {} @property def", "IMO res[cam][:,:,i] = imarr #should have worked. res[cam] = np.dstack(tmpres)", "not None: changed = {} for k,v in list(params.items()): if", "**params): if self.recon is not None: changed = {} for", "%f\" % (self.topic_prefix, msg.header.stamp.to_sec())) self.im_queue.put_nowait((self.topic_prefix,msg)) except queue.Full: if self.debug: print(self.topic_prefix,\"full\")", "post_func_args=[], verbose=False): self._result.clear() for ch in self.cam_handlers: self._result[ch.topic_prefix] = []", "{} for cam in self._result: nimgs = len(self._result[cam]) tmpres =", "n_per_camera: done=False return done class SimultaneousCameraRunner(_Runner): def __init__(self,cam_handlers,**kwargs): _Runner.__init__(self, cam_handlers,**kwargs)", "try: if self.debug: print(\"%s got image: %f\" % (self.topic_prefix, msg.header.stamp.to_sec()))", "self.recon_cache[k] != v: changed[k] = v else: changed[k] = v", "return res def cycle_duration( self, dur ): tstart = time.time()", "self.max_cam_latency)*n_per_camera #wait for the images to arrive while not self._is_done(self._result,n_per_camera,verbose=verbose):", ") if post_func: post_func(*post_func_args) class SequentialCameraRunner(_Runner): def __init__(self,cam_handlers,**kwargs): _Runner.__init__(self, cam_handlers,**kwargs)", "self.im_queue.get(1,10.0) # block, 10 second timeout except queue.Empty: continue t_image", "= time.time() while (time.time() - tstart) < dur: time.sleep(0.05) #", "[] t_earliest = time.time() self.clear_queue() t_latest = t_earliest + (self.ros_latency", "0.2 self.last_image = None self.im_queue = None self.recon = None", "import dynamic_reconfigure.srv import dynamic_reconfigure.encoding import numpy as np import time", "self, dur ): tstart = time.time() while (time.time() - tstart)", "(self.topic_prefix, msg.header.stamp.to_sec())) self.im_queue.put_nowait((self.topic_prefix,msg)) except queue.Full: if self.debug: print(self.topic_prefix,\"full\") class _Runner(object):", "if len(rdict[topic_prefix]) < n_per_camera: done=False return done class SimultaneousCameraRunner(_Runner): def", "msg.width) imarr = np.fromstring(msg.data,dtype=np.uint8) imarr.shape = (msg.height, msg.width) tmpres[i] =", "False def get_images(self,n_per_camera,verbose=False): self._result.clear() for ch in self.cam_handlers: self._result[ch.topic_prefix] =", "% (topic_prefix, t_image, t_image - t_latest)) if self.check_earliest and t_image", "block, 10 second timeout except queue.Empty: continue t_image = msg.header.stamp.to_sec()", "len(rdict[topic_prefix]) < n_per_camera: done=False return done class SimultaneousCameraRunner(_Runner): def __init__(self,cam_handlers,**kwargs):", "so we get a new image with the new settings", "topic_prefix, msg = self.im_queue.get(1,10.0) # block, 10 second timeout except", "queue class CameraHandler(object): def __init__(self,topic_prefix='',debug=False,enable_dynamic_reconfigure=False): self.topic_prefix=topic_prefix self.debug = debug rospy.Subscriber(", "import numpy as np import time import os.path import queue", "shape = (msg.height, msg.width) imarr = np.fromstring(msg.data,dtype=np.uint8) imarr.shape = (msg.height,", "for the images to arrive while not self._is_done(self._result,n_per_camera,verbose=verbose): try: topic_prefix,", "#sad to use dstack here, IMO res[cam][:,:,i] = imarr #should", "slow (by %f)\" % (topic_prefix, t_image, t_image - t_latest)) self._result[topic_prefix].append(", "#should have worked. res[cam] = np.dstack(tmpres) return res def cycle_duration(", "if pre_func: pre_func(*pre_func_args) t_latest = time.time() + (self.ros_latency + self.max_cam_latency)*n_per_camera", "self.cam_handlers: ch.set_im_queue(self.im_queue) self.ros_latency = ros_latency self.max_cam_latency = max( [ch.pipeline_max_latency for", "10 second timeout except queue.Empty: continue t_image = msg.header.stamp.to_sec() if", "self.ros_latency = ros_latency self.max_cam_latency = max( [ch.pipeline_max_latency for ch in", "self.check_latest and t_image > t_latest: rospy.logwarn(\"image from %s at t=%f", "set_im_queue(self,q): self.im_queue = q def get_image_callback(self,msg): if self.im_queue is None:", "= [0]*nimgs for i in range(nimgs): msg = self._result[cam][i] shape", "self.check_latest = False def get_images(self,n_per_camera,verbose=False): self._result.clear() for ch in self.cam_handlers:", "# block, 10 second timeout except queue.Empty: continue t_image =", "self._result: nimgs = len(self._result[cam]) tmpres = [0]*nimgs for i in", "self.recon_cache = {} def reconfigure(self, **params): if self.recon is not", "too early (by %f)\" % (topic_prefix, t_image, t_earliest - t_image))", "np.fromstring(msg.data,dtype=np.uint8) imarr.shape = (msg.height, msg.width) tmpres[i] = imarr #sad to", "= msg.header.stamp.to_sec() if t_image > t_latest: rospy.logwarn(\"image from %s at", "self._result[ch.topic_prefix] = [] t_earliest = time.time() self.clear_queue() t_latest = t_earliest", "def get_images(self,n_per_camera,verbose=False): self._result.clear() for ch in self.cam_handlers: self._result[ch.topic_prefix] = []", "pre_func=None, pre_func_args=[], post_func=None, post_func_args=[], verbose=False): self._result.clear() for ch in self.cam_handlers:", "= np.dstack(tmpres) return res def cycle_duration( self, dur ): tstart", "for cam in self._result: nimgs = len(self._result[cam]) tmpres = [0]*nimgs", "queue so we get a new image with the new", "import time import os.path import queue class CameraHandler(object): def __init__(self,topic_prefix='',debug=False,enable_dynamic_reconfigure=False):", "#clear the queue self.clear_queue() if pre_func: pre_func(*pre_func_args) t_latest = time.time()", "while 1: try: q.get_nowait() except queue.Empty: break def _is_done(self,rdict,n_per_camera,verbose=False): done=True", "def reconfigure(self, **params): if self.recon is not None: changed =", "print(self.topic_prefix,\"full\") class _Runner(object): def __init__(self,cam_handlers,ros_latency=0.2,queue_depth=20): self.cam_handlers = cam_handlers self.im_queue =", "class _Runner(object): def __init__(self,cam_handlers,ros_latency=0.2,queue_depth=20): self.cam_handlers = cam_handlers self.im_queue = queue.Queue(len(cam_handlers)*queue_depth)", "def __init__(self,cam_handlers,**kwargs): _Runner.__init__(self, cam_handlers,**kwargs) self.wait_duration = kwargs.get(\"wait_duration\", 0.1) self.check_earliest =", "= rospy.ServiceProxy('%s/set_parameters'%self.topic_prefix, dynamic_reconfigure.srv.Reconfigure) self.recon_cache = {} def reconfigure(self, **params): if", "frames for %r'%(len(rdict[topic_prefix]), topic_prefix)) if len(rdict[topic_prefix]) < n_per_camera: done=False return", "msg.header.stamp.to_sec() if t_image > t_latest: rospy.logwarn(\"image from %s at t=%f", "if self.im_queue is not None: #clear the queue so we", "get_images(self,n_per_camera,verbose=False): self._result.clear() for ch in self.cam_handlers: self._result[ch.topic_prefix] = [] t_earliest", "self.get_image_callback) self.pipeline_max_latency = 0.2 self.last_image = None self.im_queue = None", "v if changed: msg = dynamic_reconfigure.encoding.encode_config(params) self.recon_cache.update(changed) self.recon(msg) if self.im_queue", "= (msg.height, msg.width) imarr = np.fromstring(msg.data,dtype=np.uint8) imarr.shape = (msg.height, msg.width)", "tmpres[i] = imarr #sad to use dstack here, IMO res[cam][:,:,i]", "+ (self.ros_latency + self.max_cam_latency) while not self._is_done(self._result,n_per_camera,verbose=verbose): try: topic_prefix, msg", "not self._is_done(self._result,n_per_camera,verbose=verbose): try: topic_prefix, msg = self.im_queue.get(1,10.0) # block, 10", "we get a new image with the new settings while", "in list(params.items()): if k in self.recon_cache: if self.recon_cache[k] != v:", "break def set_im_queue(self,q): self.im_queue = q def get_image_callback(self,msg): if self.im_queue", "list(params.items()): if k in self.recon_cache: if self.recon_cache[k] != v: changed[k]", "1: try: q.get_nowait() except queue.Empty: break def _is_done(self,rdict,n_per_camera,verbose=False): done=True for", "the images to arrive while not self._is_done(self._result,n_per_camera,verbose=verbose): try: topic_prefix, msg", "dynamic_reconfigure.srv.Reconfigure) self.recon_cache = {} def reconfigure(self, **params): if self.recon is", "= v else: changed[k] = v if changed: msg =", "the queue so we get a new image with the", "self._result.clear() for ch in self.cam_handlers: self._result[ch.topic_prefix] = [] t_earliest =", "(topic_prefix, t_image, t_image - t_latest)) self._result[topic_prefix].append( msg ) if post_func:", "rospy.Subscriber( '%s/image_raw'%self.topic_prefix, sensor_msgs.msg.Image, self.get_image_callback) self.pipeline_max_latency = 0.2 self.last_image = None", "for i in range(nimgs): msg = self._result[cam][i] shape = (msg.height,", "msg = self._result[cam][i] shape = (msg.height, msg.width) imarr = np.fromstring(msg.data,dtype=np.uint8)", "return try: if self.debug: print(\"%s got image: %f\" % (self.topic_prefix,", "return self._result @property def result_as_nparray(self): res = {} for cam", "self.cam_handlers: self._result[ch.topic_prefix] = [] #clear the queue self.clear_queue() if pre_func:", "with the new settings while True: try: self.im_queue.get_nowait() except queue.Empty:", "import sensor_msgs.msg import dynamic_reconfigure.srv import dynamic_reconfigure.encoding import numpy as np", "np import time import os.path import queue class CameraHandler(object): def", "images to arrive while not self._is_done(self._result,n_per_camera,verbose=verbose): try: topic_prefix, msg =", "except queue.Full: if self.debug: print(self.topic_prefix,\"full\") class _Runner(object): def __init__(self,cam_handlers,ros_latency=0.2,queue_depth=20): self.cam_handlers", "= False self.check_latest = False def get_images(self,n_per_camera,verbose=False): self._result.clear() for ch", "ch in self.cam_handlers: self._result[ch.topic_prefix] = [] t_earliest = time.time() self.clear_queue()", "new image with the new settings while True: try: self.im_queue.get_nowait()", "get_image_callback(self,msg): if self.im_queue is None: return try: if self.debug: print(\"%s", "continue t_image = msg.header.stamp.to_sec() if self.check_latest and t_image > t_latest:", "= v if changed: msg = dynamic_reconfigure.encoding.encode_config(params) self.recon_cache.update(changed) self.recon(msg) if", "except queue.Empty: break def set_im_queue(self,q): self.im_queue = q def get_image_callback(self,msg):", "self.im_queue = q def get_image_callback(self,msg): if self.im_queue is None: return", "(msg.height, msg.width) imarr = np.fromstring(msg.data,dtype=np.uint8) imarr.shape = (msg.height, msg.width) tmpres[i]", "None self.recon = None if enable_dynamic_reconfigure: self.recon = rospy.ServiceProxy('%s/set_parameters'%self.topic_prefix, dynamic_reconfigure.srv.Reconfigure)", "ch in self.cam_handlers ]) self._result = {} @property def result(self):", "self.recon is not None: changed = {} for k,v in", "t=%f was too slow (by %f)\" % (topic_prefix, t_image, t_image", "t_latest = time.time() + (self.ros_latency + self.max_cam_latency)*n_per_camera #wait for the", "self.cam_handlers = cam_handlers self.im_queue = queue.Queue(len(cam_handlers)*queue_depth) for ch in self.cam_handlers:", "- tstart) < dur: time.sleep(0.05) # wait 50 msec def", "else: changed[k] = v if changed: msg = dynamic_reconfigure.encoding.encode_config(params) self.recon_cache.update(changed)", "0.1) self.check_earliest = False self.check_latest = False def get_images(self,n_per_camera,verbose=False): self._result.clear()", "self.check_earliest = False self.check_latest = False def get_images(self,n_per_camera,verbose=False): self._result.clear() for", "self.pipeline_max_latency = 0.2 self.last_image = None self.im_queue = None self.recon", "= None self.recon = None if enable_dynamic_reconfigure: self.recon = rospy.ServiceProxy('%s/set_parameters'%self.topic_prefix,", "rospy import sensor_msgs.msg import dynamic_reconfigure.srv import dynamic_reconfigure.encoding import numpy as", "early (by %f)\" % (topic_prefix, t_image, t_earliest - t_image)) continue", "= debug rospy.Subscriber( '%s/image_raw'%self.topic_prefix, sensor_msgs.msg.Image, self.get_image_callback) self.pipeline_max_latency = 0.2 self.last_image", "res = {} for cam in self._result: nimgs = len(self._result[cam])", "dynamic_reconfigure.srv import dynamic_reconfigure.encoding import numpy as np import time import", "k in self.recon_cache: if self.recon_cache[k] != v: changed[k] = v", "(msg.height, msg.width) tmpres[i] = imarr #sad to use dstack here,", "for k,v in list(params.items()): if k in self.recon_cache: if self.recon_cache[k]", "clear_queue(self): q = self.im_queue while 1: try: q.get_nowait() except queue.Empty:", "timeout except queue.Empty: continue t_image = msg.header.stamp.to_sec() if t_image >", "tstart) < dur: time.sleep(0.05) # wait 50 msec def clear_queue(self):", "(by %f)\" % (topic_prefix, t_image, t_image - t_latest)) if self.check_earliest", "try: q.get_nowait() except queue.Empty: break def _is_done(self,rdict,n_per_camera,verbose=False): done=True for topic_prefix", "self.recon(msg) if self.im_queue is not None: #clear the queue so", "!= v: changed[k] = v else: changed[k] = v if", "imarr #sad to use dstack here, IMO res[cam][:,:,i] = imarr", "settings while True: try: self.im_queue.get_nowait() except queue.Empty: break def set_im_queue(self,q):", "debug rospy.Subscriber( '%s/image_raw'%self.topic_prefix, sensor_msgs.msg.Image, self.get_image_callback) self.pipeline_max_latency = 0.2 self.last_image =", "np.dstack(tmpres) return res def cycle_duration( self, dur ): tstart =", "t_image, t_image - t_latest)) self._result[topic_prefix].append( msg ) if post_func: post_func(*post_func_args)", "is None: return try: if self.debug: print(\"%s got image: %f\"", "= t_earliest + (self.ros_latency + self.max_cam_latency) while not self._is_done(self._result,n_per_camera,verbose=verbose): try:", "t_latest)) self._result[topic_prefix].append( msg ) if post_func: post_func(*post_func_args) class SequentialCameraRunner(_Runner): def", "self.cam_handlers: self._result[ch.topic_prefix] = [] t_earliest = time.time() self.clear_queue() t_latest =", "self.clear_queue() if pre_func: pre_func(*pre_func_args) t_latest = time.time() + (self.ros_latency +", "def cycle_duration( self, dur ): tstart = time.time() while (time.time()", "= False def get_images(self,n_per_camera,verbose=False): self._result.clear() for ch in self.cam_handlers: self._result[ch.topic_prefix]", "self.recon_cache: if self.recon_cache[k] != v: changed[k] = v else: changed[k]", "__init__(self,topic_prefix='',debug=False,enable_dynamic_reconfigure=False): self.topic_prefix=topic_prefix self.debug = debug rospy.Subscriber( '%s/image_raw'%self.topic_prefix, sensor_msgs.msg.Image, self.get_image_callback) self.pipeline_max_latency", "image: %f\" % (self.topic_prefix, msg.header.stamp.to_sec())) self.im_queue.put_nowait((self.topic_prefix,msg)) except queue.Full: if self.debug:", "cam_handlers,**kwargs) self.wait_duration = kwargs.get(\"wait_duration\", 0.1) self.check_earliest = False self.check_latest =", "[0]*nimgs for i in range(nimgs): msg = self._result[cam][i] shape =", "_Runner(object): def __init__(self,cam_handlers,ros_latency=0.2,queue_depth=20): self.cam_handlers = cam_handlers self.im_queue = queue.Queue(len(cam_handlers)*queue_depth) for", "imarr.shape = (msg.height, msg.width) tmpres[i] = imarr #sad to use", "range(nimgs): msg = self._result[cam][i] shape = (msg.height, msg.width) imarr =", "def get_images(self,n_per_camera, pre_func=None, pre_func_args=[], post_func=None, post_func_args=[], verbose=False): self._result.clear() for ch", "time.sleep(0.05) # wait 50 msec def clear_queue(self): q = self.im_queue", "]) self._result = {} @property def result(self): return self._result @property", "for %r'%(len(rdict[topic_prefix]), topic_prefix)) if len(rdict[topic_prefix]) < n_per_camera: done=False return done", "import roslib roslib.load_manifest('sensor_msgs') roslib.load_manifest('dynamic_reconfigure') import rospy import sensor_msgs.msg import dynamic_reconfigure.srv", "self.im_queue is not None: #clear the queue so we get", "self.im_queue while 1: try: q.get_nowait() except queue.Empty: break def _is_done(self,rdict,n_per_camera,verbose=False):", "self._result.clear() for ch in self.cam_handlers: self._result[ch.topic_prefix] = [] #clear the", "changed[k] = v else: changed[k] = v if changed: msg", "cam_handlers,**kwargs) def get_images(self,n_per_camera, pre_func=None, pre_func_args=[], post_func=None, post_func_args=[], verbose=False): self._result.clear() for", "self.im_queue.put_nowait((self.topic_prefix,msg)) except queue.Full: if self.debug: print(self.topic_prefix,\"full\") class _Runner(object): def __init__(self,cam_handlers,ros_latency=0.2,queue_depth=20):", "at t=%f was too slow (by %f)\" % (topic_prefix, t_image,", "t_latest)) if self.check_earliest and t_image < t_earliest: rospy.logwarn(\"image from %s", "def set_im_queue(self,q): self.im_queue = q def get_image_callback(self,msg): if self.im_queue is", "(by %f)\" % (topic_prefix, t_image, t_earliest - t_image)) continue self._result[topic_prefix].append(", "got image: %f\" % (self.topic_prefix, msg.header.stamp.to_sec())) self.im_queue.put_nowait((self.topic_prefix,msg)) except queue.Full: if", "done=False return done class SimultaneousCameraRunner(_Runner): def __init__(self,cam_handlers,**kwargs): _Runner.__init__(self, cam_handlers,**kwargs) def", "ch in self.cam_handlers: self._result[ch.topic_prefix] = [] #clear the queue self.clear_queue()", "roslib roslib.load_manifest('sensor_msgs') roslib.load_manifest('dynamic_reconfigure') import rospy import sensor_msgs.msg import dynamic_reconfigure.srv import", "cam in self._result: nimgs = len(self._result[cam]) tmpres = [0]*nimgs for", "is not None: #clear the queue so we get a", "as np import time import os.path import queue class CameraHandler(object):", "= self._result[cam][i] shape = (msg.height, msg.width) imarr = np.fromstring(msg.data,dtype=np.uint8) imarr.shape", "queue.Empty: break def _is_done(self,rdict,n_per_camera,verbose=False): done=True for topic_prefix in list(rdict.keys()): if", "rospy.loginfo(' _is_done() has %d frames for %r'%(len(rdict[topic_prefix]), topic_prefix)) if len(rdict[topic_prefix])", "in self.cam_handlers: self._result[ch.topic_prefix] = [] t_earliest = time.time() self.clear_queue() t_latest", "t_image, t_image - t_latest)) if self.check_earliest and t_image < t_earliest:", "< dur: time.sleep(0.05) # wait 50 msec def clear_queue(self): q", "in self.recon_cache: if self.recon_cache[k] != v: changed[k] = v else:", "(by %f)\" % (topic_prefix, t_image, t_image - t_latest)) self._result[topic_prefix].append( msg", "the queue self.clear_queue() if pre_func: pre_func(*pre_func_args) t_latest = time.time() +", "has %d frames for %r'%(len(rdict[topic_prefix]), topic_prefix)) if len(rdict[topic_prefix]) < n_per_camera:", "'%s/image_raw'%self.topic_prefix, sensor_msgs.msg.Image, self.get_image_callback) self.pipeline_max_latency = 0.2 self.last_image = None self.im_queue", "kwargs.get(\"wait_duration\", 0.1) self.check_earliest = False self.check_latest = False def get_images(self,n_per_camera,verbose=False):", "self.recon_cache.update(changed) self.recon(msg) if self.im_queue is not None: #clear the queue", "list(rdict.keys()): if verbose: rospy.loginfo(' _is_done() has %d frames for %r'%(len(rdict[topic_prefix]),", "= None self.im_queue = None self.recon = None if enable_dynamic_reconfigure:", "time.time() self.clear_queue() t_latest = t_earliest + (self.ros_latency + self.max_cam_latency) while", "<filename>src/freemovr_engine/calib/acquire.py import roslib roslib.load_manifest('sensor_msgs') roslib.load_manifest('dynamic_reconfigure') import rospy import sensor_msgs.msg import", "= {} for k,v in list(params.items()): if k in self.recon_cache:", "res[cam][:,:,i] = imarr #should have worked. res[cam] = np.dstack(tmpres) return", "roslib.load_manifest('dynamic_reconfigure') import rospy import sensor_msgs.msg import dynamic_reconfigure.srv import dynamic_reconfigure.encoding import", "have worked. res[cam] = np.dstack(tmpres) return res def cycle_duration( self,", "done=True for topic_prefix in list(rdict.keys()): if verbose: rospy.loginfo(' _is_done() has", "if self.check_latest and t_image > t_latest: rospy.logwarn(\"image from %s at", "while (time.time() - tstart) < dur: time.sleep(0.05) # wait 50", "None: #clear the queue so we get a new image", "rospy.logwarn(\"image from %s at t=%f was too slow (by %f)\"", "new settings while True: try: self.im_queue.get_nowait() except queue.Empty: break def", "msg = self.im_queue.get(1,10.0) # block, 10 second timeout except queue.Empty:", "t_image = msg.header.stamp.to_sec() if t_image > t_latest: rospy.logwarn(\"image from %s", "was too slow (by %f)\" % (topic_prefix, t_image, t_image -", "= imarr #should have worked. res[cam] = np.dstack(tmpres) return res", "if self.debug: print(\"%s got image: %f\" % (self.topic_prefix, msg.header.stamp.to_sec())) self.im_queue.put_nowait((self.topic_prefix,msg))", "def __init__(self,cam_handlers,ros_latency=0.2,queue_depth=20): self.cam_handlers = cam_handlers self.im_queue = queue.Queue(len(cam_handlers)*queue_depth) for ch", "_Runner.__init__(self, cam_handlers,**kwargs) def get_images(self,n_per_camera, pre_func=None, pre_func_args=[], post_func=None, post_func_args=[], verbose=False): self._result.clear()", "= self.im_queue while 1: try: q.get_nowait() except queue.Empty: break def", "dstack here, IMO res[cam][:,:,i] = imarr #should have worked. res[cam]", "topic_prefix in list(rdict.keys()): if verbose: rospy.loginfo(' _is_done() has %d frames", "if enable_dynamic_reconfigure: self.recon = rospy.ServiceProxy('%s/set_parameters'%self.topic_prefix, dynamic_reconfigure.srv.Reconfigure) self.recon_cache = {} def", "t_latest = t_earliest + (self.ros_latency + self.max_cam_latency) while not self._is_done(self._result,n_per_camera,verbose=verbose):", "[ch.pipeline_max_latency for ch in self.cam_handlers ]) self._result = {} @property", "None: changed = {} for k,v in list(params.items()): if k", "_Runner.__init__(self, cam_handlers,**kwargs) self.wait_duration = kwargs.get(\"wait_duration\", 0.1) self.check_earliest = False self.check_latest", "if self.im_queue is None: return try: if self.debug: print(\"%s got", "sensor_msgs.msg import dynamic_reconfigure.srv import dynamic_reconfigure.encoding import numpy as np import", "def get_image_callback(self,msg): if self.im_queue is None: return try: if self.debug:", "msec def clear_queue(self): q = self.im_queue while 1: try: q.get_nowait()", "t_image - t_latest)) if self.check_earliest and t_image < t_earliest: rospy.logwarn(\"image", "rospy.logwarn(\"image from %s at t=%f was too early (by %f)\"", "try: self.im_queue.get_nowait() except queue.Empty: break def set_im_queue(self,q): self.im_queue = q", "self.topic_prefix=topic_prefix self.debug = debug rospy.Subscriber( '%s/image_raw'%self.topic_prefix, sensor_msgs.msg.Image, self.get_image_callback) self.pipeline_max_latency =", "self.check_earliest and t_image < t_earliest: rospy.logwarn(\"image from %s at t=%f", "in range(nimgs): msg = self._result[cam][i] shape = (msg.height, msg.width) imarr", "changed: msg = dynamic_reconfigure.encoding.encode_config(params) self.recon_cache.update(changed) self.recon(msg) if self.im_queue is not", "in self.cam_handlers: self._result[ch.topic_prefix] = [] #clear the queue self.clear_queue() if", "queue.Empty: continue t_image = msg.header.stamp.to_sec() if t_image > t_latest: rospy.logwarn(\"image", "here, IMO res[cam][:,:,i] = imarr #should have worked. res[cam] =", "%s at t=%f was too slow (by %f)\" % (topic_prefix,", "v else: changed[k] = v if changed: msg = dynamic_reconfigure.encoding.encode_config(params)", "= [] t_earliest = time.time() self.clear_queue() t_latest = t_earliest +", "while True: try: self.im_queue.get_nowait() except queue.Empty: break def set_im_queue(self,q): self.im_queue", "ch.set_im_queue(self.im_queue) self.ros_latency = ros_latency self.max_cam_latency = max( [ch.pipeline_max_latency for ch", "%f)\" % (topic_prefix, t_image, t_image - t_latest)) if self.check_earliest and", "numpy as np import time import os.path import queue class", "(topic_prefix, t_image, t_image - t_latest)) if self.check_earliest and t_image <", "= msg.header.stamp.to_sec() if self.check_latest and t_image > t_latest: rospy.logwarn(\"image from", "%r'%(len(rdict[topic_prefix]), topic_prefix)) if len(rdict[topic_prefix]) < n_per_camera: done=False return done class", "= {} @property def result(self): return self._result @property def result_as_nparray(self):", "= cam_handlers self.im_queue = queue.Queue(len(cam_handlers)*queue_depth) for ch in self.cam_handlers: ch.set_im_queue(self.im_queue)", "queue.Empty: break def set_im_queue(self,q): self.im_queue = q def get_image_callback(self,msg): if", "changed = {} for k,v in list(params.items()): if k in", "msg.header.stamp.to_sec() if self.check_latest and t_image > t_latest: rospy.logwarn(\"image from %s", "self._result[cam][i] shape = (msg.height, msg.width) imarr = np.fromstring(msg.data,dtype=np.uint8) imarr.shape =", "res[cam] = np.dstack(tmpres) return res def cycle_duration( self, dur ):", "{} for k,v in list(params.items()): if k in self.recon_cache: if", "self.cam_handlers ]) self._result = {} @property def result(self): return self._result", "__init__(self,cam_handlers,ros_latency=0.2,queue_depth=20): self.cam_handlers = cam_handlers self.im_queue = queue.Queue(len(cam_handlers)*queue_depth) for ch in", "@property def result(self): return self._result @property def result_as_nparray(self): res =", "in self._result: nimgs = len(self._result[cam]) tmpres = [0]*nimgs for i", "imarr = np.fromstring(msg.data,dtype=np.uint8) imarr.shape = (msg.height, msg.width) tmpres[i] = imarr", "topic_prefix)) if len(rdict[topic_prefix]) < n_per_camera: done=False return done class SimultaneousCameraRunner(_Runner):", "res def cycle_duration( self, dur ): tstart = time.time() while", "max( [ch.pipeline_max_latency for ch in self.cam_handlers ]) self._result = {}", "not None: #clear the queue so we get a new", "print(\"%s got image: %f\" % (self.topic_prefix, msg.header.stamp.to_sec())) self.im_queue.put_nowait((self.topic_prefix,msg)) except queue.Full:", "if self.recon_cache[k] != v: changed[k] = v else: changed[k] =", "timeout except queue.Empty: continue t_image = msg.header.stamp.to_sec() if self.check_latest and", "t_latest: rospy.logwarn(\"image from %s at t=%f was too slow (by", "self.max_cam_latency = max( [ch.pipeline_max_latency for ch in self.cam_handlers ]) self._result", "(time.time() - tstart) < dur: time.sleep(0.05) # wait 50 msec", "msg.header.stamp.to_sec())) self.im_queue.put_nowait((self.topic_prefix,msg)) except queue.Full: if self.debug: print(self.topic_prefix,\"full\") class _Runner(object): def", "def __init__(self,cam_handlers,**kwargs): _Runner.__init__(self, cam_handlers,**kwargs) def get_images(self,n_per_camera, pre_func=None, pre_func_args=[], post_func=None, post_func_args=[],", "time.time() + (self.ros_latency + self.max_cam_latency)*n_per_camera #wait for the images to", "self.recon = rospy.ServiceProxy('%s/set_parameters'%self.topic_prefix, dynamic_reconfigure.srv.Reconfigure) self.recon_cache = {} def reconfigure(self, **params):", "self.debug: print(self.topic_prefix,\"full\") class _Runner(object): def __init__(self,cam_handlers,ros_latency=0.2,queue_depth=20): self.cam_handlers = cam_handlers self.im_queue", "def clear_queue(self): q = self.im_queue while 1: try: q.get_nowait() except", "self._is_done(self._result,n_per_camera,verbose=verbose): try: topic_prefix, msg = self.im_queue.get(1,10.0) # block, 10 second", "%f)\" % (topic_prefix, t_image, t_image - t_latest)) self._result[topic_prefix].append( msg )", "a new image with the new settings while True: try:", "- t_latest)) self._result[topic_prefix].append( msg ) if post_func: post_func(*post_func_args) class SequentialCameraRunner(_Runner):", "and t_image > t_latest: rospy.logwarn(\"image from %s at t=%f was", "len(self._result[cam]) tmpres = [0]*nimgs for i in range(nimgs): msg =", "result_as_nparray(self): res = {} for cam in self._result: nimgs =", "class CameraHandler(object): def __init__(self,topic_prefix='',debug=False,enable_dynamic_reconfigure=False): self.topic_prefix=topic_prefix self.debug = debug rospy.Subscriber( '%s/image_raw'%self.topic_prefix,", "is not None: changed = {} for k,v in list(params.items()):", "_is_done() has %d frames for %r'%(len(rdict[topic_prefix]), topic_prefix)) if len(rdict[topic_prefix]) <", "self.clear_queue() t_latest = t_earliest + (self.ros_latency + self.max_cam_latency) while not", "tmpres = [0]*nimgs for i in range(nimgs): msg = self._result[cam][i]", "and t_image < t_earliest: rospy.logwarn(\"image from %s at t=%f was", "queue self.clear_queue() if pre_func: pre_func(*pre_func_args) t_latest = time.time() + (self.ros_latency", "= (msg.height, msg.width) tmpres[i] = imarr #sad to use dstack", "None self.im_queue = None self.recon = None if enable_dynamic_reconfigure: self.recon", "SequentialCameraRunner(_Runner): def __init__(self,cam_handlers,**kwargs): _Runner.__init__(self, cam_handlers,**kwargs) self.wait_duration = kwargs.get(\"wait_duration\", 0.1) self.check_earliest", "queue.Queue(len(cam_handlers)*queue_depth) for ch in self.cam_handlers: ch.set_im_queue(self.im_queue) self.ros_latency = ros_latency self.max_cam_latency", "image with the new settings while True: try: self.im_queue.get_nowait() except", "msg ) if post_func: post_func(*post_func_args) class SequentialCameraRunner(_Runner): def __init__(self,cam_handlers,**kwargs): _Runner.__init__(self,", "continue t_image = msg.header.stamp.to_sec() if t_image > t_latest: rospy.logwarn(\"image from", "self.wait_duration = kwargs.get(\"wait_duration\", 0.1) self.check_earliest = False self.check_latest = False", "done class SimultaneousCameraRunner(_Runner): def __init__(self,cam_handlers,**kwargs): _Runner.__init__(self, cam_handlers,**kwargs) def get_images(self,n_per_camera, pre_func=None,", "too slow (by %f)\" % (topic_prefix, t_image, t_image - t_latest))", "class SequentialCameraRunner(_Runner): def __init__(self,cam_handlers,**kwargs): _Runner.__init__(self, cam_handlers,**kwargs) self.wait_duration = kwargs.get(\"wait_duration\", 0.1)", "result(self): return self._result @property def result_as_nparray(self): res = {} for", "None if enable_dynamic_reconfigure: self.recon = rospy.ServiceProxy('%s/set_parameters'%self.topic_prefix, dynamic_reconfigure.srv.Reconfigure) self.recon_cache = {}", "roslib.load_manifest('sensor_msgs') roslib.load_manifest('dynamic_reconfigure') import rospy import sensor_msgs.msg import dynamic_reconfigure.srv import dynamic_reconfigure.encoding", "msg.width) tmpres[i] = imarr #sad to use dstack here, IMO", "t_image < t_earliest: rospy.logwarn(\"image from %s at t=%f was too", "__init__(self,cam_handlers,**kwargs): _Runner.__init__(self, cam_handlers,**kwargs) self.wait_duration = kwargs.get(\"wait_duration\", 0.1) self.check_earliest = False", "True: try: self.im_queue.get_nowait() except queue.Empty: break def set_im_queue(self,q): self.im_queue =", "self.im_queue.get_nowait() except queue.Empty: break def set_im_queue(self,q): self.im_queue = q def", "(self.ros_latency + self.max_cam_latency)*n_per_camera #wait for the images to arrive while", "%s at t=%f was too early (by %f)\" % (topic_prefix,", "def result_as_nparray(self): res = {} for cam in self._result: nimgs", "in list(rdict.keys()): if verbose: rospy.loginfo(' _is_done() has %d frames for", "%f)\" % (topic_prefix, t_image, t_earliest - t_image)) continue self._result[topic_prefix].append( msg", "second timeout except queue.Empty: continue t_image = msg.header.stamp.to_sec() if t_image", "import dynamic_reconfigure.encoding import numpy as np import time import os.path", "# wait 50 msec def clear_queue(self): q = self.im_queue while", "dynamic_reconfigure.encoding.encode_config(params) self.recon_cache.update(changed) self.recon(msg) if self.im_queue is not None: #clear the", "for ch in self.cam_handlers: self._result[ch.topic_prefix] = [] t_earliest = time.time()", "time import os.path import queue class CameraHandler(object): def __init__(self,topic_prefix='',debug=False,enable_dynamic_reconfigure=False): self.topic_prefix=topic_prefix", "= 0.2 self.last_image = None self.im_queue = None self.recon =", "in self.cam_handlers ]) self._result = {} @property def result(self): return", "second timeout except queue.Empty: continue t_image = msg.header.stamp.to_sec() if self.check_latest", "from %s at t=%f was too slow (by %f)\" %", "i in range(nimgs): msg = self._result[cam][i] shape = (msg.height, msg.width)", "t_image = msg.header.stamp.to_sec() if self.check_latest and t_image > t_latest: rospy.logwarn(\"image", "for ch in self.cam_handlers: ch.set_im_queue(self.im_queue) self.ros_latency = ros_latency self.max_cam_latency =", "if self.debug: print(self.topic_prefix,\"full\") class _Runner(object): def __init__(self,cam_handlers,ros_latency=0.2,queue_depth=20): self.cam_handlers = cam_handlers", "t_earliest + (self.ros_latency + self.max_cam_latency) while not self._is_done(self._result,n_per_camera,verbose=verbose): try: topic_prefix,", "= self.im_queue.get(1,10.0) # block, 10 second timeout except queue.Empty: continue", "get a new image with the new settings while True:", "worked. res[cam] = np.dstack(tmpres) return res def cycle_duration( self, dur", "except queue.Empty: continue t_image = msg.header.stamp.to_sec() if t_image > t_latest:", "except queue.Empty: continue t_image = msg.header.stamp.to_sec() if self.check_latest and t_image", "t_earliest: rospy.logwarn(\"image from %s at t=%f was too early (by", "SimultaneousCameraRunner(_Runner): def __init__(self,cam_handlers,**kwargs): _Runner.__init__(self, cam_handlers,**kwargs) def get_images(self,n_per_camera, pre_func=None, pre_func_args=[], post_func=None,", "the new settings while True: try: self.im_queue.get_nowait() except queue.Empty: break", "50 msec def clear_queue(self): q = self.im_queue while 1: try:", "imarr #should have worked. res[cam] = np.dstack(tmpres) return res def", "= time.time() + (self.ros_latency + self.max_cam_latency)*n_per_camera #wait for the images", "cycle_duration( self, dur ): tstart = time.time() while (time.time() -", "pre_func(*pre_func_args) t_latest = time.time() + (self.ros_latency + self.max_cam_latency)*n_per_camera #wait for", "if self.check_earliest and t_image < t_earliest: rospy.logwarn(\"image from %s at", "+ self.max_cam_latency)*n_per_camera #wait for the images to arrive while not", "self.im_queue = queue.Queue(len(cam_handlers)*queue_depth) for ch in self.cam_handlers: ch.set_im_queue(self.im_queue) self.ros_latency =", "dur: time.sleep(0.05) # wait 50 msec def clear_queue(self): q =", "= [] #clear the queue self.clear_queue() if pre_func: pre_func(*pre_func_args) t_latest", "= {} def reconfigure(self, **params): if self.recon is not None:", "import queue class CameraHandler(object): def __init__(self,topic_prefix='',debug=False,enable_dynamic_reconfigure=False): self.topic_prefix=topic_prefix self.debug = debug", "from %s at t=%f was too early (by %f)\" %", "self.max_cam_latency) while not self._is_done(self._result,n_per_camera,verbose=verbose): try: topic_prefix, msg = self.im_queue.get(1,10.0) #", "= kwargs.get(\"wait_duration\", 0.1) self.check_earliest = False self.check_latest = False def", "= None if enable_dynamic_reconfigure: self.recon = rospy.ServiceProxy('%s/set_parameters'%self.topic_prefix, dynamic_reconfigure.srv.Reconfigure) self.recon_cache =", "post_func(*post_func_args) class SequentialCameraRunner(_Runner): def __init__(self,cam_handlers,**kwargs): _Runner.__init__(self, cam_handlers,**kwargs) self.wait_duration = kwargs.get(\"wait_duration\",", "): tstart = time.time() while (time.time() - tstart) < dur:", "q def get_image_callback(self,msg): if self.im_queue is None: return try: if", "= len(self._result[cam]) tmpres = [0]*nimgs for i in range(nimgs): msg", "if t_image > t_latest: rospy.logwarn(\"image from %s at t=%f was", "= q def get_image_callback(self,msg): if self.im_queue is None: return try:", "in self.cam_handlers: ch.set_im_queue(self.im_queue) self.ros_latency = ros_latency self.max_cam_latency = max( [ch.pipeline_max_latency", "[] #clear the queue self.clear_queue() if pre_func: pre_func(*pre_func_args) t_latest =", "while not self._is_done(self._result,n_per_camera,verbose=verbose): try: topic_prefix, msg = self.im_queue.get(1,10.0) # block,", "pre_func: pre_func(*pre_func_args) t_latest = time.time() + (self.ros_latency + self.max_cam_latency)*n_per_camera #wait", "at t=%f was too early (by %f)\" % (topic_prefix, t_image,", "%d frames for %r'%(len(rdict[topic_prefix]), topic_prefix)) if len(rdict[topic_prefix]) < n_per_camera: done=False", "dynamic_reconfigure.encoding import numpy as np import time import os.path import", "self._result[topic_prefix].append( msg ) if post_func: post_func(*post_func_args) class SequentialCameraRunner(_Runner): def __init__(self,cam_handlers,**kwargs):", "nimgs = len(self._result[cam]) tmpres = [0]*nimgs for i in range(nimgs):", "q.get_nowait() except queue.Empty: break def _is_done(self,rdict,n_per_camera,verbose=False): done=True for topic_prefix in", "CameraHandler(object): def __init__(self,topic_prefix='',debug=False,enable_dynamic_reconfigure=False): self.topic_prefix=topic_prefix self.debug = debug rospy.Subscriber( '%s/image_raw'%self.topic_prefix, sensor_msgs.msg.Image,", "pre_func_args=[], post_func=None, post_func_args=[], verbose=False): self._result.clear() for ch in self.cam_handlers: self._result[ch.topic_prefix]", "verbose=False): self._result.clear() for ch in self.cam_handlers: self._result[ch.topic_prefix] = [] #clear", "os.path import queue class CameraHandler(object): def __init__(self,topic_prefix='',debug=False,enable_dynamic_reconfigure=False): self.topic_prefix=topic_prefix self.debug =", "= queue.Queue(len(cam_handlers)*queue_depth) for ch in self.cam_handlers: ch.set_im_queue(self.im_queue) self.ros_latency = ros_latency", "% (topic_prefix, t_image, t_earliest - t_image)) continue self._result[topic_prefix].append( msg )", "ros_latency self.max_cam_latency = max( [ch.pipeline_max_latency for ch in self.cam_handlers ])", "_is_done(self,rdict,n_per_camera,verbose=False): done=True for topic_prefix in list(rdict.keys()): if verbose: rospy.loginfo(' _is_done()", "tstart = time.time() while (time.time() - tstart) < dur: time.sleep(0.05)" ]
[ "None: cmd.extend(['--outf', results_dir]) if generate_nonfusible_param(params, 'feature_transform'): cmd.append('--feature_transform') cmd.extend( generate_fusible_param_flags( params,", "params: maps hyperparameter name to its value(s). For HFTA, the", "training process for pointnet classification task. Args: ids: Either a", "isinstance( ids, (list, tuple), ) else str(ids)) # Allocate result", "values are provided as a list. env_vars: optional, dict(str, str)", "train for', ) parser.add_argument('--dataset', type=str, required=True, help=\"dataset path\") parser.add_argument( '--dataset-type',", "(','.join([str(i) for i in ids]) if isinstance( ids, (list, tuple),", "parser.add_argument( '--dataset-type', type=str, default='shapenet', help=\"dataset type shapenet|modelnet40\", ) parser.add_argument( '--num-points',", "type=str, default='cuda', choices=['cpu', 'cuda', 'xla'], help=\"the device where this test", "} for _ in range(max(B, 1))] if B > 0:", "env_vars=env_vars, ) if not succeeded: raise RuntimeError('_run failed!') # Gather", "the training process. succeeded = True try: logging.info('--> Running cmd", "same order as ids. \"\"\" epochs = int(round(epochs)) ids_str =", "Run training. succeeded = _run( results_dir, epochs, args.iters_per_epoch, params, env_vars=env_vars,", "0: params = fuse_dicts(params) else: params = params[0] return _run(None,", "args.mode == 'hfta': cmd.append('--hfta') if args.amp: cmd.append('--amp') # Launch the", "0.1, 0.9), 'step_size': hp.choice('step_size', (5, 10, 20, 40)), } nonfusibles", ") parser.add_argument('--dataset', type=str, required=True, help=\"dataset path\") parser.add_argument( '--dataset-type', type=str, default='shapenet',", "the cmd. cmd = [ 'python', 'train_classification.py', '--epochs', str(epochs), '--iters-per-epoch',", "'step_size'], )) if args.mode == 'hfta': cmd.append('--hfta') if args.amp: cmd.append('--amp')", "(tune_hyperparameters, attach_common_args, rearrange_algorithm_kwargs, handle_integers, generate_fusible_param_flags, generate_nonfusible_param) from hfta.workflow import extract_logging_level", "**handle_integers(sample(fusibles, rng=rng_state)), **nonfusibles_kvs } for _ in range(max(B, 1))] if", "import os import pandas as pd import random import subprocess", "{}'.format(cmd)) subprocess.run( cmd, stdout=subprocess.DEVNULL if results_dir is None else open(", "0.0, 0.5), 'gamma': hp.uniform('gamma', 0.1, 0.9), 'step_size': hp.choice('step_size', (5, 10,", "goal='max', algorithm_configs={ 'hyperband': args.hyperband_kwargs, 'random': args.random_kwargs, }, seed=args.seed, outdir=args.outdir, )", "a single int ID (for serial), or a list of", "argparse import logging import numpy as np import os import", "0.001, 0.999), 'weight_decay': hp.uniform('weight_decay', 0.0, 0.5), 'gamma': hp.uniform('gamma', 0.1, 0.9),", "20, 40)), } nonfusibles = { 'batch_size': hp.choice('batch_size', (8, 16,", "of epochs to run. params: maps hyperparameter name to its", "tuple)): results = [{'acc': acc} for acc in results_frame['acc'].tolist()] assert", "serial or a list of result dicts for HFTA in", "of data loading workers', default=4, ) parser.add_argument( '--iters-per-epoch', type=int, default=int(1e9),", "--device is cuda', ) parser = attach_common_args(parser) return parser if", "needs to be forwarded to the subprocess call Returns: result(s):", "for acc in results_frame['acc'].tolist()] assert len(results) == len(ids) return results,", "if not succeeded: raise RuntimeError('_run failed!') # Gather the results.", "cmd.extend(['--outf', results_dir]) if generate_nonfusible_param(params, 'feature_transform'): cmd.append('--feature_transform') cmd.extend( generate_fusible_param_flags( params, ['lr',", "forwarded to the subprocess call Returns: result(s): A single result", "if isinstance( ids, (list, tuple), ) else str(ids)) # Allocate", "HFTA). epochs: number of epochs to run. params: maps hyperparameter", "or a list of bools for HFTA in the same", "(5, 10, 20, 40)), } nonfusibles = { 'batch_size': hp.choice('batch_size',", "epochs=None, iters_per_epoch=None, env_vars=None, ): params = [{ **handle_integers(sample(fusibles, rng=rng_state)), **nonfusibles_kvs", "succeeded = True try: logging.info('--> Running cmd = {}'.format(cmd)) subprocess.run(", ") if not succeeded: raise RuntimeError('_run failed!') # Gather the", "_run(results_dir, epochs, iters_per_epoch, params, env_vars=None): # Build the cmd. cmd", "[{'acc': acc} for acc in results_frame['acc'].tolist()] assert len(results) == len(ids)", "'hfta': cmd.append('--hfta') if args.amp: cmd.append('--amp') # Launch the training process.", "list of IDs (for HFTA). epochs: number of epochs to", "env_vars=env_vars) tune_hyperparameters( space={ **fusibles, **nonfusibles }, try_params_callback=try_params, dry_run_callback=dry_run, mode=args.mode, algorithm=args.algorithm,", "np.random.seed(args.seed) rng_state = np.random.RandomState(seed=args.seed) fusibles = { 'lr': hp.uniform('lr', 0.0001,", "else: params = params[0] return _run(None, epochs, iters_per_epoch, params, env_vars=env_vars)", "metric='acc', goal='max', algorithm_configs={ 'hyperband': args.hyperband_kwargs, 'random': args.random_kwargs, }, seed=args.seed, outdir=args.outdir,", "'hyperband': args.hyperband_kwargs, 'random': args.random_kwargs, }, seed=args.seed, outdir=args.outdir, ) def attach_args(parser=argparse.ArgumentParser()):", "of epochs to train for', ) parser.add_argument('--dataset', type=str, required=True, help=\"dataset", "main(args): random.seed(args.seed) np.random.seed(args.seed) rng_state = np.random.RandomState(seed=args.seed) fusibles = { 'lr':", "environment that needs to be forwarded to the subprocess call", "random.seed(args.seed) np.random.seed(args.seed) rng_state = np.random.RandomState(seed=args.seed) fusibles = { 'lr': hp.uniform('lr',", "results = [{'acc': acc} for acc in results_frame['acc'].tolist()] assert len(results)", "* len(ids) else: return {'acc': results_frame['acc'][0]}, False def dry_run( B=None,", "'feature_transform'): cmd.append('--feature_transform') cmd.extend( generate_fusible_param_flags( params, ['lr', 'beta1', 'beta2', 'weight_decay', 'gamma',", "parser = attach_common_args(parser) return parser if __name__ == '__main__': args", "'cuda', 'xla'], help=\"the device where this test is running\", )", "i in ids]) if isinstance( ids, (list, tuple), ) else", "dry_run_callback=dry_run, mode=args.mode, algorithm=args.algorithm, nonfusibles=nonfusibles.keys(), dry_run_repeats=args.dry_run_repeats, dry_run_epochs=args.dry_run_epochs, dry_run_iters_per_epoch=args.dry_run_iters_per_epoch, metric='acc', goal='max', algorithm_configs={", "cmd.extend( generate_fusible_param_flags( params, ['lr', 'beta1', 'beta2', 'weight_decay', 'gamma', 'step_size'], ))", "'stdout.txt'), 'w', ), stderr=subprocess.DEVNULL if results_dir is None else open(", "def try_params(ids, epochs, params, env_vars=None): \"\"\" Running the training process", "in the same order as ids. early_stop(s): Whether the training", "args.iters_per_epoch, params, env_vars=env_vars, ) if not succeeded: raise RuntimeError('_run failed!')", "as np import os import pandas as pd import random", "results. results_frame = pd.read_csv(os.path.join(results_dir, 'eval.csv')) if isinstance(ids, (list, tuple)): results", "import hp from hyperopt.pyll.stochastic import sample from hfta.hfht import (tune_hyperparameters,", "epochs, iters_per_epoch, params, env_vars=None): # Build the cmd. cmd =", "type=str, required=True, help=\"dataset path\") parser.add_argument( '--dataset-type', type=str, default='shapenet', help=\"dataset type", "result dicts for HFTA in the same order as ids.", "serial or a list of bools for HFTA in the", "that includes extra environment that needs to be forwarded to", "process early stopped. A single bool for serial or a", "> 0: params = fuse_dicts(params) else: params = params[0] return", "test is running\", ) parser.add_argument( '--amp', default=False, action='store_true', help='Enable AMP;", "cmd.append('--amp') # Launch the training process. succeeded = True try:", "tune_hyperparameters( space={ **fusibles, **nonfusibles }, try_params_callback=try_params, dry_run_callback=dry_run, mode=args.mode, algorithm=args.algorithm, nonfusibles=nonfusibles.keys(),", "is running\", ) parser.add_argument( '--amp', default=False, action='store_true', help='Enable AMP; only", "training. succeeded = _run( results_dir, epochs, args.iters_per_epoch, params, env_vars=env_vars, )", "args.dataset, '--dataset_type', args.dataset_type, '--num_points', str(args.num_points), '--device', args.device, '--eval', '--seed', str(args.seed),", "None else open( os.path.join(results_dir, 'stdout.txt'), 'w', ), stderr=subprocess.DEVNULL if results_dir", "HFTA, the values are provided as a list. env_vars: optional,", "results_frame = pd.read_csv(os.path.join(results_dir, 'eval.csv')) if isinstance(ids, (list, tuple)): results =", "to run. params: maps hyperparameter name to its value(s). For", "parser.add_argument( '--amp', default=False, action='store_true', help='Enable AMP; only used when --device", "from hfta.workflow import extract_logging_level from hfta.hfht.utils import fuse_dicts def main(args):", "generate_nonfusible_param) from hfta.workflow import extract_logging_level from hfta.hfht.utils import fuse_dicts def", "import pandas as pd import random import subprocess from pathlib", "Either a single int ID (for serial), or a list", "e: logging.error(e) succeeded = False return succeeded def try_params(ids, epochs,", ") parser.add_argument( '--num-points', type=int, default=2500, help='num of points for dataset',", "cmd = {}'.format(cmd)) subprocess.run( cmd, stdout=subprocess.DEVNULL if results_dir is None", "range(max(B, 1))] if B > 0: params = fuse_dicts(params) else:", "for dataset', ) parser.add_argument( '--device', type=str, default='cuda', choices=['cpu', 'cuda', 'xla'],", "mode=args.mode, algorithm=args.algorithm, nonfusibles=nonfusibles.keys(), dry_run_repeats=args.dry_run_repeats, dry_run_epochs=args.dry_run_epochs, dry_run_iters_per_epoch=args.dry_run_iters_per_epoch, metric='acc', goal='max', algorithm_configs={ 'hyperband':", "hfta.hfht.utils import fuse_dicts def main(args): random.seed(args.seed) np.random.seed(args.seed) rng_state = np.random.RandomState(seed=args.seed)", "if args.amp: cmd.append('--amp') # Launch the training process. succeeded =", "0.001, 0.999), 'beta2': hp.uniform('beta2', 0.001, 0.999), 'weight_decay': hp.uniform('weight_decay', 0.0, 0.5),", "in ids]) if isinstance( ids, (list, tuple), ) else str(ids))", "logging.error(e) succeeded = False return succeeded def try_params(ids, epochs, params,", "if results_dir is None else open( os.path.join(results_dir, 'stderr.txt'), 'w', ),", "epochs, params, env_vars=None): \"\"\" Running the training process for pointnet", "in results_frame['acc'].tolist()] assert len(results) == len(ids) return results, [False] *", "help='number of epochs to train for', ) parser.add_argument('--dataset', type=str, required=True,", "16, 32)), 'feature_transform': hp.choice('feature_transform', (True, False)), } def _run(results_dir, epochs,", "B > 0: params = fuse_dicts(params) else: params = params[0]", "rng_state = np.random.RandomState(seed=args.seed) fusibles = { 'lr': hp.uniform('lr', 0.0001, 0.01),", "Returns: result(s): A single result dict for serial or a", "to be forwarded to the subprocess call Returns: result(s): A", "algorithm_configs={ 'hyperband': args.hyperband_kwargs, 'random': args.random_kwargs, }, seed=args.seed, outdir=args.outdir, ) def", "'beta1', 'beta2', 'weight_decay', 'gamma', 'step_size'], )) if args.mode == 'hfta':", "return parser if __name__ == '__main__': args = attach_args().parse_args() rearrange_algorithm_kwargs(args)", "**nonfusibles_kvs } for _ in range(max(B, 1))] if B >", "env=env_vars, ) except subprocess.CalledProcessError as e: logging.error(e) succeeded = False", "or a list of IDs (for HFTA). epochs: number of", "as pd import random import subprocess from pathlib import Path", "'w', ), stderr=subprocess.DEVNULL if results_dir is None else open( os.path.join(results_dir,", "_run( results_dir, epochs, args.iters_per_epoch, params, env_vars=env_vars, ) if not succeeded:", "Path(results_dir).mkdir(parents=True, exist_ok=True) # Run training. succeeded = _run( results_dir, epochs,", "args.hyperband_kwargs, 'random': args.random_kwargs, }, seed=args.seed, outdir=args.outdir, ) def attach_args(parser=argparse.ArgumentParser()): parser.add_argument(", "'--dataset', args.dataset, '--dataset_type', args.dataset_type, '--num_points', str(args.num_points), '--device', args.device, '--eval', '--seed',", "attach_common_args, rearrange_algorithm_kwargs, handle_integers, generate_fusible_param_flags, generate_nonfusible_param) from hfta.workflow import extract_logging_level from", "ids_str = (','.join([str(i) for i in ids]) if isinstance( ids,", "classification task. Args: ids: Either a single int ID (for", "hfta.hfht import (tune_hyperparameters, attach_common_args, rearrange_algorithm_kwargs, handle_integers, generate_fusible_param_flags, generate_nonfusible_param) from hfta.workflow", "Gather the results. results_frame = pd.read_csv(os.path.join(results_dir, 'eval.csv')) if isinstance(ids, (list,", "results_dir = os.path.join(args.outdir, ids_str) Path(results_dir).mkdir(parents=True, exist_ok=True) # Run training. succeeded", "rng=rng_state)), **nonfusibles_kvs } for _ in range(max(B, 1))] if B", "os.path.join(args.outdir, ids_str) Path(results_dir).mkdir(parents=True, exist_ok=True) # Run training. succeeded = _run(", "results_dir, epochs, args.iters_per_epoch, params, env_vars=env_vars, ) if not succeeded: raise", "the same order as ids. early_stop(s): Whether the training process", "(for HFTA). epochs: number of epochs to run. params: maps", "os import pandas as pd import random import subprocess from", "return _run(None, epochs, iters_per_epoch, params, env_vars=env_vars) tune_hyperparameters( space={ **fusibles, **nonfusibles", "else str(ids)) # Allocate result dir. results_dir = os.path.join(args.outdir, ids_str)", "succeeded def try_params(ids, epochs, params, env_vars=None): \"\"\" Running the training", ") parser.add_argument( '--iters-per-epoch', type=int, default=int(1e9), help='number of epochs to train", "= os.path.join(args.outdir, ids_str) Path(results_dir).mkdir(parents=True, exist_ok=True) # Run training. succeeded =", "int ID (for serial), or a list of IDs (for", "not succeeded: raise RuntimeError('_run failed!') # Gather the results. results_frame", "that needs to be forwarded to the subprocess call Returns:", "True try: logging.info('--> Running cmd = {}'.format(cmd)) subprocess.run( cmd, stdout=subprocess.DEVNULL", "acc} for acc in results_frame['acc'].tolist()] assert len(results) == len(ids) return", "list of result dicts for HFTA in the same order", "for _ in range(max(B, 1))] if B > 0: params", "str(iters_per_epoch), '--dataset', args.dataset, '--dataset_type', args.dataset_type, '--num_points', str(args.num_points), '--device', args.device, '--eval',", "isinstance(ids, (list, tuple)): results = [{'acc': acc} for acc in", "['lr', 'beta1', 'beta2', 'weight_decay', 'gamma', 'step_size'], )) if args.mode ==", "outdir=args.outdir, ) def attach_args(parser=argparse.ArgumentParser()): parser.add_argument( '--workers', type=int, help='number of data", "if args.mode == 'hfta': cmd.append('--hfta') if args.amp: cmd.append('--amp') # Launch", "in range(max(B, 1))] if B > 0: params = fuse_dicts(params)", "len(ids) return results, [False] * len(ids) else: return {'acc': results_frame['acc'][0]},", "def _run(results_dir, epochs, iters_per_epoch, params, env_vars=None): # Build the cmd.", "params, ['lr', 'beta1', 'beta2', 'weight_decay', 'gamma', 'step_size'], )) if args.mode", "try_params(ids, epochs, params, env_vars=None): \"\"\" Running the training process for", "# Gather the results. results_frame = pd.read_csv(os.path.join(results_dir, 'eval.csv')) if isinstance(ids,", "== '__main__': args = attach_args().parse_args() rearrange_algorithm_kwargs(args) logging.basicConfig(level=extract_logging_level(args)) args.outdir = os.path.abspath(os.path.expanduser(args.outdir))", "'stderr.txt'), 'w', ), check=True, cwd=os.path.join( os.path.abspath(os.path.expanduser(os.path.dirname(__file__))), '../pointnet/'), env=env_vars, ) except", "nonfusibles = { 'batch_size': hp.choice('batch_size', (8, 16, 32)), 'feature_transform': hp.choice('feature_transform',", "return results, [False] * len(ids) else: return {'acc': results_frame['acc'][0]}, False", "dry_run_epochs=args.dry_run_epochs, dry_run_iters_per_epoch=args.dry_run_iters_per_epoch, metric='acc', goal='max', algorithm_configs={ 'hyperband': args.hyperband_kwargs, 'random': args.random_kwargs, },", "maps hyperparameter name to its value(s). For HFTA, the values", "sample from hfta.hfht import (tune_hyperparameters, attach_common_args, rearrange_algorithm_kwargs, handle_integers, generate_fusible_param_flags, generate_nonfusible_param)", "shapenet|modelnet40\", ) parser.add_argument( '--num-points', type=int, default=2500, help='num of points for", "as ids. \"\"\" epochs = int(round(epochs)) ids_str = (','.join([str(i) for", "} def _run(results_dir, epochs, iters_per_epoch, params, env_vars=None): # Build the", "'random': args.random_kwargs, }, seed=args.seed, outdir=args.outdir, ) def attach_args(parser=argparse.ArgumentParser()): parser.add_argument( '--workers',", "'w', ), check=True, cwd=os.path.join( os.path.abspath(os.path.expanduser(os.path.dirname(__file__))), '../pointnet/'), env=env_vars, ) except subprocess.CalledProcessError", "generate_nonfusible_param(params, 'feature_transform'): cmd.append('--feature_transform') cmd.extend( generate_fusible_param_flags( params, ['lr', 'beta1', 'beta2', 'weight_decay',", "for', ) parser.add_argument('--dataset', type=str, required=True, help=\"dataset path\") parser.add_argument( '--dataset-type', type=str,", "params = fuse_dicts(params) else: params = params[0] return _run(None, epochs,", "iters_per_epoch=None, env_vars=None, ): params = [{ **handle_integers(sample(fusibles, rng=rng_state)), **nonfusibles_kvs }", "0.9), 'step_size': hp.choice('step_size', (5, 10, 20, 40)), } nonfusibles =", "are provided as a list. env_vars: optional, dict(str, str) that", "hyperparameter name to its value(s). For HFTA, the values are", "np import os import pandas as pd import random import", "when --device is cuda', ) parser = attach_common_args(parser) return parser", "as e: logging.error(e) succeeded = False return succeeded def try_params(ids,", "[False] * len(ids) else: return {'acc': results_frame['acc'][0]}, False def dry_run(", "default='shapenet', help=\"dataset type shapenet|modelnet40\", ) parser.add_argument( '--num-points', type=int, default=2500, help='num", "0.0001, 0.01), 'beta1': hp.uniform('beta1', 0.001, 0.999), 'beta2': hp.uniform('beta2', 0.001, 0.999),", "'gamma': hp.uniform('gamma', 0.1, 0.9), 'step_size': hp.choice('step_size', (5, 10, 20, 40)),", "is cuda', ) parser = attach_common_args(parser) return parser if __name__", "= np.random.RandomState(seed=args.seed) fusibles = { 'lr': hp.uniform('lr', 0.0001, 0.01), 'beta1':", "args.random_kwargs, }, seed=args.seed, outdir=args.outdir, ) def attach_args(parser=argparse.ArgumentParser()): parser.add_argument( '--workers', type=int,", "points for dataset', ) parser.add_argument( '--device', type=str, default='cuda', choices=['cpu', 'cuda',", "= { 'lr': hp.uniform('lr', 0.0001, 0.01), 'beta1': hp.uniform('beta1', 0.001, 0.999),", "hyperopt.pyll.stochastic import sample from hfta.hfht import (tune_hyperparameters, attach_common_args, rearrange_algorithm_kwargs, handle_integers,", "os.path.abspath(os.path.expanduser(os.path.dirname(__file__))), '../pointnet/'), env=env_vars, ) except subprocess.CalledProcessError as e: logging.error(e) succeeded", "succeeded = _run( results_dir, epochs, args.iters_per_epoch, params, env_vars=env_vars, ) if", "fuse_dicts(params) else: params = params[0] return _run(None, epochs, iters_per_epoch, params,", "'xla'], help=\"the device where this test is running\", ) parser.add_argument(", "for i in ids]) if isinstance( ids, (list, tuple), )", "stdout=subprocess.DEVNULL if results_dir is None else open( os.path.join(results_dir, 'stdout.txt'), 'w',", "dict(str, str) that includes extra environment that needs to be", "0.5), 'gamma': hp.uniform('gamma', 0.1, 0.9), 'step_size': hp.choice('step_size', (5, 10, 20,", "== 'hfta': cmd.append('--hfta') if args.amp: cmd.append('--amp') # Launch the training", "from hfta.hfht import (tune_hyperparameters, attach_common_args, rearrange_algorithm_kwargs, handle_integers, generate_fusible_param_flags, generate_nonfusible_param) from", "action='store_true', help='Enable AMP; only used when --device is cuda', )", "= [ 'python', 'train_classification.py', '--epochs', str(epochs), '--iters-per-epoch', str(iters_per_epoch), '--dataset', args.dataset,", "seed=args.seed, outdir=args.outdir, ) def attach_args(parser=argparse.ArgumentParser()): parser.add_argument( '--workers', type=int, help='number of", "results_dir is None else open( os.path.join(results_dir, 'stderr.txt'), 'w', ), check=True,", "Args: ids: Either a single int ID (for serial), or", "from hyperopt.pyll.stochastic import sample from hfta.hfht import (tune_hyperparameters, attach_common_args, rearrange_algorithm_kwargs,", "'--batch_size', str(generate_nonfusible_param(params, 'batch_size')), ] if results_dir is not None: cmd.extend(['--outf',", "process for pointnet classification task. Args: ids: Either a single", "single result dict for serial or a list of result", "attach_common_args(parser) return parser if __name__ == '__main__': args = attach_args().parse_args()", "tuple), ) else str(ids)) # Allocate result dir. results_dir =", "env_vars=None, ): params = [{ **handle_integers(sample(fusibles, rng=rng_state)), **nonfusibles_kvs } for", "dry_run( B=None, nonfusibles_kvs=None, epochs=None, iters_per_epoch=None, env_vars=None, ): params = [{", "str(ids)) # Allocate result dir. results_dir = os.path.join(args.outdir, ids_str) Path(results_dir).mkdir(parents=True,", "def attach_args(parser=argparse.ArgumentParser()): parser.add_argument( '--workers', type=int, help='number of data loading workers',", "IDs (for HFTA). epochs: number of epochs to run. params:", "= {}'.format(cmd)) subprocess.run( cmd, stdout=subprocess.DEVNULL if results_dir is None else", "args = attach_args().parse_args() rearrange_algorithm_kwargs(args) logging.basicConfig(level=extract_logging_level(args)) args.outdir = os.path.abspath(os.path.expanduser(args.outdir)) args.dataset =", "str) that includes extra environment that needs to be forwarded", "import Path from hyperopt import hp from hyperopt.pyll.stochastic import sample", "random import subprocess from pathlib import Path from hyperopt import", "try_params_callback=try_params, dry_run_callback=dry_run, mode=args.mode, algorithm=args.algorithm, nonfusibles=nonfusibles.keys(), dry_run_repeats=args.dry_run_repeats, dry_run_epochs=args.dry_run_epochs, dry_run_iters_per_epoch=args.dry_run_iters_per_epoch, metric='acc', goal='max',", "else open( os.path.join(results_dir, 'stdout.txt'), 'w', ), stderr=subprocess.DEVNULL if results_dir is", "check=True, cwd=os.path.join( os.path.abspath(os.path.expanduser(os.path.dirname(__file__))), '../pointnet/'), env=env_vars, ) except subprocess.CalledProcessError as e:", "params[0] return _run(None, epochs, iters_per_epoch, params, env_vars=env_vars) tune_hyperparameters( space={ **fusibles,", "hfta.workflow import extract_logging_level from hfta.hfht.utils import fuse_dicts def main(args): random.seed(args.seed)", "Allocate result dir. results_dir = os.path.join(args.outdir, ids_str) Path(results_dir).mkdir(parents=True, exist_ok=True) #", "rearrange_algorithm_kwargs, handle_integers, generate_fusible_param_flags, generate_nonfusible_param) from hfta.workflow import extract_logging_level from hfta.hfht.utils", "__name__ == '__main__': args = attach_args().parse_args() rearrange_algorithm_kwargs(args) logging.basicConfig(level=extract_logging_level(args)) args.outdir =", "handle_integers, generate_fusible_param_flags, generate_nonfusible_param) from hfta.workflow import extract_logging_level from hfta.hfht.utils import", "training process early stopped. A single bool for serial or", "process. succeeded = True try: logging.info('--> Running cmd = {}'.format(cmd))", "is None else open( os.path.join(results_dir, 'stderr.txt'), 'w', ), check=True, cwd=os.path.join(", "import sample from hfta.hfht import (tune_hyperparameters, attach_common_args, rearrange_algorithm_kwargs, handle_integers, generate_fusible_param_flags,", "the subprocess call Returns: result(s): A single result dict for", "else: return {'acc': results_frame['acc'][0]}, False def dry_run( B=None, nonfusibles_kvs=None, epochs=None,", "if generate_nonfusible_param(params, 'feature_transform'): cmd.append('--feature_transform') cmd.extend( generate_fusible_param_flags( params, ['lr', 'beta1', 'beta2',", "type=str, default='shapenet', help=\"dataset type shapenet|modelnet40\", ) parser.add_argument( '--num-points', type=int, default=2500,", "of IDs (for HFTA). epochs: number of epochs to run.", "from hfta.hfht.utils import fuse_dicts def main(args): random.seed(args.seed) np.random.seed(args.seed) rng_state =", "hp.choice('batch_size', (8, 16, 32)), 'feature_transform': hp.choice('feature_transform', (True, False)), } def", "results_dir]) if generate_nonfusible_param(params, 'feature_transform'): cmd.append('--feature_transform') cmd.extend( generate_fusible_param_flags( params, ['lr', 'beta1',", "None else open( os.path.join(results_dir, 'stderr.txt'), 'w', ), check=True, cwd=os.path.join( os.path.abspath(os.path.expanduser(os.path.dirname(__file__))),", "early stopped. A single bool for serial or a list", "): params = [{ **handle_integers(sample(fusibles, rng=rng_state)), **nonfusibles_kvs } for _", "A single bool for serial or a list of bools", "training process. succeeded = True try: logging.info('--> Running cmd =", "'--eval', '--seed', str(args.seed), '--batch_size', str(generate_nonfusible_param(params, 'batch_size')), ] if results_dir is", "subprocess.run( cmd, stdout=subprocess.DEVNULL if results_dir is None else open( os.path.join(results_dir,", "), check=True, cwd=os.path.join( os.path.abspath(os.path.expanduser(os.path.dirname(__file__))), '../pointnet/'), env=env_vars, ) except subprocess.CalledProcessError as", "'--device', type=str, default='cuda', choices=['cpu', 'cuda', 'xla'], help=\"the device where this", "epochs, iters_per_epoch, params, env_vars=env_vars) tune_hyperparameters( space={ **fusibles, **nonfusibles }, try_params_callback=try_params,", "help=\"the device where this test is running\", ) parser.add_argument( '--amp',", "args.device, '--eval', '--seed', str(args.seed), '--batch_size', str(generate_nonfusible_param(params, 'batch_size')), ] if results_dir", "help='number of data loading workers', default=4, ) parser.add_argument( '--iters-per-epoch', type=int,", "False)), } def _run(results_dir, epochs, iters_per_epoch, params, env_vars=None): # Build", "str(epochs), '--iters-per-epoch', str(iters_per_epoch), '--dataset', args.dataset, '--dataset_type', args.dataset_type, '--num_points', str(args.num_points), '--device',", "pathlib import Path from hyperopt import hp from hyperopt.pyll.stochastic import", "from hyperopt import hp from hyperopt.pyll.stochastic import sample from hfta.hfht", "task. Args: ids: Either a single int ID (for serial),", "to its value(s). For HFTA, the values are provided as", "call Returns: result(s): A single result dict for serial or", "data loading workers', default=4, ) parser.add_argument( '--iters-per-epoch', type=int, default=int(1e9), help='number", "logging import numpy as np import os import pandas as", "numpy as np import os import pandas as pd import", "logging.info('--> Running cmd = {}'.format(cmd)) subprocess.run( cmd, stdout=subprocess.DEVNULL if results_dir", "includes extra environment that needs to be forwarded to the", "import random import subprocess from pathlib import Path from hyperopt", "except subprocess.CalledProcessError as e: logging.error(e) succeeded = False return succeeded", "params, env_vars=None): \"\"\" Running the training process for pointnet classification", "'__main__': args = attach_args().parse_args() rearrange_algorithm_kwargs(args) logging.basicConfig(level=extract_logging_level(args)) args.outdir = os.path.abspath(os.path.expanduser(args.outdir)) args.dataset", "os.path.join(results_dir, 'stderr.txt'), 'w', ), check=True, cwd=os.path.join( os.path.abspath(os.path.expanduser(os.path.dirname(__file__))), '../pointnet/'), env=env_vars, )", "failed!') # Gather the results. results_frame = pd.read_csv(os.path.join(results_dir, 'eval.csv')) if", "40)), } nonfusibles = { 'batch_size': hp.choice('batch_size', (8, 16, 32)),", "a list. env_vars: optional, dict(str, str) that includes extra environment", "'beta2', 'weight_decay', 'gamma', 'step_size'], )) if args.mode == 'hfta': cmd.append('--hfta')", "results, [False] * len(ids) else: return {'acc': results_frame['acc'][0]}, False def", "'--dataset-type', type=str, default='shapenet', help=\"dataset type shapenet|modelnet40\", ) parser.add_argument( '--num-points', type=int,", "params = [{ **handle_integers(sample(fusibles, rng=rng_state)), **nonfusibles_kvs } for _ in", "epochs = int(round(epochs)) ids_str = (','.join([str(i) for i in ids])", "extra environment that needs to be forwarded to the subprocess", "device where this test is running\", ) parser.add_argument( '--amp', default=False,", ") parser.add_argument( '--device', type=str, default='cuda', choices=['cpu', 'cuda', 'xla'], help=\"the device", ") else str(ids)) # Allocate result dir. results_dir = os.path.join(args.outdir,", "len(results) == len(ids) return results, [False] * len(ids) else: return", "Launch the training process. succeeded = True try: logging.info('--> Running", "Running cmd = {}'.format(cmd)) subprocess.run( cmd, stdout=subprocess.DEVNULL if results_dir is", "ids. \"\"\" epochs = int(round(epochs)) ids_str = (','.join([str(i) for i", "# Run training. succeeded = _run( results_dir, epochs, args.iters_per_epoch, params,", "<gh_stars>10-100 import argparse import logging import numpy as np import", "fuse_dicts def main(args): random.seed(args.seed) np.random.seed(args.seed) rng_state = np.random.RandomState(seed=args.seed) fusibles =", "(list, tuple)): results = [{'acc': acc} for acc in results_frame['acc'].tolist()]", "loading workers', default=4, ) parser.add_argument( '--iters-per-epoch', type=int, default=int(1e9), help='number of", "ids_str) Path(results_dir).mkdir(parents=True, exist_ok=True) # Run training. succeeded = _run( results_dir,", "extract_logging_level from hfta.hfht.utils import fuse_dicts def main(args): random.seed(args.seed) np.random.seed(args.seed) rng_state", "generate_fusible_param_flags, generate_nonfusible_param) from hfta.workflow import extract_logging_level from hfta.hfht.utils import fuse_dicts", "parser.add_argument( '--workers', type=int, help='number of data loading workers', default=4, )", "cmd. cmd = [ 'python', 'train_classification.py', '--epochs', str(epochs), '--iters-per-epoch', str(iters_per_epoch),", "where this test is running\", ) parser.add_argument( '--amp', default=False, action='store_true',", "AMP; only used when --device is cuda', ) parser =", "exist_ok=True) # Run training. succeeded = _run( results_dir, epochs, args.iters_per_epoch,", "subprocess call Returns: result(s): A single result dict for serial", "ids]) if isinstance( ids, (list, tuple), ) else str(ids)) #", "order as ids. \"\"\" epochs = int(round(epochs)) ids_str = (','.join([str(i)", "if isinstance(ids, (list, tuple)): results = [{'acc': acc} for acc", "if B > 0: params = fuse_dicts(params) else: params =", "this test is running\", ) parser.add_argument( '--amp', default=False, action='store_true', help='Enable", "str(args.seed), '--batch_size', str(generate_nonfusible_param(params, 'batch_size')), ] if results_dir is not None:", "str(generate_nonfusible_param(params, 'batch_size')), ] if results_dir is not None: cmd.extend(['--outf', results_dir])", "'beta2': hp.uniform('beta2', 0.001, 0.999), 'weight_decay': hp.uniform('weight_decay', 0.0, 0.5), 'gamma': hp.uniform('gamma',", "1))] if B > 0: params = fuse_dicts(params) else: params", "'step_size': hp.choice('step_size', (5, 10, 20, 40)), } nonfusibles = {", "HFTA in the same order as ids. early_stop(s): Whether the", "default=2500, help='num of points for dataset', ) parser.add_argument( '--device', type=str,", "subprocess.CalledProcessError as e: logging.error(e) succeeded = False return succeeded def", "help='num of points for dataset', ) parser.add_argument( '--device', type=str, default='cuda',", "Running the training process for pointnet classification task. Args: ids:", "dry_run_repeats=args.dry_run_repeats, dry_run_epochs=args.dry_run_epochs, dry_run_iters_per_epoch=args.dry_run_iters_per_epoch, metric='acc', goal='max', algorithm_configs={ 'hyperband': args.hyperband_kwargs, 'random': args.random_kwargs,", "{ 'lr': hp.uniform('lr', 0.0001, 0.01), 'beta1': hp.uniform('beta1', 0.001, 0.999), 'beta2':", "= _run( results_dir, epochs, args.iters_per_epoch, params, env_vars=env_vars, ) if not", "help='Enable AMP; only used when --device is cuda', ) parser", "dataset', ) parser.add_argument( '--device', type=str, default='cuda', choices=['cpu', 'cuda', 'xla'], help=\"the", "run. params: maps hyperparameter name to its value(s). For HFTA,", "pd.read_csv(os.path.join(results_dir, 'eval.csv')) if isinstance(ids, (list, tuple)): results = [{'acc': acc}", "of bools for HFTA in the same order as ids.", "== len(ids) return results, [False] * len(ids) else: return {'acc':", "0.01), 'beta1': hp.uniform('beta1', 0.001, 0.999), 'beta2': hp.uniform('beta2', 0.001, 0.999), 'weight_decay':", "type=int, default=2500, help='num of points for dataset', ) parser.add_argument( '--device',", "type=int, help='number of data loading workers', default=4, ) parser.add_argument( '--iters-per-epoch',", "single bool for serial or a list of bools for", "\"\"\" epochs = int(round(epochs)) ids_str = (','.join([str(i) for i in", "= attach_args().parse_args() rearrange_algorithm_kwargs(args) logging.basicConfig(level=extract_logging_level(args)) args.outdir = os.path.abspath(os.path.expanduser(args.outdir)) args.dataset = os.path.abspath(os.path.expanduser(args.dataset))", "of result dicts for HFTA in the same order as", "Path from hyperopt import hp from hyperopt.pyll.stochastic import sample from", "number of epochs to run. params: maps hyperparameter name to", "type shapenet|modelnet40\", ) parser.add_argument( '--num-points', type=int, default=2500, help='num of points", "stderr=subprocess.DEVNULL if results_dir is None else open( os.path.join(results_dir, 'stderr.txt'), 'w',", "= params[0] return _run(None, epochs, iters_per_epoch, params, env_vars=env_vars) tune_hyperparameters( space={", "'train_classification.py', '--epochs', str(epochs), '--iters-per-epoch', str(iters_per_epoch), '--dataset', args.dataset, '--dataset_type', args.dataset_type, '--num_points',", "parser.add_argument( '--iters-per-epoch', type=int, default=int(1e9), help='number of epochs to train for',", "'batch_size')), ] if results_dir is not None: cmd.extend(['--outf', results_dir]) if", "hp.uniform('lr', 0.0001, 0.01), 'beta1': hp.uniform('beta1', 0.001, 0.999), 'beta2': hp.uniform('beta2', 0.001,", "result(s): A single result dict for serial or a list", "default=int(1e9), help='number of epochs to train for', ) parser.add_argument('--dataset', type=str,", "(True, False)), } def _run(results_dir, epochs, iters_per_epoch, params, env_vars=None): #", "= pd.read_csv(os.path.join(results_dir, 'eval.csv')) if isinstance(ids, (list, tuple)): results = [{'acc':", "[ 'python', 'train_classification.py', '--epochs', str(epochs), '--iters-per-epoch', str(iters_per_epoch), '--dataset', args.dataset, '--dataset_type',", "if results_dir is None else open( os.path.join(results_dir, 'stdout.txt'), 'w', ),", "ID (for serial), or a list of IDs (for HFTA).", "try: logging.info('--> Running cmd = {}'.format(cmd)) subprocess.run( cmd, stdout=subprocess.DEVNULL if", "only used when --device is cuda', ) parser = attach_common_args(parser)", "pd import random import subprocess from pathlib import Path from", "iters_per_epoch, params, env_vars=None): # Build the cmd. cmd = [", "env_vars=None): \"\"\" Running the training process for pointnet classification task.", "if results_dir is not None: cmd.extend(['--outf', results_dir]) if generate_nonfusible_param(params, 'feature_transform'):", "a list of bools for HFTA in the same order", "used when --device is cuda', ) parser = attach_common_args(parser) return", "serial), or a list of IDs (for HFTA). epochs: number", "hp from hyperopt.pyll.stochastic import sample from hfta.hfht import (tune_hyperparameters, attach_common_args,", "params, env_vars=env_vars, ) if not succeeded: raise RuntimeError('_run failed!') #", "HFTA in the same order as ids. \"\"\" epochs =", "to train for', ) parser.add_argument('--dataset', type=str, required=True, help=\"dataset path\") parser.add_argument(", "help=\"dataset type shapenet|modelnet40\", ) parser.add_argument( '--num-points', type=int, default=2500, help='num of", "order as ids. early_stop(s): Whether the training process early stopped.", "raise RuntimeError('_run failed!') # Gather the results. results_frame = pd.read_csv(os.path.join(results_dir,", "cmd.append('--hfta') if args.amp: cmd.append('--amp') # Launch the training process. succeeded", "value(s). For HFTA, the values are provided as a list.", "hp.uniform('beta2', 0.001, 0.999), 'weight_decay': hp.uniform('weight_decay', 0.0, 0.5), 'gamma': hp.uniform('gamma', 0.1,", "workers', default=4, ) parser.add_argument( '--iters-per-epoch', type=int, default=int(1e9), help='number of epochs", "pointnet classification task. Args: ids: Either a single int ID", "open( os.path.join(results_dir, 'stderr.txt'), 'w', ), check=True, cwd=os.path.join( os.path.abspath(os.path.expanduser(os.path.dirname(__file__))), '../pointnet/'), env=env_vars,", "int(round(epochs)) ids_str = (','.join([str(i) for i in ids]) if isinstance(", "Whether the training process early stopped. A single bool for", "_run(None, epochs, iters_per_epoch, params, env_vars=env_vars) tune_hyperparameters( space={ **fusibles, **nonfusibles },", "as a list. env_vars: optional, dict(str, str) that includes extra", "as ids. early_stop(s): Whether the training process early stopped. A", "for serial or a list of bools for HFTA in", "params, env_vars=env_vars) tune_hyperparameters( space={ **fusibles, **nonfusibles }, try_params_callback=try_params, dry_run_callback=dry_run, mode=args.mode,", "'--dataset_type', args.dataset_type, '--num_points', str(args.num_points), '--device', args.device, '--eval', '--seed', str(args.seed), '--batch_size',", "\"\"\" Running the training process for pointnet classification task. Args:", "] if results_dir is not None: cmd.extend(['--outf', results_dir]) if generate_nonfusible_param(params,", "params = params[0] return _run(None, epochs, iters_per_epoch, params, env_vars=env_vars) tune_hyperparameters(", "'gamma', 'step_size'], )) if args.mode == 'hfta': cmd.append('--hfta') if args.amp:", "list. env_vars: optional, dict(str, str) that includes extra environment that", "= fuse_dicts(params) else: params = params[0] return _run(None, epochs, iters_per_epoch,", "'--num-points', type=int, default=2500, help='num of points for dataset', ) parser.add_argument(", "parser.add_argument('--dataset', type=str, required=True, help=\"dataset path\") parser.add_argument( '--dataset-type', type=str, default='shapenet', help=\"dataset", "dry_run_iters_per_epoch=args.dry_run_iters_per_epoch, metric='acc', goal='max', algorithm_configs={ 'hyperband': args.hyperband_kwargs, 'random': args.random_kwargs, }, seed=args.seed,", "{'acc': results_frame['acc'][0]}, False def dry_run( B=None, nonfusibles_kvs=None, epochs=None, iters_per_epoch=None, env_vars=None,", "env_vars: optional, dict(str, str) that includes extra environment that needs", "'--iters-per-epoch', type=int, default=int(1e9), help='number of epochs to train for', )", "is not None: cmd.extend(['--outf', results_dir]) if generate_nonfusible_param(params, 'feature_transform'): cmd.append('--feature_transform') cmd.extend(", "the training process early stopped. A single bool for serial", "the same order as ids. \"\"\" epochs = int(round(epochs)) ids_str", "succeeded: raise RuntimeError('_run failed!') # Gather the results. results_frame =", "= True try: logging.info('--> Running cmd = {}'.format(cmd)) subprocess.run( cmd,", "generate_fusible_param_flags( params, ['lr', 'beta1', 'beta2', 'weight_decay', 'gamma', 'step_size'], )) if", "# Build the cmd. cmd = [ 'python', 'train_classification.py', '--epochs',", "not None: cmd.extend(['--outf', results_dir]) if generate_nonfusible_param(params, 'feature_transform'): cmd.append('--feature_transform') cmd.extend( generate_fusible_param_flags(", "cwd=os.path.join( os.path.abspath(os.path.expanduser(os.path.dirname(__file__))), '../pointnet/'), env=env_vars, ) except subprocess.CalledProcessError as e: logging.error(e)", "# Allocate result dir. results_dir = os.path.join(args.outdir, ids_str) Path(results_dir).mkdir(parents=True, exist_ok=True)", "Build the cmd. cmd = [ 'python', 'train_classification.py', '--epochs', str(epochs),", "import extract_logging_level from hfta.hfht.utils import fuse_dicts def main(args): random.seed(args.seed) np.random.seed(args.seed)", "for pointnet classification task. Args: ids: Either a single int", "parser.add_argument( '--num-points', type=int, default=2500, help='num of points for dataset', )", "running\", ) parser.add_argument( '--amp', default=False, action='store_true', help='Enable AMP; only used", "provided as a list. env_vars: optional, dict(str, str) that includes", "_ in range(max(B, 1))] if B > 0: params =", "cuda', ) parser = attach_common_args(parser) return parser if __name__ ==", "algorithm=args.algorithm, nonfusibles=nonfusibles.keys(), dry_run_repeats=args.dry_run_repeats, dry_run_epochs=args.dry_run_epochs, dry_run_iters_per_epoch=args.dry_run_iters_per_epoch, metric='acc', goal='max', algorithm_configs={ 'hyperband': args.hyperband_kwargs,", "[{ **handle_integers(sample(fusibles, rng=rng_state)), **nonfusibles_kvs } for _ in range(max(B, 1))]", "pandas as pd import random import subprocess from pathlib import", "bools for HFTA in the same order as ids. \"\"\"", "'lr': hp.uniform('lr', 0.0001, 0.01), 'beta1': hp.uniform('beta1', 0.001, 0.999), 'beta2': hp.uniform('beta2',", "} nonfusibles = { 'batch_size': hp.choice('batch_size', (8, 16, 32)), 'feature_transform':", "fusibles = { 'lr': hp.uniform('lr', 0.0001, 0.01), 'beta1': hp.uniform('beta1', 0.001,", "cmd = [ 'python', 'train_classification.py', '--epochs', str(epochs), '--iters-per-epoch', str(iters_per_epoch), '--dataset',", "import fuse_dicts def main(args): random.seed(args.seed) np.random.seed(args.seed) rng_state = np.random.RandomState(seed=args.seed) fusibles", "results_dir is None else open( os.path.join(results_dir, 'stdout.txt'), 'w', ), stderr=subprocess.DEVNULL", "epochs: number of epochs to run. params: maps hyperparameter name", "'--amp', default=False, action='store_true', help='Enable AMP; only used when --device is", "for HFTA in the same order as ids. early_stop(s): Whether", "0.999), 'beta2': hp.uniform('beta2', 0.001, 0.999), 'weight_decay': hp.uniform('weight_decay', 0.0, 0.5), 'gamma':", "RuntimeError('_run failed!') # Gather the results. results_frame = pd.read_csv(os.path.join(results_dir, 'eval.csv'))", "iters_per_epoch, params, env_vars=env_vars) tune_hyperparameters( space={ **fusibles, **nonfusibles }, try_params_callback=try_params, dry_run_callback=dry_run,", "nonfusibles_kvs=None, epochs=None, iters_per_epoch=None, env_vars=None, ): params = [{ **handle_integers(sample(fusibles, rng=rng_state)),", "results_frame['acc'].tolist()] assert len(results) == len(ids) return results, [False] * len(ids)", "= (','.join([str(i) for i in ids]) if isinstance( ids, (list,", "nonfusibles=nonfusibles.keys(), dry_run_repeats=args.dry_run_repeats, dry_run_epochs=args.dry_run_epochs, dry_run_iters_per_epoch=args.dry_run_iters_per_epoch, metric='acc', goal='max', algorithm_configs={ 'hyperband': args.hyperband_kwargs, 'random':", "hp.uniform('gamma', 0.1, 0.9), 'step_size': hp.choice('step_size', (5, 10, 20, 40)), }", "same order as ids. early_stop(s): Whether the training process early", "cmd, stdout=subprocess.DEVNULL if results_dir is None else open( os.path.join(results_dir, 'stdout.txt'),", "type=int, default=int(1e9), help='number of epochs to train for', ) parser.add_argument('--dataset',", "{ 'batch_size': hp.choice('batch_size', (8, 16, 32)), 'feature_transform': hp.choice('feature_transform', (True, False)),", "'weight_decay': hp.uniform('weight_decay', 0.0, 0.5), 'gamma': hp.uniform('gamma', 0.1, 0.9), 'step_size': hp.choice('step_size',", "'--iters-per-epoch', str(iters_per_epoch), '--dataset', args.dataset, '--dataset_type', args.dataset_type, '--num_points', str(args.num_points), '--device', args.device,", "result dict for serial or a list of result dicts", "hp.choice('step_size', (5, 10, 20, 40)), } nonfusibles = { 'batch_size':", "'eval.csv')) if isinstance(ids, (list, tuple)): results = [{'acc': acc} for", "early_stop(s): Whether the training process early stopped. A single bool", "def dry_run( B=None, nonfusibles_kvs=None, epochs=None, iters_per_epoch=None, env_vars=None, ): params =", "**nonfusibles }, try_params_callback=try_params, dry_run_callback=dry_run, mode=args.mode, algorithm=args.algorithm, nonfusibles=nonfusibles.keys(), dry_run_repeats=args.dry_run_repeats, dry_run_epochs=args.dry_run_epochs, dry_run_iters_per_epoch=args.dry_run_iters_per_epoch,", "attach_args(parser=argparse.ArgumentParser()): parser.add_argument( '--workers', type=int, help='number of data loading workers', default=4,", "str(args.num_points), '--device', args.device, '--eval', '--seed', str(args.seed), '--batch_size', str(generate_nonfusible_param(params, 'batch_size')), ]", "ids: Either a single int ID (for serial), or a", "its value(s). For HFTA, the values are provided as a", "import numpy as np import os import pandas as pd", "'feature_transform': hp.choice('feature_transform', (True, False)), } def _run(results_dir, epochs, iters_per_epoch, params,", "'--num_points', str(args.num_points), '--device', args.device, '--eval', '--seed', str(args.seed), '--batch_size', str(generate_nonfusible_param(params, 'batch_size')),", "), stderr=subprocess.DEVNULL if results_dir is None else open( os.path.join(results_dir, 'stderr.txt'),", "ids. early_stop(s): Whether the training process early stopped. A single", "a list of IDs (for HFTA). epochs: number of epochs", "the values are provided as a list. env_vars: optional, dict(str,", "bool for serial or a list of bools for HFTA", "required=True, help=\"dataset path\") parser.add_argument( '--dataset-type', type=str, default='shapenet', help=\"dataset type shapenet|modelnet40\",", "for HFTA in the same order as ids. \"\"\" epochs", "of points for dataset', ) parser.add_argument( '--device', type=str, default='cuda', choices=['cpu',", "= False return succeeded def try_params(ids, epochs, params, env_vars=None): \"\"\"", "'--workers', type=int, help='number of data loading workers', default=4, ) parser.add_argument(", "is None else open( os.path.join(results_dir, 'stdout.txt'), 'w', ), stderr=subprocess.DEVNULL if", "epochs, args.iters_per_epoch, params, env_vars=env_vars, ) if not succeeded: raise RuntimeError('_run", "np.random.RandomState(seed=args.seed) fusibles = { 'lr': hp.uniform('lr', 0.0001, 0.01), 'beta1': hp.uniform('beta1',", "epochs to run. params: maps hyperparameter name to its value(s).", "space={ **fusibles, **nonfusibles }, try_params_callback=try_params, dry_run_callback=dry_run, mode=args.mode, algorithm=args.algorithm, nonfusibles=nonfusibles.keys(), dry_run_repeats=args.dry_run_repeats,", "succeeded = False return succeeded def try_params(ids, epochs, params, env_vars=None):", ") except subprocess.CalledProcessError as e: logging.error(e) succeeded = False return", "single int ID (for serial), or a list of IDs", "args.amp: cmd.append('--amp') # Launch the training process. succeeded = True", "dir. results_dir = os.path.join(args.outdir, ids_str) Path(results_dir).mkdir(parents=True, exist_ok=True) # Run training.", "default=4, ) parser.add_argument( '--iters-per-epoch', type=int, default=int(1e9), help='number of epochs to", "default='cuda', choices=['cpu', 'cuda', 'xla'], help=\"the device where this test is", "parser.add_argument( '--device', type=str, default='cuda', choices=['cpu', 'cuda', 'xla'], help=\"the device where", "if __name__ == '__main__': args = attach_args().parse_args() rearrange_algorithm_kwargs(args) logging.basicConfig(level=extract_logging_level(args)) args.outdir", "the training process for pointnet classification task. Args: ids: Either", "stopped. A single bool for serial or a list of", "'batch_size': hp.choice('batch_size', (8, 16, 32)), 'feature_transform': hp.choice('feature_transform', (True, False)), }", "= [{'acc': acc} for acc in results_frame['acc'].tolist()] assert len(results) ==", "ids, (list, tuple), ) else str(ids)) # Allocate result dir.", "10, 20, 40)), } nonfusibles = { 'batch_size': hp.choice('batch_size', (8,", "list of bools for HFTA in the same order as", "choices=['cpu', 'cuda', 'xla'], help=\"the device where this test is running\",", "hp.choice('feature_transform', (True, False)), } def _run(results_dir, epochs, iters_per_epoch, params, env_vars=None):", "'--epochs', str(epochs), '--iters-per-epoch', str(iters_per_epoch), '--dataset', args.dataset, '--dataset_type', args.dataset_type, '--num_points', str(args.num_points),", "a list of result dicts for HFTA in the same", "import argparse import logging import numpy as np import os", "len(ids) else: return {'acc': results_frame['acc'][0]}, False def dry_run( B=None, nonfusibles_kvs=None,", "= { 'batch_size': hp.choice('batch_size', (8, 16, 32)), 'feature_transform': hp.choice('feature_transform', (True,", "import logging import numpy as np import os import pandas", "For HFTA, the values are provided as a list. env_vars:", "args.dataset_type, '--num_points', str(args.num_points), '--device', args.device, '--eval', '--seed', str(args.seed), '--batch_size', str(generate_nonfusible_param(params,", "the results. results_frame = pd.read_csv(os.path.join(results_dir, 'eval.csv')) if isinstance(ids, (list, tuple)):", "import subprocess from pathlib import Path from hyperopt import hp", "return {'acc': results_frame['acc'][0]}, False def dry_run( B=None, nonfusibles_kvs=None, epochs=None, iters_per_epoch=None,", "to the subprocess call Returns: result(s): A single result dict", "B=None, nonfusibles_kvs=None, epochs=None, iters_per_epoch=None, env_vars=None, ): params = [{ **handle_integers(sample(fusibles,", "}, seed=args.seed, outdir=args.outdir, ) def attach_args(parser=argparse.ArgumentParser()): parser.add_argument( '--workers', type=int, help='number", "**fusibles, **nonfusibles }, try_params_callback=try_params, dry_run_callback=dry_run, mode=args.mode, algorithm=args.algorithm, nonfusibles=nonfusibles.keys(), dry_run_repeats=args.dry_run_repeats, dry_run_epochs=args.dry_run_epochs,", "def main(args): random.seed(args.seed) np.random.seed(args.seed) rng_state = np.random.RandomState(seed=args.seed) fusibles = {", "subprocess from pathlib import Path from hyperopt import hp from", ") parser = attach_common_args(parser) return parser if __name__ == '__main__':", "dicts for HFTA in the same order as ids. early_stop(s):", "name to its value(s). For HFTA, the values are provided", "}, try_params_callback=try_params, dry_run_callback=dry_run, mode=args.mode, algorithm=args.algorithm, nonfusibles=nonfusibles.keys(), dry_run_repeats=args.dry_run_repeats, dry_run_epochs=args.dry_run_epochs, dry_run_iters_per_epoch=args.dry_run_iters_per_epoch, metric='acc',", "attach_args().parse_args() rearrange_algorithm_kwargs(args) logging.basicConfig(level=extract_logging_level(args)) args.outdir = os.path.abspath(os.path.expanduser(args.outdir)) args.dataset = os.path.abspath(os.path.expanduser(args.dataset)) main(args)", "optional, dict(str, str) that includes extra environment that needs to", "epochs to train for', ) parser.add_argument('--dataset', type=str, required=True, help=\"dataset path\")", "acc in results_frame['acc'].tolist()] assert len(results) == len(ids) return results, [False]", "help=\"dataset path\") parser.add_argument( '--dataset-type', type=str, default='shapenet', help=\"dataset type shapenet|modelnet40\", )", "(8, 16, 32)), 'feature_transform': hp.choice('feature_transform', (True, False)), } def _run(results_dir,", "False return succeeded def try_params(ids, epochs, params, env_vars=None): \"\"\" Running", "cmd.append('--feature_transform') cmd.extend( generate_fusible_param_flags( params, ['lr', 'beta1', 'beta2', 'weight_decay', 'gamma', 'step_size'],", "hyperopt import hp from hyperopt.pyll.stochastic import sample from hfta.hfht import", "dict for serial or a list of result dicts for", ") parser.add_argument( '--amp', default=False, action='store_true', help='Enable AMP; only used when", ")) if args.mode == 'hfta': cmd.append('--hfta') if args.amp: cmd.append('--amp') #", "# Launch the training process. succeeded = True try: logging.info('-->", "for serial or a list of result dicts for HFTA", ") def attach_args(parser=argparse.ArgumentParser()): parser.add_argument( '--workers', type=int, help='number of data loading", "os.path.join(results_dir, 'stdout.txt'), 'w', ), stderr=subprocess.DEVNULL if results_dir is None else", "'--seed', str(args.seed), '--batch_size', str(generate_nonfusible_param(params, 'batch_size')), ] if results_dir is not", "parser if __name__ == '__main__': args = attach_args().parse_args() rearrange_algorithm_kwargs(args) logging.basicConfig(level=extract_logging_level(args))", "else open( os.path.join(results_dir, 'stderr.txt'), 'w', ), check=True, cwd=os.path.join( os.path.abspath(os.path.expanduser(os.path.dirname(__file__))), '../pointnet/'),", "result dir. results_dir = os.path.join(args.outdir, ids_str) Path(results_dir).mkdir(parents=True, exist_ok=True) # Run", "from pathlib import Path from hyperopt import hp from hyperopt.pyll.stochastic", "32)), 'feature_transform': hp.choice('feature_transform', (True, False)), } def _run(results_dir, epochs, iters_per_epoch,", "in the same order as ids. \"\"\" epochs = int(round(epochs))", "hp.uniform('beta1', 0.001, 0.999), 'beta2': hp.uniform('beta2', 0.001, 0.999), 'weight_decay': hp.uniform('weight_decay', 0.0,", "results_dir is not None: cmd.extend(['--outf', results_dir]) if generate_nonfusible_param(params, 'feature_transform'): cmd.append('--feature_transform')", "'../pointnet/'), env=env_vars, ) except subprocess.CalledProcessError as e: logging.error(e) succeeded =", "= int(round(epochs)) ids_str = (','.join([str(i) for i in ids]) if", "'beta1': hp.uniform('beta1', 0.001, 0.999), 'beta2': hp.uniform('beta2', 0.001, 0.999), 'weight_decay': hp.uniform('weight_decay',", "'weight_decay', 'gamma', 'step_size'], )) if args.mode == 'hfta': cmd.append('--hfta') if", "path\") parser.add_argument( '--dataset-type', type=str, default='shapenet', help=\"dataset type shapenet|modelnet40\", ) parser.add_argument(", "import (tune_hyperparameters, attach_common_args, rearrange_algorithm_kwargs, handle_integers, generate_fusible_param_flags, generate_nonfusible_param) from hfta.workflow import", "return succeeded def try_params(ids, epochs, params, env_vars=None): \"\"\" Running the", "results_frame['acc'][0]}, False def dry_run( B=None, nonfusibles_kvs=None, epochs=None, iters_per_epoch=None, env_vars=None, ):", "= [{ **handle_integers(sample(fusibles, rng=rng_state)), **nonfusibles_kvs } for _ in range(max(B,", "0.999), 'weight_decay': hp.uniform('weight_decay', 0.0, 0.5), 'gamma': hp.uniform('gamma', 0.1, 0.9), 'step_size':", "params, env_vars=None): # Build the cmd. cmd = [ 'python',", "= attach_common_args(parser) return parser if __name__ == '__main__': args =", "env_vars=None): # Build the cmd. cmd = [ 'python', 'train_classification.py',", "A single result dict for serial or a list of", "(for serial), or a list of IDs (for HFTA). epochs:", "(list, tuple), ) else str(ids)) # Allocate result dir. results_dir", "'--device', args.device, '--eval', '--seed', str(args.seed), '--batch_size', str(generate_nonfusible_param(params, 'batch_size')), ] if", "assert len(results) == len(ids) return results, [False] * len(ids) else:", "False def dry_run( B=None, nonfusibles_kvs=None, epochs=None, iters_per_epoch=None, env_vars=None, ): params", "open( os.path.join(results_dir, 'stdout.txt'), 'w', ), stderr=subprocess.DEVNULL if results_dir is None", "default=False, action='store_true', help='Enable AMP; only used when --device is cuda',", "'python', 'train_classification.py', '--epochs', str(epochs), '--iters-per-epoch', str(iters_per_epoch), '--dataset', args.dataset, '--dataset_type', args.dataset_type,", "hp.uniform('weight_decay', 0.0, 0.5), 'gamma': hp.uniform('gamma', 0.1, 0.9), 'step_size': hp.choice('step_size', (5,", "or a list of result dicts for HFTA in the", "be forwarded to the subprocess call Returns: result(s): A single" ]
[ "django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('trr',", "('trr', '0001_initial'), ] operations = [ migrations.AlterField( model_name='trr', name='subject_id', field=models.PositiveIntegerField(null=True),", "2018-03-06 04:00 from __future__ import unicode_literals from django.db import migrations,", "# -*- coding: utf-8 -*- # Generated by Django 1.11.4", "-*- coding: utf-8 -*- # Generated by Django 1.11.4 on", "class Migration(migrations.Migration): dependencies = [ ('trr', '0001_initial'), ] operations =", "by Django 1.11.4 on 2018-03-06 04:00 from __future__ import unicode_literals", "04:00 from __future__ import unicode_literals from django.db import migrations, models", "import migrations, models class Migration(migrations.Migration): dependencies = [ ('trr', '0001_initial'),", "-*- # Generated by Django 1.11.4 on 2018-03-06 04:00 from", "unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies =", "Migration(migrations.Migration): dependencies = [ ('trr', '0001_initial'), ] operations = [", "utf-8 -*- # Generated by Django 1.11.4 on 2018-03-06 04:00", "] operations = [ migrations.AlterField( model_name='trr', name='subject_id', field=models.PositiveIntegerField(null=True), ), ]", "models class Migration(migrations.Migration): dependencies = [ ('trr', '0001_initial'), ] operations", "from django.db import migrations, models class Migration(migrations.Migration): dependencies = [", "1.11.4 on 2018-03-06 04:00 from __future__ import unicode_literals from django.db", "coding: utf-8 -*- # Generated by Django 1.11.4 on 2018-03-06", "Django 1.11.4 on 2018-03-06 04:00 from __future__ import unicode_literals from", "migrations, models class Migration(migrations.Migration): dependencies = [ ('trr', '0001_initial'), ]", "on 2018-03-06 04:00 from __future__ import unicode_literals from django.db import", "'0001_initial'), ] operations = [ migrations.AlterField( model_name='trr', name='subject_id', field=models.PositiveIntegerField(null=True), ),", "import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies", "dependencies = [ ('trr', '0001_initial'), ] operations = [ migrations.AlterField(", "Generated by Django 1.11.4 on 2018-03-06 04:00 from __future__ import", "= [ ('trr', '0001_initial'), ] operations = [ migrations.AlterField( model_name='trr',", "__future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration):", "from __future__ import unicode_literals from django.db import migrations, models class", "[ ('trr', '0001_initial'), ] operations = [ migrations.AlterField( model_name='trr', name='subject_id',", "# Generated by Django 1.11.4 on 2018-03-06 04:00 from __future__" ]
[ "clean') output = TestRun.executor.run('pgrep iotrace') if output.stdout != \"\": TestRun.executor.run(f'kill", "TestRun.LOGGER.info(\"Removing existing traces\") trace_repository_path: str = iotrace.get_trace_repository_path() TestRun.executor.run_expect_success(f'rm -rf {trace_repository_path}/kernel')", "bool): if not check_if_installed() or reinstall: TestRun.LOGGER.info(\"Installing iotrace:\") install_iotrace() else:", "because we need iotrace # to get valid paths dut_cleanup()", "fio.is_installed(): TestRun.LOGGER.info(\"Installing fio\") fio.install() TestRun.LOGGER.info(\"Killing all IO\") kill_all_io() def dut_cleanup():", "import Fio def dut_prepare(reinstall: bool): if not check_if_installed() or reinstall:", "iotrace # to get valid paths dut_cleanup() fio = Fio()", "IO\") kill_all_io() def dut_cleanup(): iotrace: IotracePlugin = TestRun.plugins['iotrace'] TestRun.LOGGER.info(\"Stopping fuzzing\")", "get valid paths dut_cleanup() fio = Fio() if not fio.is_installed():", "def dut_cleanup(): iotrace: IotracePlugin = TestRun.plugins['iotrace'] TestRun.LOGGER.info(\"Stopping fuzzing\") TestRun.executor.run(f'{iotrace.working_dir}/standalone-linux-io-tracer/tests/security/fuzzy/fuzz.sh clean')", "SPDX-License-Identifier: BSD-3-Clause-Clear # from core.test_run_utils import TestRun from utils.installer import", "from core.test_run_utils import TestRun from utils.installer import install_iotrace, check_if_installed from", "install_iotrace, check_if_installed from utils.iotrace import IotracePlugin from utils.misc import kill_all_io", "output.stdout != \"\": TestRun.executor.run(f'kill -9 {output.stdout}') TestRun.LOGGER.info(\"Removing existing traces\") trace_repository_path:", "BSD-3-Clause-Clear # from core.test_run_utils import TestRun from utils.installer import install_iotrace,", "IotracePlugin from utils.misc import kill_all_io from test_tools.fio.fio import Fio def", "install_iotrace() else: TestRun.LOGGER.info(\"iotrace is already installed by previous test\") #", "# SPDX-License-Identifier: BSD-3-Clause-Clear # from core.test_run_utils import TestRun from utils.installer", "already installed by previous test\") # Call it after installing", "Fio() if not fio.is_installed(): TestRun.LOGGER.info(\"Installing fio\") fio.install() TestRun.LOGGER.info(\"Killing all IO\")", "TestRun.executor.run('pgrep iotrace') if output.stdout != \"\": TestRun.executor.run(f'kill -9 {output.stdout}') TestRun.LOGGER.info(\"Removing", "utils.installer import install_iotrace, check_if_installed from utils.iotrace import IotracePlugin from utils.misc", "is already installed by previous test\") # Call it after", "IotracePlugin = TestRun.plugins['iotrace'] TestRun.LOGGER.info(\"Stopping fuzzing\") TestRun.executor.run(f'{iotrace.working_dir}/standalone-linux-io-tracer/tests/security/fuzzy/fuzz.sh clean') output = TestRun.executor.run('pgrep", "= TestRun.plugins['iotrace'] TestRun.LOGGER.info(\"Stopping fuzzing\") TestRun.executor.run(f'{iotrace.working_dir}/standalone-linux-io-tracer/tests/security/fuzzy/fuzz.sh clean') output = TestRun.executor.run('pgrep iotrace')", "previous test\") # Call it after installing iotrace because we", "test\") # Call it after installing iotrace because we need", "# from core.test_run_utils import TestRun from utils.installer import install_iotrace, check_if_installed", "after installing iotrace because we need iotrace # to get", "TestRun.LOGGER.info(\"Installing fio\") fio.install() TestRun.LOGGER.info(\"Killing all IO\") kill_all_io() def dut_cleanup(): iotrace:", "it after installing iotrace because we need iotrace # to", "by previous test\") # Call it after installing iotrace because", "import kill_all_io from test_tools.fio.fio import Fio def dut_prepare(reinstall: bool): if", "fuzzing\") TestRun.executor.run(f'{iotrace.working_dir}/standalone-linux-io-tracer/tests/security/fuzzy/fuzz.sh clean') output = TestRun.executor.run('pgrep iotrace') if output.stdout !=", "# # Copyright(c) 2020 Intel Corporation # SPDX-License-Identifier: BSD-3-Clause-Clear #", "from utils.iotrace import IotracePlugin from utils.misc import kill_all_io from test_tools.fio.fio", "iotrace: IotracePlugin = TestRun.plugins['iotrace'] TestRun.LOGGER.info(\"Stopping fuzzing\") TestRun.executor.run(f'{iotrace.working_dir}/standalone-linux-io-tracer/tests/security/fuzzy/fuzz.sh clean') output =", "Fio def dut_prepare(reinstall: bool): if not check_if_installed() or reinstall: TestRun.LOGGER.info(\"Installing", "paths dut_cleanup() fio = Fio() if not fio.is_installed(): TestRun.LOGGER.info(\"Installing fio\")", "from utils.installer import install_iotrace, check_if_installed from utils.iotrace import IotracePlugin from", "kill_all_io() def dut_cleanup(): iotrace: IotracePlugin = TestRun.plugins['iotrace'] TestRun.LOGGER.info(\"Stopping fuzzing\") TestRun.executor.run(f'{iotrace.working_dir}/standalone-linux-io-tracer/tests/security/fuzzy/fuzz.sh", "= Fio() if not fio.is_installed(): TestRun.LOGGER.info(\"Installing fio\") fio.install() TestRun.LOGGER.info(\"Killing all", "fio.install() TestRun.LOGGER.info(\"Killing all IO\") kill_all_io() def dut_cleanup(): iotrace: IotracePlugin =", "to get valid paths dut_cleanup() fio = Fio() if not", "dut_cleanup() fio = Fio() if not fio.is_installed(): TestRun.LOGGER.info(\"Installing fio\") fio.install()", "if output.stdout != \"\": TestRun.executor.run(f'kill -9 {output.stdout}') TestRun.LOGGER.info(\"Removing existing traces\")", "iotrace:\") install_iotrace() else: TestRun.LOGGER.info(\"iotrace is already installed by previous test\")", "or reinstall: TestRun.LOGGER.info(\"Installing iotrace:\") install_iotrace() else: TestRun.LOGGER.info(\"iotrace is already installed", "we need iotrace # to get valid paths dut_cleanup() fio", "utils.misc import kill_all_io from test_tools.fio.fio import Fio def dut_prepare(reinstall: bool):", "test_tools.fio.fio import Fio def dut_prepare(reinstall: bool): if not check_if_installed() or", "check_if_installed() or reinstall: TestRun.LOGGER.info(\"Installing iotrace:\") install_iotrace() else: TestRun.LOGGER.info(\"iotrace is already", "TestRun.LOGGER.info(\"Installing iotrace:\") install_iotrace() else: TestRun.LOGGER.info(\"iotrace is already installed by previous", "if not fio.is_installed(): TestRun.LOGGER.info(\"Installing fio\") fio.install() TestRun.LOGGER.info(\"Killing all IO\") kill_all_io()", "-9 {output.stdout}') TestRun.LOGGER.info(\"Removing existing traces\") trace_repository_path: str = iotrace.get_trace_repository_path() TestRun.executor.run_expect_success(f'rm", "if not check_if_installed() or reinstall: TestRun.LOGGER.info(\"Installing iotrace:\") install_iotrace() else: TestRun.LOGGER.info(\"iotrace", "{output.stdout}') TestRun.LOGGER.info(\"Removing existing traces\") trace_repository_path: str = iotrace.get_trace_repository_path() TestRun.executor.run_expect_success(f'rm -rf", "# to get valid paths dut_cleanup() fio = Fio() if", "installed by previous test\") # Call it after installing iotrace", "from utils.misc import kill_all_io from test_tools.fio.fio import Fio def dut_prepare(reinstall:", "need iotrace # to get valid paths dut_cleanup() fio =", "fio\") fio.install() TestRun.LOGGER.info(\"Killing all IO\") kill_all_io() def dut_cleanup(): iotrace: IotracePlugin", "TestRun.LOGGER.info(\"Stopping fuzzing\") TestRun.executor.run(f'{iotrace.working_dir}/standalone-linux-io-tracer/tests/security/fuzzy/fuzz.sh clean') output = TestRun.executor.run('pgrep iotrace') if output.stdout", "TestRun.plugins['iotrace'] TestRun.LOGGER.info(\"Stopping fuzzing\") TestRun.executor.run(f'{iotrace.working_dir}/standalone-linux-io-tracer/tests/security/fuzzy/fuzz.sh clean') output = TestRun.executor.run('pgrep iotrace') if", "iotrace because we need iotrace # to get valid paths", "TestRun.LOGGER.info(\"Killing all IO\") kill_all_io() def dut_cleanup(): iotrace: IotracePlugin = TestRun.plugins['iotrace']", "reinstall: TestRun.LOGGER.info(\"Installing iotrace:\") install_iotrace() else: TestRun.LOGGER.info(\"iotrace is already installed by", "= TestRun.executor.run('pgrep iotrace') if output.stdout != \"\": TestRun.executor.run(f'kill -9 {output.stdout}')", "utils.iotrace import IotracePlugin from utils.misc import kill_all_io from test_tools.fio.fio import", "else: TestRun.LOGGER.info(\"iotrace is already installed by previous test\") # Call", "TestRun from utils.installer import install_iotrace, check_if_installed from utils.iotrace import IotracePlugin", "def dut_prepare(reinstall: bool): if not check_if_installed() or reinstall: TestRun.LOGGER.info(\"Installing iotrace:\")", "!= \"\": TestRun.executor.run(f'kill -9 {output.stdout}') TestRun.LOGGER.info(\"Removing existing traces\") trace_repository_path: str", "import IotracePlugin from utils.misc import kill_all_io from test_tools.fio.fio import Fio", "fio = Fio() if not fio.is_installed(): TestRun.LOGGER.info(\"Installing fio\") fio.install() TestRun.LOGGER.info(\"Killing", "all IO\") kill_all_io() def dut_cleanup(): iotrace: IotracePlugin = TestRun.plugins['iotrace'] TestRun.LOGGER.info(\"Stopping", "kill_all_io from test_tools.fio.fio import Fio def dut_prepare(reinstall: bool): if not", "output = TestRun.executor.run('pgrep iotrace') if output.stdout != \"\": TestRun.executor.run(f'kill -9", "import TestRun from utils.installer import install_iotrace, check_if_installed from utils.iotrace import", "# Call it after installing iotrace because we need iotrace", "Copyright(c) 2020 Intel Corporation # SPDX-License-Identifier: BSD-3-Clause-Clear # from core.test_run_utils", "TestRun.executor.run(f'{iotrace.working_dir}/standalone-linux-io-tracer/tests/security/fuzzy/fuzz.sh clean') output = TestRun.executor.run('pgrep iotrace') if output.stdout != \"\":", "valid paths dut_cleanup() fio = Fio() if not fio.is_installed(): TestRun.LOGGER.info(\"Installing", "dut_cleanup(): iotrace: IotracePlugin = TestRun.plugins['iotrace'] TestRun.LOGGER.info(\"Stopping fuzzing\") TestRun.executor.run(f'{iotrace.working_dir}/standalone-linux-io-tracer/tests/security/fuzzy/fuzz.sh clean') output", "import install_iotrace, check_if_installed from utils.iotrace import IotracePlugin from utils.misc import", "TestRun.LOGGER.info(\"iotrace is already installed by previous test\") # Call it", "Intel Corporation # SPDX-License-Identifier: BSD-3-Clause-Clear # from core.test_run_utils import TestRun", "core.test_run_utils import TestRun from utils.installer import install_iotrace, check_if_installed from utils.iotrace", "dut_prepare(reinstall: bool): if not check_if_installed() or reinstall: TestRun.LOGGER.info(\"Installing iotrace:\") install_iotrace()", "# Copyright(c) 2020 Intel Corporation # SPDX-License-Identifier: BSD-3-Clause-Clear # from", "not fio.is_installed(): TestRun.LOGGER.info(\"Installing fio\") fio.install() TestRun.LOGGER.info(\"Killing all IO\") kill_all_io() def", "from test_tools.fio.fio import Fio def dut_prepare(reinstall: bool): if not check_if_installed()", "2020 Intel Corporation # SPDX-License-Identifier: BSD-3-Clause-Clear # from core.test_run_utils import", "not check_if_installed() or reinstall: TestRun.LOGGER.info(\"Installing iotrace:\") install_iotrace() else: TestRun.LOGGER.info(\"iotrace is", "TestRun.executor.run(f'kill -9 {output.stdout}') TestRun.LOGGER.info(\"Removing existing traces\") trace_repository_path: str = iotrace.get_trace_repository_path()", "iotrace') if output.stdout != \"\": TestRun.executor.run(f'kill -9 {output.stdout}') TestRun.LOGGER.info(\"Removing existing", "Corporation # SPDX-License-Identifier: BSD-3-Clause-Clear # from core.test_run_utils import TestRun from", "\"\": TestRun.executor.run(f'kill -9 {output.stdout}') TestRun.LOGGER.info(\"Removing existing traces\") trace_repository_path: str =", "installing iotrace because we need iotrace # to get valid", "Call it after installing iotrace because we need iotrace #", "check_if_installed from utils.iotrace import IotracePlugin from utils.misc import kill_all_io from" ]
[ "import choice def random_song(genre): results = Song.query().filter(Song.genre==genre).fetch() print(results) songs =", "random_song = { \"title\": songs.song, \"album\": songs.album, \"artist\": songs.artist.lower(), \"genre\":", "Song.query().filter(Song.genre==genre).fetch() print(results) songs = choice(results) random_song = { \"title\": songs.song,", "= Song.query().filter(Song.genre==genre).fetch() print(results) songs = choice(results) random_song = { \"title\":", "from random import choice def random_song(genre): results = Song.query().filter(Song.genre==genre).fetch() print(results)", "{ \"title\": songs.song, \"album\": songs.album, \"artist\": songs.artist.lower(), \"genre\": genre, }", "random import choice def random_song(genre): results = Song.query().filter(Song.genre==genre).fetch() print(results) songs", "songs = choice(results) random_song = { \"title\": songs.song, \"album\": songs.album,", "= { \"title\": songs.song, \"album\": songs.album, \"artist\": songs.artist.lower(), \"genre\": genre,", "choice(results) random_song = { \"title\": songs.song, \"album\": songs.album, \"artist\": songs.artist.lower(),", "import Song from random import choice def random_song(genre): results =", "print(results) songs = choice(results) random_song = { \"title\": songs.song, \"album\":", "songs.song, \"album\": songs.album, \"artist\": songs.artist.lower(), \"genre\": genre, } return random_song", "results = Song.query().filter(Song.genre==genre).fetch() print(results) songs = choice(results) random_song = {", "= choice(results) random_song = { \"title\": songs.song, \"album\": songs.album, \"artist\":", "\"title\": songs.song, \"album\": songs.album, \"artist\": songs.artist.lower(), \"genre\": genre, } return", "def random_song(genre): results = Song.query().filter(Song.genre==genre).fetch() print(results) songs = choice(results) random_song", "random_song(genre): results = Song.query().filter(Song.genre==genre).fetch() print(results) songs = choice(results) random_song =", "choice def random_song(genre): results = Song.query().filter(Song.genre==genre).fetch() print(results) songs = choice(results)", "from models import Song from random import choice def random_song(genre):", "Song from random import choice def random_song(genre): results = Song.query().filter(Song.genre==genre).fetch()", "models import Song from random import choice def random_song(genre): results" ]
[ "csv csv.register_dialect(\"hashes\", delimiter=\"#\") f = open('items3.csv', 'w') with f: writer", "delimiter=\"#\") f = open('items3.csv', 'w') with f: writer = csv.writer(f,", "import csv csv.register_dialect(\"hashes\", delimiter=\"#\") f = open('items3.csv', 'w') with f:", "f: writer = csv.writer(f, dialect=\"hashes\") writer.writerow((\"pencils\", 2)) writer.writerow((\"plates\", 1)) writer.writerow((\"books\",", "#!/usr/bin/python # custom_dialect.py import csv csv.register_dialect(\"hashes\", delimiter=\"#\") f = open('items3.csv',", "custom_dialect.py import csv csv.register_dialect(\"hashes\", delimiter=\"#\") f = open('items3.csv', 'w') with", "open('items3.csv', 'w') with f: writer = csv.writer(f, dialect=\"hashes\") writer.writerow((\"pencils\", 2))", "'w') with f: writer = csv.writer(f, dialect=\"hashes\") writer.writerow((\"pencils\", 2)) writer.writerow((\"plates\",", "csv.register_dialect(\"hashes\", delimiter=\"#\") f = open('items3.csv', 'w') with f: writer =", "writer = csv.writer(f, dialect=\"hashes\") writer.writerow((\"pencils\", 2)) writer.writerow((\"plates\", 1)) writer.writerow((\"books\", 4))", "= open('items3.csv', 'w') with f: writer = csv.writer(f, dialect=\"hashes\") writer.writerow((\"pencils\",", "f = open('items3.csv', 'w') with f: writer = csv.writer(f, dialect=\"hashes\")", "# custom_dialect.py import csv csv.register_dialect(\"hashes\", delimiter=\"#\") f = open('items3.csv', 'w')", "with f: writer = csv.writer(f, dialect=\"hashes\") writer.writerow((\"pencils\", 2)) writer.writerow((\"plates\", 1))" ]
[ "\"ATLAS\"), (\"CMS\", \"CMS\")], default=\"ATLAS\") submit = SubmitField('Save Profile') def __init__(self,", "Name', validators=[DataRequired(), Length(0, 120)]) email = StringField('Email', validators=[DataRequired(), Email()]) institution", "Email()]) institution = StringField('Institution', validators=[DataRequired()]) experiment = SelectField('Experiment', validators=[DataRequired()], choices=[(\"ATLAS\",", "= user.name self.email.data = user.email self.institution.data = user.institution self.experiment.data =", "wtforms.validators import DataRequired, Length, Email from servicex.models import UserModel class", "Optional from flask_wtf import FlaskForm from wtforms import StringField, SelectField,", "StringField('Institution', validators=[DataRequired()]) experiment = SelectField('Experiment', validators=[DataRequired()], choices=[(\"ATLAS\", \"ATLAS\"), (\"CMS\", \"CMS\")],", "user.name self.email.data = user.email self.institution.data = user.institution self.experiment.data = user.experiment", "import DataRequired, Length, Email from servicex.models import UserModel class ProfileForm(FlaskForm):", "default=\"ATLAS\") submit = SubmitField('Save Profile') def __init__(self, user: Optional[UserModel] =", "flask_wtf import FlaskForm from wtforms import StringField, SelectField, SubmitField from", "DataRequired, Length, Email from servicex.models import UserModel class ProfileForm(FlaskForm): name", "submit = SubmitField('Save Profile') def __init__(self, user: Optional[UserModel] = None):", "import FlaskForm from wtforms import StringField, SelectField, SubmitField from wtforms.validators", "from wtforms import StringField, SelectField, SubmitField from wtforms.validators import DataRequired,", "wtforms import StringField, SelectField, SubmitField from wtforms.validators import DataRequired, Length,", "validators=[DataRequired()], choices=[(\"ATLAS\", \"ATLAS\"), (\"CMS\", \"CMS\")], default=\"ATLAS\") submit = SubmitField('Save Profile')", "SelectField, SubmitField from wtforms.validators import DataRequired, Length, Email from servicex.models", "SubmitField('Save Profile') def __init__(self, user: Optional[UserModel] = None): super().__init__() if", "ProfileForm(FlaskForm): name = StringField('Full Name', validators=[DataRequired(), Length(0, 120)]) email =", "None): super().__init__() if user: self.name.data = user.name self.email.data = user.email", "if user: self.name.data = user.name self.email.data = user.email self.institution.data =", "from typing import Optional from flask_wtf import FlaskForm from wtforms", "FlaskForm from wtforms import StringField, SelectField, SubmitField from wtforms.validators import", "import UserModel class ProfileForm(FlaskForm): name = StringField('Full Name', validators=[DataRequired(), Length(0,", "self.name.data = user.name self.email.data = user.email self.institution.data = user.institution self.experiment.data", "SelectField('Experiment', validators=[DataRequired()], choices=[(\"ATLAS\", \"ATLAS\"), (\"CMS\", \"CMS\")], default=\"ATLAS\") submit = SubmitField('Save", "= SubmitField('Save Profile') def __init__(self, user: Optional[UserModel] = None): super().__init__()", "import StringField, SelectField, SubmitField from wtforms.validators import DataRequired, Length, Email", "def __init__(self, user: Optional[UserModel] = None): super().__init__() if user: self.name.data", "StringField('Full Name', validators=[DataRequired(), Length(0, 120)]) email = StringField('Email', validators=[DataRequired(), Email()])", "Profile') def __init__(self, user: Optional[UserModel] = None): super().__init__() if user:", "= SelectField('Experiment', validators=[DataRequired()], choices=[(\"ATLAS\", \"ATLAS\"), (\"CMS\", \"CMS\")], default=\"ATLAS\") submit =", "choices=[(\"ATLAS\", \"ATLAS\"), (\"CMS\", \"CMS\")], default=\"ATLAS\") submit = SubmitField('Save Profile') def", "StringField('Email', validators=[DataRequired(), Email()]) institution = StringField('Institution', validators=[DataRequired()]) experiment = SelectField('Experiment',", "email = StringField('Email', validators=[DataRequired(), Email()]) institution = StringField('Institution', validators=[DataRequired()]) experiment", "120)]) email = StringField('Email', validators=[DataRequired(), Email()]) institution = StringField('Institution', validators=[DataRequired()])", "from flask_wtf import FlaskForm from wtforms import StringField, SelectField, SubmitField", "Email from servicex.models import UserModel class ProfileForm(FlaskForm): name = StringField('Full", "servicex.models import UserModel class ProfileForm(FlaskForm): name = StringField('Full Name', validators=[DataRequired(),", "from servicex.models import UserModel class ProfileForm(FlaskForm): name = StringField('Full Name',", "Length(0, 120)]) email = StringField('Email', validators=[DataRequired(), Email()]) institution = StringField('Institution',", "experiment = SelectField('Experiment', validators=[DataRequired()], choices=[(\"ATLAS\", \"ATLAS\"), (\"CMS\", \"CMS\")], default=\"ATLAS\") submit", "user: self.name.data = user.name self.email.data = user.email self.institution.data = user.institution", "SubmitField from wtforms.validators import DataRequired, Length, Email from servicex.models import", "(\"CMS\", \"CMS\")], default=\"ATLAS\") submit = SubmitField('Save Profile') def __init__(self, user:", "validators=[DataRequired(), Email()]) institution = StringField('Institution', validators=[DataRequired()]) experiment = SelectField('Experiment', validators=[DataRequired()],", "user: Optional[UserModel] = None): super().__init__() if user: self.name.data = user.name", "class ProfileForm(FlaskForm): name = StringField('Full Name', validators=[DataRequired(), Length(0, 120)]) email", "= StringField('Full Name', validators=[DataRequired(), Length(0, 120)]) email = StringField('Email', validators=[DataRequired(),", "__init__(self, user: Optional[UserModel] = None): super().__init__() if user: self.name.data =", "\"CMS\")], default=\"ATLAS\") submit = SubmitField('Save Profile') def __init__(self, user: Optional[UserModel]", "validators=[DataRequired()]) experiment = SelectField('Experiment', validators=[DataRequired()], choices=[(\"ATLAS\", \"ATLAS\"), (\"CMS\", \"CMS\")], default=\"ATLAS\")", "from wtforms.validators import DataRequired, Length, Email from servicex.models import UserModel", "Length, Email from servicex.models import UserModel class ProfileForm(FlaskForm): name =", "UserModel class ProfileForm(FlaskForm): name = StringField('Full Name', validators=[DataRequired(), Length(0, 120)])", "institution = StringField('Institution', validators=[DataRequired()]) experiment = SelectField('Experiment', validators=[DataRequired()], choices=[(\"ATLAS\", \"ATLAS\"),", "= StringField('Institution', validators=[DataRequired()]) experiment = SelectField('Experiment', validators=[DataRequired()], choices=[(\"ATLAS\", \"ATLAS\"), (\"CMS\",", "= None): super().__init__() if user: self.name.data = user.name self.email.data =", "StringField, SelectField, SubmitField from wtforms.validators import DataRequired, Length, Email from", "typing import Optional from flask_wtf import FlaskForm from wtforms import", "super().__init__() if user: self.name.data = user.name self.email.data = user.email self.institution.data", "Optional[UserModel] = None): super().__init__() if user: self.name.data = user.name self.email.data", "import Optional from flask_wtf import FlaskForm from wtforms import StringField,", "= StringField('Email', validators=[DataRequired(), Email()]) institution = StringField('Institution', validators=[DataRequired()]) experiment =", "validators=[DataRequired(), Length(0, 120)]) email = StringField('Email', validators=[DataRequired(), Email()]) institution =", "name = StringField('Full Name', validators=[DataRequired(), Length(0, 120)]) email = StringField('Email'," ]
[]
[ "short_side_resize_for_inference_data from libs.configs import cfgs from libs.networks import build_whole_network CKPT_PATH", "boxes = tf.transpose(tf.stack([xmin, ymin, xmax, ymax])) dets = tf.concat([tf.reshape(detection_category, [-1,", "1], \\ detected_boxes[:, 2], detected_boxes[:, 3] resized_shape = tf.shape(img_batch) resized_h,", "coding: utf-8 -*- from __future__ import absolute_import, print_function, division import", "name='DetResults') return dets def export_frozenPB(): tf.reset_default_graph() dets = build_detection_graph() saver", "img_plac = tf.placeholder(dtype=tf.uint8, shape=[None, None, 3], name='input_img') # is RGB.", "'_Frozen.pb')), clear_devices=False, initializer_nodes='') if __name__ == '__main__': os.environ[\"CUDA_VISIBLE_DEVICES\"] = ''", "with tf.Session() as sess: print(\"we have restred the weights from", "'../../output/Pbs' PB_NAME = 'FasterRCNN_Res101_Pascal.pb' def build_detection_graph(): # 1. preprocess img", "raw_h, raw_w = tf.to_float(raw_shape[0]), tf.to_float(raw_shape[1]) img_batch = tf.cast(img_plac, tf.float32) img_batch", "# [1, None, None, 3] det_net = build_whole_network.DetectionNetwork(base_network_name=cfgs.NET_NAME, is_training=False) detected_boxes,", "[1, None, None, 3] det_net = build_whole_network.DetectionNetwork(base_network_name=cfgs.NET_NAME, is_training=False) detected_boxes, detection_scores,", "xmax, ymax = detected_boxes[:, 0], detected_boxes[:, 1], \\ detected_boxes[:, 2],", "img_batch = img_batch - tf.constant(cfgs.PIXEL_MEAN) img_batch = tf.expand_dims(img_batch, axis=0) #", "preprocess img img_plac = tf.placeholder(dtype=tf.uint8, shape=[None, None, 3], name='input_img') #", "3] resized_shape = tf.shape(img_batch) resized_h, resized_w = tf.to_float(resized_shape[1]), tf.to_float(resized_shape[2]) xmin", "OUT_DIR, PB_NAME) freeze_graph.freeze_graph(input_graph=os.path.join(OUT_DIR, PB_NAME), input_saver='', input_binary=False, input_checkpoint=CKPT_PATH, output_node_names=\"DetResults\", restore_op_name=\"save/restore_all\", filename_tensor_name='save/Const:0',", "CKPT_PATH = '/home/yjr/PycharmProjects/Faster-RCNN_Tensorflow/output/trained_weights/FasterRCNN_20180517/voc_200000model.ckpt' OUT_DIR = '../../output/Pbs' PB_NAME = 'FasterRCNN_Res101_Pascal.pb' def", "# 1. preprocess img img_plac = tf.placeholder(dtype=tf.uint8, shape=[None, None, 3],", "import tf_slim as slim from tensorflow.python.tools import freeze_graph sys.path.append('../../') from", "xmin = xmin * raw_w / resized_w xmax = xmax", "tf.transpose(tf.stack([xmin, ymin, xmax, ymax])) dets = tf.concat([tf.reshape(detection_category, [-1, 1]), tf.reshape(detection_scores,", "3], name='input_img') # is RGB. not GBR raw_shape = tf.shape(img_plac)", "tf.placeholder(dtype=tf.uint8, shape=[None, None, 3], name='input_img') # is RGB. not GBR", "CKPT_PATH) tf.train.write_graph(sess.graph_def, OUT_DIR, PB_NAME) freeze_graph.freeze_graph(input_graph=os.path.join(OUT_DIR, PB_NAME), input_saver='', input_binary=False, input_checkpoint=CKPT_PATH, output_node_names=\"DetResults\",", "resized_w xmax = xmax * raw_w / resized_w ymin =", "= tf.shape(img_plac) raw_h, raw_w = tf.to_float(raw_shape[0]), tf.to_float(raw_shape[1]) img_batch = tf.cast(img_plac,", "tf.reset_default_graph() dets = build_detection_graph() saver = tf.train.Saver() with tf.Session() as", "as slim from tensorflow.python.tools import freeze_graph sys.path.append('../../') from data.io.image_preprocess import", "import short_side_resize_for_inference_data from libs.configs import cfgs from libs.networks import build_whole_network", "tf.shape(img_batch) resized_h, resized_w = tf.to_float(resized_shape[1]), tf.to_float(resized_shape[2]) xmin = xmin *", "build_detection_graph(): # 1. preprocess img img_plac = tf.placeholder(dtype=tf.uint8, shape=[None, None,", "target_shortside_len=cfgs.IMG_SHORT_SIDE_LEN, length_limitation=cfgs.IMG_MAX_LENGTH) img_batch = img_batch - tf.constant(cfgs.PIXEL_MEAN) img_batch = tf.expand_dims(img_batch,", "det_net = build_whole_network.DetectionNetwork(base_network_name=cfgs.NET_NAME, is_training=False) detected_boxes, detection_scores, detection_category = det_net.build_whole_detection_network( input_img_batch=img_batch,", "saver.restore(sess, CKPT_PATH) tf.train.write_graph(sess.graph_def, OUT_DIR, PB_NAME) freeze_graph.freeze_graph(input_graph=os.path.join(OUT_DIR, PB_NAME), input_saver='', input_binary=False, input_checkpoint=CKPT_PATH,", "clear_devices=False, initializer_nodes='') if __name__ == '__main__': os.environ[\"CUDA_VISIBLE_DEVICES\"] = '' export_frozenPB()", "tf.expand_dims(img_batch, axis=0) # [1, None, None, 3] det_net = build_whole_network.DetectionNetwork(base_network_name=cfgs.NET_NAME,", "= tf.expand_dims(img_batch, axis=0) # [1, None, None, 3] det_net =", "resized_w = tf.to_float(resized_shape[1]), tf.to_float(resized_shape[2]) xmin = xmin * raw_w /", "sess: print(\"we have restred the weights from =====>>\\n\", CKPT_PATH) saver.restore(sess,", "raw_shape = tf.shape(img_plac) raw_h, raw_w = tf.to_float(raw_shape[0]), tf.to_float(raw_shape[1]) img_batch =", "input_checkpoint=CKPT_PATH, output_node_names=\"DetResults\", restore_op_name=\"save/restore_all\", filename_tensor_name='save/Const:0', output_graph=os.path.join(OUT_DIR, PB_NAME.replace('.pb', '_Frozen.pb')), clear_devices=False, initializer_nodes='') if", "data.io.image_preprocess import short_side_resize_for_inference_data from libs.configs import cfgs from libs.networks import", "detection_scores, detection_category = det_net.build_whole_detection_network( input_img_batch=img_batch, gtboxes_batch=None) xmin, ymin, xmax, ymax", "= short_side_resize_for_inference_data(img_tensor=img_batch, target_shortside_len=cfgs.IMG_SHORT_SIDE_LEN, length_limitation=cfgs.IMG_MAX_LENGTH) img_batch = img_batch - tf.constant(cfgs.PIXEL_MEAN) img_batch", "None, None, 3] det_net = build_whole_network.DetectionNetwork(base_network_name=cfgs.NET_NAME, is_training=False) detected_boxes, detection_scores, detection_category", "img_batch - tf.constant(cfgs.PIXEL_MEAN) img_batch = tf.expand_dims(img_batch, axis=0) # [1, None,", "dets = tf.concat([tf.reshape(detection_category, [-1, 1]), tf.reshape(detection_scores, [-1, 1]), boxes], axis=1,", "libs.networks import build_whole_network CKPT_PATH = '/home/yjr/PycharmProjects/Faster-RCNN_Tensorflow/output/trained_weights/FasterRCNN_20180517/voc_200000model.ckpt' OUT_DIR = '../../output/Pbs' PB_NAME", "not GBR raw_shape = tf.shape(img_plac) raw_h, raw_w = tf.to_float(raw_shape[0]), tf.to_float(raw_shape[1])", "tensorflow.python.tools import freeze_graph sys.path.append('../../') from data.io.image_preprocess import short_side_resize_for_inference_data from libs.configs", "raw_w / resized_w xmax = xmax * raw_w / resized_w", "short_side_resize_for_inference_data(img_tensor=img_batch, target_shortside_len=cfgs.IMG_SHORT_SIDE_LEN, length_limitation=cfgs.IMG_MAX_LENGTH) img_batch = img_batch - tf.constant(cfgs.PIXEL_MEAN) img_batch =", "= tf.shape(img_batch) resized_h, resized_w = tf.to_float(resized_shape[1]), tf.to_float(resized_shape[2]) xmin = xmin", "detected_boxes[:, 1], \\ detected_boxes[:, 2], detected_boxes[:, 3] resized_shape = tf.shape(img_batch)", "img_batch = tf.cast(img_plac, tf.float32) img_batch = short_side_resize_for_inference_data(img_tensor=img_batch, target_shortside_len=cfgs.IMG_SHORT_SIDE_LEN, length_limitation=cfgs.IMG_MAX_LENGTH) img_batch", "build_whole_network.DetectionNetwork(base_network_name=cfgs.NET_NAME, is_training=False) detected_boxes, detection_scores, detection_category = det_net.build_whole_detection_network( input_img_batch=img_batch, gtboxes_batch=None) xmin,", "0], detected_boxes[:, 1], \\ detected_boxes[:, 2], detected_boxes[:, 3] resized_shape =", "print_function, division import os, sys import tensorflow as tf import", "= '../../output/Pbs' PB_NAME = 'FasterRCNN_Res101_Pascal.pb' def build_detection_graph(): # 1. preprocess", "from tensorflow.python.tools import freeze_graph sys.path.append('../../') from data.io.image_preprocess import short_side_resize_for_inference_data from", "is_training=False) detected_boxes, detection_scores, detection_category = det_net.build_whole_detection_network( input_img_batch=img_batch, gtboxes_batch=None) xmin, ymin,", "ymax])) dets = tf.concat([tf.reshape(detection_category, [-1, 1]), tf.reshape(detection_scores, [-1, 1]), boxes],", "shape=[None, None, 3], name='input_img') # is RGB. not GBR raw_shape", "'/home/yjr/PycharmProjects/Faster-RCNN_Tensorflow/output/trained_weights/FasterRCNN_20180517/voc_200000model.ckpt' OUT_DIR = '../../output/Pbs' PB_NAME = 'FasterRCNN_Res101_Pascal.pb' def build_detection_graph(): #", "axis=0) # [1, None, None, 3] det_net = build_whole_network.DetectionNetwork(base_network_name=cfgs.NET_NAME, is_training=False)", "libs.configs import cfgs from libs.networks import build_whole_network CKPT_PATH = '/home/yjr/PycharmProjects/Faster-RCNN_Tensorflow/output/trained_weights/FasterRCNN_20180517/voc_200000model.ckpt'", "/ resized_h ymax = ymax * raw_h / resized_h boxes", "tf.concat([tf.reshape(detection_category, [-1, 1]), tf.reshape(detection_scores, [-1, 1]), boxes], axis=1, name='DetResults') return", "import absolute_import, print_function, division import os, sys import tensorflow as", "__future__ import absolute_import, print_function, division import os, sys import tensorflow", "\\ detected_boxes[:, 2], detected_boxes[:, 3] resized_shape = tf.shape(img_batch) resized_h, resized_w", "= ymin * raw_h / resized_h ymax = ymax *", "division import os, sys import tensorflow as tf import tf_slim", "the weights from =====>>\\n\", CKPT_PATH) saver.restore(sess, CKPT_PATH) tf.train.write_graph(sess.graph_def, OUT_DIR, PB_NAME)", "tf_slim as slim from tensorflow.python.tools import freeze_graph sys.path.append('../../') from data.io.image_preprocess", "resized_h ymax = ymax * raw_h / resized_h boxes =", "* raw_h / resized_h ymax = ymax * raw_h /", "input_saver='', input_binary=False, input_checkpoint=CKPT_PATH, output_node_names=\"DetResults\", restore_op_name=\"save/restore_all\", filename_tensor_name='save/Const:0', output_graph=os.path.join(OUT_DIR, PB_NAME.replace('.pb', '_Frozen.pb')), clear_devices=False,", "2], detected_boxes[:, 3] resized_shape = tf.shape(img_batch) resized_h, resized_w = tf.to_float(resized_shape[1]),", "-*- from __future__ import absolute_import, print_function, division import os, sys", "restred the weights from =====>>\\n\", CKPT_PATH) saver.restore(sess, CKPT_PATH) tf.train.write_graph(sess.graph_def, OUT_DIR,", "raw_w / resized_w ymin = ymin * raw_h / resized_h", "slim from tensorflow.python.tools import freeze_graph sys.path.append('../../') from data.io.image_preprocess import short_side_resize_for_inference_data", "ymax = detected_boxes[:, 0], detected_boxes[:, 1], \\ detected_boxes[:, 2], detected_boxes[:,", "xmax * raw_w / resized_w ymin = ymin * raw_h", "ymin * raw_h / resized_h ymax = ymax * raw_h", "CKPT_PATH) saver.restore(sess, CKPT_PATH) tf.train.write_graph(sess.graph_def, OUT_DIR, PB_NAME) freeze_graph.freeze_graph(input_graph=os.path.join(OUT_DIR, PB_NAME), input_saver='', input_binary=False,", "= tf.cast(img_plac, tf.float32) img_batch = short_side_resize_for_inference_data(img_tensor=img_batch, target_shortside_len=cfgs.IMG_SHORT_SIDE_LEN, length_limitation=cfgs.IMG_MAX_LENGTH) img_batch =", "from libs.networks import build_whole_network CKPT_PATH = '/home/yjr/PycharmProjects/Faster-RCNN_Tensorflow/output/trained_weights/FasterRCNN_20180517/voc_200000model.ckpt' OUT_DIR = '../../output/Pbs'", "input_binary=False, input_checkpoint=CKPT_PATH, output_node_names=\"DetResults\", restore_op_name=\"save/restore_all\", filename_tensor_name='save/Const:0', output_graph=os.path.join(OUT_DIR, PB_NAME.replace('.pb', '_Frozen.pb')), clear_devices=False, initializer_nodes='')", "build_whole_network CKPT_PATH = '/home/yjr/PycharmProjects/Faster-RCNN_Tensorflow/output/trained_weights/FasterRCNN_20180517/voc_200000model.ckpt' OUT_DIR = '../../output/Pbs' PB_NAME = 'FasterRCNN_Res101_Pascal.pb'", "dets def export_frozenPB(): tf.reset_default_graph() dets = build_detection_graph() saver = tf.train.Saver()", "= xmax * raw_w / resized_w ymin = ymin *", "os, sys import tensorflow as tf import tf_slim as slim", "tf import tf_slim as slim from tensorflow.python.tools import freeze_graph sys.path.append('../../')", "xmax, ymax])) dets = tf.concat([tf.reshape(detection_category, [-1, 1]), tf.reshape(detection_scores, [-1, 1]),", "= tf.concat([tf.reshape(detection_category, [-1, 1]), tf.reshape(detection_scores, [-1, 1]), boxes], axis=1, name='DetResults')", "utf-8 -*- from __future__ import absolute_import, print_function, division import os,", "1. preprocess img img_plac = tf.placeholder(dtype=tf.uint8, shape=[None, None, 3], name='input_img')", "PB_NAME = 'FasterRCNN_Res101_Pascal.pb' def build_detection_graph(): # 1. preprocess img img_plac", "'FasterRCNN_Res101_Pascal.pb' def build_detection_graph(): # 1. preprocess img img_plac = tf.placeholder(dtype=tf.uint8,", "tf.to_float(resized_shape[2]) xmin = xmin * raw_w / resized_w xmax =", "length_limitation=cfgs.IMG_MAX_LENGTH) img_batch = img_batch - tf.constant(cfgs.PIXEL_MEAN) img_batch = tf.expand_dims(img_batch, axis=0)", "= '/home/yjr/PycharmProjects/Faster-RCNN_Tensorflow/output/trained_weights/FasterRCNN_20180517/voc_200000model.ckpt' OUT_DIR = '../../output/Pbs' PB_NAME = 'FasterRCNN_Res101_Pascal.pb' def build_detection_graph():", "have restred the weights from =====>>\\n\", CKPT_PATH) saver.restore(sess, CKPT_PATH) tf.train.write_graph(sess.graph_def,", "tensorflow as tf import tf_slim as slim from tensorflow.python.tools import", "= ymax * raw_h / resized_h boxes = tf.transpose(tf.stack([xmin, ymin,", "= tf.to_float(resized_shape[1]), tf.to_float(resized_shape[2]) xmin = xmin * raw_w / resized_w", "freeze_graph sys.path.append('../../') from data.io.image_preprocess import short_side_resize_for_inference_data from libs.configs import cfgs", "None, 3], name='input_img') # is RGB. not GBR raw_shape =", "img_batch = tf.expand_dims(img_batch, axis=0) # [1, None, None, 3] det_net", "detection_category = det_net.build_whole_detection_network( input_img_batch=img_batch, gtboxes_batch=None) xmin, ymin, xmax, ymax =", "ymax = ymax * raw_h / resized_h boxes = tf.transpose(tf.stack([xmin,", "freeze_graph.freeze_graph(input_graph=os.path.join(OUT_DIR, PB_NAME), input_saver='', input_binary=False, input_checkpoint=CKPT_PATH, output_node_names=\"DetResults\", restore_op_name=\"save/restore_all\", filename_tensor_name='save/Const:0', output_graph=os.path.join(OUT_DIR, PB_NAME.replace('.pb',", "cfgs from libs.networks import build_whole_network CKPT_PATH = '/home/yjr/PycharmProjects/Faster-RCNN_Tensorflow/output/trained_weights/FasterRCNN_20180517/voc_200000model.ckpt' OUT_DIR =", "1]), tf.reshape(detection_scores, [-1, 1]), boxes], axis=1, name='DetResults') return dets def", "tf.cast(img_plac, tf.float32) img_batch = short_side_resize_for_inference_data(img_tensor=img_batch, target_shortside_len=cfgs.IMG_SHORT_SIDE_LEN, length_limitation=cfgs.IMG_MAX_LENGTH) img_batch = img_batch", "= detected_boxes[:, 0], detected_boxes[:, 1], \\ detected_boxes[:, 2], detected_boxes[:, 3]", "import freeze_graph sys.path.append('../../') from data.io.image_preprocess import short_side_resize_for_inference_data from libs.configs import", "# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function,", "raw_w = tf.to_float(raw_shape[0]), tf.to_float(raw_shape[1]) img_batch = tf.cast(img_plac, tf.float32) img_batch =", "resized_shape = tf.shape(img_batch) resized_h, resized_w = tf.to_float(resized_shape[1]), tf.to_float(resized_shape[2]) xmin =", "def export_frozenPB(): tf.reset_default_graph() dets = build_detection_graph() saver = tf.train.Saver() with", "/ resized_w xmax = xmax * raw_w / resized_w ymin", "PB_NAME) freeze_graph.freeze_graph(input_graph=os.path.join(OUT_DIR, PB_NAME), input_saver='', input_binary=False, input_checkpoint=CKPT_PATH, output_node_names=\"DetResults\", restore_op_name=\"save/restore_all\", filename_tensor_name='save/Const:0', output_graph=os.path.join(OUT_DIR,", "PB_NAME), input_saver='', input_binary=False, input_checkpoint=CKPT_PATH, output_node_names=\"DetResults\", restore_op_name=\"save/restore_all\", filename_tensor_name='save/Const:0', output_graph=os.path.join(OUT_DIR, PB_NAME.replace('.pb', '_Frozen.pb')),", "tf.to_float(raw_shape[1]) img_batch = tf.cast(img_plac, tf.float32) img_batch = short_side_resize_for_inference_data(img_tensor=img_batch, target_shortside_len=cfgs.IMG_SHORT_SIDE_LEN, length_limitation=cfgs.IMG_MAX_LENGTH)", "tf.float32) img_batch = short_side_resize_for_inference_data(img_tensor=img_batch, target_shortside_len=cfgs.IMG_SHORT_SIDE_LEN, length_limitation=cfgs.IMG_MAX_LENGTH) img_batch = img_batch -", "tf.Session() as sess: print(\"we have restred the weights from =====>>\\n\",", "= xmin * raw_w / resized_w xmax = xmax *", "[-1, 1]), tf.reshape(detection_scores, [-1, 1]), boxes], axis=1, name='DetResults') return dets", "tf.train.Saver() with tf.Session() as sess: print(\"we have restred the weights", "tf.train.write_graph(sess.graph_def, OUT_DIR, PB_NAME) freeze_graph.freeze_graph(input_graph=os.path.join(OUT_DIR, PB_NAME), input_saver='', input_binary=False, input_checkpoint=CKPT_PATH, output_node_names=\"DetResults\", restore_op_name=\"save/restore_all\",", "boxes], axis=1, name='DetResults') return dets def export_frozenPB(): tf.reset_default_graph() dets =", "= 'FasterRCNN_Res101_Pascal.pb' def build_detection_graph(): # 1. preprocess img img_plac =", "detected_boxes[:, 3] resized_shape = tf.shape(img_batch) resized_h, resized_w = tf.to_float(resized_shape[1]), tf.to_float(resized_shape[2])", "weights from =====>>\\n\", CKPT_PATH) saver.restore(sess, CKPT_PATH) tf.train.write_graph(sess.graph_def, OUT_DIR, PB_NAME) freeze_graph.freeze_graph(input_graph=os.path.join(OUT_DIR,", "sys import tensorflow as tf import tf_slim as slim from", "tf.constant(cfgs.PIXEL_MEAN) img_batch = tf.expand_dims(img_batch, axis=0) # [1, None, None, 3]", "detected_boxes[:, 2], detected_boxes[:, 3] resized_shape = tf.shape(img_batch) resized_h, resized_w =", "ymin = ymin * raw_h / resized_h ymax = ymax", "is RGB. not GBR raw_shape = tf.shape(img_plac) raw_h, raw_w =", "-*- coding: utf-8 -*- from __future__ import absolute_import, print_function, division", "xmin, ymin, xmax, ymax = detected_boxes[:, 0], detected_boxes[:, 1], \\", "raw_h / resized_h boxes = tf.transpose(tf.stack([xmin, ymin, xmax, ymax])) dets", "return dets def export_frozenPB(): tf.reset_default_graph() dets = build_detection_graph() saver =", "= tf.train.Saver() with tf.Session() as sess: print(\"we have restred the", "import cfgs from libs.networks import build_whole_network CKPT_PATH = '/home/yjr/PycharmProjects/Faster-RCNN_Tensorflow/output/trained_weights/FasterRCNN_20180517/voc_200000model.ckpt' OUT_DIR", "- tf.constant(cfgs.PIXEL_MEAN) img_batch = tf.expand_dims(img_batch, axis=0) # [1, None, None,", "= build_whole_network.DetectionNetwork(base_network_name=cfgs.NET_NAME, is_training=False) detected_boxes, detection_scores, detection_category = det_net.build_whole_detection_network( input_img_batch=img_batch, gtboxes_batch=None)", "restore_op_name=\"save/restore_all\", filename_tensor_name='save/Const:0', output_graph=os.path.join(OUT_DIR, PB_NAME.replace('.pb', '_Frozen.pb')), clear_devices=False, initializer_nodes='') if __name__ ==", "resized_h boxes = tf.transpose(tf.stack([xmin, ymin, xmax, ymax])) dets = tf.concat([tf.reshape(detection_category,", "ymin, xmax, ymax = detected_boxes[:, 0], detected_boxes[:, 1], \\ detected_boxes[:,", "input_img_batch=img_batch, gtboxes_batch=None) xmin, ymin, xmax, ymax = detected_boxes[:, 0], detected_boxes[:,", "= img_batch - tf.constant(cfgs.PIXEL_MEAN) img_batch = tf.expand_dims(img_batch, axis=0) # [1,", "xmin * raw_w / resized_w xmax = xmax * raw_w", "output_node_names=\"DetResults\", restore_op_name=\"save/restore_all\", filename_tensor_name='save/Const:0', output_graph=os.path.join(OUT_DIR, PB_NAME.replace('.pb', '_Frozen.pb')), clear_devices=False, initializer_nodes='') if __name__", "# is RGB. not GBR raw_shape = tf.shape(img_plac) raw_h, raw_w", "tf.reshape(detection_scores, [-1, 1]), boxes], axis=1, name='DetResults') return dets def export_frozenPB():", "saver = tf.train.Saver() with tf.Session() as sess: print(\"we have restred", "xmax = xmax * raw_w / resized_w ymin = ymin", "resized_w ymin = ymin * raw_h / resized_h ymax =", "1]), boxes], axis=1, name='DetResults') return dets def export_frozenPB(): tf.reset_default_graph() dets", "as sess: print(\"we have restred the weights from =====>>\\n\", CKPT_PATH)", "from data.io.image_preprocess import short_side_resize_for_inference_data from libs.configs import cfgs from libs.networks", "from libs.configs import cfgs from libs.networks import build_whole_network CKPT_PATH =", "import build_whole_network CKPT_PATH = '/home/yjr/PycharmProjects/Faster-RCNN_Tensorflow/output/trained_weights/FasterRCNN_20180517/voc_200000model.ckpt' OUT_DIR = '../../output/Pbs' PB_NAME =", "PB_NAME.replace('.pb', '_Frozen.pb')), clear_devices=False, initializer_nodes='') if __name__ == '__main__': os.environ[\"CUDA_VISIBLE_DEVICES\"] =", "tf.to_float(resized_shape[1]), tf.to_float(resized_shape[2]) xmin = xmin * raw_w / resized_w xmax", "import os, sys import tensorflow as tf import tf_slim as", "detected_boxes[:, 0], detected_boxes[:, 1], \\ detected_boxes[:, 2], detected_boxes[:, 3] resized_shape", "raw_h / resized_h ymax = ymax * raw_h / resized_h", "build_detection_graph() saver = tf.train.Saver() with tf.Session() as sess: print(\"we have", "def build_detection_graph(): # 1. preprocess img img_plac = tf.placeholder(dtype=tf.uint8, shape=[None,", "img img_plac = tf.placeholder(dtype=tf.uint8, shape=[None, None, 3], name='input_img') # is", "= build_detection_graph() saver = tf.train.Saver() with tf.Session() as sess: print(\"we", "filename_tensor_name='save/Const:0', output_graph=os.path.join(OUT_DIR, PB_NAME.replace('.pb', '_Frozen.pb')), clear_devices=False, initializer_nodes='') if __name__ == '__main__':", "name='input_img') # is RGB. not GBR raw_shape = tf.shape(img_plac) raw_h,", "* raw_w / resized_w ymin = ymin * raw_h /", "dets = build_detection_graph() saver = tf.train.Saver() with tf.Session() as sess:", "OUT_DIR = '../../output/Pbs' PB_NAME = 'FasterRCNN_Res101_Pascal.pb' def build_detection_graph(): # 1.", "/ resized_w ymin = ymin * raw_h / resized_h ymax", "export_frozenPB(): tf.reset_default_graph() dets = build_detection_graph() saver = tf.train.Saver() with tf.Session()", "gtboxes_batch=None) xmin, ymin, xmax, ymax = detected_boxes[:, 0], detected_boxes[:, 1],", "=====>>\\n\", CKPT_PATH) saver.restore(sess, CKPT_PATH) tf.train.write_graph(sess.graph_def, OUT_DIR, PB_NAME) freeze_graph.freeze_graph(input_graph=os.path.join(OUT_DIR, PB_NAME), input_saver='',", "img_batch = short_side_resize_for_inference_data(img_tensor=img_batch, target_shortside_len=cfgs.IMG_SHORT_SIDE_LEN, length_limitation=cfgs.IMG_MAX_LENGTH) img_batch = img_batch - tf.constant(cfgs.PIXEL_MEAN)", "from __future__ import absolute_import, print_function, division import os, sys import", "= det_net.build_whole_detection_network( input_img_batch=img_batch, gtboxes_batch=None) xmin, ymin, xmax, ymax = detected_boxes[:,", "GBR raw_shape = tf.shape(img_plac) raw_h, raw_w = tf.to_float(raw_shape[0]), tf.to_float(raw_shape[1]) img_batch", "tf.to_float(raw_shape[0]), tf.to_float(raw_shape[1]) img_batch = tf.cast(img_plac, tf.float32) img_batch = short_side_resize_for_inference_data(img_tensor=img_batch, target_shortside_len=cfgs.IMG_SHORT_SIDE_LEN,", "resized_h, resized_w = tf.to_float(resized_shape[1]), tf.to_float(resized_shape[2]) xmin = xmin * raw_w", "axis=1, name='DetResults') return dets def export_frozenPB(): tf.reset_default_graph() dets = build_detection_graph()", "RGB. not GBR raw_shape = tf.shape(img_plac) raw_h, raw_w = tf.to_float(raw_shape[0]),", "detected_boxes, detection_scores, detection_category = det_net.build_whole_detection_network( input_img_batch=img_batch, gtboxes_batch=None) xmin, ymin, xmax,", "= tf.to_float(raw_shape[0]), tf.to_float(raw_shape[1]) img_batch = tf.cast(img_plac, tf.float32) img_batch = short_side_resize_for_inference_data(img_tensor=img_batch,", "= tf.placeholder(dtype=tf.uint8, shape=[None, None, 3], name='input_img') # is RGB. not", "output_graph=os.path.join(OUT_DIR, PB_NAME.replace('.pb', '_Frozen.pb')), clear_devices=False, initializer_nodes='') if __name__ == '__main__': os.environ[\"CUDA_VISIBLE_DEVICES\"]", "/ resized_h boxes = tf.transpose(tf.stack([xmin, ymin, xmax, ymax])) dets =", "ymax * raw_h / resized_h boxes = tf.transpose(tf.stack([xmin, ymin, xmax,", "absolute_import, print_function, division import os, sys import tensorflow as tf", "* raw_w / resized_w xmax = xmax * raw_w /", "ymin, xmax, ymax])) dets = tf.concat([tf.reshape(detection_category, [-1, 1]), tf.reshape(detection_scores, [-1,", "tf.shape(img_plac) raw_h, raw_w = tf.to_float(raw_shape[0]), tf.to_float(raw_shape[1]) img_batch = tf.cast(img_plac, tf.float32)", "print(\"we have restred the weights from =====>>\\n\", CKPT_PATH) saver.restore(sess, CKPT_PATH)", "from =====>>\\n\", CKPT_PATH) saver.restore(sess, CKPT_PATH) tf.train.write_graph(sess.graph_def, OUT_DIR, PB_NAME) freeze_graph.freeze_graph(input_graph=os.path.join(OUT_DIR, PB_NAME),", "as tf import tf_slim as slim from tensorflow.python.tools import freeze_graph", "None, 3] det_net = build_whole_network.DetectionNetwork(base_network_name=cfgs.NET_NAME, is_training=False) detected_boxes, detection_scores, detection_category =", "det_net.build_whole_detection_network( input_img_batch=img_batch, gtboxes_batch=None) xmin, ymin, xmax, ymax = detected_boxes[:, 0],", "* raw_h / resized_h boxes = tf.transpose(tf.stack([xmin, ymin, xmax, ymax]))", "sys.path.append('../../') from data.io.image_preprocess import short_side_resize_for_inference_data from libs.configs import cfgs from", "3] det_net = build_whole_network.DetectionNetwork(base_network_name=cfgs.NET_NAME, is_training=False) detected_boxes, detection_scores, detection_category = det_net.build_whole_detection_network(", "import tensorflow as tf import tf_slim as slim from tensorflow.python.tools", "= tf.transpose(tf.stack([xmin, ymin, xmax, ymax])) dets = tf.concat([tf.reshape(detection_category, [-1, 1]),", "[-1, 1]), boxes], axis=1, name='DetResults') return dets def export_frozenPB(): tf.reset_default_graph()" ]
[ "\"\"\" # AdapterRemoval # # {0}: executable # {1}: fastq1", "{2}: fastq2 abs # {3}: fastq1 # {4}: fastq2 #", "Removal templates \"\"\" # AdapterRemoval # # {0}: executable #", "{3}.p1 --output2 {4}.p2 --mm {6} --minquality {7} --minalignmentlength {8} --trimqualities", "fq2o = os.path.abspath(fq2) cmd = __ADAPTER_REMOVAL__.format(config['adapter_removal']['executable'], fq1o, fq2o, fq1, fq2,", "base uality # {8}: min merge_length __ADAPTER_REMOVAL__=\"\"\" {0} --collapse --file1", "# {6}: mismatch_rate # {7}: min base uality # {8}:", "--output1 {3}.p1 --output2 {4}.p2 --mm {6} --minquality {7} --minalignmentlength {8}", "__ADAPTER_REMOVAL__=\"\"\" {0} --collapse --file1 {1} --file2 {2} --outputstats {3}.stats --trimns", "{1} --file2 {2} --outputstats {3}.stats --trimns --outputcollapsed {3}.collapsed --minlength {5}", "minimum length # {6}: mismatch_rate # {7}: min base uality", "{0}: executable # {1}: fastq1 abs # {2}: fastq2 abs", "# AdapterRemoval # # {0}: executable # {1}: fastq1 abs", "--minlength {5} --output1 {3}.p1 --output2 {4}.p2 --mm {6} --minquality {7}", "min merge_length __ADAPTER_REMOVAL__=\"\"\" {0} --collapse --file1 {1} --file2 {2} --outputstats", "args.adapt_min_length, args.adapt_mismatch_rate ,args.adapt_min_qual, args.adapt_alignment_length) job_id = fq1 + \".adapter_removal\" return", "job_id = fq1 + \".adapter_removal\" return CommandNode(cmd, job_id, None, args.temp_directory)", "--mm {6} --minquality {7} --minalignmentlength {8} --trimqualities \"\"\" import os", "fastq1 abs # {2}: fastq2 abs # {3}: fastq1 #", "length # {6}: mismatch_rate # {7}: min base uality #", "min base uality # {8}: min merge_length __ADAPTER_REMOVAL__=\"\"\" {0} --collapse", "# {4}: fastq2 # {5}: minimum length # {6}: mismatch_rate", "{7} --minalignmentlength {8} --trimqualities \"\"\" import os from ngadnap.dependency_graph.graph import", "# # {0}: executable # {1}: fastq1 abs # {2}:", "fastq2 abs # {3}: fastq1 # {4}: fastq2 # {5}:", "__ADAPTER_REMOVAL__.format(config['adapter_removal']['executable'], fq1o, fq2o, fq1, fq2, args.adapt_min_length, args.adapt_mismatch_rate ,args.adapt_min_qual, args.adapt_alignment_length) job_id", "os.path.abspath(fq2) cmd = __ADAPTER_REMOVAL__.format(config['adapter_removal']['executable'], fq1o, fq2o, fq1, fq2, args.adapt_min_length, args.adapt_mismatch_rate", "{8} --trimqualities \"\"\" import os from ngadnap.dependency_graph.graph import CommandNode def", "fq2, args.adapt_min_length, args.adapt_mismatch_rate ,args.adapt_min_qual, args.adapt_alignment_length) job_id = fq1 + \".adapter_removal\"", "from ngadnap.dependency_graph.graph import CommandNode def adapter_removal(config, args, fq1 ,fq2): fq1o", "{2} --outputstats {3}.stats --trimns --outputcollapsed {3}.collapsed --minlength {5} --output1 {3}.p1", "{1}: fastq1 abs # {2}: fastq2 abs # {3}: fastq1", "\"\"\" import os from ngadnap.dependency_graph.graph import CommandNode def adapter_removal(config, args,", "args, fq1 ,fq2): fq1o = os.path.abspath(fq1) fq2o = os.path.abspath(fq2) cmd", "ngadnap.dependency_graph.graph import CommandNode def adapter_removal(config, args, fq1 ,fq2): fq1o =", "--output2 {4}.p2 --mm {6} --minquality {7} --minalignmentlength {8} --trimqualities \"\"\"", "{7}: min base uality # {8}: min merge_length __ADAPTER_REMOVAL__=\"\"\" {0}", "templates \"\"\" # AdapterRemoval # # {0}: executable # {1}:", "fastq2 # {5}: minimum length # {6}: mismatch_rate # {7}:", "abs # {2}: fastq2 abs # {3}: fastq1 # {4}:", "--trimqualities \"\"\" import os from ngadnap.dependency_graph.graph import CommandNode def adapter_removal(config,", "# {3}: fastq1 # {4}: fastq2 # {5}: minimum length", "# {7}: min base uality # {8}: min merge_length __ADAPTER_REMOVAL__=\"\"\"", "os from ngadnap.dependency_graph.graph import CommandNode def adapter_removal(config, args, fq1 ,fq2):", "# {0}: executable # {1}: fastq1 abs # {2}: fastq2", "fq1o, fq2o, fq1, fq2, args.adapt_min_length, args.adapt_mismatch_rate ,args.adapt_min_qual, args.adapt_alignment_length) job_id =", "{0} --collapse --file1 {1} --file2 {2} --outputstats {3}.stats --trimns --outputcollapsed", "= os.path.abspath(fq1) fq2o = os.path.abspath(fq2) cmd = __ADAPTER_REMOVAL__.format(config['adapter_removal']['executable'], fq1o, fq2o,", "{5} --output1 {3}.p1 --output2 {4}.p2 --mm {6} --minquality {7} --minalignmentlength", "{3}: fastq1 # {4}: fastq2 # {5}: minimum length #", "{3}.collapsed --minlength {5} --output1 {3}.p1 --output2 {4}.p2 --mm {6} --minquality", ",fq2): fq1o = os.path.abspath(fq1) fq2o = os.path.abspath(fq2) cmd = __ADAPTER_REMOVAL__.format(config['adapter_removal']['executable'],", "# {8}: min merge_length __ADAPTER_REMOVAL__=\"\"\" {0} --collapse --file1 {1} --file2", "fq2o, fq1, fq2, args.adapt_min_length, args.adapt_mismatch_rate ,args.adapt_min_qual, args.adapt_alignment_length) job_id = fq1", "AdapterRemoval # # {0}: executable # {1}: fastq1 abs #", "{6}: mismatch_rate # {7}: min base uality # {8}: min", "merge_length __ADAPTER_REMOVAL__=\"\"\" {0} --collapse --file1 {1} --file2 {2} --outputstats {3}.stats", "# {1}: fastq1 abs # {2}: fastq2 abs # {3}:", "{6} --minquality {7} --minalignmentlength {8} --trimqualities \"\"\" import os from", "{8}: min merge_length __ADAPTER_REMOVAL__=\"\"\" {0} --collapse --file1 {1} --file2 {2}", "CommandNode def adapter_removal(config, args, fq1 ,fq2): fq1o = os.path.abspath(fq1) fq2o", "fastq1 # {4}: fastq2 # {5}: minimum length # {6}:", "{4}: fastq2 # {5}: minimum length # {6}: mismatch_rate #", "--file1 {1} --file2 {2} --outputstats {3}.stats --trimns --outputcollapsed {3}.collapsed --minlength", "--trimns --outputcollapsed {3}.collapsed --minlength {5} --output1 {3}.p1 --output2 {4}.p2 --mm", "mismatch_rate # {7}: min base uality # {8}: min merge_length", "fq1, fq2, args.adapt_min_length, args.adapt_mismatch_rate ,args.adapt_min_qual, args.adapt_alignment_length) job_id = fq1 +", "fq1 ,fq2): fq1o = os.path.abspath(fq1) fq2o = os.path.abspath(fq2) cmd =", "= os.path.abspath(fq2) cmd = __ADAPTER_REMOVAL__.format(config['adapter_removal']['executable'], fq1o, fq2o, fq1, fq2, args.adapt_min_length,", "os.path.abspath(fq1) fq2o = os.path.abspath(fq2) cmd = __ADAPTER_REMOVAL__.format(config['adapter_removal']['executable'], fq1o, fq2o, fq1,", "abs # {3}: fastq1 # {4}: fastq2 # {5}: minimum", "cmd = __ADAPTER_REMOVAL__.format(config['adapter_removal']['executable'], fq1o, fq2o, fq1, fq2, args.adapt_min_length, args.adapt_mismatch_rate ,args.adapt_min_qual,", "adapter_removal(config, args, fq1 ,fq2): fq1o = os.path.abspath(fq1) fq2o = os.path.abspath(fq2)", "executable # {1}: fastq1 abs # {2}: fastq2 abs #", "--outputcollapsed {3}.collapsed --minlength {5} --output1 {3}.p1 --output2 {4}.p2 --mm {6}", "args.adapt_alignment_length) job_id = fq1 + \".adapter_removal\" return CommandNode(cmd, job_id, None,", "{3}.stats --trimns --outputcollapsed {3}.collapsed --minlength {5} --output1 {3}.p1 --output2 {4}.p2", "= __ADAPTER_REMOVAL__.format(config['adapter_removal']['executable'], fq1o, fq2o, fq1, fq2, args.adapt_min_length, args.adapt_mismatch_rate ,args.adapt_min_qual, args.adapt_alignment_length)", "fq1o = os.path.abspath(fq1) fq2o = os.path.abspath(fq2) cmd = __ADAPTER_REMOVAL__.format(config['adapter_removal']['executable'], fq1o,", "Adapter Removal templates \"\"\" # AdapterRemoval # # {0}: executable", "<gh_stars>0 \"\"\" Adapter Removal templates \"\"\" # AdapterRemoval # #", "import CommandNode def adapter_removal(config, args, fq1 ,fq2): fq1o = os.path.abspath(fq1)", "import os from ngadnap.dependency_graph.graph import CommandNode def adapter_removal(config, args, fq1", "# {5}: minimum length # {6}: mismatch_rate # {7}: min", "uality # {8}: min merge_length __ADAPTER_REMOVAL__=\"\"\" {0} --collapse --file1 {1}", "\"\"\" Adapter Removal templates \"\"\" # AdapterRemoval # # {0}:", "args.adapt_mismatch_rate ,args.adapt_min_qual, args.adapt_alignment_length) job_id = fq1 + \".adapter_removal\" return CommandNode(cmd,", ",args.adapt_min_qual, args.adapt_alignment_length) job_id = fq1 + \".adapter_removal\" return CommandNode(cmd, job_id,", "--collapse --file1 {1} --file2 {2} --outputstats {3}.stats --trimns --outputcollapsed {3}.collapsed", "def adapter_removal(config, args, fq1 ,fq2): fq1o = os.path.abspath(fq1) fq2o =", "--minalignmentlength {8} --trimqualities \"\"\" import os from ngadnap.dependency_graph.graph import CommandNode", "{4}.p2 --mm {6} --minquality {7} --minalignmentlength {8} --trimqualities \"\"\" import", "--outputstats {3}.stats --trimns --outputcollapsed {3}.collapsed --minlength {5} --output1 {3}.p1 --output2", "--minquality {7} --minalignmentlength {8} --trimqualities \"\"\" import os from ngadnap.dependency_graph.graph", "{5}: minimum length # {6}: mismatch_rate # {7}: min base", "# {2}: fastq2 abs # {3}: fastq1 # {4}: fastq2", "--file2 {2} --outputstats {3}.stats --trimns --outputcollapsed {3}.collapsed --minlength {5} --output1" ]
[ "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR", "may obtain # a copy of the License at #", "new_schema.immutable = True return new_schema class ImmutableNet(net.Net): '''Ensure an existing", "# # Licensed under the Apache License, Version 2.0 (the", "agreed to in writing, software # distributed under the License", "Unless required by applicable law or agreed to in writing,", "new_schema class ImmutableNet(net.Net): '''Ensure an existing net doesn't change.''' properties_schema", "distributed under the License is distributed on an \"AS IS\"", "existing subnet doesn't change.''' properties_schema = { k: _copy_schema_immutable(v) for", "port from heat.engine.resources.openstack.neutron import subnet def _copy_schema_immutable(schema): new_schema = copy.deepcopy(schema)", "schema.update_allowed: new_schema.immutable = True return new_schema class ImmutableNet(net.Net): '''Ensure an", "return new_schema class ImmutableNet(net.Net): '''Ensure an existing net doesn't change.'''", "in net.Net.properties_schema.items() } class ImmutablePort(port.Port): '''Ensure an existing port doesn't", "an existing port doesn't change.''' properties_schema = { k: _copy_schema_immutable(v)", "= { k: _copy_schema_immutable(v) for k, v in port.Port.properties_schema.items() }", "License, Version 2.0 (the \"License\"); you may # not use", "CONDITIONS OF ANY KIND, either express or implied. See the", "obtain # a copy of the License at # #", "subnet def _copy_schema_immutable(schema): new_schema = copy.deepcopy(schema) if not schema.update_allowed: new_schema.immutable", "applicable law or agreed to in writing, software # distributed", "_copy_schema_immutable(v) for k, v in subnet.Subnet.properties_schema.items() } def resource_mapping(): return", "v in subnet.Subnet.properties_schema.items() } def resource_mapping(): return { 'OS::Neutron::Net': ImmutableNet,", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "v in net.Net.properties_schema.items() } class ImmutablePort(port.Port): '''Ensure an existing port", "Version 2.0 (the \"License\"); you may # not use this", "specific language governing permissions and limitations # under the License.", "ImmutablePort(port.Port): '''Ensure an existing port doesn't change.''' properties_schema = {", "# not use this file except in compliance with the", "not use this file except in compliance with the License.", "OF ANY KIND, either express or implied. See the #", "class ImmutableNet(net.Net): '''Ensure an existing net doesn't change.''' properties_schema =", "resource_mapping(): return { 'OS::Neutron::Net': ImmutableNet, 'OS::Neutron::Port': ImmutablePort, 'OS::Neutron::Subnet': ImmutableSubnet, }", "writing, software # distributed under the License is distributed on", "WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express", "in writing, software # distributed under the License is distributed", "} class ImmutableSubnet(subnet.Subnet): '''Ensure an existing subnet doesn't change.''' properties_schema", "in compliance with the License. You may obtain # a", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "License for the specific language governing permissions and limitations #", "k, v in port.Port.properties_schema.items() } class ImmutableSubnet(subnet.Subnet): '''Ensure an existing", "change.''' properties_schema = { k: _copy_schema_immutable(v) for k, v in", "v in port.Port.properties_schema.items() } class ImmutableSubnet(subnet.Subnet): '''Ensure an existing subnet", "the License. You may obtain # a copy of the", "'''Ensure an existing port doesn't change.''' properties_schema = { k:", "an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF", "on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS", "use this file except in compliance with the License. You", "You may obtain # a copy of the License at", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "_copy_schema_immutable(v) for k, v in net.Net.properties_schema.items() } class ImmutablePort(port.Port): '''Ensure", "properties_schema = { k: _copy_schema_immutable(v) for k, v in net.Net.properties_schema.items()", "= { k: _copy_schema_immutable(v) for k, v in subnet.Subnet.properties_schema.items() }", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "limitations # under the License. import copy from heat.engine.resources.openstack.neutron import", "import subnet def _copy_schema_immutable(schema): new_schema = copy.deepcopy(schema) if not schema.update_allowed:", "def resource_mapping(): return { 'OS::Neutron::Net': ImmutableNet, 'OS::Neutron::Port': ImmutablePort, 'OS::Neutron::Subnet': ImmutableSubnet,", "either express or implied. See the # License for the", "import net from heat.engine.resources.openstack.neutron import port from heat.engine.resources.openstack.neutron import subnet", "net.Net.properties_schema.items() } class ImmutablePort(port.Port): '''Ensure an existing port doesn't change.'''", "under the License is distributed on an \"AS IS\" BASIS,", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "the License. import copy from heat.engine.resources.openstack.neutron import net from heat.engine.resources.openstack.neutron", "Licensed under the Apache License, Version 2.0 (the \"License\"); you", "may # not use this file except in compliance with", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "= copy.deepcopy(schema) if not schema.update_allowed: new_schema.immutable = True return new_schema", "{ k: _copy_schema_immutable(v) for k, v in net.Net.properties_schema.items() } class", "License is distributed on an \"AS IS\" BASIS, WITHOUT #", "with the License. You may obtain # a copy of", "KIND, either express or implied. See the # License for", "# License for the specific language governing permissions and limitations", "properties_schema = { k: _copy_schema_immutable(v) for k, v in port.Port.properties_schema.items()", "permissions and limitations # under the License. import copy from", "you may # not use this file except in compliance", "existing port doesn't change.''' properties_schema = { k: _copy_schema_immutable(v) for", "\"License\"); you may # not use this file except in", "copy.deepcopy(schema) if not schema.update_allowed: new_schema.immutable = True return new_schema class", "IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND,", "{ k: _copy_schema_immutable(v) for k, v in port.Port.properties_schema.items() } class", "for k, v in subnet.Subnet.properties_schema.items() } def resource_mapping(): return {", "governing permissions and limitations # under the License. import copy", "express or implied. See the # License for the specific", "this file except in compliance with the License. You may", "= True return new_schema class ImmutableNet(net.Net): '''Ensure an existing net", "compliance with the License. You may obtain # a copy", "= { k: _copy_schema_immutable(v) for k, v in net.Net.properties_schema.items() }", "the Apache License, Version 2.0 (the \"License\"); you may #", "from heat.engine.resources.openstack.neutron import port from heat.engine.resources.openstack.neutron import subnet def _copy_schema_immutable(schema):", "{ k: _copy_schema_immutable(v) for k, v in subnet.Subnet.properties_schema.items() } def", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "port.Port.properties_schema.items() } class ImmutableSubnet(subnet.Subnet): '''Ensure an existing subnet doesn't change.'''", "} class ImmutablePort(port.Port): '''Ensure an existing port doesn't change.''' properties_schema", "# WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "for k, v in net.Net.properties_schema.items() } class ImmutablePort(port.Port): '''Ensure an", "See the # License for the specific language governing permissions", "software # distributed under the License is distributed on an", "(the \"License\"); you may # not use this file except", "def _copy_schema_immutable(schema): new_schema = copy.deepcopy(schema) if not schema.update_allowed: new_schema.immutable =", "from heat.engine.resources.openstack.neutron import net from heat.engine.resources.openstack.neutron import port from heat.engine.resources.openstack.neutron", "the License is distributed on an \"AS IS\" BASIS, WITHOUT", "properties_schema = { k: _copy_schema_immutable(v) for k, v in subnet.Subnet.properties_schema.items()", "the # License for the specific language governing permissions and", "net from heat.engine.resources.openstack.neutron import port from heat.engine.resources.openstack.neutron import subnet def", "License. import copy from heat.engine.resources.openstack.neutron import net from heat.engine.resources.openstack.neutron import", "# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "# # Unless required by applicable law or agreed to", "for k, v in port.Port.properties_schema.items() } class ImmutableSubnet(subnet.Subnet): '''Ensure an", "True return new_schema class ImmutableNet(net.Net): '''Ensure an existing net doesn't", "ImmutableSubnet(subnet.Subnet): '''Ensure an existing subnet doesn't change.''' properties_schema = {", "_copy_schema_immutable(schema): new_schema = copy.deepcopy(schema) if not schema.update_allowed: new_schema.immutable = True", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "k, v in net.Net.properties_schema.items() } class ImmutablePort(port.Port): '''Ensure an existing", "file except in compliance with the License. You may obtain", "port doesn't change.''' properties_schema = { k: _copy_schema_immutable(v) for k,", "'''Ensure an existing net doesn't change.''' properties_schema = { k:", "an existing subnet doesn't change.''' properties_schema = { k: _copy_schema_immutable(v)", "import copy from heat.engine.resources.openstack.neutron import net from heat.engine.resources.openstack.neutron import port", "class ImmutablePort(port.Port): '''Ensure an existing port doesn't change.''' properties_schema =", "k, v in subnet.Subnet.properties_schema.items() } def resource_mapping(): return { 'OS::Neutron::Net':", "for the specific language governing permissions and limitations # under", "law or agreed to in writing, software # distributed under", "OR CONDITIONS OF ANY KIND, either express or implied. See", "the specific language governing permissions and limitations # under the", "from heat.engine.resources.openstack.neutron import subnet def _copy_schema_immutable(schema): new_schema = copy.deepcopy(schema) if", "in subnet.Subnet.properties_schema.items() } def resource_mapping(): return { 'OS::Neutron::Net': ImmutableNet, 'OS::Neutron::Port':", "new_schema = copy.deepcopy(schema) if not schema.update_allowed: new_schema.immutable = True return", "import port from heat.engine.resources.openstack.neutron import subnet def _copy_schema_immutable(schema): new_schema =", "under the Apache License, Version 2.0 (the \"License\"); you may", "except in compliance with the License. You may obtain #", "2.0 (the \"License\"); you may # not use this file", "implied. See the # License for the specific language governing", "k: _copy_schema_immutable(v) for k, v in subnet.Subnet.properties_schema.items() } def resource_mapping():", "} def resource_mapping(): return { 'OS::Neutron::Net': ImmutableNet, 'OS::Neutron::Port': ImmutablePort, 'OS::Neutron::Subnet':", "class ImmutableSubnet(subnet.Subnet): '''Ensure an existing subnet doesn't change.''' properties_schema =", "language governing permissions and limitations # under the License. import", "License. You may obtain # a copy of the License", "subnet doesn't change.''' properties_schema = { k: _copy_schema_immutable(v) for k,", "by applicable law or agreed to in writing, software #", "# distributed under the License is distributed on an \"AS", "ANY KIND, either express or implied. See the # License", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "\"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY", "# Unless required by applicable law or agreed to in", "'''Ensure an existing subnet doesn't change.''' properties_schema = { k:", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "copy from heat.engine.resources.openstack.neutron import net from heat.engine.resources.openstack.neutron import port from", "to in writing, software # distributed under the License is", "is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES", "k: _copy_schema_immutable(v) for k, v in port.Port.properties_schema.items() } class ImmutableSubnet(subnet.Subnet):", "subnet.Subnet.properties_schema.items() } def resource_mapping(): return { 'OS::Neutron::Net': ImmutableNet, 'OS::Neutron::Port': ImmutablePort,", "BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either", "heat.engine.resources.openstack.neutron import net from heat.engine.resources.openstack.neutron import port from heat.engine.resources.openstack.neutron import", "net doesn't change.''' properties_schema = { k: _copy_schema_immutable(v) for k,", "or agreed to in writing, software # distributed under the", "under the License. import copy from heat.engine.resources.openstack.neutron import net from", "if not schema.update_allowed: new_schema.immutable = True return new_schema class ImmutableNet(net.Net):", "# under the License. import copy from heat.engine.resources.openstack.neutron import net", "k: _copy_schema_immutable(v) for k, v in net.Net.properties_schema.items() } class ImmutablePort(port.Port):", "not schema.update_allowed: new_schema.immutable = True return new_schema class ImmutableNet(net.Net): '''Ensure", "required by applicable law or agreed to in writing, software", "and limitations # under the License. import copy from heat.engine.resources.openstack.neutron", "an existing net doesn't change.''' properties_schema = { k: _copy_schema_immutable(v)", "heat.engine.resources.openstack.neutron import subnet def _copy_schema_immutable(schema): new_schema = copy.deepcopy(schema) if not", "existing net doesn't change.''' properties_schema = { k: _copy_schema_immutable(v) for", "doesn't change.''' properties_schema = { k: _copy_schema_immutable(v) for k, v", "_copy_schema_immutable(v) for k, v in port.Port.properties_schema.items() } class ImmutableSubnet(subnet.Subnet): '''Ensure", "ImmutableNet(net.Net): '''Ensure an existing net doesn't change.''' properties_schema = {", "in port.Port.properties_schema.items() } class ImmutableSubnet(subnet.Subnet): '''Ensure an existing subnet doesn't", "heat.engine.resources.openstack.neutron import port from heat.engine.resources.openstack.neutron import subnet def _copy_schema_immutable(schema): new_schema", "or implied. See the # License for the specific language", "Apache License, Version 2.0 (the \"License\"); you may # not" ]
[ "type self.__data = deepcopy(data) def __repr__(self): return repr(self.__data) def __str__(self):", "= deepcopy(data) def __repr__(self): return repr(self.__data) def __str__(self): return str(self.__type)", "self.__type = type self.__data = deepcopy(data) def __repr__(self): return repr(self.__data)", "self.__data = deepcopy(data) def __repr__(self): return repr(self.__data) def __str__(self): return", "__init__(self, type, data): self.__type = type self.__data = deepcopy(data) def", "= type self.__data = deepcopy(data) def __repr__(self): return repr(self.__data) def", "def __repr__(self): return repr(self.__data) def __str__(self): return str(self.__type) + str(self.__data)", "deepcopy(data) def __repr__(self): return repr(self.__data) def __str__(self): return str(self.__type) +", "def __init__(self, type, data): self.__type = type self.__data = deepcopy(data)", "Input(object): def __init__(self, type, data): self.__type = type self.__data =", "data): self.__type = type self.__data = deepcopy(data) def __repr__(self): return", "class Input(object): def __init__(self, type, data): self.__type = type self.__data", "type, data): self.__type = type self.__data = deepcopy(data) def __repr__(self):" ]
[ "from setuptools import setup, find_packages from setuptools.command.bdist_egg import bdist_egg from", "'Programming Language :: Python :: 2', 'Programming Language :: Python", "slybot import __version__ from setuptools import setup, find_packages from setuptools.command.bdist_egg", "as f: f.write(';(function(){\\n%s\\n})();' % '\\n'.join(fdata)) class bdist_egg_command(bdist_egg): def run(self): build_js()", "bdist_egg_command(bdist_egg): def run(self): build_js() bdist_egg.run(self) class sdist_command(sdist): def run(self): build_js()", "['nose', 'nose-timer'], 'clustering': ['page_clustering'] } setup(name='slybot', version=__version__, license='BSD', description='Slybot crawler',", "Independent', 'Programming Language :: Python', 'Programming Language :: Python ::", "author_email='<EMAIL>', url='http://github.com/scrapinghub/portia', packages=find_packages(exclude=('tests', 'tests.*')), platforms=['Any'], scripts=['bin/slybot', 'bin/portiacrawl'], install_requires=install_requires, extras_require=extras, package_data={'':", "extras_require=extras, package_data={'': ['slybot/splash-script-combined.js']}, include_package_data=True, cmdclass={ 'bdist_egg': bdist_egg_command, 'sdist': sdist_command },", "in files: with open(join(base_path, fname)) as f: fdata.append(f.read()) js_file =", "license='BSD', description='Slybot crawler', author='Scrapy project', author_email='<EMAIL>', url='http://github.com/scrapinghub/portia', packages=find_packages(exclude=('tests', 'tests.*')), platforms=['Any'],", "run(self): build_js() sdist.run(self) install_requires = ['Scrapy', 'scrapely', 'loginform', 'lxml', 'jsonschema',", "from setuptools.command.bdist_egg import bdist_egg from setuptools.command.sdist import sdist def build_js():", "def build_js(): root = abspath(dirname(__file__)) base_path = abspath(join(root, '..', 'splash_utils'))", "'lxml', 'jsonschema', 'dateparser', 'scrapyjs', 'page_finder', 'six'] extras = { 'tests':", "BSD License', 'Operating System :: OS Independent', 'Programming Language ::", "'..', 'slyd', 'splash_utils')) files = ('waitAsync.js', 'perform_actions.js') fdata = []", "run(self): build_js() bdist_egg.run(self) class sdist_command(sdist): def run(self): build_js() sdist.run(self) install_requires", "- Beta', 'License :: OSI Approved :: BSD License', 'Operating", "base_path = abspath(join(root, '..', 'splash_utils')) if not exists(base_path): base_path =", "sdist_command(sdist): def run(self): build_js() sdist.run(self) install_requires = ['Scrapy', 'scrapely', 'loginform',", "Python', 'Programming Language :: Python :: 2', 'Programming Language ::", "project', author_email='<EMAIL>', url='http://github.com/scrapinghub/portia', packages=find_packages(exclude=('tests', 'tests.*')), platforms=['Any'], scripts=['bin/slybot', 'bin/portiacrawl'], install_requires=install_requires, extras_require=extras,", "build_js() sdist.run(self) install_requires = ['Scrapy', 'scrapely', 'loginform', 'lxml', 'jsonschema', 'dateparser',", "= abspath(join(root, 'slybot', 'splash-script-combined.js')) with open(js_file, 'w') as f: f.write(';(function(){\\n%s\\n})();'", "with open(js_file, 'w') as f: f.write(';(function(){\\n%s\\n})();' % '\\n'.join(fdata)) class bdist_egg_command(bdist_egg):", "f: f.write(';(function(){\\n%s\\n})();' % '\\n'.join(fdata)) class bdist_egg_command(bdist_egg): def run(self): build_js() bdist_egg.run(self)", "as f: fdata.append(f.read()) js_file = abspath(join(root, 'slybot', 'splash-script-combined.js')) with open(js_file,", "'dateparser', 'scrapyjs', 'page_finder', 'six'] extras = { 'tests': ['nose', 'nose-timer'],", "install_requires = ['Scrapy', 'scrapely', 'loginform', 'lxml', 'jsonschema', 'dateparser', 'scrapyjs', 'page_finder',", "from os.path import join, abspath, dirname, exists from slybot import", "[] for fname in files: with open(join(base_path, fname)) as f:", "'clustering': ['page_clustering'] } setup(name='slybot', version=__version__, license='BSD', description='Slybot crawler', author='Scrapy project',", "setup, find_packages from setuptools.command.bdist_egg import bdist_egg from setuptools.command.sdist import sdist", ":: OS Independent', 'Programming Language :: Python', 'Programming Language ::", "fdata = [] for fname in files: with open(join(base_path, fname))", "'scrapyjs', 'page_finder', 'six'] extras = { 'tests': ['nose', 'nose-timer'], 'clustering':", "['Scrapy', 'scrapely', 'loginform', 'lxml', 'jsonschema', 'dateparser', 'scrapyjs', 'page_finder', 'six'] extras", "'bin/portiacrawl'], install_requires=install_requires, extras_require=extras, package_data={'': ['slybot/splash-script-combined.js']}, include_package_data=True, cmdclass={ 'bdist_egg': bdist_egg_command, 'sdist':", "include_package_data=True, cmdclass={ 'bdist_egg': bdist_egg_command, 'sdist': sdist_command }, classifiers=[ 'Development Status", "author='Scrapy project', author_email='<EMAIL>', url='http://github.com/scrapinghub/portia', packages=find_packages(exclude=('tests', 'tests.*')), platforms=['Any'], scripts=['bin/slybot', 'bin/portiacrawl'], install_requires=install_requires,", "crawler', author='Scrapy project', author_email='<EMAIL>', url='http://github.com/scrapinghub/portia', packages=find_packages(exclude=('tests', 'tests.*')), platforms=['Any'], scripts=['bin/slybot', 'bin/portiacrawl'],", "cmdclass={ 'bdist_egg': bdist_egg_command, 'sdist': sdist_command }, classifiers=[ 'Development Status ::", "OSI Approved :: BSD License', 'Operating System :: OS Independent',", "dirname, exists from slybot import __version__ from setuptools import setup,", "find_packages from setuptools.command.bdist_egg import bdist_egg from setuptools.command.sdist import sdist def", "class sdist_command(sdist): def run(self): build_js() sdist.run(self) install_requires = ['Scrapy', 'scrapely',", "Language :: Python', 'Programming Language :: Python :: 2', 'Programming", "'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming", "'..', 'splash_utils')) if not exists(base_path): base_path = abspath(join(root, '..', 'slyd',", "= [] for fname in files: with open(join(base_path, fname)) as", "f.write(';(function(){\\n%s\\n})();' % '\\n'.join(fdata)) class bdist_egg_command(bdist_egg): def run(self): build_js() bdist_egg.run(self) class", "'nose-timer'], 'clustering': ['page_clustering'] } setup(name='slybot', version=__version__, license='BSD', description='Slybot crawler', author='Scrapy", "not exists(base_path): base_path = abspath(join(root, '..', 'slyd', 'splash_utils')) files =", "files: with open(join(base_path, fname)) as f: fdata.append(f.read()) js_file = abspath(join(root,", "abspath(join(root, '..', 'splash_utils')) if not exists(base_path): base_path = abspath(join(root, '..',", "setuptools import setup, find_packages from setuptools.command.bdist_egg import bdist_egg from setuptools.command.sdist", "'\\n'.join(fdata)) class bdist_egg_command(bdist_egg): def run(self): build_js() bdist_egg.run(self) class sdist_command(sdist): def", "sdist.run(self) install_requires = ['Scrapy', 'scrapely', 'loginform', 'lxml', 'jsonschema', 'dateparser', 'scrapyjs',", "abspath(join(root, '..', 'slyd', 'splash_utils')) files = ('waitAsync.js', 'perform_actions.js') fdata =", ":: BSD License', 'Operating System :: OS Independent', 'Programming Language", "'Development Status :: 4 - Beta', 'License :: OSI Approved", "Status :: 4 - Beta', 'License :: OSI Approved ::", "'page_finder', 'six'] extras = { 'tests': ['nose', 'nose-timer'], 'clustering': ['page_clustering']", "version=__version__, license='BSD', description='Slybot crawler', author='Scrapy project', author_email='<EMAIL>', url='http://github.com/scrapinghub/portia', packages=find_packages(exclude=('tests', 'tests.*')),", "files = ('waitAsync.js', 'perform_actions.js') fdata = [] for fname in", "License', 'Operating System :: OS Independent', 'Programming Language :: Python',", "def run(self): build_js() sdist.run(self) install_requires = ['Scrapy', 'scrapely', 'loginform', 'lxml',", "import __version__ from setuptools import setup, find_packages from setuptools.command.bdist_egg import", "} setup(name='slybot', version=__version__, license='BSD', description='Slybot crawler', author='Scrapy project', author_email='<EMAIL>', url='http://github.com/scrapinghub/portia',", "from slybot import __version__ from setuptools import setup, find_packages from", "__version__ from setuptools import setup, find_packages from setuptools.command.bdist_egg import bdist_egg", "sdist def build_js(): root = abspath(dirname(__file__)) base_path = abspath(join(root, '..',", "build_js() bdist_egg.run(self) class sdist_command(sdist): def run(self): build_js() sdist.run(self) install_requires =", "= abspath(dirname(__file__)) base_path = abspath(join(root, '..', 'splash_utils')) if not exists(base_path):", "sdist_command }, classifiers=[ 'Development Status :: 4 - Beta', 'License", "classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI", "= abspath(join(root, '..', 'slyd', 'splash_utils')) files = ('waitAsync.js', 'perform_actions.js') fdata", "setuptools.command.bdist_egg import bdist_egg from setuptools.command.sdist import sdist def build_js(): root", ":: Python :: 2', 'Programming Language :: Python :: 2.7'", "['page_clustering'] } setup(name='slybot', version=__version__, license='BSD', description='Slybot crawler', author='Scrapy project', author_email='<EMAIL>',", "setup(name='slybot', version=__version__, license='BSD', description='Slybot crawler', author='Scrapy project', author_email='<EMAIL>', url='http://github.com/scrapinghub/portia', packages=find_packages(exclude=('tests',", "OS Independent', 'Programming Language :: Python', 'Programming Language :: Python", "Python :: 2', 'Programming Language :: Python :: 2.7' ])", "'splash_utils')) files = ('waitAsync.js', 'perform_actions.js') fdata = [] for fname", "url='http://github.com/scrapinghub/portia', packages=find_packages(exclude=('tests', 'tests.*')), platforms=['Any'], scripts=['bin/slybot', 'bin/portiacrawl'], install_requires=install_requires, extras_require=extras, package_data={'': ['slybot/splash-script-combined.js']},", "platforms=['Any'], scripts=['bin/slybot', 'bin/portiacrawl'], install_requires=install_requires, extras_require=extras, package_data={'': ['slybot/splash-script-combined.js']}, include_package_data=True, cmdclass={ 'bdist_egg':", "}, classifiers=[ 'Development Status :: 4 - Beta', 'License ::", "Approved :: BSD License', 'Operating System :: OS Independent', 'Programming", "= { 'tests': ['nose', 'nose-timer'], 'clustering': ['page_clustering'] } setup(name='slybot', version=__version__,", "abspath(join(root, 'slybot', 'splash-script-combined.js')) with open(js_file, 'w') as f: f.write(';(function(){\\n%s\\n})();' %", "description='Slybot crawler', author='Scrapy project', author_email='<EMAIL>', url='http://github.com/scrapinghub/portia', packages=find_packages(exclude=('tests', 'tests.*')), platforms=['Any'], scripts=['bin/slybot',", "f: fdata.append(f.read()) js_file = abspath(join(root, 'slybot', 'splash-script-combined.js')) with open(js_file, 'w')", "= ('waitAsync.js', 'perform_actions.js') fdata = [] for fname in files:", "= ['Scrapy', 'scrapely', 'loginform', 'lxml', 'jsonschema', 'dateparser', 'scrapyjs', 'page_finder', 'six']", "{ 'tests': ['nose', 'nose-timer'], 'clustering': ['page_clustering'] } setup(name='slybot', version=__version__, license='BSD',", "'splash_utils')) if not exists(base_path): base_path = abspath(join(root, '..', 'slyd', 'splash_utils'))", "os.path import join, abspath, dirname, exists from slybot import __version__", "from setuptools.command.sdist import sdist def build_js(): root = abspath(dirname(__file__)) base_path", "exists(base_path): base_path = abspath(join(root, '..', 'slyd', 'splash_utils')) files = ('waitAsync.js',", "'splash-script-combined.js')) with open(js_file, 'w') as f: f.write(';(function(){\\n%s\\n})();' % '\\n'.join(fdata)) class", "scripts=['bin/slybot', 'bin/portiacrawl'], install_requires=install_requires, extras_require=extras, package_data={'': ['slybot/splash-script-combined.js']}, include_package_data=True, cmdclass={ 'bdist_egg': bdist_egg_command,", "4 - Beta', 'License :: OSI Approved :: BSD License',", "Beta', 'License :: OSI Approved :: BSD License', 'Operating System", "open(join(base_path, fname)) as f: fdata.append(f.read()) js_file = abspath(join(root, 'slybot', 'splash-script-combined.js'))", "def run(self): build_js() bdist_egg.run(self) class sdist_command(sdist): def run(self): build_js() sdist.run(self)", "'scrapely', 'loginform', 'lxml', 'jsonschema', 'dateparser', 'scrapyjs', 'page_finder', 'six'] extras =", "<filename>slybot/setup.py from os.path import join, abspath, dirname, exists from slybot", "if not exists(base_path): base_path = abspath(join(root, '..', 'slyd', 'splash_utils')) files", "fname)) as f: fdata.append(f.read()) js_file = abspath(join(root, 'slybot', 'splash-script-combined.js')) with", "import sdist def build_js(): root = abspath(dirname(__file__)) base_path = abspath(join(root,", "['slybot/splash-script-combined.js']}, include_package_data=True, cmdclass={ 'bdist_egg': bdist_egg_command, 'sdist': sdist_command }, classifiers=[ 'Development", "'slyd', 'splash_utils')) files = ('waitAsync.js', 'perform_actions.js') fdata = [] for", "'six'] extras = { 'tests': ['nose', 'nose-timer'], 'clustering': ['page_clustering'] }", "'w') as f: f.write(';(function(){\\n%s\\n})();' % '\\n'.join(fdata)) class bdist_egg_command(bdist_egg): def run(self):", "'tests.*')), platforms=['Any'], scripts=['bin/slybot', 'bin/portiacrawl'], install_requires=install_requires, extras_require=extras, package_data={'': ['slybot/splash-script-combined.js']}, include_package_data=True, cmdclass={", "abspath(dirname(__file__)) base_path = abspath(join(root, '..', 'splash_utils')) if not exists(base_path): base_path", "bdist_egg_command, 'sdist': sdist_command }, classifiers=[ 'Development Status :: 4 -", "'Programming Language :: Python', 'Programming Language :: Python :: 2',", ":: 4 - Beta', 'License :: OSI Approved :: BSD", "'License :: OSI Approved :: BSD License', 'Operating System ::", "build_js(): root = abspath(dirname(__file__)) base_path = abspath(join(root, '..', 'splash_utils')) if", "import bdist_egg from setuptools.command.sdist import sdist def build_js(): root =", "% '\\n'.join(fdata)) class bdist_egg_command(bdist_egg): def run(self): build_js() bdist_egg.run(self) class sdist_command(sdist):", "import setup, find_packages from setuptools.command.bdist_egg import bdist_egg from setuptools.command.sdist import", "fdata.append(f.read()) js_file = abspath(join(root, 'slybot', 'splash-script-combined.js')) with open(js_file, 'w') as", "abspath, dirname, exists from slybot import __version__ from setuptools import", "setuptools.command.sdist import sdist def build_js(): root = abspath(dirname(__file__)) base_path =", ":: Python', 'Programming Language :: Python :: 2', 'Programming Language", "bdist_egg from setuptools.command.sdist import sdist def build_js(): root = abspath(dirname(__file__))", "package_data={'': ['slybot/splash-script-combined.js']}, include_package_data=True, cmdclass={ 'bdist_egg': bdist_egg_command, 'sdist': sdist_command }, classifiers=[", "class bdist_egg_command(bdist_egg): def run(self): build_js() bdist_egg.run(self) class sdist_command(sdist): def run(self):", "open(js_file, 'w') as f: f.write(';(function(){\\n%s\\n})();' % '\\n'.join(fdata)) class bdist_egg_command(bdist_egg): def", "install_requires=install_requires, extras_require=extras, package_data={'': ['slybot/splash-script-combined.js']}, include_package_data=True, cmdclass={ 'bdist_egg': bdist_egg_command, 'sdist': sdist_command", "('waitAsync.js', 'perform_actions.js') fdata = [] for fname in files: with", "fname in files: with open(join(base_path, fname)) as f: fdata.append(f.read()) js_file", "with open(join(base_path, fname)) as f: fdata.append(f.read()) js_file = abspath(join(root, 'slybot',", "for fname in files: with open(join(base_path, fname)) as f: fdata.append(f.read())", "= abspath(join(root, '..', 'splash_utils')) if not exists(base_path): base_path = abspath(join(root,", "'jsonschema', 'dateparser', 'scrapyjs', 'page_finder', 'six'] extras = { 'tests': ['nose',", "'sdist': sdist_command }, classifiers=[ 'Development Status :: 4 - Beta',", "extras = { 'tests': ['nose', 'nose-timer'], 'clustering': ['page_clustering'] } setup(name='slybot',", "'perform_actions.js') fdata = [] for fname in files: with open(join(base_path,", "import join, abspath, dirname, exists from slybot import __version__ from", "'loginform', 'lxml', 'jsonschema', 'dateparser', 'scrapyjs', 'page_finder', 'six'] extras = {", "'tests': ['nose', 'nose-timer'], 'clustering': ['page_clustering'] } setup(name='slybot', version=__version__, license='BSD', description='Slybot", ":: OSI Approved :: BSD License', 'Operating System :: OS", "root = abspath(dirname(__file__)) base_path = abspath(join(root, '..', 'splash_utils')) if not", "'bdist_egg': bdist_egg_command, 'sdist': sdist_command }, classifiers=[ 'Development Status :: 4", "join, abspath, dirname, exists from slybot import __version__ from setuptools", "exists from slybot import __version__ from setuptools import setup, find_packages", "'slybot', 'splash-script-combined.js')) with open(js_file, 'w') as f: f.write(';(function(){\\n%s\\n})();' % '\\n'.join(fdata))", "System :: OS Independent', 'Programming Language :: Python', 'Programming Language", "base_path = abspath(join(root, '..', 'slyd', 'splash_utils')) files = ('waitAsync.js', 'perform_actions.js')", "bdist_egg.run(self) class sdist_command(sdist): def run(self): build_js() sdist.run(self) install_requires = ['Scrapy',", "packages=find_packages(exclude=('tests', 'tests.*')), platforms=['Any'], scripts=['bin/slybot', 'bin/portiacrawl'], install_requires=install_requires, extras_require=extras, package_data={'': ['slybot/splash-script-combined.js']}, include_package_data=True,", "js_file = abspath(join(root, 'slybot', 'splash-script-combined.js')) with open(js_file, 'w') as f:", "Language :: Python :: 2', 'Programming Language :: Python ::" ]
[ "i==-1 else 2)) dn_layer = self.make_group_layer(nf, nb, stride=2) self.add_module(f\"darknet_{i}\", dn_layer)", "1024], 1024, anchors_per_region*(5+num_classes)) self.yolo_0 = YoloLayer(anchors=[(116., 90.), (156., 198.), (373.,", "self.yolo_1 = YoloLayer(anchors=[(30., 61.), (62., 45.), (59., 119.)], stride=16, num_classes=num_classes)", "in range(num_blocks): layers.append(DarknetBlock(ch_in*2)) return nn.Sequential(*layers) def forward(self, x): y =", "def forward(self, x): y = [self.base(x)] for l in self.layers:", "xb): x, y0 = self.yolo_0_pre(xb[-1]) x = self.yolo_1_c(x) x =", "= [self.base(x)] for l in self.layers: y.append(l(y[-1])) return y class", "filters_list, in_filters, out_filters): super().__init__() self.branch = nn.ModuleList([ ConvBN(in_filters, filters_list[0], 1),", "num_classes=num_classes) def get_loss_layers(self): return [self.yolo_0, self.yolo_1, self.yolo_2] def forward_yolo(self, xb):", "mode='nearest')(x) x = torch.cat([x, xb[-3]], 1) x, y2 = self.yolo_2_prep(x)", "512+256, anchors_per_region*(5+num_classes)) self.yolo_1 = YoloLayer(anchors=[(30., 61.), (62., 45.), (59., 119.)],", "Backbone and helper modules class DarknetBlock(nn.Module): def __init__(self, ch_in): super().__init__()", "kernel_size=3), ConvBN(filters_list[1], filters_list[0], kernel_size=1), ConvBN(filters_list[0], filters_list[1], kernel_size=3), ConvBN(filters_list[1], filters_list[0], kernel_size=1),])", "super().__init__() self.branch = nn.ModuleList([ ConvBN(in_filters, filters_list[0], 1), ConvBN(filters_list[0], filters_list[1], kernel_size=3),", "filters_list[1], kernel_size=3), ConvBN(filters_list[1], filters_list[0], kernel_size=1), ConvBN(filters_list[0], filters_list[1], kernel_size=3), ConvBN(filters_list[1], filters_list[0],", "start_nf self.base = ConvBN(3, nf, kernel_size=3, stride=1) #, padding=1) self.layers", "y = [self.base(x)] for l in self.layers: y.append(l(y[-1])) return y", "__init__(self, filters_list, in_filters, out_filters): super().__init__() self.branch = nn.ModuleList([ ConvBN(in_filters, filters_list[0],", "kernel_size=1), ConvBN(filters_list[0], filters_list[1], kernel_size=3), ConvBN(filters_list[1], filters_list[0], kernel_size=1),]) self.for_yolo = nn.ModuleList([", "self.yolo_1_prep(x) x = self.yolo_2_c(x) x = nn.Upsample(scale_factor=2, mode='nearest')(x) x =", "= self.yolo_1_prep(x) x = self.yolo_2_c(x) x = nn.Upsample(scale_factor=2, mode='nearest')(x) x", "Yolov3UpsamplePrep([256, 512], 512+256, anchors_per_region*(5+num_classes)) self.yolo_1 = YoloLayer(anchors=[(30., 61.), (62., 45.),", "return self.conv2(self.conv1(x)) + x class Darknet(nn.Module): def __init__(self, num_blocks, start_nf=32):", "= self.yolo_1_c(x) x = nn.Upsample(scale_factor=2, mode='nearest')(x) x = torch.cat([x, xb[-2]],", "self.yolo_2_c(x) x = nn.Upsample(scale_factor=2, mode='nearest')(x) x = torch.cat([x, xb[-3]], 1)", "= self.make_group_layer(nf, nb, stride=2) self.add_module(f\"darknet_{i}\", dn_layer) self.layers.append(dn_layer) nf *= 2", "x): for m in self.branch: x = m(x) branch_out =", "1), ConvBN(filters_list[0], filters_list[1], kernel_size=3), ConvBN(filters_list[1], filters_list[0], kernel_size=1), ConvBN(filters_list[0], filters_list[1], kernel_size=3),", "self.yolo_0_pre = Yolov3UpsamplePrep([512, 1024], 1024, anchors_per_region*(5+num_classes)) self.yolo_0 = YoloLayer(anchors=[(116., 90.),", "= nn.ModuleList([ ConvBN(in_filters, filters_list[0], 1), ConvBN(filters_list[0], filters_list[1], kernel_size=3), ConvBN(filters_list[1], filters_list[0],", "for i, nb in enumerate(num_blocks): # dn_layer = make_group_layer(nf, nb,", "= x for m in self.for_yolo: x = m(x) return", "ConvBN(filters_list[1], filters_list[0], kernel_size=1),]) self.for_yolo = nn.ModuleList([ ConvBN(filters_list[0], filters_list[1], kernel_size=3), nn.Conv2d(filters_list[1],", "in enumerate(num_blocks): # dn_layer = make_group_layer(nf, nb, stride=(1 if i==-1", "256], 256+128, anchors_per_region*(5+num_classes)) self.yolo_2 = YoloLayer(anchors=[(10., 13.), (16., 30.), (33.,", "num_blocks, start_nf=32): super().__init__() nf = start_nf self.base = ConvBN(3, nf,", "return [self.yolo_0, self.yolo_1, self.yolo_2] def forward_yolo(self, xb): x, y0 =", "ConvBN(ch_hid, ch_in, kernel_size=3, stride=1, padding=1) def forward(self, x): return self.conv2(self.conv1(x))", "1) self.yolo_2_prep = Yolov3UpsamplePrep([128, 256], 256+128, anchors_per_region*(5+num_classes)) self.yolo_2 = YoloLayer(anchors=[(10.,", "= self.yolo_2_c(x) x = nn.Upsample(scale_factor=2, mode='nearest')(x) x = torch.cat([x, xb[-3]],", "in self.layers: y.append(l(y[-1])) return y class Yolov3UpsamplePrep(nn.Module): def __init__(self, filters_list,", "nn.Sequential(*layers) def forward(self, x): y = [self.base(x)] for l in", "self.yolo_1_c = ConvBN(512, 256, 1) self.yolo_1_prep = Yolov3UpsamplePrep([256, 512], 512+256,", "mode='nearest')(x) x = torch.cat([x, xb[-2]], 1) x, y1 = self.yolo_1_prep(x)", "in self.branch: x = m(x) branch_out = x for m", "stride=2): layers = [ConvBN(ch_in, ch_in*2, stride=stride)] for i in range(num_blocks):", "= nn.ModuleList([ ConvBN(filters_list[0], filters_list[1], kernel_size=3), nn.Conv2d(filters_list[1], out_filters, kernel_size=1, stride=1, padding=0,", "ConvBN(512, 256, 1) self.yolo_1_prep = Yolov3UpsamplePrep([256, 512], 512+256, anchors_per_region*(5+num_classes)) self.yolo_1", "from .yolov3_base import * class Yolov3(Yolov3Base): def __init__(self, num_classes=80): super().__init__()", "num_blocks, stride=2): layers = [ConvBN(ch_in, ch_in*2, stride=stride)] for i in", "1) self.yolo_1_prep = Yolov3UpsamplePrep([256, 512], 512+256, anchors_per_region*(5+num_classes)) self.yolo_1 = YoloLayer(anchors=[(30.,", "__init__(self, ch_in): super().__init__() ch_hid = ch_in//2 self.conv1 = ConvBN(ch_in, ch_hid,", "[ConvBN(ch_in, ch_in*2, stride=stride)] for i in range(num_blocks): layers.append(DarknetBlock(ch_in*2)) return nn.Sequential(*layers)", "ch_in, num_blocks, stride=2): layers = [ConvBN(ch_in, ch_in*2, stride=stride)] for i", "def get_loss_layers(self): return [self.yolo_0, self.yolo_1, self.yolo_2] def forward_yolo(self, xb): x,", "self.conv2 = ConvBN(ch_hid, ch_in, kernel_size=3, stride=1, padding=1) def forward(self, x):", "y2] ################################################################### ## Backbone and helper modules class DarknetBlock(nn.Module): def", "and helper modules class DarknetBlock(nn.Module): def __init__(self, ch_in): super().__init__() ch_hid", "self.branch = nn.ModuleList([ ConvBN(in_filters, filters_list[0], 1), ConvBN(filters_list[0], filters_list[1], kernel_size=3), ConvBN(filters_list[1],", "# dn_layer = make_group_layer(nf, nb, stride=(1 if i==-1 else 2))", "forward(self, x): y = [self.base(x)] for l in self.layers: y.append(l(y[-1]))", "def make_group_layer(self, ch_in, num_blocks, stride=2): layers = [ConvBN(ch_in, ch_in*2, stride=stride)]", "## Backbone and helper modules class DarknetBlock(nn.Module): def __init__(self, ch_in):", "ConvBN(filters_list[0], filters_list[1], kernel_size=3), ConvBN(filters_list[1], filters_list[0], kernel_size=1),]) self.for_yolo = nn.ModuleList([ ConvBN(filters_list[0],", "= nn.Upsample(scale_factor=2, mode='nearest')(x) x = torch.cat([x, xb[-3]], 1) x, y2", "Darknet([1,2,8,8,4]) anchors_per_region = 3 self.yolo_0_pre = Yolov3UpsamplePrep([512, 1024], 1024, anchors_per_region*(5+num_classes))", "def forward(self, x): for m in self.branch: x = m(x)", "x): return self.conv2(self.conv1(x)) + x class Darknet(nn.Module): def __init__(self, num_blocks,", "y.append(l(y[-1])) return y class Yolov3UpsamplePrep(nn.Module): def __init__(self, filters_list, in_filters, out_filters):", "kernel_size=3), nn.Conv2d(filters_list[1], out_filters, kernel_size=1, stride=1, padding=0, bias=True)]) def forward(self, x):", "= Yolov3UpsamplePrep([256, 512], 512+256, anchors_per_region*(5+num_classes)) self.yolo_1 = YoloLayer(anchors=[(30., 61.), (62.,", "import * from .yolov3_base import * class Yolov3(Yolov3Base): def __init__(self,", "padding=0, bias=True)]) def forward(self, x): for m in self.branch: x", "nn.ModuleList([ ConvBN(filters_list[0], filters_list[1], kernel_size=3), nn.Conv2d(filters_list[1], out_filters, kernel_size=1, stride=1, padding=0, bias=True)])", "branch_out = x for m in self.for_yolo: x = m(x)", "helper modules class DarknetBlock(nn.Module): def __init__(self, ch_in): super().__init__() ch_hid =", "stride=stride)] for i in range(num_blocks): layers.append(DarknetBlock(ch_in*2)) return nn.Sequential(*layers) def forward(self,", "= ConvBN(3, nf, kernel_size=3, stride=1) #, padding=1) self.layers = []", "xb[-2]], 1) x, y1 = self.yolo_1_prep(x) x = self.yolo_2_c(x) x", "x, y1 = self.yolo_1_prep(x) x = self.yolo_2_c(x) x = nn.Upsample(scale_factor=2,", "y class Yolov3UpsamplePrep(nn.Module): def __init__(self, filters_list, in_filters, out_filters): super().__init__() self.branch", "for m in self.branch: x = m(x) branch_out = x", "torch.nn as nn from .yolo_layer import * from .yolov3_base import", "if i==-1 else 2)) dn_layer = self.make_group_layer(nf, nb, stride=2) self.add_module(f\"darknet_{i}\",", "= Yolov3UpsamplePrep([512, 1024], 1024, anchors_per_region*(5+num_classes)) self.yolo_0 = YoloLayer(anchors=[(116., 90.), (156.,", "return nn.Sequential(*layers) def forward(self, x): y = [self.base(x)] for l", "nf = start_nf self.base = ConvBN(3, nf, kernel_size=3, stride=1) #,", "<filename>yolov3.py import torch import torch.nn as nn from .yolo_layer import", "as nn from .yolo_layer import * from .yolov3_base import *", "def forward_yolo(self, xb): x, y0 = self.yolo_0_pre(xb[-1]) x = self.yolo_1_c(x)", "x, y2 = self.yolo_2_prep(x) return [y0, y1, y2] ################################################################### ##", "= ConvBN(ch_in, ch_hid, kernel_size=1, stride=1, padding=0) self.conv2 = ConvBN(ch_hid, ch_in,", "stride=1, padding=1) def forward(self, x): return self.conv2(self.conv1(x)) + x class", "nf *= 2 def make_group_layer(self, ch_in, num_blocks, stride=2): layers =", "ConvBN(256, 128, 1) self.yolo_2_prep = Yolov3UpsamplePrep([128, 256], 256+128, anchors_per_region*(5+num_classes)) self.yolo_2", "ConvBN(filters_list[0], filters_list[1], kernel_size=3), ConvBN(filters_list[1], filters_list[0], kernel_size=1), ConvBN(filters_list[0], filters_list[1], kernel_size=3), ConvBN(filters_list[1],", "forward_yolo(self, xb): x, y0 = self.yolo_0_pre(xb[-1]) x = self.yolo_1_c(x) x", "def __init__(self, num_classes=80): super().__init__() self.backbone = Darknet([1,2,8,8,4]) anchors_per_region = 3", "nb in enumerate(num_blocks): # dn_layer = make_group_layer(nf, nb, stride=(1 if", "__init__(self, num_classes=80): super().__init__() self.backbone = Darknet([1,2,8,8,4]) anchors_per_region = 3 self.yolo_0_pre", "return y class Yolov3UpsamplePrep(nn.Module): def __init__(self, filters_list, in_filters, out_filters): super().__init__()", "filters_list[0], 1), ConvBN(filters_list[0], filters_list[1], kernel_size=3), ConvBN(filters_list[1], filters_list[0], kernel_size=1), ConvBN(filters_list[0], filters_list[1],", "30.), (33., 23.)], stride=8, num_classes=num_classes) def get_loss_layers(self): return [self.yolo_0, self.yolo_1,", "= Yolov3UpsamplePrep([128, 256], 256+128, anchors_per_region*(5+num_classes)) self.yolo_2 = YoloLayer(anchors=[(10., 13.), (16.,", "= ConvBN(ch_hid, ch_in, kernel_size=3, stride=1, padding=1) def forward(self, x): return", "x = m(x) branch_out = x for m in self.for_yolo:", "= ch_in//2 self.conv1 = ConvBN(ch_in, ch_hid, kernel_size=1, stride=1, padding=0) self.conv2", "super().__init__() nf = start_nf self.base = ConvBN(3, nf, kernel_size=3, stride=1)", "YoloLayer(anchors=[(116., 90.), (156., 198.), (373., 326.)], stride=32, num_classes=num_classes) self.yolo_1_c =", "326.)], stride=32, num_classes=num_classes) self.yolo_1_c = ConvBN(512, 256, 1) self.yolo_1_prep =", "(33., 23.)], stride=8, num_classes=num_classes) def get_loss_layers(self): return [self.yolo_0, self.yolo_1, self.yolo_2]", "#, padding=1) self.layers = [] for i, nb in enumerate(num_blocks):", "1) x, y2 = self.yolo_2_prep(x) return [y0, y1, y2] ###################################################################", "x): y = [self.base(x)] for l in self.layers: y.append(l(y[-1])) return", "Yolov3UpsamplePrep([128, 256], 256+128, anchors_per_region*(5+num_classes)) self.yolo_2 = YoloLayer(anchors=[(10., 13.), (16., 30.),", "= [ConvBN(ch_in, ch_in*2, stride=stride)] for i in range(num_blocks): layers.append(DarknetBlock(ch_in*2)) return", "for l in self.layers: y.append(l(y[-1])) return y class Yolov3UpsamplePrep(nn.Module): def", "filters_list[1], kernel_size=3), ConvBN(filters_list[1], filters_list[0], kernel_size=1),]) self.for_yolo = nn.ModuleList([ ConvBN(filters_list[0], filters_list[1],", "anchors_per_region*(5+num_classes)) self.yolo_1 = YoloLayer(anchors=[(30., 61.), (62., 45.), (59., 119.)], stride=16,", "################################################################### ## Backbone and helper modules class DarknetBlock(nn.Module): def __init__(self,", ".yolov3_base import * class Yolov3(Yolov3Base): def __init__(self, num_classes=80): super().__init__() self.backbone", "= torch.cat([x, xb[-3]], 1) x, y2 = self.yolo_2_prep(x) return [y0,", "nn from .yolo_layer import * from .yolov3_base import * class", "import torch.nn as nn from .yolo_layer import * from .yolov3_base", "stride=1, padding=0, bias=True)]) def forward(self, x): for m in self.branch:", "ch_in, kernel_size=3, stride=1, padding=1) def forward(self, x): return self.conv2(self.conv1(x)) +", "x = self.yolo_2_c(x) x = nn.Upsample(scale_factor=2, mode='nearest')(x) x = torch.cat([x,", "1) x, y1 = self.yolo_1_prep(x) x = self.yolo_2_c(x) x =", "self.conv1 = ConvBN(ch_in, ch_hid, kernel_size=1, stride=1, padding=0) self.conv2 = ConvBN(ch_hid,", "m in self.branch: x = m(x) branch_out = x for", "(62., 45.), (59., 119.)], stride=16, num_classes=num_classes) self.yolo_2_c = ConvBN(256, 128,", "__init__(self, num_blocks, start_nf=32): super().__init__() nf = start_nf self.base = ConvBN(3,", "self.yolo_2_prep = Yolov3UpsamplePrep([128, 256], 256+128, anchors_per_region*(5+num_classes)) self.yolo_2 = YoloLayer(anchors=[(10., 13.),", "anchors_per_region*(5+num_classes)) self.yolo_2 = YoloLayer(anchors=[(10., 13.), (16., 30.), (33., 23.)], stride=8,", "self.yolo_2_c = ConvBN(256, 128, 1) self.yolo_2_prep = Yolov3UpsamplePrep([128, 256], 256+128,", "torch.cat([x, xb[-2]], 1) x, y1 = self.yolo_1_prep(x) x = self.yolo_2_c(x)", "= m(x) branch_out = x for m in self.for_yolo: x", "nb, stride=(1 if i==-1 else 2)) dn_layer = self.make_group_layer(nf, nb,", "dn_layer) self.layers.append(dn_layer) nf *= 2 def make_group_layer(self, ch_in, num_blocks, stride=2):", "ConvBN(filters_list[0], filters_list[1], kernel_size=3), nn.Conv2d(filters_list[1], out_filters, kernel_size=1, stride=1, padding=0, bias=True)]) def", "Darknet(nn.Module): def __init__(self, num_blocks, start_nf=32): super().__init__() nf = start_nf self.base", "stride=16, num_classes=num_classes) self.yolo_2_c = ConvBN(256, 128, 1) self.yolo_2_prep = Yolov3UpsamplePrep([128,", "stride=2) self.add_module(f\"darknet_{i}\", dn_layer) self.layers.append(dn_layer) nf *= 2 def make_group_layer(self, ch_in,", "= ConvBN(256, 128, 1) self.yolo_2_prep = Yolov3UpsamplePrep([128, 256], 256+128, anchors_per_region*(5+num_classes))", "*= 2 def make_group_layer(self, ch_in, num_blocks, stride=2): layers = [ConvBN(ch_in,", "filters_list[0], kernel_size=1), ConvBN(filters_list[0], filters_list[1], kernel_size=3), ConvBN(filters_list[1], filters_list[0], kernel_size=1),]) self.for_yolo =", "kernel_size=3), ConvBN(filters_list[1], filters_list[0], kernel_size=1),]) self.for_yolo = nn.ModuleList([ ConvBN(filters_list[0], filters_list[1], kernel_size=3),", "torch.cat([x, xb[-3]], 1) x, y2 = self.yolo_2_prep(x) return [y0, y1,", "def __init__(self, filters_list, in_filters, out_filters): super().__init__() self.branch = nn.ModuleList([ ConvBN(in_filters,", "class Yolov3UpsamplePrep(nn.Module): def __init__(self, filters_list, in_filters, out_filters): super().__init__() self.branch =", "class DarknetBlock(nn.Module): def __init__(self, ch_in): super().__init__() ch_hid = ch_in//2 self.conv1", "(59., 119.)], stride=16, num_classes=num_classes) self.yolo_2_c = ConvBN(256, 128, 1) self.yolo_2_prep", "* class Yolov3(Yolov3Base): def __init__(self, num_classes=80): super().__init__() self.backbone = Darknet([1,2,8,8,4])", "= torch.cat([x, xb[-2]], 1) x, y1 = self.yolo_1_prep(x) x =", "3 self.yolo_0_pre = Yolov3UpsamplePrep([512, 1024], 1024, anchors_per_region*(5+num_classes)) self.yolo_0 = YoloLayer(anchors=[(116.,", "in_filters, out_filters): super().__init__() self.branch = nn.ModuleList([ ConvBN(in_filters, filters_list[0], 1), ConvBN(filters_list[0],", "self.yolo_1_prep = Yolov3UpsamplePrep([256, 512], 512+256, anchors_per_region*(5+num_classes)) self.yolo_1 = YoloLayer(anchors=[(30., 61.),", "y0 = self.yolo_0_pre(xb[-1]) x = self.yolo_1_c(x) x = nn.Upsample(scale_factor=2, mode='nearest')(x)", "nn.Upsample(scale_factor=2, mode='nearest')(x) x = torch.cat([x, xb[-3]], 1) x, y2 =", "self.add_module(f\"darknet_{i}\", dn_layer) self.layers.append(dn_layer) nf *= 2 def make_group_layer(self, ch_in, num_blocks,", "1024, anchors_per_region*(5+num_classes)) self.yolo_0 = YoloLayer(anchors=[(116., 90.), (156., 198.), (373., 326.)],", "anchors_per_region*(5+num_classes)) self.yolo_0 = YoloLayer(anchors=[(116., 90.), (156., 198.), (373., 326.)], stride=32,", "self.yolo_2 = YoloLayer(anchors=[(10., 13.), (16., 30.), (33., 23.)], stride=8, num_classes=num_classes)", "for i in range(num_blocks): layers.append(DarknetBlock(ch_in*2)) return nn.Sequential(*layers) def forward(self, x):", "x, y0 = self.yolo_0_pre(xb[-1]) x = self.yolo_1_c(x) x = nn.Upsample(scale_factor=2,", "return [y0, y1, y2] ################################################################### ## Backbone and helper modules", "ConvBN(3, nf, kernel_size=3, stride=1) #, padding=1) self.layers = [] for", "dn_layer = self.make_group_layer(nf, nb, stride=2) self.add_module(f\"darknet_{i}\", dn_layer) self.layers.append(dn_layer) nf *=", "nn.Conv2d(filters_list[1], out_filters, kernel_size=1, stride=1, padding=0, bias=True)]) def forward(self, x): for", "out_filters, kernel_size=1, stride=1, padding=0, bias=True)]) def forward(self, x): for m", "self.base = ConvBN(3, nf, kernel_size=3, stride=1) #, padding=1) self.layers =", "class Yolov3(Yolov3Base): def __init__(self, num_classes=80): super().__init__() self.backbone = Darknet([1,2,8,8,4]) anchors_per_region", "self.yolo_1_c(x) x = nn.Upsample(scale_factor=2, mode='nearest')(x) x = torch.cat([x, xb[-2]], 1)", "= YoloLayer(anchors=[(10., 13.), (16., 30.), (33., 23.)], stride=8, num_classes=num_classes) def", "forward(self, x): return self.conv2(self.conv1(x)) + x class Darknet(nn.Module): def __init__(self,", "enumerate(num_blocks): # dn_layer = make_group_layer(nf, nb, stride=(1 if i==-1 else", "kernel_size=1, stride=1, padding=0, bias=True)]) def forward(self, x): for m in", "self.layers = [] for i, nb in enumerate(num_blocks): # dn_layer", "i, nb in enumerate(num_blocks): # dn_layer = make_group_layer(nf, nb, stride=(1", "num_classes=80): super().__init__() self.backbone = Darknet([1,2,8,8,4]) anchors_per_region = 3 self.yolo_0_pre =", "ConvBN(ch_in, ch_hid, kernel_size=1, stride=1, padding=0) self.conv2 = ConvBN(ch_hid, ch_in, kernel_size=3,", "self.yolo_0_pre(xb[-1]) x = self.yolo_1_c(x) x = nn.Upsample(scale_factor=2, mode='nearest')(x) x =", "= nn.Upsample(scale_factor=2, mode='nearest')(x) x = torch.cat([x, xb[-2]], 1) x, y1", "Yolov3UpsamplePrep([512, 1024], 1024, anchors_per_region*(5+num_classes)) self.yolo_0 = YoloLayer(anchors=[(116., 90.), (156., 198.),", "128, 1) self.yolo_2_prep = Yolov3UpsamplePrep([128, 256], 256+128, anchors_per_region*(5+num_classes)) self.yolo_2 =", "layers = [ConvBN(ch_in, ch_in*2, stride=stride)] for i in range(num_blocks): layers.append(DarknetBlock(ch_in*2))", "make_group_layer(nf, nb, stride=(1 if i==-1 else 2)) dn_layer = self.make_group_layer(nf,", "layers.append(DarknetBlock(ch_in*2)) return nn.Sequential(*layers) def forward(self, x): y = [self.base(x)] for", "YoloLayer(anchors=[(30., 61.), (62., 45.), (59., 119.)], stride=16, num_classes=num_classes) self.yolo_2_c =", "ch_in*2, stride=stride)] for i in range(num_blocks): layers.append(DarknetBlock(ch_in*2)) return nn.Sequential(*layers) def", "num_classes=num_classes) self.yolo_1_c = ConvBN(512, 256, 1) self.yolo_1_prep = Yolov3UpsamplePrep([256, 512],", "y1, y2] ################################################################### ## Backbone and helper modules class DarknetBlock(nn.Module):", "filters_list[0], kernel_size=1),]) self.for_yolo = nn.ModuleList([ ConvBN(filters_list[0], filters_list[1], kernel_size=3), nn.Conv2d(filters_list[1], out_filters,", "bias=True)]) def forward(self, x): for m in self.branch: x =", "padding=1) self.layers = [] for i, nb in enumerate(num_blocks): #", "198.), (373., 326.)], stride=32, num_classes=num_classes) self.yolo_1_c = ConvBN(512, 256, 1)", "get_loss_layers(self): return [self.yolo_0, self.yolo_1, self.yolo_2] def forward_yolo(self, xb): x, y0", "YoloLayer(anchors=[(10., 13.), (16., 30.), (33., 23.)], stride=8, num_classes=num_classes) def get_loss_layers(self):", "padding=1) def forward(self, x): return self.conv2(self.conv1(x)) + x class Darknet(nn.Module):", "= 3 self.yolo_0_pre = Yolov3UpsamplePrep([512, 1024], 1024, anchors_per_region*(5+num_classes)) self.yolo_0 =", "= self.yolo_2_prep(x) return [y0, y1, y2] ################################################################### ## Backbone and", "self.yolo_2] def forward_yolo(self, xb): x, y0 = self.yolo_0_pre(xb[-1]) x =", "2 def make_group_layer(self, ch_in, num_blocks, stride=2): layers = [ConvBN(ch_in, ch_in*2,", "Yolov3(Yolov3Base): def __init__(self, num_classes=80): super().__init__() self.backbone = Darknet([1,2,8,8,4]) anchors_per_region =", "256+128, anchors_per_region*(5+num_classes)) self.yolo_2 = YoloLayer(anchors=[(10., 13.), (16., 30.), (33., 23.)],", "self.for_yolo = nn.ModuleList([ ConvBN(filters_list[0], filters_list[1], kernel_size=3), nn.Conv2d(filters_list[1], out_filters, kernel_size=1, stride=1,", "x class Darknet(nn.Module): def __init__(self, num_blocks, start_nf=32): super().__init__() nf =", "x = nn.Upsample(scale_factor=2, mode='nearest')(x) x = torch.cat([x, xb[-2]], 1) x,", "45.), (59., 119.)], stride=16, num_classes=num_classes) self.yolo_2_c = ConvBN(256, 128, 1)", "13.), (16., 30.), (33., 23.)], stride=8, num_classes=num_classes) def get_loss_layers(self): return", "self.yolo_1, self.yolo_2] def forward_yolo(self, xb): x, y0 = self.yolo_0_pre(xb[-1]) x", "num_classes=num_classes) self.yolo_2_c = ConvBN(256, 128, 1) self.yolo_2_prep = Yolov3UpsamplePrep([128, 256],", "self.backbone = Darknet([1,2,8,8,4]) anchors_per_region = 3 self.yolo_0_pre = Yolov3UpsamplePrep([512, 1024],", "(373., 326.)], stride=32, num_classes=num_classes) self.yolo_1_c = ConvBN(512, 256, 1) self.yolo_1_prep", "= self.yolo_0_pre(xb[-1]) x = self.yolo_1_c(x) x = nn.Upsample(scale_factor=2, mode='nearest')(x) x", "padding=0) self.conv2 = ConvBN(ch_hid, ch_in, kernel_size=3, stride=1, padding=1) def forward(self,", "kernel_size=3, stride=1, padding=1) def forward(self, x): return self.conv2(self.conv1(x)) + x", "Yolov3UpsamplePrep(nn.Module): def __init__(self, filters_list, in_filters, out_filters): super().__init__() self.branch = nn.ModuleList([", "kernel_size=1),]) self.for_yolo = nn.ModuleList([ ConvBN(filters_list[0], filters_list[1], kernel_size=3), nn.Conv2d(filters_list[1], out_filters, kernel_size=1,", "forward(self, x): for m in self.branch: x = m(x) branch_out", "filters_list[1], kernel_size=3), nn.Conv2d(filters_list[1], out_filters, kernel_size=1, stride=1, padding=0, bias=True)]) def forward(self,", "nb, stride=2) self.add_module(f\"darknet_{i}\", dn_layer) self.layers.append(dn_layer) nf *= 2 def make_group_layer(self,", "nn.Upsample(scale_factor=2, mode='nearest')(x) x = torch.cat([x, xb[-2]], 1) x, y1 =", "range(num_blocks): layers.append(DarknetBlock(ch_in*2)) return nn.Sequential(*layers) def forward(self, x): y = [self.base(x)]", "for m in self.for_yolo: x = m(x) return branch_out, x", "= [] for i, nb in enumerate(num_blocks): # dn_layer =", "l in self.layers: y.append(l(y[-1])) return y class Yolov3UpsamplePrep(nn.Module): def __init__(self,", "(156., 198.), (373., 326.)], stride=32, num_classes=num_classes) self.yolo_1_c = ConvBN(512, 256,", "x = torch.cat([x, xb[-3]], 1) x, y2 = self.yolo_2_prep(x) return", "ch_in//2 self.conv1 = ConvBN(ch_in, ch_hid, kernel_size=1, stride=1, padding=0) self.conv2 =", "ConvBN(in_filters, filters_list[0], 1), ConvBN(filters_list[0], filters_list[1], kernel_size=3), ConvBN(filters_list[1], filters_list[0], kernel_size=1), ConvBN(filters_list[0],", "self.layers: y.append(l(y[-1])) return y class Yolov3UpsamplePrep(nn.Module): def __init__(self, filters_list, in_filters,", "* from .yolov3_base import * class Yolov3(Yolov3Base): def __init__(self, num_classes=80):", "[] for i, nb in enumerate(num_blocks): # dn_layer = make_group_layer(nf,", "import * class Yolov3(Yolov3Base): def __init__(self, num_classes=80): super().__init__() self.backbone =", "stride=32, num_classes=num_classes) self.yolo_1_c = ConvBN(512, 256, 1) self.yolo_1_prep = Yolov3UpsamplePrep([256,", "self.conv2(self.conv1(x)) + x class Darknet(nn.Module): def __init__(self, num_blocks, start_nf=32): super().__init__()", "stride=8, num_classes=num_classes) def get_loss_layers(self): return [self.yolo_0, self.yolo_1, self.yolo_2] def forward_yolo(self,", "def forward(self, x): return self.conv2(self.conv1(x)) + x class Darknet(nn.Module): def", "else 2)) dn_layer = self.make_group_layer(nf, nb, stride=2) self.add_module(f\"darknet_{i}\", dn_layer) self.layers.append(dn_layer)", "nn.ModuleList([ ConvBN(in_filters, filters_list[0], 1), ConvBN(filters_list[0], filters_list[1], kernel_size=3), ConvBN(filters_list[1], filters_list[0], kernel_size=1),", "= start_nf self.base = ConvBN(3, nf, kernel_size=3, stride=1) #, padding=1)", "m(x) branch_out = x for m in self.for_yolo: x =", "61.), (62., 45.), (59., 119.)], stride=16, num_classes=num_classes) self.yolo_2_c = ConvBN(256,", "def __init__(self, ch_in): super().__init__() ch_hid = ch_in//2 self.conv1 = ConvBN(ch_in,", "nf, kernel_size=3, stride=1) #, padding=1) self.layers = [] for i,", "y2 = self.yolo_2_prep(x) return [y0, y1, y2] ################################################################### ## Backbone", "stride=(1 if i==-1 else 2)) dn_layer = self.make_group_layer(nf, nb, stride=2)", "x = nn.Upsample(scale_factor=2, mode='nearest')(x) x = torch.cat([x, xb[-3]], 1) x,", "def __init__(self, num_blocks, start_nf=32): super().__init__() nf = start_nf self.base =", "(16., 30.), (33., 23.)], stride=8, num_classes=num_classes) def get_loss_layers(self): return [self.yolo_0,", "= ConvBN(512, 256, 1) self.yolo_1_prep = Yolov3UpsamplePrep([256, 512], 512+256, anchors_per_region*(5+num_classes))", "119.)], stride=16, num_classes=num_classes) self.yolo_2_c = ConvBN(256, 128, 1) self.yolo_2_prep =", ".yolo_layer import * from .yolov3_base import * class Yolov3(Yolov3Base): def", "ch_in): super().__init__() ch_hid = ch_in//2 self.conv1 = ConvBN(ch_in, ch_hid, kernel_size=1,", "ch_hid, kernel_size=1, stride=1, padding=0) self.conv2 = ConvBN(ch_hid, ch_in, kernel_size=3, stride=1,", "[y0, y1, y2] ################################################################### ## Backbone and helper modules class", "+ x class Darknet(nn.Module): def __init__(self, num_blocks, start_nf=32): super().__init__() nf", "512], 512+256, anchors_per_region*(5+num_classes)) self.yolo_1 = YoloLayer(anchors=[(30., 61.), (62., 45.), (59.,", "DarknetBlock(nn.Module): def __init__(self, ch_in): super().__init__() ch_hid = ch_in//2 self.conv1 =", "= make_group_layer(nf, nb, stride=(1 if i==-1 else 2)) dn_layer =", "[self.base(x)] for l in self.layers: y.append(l(y[-1])) return y class Yolov3UpsamplePrep(nn.Module):", "23.)], stride=8, num_classes=num_classes) def get_loss_layers(self): return [self.yolo_0, self.yolo_1, self.yolo_2] def", "x = torch.cat([x, xb[-2]], 1) x, y1 = self.yolo_1_prep(x) x", "dn_layer = make_group_layer(nf, nb, stride=(1 if i==-1 else 2)) dn_layer", "y1 = self.yolo_1_prep(x) x = self.yolo_2_c(x) x = nn.Upsample(scale_factor=2, mode='nearest')(x)", "anchors_per_region = 3 self.yolo_0_pre = Yolov3UpsamplePrep([512, 1024], 1024, anchors_per_region*(5+num_classes)) self.yolo_0", "super().__init__() self.backbone = Darknet([1,2,8,8,4]) anchors_per_region = 3 self.yolo_0_pre = Yolov3UpsamplePrep([512,", "self.layers.append(dn_layer) nf *= 2 def make_group_layer(self, ch_in, num_blocks, stride=2): layers", "stride=1) #, padding=1) self.layers = [] for i, nb in", "= Darknet([1,2,8,8,4]) anchors_per_region = 3 self.yolo_0_pre = Yolov3UpsamplePrep([512, 1024], 1024,", "[self.yolo_0, self.yolo_1, self.yolo_2] def forward_yolo(self, xb): x, y0 = self.yolo_0_pre(xb[-1])", "x = self.yolo_1_c(x) x = nn.Upsample(scale_factor=2, mode='nearest')(x) x = torch.cat([x,", "class Darknet(nn.Module): def __init__(self, num_blocks, start_nf=32): super().__init__() nf = start_nf", "kernel_size=3, stride=1) #, padding=1) self.layers = [] for i, nb", "torch import torch.nn as nn from .yolo_layer import * from", "= YoloLayer(anchors=[(116., 90.), (156., 198.), (373., 326.)], stride=32, num_classes=num_classes) self.yolo_1_c", "2)) dn_layer = self.make_group_layer(nf, nb, stride=2) self.add_module(f\"darknet_{i}\", dn_layer) self.layers.append(dn_layer) nf", "ConvBN(filters_list[1], filters_list[0], kernel_size=1), ConvBN(filters_list[0], filters_list[1], kernel_size=3), ConvBN(filters_list[1], filters_list[0], kernel_size=1),]) self.for_yolo", "out_filters): super().__init__() self.branch = nn.ModuleList([ ConvBN(in_filters, filters_list[0], 1), ConvBN(filters_list[0], filters_list[1],", "self.branch: x = m(x) branch_out = x for m in", "self.yolo_0 = YoloLayer(anchors=[(116., 90.), (156., 198.), (373., 326.)], stride=32, num_classes=num_classes)", "90.), (156., 198.), (373., 326.)], stride=32, num_classes=num_classes) self.yolo_1_c = ConvBN(512,", "kernel_size=1, stride=1, padding=0) self.conv2 = ConvBN(ch_hid, ch_in, kernel_size=3, stride=1, padding=1)", "= YoloLayer(anchors=[(30., 61.), (62., 45.), (59., 119.)], stride=16, num_classes=num_classes) self.yolo_2_c", "make_group_layer(self, ch_in, num_blocks, stride=2): layers = [ConvBN(ch_in, ch_in*2, stride=stride)] for", "ch_hid = ch_in//2 self.conv1 = ConvBN(ch_in, ch_hid, kernel_size=1, stride=1, padding=0)", "256, 1) self.yolo_1_prep = Yolov3UpsamplePrep([256, 512], 512+256, anchors_per_region*(5+num_classes)) self.yolo_1 =", "self.yolo_2_prep(x) return [y0, y1, y2] ################################################################### ## Backbone and helper", "modules class DarknetBlock(nn.Module): def __init__(self, ch_in): super().__init__() ch_hid = ch_in//2", "self.make_group_layer(nf, nb, stride=2) self.add_module(f\"darknet_{i}\", dn_layer) self.layers.append(dn_layer) nf *= 2 def", "start_nf=32): super().__init__() nf = start_nf self.base = ConvBN(3, nf, kernel_size=3,", "stride=1, padding=0) self.conv2 = ConvBN(ch_hid, ch_in, kernel_size=3, stride=1, padding=1) def", "i in range(num_blocks): layers.append(DarknetBlock(ch_in*2)) return nn.Sequential(*layers) def forward(self, x): y", "import torch import torch.nn as nn from .yolo_layer import *", "x for m in self.for_yolo: x = m(x) return branch_out,", "xb[-3]], 1) x, y2 = self.yolo_2_prep(x) return [y0, y1, y2]", "super().__init__() ch_hid = ch_in//2 self.conv1 = ConvBN(ch_in, ch_hid, kernel_size=1, stride=1,", "from .yolo_layer import * from .yolov3_base import * class Yolov3(Yolov3Base):" ]
[ "pytest from modelkit.assets import errors from tests.conftest import skip_unless def", "driver.download_object(\"someasset\", \"somedestination\") assert not os.path.isfile(\"somedestination\") def test_local_driver(local_assetsmanager): local_driver = local_assetsmanager.remote_assets_store.driver", "local_assetsmanager.remote_assets_store.driver _perform_driver_error_object_not_found(local_driver) @skip_unless(\"ENABLE_GCS_TEST\", \"True\") def test_gcs_driver(gcs_assetsmanager): gcs_driver = gcs_assetsmanager.remote_assets_store.driver _perform_driver_error_object_not_found(gcs_driver)", "from modelkit.assets import errors from tests.conftest import skip_unless def _perform_driver_error_object_not_found(driver):", "pytest.raises(errors.ObjectDoesNotExistError): driver.download_object(\"someasset\", \"somedestination\") assert not os.path.isfile(\"somedestination\") def test_local_driver(local_assetsmanager): local_driver =", "@skip_unless(\"ENABLE_GCS_TEST\", \"True\") def test_gcs_driver(gcs_assetsmanager): gcs_driver = gcs_assetsmanager.remote_assets_store.driver _perform_driver_error_object_not_found(gcs_driver) @skip_unless(\"ENABLE_S3_TEST\", \"True\")", "from tests.conftest import skip_unless def _perform_driver_error_object_not_found(driver): with pytest.raises(errors.ObjectDoesNotExistError): driver.download_object(\"someasset\", \"somedestination\")", "test_local_driver(local_assetsmanager): local_driver = local_assetsmanager.remote_assets_store.driver _perform_driver_error_object_not_found(local_driver) @skip_unless(\"ENABLE_GCS_TEST\", \"True\") def test_gcs_driver(gcs_assetsmanager): gcs_driver", "gcs_assetsmanager.remote_assets_store.driver _perform_driver_error_object_not_found(gcs_driver) @skip_unless(\"ENABLE_S3_TEST\", \"True\") def test_s3_driver(s3_assetsmanager): s3_driver = s3_assetsmanager.remote_assets_store.driver _perform_driver_error_object_not_found(s3_driver)", "assert not os.path.isfile(\"somedestination\") def test_local_driver(local_assetsmanager): local_driver = local_assetsmanager.remote_assets_store.driver _perform_driver_error_object_not_found(local_driver) @skip_unless(\"ENABLE_GCS_TEST\",", "\"True\") def test_gcs_driver(gcs_assetsmanager): gcs_driver = gcs_assetsmanager.remote_assets_store.driver _perform_driver_error_object_not_found(gcs_driver) @skip_unless(\"ENABLE_S3_TEST\", \"True\") def", "os import pytest from modelkit.assets import errors from tests.conftest import", "import pytest from modelkit.assets import errors from tests.conftest import skip_unless", "_perform_driver_error_object_not_found(local_driver) @skip_unless(\"ENABLE_GCS_TEST\", \"True\") def test_gcs_driver(gcs_assetsmanager): gcs_driver = gcs_assetsmanager.remote_assets_store.driver _perform_driver_error_object_not_found(gcs_driver) @skip_unless(\"ENABLE_S3_TEST\",", "test_gcs_driver(gcs_assetsmanager): gcs_driver = gcs_assetsmanager.remote_assets_store.driver _perform_driver_error_object_not_found(gcs_driver) @skip_unless(\"ENABLE_S3_TEST\", \"True\") def test_s3_driver(s3_assetsmanager): s3_driver", "local_driver = local_assetsmanager.remote_assets_store.driver _perform_driver_error_object_not_found(local_driver) @skip_unless(\"ENABLE_GCS_TEST\", \"True\") def test_gcs_driver(gcs_assetsmanager): gcs_driver =", "= local_assetsmanager.remote_assets_store.driver _perform_driver_error_object_not_found(local_driver) @skip_unless(\"ENABLE_GCS_TEST\", \"True\") def test_gcs_driver(gcs_assetsmanager): gcs_driver = gcs_assetsmanager.remote_assets_store.driver", "_perform_driver_error_object_not_found(driver): with pytest.raises(errors.ObjectDoesNotExistError): driver.download_object(\"someasset\", \"somedestination\") assert not os.path.isfile(\"somedestination\") def test_local_driver(local_assetsmanager):", "modelkit.assets import errors from tests.conftest import skip_unless def _perform_driver_error_object_not_found(driver): with", "gcs_driver = gcs_assetsmanager.remote_assets_store.driver _perform_driver_error_object_not_found(gcs_driver) @skip_unless(\"ENABLE_S3_TEST\", \"True\") def test_s3_driver(s3_assetsmanager): s3_driver =", "os.path.isfile(\"somedestination\") def test_local_driver(local_assetsmanager): local_driver = local_assetsmanager.remote_assets_store.driver _perform_driver_error_object_not_found(local_driver) @skip_unless(\"ENABLE_GCS_TEST\", \"True\") def", "\"somedestination\") assert not os.path.isfile(\"somedestination\") def test_local_driver(local_assetsmanager): local_driver = local_assetsmanager.remote_assets_store.driver _perform_driver_error_object_not_found(local_driver)", "def test_gcs_driver(gcs_assetsmanager): gcs_driver = gcs_assetsmanager.remote_assets_store.driver _perform_driver_error_object_not_found(gcs_driver) @skip_unless(\"ENABLE_S3_TEST\", \"True\") def test_s3_driver(s3_assetsmanager):", "= gcs_assetsmanager.remote_assets_store.driver _perform_driver_error_object_not_found(gcs_driver) @skip_unless(\"ENABLE_S3_TEST\", \"True\") def test_s3_driver(s3_assetsmanager): s3_driver = s3_assetsmanager.remote_assets_store.driver", "import os import pytest from modelkit.assets import errors from tests.conftest", "errors from tests.conftest import skip_unless def _perform_driver_error_object_not_found(driver): with pytest.raises(errors.ObjectDoesNotExistError): driver.download_object(\"someasset\",", "import errors from tests.conftest import skip_unless def _perform_driver_error_object_not_found(driver): with pytest.raises(errors.ObjectDoesNotExistError):", "not os.path.isfile(\"somedestination\") def test_local_driver(local_assetsmanager): local_driver = local_assetsmanager.remote_assets_store.driver _perform_driver_error_object_not_found(local_driver) @skip_unless(\"ENABLE_GCS_TEST\", \"True\")", "tests.conftest import skip_unless def _perform_driver_error_object_not_found(driver): with pytest.raises(errors.ObjectDoesNotExistError): driver.download_object(\"someasset\", \"somedestination\") assert", "def _perform_driver_error_object_not_found(driver): with pytest.raises(errors.ObjectDoesNotExistError): driver.download_object(\"someasset\", \"somedestination\") assert not os.path.isfile(\"somedestination\") def", "import skip_unless def _perform_driver_error_object_not_found(driver): with pytest.raises(errors.ObjectDoesNotExistError): driver.download_object(\"someasset\", \"somedestination\") assert not", "def test_local_driver(local_assetsmanager): local_driver = local_assetsmanager.remote_assets_store.driver _perform_driver_error_object_not_found(local_driver) @skip_unless(\"ENABLE_GCS_TEST\", \"True\") def test_gcs_driver(gcs_assetsmanager):", "skip_unless def _perform_driver_error_object_not_found(driver): with pytest.raises(errors.ObjectDoesNotExistError): driver.download_object(\"someasset\", \"somedestination\") assert not os.path.isfile(\"somedestination\")", "with pytest.raises(errors.ObjectDoesNotExistError): driver.download_object(\"someasset\", \"somedestination\") assert not os.path.isfile(\"somedestination\") def test_local_driver(local_assetsmanager): local_driver" ]
[ "database end = self.client.get('/') result = end.context['pages'] self.assertQuerysetEqual(result, ['<Page: My", "the MakeWiki homepage that will get a response back post_data", "response = self.client.post('/form/', data=post_data) # Check if response is 200", "data = post_data) self.assertEqual(response.status_code, 302) page_object = Page.objects.get(title='COVID19') self.assertEqual(page_object.content, 'Mass", "author=user) page.save() # Slug is generated matches with what we", "the database page = Page(title=\"My Detail Test Page\", content=\"details_test\", author=user)", "will be displayed on the screen user = User.objects.create() user.save()", "# Create your tests here. def test_detail_page(self): \"\"\" Test to", "= end.context['pages'] self.assertQuerysetEqual(result, ['<Page: My Test Page>', '<Page: Test>'], ordered=False)", "django.contrib.auth.models import User from wiki.models import Page # Create your", "# Create a page and save to the database page", "Test>'], ordered=False) def test_page_creation(self): # Create user object and save", "content=\"edit_test\", author=user) page.save() # Make a GET request to the", "you?', 'author': user.id, } response = self.client.post('/form/', data=post_data) # Check", "page = Page.objects.create(title=\"The Test Page\", content=\"edit_test\", author=user) page.save() post_data =", "to the database page = Page(title=\"My Detail Test Page\", content=\"details_test\",", "html=True) def test_edit_page(self): \"\"\"Test edit page.\"\"\" # Test data that", "that will be displayed on the screen user = User.objects.create()", "the number of pages passed to the template matches the", "user object and save it user = User.objects.create() user.save() #", "Detail Test Page\", content=\"details_test\", author=user) page.save() # Slug is generated", "user.save() # Create a page page = Page.objects.create(title=\"The Test Page\",", "Check if response is 200 self.assertEqual(response.status_code, 200) # Check the", "page.slug response = self.client.get(f'/{slug}/') self.assertEqual(response.status_code, 200) info = self.client.get('/') self.assertContains(info,", "Page # Create your tests here. def test_detail_page(self): \"\"\" Test", "# Slug is generated matches with what we expect slug", "a GET request to the MakeWiki homepage that will get", "Underway', 'author': user.id } response = self.client.post('/form/', data = post_data)", "Page.objects.create(title=\"My Test Page\", content=\"edit_test\", author=user) page.save() # Make a GET", "import User from wiki.models import Page # Create your tests", "Page\", content=\"edit_test\", author=user) page.save() # Make a GET request to", "django.test import TestCase from django.contrib.auth.models import User from wiki.models import", "slug = page.slug response = self.client.get(f'/{slug}/') self.assertEqual(response.status_code, 200) info =", "Page.objects.create(title=\"The Test Page\", content=\"edit_test\", author=user) page.save() post_data = { 'title':", "of pages passed to the template matches the number of", "test_detail_page(self): \"\"\" Test to see if slug generated when saving", "we expect slug = page.slug response = self.client.get(f'/{slug}/') self.assertEqual(response.status_code, 200)", "# Create a page page = Page.objects.create(title=\"The Test Page\", content=\"edit_test\",", "test_edit_page(self): \"\"\"Test edit page.\"\"\" # Test data that will be", "page.save() post_data = { 'title': 'COVID19', 'content': 'Mass Testing is", "Page(title=\"My Detail Test Page\", content=\"details_test\", author=user) page.save() # Slug is", "end = self.client.get('/') result = end.context['pages'] self.assertQuerysetEqual(result, ['<Page: My Test", "def test_edit_page(self): \"\"\"Test edit page.\"\"\" # Test data that will", "= page.slug response = self.client.get(f'/{slug}/') self.assertEqual(response.status_code, 200) info = self.client.get('/')", "the screen user = User.objects.create() user.save() page = Page.objects.create(title=\"My Test", "Create user object and save it user = User.objects.create() user.save()", "number of pages in the database end = self.client.get('/') result", "page page = Page.objects.create(title=\"The Test Page\", content=\"edit_test\", author=user) page.save() post_data", "self.assertEqual(response.status_code, 302) page_object = Page.objects.get(title='COVID19') self.assertEqual(page_object.content, 'Mass Testing is Underway')", "displayed on the screen user = User.objects.create() user.save() page =", "number of pages passed to the template matches the number", "homepage that will get a response back post_data = {", "matches the number of pages in the database end =", "TestCase from django.contrib.auth.models import User from wiki.models import Page #", "content=\"details_test\", author=user) page.save() # Slug is generated matches with what", "= self.client.get(f'/{slug}/') self.assertEqual(response.status_code, 200) info = self.client.get('/') self.assertContains(info, 'makewiki', html=True)", "My Test Page>', '<Page: Test>'], ordered=False) def test_page_creation(self): # Create", "Test Page>', '<Page: Test>'], ordered=False) def test_page_creation(self): # Create user", "user = User.objects.create() user.save() # Create a page page =", "post_data) self.assertEqual(response.status_code, 302) page_object = Page.objects.get(title='COVID19') self.assertEqual(page_object.content, 'Mass Testing is", "the database user = User.objects.create() user.save() # Create a page", "from django.contrib.auth.models import User from wiki.models import Page # Create", "the number of pages in the database end = self.client.get('/')", "page and save to the database page = Page(title=\"My Detail", "when saving a Page.\"\"\" # Create a user and save", "in the database end = self.client.get('/') result = end.context['pages'] self.assertQuerysetEqual(result,", "self.client.get(f'/{slug}/') self.assertEqual(response.status_code, 200) info = self.client.get('/') self.assertContains(info, 'makewiki', html=True) def", "Test data that will be displayed on the screen user", "= User.objects.create() user.save() page = Page.objects.create(title=\"My Test Page\", content=\"edit_test\", author=user)", "# Make a GET request to the MakeWiki homepage that", "Page\", content=\"edit_test\", author=user) page.save() post_data = { 'title': 'COVID19', 'content':", "to the MakeWiki homepage that will get a response back", "Create a page and save to the database page =", "\"\"\" Test to see if slug generated when saving a", "data that will be displayed on the screen user =", "screen user = User.objects.create() user.save() page = Page.objects.create(title=\"My Test Page\",", "page.save() # Make a GET request to the MakeWiki homepage", "'title': 'COVID19', 'content': 'Mass Testing is Underway', 'author': user.id }", "generated when saving a Page.\"\"\" # Create a user and", "generated matches with what we expect slug = page.slug response", "content=\"edit_test\", author=user) page.save() post_data = { 'title': 'COVID19', 'content': 'Mass", "object and save it user = User.objects.create() user.save() # Create", "} response = self.client.post('/form/', data = post_data) self.assertEqual(response.status_code, 302) page_object", "to the database user = User.objects.create() user.save() # Create a", "user.id } response = self.client.post('/form/', data = post_data) self.assertEqual(response.status_code, 302)", "info = self.client.get('/') self.assertContains(info, 'makewiki', html=True) def test_edit_page(self): \"\"\"Test edit", "is Underway', 'author': user.id } response = self.client.post('/form/', data =", "# Test data that will be displayed on the screen", "User.objects.create() user.save() # Create a page and save to the", "'COVID19', 'content': 'Mass Testing is Underway', 'author': user.id } response", "self.assertQuerysetEqual(result, ['<Page: My Test Page>', '<Page: Test>'], ordered=False) def test_page_creation(self):", "'author': user.id } response = self.client.post('/form/', data = post_data) self.assertEqual(response.status_code,", "Test Page\", content=\"details_test\", author=user) page.save() # Slug is generated matches", "GET request to the MakeWiki homepage that will get a", "pages in the database end = self.client.get('/') result = end.context['pages']", "'content': 'Mass Testing is Underway', 'author': user.id } response =", "= self.client.post('/form/', data=post_data) # Check if response is 200 self.assertEqual(response.status_code,", "from wiki.models import Page # Create your tests here. def", "Slug is generated matches with what we expect slug =", "= User.objects.create() user.save() # Create a page page = Page.objects.create(title=\"The", "database page = Page(title=\"My Detail Test Page\", content=\"details_test\", author=user) page.save()", "saving a Page.\"\"\" # Create a user and save to", "# Check if response is 200 self.assertEqual(response.status_code, 200) # Check", "if slug generated when saving a Page.\"\"\" # Create a", "author=user) page.save() # Make a GET request to the MakeWiki", "'Are you?', 'author': user.id, } response = self.client.post('/form/', data=post_data) #", "request to the MakeWiki homepage that will get a response", "pages passed to the template matches the number of pages", "what we expect slug = page.slug response = self.client.get(f'/{slug}/') self.assertEqual(response.status_code,", "back post_data = { 'title': 'Who', 'content': 'Are you?', 'author':", "\"\"\"Test edit page.\"\"\" # Test data that will be displayed", "to the template matches the number of pages in the", "that will get a response back post_data = { 'title':", "with what we expect slug = page.slug response = self.client.get(f'/{slug}/')", "= User.objects.create() user.save() # Create a page and save to", "on the screen user = User.objects.create() user.save() page = Page.objects.create(title=\"My", "['<Page: My Test Page>', '<Page: Test>'], ordered=False) def test_page_creation(self): #", "of pages in the database end = self.client.get('/') result =", "# Check the number of pages passed to the template", "= { 'title': 'Who', 'content': 'Are you?', 'author': user.id, }", "response is 200 self.assertEqual(response.status_code, 200) # Check the number of", "'<Page: Test>'], ordered=False) def test_page_creation(self): # Create user object and", "see if slug generated when saving a Page.\"\"\" # Create", "a Page.\"\"\" # Create a user and save to the", "save to the database user = User.objects.create() user.save() # Create", "ordered=False) def test_page_creation(self): # Create user object and save it", "# Create user object and save it user = User.objects.create()", "post_data = { 'title': 'COVID19', 'content': 'Mass Testing is Underway',", "self.client.get('/') self.assertContains(info, 'makewiki', html=True) def test_edit_page(self): \"\"\"Test edit page.\"\"\" #", "= { 'title': 'COVID19', 'content': 'Mass Testing is Underway', 'author':", "'Mass Testing is Underway', 'author': user.id } response = self.client.post('/form/',", "wiki.models import Page # Create your tests here. def test_detail_page(self):", "database user = User.objects.create() user.save() # Create a page and", "a response back post_data = { 'title': 'Who', 'content': 'Are", "self.client.get('/') result = end.context['pages'] self.assertQuerysetEqual(result, ['<Page: My Test Page>', '<Page:", "def test_page_creation(self): # Create user object and save it user", "Page\", content=\"details_test\", author=user) page.save() # Slug is generated matches with", "save to the database page = Page(title=\"My Detail Test Page\",", "a user and save to the database user = User.objects.create()", "200 self.assertEqual(response.status_code, 200) # Check the number of pages passed", "self.assertContains(info, 'makewiki', html=True) def test_edit_page(self): \"\"\"Test edit page.\"\"\" # Test", "200) info = self.client.get('/') self.assertContains(info, 'makewiki', html=True) def test_edit_page(self): \"\"\"Test", "response = self.client.post('/form/', data = post_data) self.assertEqual(response.status_code, 302) page_object =", "post_data = { 'title': 'Who', 'content': 'Are you?', 'author': user.id,", "import Page # Create your tests here. def test_detail_page(self): \"\"\"", "slug generated when saving a Page.\"\"\" # Create a user", "passed to the template matches the number of pages in", "response back post_data = { 'title': 'Who', 'content': 'Are you?',", "{ 'title': 'COVID19', 'content': 'Mass Testing is Underway', 'author': user.id", "Create your tests here. def test_detail_page(self): \"\"\" Test to see", "User from wiki.models import Page # Create your tests here.", "your tests here. def test_detail_page(self): \"\"\" Test to see if", "a page page = Page.objects.create(title=\"The Test Page\", content=\"edit_test\", author=user) page.save()", "save it user = User.objects.create() user.save() # Create a page", "user = User.objects.create() user.save() # Create a page and save", "= Page(title=\"My Detail Test Page\", content=\"details_test\", author=user) page.save() # Slug", "to see if slug generated when saving a Page.\"\"\" #", "= self.client.get('/') self.assertContains(info, 'makewiki', html=True) def test_edit_page(self): \"\"\"Test edit page.\"\"\"", "result = end.context['pages'] self.assertQuerysetEqual(result, ['<Page: My Test Page>', '<Page: Test>'],", "user.save() page = Page.objects.create(title=\"My Test Page\", content=\"edit_test\", author=user) page.save() #", "get a response back post_data = { 'title': 'Who', 'content':", "Create a page page = Page.objects.create(title=\"The Test Page\", content=\"edit_test\", author=user)", "user.id, } response = self.client.post('/form/', data=post_data) # Check if response", "is generated matches with what we expect slug = page.slug", "self.client.post('/form/', data=post_data) # Check if response is 200 self.assertEqual(response.status_code, 200)", "Page.\"\"\" # Create a user and save to the database", "matches with what we expect slug = page.slug response =", "Make a GET request to the MakeWiki homepage that will", "'makewiki', html=True) def test_edit_page(self): \"\"\"Test edit page.\"\"\" # Test data", "Test Page\", content=\"edit_test\", author=user) page.save() # Make a GET request", "and save to the database page = Page(title=\"My Detail Test", "expect slug = page.slug response = self.client.get(f'/{slug}/') self.assertEqual(response.status_code, 200) info", "'title': 'Who', 'content': 'Are you?', 'author': user.id, } response =", "import TestCase from django.contrib.auth.models import User from wiki.models import Page", "the template matches the number of pages in the database", "user = User.objects.create() user.save() page = Page.objects.create(title=\"My Test Page\", content=\"edit_test\",", "it user = User.objects.create() user.save() # Create a page page", "= Page.objects.create(title=\"The Test Page\", content=\"edit_test\", author=user) page.save() post_data = {", "{ 'title': 'Who', 'content': 'Are you?', 'author': user.id, } response", "template matches the number of pages in the database end", "here. def test_detail_page(self): \"\"\" Test to see if slug generated", "def test_detail_page(self): \"\"\" Test to see if slug generated when", "self.assertEqual(response.status_code, 200) info = self.client.get('/') self.assertContains(info, 'makewiki', html=True) def test_edit_page(self):", "MakeWiki homepage that will get a response back post_data =", "# Create a user and save to the database user", "is 200 self.assertEqual(response.status_code, 200) # Check the number of pages", "Page>', '<Page: Test>'], ordered=False) def test_page_creation(self): # Create user object", "and save it user = User.objects.create() user.save() # Create a", "'content': 'Are you?', 'author': user.id, } response = self.client.post('/form/', data=post_data)", "be displayed on the screen user = User.objects.create() user.save() page", "the database end = self.client.get('/') result = end.context['pages'] self.assertQuerysetEqual(result, ['<Page:", "end.context['pages'] self.assertQuerysetEqual(result, ['<Page: My Test Page>', '<Page: Test>'], ordered=False) def", "if response is 200 self.assertEqual(response.status_code, 200) # Check the number", "User.objects.create() user.save() # Create a page page = Page.objects.create(title=\"The Test", "test_page_creation(self): # Create user object and save it user =", "= Page.objects.create(title=\"My Test Page\", content=\"edit_test\", author=user) page.save() # Make a", "page.\"\"\" # Test data that will be displayed on the", "edit page.\"\"\" # Test data that will be displayed on", "page.save() # Slug is generated matches with what we expect", "'author': user.id, } response = self.client.post('/form/', data=post_data) # Check if", "will get a response back post_data = { 'title': 'Who',", "data=post_data) # Check if response is 200 self.assertEqual(response.status_code, 200) #", "= post_data) self.assertEqual(response.status_code, 302) page_object = Page.objects.get(title='COVID19') self.assertEqual(page_object.content, 'Mass Testing", "200) # Check the number of pages passed to the", "self.client.post('/form/', data = post_data) self.assertEqual(response.status_code, 302) page_object = Page.objects.get(title='COVID19') self.assertEqual(page_object.content,", "Check the number of pages passed to the template matches", "= self.client.post('/form/', data = post_data) self.assertEqual(response.status_code, 302) page_object = Page.objects.get(title='COVID19')", "a page and save to the database page = Page(title=\"My", "page = Page.objects.create(title=\"My Test Page\", content=\"edit_test\", author=user) page.save() # Make", "Test Page\", content=\"edit_test\", author=user) page.save() post_data = { 'title': 'COVID19',", "user and save to the database user = User.objects.create() user.save()", "Create a user and save to the database user =", "} response = self.client.post('/form/', data=post_data) # Check if response is", "Test to see if slug generated when saving a Page.\"\"\"", "'Who', 'content': 'Are you?', 'author': user.id, } response = self.client.post('/form/',", "page = Page(title=\"My Detail Test Page\", content=\"details_test\", author=user) page.save() #", "from django.test import TestCase from django.contrib.auth.models import User from wiki.models", "tests here. def test_detail_page(self): \"\"\" Test to see if slug", "Testing is Underway', 'author': user.id } response = self.client.post('/form/', data", "author=user) page.save() post_data = { 'title': 'COVID19', 'content': 'Mass Testing", "= self.client.get('/') result = end.context['pages'] self.assertQuerysetEqual(result, ['<Page: My Test Page>',", "user.save() # Create a page and save to the database", "and save to the database user = User.objects.create() user.save() #", "User.objects.create() user.save() page = Page.objects.create(title=\"My Test Page\", content=\"edit_test\", author=user) page.save()", "self.assertEqual(response.status_code, 200) # Check the number of pages passed to", "response = self.client.get(f'/{slug}/') self.assertEqual(response.status_code, 200) info = self.client.get('/') self.assertContains(info, 'makewiki'," ]
[ "MultiArmedBandit from .eps_greedy_constant_stepsize import EpsilonGreedyConstantStepsize from .greedy_constant_stepsize import GreedyConstantStepsize from", "from .eps_greedy_constant_stepsize import EpsilonGreedyConstantStepsize from .greedy_constant_stepsize import GreedyConstantStepsize from .epsilon_greedy_average_step", "EpsilonGreedyConstantStepsize from .greedy_constant_stepsize import GreedyConstantStepsize from .epsilon_greedy_average_step import EpsilonGreedyAverageStep from", "import GreedyConstantStepsize from .epsilon_greedy_average_step import EpsilonGreedyAverageStep from .greedy_average_step import GreedyAverageStep", "import EpsilonGreedyConstantStepsize from .greedy_constant_stepsize import GreedyConstantStepsize from .epsilon_greedy_average_step import EpsilonGreedyAverageStep", "import EpsilonGreedyAverageStep from .greedy_average_step import GreedyAverageStep from .greedy_bayes_update import GreedyBayesianUpdate", "import MultiArmedBandit from .eps_greedy_constant_stepsize import EpsilonGreedyConstantStepsize from .greedy_constant_stepsize import GreedyConstantStepsize", "from .multiarmedbandit import MultiArmedBandit from .eps_greedy_constant_stepsize import EpsilonGreedyConstantStepsize from .greedy_constant_stepsize", ".greedy_constant_stepsize import GreedyConstantStepsize from .epsilon_greedy_average_step import EpsilonGreedyAverageStep from .greedy_average_step import", "import GreedyAverageStep from .greedy_bayes_update import GreedyBayesianUpdate from .eps_greedy_bayes_update import EpsilonGreedyBayesianUpdate", ".greedy_average_step import GreedyAverageStep from .greedy_bayes_update import GreedyBayesianUpdate from .eps_greedy_bayes_update import", "<reponame>AJB0211/BanditSim from .multiarmedbandit import MultiArmedBandit from .eps_greedy_constant_stepsize import EpsilonGreedyConstantStepsize from", "from .epsilon_greedy_average_step import EpsilonGreedyAverageStep from .greedy_average_step import GreedyAverageStep from .greedy_bayes_update", ".eps_greedy_constant_stepsize import EpsilonGreedyConstantStepsize from .greedy_constant_stepsize import GreedyConstantStepsize from .epsilon_greedy_average_step import", ".multiarmedbandit import MultiArmedBandit from .eps_greedy_constant_stepsize import EpsilonGreedyConstantStepsize from .greedy_constant_stepsize import", "from .greedy_average_step import GreedyAverageStep from .greedy_bayes_update import GreedyBayesianUpdate from .eps_greedy_bayes_update", "from .greedy_constant_stepsize import GreedyConstantStepsize from .epsilon_greedy_average_step import EpsilonGreedyAverageStep from .greedy_average_step", "EpsilonGreedyAverageStep from .greedy_average_step import GreedyAverageStep from .greedy_bayes_update import GreedyBayesianUpdate from", ".epsilon_greedy_average_step import EpsilonGreedyAverageStep from .greedy_average_step import GreedyAverageStep from .greedy_bayes_update import", "GreedyConstantStepsize from .epsilon_greedy_average_step import EpsilonGreedyAverageStep from .greedy_average_step import GreedyAverageStep from" ]
[ "Item._meta.get_field('modified')) def test_transform(self): query = Query(Author) with register_lookup(CharField, Lower): where", "ObjectC, Ranking class TestQuery(TestCase): def test_simple_query(self): query = Query(Author) where", "= Query(Ranking) with self.assertRaises(FieldError): query.build_where(Q(rank__gt=F('author__num'))) def test_foreign_key_exclusive(self): query = Query(ObjectC)", "django.db.models.fields.related_lookups import RelatedIsNull from django.db.models.functions import Lower from django.db.models.lookups import", "import Lower from django.db.models.lookups import Exact, GreaterThan, IsNull, LessThan from", "django.test import TestCase from django.test.utils import register_lookup from .models import", "register_lookup from .models import Author, Item, ObjectC, Ranking class TestQuery(TestCase):", "def test_complex_query(self): query = Query(Author) where = query.build_where(Q(num__gt=2) | Q(num__lt=0))", "permitted in this query' with self.assertRaisesMessage(FieldError, msg): query.build_where(Q(creator__num__gt=2)) def test_foreign_key_f(self):", "django.db.models.lookups import Exact, GreaterThan, IsNull, LessThan from django.db.models.sql.query import Query", "from django.db.models.sql.query import Query from django.db.models.sql.where import OR from django.test", "import Author, Item, ObjectC, Ranking class TestQuery(TestCase): def test_simple_query(self): query", "lookup = where.children[0] self.assertIsInstance(lookup, GreaterThan) self.assertEqual(lookup.rhs, 2) self.assertEqual(lookup.lhs.target, Author._meta.get_field('num')) def", "import CharField, F, Q from django.db.models.expressions import SimpleCol from django.db.models.fields.related_lookups", "GreaterThan) self.assertIsInstance(lookup.rhs, SimpleCol) self.assertIsInstance(lookup.lhs, SimpleCol) self.assertEqual(lookup.rhs.target, Item._meta.get_field('created')) self.assertEqual(lookup.lhs.target, Item._meta.get_field('modified')) def", "self.assertIsInstance(lookup, LessThan) self.assertEqual(lookup.rhs, 0) self.assertEqual(lookup.lhs.target, Author._meta.get_field('num')) def test_multiple_fields(self): query =", "self.assertEqual(lookup.lhs.target, Item._meta.get_field('modified')) def test_transform(self): query = Query(Author) with register_lookup(CharField, Lower):", "self.assertEqual(lookup.lhs.target, Item._meta.get_field('modified')) lookup = where.children[1] self.assertIsInstance(lookup, IsNull) self.assertEqual(lookup.lhs.target, Item._meta.get_field('modified')) def", "field references are not permitted in this query' with self.assertRaisesMessage(FieldError,", "import RelatedIsNull from django.db.models.functions import Lower from django.db.models.lookups import Exact,", "LessThan) self.assertEqual(lookup.lhs.target, Item._meta.get_field('modified')) lookup = where.children[1] self.assertIsInstance(lookup, IsNull) self.assertEqual(lookup.lhs.target, Item._meta.get_field('modified'))", "RelatedIsNull from django.db.models.functions import Lower from django.db.models.lookups import Exact, GreaterThan,", "= query.build_where(Q(modified__gt=F('created'))) lookup = where.children[0] self.assertIsInstance(lookup, GreaterThan) self.assertIsInstance(lookup.rhs, SimpleCol) self.assertIsInstance(lookup.lhs,", "Author._meta.get_field('name')) def test_negated_nullable(self): query = Query(Item) where = query.build_where(~Q(modified__lt=datetime(2017, 1,", "where = query.build_where(~Q(modified__lt=datetime(2017, 1, 1))) self.assertTrue(where.negated) lookup = where.children[0] self.assertIsInstance(lookup,", "query.build_where(Q(modified__gt=F('created'))) lookup = where.children[0] self.assertIsInstance(lookup, GreaterThan) self.assertIsInstance(lookup.rhs, SimpleCol) self.assertIsInstance(lookup.lhs, SimpleCol)", "= Query(Item) where = query.build_where(~Q(modified__lt=datetime(2017, 1, 1))) self.assertTrue(where.negated) lookup =", "test_foreign_key_exclusive(self): query = Query(ObjectC) where = query.build_where(Q(objecta=None) | Q(objectb=None)) a_isnull", "from django.db.models import CharField, F, Q from django.db.models.expressions import SimpleCol", "a_isnull = where.children[0] self.assertIsInstance(a_isnull, RelatedIsNull) self.assertIsInstance(a_isnull.lhs, SimpleCol) self.assertEqual(a_isnull.lhs.target, ObjectC._meta.get_field('objecta')) b_isnull", "Q from django.db.models.expressions import SimpleCol from django.db.models.fields.related_lookups import RelatedIsNull from", "import Query from django.db.models.sql.where import OR from django.test import TestCase", "= query.build_where(Q(num__gt=2)) lookup = where.children[0] self.assertIsInstance(lookup, GreaterThan) self.assertEqual(lookup.rhs, 2) self.assertEqual(lookup.lhs.target,", "import datetime from django.core.exceptions import FieldError from django.db.models import CharField,", "where.children[1] self.assertIsInstance(lookup, IsNull) self.assertEqual(lookup.lhs.target, Item._meta.get_field('modified')) def test_foreign_key(self): query = Query(Item)", "self.assertIsInstance(lookup.lhs, SimpleCol) self.assertEqual(lookup.rhs.target, Item._meta.get_field('created')) self.assertEqual(lookup.lhs.target, Item._meta.get_field('modified')) def test_transform(self): query =", "'Joined field references are not permitted in this query' with", "self.assertIsInstance(a_isnull.lhs, SimpleCol) self.assertEqual(a_isnull.lhs.target, ObjectC._meta.get_field('objecta')) b_isnull = where.children[1] self.assertIsInstance(b_isnull, RelatedIsNull) self.assertIsInstance(b_isnull.lhs,", "where = query.build_where(Q(objecta=None) | Q(objectb=None)) a_isnull = where.children[0] self.assertIsInstance(a_isnull, RelatedIsNull)", "query.build_where(~Q(name__lower='foo')) lookup = where.children[0] self.assertIsInstance(lookup, Exact) self.assertIsInstance(lookup.lhs, Lower) self.assertIsInstance(lookup.lhs.lhs, SimpleCol)", "| Q(num__lt=0)) self.assertEqual(where.connector, OR) lookup = where.children[0] self.assertIsInstance(lookup, GreaterThan) self.assertEqual(lookup.rhs,", "import OR from django.test import TestCase from django.test.utils import register_lookup", "Author._meta.get_field('num')) def test_multiple_fields(self): query = Query(Item) where = query.build_where(Q(modified__gt=F('created'))) lookup", "test_multiple_fields(self): query = Query(Item) where = query.build_where(Q(modified__gt=F('created'))) lookup = where.children[0]", "where.children[0] self.assertIsInstance(lookup, GreaterThan) self.assertEqual(lookup.rhs, 2) self.assertEqual(lookup.lhs.target, Author._meta.get_field('num')) def test_complex_query(self): query", "IsNull, LessThan from django.db.models.sql.query import Query from django.db.models.sql.where import OR", "from .models import Author, Item, ObjectC, Ranking class TestQuery(TestCase): def", "import Exact, GreaterThan, IsNull, LessThan from django.db.models.sql.query import Query from", "self.assertEqual(lookup.rhs.target, Item._meta.get_field('created')) self.assertEqual(lookup.lhs.target, Item._meta.get_field('modified')) def test_transform(self): query = Query(Author) with", "where.children[0] self.assertIsInstance(lookup, LessThan) self.assertEqual(lookup.lhs.target, Item._meta.get_field('modified')) lookup = where.children[1] self.assertIsInstance(lookup, IsNull)", "django.db.models.sql.where import OR from django.test import TestCase from django.test.utils import", "register_lookup(CharField, Lower): where = query.build_where(~Q(name__lower='foo')) lookup = where.children[0] self.assertIsInstance(lookup, Exact)", "django.db.models import CharField, F, Q from django.db.models.expressions import SimpleCol from", "test_negated_nullable(self): query = Query(Item) where = query.build_where(~Q(modified__lt=datetime(2017, 1, 1))) self.assertTrue(where.negated)", "Query(Author) where = query.build_where(Q(num__gt=2) | Q(num__lt=0)) self.assertEqual(where.connector, OR) lookup =", "= Query(Author) where = query.build_where(Q(num__gt=2)) lookup = where.children[0] self.assertIsInstance(lookup, GreaterThan)", "lookup = where.children[0] self.assertIsInstance(lookup, Exact) self.assertIsInstance(lookup.lhs, Lower) self.assertIsInstance(lookup.lhs.lhs, SimpleCol) self.assertEqual(lookup.lhs.lhs.target,", "self.assertIsInstance(lookup, Exact) self.assertIsInstance(lookup.lhs, Lower) self.assertIsInstance(lookup.lhs.lhs, SimpleCol) self.assertEqual(lookup.lhs.lhs.target, Author._meta.get_field('name')) def test_negated_nullable(self):", "self.assertEqual(lookup.lhs.lhs.target, Author._meta.get_field('name')) def test_negated_nullable(self): query = Query(Item) where = query.build_where(~Q(modified__lt=datetime(2017,", "from django.db.models.functions import Lower from django.db.models.lookups import Exact, GreaterThan, IsNull,", "= query.build_where(~Q(name__lower='foo')) lookup = where.children[0] self.assertIsInstance(lookup, Exact) self.assertIsInstance(lookup.lhs, Lower) self.assertIsInstance(lookup.lhs.lhs,", "django.db.models.sql.query import Query from django.db.models.sql.where import OR from django.test import", "Query(Ranking) with self.assertRaises(FieldError): query.build_where(Q(rank__gt=F('author__num'))) def test_foreign_key_exclusive(self): query = Query(ObjectC) where", "query.build_where(Q(num__gt=2)) lookup = where.children[0] self.assertIsInstance(lookup, GreaterThan) self.assertEqual(lookup.rhs, 2) self.assertEqual(lookup.lhs.target, Author._meta.get_field('num'))", "self.assertEqual(lookup.rhs, 2) self.assertEqual(lookup.lhs.target, Author._meta.get_field('num')) lookup = where.children[1] self.assertIsInstance(lookup, LessThan) self.assertEqual(lookup.rhs,", "SimpleCol) self.assertIsInstance(lookup.lhs, SimpleCol) self.assertEqual(lookup.rhs.target, Item._meta.get_field('created')) self.assertEqual(lookup.lhs.target, Item._meta.get_field('modified')) def test_transform(self): query", "Item._meta.get_field('modified')) def test_foreign_key(self): query = Query(Item) msg = 'Joined field", "Query(ObjectC) where = query.build_where(Q(objecta=None) | Q(objectb=None)) a_isnull = where.children[0] self.assertIsInstance(a_isnull,", "self.assertEqual(lookup.rhs, 0) self.assertEqual(lookup.lhs.target, Author._meta.get_field('num')) def test_multiple_fields(self): query = Query(Item) where", "django.db.models.functions import Lower from django.db.models.lookups import Exact, GreaterThan, IsNull, LessThan", "where = query.build_where(~Q(name__lower='foo')) lookup = where.children[0] self.assertIsInstance(lookup, Exact) self.assertIsInstance(lookup.lhs, Lower)", "django.test.utils import register_lookup from .models import Author, Item, ObjectC, Ranking", "LessThan from django.db.models.sql.query import Query from django.db.models.sql.where import OR from", "where = query.build_where(Q(num__gt=2) | Q(num__lt=0)) self.assertEqual(where.connector, OR) lookup = where.children[0]", "self.assertIsInstance(lookup.rhs, SimpleCol) self.assertIsInstance(lookup.lhs, SimpleCol) self.assertEqual(lookup.rhs.target, Item._meta.get_field('created')) self.assertEqual(lookup.lhs.target, Item._meta.get_field('modified')) def test_transform(self):", "= query.build_where(~Q(modified__lt=datetime(2017, 1, 1))) self.assertTrue(where.negated) lookup = where.children[0] self.assertIsInstance(lookup, LessThan)", "= query.build_where(Q(objecta=None) | Q(objectb=None)) a_isnull = where.children[0] self.assertIsInstance(a_isnull, RelatedIsNull) self.assertIsInstance(a_isnull.lhs,", "query' with self.assertRaisesMessage(FieldError, msg): query.build_where(Q(creator__num__gt=2)) def test_foreign_key_f(self): query = Query(Ranking)", "def test_foreign_key_exclusive(self): query = Query(ObjectC) where = query.build_where(Q(objecta=None) | Q(objectb=None))", "django.core.exceptions import FieldError from django.db.models import CharField, F, Q from", "self.assertIsInstance(lookup, GreaterThan) self.assertEqual(lookup.rhs, 2) self.assertEqual(lookup.lhs.target, Author._meta.get_field('num')) def test_complex_query(self): query =", "from django.db.models.fields.related_lookups import RelatedIsNull from django.db.models.functions import Lower from django.db.models.lookups", "datetime from django.core.exceptions import FieldError from django.db.models import CharField, F,", "with self.assertRaisesMessage(FieldError, msg): query.build_where(Q(creator__num__gt=2)) def test_foreign_key_f(self): query = Query(Ranking) with", "with self.assertRaises(FieldError): query.build_where(Q(rank__gt=F('author__num'))) def test_foreign_key_exclusive(self): query = Query(ObjectC) where =", "query = Query(ObjectC) where = query.build_where(Q(objecta=None) | Q(objectb=None)) a_isnull =", "Author._meta.get_field('num')) def test_complex_query(self): query = Query(Author) where = query.build_where(Q(num__gt=2) |", "from django.test.utils import register_lookup from .models import Author, Item, ObjectC,", "self.assertTrue(where.negated) lookup = where.children[0] self.assertIsInstance(lookup, LessThan) self.assertEqual(lookup.lhs.target, Item._meta.get_field('modified')) lookup =", "LessThan) self.assertEqual(lookup.rhs, 0) self.assertEqual(lookup.lhs.target, Author._meta.get_field('num')) def test_multiple_fields(self): query = Query(Item)", "self.assertEqual(where.connector, OR) lookup = where.children[0] self.assertIsInstance(lookup, GreaterThan) self.assertEqual(lookup.rhs, 2) self.assertEqual(lookup.lhs.target,", "self.assertEqual(lookup.lhs.target, Author._meta.get_field('num')) def test_multiple_fields(self): query = Query(Item) where = query.build_where(Q(modified__gt=F('created')))", "import FieldError from django.db.models import CharField, F, Q from django.db.models.expressions", "= where.children[0] self.assertIsInstance(lookup, GreaterThan) self.assertIsInstance(lookup.rhs, SimpleCol) self.assertIsInstance(lookup.lhs, SimpleCol) self.assertEqual(lookup.rhs.target, Item._meta.get_field('created'))", "self.assertIsInstance(lookup, GreaterThan) self.assertIsInstance(lookup.rhs, SimpleCol) self.assertIsInstance(lookup.lhs, SimpleCol) self.assertEqual(lookup.rhs.target, Item._meta.get_field('created')) self.assertEqual(lookup.lhs.target, Item._meta.get_field('modified'))", "Query(Author) with register_lookup(CharField, Lower): where = query.build_where(~Q(name__lower='foo')) lookup = where.children[0]", "from django.db.models.expressions import SimpleCol from django.db.models.fields.related_lookups import RelatedIsNull from django.db.models.functions", "Item, ObjectC, Ranking class TestQuery(TestCase): def test_simple_query(self): query = Query(Author)", "Query(Author) where = query.build_where(Q(num__gt=2)) lookup = where.children[0] self.assertIsInstance(lookup, GreaterThan) self.assertEqual(lookup.rhs,", "query.build_where(Q(num__gt=2) | Q(num__lt=0)) self.assertEqual(where.connector, OR) lookup = where.children[0] self.assertIsInstance(lookup, GreaterThan)", "0) self.assertEqual(lookup.lhs.target, Author._meta.get_field('num')) def test_multiple_fields(self): query = Query(Item) where =", "where.children[0] self.assertIsInstance(lookup, Exact) self.assertIsInstance(lookup.lhs, Lower) self.assertIsInstance(lookup.lhs.lhs, SimpleCol) self.assertEqual(lookup.lhs.lhs.target, Author._meta.get_field('name')) def", "not permitted in this query' with self.assertRaisesMessage(FieldError, msg): query.build_where(Q(creator__num__gt=2)) def", "= Query(Item) msg = 'Joined field references are not permitted", "self.assertIsInstance(lookup, IsNull) self.assertEqual(lookup.lhs.target, Item._meta.get_field('modified')) def test_foreign_key(self): query = Query(Item) msg", "= where.children[0] self.assertIsInstance(lookup, GreaterThan) self.assertEqual(lookup.rhs, 2) self.assertEqual(lookup.lhs.target, Author._meta.get_field('num')) lookup =", "self.assertRaisesMessage(FieldError, msg): query.build_where(Q(creator__num__gt=2)) def test_foreign_key_f(self): query = Query(Ranking) with self.assertRaises(FieldError):", "are not permitted in this query' with self.assertRaisesMessage(FieldError, msg): query.build_where(Q(creator__num__gt=2))", "Item._meta.get_field('modified')) lookup = where.children[1] self.assertIsInstance(lookup, IsNull) self.assertEqual(lookup.lhs.target, Item._meta.get_field('modified')) def test_foreign_key(self):", "test_transform(self): query = Query(Author) with register_lookup(CharField, Lower): where = query.build_where(~Q(name__lower='foo'))", "where.children[0] self.assertIsInstance(lookup, GreaterThan) self.assertEqual(lookup.rhs, 2) self.assertEqual(lookup.lhs.target, Author._meta.get_field('num')) lookup = where.children[1]", "self.assertIsInstance(a_isnull, RelatedIsNull) self.assertIsInstance(a_isnull.lhs, SimpleCol) self.assertEqual(a_isnull.lhs.target, ObjectC._meta.get_field('objecta')) b_isnull = where.children[1] self.assertIsInstance(b_isnull,", "with register_lookup(CharField, Lower): where = query.build_where(~Q(name__lower='foo')) lookup = where.children[0] self.assertIsInstance(lookup,", "import SimpleCol from django.db.models.fields.related_lookups import RelatedIsNull from django.db.models.functions import Lower", "test_foreign_key(self): query = Query(Item) msg = 'Joined field references are", "where = query.build_where(Q(modified__gt=F('created'))) lookup = where.children[0] self.assertIsInstance(lookup, GreaterThan) self.assertIsInstance(lookup.rhs, SimpleCol)", "self.assertRaises(FieldError): query.build_where(Q(rank__gt=F('author__num'))) def test_foreign_key_exclusive(self): query = Query(ObjectC) where = query.build_where(Q(objecta=None)", "lookup = where.children[0] self.assertIsInstance(lookup, GreaterThan) self.assertIsInstance(lookup.rhs, SimpleCol) self.assertIsInstance(lookup.lhs, SimpleCol) self.assertEqual(lookup.rhs.target,", "self.assertEqual(lookup.lhs.target, Author._meta.get_field('num')) def test_complex_query(self): query = Query(Author) where = query.build_where(Q(num__gt=2)", "def test_foreign_key(self): query = Query(Item) msg = 'Joined field references", ".models import Author, Item, ObjectC, Ranking class TestQuery(TestCase): def test_simple_query(self):", "1))) self.assertTrue(where.negated) lookup = where.children[0] self.assertIsInstance(lookup, LessThan) self.assertEqual(lookup.lhs.target, Item._meta.get_field('modified')) lookup", "def test_transform(self): query = Query(Author) with register_lookup(CharField, Lower): where =", "1, 1))) self.assertTrue(where.negated) lookup = where.children[0] self.assertIsInstance(lookup, LessThan) self.assertEqual(lookup.lhs.target, Item._meta.get_field('modified'))", "datetime import datetime from django.core.exceptions import FieldError from django.db.models import", "references are not permitted in this query' with self.assertRaisesMessage(FieldError, msg):", "Ranking class TestQuery(TestCase): def test_simple_query(self): query = Query(Author) where =", "Q(num__lt=0)) self.assertEqual(where.connector, OR) lookup = where.children[0] self.assertIsInstance(lookup, GreaterThan) self.assertEqual(lookup.rhs, 2)", "= Query(Author) where = query.build_where(Q(num__gt=2) | Q(num__lt=0)) self.assertEqual(where.connector, OR) lookup", "| Q(objectb=None)) a_isnull = where.children[0] self.assertIsInstance(a_isnull, RelatedIsNull) self.assertIsInstance(a_isnull.lhs, SimpleCol) self.assertEqual(a_isnull.lhs.target,", "lookup = where.children[1] self.assertIsInstance(lookup, IsNull) self.assertEqual(lookup.lhs.target, Item._meta.get_field('modified')) def test_foreign_key(self): query", "msg): query.build_where(Q(creator__num__gt=2)) def test_foreign_key_f(self): query = Query(Ranking) with self.assertRaises(FieldError): query.build_where(Q(rank__gt=F('author__num')))", "query = Query(Author) with register_lookup(CharField, Lower): where = query.build_where(~Q(name__lower='foo')) lookup", "OR) lookup = where.children[0] self.assertIsInstance(lookup, GreaterThan) self.assertEqual(lookup.rhs, 2) self.assertEqual(lookup.lhs.target, Author._meta.get_field('num'))", "from django.db.models.sql.where import OR from django.test import TestCase from django.test.utils", "django.db.models.expressions import SimpleCol from django.db.models.fields.related_lookups import RelatedIsNull from django.db.models.functions import", "= Query(Item) where = query.build_where(Q(modified__gt=F('created'))) lookup = where.children[0] self.assertIsInstance(lookup, GreaterThan)", "Lower): where = query.build_where(~Q(name__lower='foo')) lookup = where.children[0] self.assertIsInstance(lookup, Exact) self.assertIsInstance(lookup.lhs,", "= where.children[0] self.assertIsInstance(lookup, Exact) self.assertIsInstance(lookup.lhs, Lower) self.assertIsInstance(lookup.lhs.lhs, SimpleCol) self.assertEqual(lookup.lhs.lhs.target, Author._meta.get_field('name'))", "from django.db.models.lookups import Exact, GreaterThan, IsNull, LessThan from django.db.models.sql.query import", "test_simple_query(self): query = Query(Author) where = query.build_where(Q(num__gt=2)) lookup = where.children[0]", "this query' with self.assertRaisesMessage(FieldError, msg): query.build_where(Q(creator__num__gt=2)) def test_foreign_key_f(self): query =", "import TestCase from django.test.utils import register_lookup from .models import Author,", "import register_lookup from .models import Author, Item, ObjectC, Ranking class", "query = Query(Item) msg = 'Joined field references are not", "where.children[1] self.assertIsInstance(lookup, LessThan) self.assertEqual(lookup.rhs, 0) self.assertEqual(lookup.lhs.target, Author._meta.get_field('num')) def test_multiple_fields(self): query", "Query(Item) msg = 'Joined field references are not permitted in", "Exact) self.assertIsInstance(lookup.lhs, Lower) self.assertIsInstance(lookup.lhs.lhs, SimpleCol) self.assertEqual(lookup.lhs.lhs.target, Author._meta.get_field('name')) def test_negated_nullable(self): query", "SimpleCol from django.db.models.fields.related_lookups import RelatedIsNull from django.db.models.functions import Lower from", "Author, Item, ObjectC, Ranking class TestQuery(TestCase): def test_simple_query(self): query =", "from datetime import datetime from django.core.exceptions import FieldError from django.db.models", "= 'Joined field references are not permitted in this query'", "FieldError from django.db.models import CharField, F, Q from django.db.models.expressions import", "self.assertIsInstance(lookup, GreaterThan) self.assertEqual(lookup.rhs, 2) self.assertEqual(lookup.lhs.target, Author._meta.get_field('num')) lookup = where.children[1] self.assertIsInstance(lookup,", "lookup = where.children[1] self.assertIsInstance(lookup, LessThan) self.assertEqual(lookup.rhs, 0) self.assertEqual(lookup.lhs.target, Author._meta.get_field('num')) def", "self.assertEqual(a_isnull.lhs.target, ObjectC._meta.get_field('objecta')) b_isnull = where.children[1] self.assertIsInstance(b_isnull, RelatedIsNull) self.assertIsInstance(b_isnull.lhs, SimpleCol) self.assertEqual(b_isnull.lhs.target,", "self.assertIsInstance(lookup.lhs, Lower) self.assertIsInstance(lookup.lhs.lhs, SimpleCol) self.assertEqual(lookup.lhs.lhs.target, Author._meta.get_field('name')) def test_negated_nullable(self): query =", "Query from django.db.models.sql.where import OR from django.test import TestCase from", "= Query(ObjectC) where = query.build_where(Q(objecta=None) | Q(objectb=None)) a_isnull = where.children[0]", "= where.children[0] self.assertIsInstance(lookup, LessThan) self.assertEqual(lookup.lhs.target, Item._meta.get_field('modified')) lookup = where.children[1] self.assertIsInstance(lookup,", "ObjectC._meta.get_field('objecta')) b_isnull = where.children[1] self.assertIsInstance(b_isnull, RelatedIsNull) self.assertIsInstance(b_isnull.lhs, SimpleCol) self.assertEqual(b_isnull.lhs.target, ObjectC._meta.get_field('objectb'))", "where = query.build_where(Q(num__gt=2)) lookup = where.children[0] self.assertIsInstance(lookup, GreaterThan) self.assertEqual(lookup.rhs, 2)", "self.assertEqual(lookup.rhs, 2) self.assertEqual(lookup.lhs.target, Author._meta.get_field('num')) def test_complex_query(self): query = Query(Author) where", "def test_negated_nullable(self): query = Query(Item) where = query.build_where(~Q(modified__lt=datetime(2017, 1, 1)))", "Q(objectb=None)) a_isnull = where.children[0] self.assertIsInstance(a_isnull, RelatedIsNull) self.assertIsInstance(a_isnull.lhs, SimpleCol) self.assertEqual(a_isnull.lhs.target, ObjectC._meta.get_field('objecta'))", "Lower) self.assertIsInstance(lookup.lhs.lhs, SimpleCol) self.assertEqual(lookup.lhs.lhs.target, Author._meta.get_field('name')) def test_negated_nullable(self): query = Query(Item)", "F, Q from django.db.models.expressions import SimpleCol from django.db.models.fields.related_lookups import RelatedIsNull", "where.children[0] self.assertIsInstance(lookup, GreaterThan) self.assertIsInstance(lookup.rhs, SimpleCol) self.assertIsInstance(lookup.lhs, SimpleCol) self.assertEqual(lookup.rhs.target, Item._meta.get_field('created')) self.assertEqual(lookup.lhs.target,", "self.assertIsInstance(lookup.lhs.lhs, SimpleCol) self.assertEqual(lookup.lhs.lhs.target, Author._meta.get_field('name')) def test_negated_nullable(self): query = Query(Item) where", "query = Query(Author) where = query.build_where(Q(num__gt=2)) lookup = where.children[0] self.assertIsInstance(lookup,", "IsNull) self.assertEqual(lookup.lhs.target, Item._meta.get_field('modified')) def test_foreign_key(self): query = Query(Item) msg =", "query = Query(Ranking) with self.assertRaises(FieldError): query.build_where(Q(rank__gt=F('author__num'))) def test_foreign_key_exclusive(self): query =", "GreaterThan) self.assertEqual(lookup.rhs, 2) self.assertEqual(lookup.lhs.target, Author._meta.get_field('num')) def test_complex_query(self): query = Query(Author)", "TestCase from django.test.utils import register_lookup from .models import Author, Item,", "GreaterThan) self.assertEqual(lookup.rhs, 2) self.assertEqual(lookup.lhs.target, Author._meta.get_field('num')) lookup = where.children[1] self.assertIsInstance(lookup, LessThan)", "= where.children[1] self.assertIsInstance(lookup, LessThan) self.assertEqual(lookup.rhs, 0) self.assertEqual(lookup.lhs.target, Author._meta.get_field('num')) def test_multiple_fields(self):", "query.build_where(Q(creator__num__gt=2)) def test_foreign_key_f(self): query = Query(Ranking) with self.assertRaises(FieldError): query.build_where(Q(rank__gt=F('author__num'))) def", "Exact, GreaterThan, IsNull, LessThan from django.db.models.sql.query import Query from django.db.models.sql.where", "from django.test import TestCase from django.test.utils import register_lookup from .models", "Query(Item) where = query.build_where(Q(modified__gt=F('created'))) lookup = where.children[0] self.assertIsInstance(lookup, GreaterThan) self.assertIsInstance(lookup.rhs,", "def test_simple_query(self): query = Query(Author) where = query.build_where(Q(num__gt=2)) lookup =", "query = Query(Author) where = query.build_where(Q(num__gt=2) | Q(num__lt=0)) self.assertEqual(where.connector, OR)", "= where.children[1] self.assertIsInstance(lookup, IsNull) self.assertEqual(lookup.lhs.target, Item._meta.get_field('modified')) def test_foreign_key(self): query =", "msg = 'Joined field references are not permitted in this", "= where.children[0] self.assertIsInstance(lookup, GreaterThan) self.assertEqual(lookup.rhs, 2) self.assertEqual(lookup.lhs.target, Author._meta.get_field('num')) def test_complex_query(self):", "SimpleCol) self.assertEqual(a_isnull.lhs.target, ObjectC._meta.get_field('objecta')) b_isnull = where.children[1] self.assertIsInstance(b_isnull, RelatedIsNull) self.assertIsInstance(b_isnull.lhs, SimpleCol)", "GreaterThan, IsNull, LessThan from django.db.models.sql.query import Query from django.db.models.sql.where import", "from django.core.exceptions import FieldError from django.db.models import CharField, F, Q", "OR from django.test import TestCase from django.test.utils import register_lookup from", "test_complex_query(self): query = Query(Author) where = query.build_where(Q(num__gt=2) | Q(num__lt=0)) self.assertEqual(where.connector,", "= where.children[0] self.assertIsInstance(a_isnull, RelatedIsNull) self.assertIsInstance(a_isnull.lhs, SimpleCol) self.assertEqual(a_isnull.lhs.target, ObjectC._meta.get_field('objecta')) b_isnull =", "RelatedIsNull) self.assertIsInstance(a_isnull.lhs, SimpleCol) self.assertEqual(a_isnull.lhs.target, ObjectC._meta.get_field('objecta')) b_isnull = where.children[1] self.assertIsInstance(b_isnull, RelatedIsNull)", "query = Query(Item) where = query.build_where(~Q(modified__lt=datetime(2017, 1, 1))) self.assertTrue(where.negated) lookup", "2) self.assertEqual(lookup.lhs.target, Author._meta.get_field('num')) lookup = where.children[1] self.assertIsInstance(lookup, LessThan) self.assertEqual(lookup.rhs, 0)", "def test_multiple_fields(self): query = Query(Item) where = query.build_where(Q(modified__gt=F('created'))) lookup =", "in this query' with self.assertRaisesMessage(FieldError, msg): query.build_where(Q(creator__num__gt=2)) def test_foreign_key_f(self): query", "Lower from django.db.models.lookups import Exact, GreaterThan, IsNull, LessThan from django.db.models.sql.query", "query = Query(Item) where = query.build_where(Q(modified__gt=F('created'))) lookup = where.children[0] self.assertIsInstance(lookup,", "query.build_where(Q(rank__gt=F('author__num'))) def test_foreign_key_exclusive(self): query = Query(ObjectC) where = query.build_where(Q(objecta=None) |", "= Query(Author) with register_lookup(CharField, Lower): where = query.build_where(~Q(name__lower='foo')) lookup =", "SimpleCol) self.assertEqual(lookup.lhs.lhs.target, Author._meta.get_field('name')) def test_negated_nullable(self): query = Query(Item) where =", "Query(Item) where = query.build_where(~Q(modified__lt=datetime(2017, 1, 1))) self.assertTrue(where.negated) lookup = where.children[0]", "def test_foreign_key_f(self): query = Query(Ranking) with self.assertRaises(FieldError): query.build_where(Q(rank__gt=F('author__num'))) def test_foreign_key_exclusive(self):", "self.assertEqual(lookup.lhs.target, Item._meta.get_field('modified')) def test_foreign_key(self): query = Query(Item) msg = 'Joined", "Item._meta.get_field('created')) self.assertEqual(lookup.lhs.target, Item._meta.get_field('modified')) def test_transform(self): query = Query(Author) with register_lookup(CharField,", "self.assertIsInstance(lookup, LessThan) self.assertEqual(lookup.lhs.target, Item._meta.get_field('modified')) lookup = where.children[1] self.assertIsInstance(lookup, IsNull) self.assertEqual(lookup.lhs.target,", "Author._meta.get_field('num')) lookup = where.children[1] self.assertIsInstance(lookup, LessThan) self.assertEqual(lookup.rhs, 0) self.assertEqual(lookup.lhs.target, Author._meta.get_field('num'))", "TestQuery(TestCase): def test_simple_query(self): query = Query(Author) where = query.build_where(Q(num__gt=2)) lookup", "class TestQuery(TestCase): def test_simple_query(self): query = Query(Author) where = query.build_where(Q(num__gt=2))", "= query.build_where(Q(num__gt=2) | Q(num__lt=0)) self.assertEqual(where.connector, OR) lookup = where.children[0] self.assertIsInstance(lookup,", "query.build_where(~Q(modified__lt=datetime(2017, 1, 1))) self.assertTrue(where.negated) lookup = where.children[0] self.assertIsInstance(lookup, LessThan) self.assertEqual(lookup.lhs.target,", "query.build_where(Q(objecta=None) | Q(objectb=None)) a_isnull = where.children[0] self.assertIsInstance(a_isnull, RelatedIsNull) self.assertIsInstance(a_isnull.lhs, SimpleCol)", "where.children[0] self.assertIsInstance(a_isnull, RelatedIsNull) self.assertIsInstance(a_isnull.lhs, SimpleCol) self.assertEqual(a_isnull.lhs.target, ObjectC._meta.get_field('objecta')) b_isnull = where.children[1]", "SimpleCol) self.assertEqual(lookup.rhs.target, Item._meta.get_field('created')) self.assertEqual(lookup.lhs.target, Item._meta.get_field('modified')) def test_transform(self): query = Query(Author)", "lookup = where.children[0] self.assertIsInstance(lookup, LessThan) self.assertEqual(lookup.lhs.target, Item._meta.get_field('modified')) lookup = where.children[1]", "lookup = where.children[0] self.assertIsInstance(lookup, GreaterThan) self.assertEqual(lookup.rhs, 2) self.assertEqual(lookup.lhs.target, Author._meta.get_field('num')) lookup", "2) self.assertEqual(lookup.lhs.target, Author._meta.get_field('num')) def test_complex_query(self): query = Query(Author) where =", "CharField, F, Q from django.db.models.expressions import SimpleCol from django.db.models.fields.related_lookups import", "self.assertEqual(lookup.lhs.target, Author._meta.get_field('num')) lookup = where.children[1] self.assertIsInstance(lookup, LessThan) self.assertEqual(lookup.rhs, 0) self.assertEqual(lookup.lhs.target,", "test_foreign_key_f(self): query = Query(Ranking) with self.assertRaises(FieldError): query.build_where(Q(rank__gt=F('author__num'))) def test_foreign_key_exclusive(self): query" ]
[ "= True if use_mp: pool = Pool(processes=2) # Well be", "lr=lr) else: optimizer = Adam(params, lr=lr) for i in range(t_max):", "pi = F.softmax(thetas_dec[i][dec_state] * beta, -1) pi_dec.append(pi) return pi_pcs, pi_dec,", "in [0, 1]: for obs_0 in [0, 1]: for obs_1", "payoff values [5, 0, 0, 2, 0], [0, 1, 2,", "r_s = -loss.data.numpy() optimizer.zero_grad() loss.backward() optimizer.step() if i % (t_max", "p_joint_ck2) + \\ p_one * make_joint(p_joint_ck2, p_joint_ck1) + \\ (p_one", "appending results to these lists run_results = [] for run", "isinstance(_v, (list, tuple)) else [_v] for _v in thetas.values()]) params", "+ \\ p_both * p_joint_ck2 + \\ p_one * make_joint(p_joint_ck1,", "p_joint_val = p_joint_all_noise_alt(pol_vals, pi_dec, p_ck_noise, ck_state) # Expected return is", "n_actions).clone().sum(dim=0) p_marg_ag1_ck1 = pi_pcs[1][1:].view(n_actions, n_actions).clone().sum(dim=1) p_marg_ag1_ck2 = pi_pcs[2][1:].view(n_actions, n_actions).clone().sum(dim=1) p_joint_ck0", "linewidth=1) ax.set_title(titles[pl]) plt.legend() plt.xticks([0, 0.5, 1]) plt.yticks([0.5, 0.75, 1]) plt.savefig(\"MACKRL", "for param in params: param = param.to(\"cuda\") if optim ==", "= init.normal_(torch.zeros(n_states_joint, n_actions ** 2 + 1, requires_grad=True), std=0.1) #", "= p_vec if not os.path.exists(os.path.join(os.path.dirname(os.path.abspath(__file__)), \"pickles\")): os.makedirs(os.path.join(os.path.dirname(os.path.abspath(__file__)), \"pickles\")) pickle.dump(res_dict, open(os.path.join(os.path.dirname(os.path.abspath(__file__)),", "torch.ger(p_marg_ag0_ck2, pi_dec[1]) \\ + p_one * p_d_ck2 * (1 -", "low1: p_final[i] = torch.min(high1, high2) - low1 pass elif low2", "= p1.clone().view(-1) p2 = p2.clone().view(-1) p_final = p1.clone().zero_() if mode", "1 return common_knowledge, observations, matrix_id # Calculate the expected return:", "in range(t_max): if run in ['MACKRL', 'JAL', 'IAC']: loss =", "p_joint = pi_pc[1:].view(n_actions, n_actions).clone() pi_a_pi_b = torch.ger(pi_dec[0], pi_dec[1]) p_joint =", "(1 - p_d_ck2) * torch.ger(pi_dec[0], p_marg_ag1_ck2) \\ + p_one *", "/ (n_trials)**0.5 high = this_mean + std / (n_trials)**0.5 mean_vals.append(", "return p_joint # always delegate elif ck_state == 1: p_joint", "as np import matplotlib.pyplot as plt use_cuda = False payoff_values", "# apply temperature to set testing pi_pcs.append(F.softmax(pol_vals[i] * beta, -1))", "if common_knowledge == 1: observations = np.repeat(matrix_id, 2) else: observations", "_proc(args): p_common, p_observation, run, p_ck_noise, t_max, n_trials = args results", "common_knowledge, observations, matrix_id = get_state(ck, obs_0, obs_1, matrix_id) # Get", "expected_return(p_common, p_observation, thetas, run, True, p_ck_noise) results_log_test[i // (t_max //", "pi_dec[1]) \\ + p_one * p_d_ck2 * (1 - p_d_ck1)", "= 2 n_actions = len(payoff_values[0]) n_states_dec = 5 n_states_joint =", "be executed online, no need to download anything # http://pytorch.org/", "2 # both noised p_one = (1-p_ck_noise) * p_ck_noise #", "for i in range(p1.shape[0]): # calculate overlap between the probability", "+ \\ p_one * make_joint(p_joint_ck1, p_joint_ck2) + \\ (p_one *", "independent learner and joint-action-learner # independent learner has a pair", "for pl in [0,1]: ax = plt.subplot(1, 1, 1) for", "[_proc((pc, p_observation, run, pnoise, t_max, n_trials)) for pc in p_vec", "* expected_ret return ret_val def _proc(args): p_common, p_observation, run, p_ck_noise,", "== 0: pol_vals = theta_joint[ck_state, :].clone() # logits get masked", "\\ p_both * p_joint_ck2 + \\ p_one * make_joint(p_joint_ck1, p_joint_ck2)", "to the independent agents. # theta_joint = init.normal_(torch.zeros(n_states_joint, n_actions **", "p_ck_noise: {}\".format(labels[i], pcknoise)) plt.fill_between(p_vec, min_vals, max_vals, facecolor=color[i], alpha=0.3) plt.xlabel('P(common knowledge)')", "(pc, p_observation, run, pnoise, t_max, n_trials) for pc in p_vec", "p_d_ck1 * torch.ger(p_marg_ag0_ck2, pi_dec[1]) return p_joint pass def get_policies(common_knowledge, observations,", "1 actions = [] pi_dec = [] # common_knowledge decides", "the expected return: sum_{\\tau} P(\\tau | pi) R(\\tau) def expected_return(p_common,", "get_policies(common_knowledge, observations, run, test, thetas_dec, theta_joint, p_ck_noise=0): if test: beta", "std=std_val) for i in range(n_agents)] thetas[\"joint\"] = init.normal_(torch.zeros(n_states_joint, n_actions **", "p_d_ck2) * p_d_ck1 * torch.ger(p_marg_ag0_ck2, pi_dec[1]) return p_joint pass def", "def get_policies(common_knowledge, observations, run, test, thetas_dec, theta_joint, p_ck_noise=0): if test:", "int(observations[0] + 1) if p_ck_noise == 0: pol_vals = theta_joint[ck_state,", "1.0 # These are the 3 settings we run: MACRKL,", "the 3 settings we run: MACRKL, Joint-action-learner (always uses CK),", "** 2 # both unnoised p_both = (p_ck_noise) ** 2", "results_log = np.zeros((t_max // (t_max // 100),)) results_log_test = np.zeros((t_max", "- p_observation, p_observation] # Matrices are chosen 50 / 50", "p_joint_ck1 = pi_pcs[1][1:].view(n_actions, n_actions).clone() p_joint_ck2 = pi_pcs[2][1:].view(n_actions, n_actions).clone() p_d_ck0 =", "a high learning rate, since we have exact gradients lr", "'c', 'm', 'y', 'k'] titles = ['Test', 'Train Performance'] for", "theta_joint, p_ck_noise=0): if test: beta = 100 else: beta =", "make_joint(p1, p2, mode=\"interval\"): \"\"\" 1. Pick uniform random variable between", "pool.close() pool.join() else: # Well be appending results to these", "obs_1, matrix_id) # Get final probabilities for joint actions if", "+ p_one * p_d_ck1 * p_d_ck2 + p_both * p_d_ck1", "= np.zeros((t_max // (t_max // 100),)) results_log_test = np.zeros((t_max //", "# apply temperature to set testing pi_pc = F.softmax(pol_vals *", "p_observation] # Matrices are chosen 50 / 50 p_matrix =", "matrix_id in [0, 1]: for obs_0 in [0, 1]: for", "values [0, 0, 1, 0, 5], [0, 0, 2, 0,", "final_res.append([all_res_test, all_res]) pool.close() pool.join() else: # Well be appending results", "+ p_one * p_d_ck2 * p_d_ck1 + p_both * p_d_ck2", "(1 - p_d_ck2) * p_d_ck1 * torch.ger(p_marg_ag0_ck2, pi_dec[1]) \\ +", "optimizer = Adam(params, lr=lr) for i in range(t_max): if run", "uniform random variable between [0,1] 2. Do multinomial sampling through", "pol_vals[i][0] = -10 ** 10 elif run == 'IAC': pol_vals[i][1:]", "100 else: beta = 1 actions = [] pi_dec =", "all_res.append(np.stack([r[1] for r in results], axis=1)) final_res.append([all_res_test, all_res]) import pickle", "= ['Test', 'Train Performance'] for pl in [0,1]: ax =", "= pi_pc[1:].view(n_actions, n_actions).clone() pi_a_pi_b = torch.ger(pi_dec[0], pi_dec[1]) p_joint = pi_pc[0]", "+ 1 action for delegation to the independent agents. #", "P(\\tau | pi) R(\\tau) def expected_return(p_common, p_observation, thetas, run, test,", "(Eg. n_trials = 20) #n_trials = 100 # 30 n_trials", "= p_ck_noise res_dict[\"p_vec\"] = p_vec if not os.path.exists(os.path.join(os.path.dirname(os.path.abspath(__file__)), \"pickles\")): os.makedirs(os.path.join(os.path.dirname(os.path.abspath(__file__)),", "== 1: p_joint = p_none * p_joint_ck1 + \\ p_both", "import torch import torch.nn.functional as F from torch.multiprocessing import Pool,", "temperature to set testing pi_pc = F.softmax(pol_vals * beta, -1)", "* p_matrix[matrix_id] common_knowledge, observations, matrix_id = get_state(ck, obs_0, obs_1, matrix_id)", "+ p_one * p_d_ck1 * (1 - p_d_ck2) * torch.ger(pi_dec[0],", "Probability of CK p_common_val = [1 - p_common, p_common] #", "optimizer = SGD(params, lr=lr) else: optimizer = Adam(params, lr=lr) for", "in enumerate(labels): for pnoise_id, pnoise in enumerate(p_ck_noise): try: results =", "0, 0], [0, 0, 1, 0, 0], ], dtype=torch.float32) *", "pi_dec.append(pi) return pi_pcs, pi_dec, ck_state def get_state(common_knowledge, obs_0, obs_1, matrix_id):", "p_common_id, p_common in enumerate(p_vec): all_res = [] all_res_test = []", "min_vals = [] max_vals = [] for j, p in", "for both p1, p2 \"\"\" p1 = p1.clone().view(-1) p2 =", "= 0 else: ck_state = int(observations[0] + 1) if p_ck_noise", "= p2.clone().view(-1) p_final = p1.clone().zero_() if mode == \"interval\": for", "= \"{} p_ck_noise: {}\".format(labels[i], pcknoise)) plt.fill_between(p_vec, min_vals, max_vals, facecolor=color[i], alpha=0.3)", "beta, -1) pi_dec.append(pi) return pi_pc, pi_dec else: pol_vals = theta_joint.clone()", "optimizer.zero_grad() loss.backward() optimizer.step() if i % (t_max // 100) ==", "ck_state is informative if common_knowledge == 0: ck_state = 0", "p1[i] low2 = torch.sum(p2[:i]) high2 = low2 + p2[i] if", "optimizer.step() if i % (t_max // 100) == 0: if", "n_actions).clone().sum(dim=1) p_joint_ck0 = pi_pcs[0][1:].view(n_actions, n_actions).clone() p_joint_ck1 = pi_pcs[1][1:].view(n_actions, n_actions).clone() p_joint_ck2", "overlap between the probability distributions low1 = torch.sum(p1[:i]) high1 =", "for independent learner and joint-action-learner # independent learner has a", "int(observations[i]) pi = F.softmax(thetas_dec[i][dec_state] * beta, -1) pi_dec.append(pi) return pi_pcs,", "n_actions ** 2 + 1, requires_grad=True), std=std_val) params = chain(*[_v", "return common_knowledge, observations, matrix_id # Calculate the expected return: sum_{\\tau}", "CK), # Independent Actor-Critic (always uses decentralised actions selection) labels", "test, thetas_dec, theta_joint, p_ck_noise) p_joint_val = p_joint_all_noise_alt(pol_vals, pi_dec, p_ck_noise, ck_state)", "= (1-p_ck_noise) * p_ck_noise # exactly one noised p_marg_ag0_ck1 =", "= pi_pcs[1][1:].view(n_actions, n_actions).clone().sum(dim=0) p_marg_ag0_ck2 = pi_pcs[2][1:].view(n_actions, n_actions).clone().sum(dim=0) p_marg_ag1_ck1 = pi_pcs[1][1:].view(n_actions,", "be using a high learning rate, since we have exact", "= pool.map(_proc, [ (pc, p_observation, run, pnoise, t_max, n_trials) for", "common_knowledge == 1: observations = np.repeat(matrix_id, 2) else: observations =", "[] max_vals = [] for j, p in enumerate( p_vec", "0.0] # DEBUG! # Initialise expected return ret_val = 0", "= p_common_val[ck] * p_obs_val[obs_0] * p_obs_val[obs_1] * p_matrix[matrix_id] common_knowledge, observations,", "100 # 30 n_trials = 20 #15 #100 std_val =", "import Adam, SGD import numpy as np import matplotlib.pyplot as", "if you are short on time. (Eg. n_trials = 20)", "set_start_method, freeze_support try: set_start_method('spawn') except RuntimeError: pass from torch.nn import", "pi_pc[0] * pi_a_pi_b + p_joint return p_joint def p_joint_all_noise_alt(pi_pcs, pi_dec,", "in p_vec ] noise_results.append(results) run_results.append(noise_results) for p_common_id, p_common in enumerate(p_vec):", "= np.zeros((t_max // (t_max // 100),)) thetas = {} thetas[\"dec\"]", "if use_cuda: for param in params: param = param.to(\"cuda\") if", "p_marg_ag1_ck1 = pi_pcs[1][1:].view(n_actions, n_actions).clone().sum(dim=1) p_marg_ag1_ck2 = pi_pcs[2][1:].view(n_actions, n_actions).clone().sum(dim=1) p_joint_ck0 =", "The entire notebook can be executed online, no need to", "independent learner has a pair controller that always delegates if", "= final_res res_dict[\"labels\"] = labels res_dict[\"p_ck_noise\"] = p_ck_noise res_dict[\"p_vec\"] =", "n_mix_hidden = 3 p_observation = 0.5 p_ck_noise = [0.0] #", "p_common, p_common] # Probability of observation given no CK) p_obs_val", "202 # We'll be using a high learning rate, since", "p_observation, thetas, run, True, p_ck_noise) results_log_test[i // (t_max // 100)]", "p_one * p_d_ck2 * p_d_ck1 + p_both * p_d_ck2 +", "out for independent learner and joint-action-learner # independent learner has", "= 0 return p_final.clone().view(n_actions, n_actions) if ck_state == 0: p_joint", "obs_1] if common_knowledge == 1: observations = np.repeat(matrix_id, 2) else:", "= [obs_0, obs_1] if common_knowledge == 1: observations = np.repeat(matrix_id,", "exact gradients lr = 0.05 # DEBUG: 0.05 if exact", "- p_d_ck1) * p_d_ck2 * torch.ger(p_marg_ag0_ck1, pi_dec[1]) \\ + p_one", "noise_results = [] for pnoise in p_ck_noise: print(\"Run: {} P_CK_NOISE:", "= ['b', 'r','g', 'c', 'm', 'y', 'k','b', 'r','g', 'c', 'm',", "** 2 + 1, requires_grad=True), std=std_val) params = chain(*[_v if", "thetas.values()]) params = list(params) if use_cuda: for param in params:", "* 2 # for ag in range(n_agents): if receives_obs[ag]: observations[ag]", "0.5 p_ck_noise = [0.0] # Number of gradient steps t_max", "for obs_1 in [0, 1]: p_state = p_common_val[ck] * p_obs_val[obs_0]", "obs_0 in [0, 1]: for obs_1 in [0, 1]: p_state", "beta = 1 actions = [] pi_dec = [] #", "-10 ** 10 # apply temperature to set testing pi_pc", "return: sum_{\\tau} P(\\tau | pi) R(\\tau) def expected_return(p_common, p_observation, thetas,", "p_joint_ck0 = pi_pcs[0][1:].view(n_actions, n_actions).clone() p_joint_ck1 = pi_pcs[1][1:].view(n_actions, n_actions).clone() p_joint_ck2 =", "no CK) p_obs_val = [1 - p_observation, p_observation] # Matrices", "Calculate the expected return: sum_{\\tau} P(\\tau | pi) R(\\tau) def", "test, p_ck_noise=0): thetas_dec = thetas[\"dec\"] theta_joint = thetas[\"joint\"] # Probability", "on time. (Eg. n_trials = 20) #n_trials = 100 #", "* payoff_values[matrix_id]).sum() # Add return from given state ret_val =", "# DEBUG: 0.05 if exact gradients! optim = 'adam' #", "in enumerate( p_vec ): vals = final_res[j][pl] this_mean = np.mean(", "p_d_ck1) * p_d_ck2 * torch.ger(p_marg_ag0_ck1, pi_dec[1]) \\ + p_one *", "thetas_dec = thetas[\"dec\"] theta_joint = thetas[\"joint\"] # Probability of CK", "observations = np.repeat(matrix_id, 2) else: observations = np.ones((n_agents)) * 2", "steps t_max = 202 # We'll be using a high", "and high1 > low2: p_final[i] = torch.min(high1, high2) - low2", "else: # Well be appending results to these lists run_results", "2. Do multinomial sampling through contiguous, ordered bucketing for both", "(t_max // 100)] = r_s results.append((results_log_test, results_log)) return results def", "ax.grid(color='k', linestyle='-', linewidth=1) ax.set_title(titles[pl]) plt.legend() plt.xticks([0, 0.5, 1]) plt.yticks([0.5, 0.75,", "p_d_ck1 * (1 - p_d_ck2) * torch.ger(pi_dec[0], p_marg_ag1_ck2) \\ +", "axis=1)) final_res.append([all_res_test, all_res]) pool.close() pool.join() else: # Well be appending", "theta_joint) p_joint_val = p_joint_all(pi_pc, pi_dec) else: pol_vals, pi_dec, ck_state =", "10 elif run == 'IAC': pol_vals[1:] = -10 ** 10", "return is just the elementwise product of rewards and action", "if exact gradients! optim = 'adam' # You can reduce", "CK) p_obs_val = [1 - p_observation, p_observation] # Matrices are", "to download anything # http://pytorch.org/ from itertools import chain import", "== 0: p_joint = p_joint_ck0 + p_d_ck0 * torch.ger(pi_dec[0], pi_dec[1])", "theta_joint = thetas[\"joint\"] # Probability of CK p_common_val = [1", "= pi_pcs[0][1:].view(n_actions, n_actions).clone() p_joint_ck1 = pi_pcs[1][1:].view(n_actions, n_actions).clone() p_joint_ck2 = pi_pcs[2][1:].view(n_actions,", "[0.0, 0.2, 0.4, 0.6, 0.8, 1.0] final_res = [] #", "- p_d_ck1) * p_d_ck2 * torch.ger(p_marg_ag0_ck1, pi_dec[1]) return p_joint elif", "for # # joint action + 1 action for delegation", "SGD(params, lr=lr) else: optimizer = Adam(params, lr=lr) for i in", "p in enumerate( p_vec ): vals = final_res[j][pl] this_mean =", "get_policies(common_knowledge, observations, run, test, thetas_dec, theta_joint) p_joint_val = p_joint_all(pi_pc, pi_dec)", "{}\".format(run, pnoise)) results = [_proc((pc, p_observation, run, pnoise, t_max, n_trials))", "std / (n_trials)**0.5 mean_vals.append( this_mean ) min_vals.append( low ) max_vals.append(", "print(\"Run: {} P_CK_NOISE: {}\".format(run, pnoise)) results = pool.map(_proc, [ (pc,", "# always delegate elif ck_state == 1: p_joint = p_none", "0, 0], ], dtype=torch.float32) * 0.2) payoff_values.append( torch.tensor([ # payoff", "(p_joint_val * payoff_values[matrix_id]).sum() # Add return from given state ret_val", "observations, matrix_id # Calculate the expected return: sum_{\\tau} P(\\tau |", "final_res res_dict[\"labels\"] = labels res_dict[\"p_ck_noise\"] = p_ck_noise res_dict[\"p_vec\"] = p_vec", "= [] min_vals = [] max_vals = [] for j,", "p_ck_noise = [0.0] # Number of gradient steps t_max =", "= 0.05 # DEBUG: 0.05 if exact gradients! optim =", "return pi_pcs, pi_dec, ck_state def get_state(common_knowledge, obs_0, obs_1, matrix_id): receives_obs", "= len(payoff_values[0]) n_states_dec = 5 n_states_joint = 3 n_mix_hidden =", "pi_dec = [] # common_knowledge decides whether ck_state is informative", "Number of gradient steps t_max = 202 # We'll be", "run, p_ck_noise, t_max, n_trials = args results = [] for", "run, test, p_ck_noise=0): thetas_dec = thetas[\"dec\"] theta_joint = thetas[\"joint\"] #", "0, 2, 0], [0, 0, 0, 1, 0], [0, 0,", "(t_max // 100),)) results_log_test = np.zeros((t_max // (t_max // 100),))", "action probabilities expected_ret = (p_joint_val * payoff_values[matrix_id]).sum() # Add return", "pi_dec): p_joint = pi_pc[1:].view(n_actions, n_actions).clone() pi_a_pi_b = torch.ger(pi_dec[0], pi_dec[1]) p_joint", "results = pool.map(_proc, [ (pc, p_observation, run, pnoise, t_max, n_trials)", "state ret_val = ret_val + p_state * expected_ret return ret_val", "= pi_pcs[1][1:].view(n_actions, n_actions).clone().sum(dim=1) p_marg_ag1_ck2 = pi_pcs[2][1:].view(n_actions, n_actions).clone().sum(dim=1) p_joint_ck0 = pi_pcs[0][1:].view(n_actions,", "these lists run_results = [] for run in labels: noise_results", "np.mean( vals[i*len(p_ck_noise) + pck], 1)[-1] std = np.std(vals[i], 1)[-1]/0.5 low", "* p_d_ck1 + p_both * p_d_ck2 + p_none * p_d_ck1)", "p_marg_ag1_ck1) \\ + p_one * (1 - p_d_ck1) * p_d_ck2", "0: p_joint = p_joint_ck0 + p_d_ck0 * torch.ger(pi_dec[0], pi_dec[1]) return", "pi) R(\\tau) def expected_return(p_common, p_observation, thetas, run, test, p_ck_noise=0): thetas_dec", "low2 and high2 > low1: p_final[i] = torch.min(high1, high2) -", "results_log_test = np.zeros((t_max // (t_max // 100),)) thetas = {}", "testing pi_pc = F.softmax(pol_vals * beta, -1) # calcuate decentralised", "torch.ger(pi_dec[0], pi_dec[1]) \\ + p_one * p_d_ck2 * (1 -", "gradients! optim = 'adam' # You can reduce this number", "pol_vals[0] = -10 ** 10 elif run == 'IAC': pol_vals[1:]", "final_res[j][pl] this_mean = np.mean( vals[i*len(p_ck_noise) + pck], 1)[-1] std =", "thetas = {} thetas[\"dec\"] = [init.normal_(torch.zeros(n_states_dec, n_actions, requires_grad=True), std=std_val) for", "** 2 # both noised p_one = (1-p_ck_noise) * p_ck_noise", "p_joint = p_none * p_joint_ck1 + \\ p_both * p_joint_ck2", "range(t_max): if run in ['MACKRL', 'JAL', 'IAC']: loss = -", "for ck in [0, 1]: for matrix_id in [0, 1]:", "pl in [0,1]: ax = plt.subplot(1, 1, 1) for i", "p_joint elif ck_state == 2: p_joint = p_none * p_joint_ck2", "return pi_pc, pi_dec else: pol_vals = theta_joint.clone() pi_pcs = []", "-1) pi_dec.append(pi) return pi_pc, pi_dec else: pol_vals = theta_joint.clone() pi_pcs", "r in results], axis=1)) final_res.append([all_res_test, all_res]) import pickle import uuid", "high1 = low1 + p1[i] low2 = torch.sum(p2[:i]) high2 =", "notebook can be executed online, no need to download anything", "\\ + p_one * (1 - p_d_ck2) * p_d_ck1 *", "pi_pcs[1][1:].view(n_actions, n_actions).clone() p_joint_ck2 = pi_pcs[2][1:].view(n_actions, n_actions).clone() p_d_ck0 = pi_pcs[0][0] p_d_ck1", "high2 > low1: p_final[i] = torch.min(high1, high2) - low1 pass", "] noise_results.append(results) run_results.append(noise_results) for p_common_id, p_common in enumerate(p_vec): all_res =", "30 n_trials = 20 #15 #100 std_val = 1.0 #", "We'll be using a high learning rate, since we have", "is just the elementwise product of rewards and action probabilities", "always delegates if run == 'JAL': pol_vals[0] = -10 **", "+ pck) % len(color)], label = \"{} p_ck_noise: {}\".format(labels[i], pcknoise))", "= [] pi_dec = [] # common_knowledge decides whether ck_state", "= pi_pcs[1][0] p_d_ck2 = pi_pcs[2][0] def make_joint(p1, p2, mode=\"interval\"): \"\"\"", "# calcuate decentralised policies for i in range(n_agents): dec_state =", "p_joint_ck2 + \\ p_one * make_joint(p_joint_ck1, p_joint_ck2) + \\ p_one", "http://pytorch.org/ from itertools import chain import torch import torch.nn.functional as", "pck) % len(color)], label = \"{} p_ck_noise: {}\".format(labels[i], pcknoise)) plt.fill_between(p_vec,", "1. Pick uniform random variable between [0,1] 2. Do multinomial", "-1) pi_dec.append(pi) return pi_pcs, pi_dec, ck_state def get_state(common_knowledge, obs_0, obs_1,", "= p_joint_all_noise_alt(pol_vals, pi_dec, p_ck_noise, ck_state) # Expected return is just", "param.to(\"cuda\") if optim == 'sgd': optimizer = SGD(params, lr=lr) else:", "pi_pcs, pi_dec, ck_state def get_state(common_knowledge, obs_0, obs_1, matrix_id): receives_obs =", "bucketing for both p1, p2 \"\"\" p1 = p1.clone().view(-1) p2", "theta_joint = init.normal_(torch.zeros(n_states_joint, n_actions ** 2 + 1, requires_grad=True), std=0.1)", "False payoff_values = [] payoff_values.append(torch.tensor([ # payoff values [5, 0,", "// (t_max // 100),)) results_log_test = np.zeros((t_max // (t_max //", "* p_joint_ck2 + \\ p_both * p_joint_ck1 + \\ p_one", "results = run_results[run_id][pnoise_id][p_common_id] except Exception as e: pass all_res_test.append(np.stack([r[0] for", "in enumerate(p_vec): all_res = [] all_res_test = [] for run_id,", "-loss.data.numpy() optimizer.zero_grad() loss.backward() optimizer.step() if i % (t_max // 100)", "run, True, p_ck_noise) results_log_test[i // (t_max // 100)] = r_test", "0], ], dtype=torch.float32) * 0.2) payoff_values.append( torch.tensor([ # payoff values", "np.std(vals[i], 1)[-1]/0.5 low = this_mean-std / (n_trials)**0.5 high = this_mean", "{}\".format(run, p_ck_noise, p_common, nt)) results_log = np.zeros((t_max // (t_max //", "def make_joint(p1, p2, mode=\"interval\"): \"\"\" 1. Pick uniform random variable", "i in range(t_max): if run in ['MACKRL', 'JAL', 'IAC']: loss", "pi_dec[1]) \\ + p_one * p_d_ck1 * (1 - p_d_ck2)", "os res_dict = {} res_dict[\"final_res\"] = final_res res_dict[\"labels\"] = labels", "pi^a * pi^b + p(u^ab) def p_joint_all(pi_pc, pi_dec): p_joint =", "for nt in range(n_trials): print(\"Run: {} P_CK_NOISE: {} P_common: {}", "** 10 elif run == 'IAC': pol_vals[i][1:] = -10 **", "* p_d_ck1 * p_d_ck2 + p_both * p_d_ck1 + p_none", "[] for run_id, run in enumerate(labels): for pnoise_id, pnoise in", "P_CK_NOISE: {} P_common: {} #Trial: {}\".format(run, p_ck_noise, p_common, nt)) results_log", "* p_d_ck2 * p_d_ck1 + p_one * p_d_ck1 * p_d_ck2", "* torch.ger(pi_dec[0], pi_dec[1]) return p_joint # always delegate elif ck_state", "in [0,1]: ax = plt.subplot(1, 1, 1) for i in", "* p_d_ck1 * (1 - p_d_ck2) * torch.ger(pi_dec[0], p_marg_ag1_ck2) \\", "\\ p_one * make_joint(p_joint_ck1, p_joint_ck2) + \\ p_one * make_joint(p_joint_ck2,", "2, 0, 0], [1, 2, 4, 2, 1], [0, 0,", "exactly one noised p_marg_ag0_ck1 = pi_pcs[1][1:].view(n_actions, n_actions).clone().sum(dim=0) p_marg_ag0_ck2 = pi_pcs[2][1:].view(n_actions,", "np import matplotlib.pyplot as plt use_cuda = False payoff_values =", "p_joint = pi_pc[0] * pi_a_pi_b + p_joint return p_joint def", "* p_d_ck2 + p_none * p_d_ck1) * torch.ger(pi_dec[0], pi_dec[1]) \\", "as e: pass all_res_test.append(np.stack([r[0] for r in results], axis=1)) all_res.append(np.stack([r[1]", "F.softmax(thetas_dec[i][dec_state] * beta, -1) pi_dec.append(pi) return pi_pc, pi_dec else: pol_vals", "else: p_final[i] = 0 return p_final.clone().view(n_actions, n_actions) if ck_state ==", "# Matrices are chosen 50 / 50 p_matrix = [0.5,", "# for ag in range(n_agents): if receives_obs[ag]: observations[ag] += matrix_id", "are chosen 50 / 50 p_matrix = [0.5, 0.5] #", "+ \\ p_one * make_joint(p_joint_ck2, p_joint_ck1) + \\ (p_one *", "in range(n_agents): if receives_obs[ag]: observations[ag] += matrix_id + 1 return", "20) #n_trials = 100 # 30 n_trials = 20 #15", "p_both * p_joint_ck2 + \\ p_one * make_joint(p_joint_ck1, p_joint_ck2) +", "= -10 ** 10 elif run == 'IAC': pol_vals[i][1:] =", "titles = ['Test', 'Train Performance'] for pl in [0,1]: ax", "Joint-action-learner (always uses CK), # Independent Actor-Critic (always uses decentralised", "t_max, n_trials) for pc in p_vec ]) noise_results.append(results) run_results.append(noise_results) for", "* beta, -1) pi_dec.append(pi) return pi_pcs, pi_dec, ck_state def get_state(common_knowledge,", "# exactly one noised p_marg_ag0_ck1 = pi_pcs[1][1:].view(n_actions, n_actions).clone().sum(dim=0) p_marg_ag0_ck2 =", "in ['MACKRL', 'JAL', 'IAC']: loss = - expected_return(p_common, p_observation, thetas,", "1, requires_grad=True), std=0.1) # Produce marginalised policy: pi_pc[0] * pi^a", "print(\"Run: {} P_CK_NOISE: {}\".format(run, pnoise)) results = [_proc((pc, p_observation, run,", "1)[-1]/0.5 low = this_mean-std / (n_trials)**0.5 high = this_mean +", "torch.tensor([ # payoff values [0, 0, 1, 0, 5], [0,", "knowledge)') plt.ylabel('Expected Return') plt.ylim([0.0, 1.01]) plt.xlim([-0.01, 1.01]) ax.set_facecolor((1.0, 1.0, 1.0))", "pi_a_pi_b = torch.ger(pi_dec[0], pi_dec[1]) p_joint = pi_pc[0] * pi_a_pi_b +", "plt use_cuda = False payoff_values = [] payoff_values.append(torch.tensor([ # payoff", "R(\\tau) def expected_return(p_common, p_observation, thetas, run, test, p_ck_noise=0): thetas_dec =", "whether ck_state is informative if common_knowledge == 0: ck_state =", "+ p_none * p_d_ck2) * torch.ger(pi_dec[0], pi_dec[1]) \\ + p_one", "1.0] final_res = [] # # Pair-Controller with 3 input", "ax.set_title(titles[pl]) plt.legend() plt.xticks([0, 0.5, 1]) plt.yticks([0.5, 0.75, 1]) plt.savefig(\"MACKRL {}.pdf\".format(titles[pl]))", "pi_dec[1]) p_joint = pi_pc[0] * pi_a_pi_b + p_joint return p_joint", "param in params: param = param.to(\"cuda\") if optim == 'sgd':", "* p_d_ck2) * torch.ger(pi_dec[0], pi_dec[1]) \\ + p_one * p_d_ck2", "p_marg_ag1_ck2) \\ + p_one * (1 - p_d_ck2) * p_d_ck1", "= plt.subplot(1, 1, 1) for i in range(len(labels)): for pck,", "all_res_test.append(np.stack([r[0] for r in results], axis=1)) all_res.append(np.stack([r[1] for r in", "in thetas.values()]) params = list(params) if use_cuda: for param in", "n_states_joint = 3 n_mix_hidden = 3 p_observation = 0.5 p_ck_noise", "p_state * expected_ret return ret_val def _proc(args): p_common, p_observation, run,", "\\ + p_one * (1 - p_d_ck1) * p_d_ck2 *", "pi_pcs[2][0] def make_joint(p1, p2, mode=\"interval\"): \"\"\" 1. Pick uniform random", "except Exception as e: pass all_res_test.append(np.stack([r[0] for r in results],", "0: if run in ['MACKRL', 'JAL', 'IAC']: r_test = expected_return(p_common,", "+ p_both * p_d_ck1 + p_none * p_d_ck2) * torch.ger(pi_dec[0],", "+ std / (n_trials)**0.5 mean_vals.append( this_mean ) min_vals.append( low )", "if not os.path.exists(os.path.join(os.path.dirname(os.path.abspath(__file__)), \"pickles\")): os.makedirs(os.path.join(os.path.dirname(os.path.abspath(__file__)), \"pickles\")) pickle.dump(res_dict, open(os.path.join(os.path.dirname(os.path.abspath(__file__)), \"pickles\", \"final_res_{}.p\".format(uuid.uuid4().hex[:4])),", "0.05 # DEBUG: 0.05 if exact gradients! optim = 'adam'", "n_actions).clone() pi_a_pi_b = torch.ger(pi_dec[0], pi_dec[1]) p_joint = pi_pc[0] * pi_a_pi_b", "= [0.0] # Number of gradient steps t_max = 202", "results = [] for nt in range(n_trials): print(\"Run: {} P_CK_NOISE:", "p_d_ck2 = pi_pcs[2][0] def make_joint(p1, p2, mode=\"interval\"): \"\"\" 1. Pick", "n_trials = 20 #15 #100 std_val = 1.0 # These", "pi_pcs[2][1:].view(n_actions, n_actions).clone().sum(dim=1) p_joint_ck0 = pi_pcs[0][1:].view(n_actions, n_actions).clone() p_joint_ck1 = pi_pcs[1][1:].view(n_actions, n_actions).clone()", "else [_v] for _v in thetas.values()]) params = list(params) if", "both noised p_one = (1-p_ck_noise) * p_ck_noise # exactly one", "* beta, -1) pi_dec.append(pi) return pi_pc, pi_dec else: pol_vals =", "= 20) #n_trials = 100 # 30 n_trials = 20", "run in enumerate(labels): for pnoise_id, pnoise in enumerate(p_ck_noise): try: results", "results_log_test[i // (t_max // 100)] = r_test results_log[i // (t_max", "beta, -1) # calcuate decentralised policies for i in range(n_agents):", "1, 0], [0, 0, 0, 0, 0], ], dtype=torch.float32) *", "* 0.2) n_agents = 2 n_actions = len(payoff_values[0]) n_states_dec =", "# theta_joint = init.normal_(torch.zeros(n_states_joint, n_actions ** 2 + 1, requires_grad=True),", "= 'adam' # You can reduce this number if you", "{} P_CK_NOISE: {} P_common: {} #Trial: {}\".format(run, p_ck_noise, p_common, nt))", "{} P_CK_NOISE: {}\".format(run, pnoise)) results = pool.map(_proc, [ (pc, p_observation,", "= [1 - p_common, p_common] # Probability of observation given", "// 100) == 0: if run in ['MACKRL', 'JAL', 'IAC']:", "[] for nt in range(n_trials): print(\"Run: {} P_CK_NOISE: {} P_common:", "n_actions).clone() p_d_ck0 = pi_pcs[0][0] p_d_ck1 = pi_pcs[1][0] p_d_ck2 = pi_pcs[2][0]", "for pck, pcknoise in enumerate(p_ck_noise): mean_vals = [] min_vals =", "r in results], axis=1)) final_res.append([all_res_test, all_res]) pool.close() pool.join() else: #", "'IAC': pol_vals[1:] = -10 ** 10 # apply temperature to", "for pnoise_id, pnoise in enumerate(p_ck_noise): try: results = run_results[run_id][pnoise_id][p_common_id] except", "pcknoise in enumerate(p_ck_noise): mean_vals = [] min_vals = [] max_vals", "# Expected return is just the elementwise product of rewards", "p_ck_noise==0: pi_pc, pi_dec = get_policies(common_knowledge, observations, run, test, thetas_dec, theta_joint)", "+= matrix_id + 1 return common_knowledge, observations, matrix_id # Calculate", "results_log[i // (t_max // 100)] = r_s results.append((results_log_test, results_log)) return", "p_vec ): vals = final_res[j][pl] this_mean = np.mean( vals[i*len(p_ck_noise) +", "low2: p_final[i] = torch.min(high1, high2) - low2 else: p_final[i] =", "test, thetas_dec, theta_joint) p_joint_val = p_joint_all(pi_pc, pi_dec) else: pol_vals, pi_dec,", "= [] # common_knowledge decides whether ck_state is informative if", "p1 = p1.clone().view(-1) p2 = p2.clone().view(-1) p_final = p1.clone().zero_() if", "p2[i] if low1 >= low2 and high2 > low1: p_final[i]", "p_d_ck2) * torch.ger(pi_dec[0], p_marg_ag1_ck2) \\ + p_one * (1 -", "p_joint_ck1 + \\ p_one * make_joint(p_joint_ck2, p_joint_ck1) + \\ p_one", "labels res_dict[\"p_ck_noise\"] = p_ck_noise res_dict[\"p_vec\"] = p_vec if not os.path.exists(os.path.join(os.path.dirname(os.path.abspath(__file__)),", "probabilities expected_ret = (p_joint_val * payoff_values[matrix_id]).sum() # Add return from", "= [] # # Pair-Controller with 3 input state (no", "high ) plt.plot(p_vec, mean_vals, color[(i*len(p_ck_noise) + pck) % len(color)], label", "* torch.ger(pi_dec[0], p_marg_ag1_ck1) \\ + p_one * (1 - p_d_ck1)", "# 30 n_trials = 20 #15 #100 std_val = 1.0", "enumerate(labels): for pnoise_id, pnoise in enumerate(p_ck_noise): try: results = run_results[run_id][pnoise_id][p_common_id]", "pickle import uuid import os res_dict = {} res_dict[\"final_res\"] =", "pass elif low2 >= low1 and high1 > low2: p_final[i]", "make_joint(p_joint_ck1, p_joint_ck2) + \\ (p_one * p_d_ck2 * p_d_ck1 +", "pi_pc[0] * pi^a * pi^b + p(u^ab) def p_joint_all(pi_pc, pi_dec):", "Exception as e: pass all_res_test.append(np.stack([r[0] for r in results], axis=1))", "this_mean = np.mean( vals[i*len(p_ck_noise) + pck], 1)[-1] std = np.std(vals[i],", "p_d_ck1) * torch.ger(pi_dec[0], p_marg_ag1_ck1) \\ + p_one * (1 -", "run == 'IAC': pol_vals[i][1:] = -10 ** 10 # apply", "pi_dec) else: pol_vals, pi_dec, ck_state = get_policies(common_knowledge, observations, run, test,", "for r in results], axis=1)) all_res.append(np.stack([r[1] for r in results],", "all_res]) pool.close() pool.join() else: # Well be appending results to", "1: p_joint = p_none * p_joint_ck1 + \\ p_both *", "p_ck_noise, ck_state) # Expected return is just the elementwise product", "[] for pnoise in p_ck_noise: print(\"Run: {} P_CK_NOISE: {}\".format(run, pnoise))", "== 'IAC': pol_vals[i][1:] = -10 ** 10 # apply temperature", "= (p_joint_val * payoff_values[matrix_id]).sum() # Add return from given state", "noised p_one = (1-p_ck_noise) * p_ck_noise # exactly one noised", "p_d_ck1 * p_d_ck2 + p_one * p_d_ck2 * p_d_ck1 +", "p_one * make_joint(p_joint_ck2, p_joint_ck1) + \\ (p_one * p_d_ck1 *", "2 # both unnoised p_both = (p_ck_noise) ** 2 #", "as F from torch.multiprocessing import Pool, set_start_method, freeze_support try: set_start_method('spawn')", "pcknoise)) plt.fill_between(p_vec, min_vals, max_vals, facecolor=color[i], alpha=0.3) plt.xlabel('P(common knowledge)') plt.ylabel('Expected Return')", "r in results], axis=1)) all_res.append(np.stack([r[1] for r in results], axis=1))", "# Independent Actor-Critic (always uses decentralised actions selection) labels =", "axis=1)) all_res.append(np.stack([r[1] for r in results], axis=1)) final_res.append([all_res_test, all_res]) pool.close()", "noised p_marg_ag0_ck1 = pi_pcs[1][1:].view(n_actions, n_actions).clone().sum(dim=0) p_marg_ag0_ck2 = pi_pcs[2][1:].view(n_actions, n_actions).clone().sum(dim=0) p_marg_ag1_ck1", "3 p_observation = 0.5 p_ck_noise = [0.0] # Number of", "low1 pass elif low2 >= low1 and high1 > low2:", "p_d_ck1 + p_both * p_d_ck2 + p_none * p_d_ck1) *", "alpha=0.3) plt.xlabel('P(common knowledge)') plt.ylabel('Expected Return') plt.ylim([0.0, 1.01]) plt.xlim([-0.01, 1.01]) ax.set_facecolor((1.0,", "low ) max_vals.append( high ) plt.plot(p_vec, mean_vals, color[(i*len(p_ck_noise) + pck)", "(p_one * p_d_ck2 * p_d_ck1 + p_one * p_d_ck1 *", "Get final probabilities for joint actions if p_ck_noise==0: pi_pc, pi_dec", "no need to download anything # http://pytorch.org/ from itertools import", "ck_state = 0 else: ck_state = int(observations[0] + 1) if", "pi_pcs[0][0] p_d_ck1 = pi_pcs[1][0] p_d_ck2 = pi_pcs[2][0] def make_joint(p1, p2,", "delegation to the independent agents. # theta_joint = init.normal_(torch.zeros(n_states_joint, n_actions", "p_ck_noise, p_common, nt)) results_log = np.zeros((t_max // (t_max // 100),))", "Well be appending results to these lists run_results = []", "p_d_ck2 * torch.ger(p_marg_ag0_ck1, pi_dec[1]) return p_joint elif ck_state == 2:", "F from torch.multiprocessing import Pool, set_start_method, freeze_support try: set_start_method('spawn') except", "optim == 'sgd': optimizer = SGD(params, lr=lr) else: optimizer =", "return ret_val def _proc(args): p_common, p_observation, run, p_ck_noise, t_max, n_trials", "CK & Matrix ID = 1), n_actions^2 actions for #", "| pi) R(\\tau) def expected_return(p_common, p_observation, thetas, run, test, p_ck_noise=0):", "if use_mp: pool = Pool(processes=2) # Well be appending results", "(always uses decentralised actions selection) labels = [\"IAC\", \"JAL\"] p_vec", "std=std_val) params = chain(*[_v if isinstance(_v, (list, tuple)) else [_v]", "run == 'JAL': pol_vals[0] = -10 ** 10 elif run", "p_ck_noise) results_log_test[i // (t_max // 100)] = r_test results_log[i //", "Produce marginalised policy: pi_pc[0] * pi^a * pi^b + p(u^ab)", "to these lists run_results = [] for run in labels:", "p_common, nt)) results_log = np.zeros((t_max // (t_max // 100),)) results_log_test", "0, 2, 0, 0], [1, 2, 4, 2, 1], [0,", "if run == 'JAL': pol_vals[i][0] = -10 ** 10 elif", "= expected_return(p_common, p_observation, thetas, run, True, p_ck_noise) results_log_test[i // (t_max", "0, CK & Matrix ID = 1), n_actions^2 actions for", "= [1.0, 0.0] # DEBUG! # Initialise expected return ret_val", "= [] for j, p in enumerate( p_vec ): vals", "loss.backward() optimizer.step() if i % (t_max // 100) == 0:", "p_common in enumerate(p_vec): all_res = [] all_res_test = [] for", "list(params) if use_cuda: for param in params: param = param.to(\"cuda\")", "both unnoised p_both = (p_ck_noise) ** 2 # both noised", "Actor-Critic (always uses decentralised actions selection) labels = [\"IAC\", \"JAL\"]", "elif ck_state == 1: p_joint = p_none * p_joint_ck1 +", "0], [1, 2, 4, 2, 1], [0, 0, 2, 0,", "// (t_max // 100)] = r_test results_log[i // (t_max //", "get masked out for independent learner and joint-action-learner # independent", "Reinforcement Learning (MACKRL) # The entire notebook can be executed", "p_d_ck2 * torch.ger(p_marg_ag0_ck1, pi_dec[1]) \\ + p_one * p_d_ck1 *", "plt.yticks([0.5, 0.75, 1]) plt.savefig(\"MACKRL {}.pdf\".format(titles[pl])) plt.show(block=False) if __name__ == \"__main__\":", "= np.std(vals[i], 1)[-1]/0.5 low = this_mean-std / (n_trials)**0.5 high =", "0], [0, 0, 1, 0, 0], ], dtype=torch.float32) * 0.2)", "selection) labels = [\"IAC\", \"JAL\"] p_vec = [0.0, 0.2, 0.4,", "for delegation to the independent agents. # theta_joint = init.normal_(torch.zeros(n_states_joint,", "1.01]) ax.set_facecolor((1.0, 1.0, 1.0)) ax.grid(color='k', linestyle='-', linewidth=1) ax.set_title(titles[pl]) plt.legend() plt.xticks([0,", "-10 ** 10 elif run == 'IAC': pol_vals[1:] = -10", "Matrices are chosen 50 / 50 p_matrix = [0.5, 0.5]", "'m', 'y', 'k'] titles = ['Test', 'Train Performance'] for pl", "plt.ylabel('Expected Return') plt.ylim([0.0, 1.01]) plt.xlim([-0.01, 1.01]) ax.set_facecolor((1.0, 1.0, 1.0)) ax.grid(color='k',", "p_d_ck2 + p_both * p_d_ck1 + p_none * p_d_ck2) *", "between the probability distributions low1 = torch.sum(p1[:i]) high1 = low1", "- expected_return(p_common, p_observation, thetas, run, False, p_ck_noise) r_s = -loss.data.numpy()", "1), n_actions^2 actions for # # joint action + 1", "in [0, 1]: for obs_1 in [0, 1]: p_state =", "r_test results_log[i // (t_max // 100)] = r_s results.append((results_log_test, results_log))", "freeze_support try: set_start_method('spawn') except RuntimeError: pass from torch.nn import init", "gradient steps t_max = 202 # We'll be using a", "= -10 ** 10 # apply temperature to set testing", "pol_vals[1:] = -10 ** 10 # apply temperature to set", "= thetas[\"dec\"] theta_joint = thetas[\"joint\"] # Probability of CK p_common_val", "pol_vals, pi_dec, ck_state = get_policies(common_knowledge, observations, run, test, thetas_dec, theta_joint,", "if isinstance(_v, (list, tuple)) else [_v] for _v in thetas.values()])", "all_res]) import pickle import uuid import os res_dict = {}", "expected_return(p_common, p_observation, thetas, run, False, p_ck_noise) r_s = -loss.data.numpy() optimizer.zero_grad()", "through contiguous, ordered bucketing for both p1, p2 \"\"\" p1", "* torch.ger(pi_dec[0], p_marg_ag1_ck2) \\ + p_one * (1 - p_d_ck2)", "* (1 - p_d_ck2) * p_d_ck1 * torch.ger(p_marg_ag0_ck2, pi_dec[1]) return", "p_obs_val[obs_1] * p_matrix[matrix_id] common_knowledge, observations, matrix_id = get_state(ck, obs_0, obs_1,", "+ pck], 1)[-1] std = np.std(vals[i], 1)[-1]/0.5 low = this_mean-std", "50 p_matrix = [0.5, 0.5] # p_matrix = [1.0, 0.0]", "0], ], dtype=torch.float32) * 0.2) n_agents = 2 n_actions =", "can reduce this number if you are short on time.", "pi_dec[1]) return p_joint elif ck_state == 2: p_joint = p_none", "values [5, 0, 0, 2, 0], [0, 1, 2, 4,", "* p_joint_ck1 + \\ p_one * make_joint(p_joint_ck2, p_joint_ck1) + \\", "= this_mean + std / (n_trials)**0.5 mean_vals.append( this_mean ) min_vals.append(", "[] for i in range(n_states_joint): if run == 'JAL': pol_vals[i][0]", "elif run == 'IAC': pol_vals[i][1:] = -10 ** 10 #", "obs_0, obs_1, matrix_id): receives_obs = [obs_0, obs_1] if common_knowledge ==", "'JAL': pol_vals[0] = -10 ** 10 elif run == 'IAC':", "0, 1, 0, 0], ], dtype=torch.float32) * 0.2) n_agents =", "= torch.sum(p1[:i]) high1 = low1 + p1[i] low2 = torch.sum(p2[:i])", "0: ck_state = 0 else: ck_state = int(observations[0] + 1)", "import torch.nn.functional as F from torch.multiprocessing import Pool, set_start_method, freeze_support", "* pi_a_pi_b + p_joint return p_joint def p_joint_all_noise_alt(pi_pcs, pi_dec, p_ck_noise,", "return p_joint elif ck_state == 2: p_joint = p_none *", "Independent Actor-Critic (always uses decentralised actions selection) labels = [\"IAC\",", "range(n_agents): dec_state = int(observations[i]) pi = F.softmax(thetas_dec[i][dec_state] * beta, -1)", "product of rewards and action probabilities expected_ret = (p_joint_val *", "low2 + p2[i] if low1 >= low2 and high2 >", "low1 + p1[i] low2 = torch.sum(p2[:i]) high2 = low2 +", "run, test, thetas_dec, theta_joint) p_joint_val = p_joint_all(pi_pc, pi_dec) else: pol_vals,", "enumerate(p_ck_noise): mean_vals = [] min_vals = [] max_vals = []", "= 1), n_actions^2 actions for # # joint action +", "= F.softmax(pol_vals * beta, -1) # calcuate decentralised policies for", "[0, 1]: for obs_0 in [0, 1]: for obs_1 in", "(n_trials)**0.5 mean_vals.append( this_mean ) min_vals.append( low ) max_vals.append( high )", "= pi_pcs[0][0] p_d_ck1 = pi_pcs[1][0] p_d_ck2 = pi_pcs[2][0] def make_joint(p1,", "p_both * p_d_ck1 + p_none * p_d_ck2) * torch.ger(pi_dec[0], pi_dec[1])", "pi_pcs[1][1:].view(n_actions, n_actions).clone().sum(dim=1) p_marg_ag1_ck2 = pi_pcs[2][1:].view(n_actions, n_actions).clone().sum(dim=1) p_joint_ck0 = pi_pcs[0][1:].view(n_actions, n_actions).clone()", "= pi_pcs[2][1:].view(n_actions, n_actions).clone().sum(dim=1) p_joint_ck0 = pi_pcs[0][1:].view(n_actions, n_actions).clone() p_joint_ck1 = pi_pcs[1][1:].view(n_actions,", "\"\"\" 1. Pick uniform random variable between [0,1] 2. Do", "= get_policies(common_knowledge, observations, run, test, thetas_dec, theta_joint, p_ck_noise) p_joint_val =", "= [\"IAC\", \"JAL\"] p_vec = [0.0, 0.2, 0.4, 0.6, 0.8,", "thetas, run, False, p_ck_noise) r_s = -loss.data.numpy() optimizer.zero_grad() loss.backward() optimizer.step()", "# joint action + 1 action for delegation to the", "in range(n_agents): dec_state = int(observations[i]) pi = F.softmax(thetas_dec[i][dec_state] * beta,", "p_common, p_observation, run, p_ck_noise, t_max, n_trials = args results =", "probabilities for joint actions if p_ck_noise==0: pi_pc, pi_dec = get_policies(common_knowledge,", "p_none * p_joint_ck1 + \\ p_both * p_joint_ck2 + \\", "run: MACRKL, Joint-action-learner (always uses CK), # Independent Actor-Critic (always", "except RuntimeError: pass from torch.nn import init from torch.optim import", "p_one = (1-p_ck_noise) * p_ck_noise # exactly one noised p_marg_ag0_ck1", "MACRKL, Joint-action-learner (always uses CK), # Independent Actor-Critic (always uses", "-10 ** 10 elif run == 'IAC': pol_vals[i][1:] = -10", "* pi^b + p(u^ab) def p_joint_all(pi_pc, pi_dec): p_joint = pi_pc[1:].view(n_actions,", "matrix_id): receives_obs = [obs_0, obs_1] if common_knowledge == 1: observations", "itertools import chain import torch import torch.nn.functional as F from", "pool = Pool(processes=2) # Well be appending results to these", "2) else: observations = np.ones((n_agents)) * 2 # for ag", "t_max, n_trials)) for pc in p_vec ] noise_results.append(results) run_results.append(noise_results) for", "in range(n_trials): print(\"Run: {} P_CK_NOISE: {} P_common: {} #Trial: {}\".format(run,", "need to download anything # http://pytorch.org/ from itertools import chain", "RuntimeError: pass from torch.nn import init from torch.optim import Adam,", "== 'JAL': pol_vals[i][0] = -10 ** 10 elif run ==", "run_results[run_id][pnoise_id][p_common_id] except Exception as e: pass all_res_test.append(np.stack([r[0] for r in", "run_results = [] for run in labels: noise_results = []", "(1-p_ck_noise) * p_ck_noise # exactly one noised p_marg_ag0_ck1 = pi_pcs[1][1:].view(n_actions,", "mode=\"interval\"): \"\"\" 1. Pick uniform random variable between [0,1] 2.", "= r_s results.append((results_log_test, results_log)) return results def main(): use_mp =", "from torch.multiprocessing import Pool, set_start_method, freeze_support try: set_start_method('spawn') except RuntimeError:", "matrix_id + 1 return common_knowledge, observations, matrix_id # Calculate the", "#100 std_val = 1.0 # These are the 3 settings", "p_observation, thetas, run, test, p_ck_noise=0): thetas_dec = thetas[\"dec\"] theta_joint =", "requires_grad=True), std=0.1) # Produce marginalised policy: pi_pc[0] * pi^a *", "p1, p2 \"\"\" p1 = p1.clone().view(-1) p2 = p2.clone().view(-1) p_final", "logits get masked out for independent learner and joint-action-learner #", "and high2 > low1: p_final[i] = torch.min(high1, high2) - low1", "pickle.dump(res_dict, open(os.path.join(os.path.dirname(os.path.abspath(__file__)), \"pickles\", \"final_res_{}.p\".format(uuid.uuid4().hex[:4])), \"wb\")) plt.figure(figsize=(5, 5)) color = ['b',", "p_d_ck0 * torch.ger(pi_dec[0], pi_dec[1]) return p_joint # always delegate elif", "p_d_ck2) * torch.ger(pi_dec[0], pi_dec[1]) \\ + p_one * p_d_ck2 *", "p_one * make_joint(p_joint_ck1, p_joint_ck2) + \\ (p_one * p_d_ck2 *", "0.2, 0.4, 0.6, 0.8, 1.0] final_res = [] # #", "1: observations = np.repeat(matrix_id, 2) else: observations = np.ones((n_agents)) *", "mode == \"interval\": for i in range(p1.shape[0]): # calculate overlap", "= [] for run in labels: noise_results = [] for", ") plt.plot(p_vec, mean_vals, color[(i*len(p_ck_noise) + pck) % len(color)], label =", "- p_d_ck2) * p_d_ck1 * torch.ger(p_marg_ag0_ck2, pi_dec[1]) \\ + p_one", "results.append((results_log_test, results_log)) return results def main(): use_mp = True if", "1, 1) for i in range(len(labels)): for pck, pcknoise in", "[0, 0, 0, 2, 0], [0, 0, 0, 1, 0],", "in enumerate(p_ck_noise): mean_vals = [] min_vals = [] max_vals =", "0, 0], [1, 2, 4, 2, 1], [0, 0, 2,", "p_d_ck1) * p_d_ck2 * torch.ger(p_marg_ag0_ck1, pi_dec[1]) return p_joint elif ck_state", "max_vals = [] for j, p in enumerate( p_vec ):", "plt.fill_between(p_vec, min_vals, max_vals, facecolor=color[i], alpha=0.3) plt.xlabel('P(common knowledge)') plt.ylabel('Expected Return') plt.ylim([0.0,", "p_d_ck1 + p_none * p_d_ck2) * torch.ger(pi_dec[0], pi_dec[1]) \\ +", "[] # common_knowledge decides whether ck_state is informative if common_knowledge", "* pi^a * pi^b + p(u^ab) def p_joint_all(pi_pc, pi_dec): p_joint", "else: pol_vals = theta_joint.clone() pi_pcs = [] for i in", "from torch.nn import init from torch.optim import Adam, SGD import", "thetas_dec, theta_joint) p_joint_val = p_joint_all(pi_pc, pi_dec) else: pol_vals, pi_dec, ck_state", "= 0.5 p_ck_noise = [0.0] # Number of gradient steps", "[1.0, 0.0] # DEBUG! # Initialise expected return ret_val =", "10 # apply temperature to set testing pi_pcs.append(F.softmax(pol_vals[i] * beta,", "range(n_states_joint): if run == 'JAL': pol_vals[i][0] = -10 ** 10", "has a pair controller that always delegates if run ==", "expected_return(p_common, p_observation, thetas, run, test, p_ck_noise=0): thetas_dec = thetas[\"dec\"] theta_joint", "get_policies(common_knowledge, observations, run, test, thetas_dec, theta_joint, p_ck_noise) p_joint_val = p_joint_all_noise_alt(pol_vals,", "F.softmax(pol_vals * beta, -1) # calcuate decentralised policies for i", "n_trials = args results = [] for nt in range(n_trials):", "+ p(u^ab) def p_joint_all(pi_pc, pi_dec): p_joint = pi_pc[1:].view(n_actions, n_actions).clone() pi_a_pi_b", "this number if you are short on time. (Eg. n_trials", "#15 #100 std_val = 1.0 # These are the 3", "with 3 input state (no CK, CK & Matrix ID", "Adam(params, lr=lr) for i in range(t_max): if run in ['MACKRL',", "in results], axis=1)) final_res.append([all_res_test, all_res]) import pickle import uuid import", "= np.ones((n_agents)) * 2 # for ag in range(n_agents): if", "else: pol_vals, pi_dec, ck_state = get_policies(common_knowledge, observations, run, test, thetas_dec,", "p_marg_ag0_ck1 = pi_pcs[1][1:].view(n_actions, n_actions).clone().sum(dim=0) p_marg_ag0_ck2 = pi_pcs[2][1:].view(n_actions, n_actions).clone().sum(dim=0) p_marg_ag1_ck1 =", "make_joint(p_joint_ck2, p_joint_ck1) + \\ (p_one * p_d_ck1 * p_d_ck2 +", "* make_joint(p_joint_ck1, p_joint_ck2) + \\ (p_one * p_d_ck2 * p_d_ck1", "DEBUG! # Initialise expected return ret_val = 0 for ck", "'c', 'm', 'y', 'k','b', 'r','g', 'c', 'm', 'y', 'k'] titles", "from torch.optim import Adam, SGD import numpy as np import", "in labels: noise_results = [] for pnoise in p_ck_noise: print(\"Run:", "of CK p_common_val = [1 - p_common, p_common] # Probability", "payoff_values[matrix_id]).sum() # Add return from given state ret_val = ret_val", "// (t_max // 100)] = r_s results.append((results_log_test, results_log)) return results", "np.zeros((t_max // (t_max // 100),)) results_log_test = np.zeros((t_max // (t_max", "res_dict[\"p_vec\"] = p_vec if not os.path.exists(os.path.join(os.path.dirname(os.path.abspath(__file__)), \"pickles\")): os.makedirs(os.path.join(os.path.dirname(os.path.abspath(__file__)), \"pickles\")) pickle.dump(res_dict,", "p_d_ck1) * torch.ger(pi_dec[0], pi_dec[1]) \\ + p_one * p_d_ck1 *", "2, 0], [0, 1, 2, 4, 2], [0, 0, 0,", "torch.ger(p_marg_ag0_ck2, pi_dec[1]) return p_joint pass def get_policies(common_knowledge, observations, run, test,", "p_d_ck0 = pi_pcs[0][0] p_d_ck1 = pi_pcs[1][0] p_d_ck2 = pi_pcs[2][0] def", "(MACKRL) # The entire notebook can be executed online, no", "[obs_0, obs_1] if common_knowledge == 1: observations = np.repeat(matrix_id, 2)", "= thetas[\"joint\"] # Probability of CK p_common_val = [1 -", "p2 \"\"\" p1 = p1.clone().view(-1) p2 = p2.clone().view(-1) p_final =", "settings we run: MACRKL, Joint-action-learner (always uses CK), # Independent", "* p_obs_val[obs_0] * p_obs_val[obs_1] * p_matrix[matrix_id] common_knowledge, observations, matrix_id =", "for p_common_id, p_common in enumerate(p_vec): all_res = [] all_res_test =", "and action probabilities expected_ret = (p_joint_val * payoff_values[matrix_id]).sum() # Add", "p_one * p_d_ck2 * (1 - p_d_ck1) * torch.ger(pi_dec[0], p_marg_ag1_ck1)", "def main(): use_mp = True if use_mp: pool = Pool(processes=2)", "all_res_test = [] for run_id, run in enumerate(labels): for pnoise_id,", "in range(p1.shape[0]): # calculate overlap between the probability distributions low1", "2, 4, 2, 1], [0, 0, 2, 0, 0], [0,", "init.normal_(torch.zeros(n_states_joint, n_actions ** 2 + 1, requires_grad=True), std=std_val) params =", "joint action + 1 action for delegation to the independent", "p2.clone().view(-1) p_final = p1.clone().zero_() if mode == \"interval\": for i", "Return') plt.ylim([0.0, 1.01]) plt.xlim([-0.01, 1.01]) ax.set_facecolor((1.0, 1.0, 1.0)) ax.grid(color='k', linestyle='-',", "p_d_ck2) * p_d_ck1 * torch.ger(p_marg_ag0_ck2, pi_dec[1]) \\ + p_one *", "p_observation, run, pnoise, t_max, n_trials) for pc in p_vec ])", "pnoise)) results = pool.map(_proc, [ (pc, p_observation, run, pnoise, t_max,", "Common Knowledge Reinforcement Learning (MACKRL) # The entire notebook can", "high2) - low2 else: p_final[i] = 0 return p_final.clone().view(n_actions, n_actions)", "p_joint def p_joint_all_noise_alt(pi_pcs, pi_dec, p_ck_noise, ck_state): p_none = (1-p_ck_noise) **", "pi_dec[1]) return p_joint pass def get_policies(common_knowledge, observations, run, test, thetas_dec,", "if run == 'JAL': pol_vals[0] = -10 ** 10 elif", "+ p2[i] if low1 >= low2 and high2 > low1:", "p_joint_all(pi_pc, pi_dec): p_joint = pi_pc[1:].view(n_actions, n_actions).clone() pi_a_pi_b = torch.ger(pi_dec[0], pi_dec[1])", "thetas, run, test, p_ck_noise=0): thetas_dec = thetas[\"dec\"] theta_joint = thetas[\"joint\"]", "pair controller that always delegates if run == 'JAL': pol_vals[0]", "p_observation, p_observation] # Matrices are chosen 50 / 50 p_matrix", "# p_matrix = [1.0, 0.0] # DEBUG! # Initialise expected", "** 10 elif run == 'IAC': pol_vals[1:] = -10 **", "* p_d_ck1) * torch.ger(pi_dec[0], pi_dec[1]) \\ + p_one * p_d_ck1", "p_marg_ag1_ck2 = pi_pcs[2][1:].view(n_actions, n_actions).clone().sum(dim=1) p_joint_ck0 = pi_pcs[0][1:].view(n_actions, n_actions).clone() p_joint_ck1 =", "* p_d_ck2 * torch.ger(p_marg_ag0_ck1, pi_dec[1]) \\ + p_one * p_d_ck1", "[0,1]: ax = plt.subplot(1, 1, 1) for i in range(len(labels)):", "(p_ck_noise) ** 2 # both noised p_one = (1-p_ck_noise) *", "= 3 n_mix_hidden = 3 p_observation = 0.5 p_ck_noise =", "# This notebook implements a proof-of-principle for # Multi-Agent Common", "thetas[\"joint\"] = init.normal_(torch.zeros(n_states_joint, n_actions ** 2 + 1, requires_grad=True), std=std_val)", "enumerate(p_vec): all_res = [] all_res_test = [] for run_id, run", "* (1 - p_d_ck1) * p_d_ck2 * torch.ger(p_marg_ag0_ck1, pi_dec[1]) \\", "\"final_res_{}.p\".format(uuid.uuid4().hex[:4])), \"wb\")) plt.figure(figsize=(5, 5)) color = ['b', 'r','g', 'c', 'm',", "ck_state): p_none = (1-p_ck_noise) ** 2 # both unnoised p_both", "== 'sgd': optimizer = SGD(params, lr=lr) else: optimizer = Adam(params,", "download anything # http://pytorch.org/ from itertools import chain import torch", "* p_d_ck1 * p_d_ck2 + p_one * p_d_ck2 * p_d_ck1", "pool.map(_proc, [ (pc, p_observation, run, pnoise, t_max, n_trials) for pc", "testing pi_pcs.append(F.softmax(pol_vals[i] * beta, -1)) # calcuate decentralised policies for", "params: param = param.to(\"cuda\") if optim == 'sgd': optimizer =", "== 0: if run in ['MACKRL', 'JAL', 'IAC']: r_test =", "joint-action-learner # independent learner has a pair controller that always", "(t_max // 100) == 0: if run in ['MACKRL', 'JAL',", "(t_max // 100)] = r_test results_log[i // (t_max // 100)]", "return results def main(): use_mp = True if use_mp: pool", "= 5 n_states_joint = 3 n_mix_hidden = 3 p_observation =", "\\ + p_one * p_d_ck1 * (1 - p_d_ck2) *", "run == 'IAC': pol_vals[1:] = -10 ** 10 # apply", "n_trials = 20) #n_trials = 100 # 30 n_trials =", "\\ p_one * make_joint(p_joint_ck2, p_joint_ck1) + \\ p_one * make_joint(p_joint_ck1,", "pi = F.softmax(thetas_dec[i][dec_state] * beta, -1) pi_dec.append(pi) return pi_pc, pi_dec", "use_cuda: for param in params: param = param.to(\"cuda\") if optim", "anything # http://pytorch.org/ from itertools import chain import torch import", "p_final[i] = 0 return p_final.clone().view(n_actions, n_actions) if ck_state == 0:", "p_common_val[ck] * p_obs_val[obs_0] * p_obs_val[obs_1] * p_matrix[matrix_id] common_knowledge, observations, matrix_id", "n_trials)) for pc in p_vec ] noise_results.append(results) run_results.append(noise_results) for p_common_id,", "pi_pcs[2][1:].view(n_actions, n_actions).clone() p_d_ck0 = pi_pcs[0][0] p_d_ck1 = pi_pcs[1][0] p_d_ck2 =", "np.ones((n_agents)) * 2 # for ag in range(n_agents): if receives_obs[ag]:", "# payoff values [0, 0, 1, 0, 5], [0, 0,", "p_ck_noise, ck_state): p_none = (1-p_ck_noise) ** 2 # both unnoised", "+ \\ p_both * p_joint_ck1 + \\ p_one * make_joint(p_joint_ck2,", "[0, 0, 1, 0, 0], ], dtype=torch.float32) * 0.2) n_agents", "this_mean-std / (n_trials)**0.5 high = this_mean + std / (n_trials)**0.5", "just the elementwise product of rewards and action probabilities expected_ret", "torch.ger(pi_dec[0], pi_dec[1]) p_joint = pi_pc[0] * pi_a_pi_b + p_joint return", "pnoise_id, pnoise in enumerate(p_ck_noise): try: results = run_results[run_id][pnoise_id][p_common_id] except Exception", "= F.softmax(thetas_dec[i][dec_state] * beta, -1) pi_dec.append(pi) return pi_pcs, pi_dec, ck_state", "for i in range(n_states_joint): if run == 'JAL': pol_vals[i][0] =", "* torch.ger(p_marg_ag0_ck2, pi_dec[1]) return p_joint pass def get_policies(common_knowledge, observations, run,", "CK p_common_val = [1 - p_common, p_common] # Probability of", "= torch.min(high1, high2) - low2 else: p_final[i] = 0 return", "use_mp = True if use_mp: pool = Pool(processes=2) # Well", "= p1.clone().zero_() if mode == \"interval\": for i in range(p1.shape[0]):", "p2 = p2.clone().view(-1) p_final = p1.clone().zero_() if mode == \"interval\":", "p_ck_noise, t_max, n_trials = args results = [] for nt", "ret_val = ret_val + p_state * expected_ret return ret_val def", "{} P_CK_NOISE: {}\".format(run, pnoise)) results = [_proc((pc, p_observation, run, pnoise,", "p_joint_ck2 = pi_pcs[2][1:].view(n_actions, n_actions).clone() p_d_ck0 = pi_pcs[0][0] p_d_ck1 = pi_pcs[1][0]", "params = chain(*[_v if isinstance(_v, (list, tuple)) else [_v] for", "/ 50 p_matrix = [0.5, 0.5] # p_matrix = [1.0,", "* (1 - p_d_ck2) * p_d_ck1 * torch.ger(p_marg_ag0_ck2, pi_dec[1]) \\", "make_joint(p_joint_ck1, p_joint_ck2) + \\ p_one * make_joint(p_joint_ck2, p_joint_ck1) + \\", "+ \\ (p_one * p_d_ck2 * p_d_ck1 + p_one *", "= p_joint_ck0 + p_d_ck0 * torch.ger(pi_dec[0], pi_dec[1]) return p_joint #", "mean_vals = [] min_vals = [] max_vals = [] for", "Pool, set_start_method, freeze_support try: set_start_method('spawn') except RuntimeError: pass from torch.nn", "torch.min(high1, high2) - low2 else: p_final[i] = 0 return p_final.clone().view(n_actions,", "= theta_joint[ck_state, :].clone() # logits get masked out for independent", "'IAC': pol_vals[i][1:] = -10 ** 10 # apply temperature to", "pass from torch.nn import init from torch.optim import Adam, SGD", "+ p_one * (1 - p_d_ck1) * p_d_ck2 * torch.ger(p_marg_ag0_ck1,", "[0, 1, 2, 4, 2], [0, 0, 0, 2, 0],", "p_vec = [0.0, 0.2, 0.4, 0.6, 0.8, 1.0] final_res =", "* make_joint(p_joint_ck1, p_joint_ck2) + \\ p_one * make_joint(p_joint_ck2, p_joint_ck1) +", "+ 1) if p_ck_noise == 0: pol_vals = theta_joint[ck_state, :].clone()", "= [0.0, 0.2, 0.4, 0.6, 0.8, 1.0] final_res = []", "ret_val + p_state * expected_ret return ret_val def _proc(args): p_common,", "p_observation, run, pnoise, t_max, n_trials)) for pc in p_vec ]", "lr = 0.05 # DEBUG: 0.05 if exact gradients! optim", "all_res = [] all_res_test = [] for run_id, run in", "pi^b + p(u^ab) def p_joint_all(pi_pc, pi_dec): p_joint = pi_pc[1:].view(n_actions, n_actions).clone()", "p_joint return p_joint def p_joint_all_noise_alt(pi_pcs, pi_dec, p_ck_noise, ck_state): p_none =", "unnoised p_both = (p_ck_noise) ** 2 # both noised p_one", "= chain(*[_v if isinstance(_v, (list, tuple)) else [_v] for _v", "action + 1 action for delegation to the independent agents.", "* beta, -1)) # calcuate decentralised policies for i in", "learner and joint-action-learner # independent learner has a pair controller", "p_joint = p_joint_ck0 + p_d_ck0 * torch.ger(pi_dec[0], pi_dec[1]) return p_joint", "try: set_start_method('spawn') except RuntimeError: pass from torch.nn import init from", "p_joint # always delegate elif ck_state == 1: p_joint =", "[5, 0, 0, 2, 0], [0, 1, 2, 4, 2],", "= get_state(ck, obs_0, obs_1, matrix_id) # Get final probabilities for", "1 action for delegation to the independent agents. # theta_joint", "= -loss.data.numpy() optimizer.zero_grad() loss.backward() optimizer.step() if i % (t_max //", "pnoise in enumerate(p_ck_noise): try: results = run_results[run_id][pnoise_id][p_common_id] except Exception as", "{} #Trial: {}\".format(run, p_ck_noise, p_common, nt)) results_log = np.zeros((t_max //", "that always delegates if run == 'JAL': pol_vals[0] = -10", "low1 = torch.sum(p1[:i]) high1 = low1 + p1[i] low2 =", "20 #15 #100 std_val = 1.0 # These are the", "if p_ck_noise==0: pi_pc, pi_dec = get_policies(common_knowledge, observations, run, test, thetas_dec,", "for pnoise in p_ck_noise: print(\"Run: {} P_CK_NOISE: {}\".format(run, pnoise)) results", "** 2 + 1, requires_grad=True), std=0.1) # Produce marginalised policy:", "t_max = 202 # We'll be using a high learning", "p_joint_val = p_joint_all(pi_pc, pi_dec) else: pol_vals, pi_dec, ck_state = get_policies(common_knowledge,", "lists run_results = [] for run in labels: noise_results =", "matplotlib.pyplot as plt use_cuda = False payoff_values = [] payoff_values.append(torch.tensor([", "pck], 1)[-1] std = np.std(vals[i], 1)[-1]/0.5 low = this_mean-std /", "low1 and high1 > low2: p_final[i] = torch.min(high1, high2) -", "Add return from given state ret_val = ret_val + p_state", "if receives_obs[ag]: observations[ag] += matrix_id + 1 return common_knowledge, observations,", "= p_none * p_joint_ck2 + \\ p_both * p_joint_ck1 +", "results def main(): use_mp = True if use_mp: pool =", "learner has a pair controller that always delegates if run", "pi_pcs[1][0] p_d_ck2 = pi_pcs[2][0] def make_joint(p1, p2, mode=\"interval\"): \"\"\" 1.", "Initialise expected return ret_val = 0 for ck in [0,", "// 100),)) thetas = {} thetas[\"dec\"] = [init.normal_(torch.zeros(n_states_dec, n_actions, requires_grad=True),", "0.5, 1]) plt.yticks([0.5, 0.75, 1]) plt.savefig(\"MACKRL {}.pdf\".format(titles[pl])) plt.show(block=False) if __name__", "'IAC']: loss = - expected_return(p_common, p_observation, thetas, run, False, p_ck_noise)", "numpy as np import matplotlib.pyplot as plt use_cuda = False", "for matrix_id in [0, 1]: for obs_0 in [0, 1]:", "p_one * make_joint(p_joint_ck2, p_joint_ck1) + \\ p_one * make_joint(p_joint_ck1, p_joint_ck2)", "observations, run, test, thetas_dec, theta_joint, p_ck_noise=0): if test: beta =", "i in range(p1.shape[0]): # calculate overlap between the probability distributions", "// 100)] = r_test results_log[i // (t_max // 100)] =", "1], [0, 0, 2, 0, 0], [0, 0, 1, 0,", "os.path.exists(os.path.join(os.path.dirname(os.path.abspath(__file__)), \"pickles\")): os.makedirs(os.path.join(os.path.dirname(os.path.abspath(__file__)), \"pickles\")) pickle.dump(res_dict, open(os.path.join(os.path.dirname(os.path.abspath(__file__)), \"pickles\", \"final_res_{}.p\".format(uuid.uuid4().hex[:4])), \"wb\")) plt.figure(figsize=(5,", "vals = final_res[j][pl] this_mean = np.mean( vals[i*len(p_ck_noise) + pck], 1)[-1]", "P_CK_NOISE: {}\".format(run, pnoise)) results = [_proc((pc, p_observation, run, pnoise, t_max,", "if low1 >= low2 and high2 > low1: p_final[i] =", "both p1, p2 \"\"\" p1 = p1.clone().view(-1) p2 = p2.clone().view(-1)", "5], [0, 0, 2, 0, 0], [1, 2, 4, 2,", "expected_ret = (p_joint_val * payoff_values[matrix_id]).sum() # Add return from given", "Pool(processes=2) # Well be appending results to these lists run_results", "0.6, 0.8, 1.0] final_res = [] # # Pair-Controller with", "actions selection) labels = [\"IAC\", \"JAL\"] p_vec = [0.0, 0.2,", "4, 2], [0, 0, 0, 2, 0], [0, 0, 0,", "= [] for nt in range(n_trials): print(\"Run: {} P_CK_NOISE: {}", "== 0: ck_state = 0 else: ck_state = int(observations[0] +", "ax = plt.subplot(1, 1, 1) for i in range(len(labels)): for", "= [_proc((pc, p_observation, run, pnoise, t_max, n_trials)) for pc in", "CK, CK & Matrix ID = 0, CK & Matrix", "nt)) results_log = np.zeros((t_max // (t_max // 100),)) results_log_test =", "n_agents = 2 n_actions = len(payoff_values[0]) n_states_dec = 5 n_states_joint", "= 202 # We'll be using a high learning rate,", "[0, 0, 2, 0, 0], [0, 0, 1, 0, 0],", "= param.to(\"cuda\") if optim == 'sgd': optimizer = SGD(params, lr=lr)", "results = [_proc((pc, p_observation, run, pnoise, t_max, n_trials)) for pc", "payoff_values.append(torch.tensor([ # payoff values [5, 0, 0, 2, 0], [0,", "['MACKRL', 'JAL', 'IAC']: loss = - expected_return(p_common, p_observation, thetas, run,", "= pi_pcs[1][1:].view(n_actions, n_actions).clone() p_joint_ck2 = pi_pcs[2][1:].view(n_actions, n_actions).clone() p_d_ck0 = pi_pcs[0][0]", "facecolor=color[i], alpha=0.3) plt.xlabel('P(common knowledge)') plt.ylabel('Expected Return') plt.ylim([0.0, 1.01]) plt.xlim([-0.01, 1.01])", "p_d_ck2 * (1 - p_d_ck1) * torch.ger(pi_dec[0], p_marg_ag1_ck1) \\ +", "[] min_vals = [] max_vals = [] for j, p", "# common_knowledge decides whether ck_state is informative if common_knowledge ==", "a proof-of-principle for # Multi-Agent Common Knowledge Reinforcement Learning (MACKRL)", "= pi_pcs[2][0] def make_joint(p1, p2, mode=\"interval\"): \"\"\" 1. Pick uniform", "pck, pcknoise in enumerate(p_ck_noise): mean_vals = [] min_vals = []", "plt.plot(p_vec, mean_vals, color[(i*len(p_ck_noise) + pck) % len(color)], label = \"{}", "not os.path.exists(os.path.join(os.path.dirname(os.path.abspath(__file__)), \"pickles\")): os.makedirs(os.path.join(os.path.dirname(os.path.abspath(__file__)), \"pickles\")) pickle.dump(res_dict, open(os.path.join(os.path.dirname(os.path.abspath(__file__)), \"pickles\", \"final_res_{}.p\".format(uuid.uuid4().hex[:4])), \"wb\"))", "1) for i in range(len(labels)): for pck, pcknoise in enumerate(p_ck_noise):", "* make_joint(p_joint_ck2, p_joint_ck1) + \\ p_one * make_joint(p_joint_ck1, p_joint_ck2) +", "uses CK), # Independent Actor-Critic (always uses decentralised actions selection)", "= ret_val + p_state * expected_ret return ret_val def _proc(args):", "receives_obs = [obs_0, obs_1] if common_knowledge == 1: observations =", "pi_pcs[0][1:].view(n_actions, n_actions).clone() p_joint_ck1 = pi_pcs[1][1:].view(n_actions, n_actions).clone() p_joint_ck2 = pi_pcs[2][1:].view(n_actions, n_actions).clone()", "observation given no CK) p_obs_val = [1 - p_observation, p_observation]", "theta_joint[ck_state, :].clone() # logits get masked out for independent learner", "Adam, SGD import numpy as np import matplotlib.pyplot as plt", "policy: pi_pc[0] * pi^a * pi^b + p(u^ab) def p_joint_all(pi_pc,", "50 / 50 p_matrix = [0.5, 0.5] # p_matrix =", "P_CK_NOISE: {}\".format(run, pnoise)) results = pool.map(_proc, [ (pc, p_observation, run,", "axis=1)) final_res.append([all_res_test, all_res]) import pickle import uuid import os res_dict", "label = \"{} p_ck_noise: {}\".format(labels[i], pcknoise)) plt.fill_between(p_vec, min_vals, max_vals, facecolor=color[i],", "0: pol_vals = theta_joint[ck_state, :].clone() # logits get masked out", "common_knowledge, observations, matrix_id # Calculate the expected return: sum_{\\tau} P(\\tau", "low = this_mean-std / (n_trials)**0.5 high = this_mean + std", "0.2) n_agents = 2 n_actions = len(payoff_values[0]) n_states_dec = 5", "= get_policies(common_knowledge, observations, run, test, thetas_dec, theta_joint) p_joint_val = p_joint_all(pi_pc,", "3 settings we run: MACRKL, Joint-action-learner (always uses CK), #", "* torch.ger(p_marg_ag0_ck1, pi_dec[1]) \\ + p_one * p_d_ck1 * (1", "apply temperature to set testing pi_pc = F.softmax(pol_vals * beta,", "expected return: sum_{\\tau} P(\\tau | pi) R(\\tau) def expected_return(p_common, p_observation,", "# These are the 3 settings we run: MACRKL, Joint-action-learner", "Matrix ID = 0, CK & Matrix ID = 1),", "range(n_agents): if receives_obs[ag]: observations[ag] += matrix_id + 1 return common_knowledge,", "short on time. (Eg. n_trials = 20) #n_trials = 100", "elif low2 >= low1 and high1 > low2: p_final[i] =", "[\"IAC\", \"JAL\"] p_vec = [0.0, 0.2, 0.4, 0.6, 0.8, 1.0]", "executed online, no need to download anything # http://pytorch.org/ from", "'IAC']: r_test = expected_return(p_common, p_observation, thetas, run, True, p_ck_noise) results_log_test[i", "gradients lr = 0.05 # DEBUG: 0.05 if exact gradients!", "elif run == 'IAC': pol_vals[1:] = -10 ** 10 #", "1]) plt.savefig(\"MACKRL {}.pdf\".format(titles[pl])) plt.show(block=False) if __name__ == \"__main__\": freeze_support() main()", "in [0, 1]: for matrix_id in [0, 1]: for obs_0", "= - expected_return(p_common, p_observation, thetas, run, False, p_ck_noise) r_s =", "p_ck_noise) r_s = -loss.data.numpy() optimizer.zero_grad() loss.backward() optimizer.step() if i %", "(always uses CK), # Independent Actor-Critic (always uses decentralised actions", "test: beta = 100 else: beta = 1 actions =", "* p_d_ck2 + p_both * p_d_ck1 + p_none * p_d_ck2)", "ck_state == 2: p_joint = p_none * p_joint_ck2 + \\", "[0,1] 2. Do multinomial sampling through contiguous, ordered bucketing for", "get_state(ck, obs_0, obs_1, matrix_id) # Get final probabilities for joint", "= p_none * p_joint_ck1 + \\ p_both * p_joint_ck2 +", "in enumerate(p_ck_noise): try: results = run_results[run_id][pnoise_id][p_common_id] except Exception as e:", "* torch.ger(p_marg_ag0_ck2, pi_dec[1]) \\ + p_one * p_d_ck2 * (1", "ck_state = get_policies(common_knowledge, observations, run, test, thetas_dec, theta_joint, p_ck_noise) p_joint_val", "# Add return from given state ret_val = ret_val +", "p2, mode=\"interval\"): \"\"\" 1. Pick uniform random variable between [0,1]", "import pickle import uuid import os res_dict = {} res_dict[\"final_res\"]", "thetas, run, True, p_ck_noise) results_log_test[i // (t_max // 100)] =", "1]: for obs_0 in [0, 1]: for obs_1 in [0,", "0 else: ck_state = int(observations[0] + 1) if p_ck_noise ==", "return p_joint pass def get_policies(common_knowledge, observations, run, test, thetas_dec, theta_joint,", "in params: param = param.to(\"cuda\") if optim == 'sgd': optimizer", "high learning rate, since we have exact gradients lr =", "final probabilities for joint actions if p_ck_noise==0: pi_pc, pi_dec =", "else: ck_state = int(observations[0] + 1) if p_ck_noise == 0:", "masked out for independent learner and joint-action-learner # independent learner", "else: observations = np.ones((n_agents)) * 2 # for ag in", "torch.sum(p2[:i]) high2 = low2 + p2[i] if low1 >= low2", "t_max, n_trials = args results = [] for nt in", "for r in results], axis=1)) final_res.append([all_res_test, all_res]) pool.close() pool.join() else:", "DEBUG: 0.05 if exact gradients! optim = 'adam' # You", "ag in range(n_agents): if receives_obs[ag]: observations[ag] += matrix_id + 1", "plt.figure(figsize=(5, 5)) color = ['b', 'r','g', 'c', 'm', 'y', 'k','b',", ":].clone() # logits get masked out for independent learner and", "== 1: observations = np.repeat(matrix_id, 2) else: observations = np.ones((n_agents))", "- low1 pass elif low2 >= low1 and high1 >", "beta, -1)) # calcuate decentralised policies for i in range(n_agents):", "Probability of observation given no CK) p_obs_val = [1 -", "= np.repeat(matrix_id, 2) else: observations = np.ones((n_agents)) * 2 #", "0, 0], ], dtype=torch.float32) * 0.2) n_agents = 2 n_actions", "+ p_none * p_d_ck1) * torch.ger(pi_dec[0], pi_dec[1]) \\ + p_one", "for obs_0 in [0, 1]: for obs_1 in [0, 1]:", "run_results.append(noise_results) for p_common_id, p_common in enumerate(p_vec): all_res = [] all_res_test", "1]) plt.yticks([0.5, 0.75, 1]) plt.savefig(\"MACKRL {}.pdf\".format(titles[pl])) plt.show(block=False) if __name__ ==", "Knowledge Reinforcement Learning (MACKRL) # The entire notebook can be", ">= low2 and high2 > low1: p_final[i] = torch.min(high1, high2)", "plt.legend() plt.xticks([0, 0.5, 1]) plt.yticks([0.5, 0.75, 1]) plt.savefig(\"MACKRL {}.pdf\".format(titles[pl])) plt.show(block=False)", "given no CK) p_obs_val = [1 - p_observation, p_observation] #", "pi_pcs[2][1:].view(n_actions, n_actions).clone().sum(dim=0) p_marg_ag1_ck1 = pi_pcs[1][1:].view(n_actions, n_actions).clone().sum(dim=1) p_marg_ag1_ck2 = pi_pcs[2][1:].view(n_actions, n_actions).clone().sum(dim=1)", "p_joint pass def get_policies(common_knowledge, observations, run, test, thetas_dec, theta_joint, p_ck_noise=0):", "(p_one * p_d_ck1 * p_d_ck2 + p_one * p_d_ck2 *", "j, p in enumerate( p_vec ): vals = final_res[j][pl] this_mean", "in range(n_agents)] thetas[\"joint\"] = init.normal_(torch.zeros(n_states_joint, n_actions ** 2 + 1,", "// 100)] = r_s results.append((results_log_test, results_log)) return results def main():", "p_d_ck1 * p_d_ck2 + p_both * p_d_ck1 + p_none *", "loss = - expected_return(p_common, p_observation, thetas, run, False, p_ck_noise) r_s", "(1 - p_d_ck1) * p_d_ck2 * torch.ger(p_marg_ag0_ck1, pi_dec[1]) return p_joint", "100)] = r_test results_log[i // (t_max // 100)] = r_s", "\\ p_both * p_joint_ck1 + \\ p_one * make_joint(p_joint_ck2, p_joint_ck1)", "/ (n_trials)**0.5 mean_vals.append( this_mean ) min_vals.append( low ) max_vals.append( high", "torch.ger(pi_dec[0], p_marg_ag1_ck2) \\ + p_one * (1 - p_d_ck2) *", "axis=1)) all_res.append(np.stack([r[1] for r in results], axis=1)) final_res.append([all_res_test, all_res]) import", "online, no need to download anything # http://pytorch.org/ from itertools", "* torch.ger(p_marg_ag0_ck1, pi_dec[1]) return p_joint elif ck_state == 2: p_joint", "n_actions, requires_grad=True), std=std_val) for i in range(n_agents)] thetas[\"joint\"] = init.normal_(torch.zeros(n_states_joint,", "pi_pcs[1][1:].view(n_actions, n_actions).clone().sum(dim=0) p_marg_ag0_ck2 = pi_pcs[2][1:].view(n_actions, n_actions).clone().sum(dim=0) p_marg_ag1_ck1 = pi_pcs[1][1:].view(n_actions, n_actions).clone().sum(dim=1)", "p_common_val = [1 - p_common, p_common] # Probability of observation", "(n_trials)**0.5 high = this_mean + std / (n_trials)**0.5 mean_vals.append( this_mean", "True, p_ck_noise) results_log_test[i // (t_max // 100)] = r_test results_log[i", "vals[i*len(p_ck_noise) + pck], 1)[-1] std = np.std(vals[i], 1)[-1]/0.5 low =", "= Adam(params, lr=lr) for i in range(t_max): if run in", "n_actions).clone() p_joint_ck2 = pi_pcs[2][1:].view(n_actions, n_actions).clone() p_d_ck0 = pi_pcs[0][0] p_d_ck1 =", "// (t_max // 100),)) thetas = {} thetas[\"dec\"] = [init.normal_(torch.zeros(n_states_dec,", "receives_obs[ag]: observations[ag] += matrix_id + 1 return common_knowledge, observations, matrix_id", "ID = 1), n_actions^2 actions for # # joint action", "['b', 'r','g', 'c', 'm', 'y', 'k','b', 'r','g', 'c', 'm', 'y',", "# logits get masked out for independent learner and joint-action-learner", "p_one * p_d_ck1 * (1 - p_d_ck2) * torch.ger(pi_dec[0], p_marg_ag1_ck2)", "+ p_both * p_d_ck2 + p_none * p_d_ck1) * torch.ger(pi_dec[0],", "thetas_dec, theta_joint, p_ck_noise=0): if test: beta = 100 else: beta", "input state (no CK, CK & Matrix ID = 0,", "run_id, run in enumerate(labels): for pnoise_id, pnoise in enumerate(p_ck_noise): try:", "p1.clone().view(-1) p2 = p2.clone().view(-1) p_final = p1.clone().zero_() if mode ==", "+ p1[i] low2 = torch.sum(p2[:i]) high2 = low2 + p2[i]", "+ p_state * expected_ret return ret_val def _proc(args): p_common, p_observation,", "(1 - p_d_ck2) * p_d_ck1 * torch.ger(p_marg_ag0_ck2, pi_dec[1]) return p_joint", "0, 0, 2, 0], [0, 0, 0, 1, 0], [0,", "if common_knowledge == 0: ck_state = 0 else: ck_state =", "[] for j, p in enumerate( p_vec ): vals =", "agents. # theta_joint = init.normal_(torch.zeros(n_states_joint, n_actions ** 2 + 1,", "-1)) # calcuate decentralised policies for i in range(n_agents): dec_state", "sampling through contiguous, ordered bucketing for both p1, p2 \"\"\"", "5)) color = ['b', 'r','g', 'c', 'm', 'y', 'k','b', 'r','g',", "uses decentralised actions selection) labels = [\"IAC\", \"JAL\"] p_vec =", "r_s results.append((results_log_test, results_log)) return results def main(): use_mp = True", "# payoff values [5, 0, 0, 2, 0], [0, 1,", "max_vals.append( high ) plt.plot(p_vec, mean_vals, color[(i*len(p_ck_noise) + pck) % len(color)],", "[1 - p_common, p_common] # Probability of observation given no", "# http://pytorch.org/ from itertools import chain import torch import torch.nn.functional", "These are the 3 settings we run: MACRKL, Joint-action-learner (always", "= {} res_dict[\"final_res\"] = final_res res_dict[\"labels\"] = labels res_dict[\"p_ck_noise\"] =", "run in ['MACKRL', 'JAL', 'IAC']: loss = - expected_return(p_common, p_observation,", "* p_d_ck2 * torch.ger(p_marg_ag0_ck1, pi_dec[1]) return p_joint elif ck_state ==", "P_common: {} #Trial: {}\".format(run, p_ck_noise, p_common, nt)) results_log = np.zeros((t_max", "def p_joint_all(pi_pc, pi_dec): p_joint = pi_pc[1:].view(n_actions, n_actions).clone() pi_a_pi_b = torch.ger(pi_dec[0],", "temperature to set testing pi_pcs.append(F.softmax(pol_vals[i] * beta, -1)) # calcuate", "std = np.std(vals[i], 1)[-1]/0.5 low = this_mean-std / (n_trials)**0.5 high", "= F.softmax(thetas_dec[i][dec_state] * beta, -1) pi_dec.append(pi) return pi_pc, pi_dec else:", "[] payoff_values.append(torch.tensor([ # payoff values [5, 0, 0, 2, 0],", "Multi-Agent Common Knowledge Reinforcement Learning (MACKRL) # The entire notebook", "rate, since we have exact gradients lr = 0.05 #", "random variable between [0,1] 2. Do multinomial sampling through contiguous,", "= torch.sum(p2[:i]) high2 = low2 + p2[i] if low1 >=", "actions for # # joint action + 1 action for", "in range(n_states_joint): if run == 'JAL': pol_vals[i][0] = -10 **", "# Probability of observation given no CK) p_obs_val = [1", "for joint actions if p_ck_noise==0: pi_pc, pi_dec = get_policies(common_knowledge, observations,", "run, pnoise, t_max, n_trials)) for pc in p_vec ] noise_results.append(results)", "Learning (MACKRL) # The entire notebook can be executed online,", "informative if common_knowledge == 0: ck_state = 0 else: ck_state", "p_d_ck2 * p_d_ck1 + p_one * p_d_ck1 * p_d_ck2 +", "'r','g', 'c', 'm', 'y', 'k'] titles = ['Test', 'Train Performance']", "requires_grad=True), std=std_val) params = chain(*[_v if isinstance(_v, (list, tuple)) else", "5 n_states_joint = 3 n_mix_hidden = 3 p_observation = 0.5", "= args results = [] for nt in range(n_trials): print(\"Run:", "[ (pc, p_observation, run, pnoise, t_max, n_trials) for pc in", "results_log)) return results def main(): use_mp = True if use_mp:", "= 100 else: beta = 1 actions = [] pi_dec", "min_vals, max_vals, facecolor=color[i], alpha=0.3) plt.xlabel('P(common knowledge)') plt.ylabel('Expected Return') plt.ylim([0.0, 1.01])", "all_res.append(np.stack([r[1] for r in results], axis=1)) final_res.append([all_res_test, all_res]) pool.close() pool.join()", "labels = [\"IAC\", \"JAL\"] p_vec = [0.0, 0.2, 0.4, 0.6,", "n_actions).clone().sum(dim=1) p_marg_ag1_ck2 = pi_pcs[2][1:].view(n_actions, n_actions).clone().sum(dim=1) p_joint_ck0 = pi_pcs[0][1:].view(n_actions, n_actions).clone() p_joint_ck1", "in range(len(labels)): for pck, pcknoise in enumerate(p_ck_noise): mean_vals = []", "if i % (t_max // 100) == 0: if run", "# calculate overlap between the probability distributions low1 = torch.sum(p1[:i])", "rewards and action probabilities expected_ret = (p_joint_val * payoff_values[matrix_id]).sum() #", "= 1 actions = [] pi_dec = [] # common_knowledge", "= low1 + p1[i] low2 = torch.sum(p2[:i]) high2 = low2", "= Pool(processes=2) # Well be appending results to these lists", "linestyle='-', linewidth=1) ax.set_title(titles[pl]) plt.legend() plt.xticks([0, 0.5, 1]) plt.yticks([0.5, 0.75, 1])", "n_actions) if ck_state == 0: p_joint = p_joint_ck0 + p_d_ck0", "p_obs_val[obs_0] * p_obs_val[obs_1] * p_matrix[matrix_id] common_knowledge, observations, matrix_id = get_state(ck,", "p_observation, run, p_ck_noise, t_max, n_trials = args results = []", "100),)) results_log_test = np.zeros((t_max // (t_max // 100),)) thetas =", "(t_max // 100),)) thetas = {} thetas[\"dec\"] = [init.normal_(torch.zeros(n_states_dec, n_actions,", "(list, tuple)) else [_v] for _v in thetas.values()]) params =", "== 'IAC': pol_vals[1:] = -10 ** 10 # apply temperature", "torch.ger(pi_dec[0], p_marg_ag1_ck1) \\ + p_one * (1 - p_d_ck1) *", "== 2: p_joint = p_none * p_joint_ck2 + \\ p_both", "n_actions ** 2 + 1, requires_grad=True), std=0.1) # Produce marginalised", "p_matrix[matrix_id] common_knowledge, observations, matrix_id = get_state(ck, obs_0, obs_1, matrix_id) #", "= [] for pnoise in p_ck_noise: print(\"Run: {} P_CK_NOISE: {}\".format(run,", "between [0,1] 2. Do multinomial sampling through contiguous, ordered bucketing", "\"wb\")) plt.figure(figsize=(5, 5)) color = ['b', 'r','g', 'c', 'm', 'y',", "np.repeat(matrix_id, 2) else: observations = np.ones((n_agents)) * 2 # for", "dtype=torch.float32) * 0.2) payoff_values.append( torch.tensor([ # payoff values [0, 0,", "def p_joint_all_noise_alt(pi_pcs, pi_dec, p_ck_noise, ck_state): p_none = (1-p_ck_noise) ** 2", "if mode == \"interval\": for i in range(p1.shape[0]): # calculate", "pi_pcs.append(F.softmax(pol_vals[i] * beta, -1)) # calcuate decentralised policies for i", "- p_d_ck2) * torch.ger(pi_dec[0], p_marg_ag1_ck2) \\ + p_one * (1", "param = param.to(\"cuda\") if optim == 'sgd': optimizer = SGD(params,", "= 0, CK & Matrix ID = 1), n_actions^2 actions", "as plt use_cuda = False payoff_values = [] payoff_values.append(torch.tensor([ #", "return p_joint def p_joint_all_noise_alt(pi_pcs, pi_dec, p_ck_noise, ck_state): p_none = (1-p_ck_noise)", "pnoise, t_max, n_trials) for pc in p_vec ]) noise_results.append(results) run_results.append(noise_results)", "n_trials) for pc in p_vec ]) noise_results.append(results) run_results.append(noise_results) for p_common_id,", "torch.ger(p_marg_ag0_ck1, pi_dec[1]) \\ + p_one * p_d_ck1 * (1 -", "+ p_d_ck0 * torch.ger(pi_dec[0], pi_dec[1]) return p_joint # always delegate", "= 20 #15 #100 std_val = 1.0 # These are", "theta_joint, p_ck_noise) p_joint_val = p_joint_all_noise_alt(pol_vals, pi_dec, p_ck_noise, ck_state) # Expected", "res_dict[\"labels\"] = labels res_dict[\"p_ck_noise\"] = p_ck_noise res_dict[\"p_vec\"] = p_vec if", "# Well be appending results to these lists run_results =", "p_ck_noise == 0: pol_vals = theta_joint[ck_state, :].clone() # logits get", "Matrix ID = 1), n_actions^2 actions for # # joint", "p_joint_ck2) + \\ (p_one * p_d_ck2 * p_d_ck1 + p_one", "= [0.5, 0.5] # p_matrix = [1.0, 0.0] # DEBUG!", "range(n_trials): print(\"Run: {} P_CK_NOISE: {} P_common: {} #Trial: {}\".format(run, p_ck_noise,", "- p_d_ck2) * p_d_ck1 * torch.ger(p_marg_ag0_ck2, pi_dec[1]) return p_joint pass", "= 1.0 # These are the 3 settings we run:", "= [] for run_id, run in enumerate(labels): for pnoise_id, pnoise", "+ p_one * (1 - p_d_ck2) * p_d_ck1 * torch.ger(p_marg_ag0_ck2,", "[0.0] # Number of gradient steps t_max = 202 #", "in ['MACKRL', 'JAL', 'IAC']: r_test = expected_return(p_common, p_observation, thetas, run,", "pol_vals[i][1:] = -10 ** 10 # apply temperature to set", "decentralised policies for i in range(n_agents): dec_state = int(observations[i]) pi", "import init from torch.optim import Adam, SGD import numpy as", "pnoise in p_ck_noise: print(\"Run: {} P_CK_NOISE: {}\".format(run, pnoise)) results =", "0, 2, 0, 0], [0, 0, 1, 0, 0], ],", "p_obs_val = [1 - p_observation, p_observation] # Matrices are chosen", "[1, 2, 4, 2, 1], [0, 0, 2, 0, 0],", "# Initialise expected return ret_val = 0 for ck in", "return p_final.clone().view(n_actions, n_actions) if ck_state == 0: p_joint = p_joint_ck0", "2, 1], [0, 0, 2, 0, 0], [0, 0, 1,", "n_states_dec = 5 n_states_joint = 3 n_mix_hidden = 3 p_observation", "\"\"\" p1 = p1.clone().view(-1) p2 = p2.clone().view(-1) p_final = p1.clone().zero_()", "= SGD(params, lr=lr) else: optimizer = Adam(params, lr=lr) for i", "range(n_agents)] thetas[\"joint\"] = init.normal_(torch.zeros(n_states_joint, n_actions ** 2 + 1, requires_grad=True),", "you are short on time. (Eg. n_trials = 20) #n_trials", "obs_1, matrix_id): receives_obs = [obs_0, obs_1] if common_knowledge == 1:", "pi_dec, p_ck_noise, ck_state): p_none = (1-p_ck_noise) ** 2 # both", ") max_vals.append( high ) plt.plot(p_vec, mean_vals, color[(i*len(p_ck_noise) + pck) %", "in [0, 1]: p_state = p_common_val[ck] * p_obs_val[obs_0] * p_obs_val[obs_1]", "torch.multiprocessing import Pool, set_start_method, freeze_support try: set_start_method('spawn') except RuntimeError: pass", "min_vals.append( low ) max_vals.append( high ) plt.plot(p_vec, mean_vals, color[(i*len(p_ck_noise) +", "init.normal_(torch.zeros(n_states_joint, n_actions ** 2 + 1, requires_grad=True), std=0.1) # Produce", "1, 2, 4, 2], [0, 0, 0, 2, 0], [0,", "ret_val def _proc(args): p_common, p_observation, run, p_ck_noise, t_max, n_trials =", "p_none = (1-p_ck_noise) ** 2 # both unnoised p_both =", "+ \\ p_one * make_joint(p_joint_ck2, p_joint_ck1) + \\ p_one *", "plt.xticks([0, 0.5, 1]) plt.yticks([0.5, 0.75, 1]) plt.savefig(\"MACKRL {}.pdf\".format(titles[pl])) plt.show(block=False) if", "'m', 'y', 'k','b', 'r','g', 'c', 'm', 'y', 'k'] titles =", "['Test', 'Train Performance'] for pl in [0,1]: ax = plt.subplot(1,", "[0, 0, 1, 0, 5], [0, 0, 2, 0, 0],", "= 0 for ck in [0, 1]: for matrix_id in", "# Produce marginalised policy: pi_pc[0] * pi^a * pi^b +", "if optim == 'sgd': optimizer = SGD(params, lr=lr) else: optimizer", "range(p1.shape[0]): # calculate overlap between the probability distributions low1 =", "= labels res_dict[\"p_ck_noise\"] = p_ck_noise res_dict[\"p_vec\"] = p_vec if not", "open(os.path.join(os.path.dirname(os.path.abspath(__file__)), \"pickles\", \"final_res_{}.p\".format(uuid.uuid4().hex[:4])), \"wb\")) plt.figure(figsize=(5, 5)) color = ['b', 'r','g',", "high2) - low1 pass elif low2 >= low1 and high1", "'k'] titles = ['Test', 'Train Performance'] for pl in [0,1]:", "def get_state(common_knowledge, obs_0, obs_1, matrix_id): receives_obs = [obs_0, obs_1] if", "\"interval\": for i in range(p1.shape[0]): # calculate overlap between the", "1, 0, 0], ], dtype=torch.float32) * 0.2) n_agents = 2", "ordered bucketing for both p1, p2 \"\"\" p1 = p1.clone().view(-1)", "decides whether ck_state is informative if common_knowledge == 0: ck_state", "thetas[\"dec\"] theta_joint = thetas[\"joint\"] # Probability of CK p_common_val =", "run == 'JAL': pol_vals[i][0] = -10 ** 10 elif run", "high2 = low2 + p2[i] if low1 >= low2 and", "# We'll be using a high learning rate, since we", "thetas_dec, theta_joint, p_ck_noise) p_joint_val = p_joint_all_noise_alt(pol_vals, pi_dec, p_ck_noise, ck_state) #", "0.4, 0.6, 0.8, 1.0] final_res = [] # # Pair-Controller", "[] pi_dec = [] # common_knowledge decides whether ck_state is", "This notebook implements a proof-of-principle for # Multi-Agent Common Knowledge", "'JAL', 'IAC']: r_test = expected_return(p_common, p_observation, thetas, run, True, p_ck_noise)", "of rewards and action probabilities expected_ret = (p_joint_val * payoff_values[matrix_id]).sum()", "= pi_pc[0] * pi_a_pi_b + p_joint return p_joint def p_joint_all_noise_alt(pi_pcs,", "the independent agents. # theta_joint = init.normal_(torch.zeros(n_states_joint, n_actions ** 2", "main(): use_mp = True if use_mp: pool = Pool(processes=2) #", "for ag in range(n_agents): if receives_obs[ag]: observations[ag] += matrix_id +", "run, False, p_ck_noise) r_s = -loss.data.numpy() optimizer.zero_grad() loss.backward() optimizer.step() if", "* make_joint(p_joint_ck2, p_joint_ck1) + \\ (p_one * p_d_ck1 * p_d_ck2", ">= low1 and high1 > low2: p_final[i] = torch.min(high1, high2)", "p_joint_ck2 + \\ p_both * p_joint_ck1 + \\ p_one *", "'r','g', 'c', 'm', 'y', 'k','b', 'r','g', 'c', 'm', 'y', 'k']", "len(color)], label = \"{} p_ck_noise: {}\".format(labels[i], pcknoise)) plt.fill_between(p_vec, min_vals, max_vals,", "import chain import torch import torch.nn.functional as F from torch.multiprocessing", "0, 0, 0], ], dtype=torch.float32) * 0.2) payoff_values.append( torch.tensor([ #", "optim = 'adam' # You can reduce this number if", "2 + 1, requires_grad=True), std=0.1) # Produce marginalised policy: pi_pc[0]", "pol_vals = theta_joint.clone() pi_pcs = [] for i in range(n_states_joint):", "pi_dec, p_ck_noise, ck_state) # Expected return is just the elementwise", "1]: for obs_1 in [0, 1]: p_state = p_common_val[ck] *", "* torch.ger(pi_dec[0], pi_dec[1]) \\ + p_one * p_d_ck2 * (1", "payoff values [0, 0, 1, 0, 5], [0, 0, 2,", "torch.ger(pi_dec[0], pi_dec[1]) \\ + p_one * p_d_ck1 * (1 -", "payoff_values = [] payoff_values.append(torch.tensor([ # payoff values [5, 0, 0,", "> low1: p_final[i] = torch.min(high1, high2) - low1 pass elif", "in p_vec ]) noise_results.append(results) run_results.append(noise_results) for p_common_id, p_common in enumerate(p_vec):", "ID = 0, CK & Matrix ID = 1), n_actions^2", "policies for i in range(n_agents): dec_state = int(observations[i]) pi =", "pnoise, t_max, n_trials)) for pc in p_vec ] noise_results.append(results) run_results.append(noise_results)", "p_d_ck2 + p_one * p_d_ck2 * p_d_ck1 + p_both *", "torch.ger(p_marg_ag0_ck1, pi_dec[1]) return p_joint elif ck_state == 2: p_joint =", "\"{} p_ck_noise: {}\".format(labels[i], pcknoise)) plt.fill_between(p_vec, min_vals, max_vals, facecolor=color[i], alpha=0.3) plt.xlabel('P(common", "3 n_mix_hidden = 3 p_observation = 0.5 p_ck_noise = [0.0]", "p_joint_ck1) + \\ p_one * make_joint(p_joint_ck1, p_joint_ck2) + \\ (p_one", "ret_val = 0 for ck in [0, 1]: for matrix_id", "max_vals, facecolor=color[i], alpha=0.3) plt.xlabel('P(common knowledge)') plt.ylabel('Expected Return') plt.ylim([0.0, 1.01]) plt.xlim([-0.01,", "pi_pcs = [] for i in range(n_states_joint): if run ==", "mean_vals, color[(i*len(p_ck_noise) + pck) % len(color)], label = \"{} p_ck_noise:", "we run: MACRKL, Joint-action-learner (always uses CK), # Independent Actor-Critic", "CK & Matrix ID = 0, CK & Matrix ID", "'JAL': pol_vals[i][0] = -10 ** 10 elif run == 'IAC':", "= torch.ger(pi_dec[0], pi_dec[1]) p_joint = pi_pc[0] * pi_a_pi_b + p_joint", "* p_d_ck1 * torch.ger(p_marg_ag0_ck2, pi_dec[1]) return p_joint pass def get_policies(common_knowledge,", "p_observation = 0.5 p_ck_noise = [0.0] # Number of gradient", "0], [0, 0, 0, 1, 0], [0, 0, 0, 0,", "low1 >= low2 and high2 > low1: p_final[i] = torch.min(high1,", "= False payoff_values = [] payoff_values.append(torch.tensor([ # payoff values [5,", "import numpy as np import matplotlib.pyplot as plt use_cuda =", "(1-p_ck_noise) ** 2 # both unnoised p_both = (p_ck_noise) **", "= 3 p_observation = 0.5 p_ck_noise = [0.0] # Number", "torch.ger(pi_dec[0], pi_dec[1]) return p_joint # always delegate elif ck_state ==", "to set testing pi_pcs.append(F.softmax(pol_vals[i] * beta, -1)) # calcuate decentralised", "p_joint_all_noise_alt(pi_pcs, pi_dec, p_ck_noise, ck_state): p_none = (1-p_ck_noise) ** 2 #", "0 return p_final.clone().view(n_actions, n_actions) if ck_state == 0: p_joint =", ") min_vals.append( low ) max_vals.append( high ) plt.plot(p_vec, mean_vals, color[(i*len(p_ck_noise)", "[] for run in labels: noise_results = [] for pnoise", "p_one * (1 - p_d_ck2) * p_d_ck1 * torch.ger(p_marg_ag0_ck2, pi_dec[1])", "in results], axis=1)) final_res.append([all_res_test, all_res]) pool.close() pool.join() else: # Well", "% len(color)], label = \"{} p_ck_noise: {}\".format(labels[i], pcknoise)) plt.fill_between(p_vec, min_vals,", "multinomial sampling through contiguous, ordered bucketing for both p1, p2", "100)] = r_s results.append((results_log_test, results_log)) return results def main(): use_mp", "0.2) payoff_values.append( torch.tensor([ # payoff values [0, 0, 1, 0,", "for _v in thetas.values()]) params = list(params) if use_cuda: for", "for # Multi-Agent Common Knowledge Reinforcement Learning (MACKRL) # The", "], dtype=torch.float32) * 0.2) payoff_values.append( torch.tensor([ # payoff values [0,", "pass def get_policies(common_knowledge, observations, run, test, thetas_dec, theta_joint, p_ck_noise=0): if", "params = list(params) if use_cuda: for param in params: param", "Pair-Controller with 3 input state (no CK, CK & Matrix", "#Trial: {}\".format(run, p_ck_noise, p_common, nt)) results_log = np.zeros((t_max // (t_max", "action for delegation to the independent agents. # theta_joint =", "std=0.1) # Produce marginalised policy: pi_pc[0] * pi^a * pi^b", "pol_vals = theta_joint[ck_state, :].clone() # logits get masked out for", "res_dict[\"p_ck_noise\"] = p_ck_noise res_dict[\"p_vec\"] = p_vec if not os.path.exists(os.path.join(os.path.dirname(os.path.abspath(__file__)), \"pickles\")):", "\\ p_one * make_joint(p_joint_ck2, p_joint_ck1) + \\ (p_one * p_d_ck1", "(no CK, CK & Matrix ID = 0, CK &", "implements a proof-of-principle for # Multi-Agent Common Knowledge Reinforcement Learning", "# Get final probabilities for joint actions if p_ck_noise==0: pi_pc,", "p_joint_ck0 + p_d_ck0 * torch.ger(pi_dec[0], pi_dec[1]) return p_joint # always", "* 0.2) payoff_values.append( torch.tensor([ # payoff values [0, 0, 1,", "for i in range(len(labels)): for pck, pcknoise in enumerate(p_ck_noise): mean_vals", "plt.ylim([0.0, 1.01]) plt.xlim([-0.01, 1.01]) ax.set_facecolor((1.0, 1.0, 1.0)) ax.grid(color='k', linestyle='-', linewidth=1)", "chain(*[_v if isinstance(_v, (list, tuple)) else [_v] for _v in", "# Pair-Controller with 3 input state (no CK, CK &", "p_matrix = [1.0, 0.0] # DEBUG! # Initialise expected return", "{} P_common: {} #Trial: {}\".format(run, p_ck_noise, p_common, nt)) results_log =", "p_joint = p_none * p_joint_ck2 + \\ p_both * p_joint_ck1", "final_res = [] # # Pair-Controller with 3 input state", "p_common] # Probability of observation given no CK) p_obs_val =", "p(u^ab) def p_joint_all(pi_pc, pi_dec): p_joint = pi_pc[1:].view(n_actions, n_actions).clone() pi_a_pi_b =", "\\ (p_one * p_d_ck2 * p_d_ck1 + p_one * p_d_ck1", "theta_joint.clone() pi_pcs = [] for i in range(n_states_joint): if run", "observations, run, test, thetas_dec, theta_joint, p_ck_noise) p_joint_val = p_joint_all_noise_alt(pol_vals, pi_dec,", "# both noised p_one = (1-p_ck_noise) * p_ck_noise # exactly", "2 + 1, requires_grad=True), std=std_val) params = chain(*[_v if isinstance(_v,", "nt in range(n_trials): print(\"Run: {} P_CK_NOISE: {} P_common: {} #Trial:", "of gradient steps t_max = 202 # We'll be using", "p_ck_noise # exactly one noised p_marg_ag0_ck1 = pi_pcs[1][1:].view(n_actions, n_actions).clone().sum(dim=0) p_marg_ag0_ck2", "pi_dec, ck_state def get_state(common_knowledge, obs_0, obs_1, matrix_id): receives_obs = [obs_0,", "sum_{\\tau} P(\\tau | pi) R(\\tau) def expected_return(p_common, p_observation, thetas, run,", "p_both = (p_ck_noise) ** 2 # both noised p_one =", "this_mean ) min_vals.append( low ) max_vals.append( high ) plt.plot(p_vec, mean_vals,", "pi_dec.append(pi) return pi_pc, pi_dec else: pol_vals = theta_joint.clone() pi_pcs =", "results], axis=1)) final_res.append([all_res_test, all_res]) pool.close() pool.join() else: # Well be", "+ \\ p_one * make_joint(p_joint_ck1, p_joint_ck2) + \\ p_one *", "1) if p_ck_noise == 0: pol_vals = theta_joint[ck_state, :].clone() #", "(1 - p_d_ck1) * p_d_ck2 * torch.ger(p_marg_ag0_ck1, pi_dec[1]) \\ +", "torch.nn.functional as F from torch.multiprocessing import Pool, set_start_method, freeze_support try:", "+ \\ (p_one * p_d_ck1 * p_d_ck2 + p_one *", "matrix_id) # Get final probabilities for joint actions if p_ck_noise==0:", "]) noise_results.append(results) run_results.append(noise_results) for p_common_id, p_common in enumerate(p_vec): all_res =", "high = this_mean + std / (n_trials)**0.5 mean_vals.append( this_mean )", "range(len(labels)): for pck, pcknoise in enumerate(p_ck_noise): mean_vals = [] min_vals", "Do multinomial sampling through contiguous, ordered bucketing for both p1,", "apply temperature to set testing pi_pcs.append(F.softmax(pol_vals[i] * beta, -1)) #", "'adam' # You can reduce this number if you are", "+ 1, requires_grad=True), std=0.1) # Produce marginalised policy: pi_pc[0] *", "low2 >= low1 and high1 > low2: p_final[i] = torch.min(high1,", "** 10 # apply temperature to set testing pi_pcs.append(F.softmax(pol_vals[i] *", "[0, 0, 0, 1, 0], [0, 0, 0, 0, 0],", "labels: noise_results = [] for pnoise in p_ck_noise: print(\"Run: {}", "0, 5], [0, 0, 2, 0, 0], [1, 2, 4,", "e: pass all_res_test.append(np.stack([r[0] for r in results], axis=1)) all_res.append(np.stack([r[1] for", "pc in p_vec ]) noise_results.append(results) run_results.append(noise_results) for p_common_id, p_common in", "enumerate(p_ck_noise): try: results = run_results[run_id][pnoise_id][p_common_id] except Exception as e: pass", "test, thetas_dec, theta_joint, p_ck_noise=0): if test: beta = 100 else:", "are short on time. (Eg. n_trials = 20) #n_trials =", "* p_d_ck1 + p_one * p_d_ck1 * p_d_ck2 + p_both", "for i in range(n_agents): dec_state = int(observations[i]) pi = F.softmax(thetas_dec[i][dec_state]", "F.softmax(thetas_dec[i][dec_state] * beta, -1) pi_dec.append(pi) return pi_pcs, pi_dec, ck_state def", "for pc in p_vec ] noise_results.append(results) run_results.append(noise_results) for p_common_id, p_common", "r_test = expected_return(p_common, p_observation, thetas, run, True, p_ck_noise) results_log_test[i //", "noise_results.append(results) run_results.append(noise_results) for p_common_id, p_common in enumerate(p_vec): all_res = []", "100),)) thetas = {} thetas[\"dec\"] = [init.normal_(torch.zeros(n_states_dec, n_actions, requires_grad=True), std=std_val)", "set testing pi_pcs.append(F.softmax(pol_vals[i] * beta, -1)) # calcuate decentralised policies", "n_actions).clone() p_joint_ck1 = pi_pcs[1][1:].view(n_actions, n_actions).clone() p_joint_ck2 = pi_pcs[2][1:].view(n_actions, n_actions).clone() p_d_ck0", "0.05 if exact gradients! optim = 'adam' # You can", "= this_mean-std / (n_trials)**0.5 high = this_mean + std /", "learning rate, since we have exact gradients lr = 0.05", "Performance'] for pl in [0,1]: ax = plt.subplot(1, 1, 1)", "p_joint_all_noise_alt(pol_vals, pi_dec, p_ck_noise, ck_state) # Expected return is just the", "= [] for i in range(n_states_joint): if run == 'JAL':", "pi_dec else: pol_vals = theta_joint.clone() pi_pcs = [] for i", "+ 1 return common_knowledge, observations, matrix_id # Calculate the expected", "# # Pair-Controller with 3 input state (no CK, CK", "def _proc(args): p_common, p_observation, run, p_ck_noise, t_max, n_trials = args", "plt.xlabel('P(common knowledge)') plt.ylabel('Expected Return') plt.ylim([0.0, 1.01]) plt.xlim([-0.01, 1.01]) ax.set_facecolor((1.0, 1.0,", "delegate elif ck_state == 1: p_joint = p_none * p_joint_ck1", "lr=lr) for i in range(t_max): if run in ['MACKRL', 'JAL',", "- p_d_ck1) * torch.ger(pi_dec[0], p_marg_ag1_ck1) \\ + p_one * (1", "# Number of gradient steps t_max = 202 # We'll", "controller that always delegates if run == 'JAL': pol_vals[0] =", "10 elif run == 'IAC': pol_vals[i][1:] = -10 ** 10", "= r_test results_log[i // (t_max // 100)] = r_s results.append((results_log_test,", "** 10 # apply temperature to set testing pi_pc =", "print(\"Run: {} P_CK_NOISE: {} P_common: {} #Trial: {}\".format(run, p_ck_noise, p_common,", "pi_pc[1:].view(n_actions, n_actions).clone() pi_a_pi_b = torch.ger(pi_dec[0], pi_dec[1]) p_joint = pi_pc[0] *", "delegates if run == 'JAL': pol_vals[0] = -10 ** 10", "one noised p_marg_ag0_ck1 = pi_pcs[1][1:].view(n_actions, n_actions).clone().sum(dim=0) p_marg_ag0_ck2 = pi_pcs[2][1:].view(n_actions, n_actions).clone().sum(dim=0)", "torch.sum(p1[:i]) high1 = low1 + p1[i] low2 = torch.sum(p2[:i]) high2", "[0, 0, 0, 0, 0], ], dtype=torch.float32) * 0.2) payoff_values.append(", "# # joint action + 1 action for delegation to", "p_joint_ck1) + \\ (p_one * p_d_ck1 * p_d_ck2 + p_one", "the probability distributions low1 = torch.sum(p1[:i]) high1 = low1 +", "p_state = p_common_val[ck] * p_obs_val[obs_0] * p_obs_val[obs_1] * p_matrix[matrix_id] common_knowledge,", "torch.nn import init from torch.optim import Adam, SGD import numpy", "p_none * p_joint_ck2 + \\ p_both * p_joint_ck1 + \\", "this_mean + std / (n_trials)**0.5 mean_vals.append( this_mean ) min_vals.append( low", "for i in range(n_agents)] thetas[\"joint\"] = init.normal_(torch.zeros(n_states_joint, n_actions ** 2", "_v in thetas.values()]) params = list(params) if use_cuda: for param", "variable between [0,1] 2. Do multinomial sampling through contiguous, ordered", "p_both * p_d_ck2 + p_none * p_d_ck1) * torch.ger(pi_dec[0], pi_dec[1])", "if test: beta = 100 else: beta = 1 actions", "= np.mean( vals[i*len(p_ck_noise) + pck], 1)[-1] std = np.std(vals[i], 1)[-1]/0.5", "are the 3 settings we run: MACRKL, Joint-action-learner (always uses", "= int(observations[i]) pi = F.softmax(thetas_dec[i][dec_state] * beta, -1) pi_dec.append(pi) return", "res_dict[\"final_res\"] = final_res res_dict[\"labels\"] = labels res_dict[\"p_ck_noise\"] = p_ck_noise res_dict[\"p_vec\"]", "2: p_joint = p_none * p_joint_ck2 + \\ p_both *", "[] all_res_test = [] for run_id, run in enumerate(labels): for", "probability distributions low1 = torch.sum(p1[:i]) high1 = low1 + p1[i]", "dec_state = int(observations[i]) pi = F.softmax(thetas_dec[i][dec_state] * beta, -1) pi_dec.append(pi)", "matrix_id = get_state(ck, obs_0, obs_1, matrix_id) # Get final probabilities", "actions if p_ck_noise==0: pi_pc, pi_dec = get_policies(common_knowledge, observations, run, test,", "std_val = 1.0 # These are the 3 settings we", "p_one * make_joint(p_joint_ck1, p_joint_ck2) + \\ p_one * make_joint(p_joint_ck2, p_joint_ck1)", "proof-of-principle for # Multi-Agent Common Knowledge Reinforcement Learning (MACKRL) #", "[0, 1]: for obs_1 in [0, 1]: p_state = p_common_val[ck]", "notebook implements a proof-of-principle for # Multi-Agent Common Knowledge Reinforcement", "== 'JAL': pol_vals[0] = -10 ** 10 elif run ==", "pi_pc = F.softmax(pol_vals * beta, -1) # calcuate decentralised policies", "1, requires_grad=True), std=std_val) params = chain(*[_v if isinstance(_v, (list, tuple))", "dtype=torch.float32) * 0.2) n_agents = 2 n_actions = len(payoff_values[0]) n_states_dec", "calcuate decentralised policies for i in range(n_agents): dec_state = int(observations[i])", "100) == 0: if run in ['MACKRL', 'JAL', 'IAC']: r_test", "0, 2, 0], [0, 1, 2, 4, 2], [0, 0,", "calculate overlap between the probability distributions low1 = torch.sum(p1[:i]) high1", "if run in ['MACKRL', 'JAL', 'IAC']: loss = - expected_return(p_common,", "run in ['MACKRL', 'JAL', 'IAC']: r_test = expected_return(p_common, p_observation, thetas,", "= (1-p_ck_noise) ** 2 # both unnoised p_both = (p_ck_noise)", "> low2: p_final[i] = torch.min(high1, high2) - low2 else: p_final[i]", "[init.normal_(torch.zeros(n_states_dec, n_actions, requires_grad=True), std=std_val) for i in range(n_agents)] thetas[\"joint\"] =", "elementwise product of rewards and action probabilities expected_ret = (p_joint_val", "reduce this number if you are short on time. (Eg.", "state (no CK, CK & Matrix ID = 0, CK", "], dtype=torch.float32) * 0.2) n_agents = 2 n_actions = len(payoff_values[0])", "pi_dec[1]) return p_joint # always delegate elif ck_state == 1:", "# both unnoised p_both = (p_ck_noise) ** 2 # both", "ck_state == 1: p_joint = p_none * p_joint_ck1 + \\", "joint actions if p_ck_noise==0: pi_pc, pi_dec = get_policies(common_knowledge, observations, run,", "p1.clone().zero_() if mode == \"interval\": for i in range(p1.shape[0]): #", "= low2 + p2[i] if low1 >= low2 and high2", "[_v] for _v in thetas.values()]) params = list(params) if use_cuda:", "n_actions^2 actions for # # joint action + 1 action", "[] # # Pair-Controller with 3 input state (no CK,", "'JAL', 'IAC']: loss = - expected_return(p_common, p_observation, thetas, run, False,", "#n_trials = 100 # 30 n_trials = 20 #15 #100", "* beta, -1) # calcuate decentralised policies for i in", "{}\".format(labels[i], pcknoise)) plt.fill_between(p_vec, min_vals, max_vals, facecolor=color[i], alpha=0.3) plt.xlabel('P(common knowledge)') plt.ylabel('Expected", "p_ck_noise) p_joint_val = p_joint_all_noise_alt(pol_vals, pi_dec, p_ck_noise, ck_state) # Expected return", "and joint-action-learner # independent learner has a pair controller that", "independent agents. # theta_joint = init.normal_(torch.zeros(n_states_joint, n_actions ** 2 +", "final_res.append([all_res_test, all_res]) import pickle import uuid import os res_dict =", "import os res_dict = {} res_dict[\"final_res\"] = final_res res_dict[\"labels\"] =", "from given state ret_val = ret_val + p_state * expected_ret", "from itertools import chain import torch import torch.nn.functional as F", "0, 1, 0], [0, 0, 0, 0, 0], ], dtype=torch.float32)", "tuple)) else [_v] for _v in thetas.values()]) params = list(params)", "pi_a_pi_b + p_joint return p_joint def p_joint_all_noise_alt(pi_pcs, pi_dec, p_ck_noise, ck_state):", "p_d_ck1 * torch.ger(p_marg_ag0_ck2, pi_dec[1]) \\ + p_one * p_d_ck2 *", "int(observations[i]) pi = F.softmax(thetas_dec[i][dec_state] * beta, -1) pi_dec.append(pi) return pi_pc,", "elif ck_state == 2: p_joint = p_none * p_joint_ck2 +", "0], [0, 0, 0, 0, 0], ], dtype=torch.float32) * 0.2)", "for i in range(t_max): if run in ['MACKRL', 'JAL', 'IAC']:", "p_none * p_d_ck2) * torch.ger(pi_dec[0], pi_dec[1]) \\ + p_one *", "pi_pc, pi_dec = get_policies(common_knowledge, observations, run, test, thetas_dec, theta_joint) p_joint_val", "p_matrix = [0.5, 0.5] # p_matrix = [1.0, 0.0] #", "common_knowledge decides whether ck_state is informative if common_knowledge == 0:", "= 100 # 30 n_trials = 20 #15 #100 std_val", "p_final.clone().view(n_actions, n_actions) if ck_state == 0: p_joint = p_joint_ck0 +", "if p_ck_noise == 0: pol_vals = theta_joint[ck_state, :].clone() # logits", "thetas[\"joint\"] # Probability of CK p_common_val = [1 - p_common,", "else: beta = 1 actions = [] pi_dec = []", "# Calculate the expected return: sum_{\\tau} P(\\tau | pi) R(\\tau)", "i in range(n_states_joint): if run == 'JAL': pol_vals[i][0] = -10", "\"pickles\", \"final_res_{}.p\".format(uuid.uuid4().hex[:4])), \"wb\")) plt.figure(figsize=(5, 5)) color = ['b', 'r','g', 'c',", "p_ck_noise: print(\"Run: {} P_CK_NOISE: {}\".format(run, pnoise)) results = [_proc((pc, p_observation,", "obs_1 in [0, 1]: p_state = p_common_val[ck] * p_obs_val[obs_0] *", "contiguous, ordered bucketing for both p1, p2 \"\"\" p1 =", "3 input state (no CK, CK & Matrix ID =", "ax.set_facecolor((1.0, 1.0, 1.0)) ax.grid(color='k', linestyle='-', linewidth=1) ax.set_title(titles[pl]) plt.legend() plt.xticks([0, 0.5,", "p_joint_ck1 + \\ p_both * p_joint_ck2 + \\ p_one *", "pool.join() else: # Well be appending results to these lists", "get_state(common_knowledge, obs_0, obs_1, matrix_id): receives_obs = [obs_0, obs_1] if common_knowledge", "pi_pc, pi_dec else: pol_vals = theta_joint.clone() pi_pcs = [] for", "ck in [0, 1]: for matrix_id in [0, 1]: for", "= [] payoff_values.append(torch.tensor([ # payoff values [5, 0, 0, 2,", "2 n_actions = len(payoff_values[0]) n_states_dec = 5 n_states_joint = 3", "run, pnoise, t_max, n_trials) for pc in p_vec ]) noise_results.append(results)", "distributions low1 = torch.sum(p1[:i]) high1 = low1 + p1[i] low2", "enumerate( p_vec ): vals = final_res[j][pl] this_mean = np.mean( vals[i*len(p_ck_noise)", "plt.xlim([-0.01, 1.01]) ax.set_facecolor((1.0, 1.0, 1.0)) ax.grid(color='k', linestyle='-', linewidth=1) ax.set_title(titles[pl]) plt.legend()", "1.01]) plt.xlim([-0.01, 1.01]) ax.set_facecolor((1.0, 1.0, 1.0)) ax.grid(color='k', linestyle='-', linewidth=1) ax.set_title(titles[pl])", "mean_vals.append( this_mean ) min_vals.append( low ) max_vals.append( high ) plt.plot(p_vec,", "& Matrix ID = 0, CK & Matrix ID =", "1, 0, 5], [0, 0, 2, 0, 0], [1, 2,", "[1 - p_observation, p_observation] # Matrices are chosen 50 /", "2 # for ag in range(n_agents): if receives_obs[ag]: observations[ag] +=", "p_both * p_joint_ck1 + \\ p_one * make_joint(p_joint_ck2, p_joint_ck1) +", "{}\".format(run, pnoise)) results = pool.map(_proc, [ (pc, p_observation, run, pnoise,", "0, 0, 1, 0], [0, 0, 0, 0, 0], ],", "# You can reduce this number if you are short", "ck_state == 0: p_joint = p_joint_ck0 + p_d_ck0 * torch.ger(pi_dec[0],", "& Matrix ID = 1), n_actions^2 actions for # #", "def expected_return(p_common, p_observation, thetas, run, test, p_ck_noise=0): thetas_dec = thetas[\"dec\"]", "False, p_ck_noise) r_s = -loss.data.numpy() optimizer.zero_grad() loss.backward() optimizer.step() if i", "% (t_max // 100) == 0: if run in ['MACKRL',", "-1) # calcuate decentralised policies for i in range(n_agents): dec_state", "marginalised policy: pi_pc[0] * pi^a * pi^b + p(u^ab) def", "np.zeros((t_max // (t_max // 100),)) thetas = {} thetas[\"dec\"] =", "): vals = final_res[j][pl] this_mean = np.mean( vals[i*len(p_ck_noise) + pck],", "len(payoff_values[0]) n_states_dec = 5 n_states_joint = 3 n_mix_hidden = 3", "if ck_state == 0: p_joint = p_joint_ck0 + p_d_ck0 *", "'Train Performance'] for pl in [0,1]: ax = plt.subplot(1, 1,", "uuid import os res_dict = {} res_dict[\"final_res\"] = final_res res_dict[\"labels\"]", "p_marg_ag0_ck2 = pi_pcs[2][1:].view(n_actions, n_actions).clone().sum(dim=0) p_marg_ag1_ck1 = pi_pcs[1][1:].view(n_actions, n_actions).clone().sum(dim=1) p_marg_ag1_ck2 =", "chosen 50 / 50 p_matrix = [0.5, 0.5] # p_matrix", "return from given state ret_val = ret_val + p_state *", "= list(params) if use_cuda: for param in params: param =", "else: optimizer = Adam(params, lr=lr) for i in range(t_max): if", "observations, run, test, thetas_dec, theta_joint) p_joint_val = p_joint_all(pi_pc, pi_dec) else:", "p_ck_noise res_dict[\"p_vec\"] = p_vec if not os.path.exists(os.path.join(os.path.dirname(os.path.abspath(__file__)), \"pickles\")): os.makedirs(os.path.join(os.path.dirname(os.path.abspath(__file__)), \"pickles\"))", "'k','b', 'r','g', 'c', 'm', 'y', 'k'] titles = ['Test', 'Train", "p_vec ] noise_results.append(results) run_results.append(noise_results) for p_common_id, p_common in enumerate(p_vec): all_res", "True if use_mp: pool = Pool(processes=2) # Well be appending", "* p_d_ck2 * (1 - p_d_ck1) * torch.ger(pi_dec[0], p_marg_ag1_ck1) \\", "results to these lists run_results = [] for run in", "= {} thetas[\"dec\"] = [init.normal_(torch.zeros(n_states_dec, n_actions, requires_grad=True), std=std_val) for i", "entire notebook can be executed online, no need to download", "1)[-1] std = np.std(vals[i], 1)[-1]/0.5 low = this_mean-std / (n_trials)**0.5", "0.5] # p_matrix = [1.0, 0.0] # DEBUG! # Initialise", "ck_state def get_state(common_knowledge, obs_0, obs_1, matrix_id): receives_obs = [obs_0, obs_1]", "0], [0, 1, 2, 4, 2], [0, 0, 0, 2,", "# The entire notebook can be executed online, no need", "== \"interval\": for i in range(p1.shape[0]): # calculate overlap between", "number if you are short on time. (Eg. n_trials =", "p_final[i] = torch.min(high1, high2) - low1 pass elif low2 >=", "2, 4, 2], [0, 0, 0, 2, 0], [0, 0,", "observations = np.ones((n_agents)) * 2 # for ag in range(n_agents):", "matrix_id # Calculate the expected return: sum_{\\tau} P(\\tau | pi)", "= pi_pcs[2][1:].view(n_actions, n_actions).clone() p_d_ck0 = pi_pcs[0][0] p_d_ck1 = pi_pcs[1][0] p_d_ck2", "low2 else: p_final[i] = 0 return p_final.clone().view(n_actions, n_actions) if ck_state", "= int(observations[0] + 1) if p_ck_noise == 0: pol_vals =", "\\ (p_one * p_d_ck1 * p_d_ck2 + p_one * p_d_ck2", "can be executed online, no need to download anything #", "p_vec ]) noise_results.append(results) run_results.append(noise_results) for p_common_id, p_common in enumerate(p_vec): all_res", "run, test, thetas_dec, theta_joint, p_ck_noise) p_joint_val = p_joint_all_noise_alt(pol_vals, pi_dec, p_ck_noise,", "set testing pi_pc = F.softmax(pol_vals * beta, -1) # calcuate", "for r in results], axis=1)) final_res.append([all_res_test, all_res]) import pickle import", "p_vec if not os.path.exists(os.path.join(os.path.dirname(os.path.abspath(__file__)), \"pickles\")): os.makedirs(os.path.join(os.path.dirname(os.path.abspath(__file__)), \"pickles\")) pickle.dump(res_dict, open(os.path.join(os.path.dirname(os.path.abspath(__file__)), \"pickles\",", "of observation given no CK) p_obs_val = [1 - p_observation,", "args results = [] for nt in range(n_trials): print(\"Run: {}", "pass all_res_test.append(np.stack([r[0] for r in results], axis=1)) all_res.append(np.stack([r[1] for r", "-10 ** 10 # apply temperature to set testing pi_pcs.append(F.softmax(pol_vals[i]", "torch import torch.nn.functional as F from torch.multiprocessing import Pool, set_start_method,", "use_cuda = False payoff_values = [] payoff_values.append(torch.tensor([ # payoff values", "p_joint_all(pi_pc, pi_dec) else: pol_vals, pi_dec, ck_state = get_policies(common_knowledge, observations, run,", "Pick uniform random variable between [0,1] 2. Do multinomial sampling", "use_mp: pool = Pool(processes=2) # Well be appending results to", "p_ck_noise=0): thetas_dec = thetas[\"dec\"] theta_joint = thetas[\"joint\"] # Probability of", "requires_grad=True), std=std_val) for i in range(n_agents)] thetas[\"joint\"] = init.normal_(torch.zeros(n_states_joint, n_actions", "have exact gradients lr = 0.05 # DEBUG: 0.05 if", "\"pickles\")) pickle.dump(res_dict, open(os.path.join(os.path.dirname(os.path.abspath(__file__)), \"pickles\", \"final_res_{}.p\".format(uuid.uuid4().hex[:4])), \"wb\")) plt.figure(figsize=(5, 5)) color =", "actions = [] pi_dec = [] # common_knowledge decides whether", "* p_joint_ck2 + \\ p_one * make_joint(p_joint_ck1, p_joint_ck2) + \\", "i in range(n_agents)] thetas[\"joint\"] = init.normal_(torch.zeros(n_states_joint, n_actions ** 2 +", "= p_joint_all(pi_pc, pi_dec) else: pol_vals, pi_dec, ck_state = get_policies(common_knowledge, observations,", "in results], axis=1)) all_res.append(np.stack([r[1] for r in results], axis=1)) final_res.append([all_res_test,", "pc in p_vec ] noise_results.append(results) run_results.append(noise_results) for p_common_id, p_common in", "SGD import numpy as np import matplotlib.pyplot as plt use_cuda", "torch.min(high1, high2) - low1 pass elif low2 >= low1 and", "p_d_ck2 + p_none * p_d_ck1) * torch.ger(pi_dec[0], pi_dec[1]) \\ +", "= -10 ** 10 elif run == 'IAC': pol_vals[1:] =", "i in range(len(labels)): for pck, pcknoise in enumerate(p_ck_noise): mean_vals =", "p_final[i] = torch.min(high1, high2) - low2 else: p_final[i] = 0", "ck_state = int(observations[0] + 1) if p_ck_noise == 0: pol_vals", "always delegate elif ck_state == 1: p_joint = p_none *", "\\ + p_one * p_d_ck2 * (1 - p_d_ck1) *", "payoff_values.append( torch.tensor([ # payoff values [0, 0, 1, 0, 5],", "observations[ag] += matrix_id + 1 return common_knowledge, observations, matrix_id #", "a pair controller that always delegates if run == 'JAL':", "n_actions).clone().sum(dim=0) p_marg_ag0_ck2 = pi_pcs[2][1:].view(n_actions, n_actions).clone().sum(dim=0) p_marg_ag1_ck1 = pi_pcs[1][1:].view(n_actions, n_actions).clone().sum(dim=1) p_marg_ag1_ck2", "the elementwise product of rewards and action probabilities expected_ret =", "ck_state) # Expected return is just the elementwise product of", "using a high learning rate, since we have exact gradients", "* (1 - p_d_ck1) * torch.ger(pi_dec[0], p_marg_ag1_ck1) \\ + p_one", "make_joint(p_joint_ck2, p_joint_ck1) + \\ p_one * make_joint(p_joint_ck1, p_joint_ck2) + \\", "set_start_method('spawn') except RuntimeError: pass from torch.nn import init from torch.optim", "{} res_dict[\"final_res\"] = final_res res_dict[\"labels\"] = labels res_dict[\"p_ck_noise\"] = p_ck_noise", "2], [0, 0, 0, 2, 0], [0, 0, 0, 1,", "init from torch.optim import Adam, SGD import numpy as np", "for j, p in enumerate( p_vec ): vals = final_res[j][pl]", "(1 - p_d_ck1) * torch.ger(pi_dec[0], p_marg_ag1_ck1) \\ + p_one *", "i in range(n_agents): dec_state = int(observations[i]) pi = F.softmax(thetas_dec[i][dec_state] *", "+ 1, requires_grad=True), std=std_val) params = chain(*[_v if isinstance(_v, (list,", "thetas[\"dec\"] = [init.normal_(torch.zeros(n_states_dec, n_actions, requires_grad=True), std=std_val) for i in range(n_agents)]", "0.75, 1]) plt.savefig(\"MACKRL {}.pdf\".format(titles[pl])) plt.show(block=False) if __name__ == \"__main__\": freeze_support()", "pi_dec, ck_state = get_policies(common_knowledge, observations, run, test, thetas_dec, theta_joint, p_ck_noise)", "* p_d_ck1 + p_none * p_d_ck2) * torch.ger(pi_dec[0], pi_dec[1]) \\", "# Multi-Agent Common Knowledge Reinforcement Learning (MACKRL) # The entire", "10 # apply temperature to set testing pi_pc = F.softmax(pol_vals", "// 100),)) results_log_test = np.zeros((t_max // (t_max // 100),)) thetas", "color[(i*len(p_ck_noise) + pck) % len(color)], label = \"{} p_ck_noise: {}\".format(labels[i],", "chain import torch import torch.nn.functional as F from torch.multiprocessing import", "p_one * p_d_ck1 * p_d_ck2 + p_both * p_d_ck1 +", "import uuid import os res_dict = {} res_dict[\"final_res\"] = final_res", "\"pickles\")): os.makedirs(os.path.join(os.path.dirname(os.path.abspath(__file__)), \"pickles\")) pickle.dump(res_dict, open(os.path.join(os.path.dirname(os.path.abspath(__file__)), \"pickles\", \"final_res_{}.p\".format(uuid.uuid4().hex[:4])), \"wb\")) plt.figure(figsize=(5, 5))", "p_one * (1 - p_d_ck1) * p_d_ck2 * torch.ger(p_marg_ag0_ck1, pi_dec[1])", "['MACKRL', 'JAL', 'IAC']: r_test = expected_return(p_common, p_observation, thetas, run, True,", "# independent learner has a pair controller that always delegates", "{} thetas[\"dec\"] = [init.normal_(torch.zeros(n_states_dec, n_actions, requires_grad=True), std=std_val) for i in", "= pi_pcs[2][1:].view(n_actions, n_actions).clone().sum(dim=0) p_marg_ag1_ck1 = pi_pcs[1][1:].view(n_actions, n_actions).clone().sum(dim=1) p_marg_ag1_ck2 = pi_pcs[2][1:].view(n_actions,", "* (1 - p_d_ck2) * torch.ger(pi_dec[0], p_marg_ag1_ck2) \\ + p_one", "* p_obs_val[obs_1] * p_matrix[matrix_id] common_knowledge, observations, matrix_id = get_state(ck, obs_0,", "expected_ret return ret_val def _proc(args): p_common, p_observation, run, p_ck_noise, t_max,", "= [] all_res_test = [] for run_id, run in enumerate(labels):", "torch.optim import Adam, SGD import numpy as np import matplotlib.pyplot", "for run_id, run in enumerate(labels): for pnoise_id, pnoise in enumerate(p_ck_noise):", "import matplotlib.pyplot as plt use_cuda = False payoff_values = []", "common_knowledge == 0: ck_state = 0 else: ck_state = int(observations[0]", "\\ p_one * make_joint(p_joint_ck1, p_joint_ck2) + \\ (p_one * p_d_ck2", "- low2 else: p_final[i] = 0 return p_final.clone().view(n_actions, n_actions) if", "= init.normal_(torch.zeros(n_states_joint, n_actions ** 2 + 1, requires_grad=True), std=std_val) params", "p_d_ck1 + p_one * p_d_ck1 * p_d_ck2 + p_both *", "\"JAL\"] p_vec = [0.0, 0.2, 0.4, 0.6, 0.8, 1.0] final_res", "decentralised actions selection) labels = [\"IAC\", \"JAL\"] p_vec = [0.0,", "p_ck_noise=0): if test: beta = 100 else: beta = 1", "1.0)) ax.grid(color='k', linestyle='-', linewidth=1) ax.set_title(titles[pl]) plt.legend() plt.xticks([0, 0.5, 1]) plt.yticks([0.5,", "be appending results to these lists run_results = [] for", "p_d_ck2 * p_d_ck1 + p_both * p_d_ck2 + p_none *", "high1 > low2: p_final[i] = torch.min(high1, high2) - low2 else:", "= (p_ck_noise) ** 2 # both noised p_one = (1-p_ck_noise)", "'y', 'k','b', 'r','g', 'c', 'm', 'y', 'k'] titles = ['Test',", "'y', 'k'] titles = ['Test', 'Train Performance'] for pl in", "in p_ck_noise: print(\"Run: {} P_CK_NOISE: {}\".format(run, pnoise)) results = pool.map(_proc,", "import Pool, set_start_method, freeze_support try: set_start_method('spawn') except RuntimeError: pass from", "plt.subplot(1, 1, 1) for i in range(len(labels)): for pck, pcknoise", "run in labels: noise_results = [] for pnoise in p_ck_noise:", "we have exact gradients lr = 0.05 # DEBUG: 0.05", "* p_d_ck2 * p_d_ck1 + p_both * p_d_ck2 + p_none", "is informative if common_knowledge == 0: ck_state = 0 else:", "to set testing pi_pc = F.softmax(pol_vals * beta, -1) #", "* p_d_ck2 + p_one * p_d_ck2 * p_d_ck1 + p_both", "'sgd': optimizer = SGD(params, lr=lr) else: optimizer = Adam(params, lr=lr)", "results], axis=1)) final_res.append([all_res_test, all_res]) import pickle import uuid import os", "run, test, thetas_dec, theta_joint, p_ck_noise=0): if test: beta = 100", "beta, -1) pi_dec.append(pi) return pi_pcs, pi_dec, ck_state def get_state(common_knowledge, obs_0,", "return ret_val = 0 for ck in [0, 1]: for", "given state ret_val = ret_val + p_state * expected_ret return", "color = ['b', 'r','g', 'c', 'm', 'y', 'k','b', 'r','g', 'c',", "i % (t_max // 100) == 0: if run in", "1]: for matrix_id in [0, 1]: for obs_0 in [0,", "0.8, 1.0] final_res = [] # # Pair-Controller with 3", "* p_d_ck1 * torch.ger(p_marg_ag0_ck2, pi_dec[1]) \\ + p_one * p_d_ck2", "0, 1, 0, 5], [0, 0, 2, 0, 0], [1,", "[0, 0, 2, 0, 0], [1, 2, 4, 2, 1],", "for pc in p_vec ]) noise_results.append(results) run_results.append(noise_results) for p_common_id, p_common", "os.makedirs(os.path.join(os.path.dirname(os.path.abspath(__file__)), \"pickles\")) pickle.dump(res_dict, open(os.path.join(os.path.dirname(os.path.abspath(__file__)), \"pickles\", \"final_res_{}.p\".format(uuid.uuid4().hex[:4])), \"wb\")) plt.figure(figsize=(5, 5)) color", "= run_results[run_id][pnoise_id][p_common_id] except Exception as e: pass all_res_test.append(np.stack([r[0] for r", "= final_res[j][pl] this_mean = np.mean( vals[i*len(p_ck_noise) + pck], 1)[-1] std", "- p_common, p_common] # Probability of observation given no CK)", "= [init.normal_(torch.zeros(n_states_dec, n_actions, requires_grad=True), std=std_val) for i in range(n_agents)] thetas[\"joint\"]", "0, 0, 2, 0], [0, 1, 2, 4, 2], [0,", "0 for ck in [0, 1]: for matrix_id in [0,", "2, 0], [0, 0, 0, 1, 0], [0, 0, 0,", "exact gradients! optim = 'adam' # You can reduce this", "pnoise)) results = [_proc((pc, p_observation, run, pnoise, t_max, n_trials)) for", "[0, 1]: for matrix_id in [0, 1]: for obs_0 in", "since we have exact gradients lr = 0.05 # DEBUG:", "You can reduce this number if you are short on", "for run in labels: noise_results = [] for pnoise in", "* p_joint_ck1 + \\ p_both * p_joint_ck2 + \\ p_one", "res_dict = {} res_dict[\"final_res\"] = final_res res_dict[\"labels\"] = labels res_dict[\"p_ck_noise\"]", "if run in ['MACKRL', 'JAL', 'IAC']: r_test = expected_return(p_common, p_observation,", "* p_ck_noise # exactly one noised p_marg_ag0_ck1 = pi_pcs[1][1:].view(n_actions, n_actions).clone().sum(dim=0)", "[0.5, 0.5] # p_matrix = [1.0, 0.0] # DEBUG! #", "low2 = torch.sum(p2[:i]) high2 = low2 + p2[i] if low1", "* torch.ger(pi_dec[0], pi_dec[1]) \\ + p_one * p_d_ck1 * (1", "p_final = p1.clone().zero_() if mode == \"interval\": for i in", "1]: p_state = p_common_val[ck] * p_obs_val[obs_0] * p_obs_val[obs_1] * p_matrix[matrix_id]", "1.0, 1.0)) ax.grid(color='k', linestyle='-', linewidth=1) ax.set_title(titles[pl]) plt.legend() plt.xticks([0, 0.5, 1])", "beta = 100 else: beta = 1 actions = []", "2, 0, 0], [0, 0, 1, 0, 0], ], dtype=torch.float32)", "4, 2, 1], [0, 0, 2, 0, 0], [0, 0,", "try: results = run_results[run_id][pnoise_id][p_common_id] except Exception as e: pass all_res_test.append(np.stack([r[0]", "in p_ck_noise: print(\"Run: {} P_CK_NOISE: {}\".format(run, pnoise)) results = [_proc((pc,", "+ p_one * p_d_ck2 * (1 - p_d_ck1) * torch.ger(pi_dec[0],", "p_d_ck1 = pi_pcs[1][0] p_d_ck2 = pi_pcs[2][0] def make_joint(p1, p2, mode=\"interval\"):", "p_observation, thetas, run, False, p_ck_noise) r_s = -loss.data.numpy() optimizer.zero_grad() loss.backward()", "results], axis=1)) all_res.append(np.stack([r[1] for r in results], axis=1)) final_res.append([all_res_test, all_res])", "+ p_joint return p_joint def p_joint_all_noise_alt(pi_pcs, pi_dec, p_ck_noise, ck_state): p_none", "= [] max_vals = [] for j, p in enumerate(", "0, 0, 0, 0], ], dtype=torch.float32) * 0.2) payoff_values.append( torch.tensor([", "[0, 1]: p_state = p_common_val[ck] * p_obs_val[obs_0] * p_obs_val[obs_1] *", "observations, matrix_id = get_state(ck, obs_0, obs_1, matrix_id) # Get final", "p_ck_noise: print(\"Run: {} P_CK_NOISE: {}\".format(run, pnoise)) results = pool.map(_proc, [", "n_actions = len(payoff_values[0]) n_states_dec = 5 n_states_joint = 3 n_mix_hidden", "* (1 - p_d_ck1) * p_d_ck2 * torch.ger(p_marg_ag0_ck1, pi_dec[1]) return", "obs_0, obs_1, matrix_id) # Get final probabilities for joint actions", "p_none * p_d_ck1) * torch.ger(pi_dec[0], pi_dec[1]) \\ + p_one *", "expected return ret_val = 0 for ck in [0, 1]:", "time. (Eg. n_trials = 20) #n_trials = 100 # 30", "= theta_joint.clone() pi_pcs = [] for i in range(n_states_joint): if", "# DEBUG! # Initialise expected return ret_val = 0 for", "= torch.min(high1, high2) - low1 pass elif low2 >= low1", "= [1 - p_observation, p_observation] # Matrices are chosen 50", "pi_dec = get_policies(common_knowledge, observations, run, test, thetas_dec, theta_joint) p_joint_val =", "# Probability of CK p_common_val = [1 - p_common, p_common]", "Expected return is just the elementwise product of rewards and" ]
[ "in commit messages, so this is not # completely foolproof,", "shell=True) subprocess.call(f'git checkout {branch}', shell=True) if ORIGIN: subprocess.call(f'git reset --hard", "import json import re import subprocess import tempfile from collections", "JSON file that contains for each pull request the #", "branches and find all PRs in the branch for branch", "subprocess.call(f'git clone {REPOSITORY}', shell=True) os.chdir(NAME) # Loop over branches and", "look specifically for the # message \"Merge pull request #xxxx", "work for now. import os import sys import json import", "retain the clone between runs ORIGIN = 'origin' # set", "shell=True) # Extract log: log = subprocess.check_output('git log', shell=True).decode('utf-8') #", "contains for each pull request the # list of all", "Loop over branches and find all PRs in the branch", "print(\"The repository this script currently works with is '{}'.\\n\" .format(REPOSITORY_NAME))", "if sys.argv[1:]: REPOSITORY_NAME = sys.argv[1] else: REPOSITORY_NAME = 'astropy/astropy' print(\"The", "Change branch color_print(f'Switching to branch {branch}', 'green') subprocess.call('git reset --hard',", "shell=True) os.chdir(NAME) # Loop over branches and find all PRs", "request #(\\d+) ', log) + re.findall(r'Backport PR #(\\d+):', log)): pr_branches[pr].append(branch)", "over branches and find all PRs in the branch for", "f'git://github.com/{REPOSITORY_NAME}.git' NAME = os.path.basename(REPOSITORY_NAME) DIRTOCLONEIN = tempfile.mkdtemp() # set this", "it is an already ' 'existing clone'.format(NAME), 'yellow') os.chdir(NAME) if", "try: # Set up repository color_print(f'Cloning {REPOSITORY}', 'green') os.chdir(DIRTOCLONEIN) if", "subprocess.check_output('git log', shell=True).decode('utf-8') # Check for the presence of the", "= json.load(merged) # Set up a dictionary where each key", "dictionary where each key will be a PR and each", "not # completely foolproof, but seems to work for now.", "repository color_print(f'Cloning {REPOSITORY}', 'green') os.chdir(DIRTOCLONEIN) if os.path.isdir(NAME): # already exists...", "in a list of all the PRs with open(f'merged_pull_requests_{NAME}.json') as", "sys.argv[1] else: REPOSITORY_NAME = 'astropy/astropy' print(\"The repository this script currently", "PR and each value will be a list # of", "get_branches(REPOSITORY_NAME) # Read in a list of all the PRs", "Set up repository color_print(f'Cloning {REPOSITORY}', 'green') os.chdir(DIRTOCLONEIN) if os.path.isdir(NAME): #", "= 'origin' # set this to None to not fetch", "os.chdir(NAME) if ORIGIN: subprocess.call(f'git fetch {ORIGIN}', shell=True) else: subprocess.call(f'git clone", "message \"Merge pull request #xxxx \" in commit messages, so", "= f'git://github.com/{REPOSITORY_NAME}.git' NAME = os.path.basename(REPOSITORY_NAME) DIRTOCLONEIN = tempfile.mkdtemp() # set", "Check for the presence of the PR in the log", "pull requests are included in which # branches. The output", "in which it is included. We look specifically for the", "list # of branches in which the PR is present", "collections import defaultdict from astropy.utils.console import color_print from common import", "PR #(\\d+):', log)): pr_branches[pr].append(branch) finally: os.chdir(STARTDIR) with open(f'pull_requests_branches_{NAME}.json', 'w') as", "this is not # completely foolproof, but seems to work", "will be a PR and each value will be a", "+ re.findall(r'Backport PR #(\\d+):', log)): pr_branches[pr].append(branch) finally: os.chdir(STARTDIR) with open(f'pull_requests_branches_{NAME}.json',", "is a JSON file that contains for each pull request", "subprocess.call('git clean -fxd', shell=True) subprocess.call(f'git checkout {branch}', shell=True) if ORIGIN:", "tempfile from collections import defaultdict from astropy.utils.console import color_print from", "its the right thing color_print('\"{}\" directory already exists - assuming", "log) + re.findall(r'Backport PR #(\\d+):', log)): pr_branches[pr].append(branch) finally: os.chdir(STARTDIR) with", "\" in commit messages, so this is not # completely", "right thing color_print('\"{}\" directory already exists - assuming it is", "else: REPOSITORY_NAME = 'astropy/astropy' print(\"The repository this script currently works", "of all the PRs with open(f'merged_pull_requests_{NAME}.json') as merged: merged_prs =", "reset --hard', shell=True) subprocess.call('git clean -fxd', shell=True) subprocess.call(f'git checkout {branch}',", "pr_branches[pr].append(branch) finally: os.chdir(STARTDIR) with open(f'pull_requests_branches_{NAME}.json', 'w') as f: json.dump(pr_branches, f,", "else: subprocess.call(f'git clone {REPOSITORY}', shell=True) os.chdir(NAME) # Loop over branches", "import os import sys import json import re import subprocess", "are interested in BRANCHES = get_branches(REPOSITORY_NAME) # Read in a", "with open(f'merged_pull_requests_{NAME}.json') as merged: merged_prs = json.load(merged) # Set up", "subprocess.call(f'git fetch {ORIGIN}', shell=True) else: subprocess.call(f'git clone {REPOSITORY}', shell=True) os.chdir(NAME)", "be a PR and each value will be a list", "present pr_branches = defaultdict(list) try: # Set up repository color_print(f'Cloning", "-fxd', shell=True) subprocess.call(f'git checkout {branch}', shell=True) if ORIGIN: subprocess.call(f'git reset", "# Set up a dictionary where each key will be", "a dictionary where each key will be a PR and", "an already ' 'existing clone'.format(NAME), 'yellow') os.chdir(NAME) if ORIGIN: subprocess.call(f'git", "the right thing color_print('\"{}\" directory already exists - assuming it", "branches of the # given repository, and find which pull", "= sys.argv[1] else: REPOSITORY_NAME = 'astropy/astropy' print(\"The repository this script", "the log for pr in (re.findall(r'Merge pull request #(\\d+) ',", "commit messages, so this is not # completely foolproof, but", "each pull request the # list of all branches in", "is present pr_branches = defaultdict(list) try: # Set up repository", "#(\\d+):', log)): pr_branches[pr].append(branch) finally: os.chdir(STARTDIR) with open(f'pull_requests_branches_{NAME}.json', 'w') as f:", "the directory as-is. STARTDIR = os.path.abspath('.') # The branches we", "of branches in which the PR is present pr_branches =", "assume its the right thing color_print('\"{}\" directory already exists -", "up a dictionary where each key will be a PR", "'origin' # set this to None to not fetch anything", "REPOSITORY = f'git://github.com/{REPOSITORY_NAME}.git' NAME = os.path.basename(REPOSITORY_NAME) DIRTOCLONEIN = tempfile.mkdtemp() #", "for pr in (re.findall(r'Merge pull request #(\\d+) ', log) +", "sys.argv[1:]: REPOSITORY_NAME = sys.argv[1] else: REPOSITORY_NAME = 'astropy/astropy' print(\"The repository", "to a non-temp directory to retain the clone between runs", "be a list # of branches in which the PR", "# of branches in which the PR is present pr_branches", "interested in BRANCHES = get_branches(REPOSITORY_NAME) # Read in a list", "json import re import subprocess import tempfile from collections import", "are included in which # branches. The output is a", "but seems to work for now. import os import sys", "file that contains for each pull request the # list", "included. We look specifically for the # message \"Merge pull", "os.chdir(STARTDIR) with open(f'pull_requests_branches_{NAME}.json', 'w') as f: json.dump(pr_branches, f, sort_keys=True, indent=2)", "list of all the PRs with open(f'merged_pull_requests_{NAME}.json') as merged: merged_prs", "# The purpose of this script is to check all", "already ' 'existing clone'.format(NAME), 'yellow') os.chdir(NAME) if ORIGIN: subprocess.call(f'git fetch", "in the branch for branch in BRANCHES: # Change branch", "a JSON file that contains for each pull request the", "# Read in a list of all the PRs with", "already exists... assume its the right thing color_print('\"{}\" directory already", "this to None to not fetch anything but rather use", "'green') os.chdir(DIRTOCLONEIN) if os.path.isdir(NAME): # already exists... assume its the", "is not # completely foolproof, but seems to work for", "PR in the log for pr in (re.findall(r'Merge pull request", "request #xxxx \" in commit messages, so this is not", "a PR and each value will be a list #", "ORIGIN = 'origin' # set this to None to not", "to branch {branch}', 'green') subprocess.call('git reset --hard', shell=True) subprocess.call('git clean", "where each key will be a PR and each value", "if ORIGIN: subprocess.call(f'git fetch {ORIGIN}', shell=True) else: subprocess.call(f'git clone {REPOSITORY}',", "--hard', shell=True) subprocess.call('git clean -fxd', shell=True) subprocess.call(f'git checkout {branch}', shell=True)", "pull request the # list of all branches in which", "directory as-is. STARTDIR = os.path.abspath('.') # The branches we are", "= 'astropy/astropy' print(\"The repository this script currently works with is", "tempfile.mkdtemp() # set this to a non-temp directory to retain", "in which the PR is present pr_branches = defaultdict(list) try:", "# set this to None to not fetch anything but", "clone'.format(NAME), 'yellow') os.chdir(NAME) if ORIGIN: subprocess.call(f'git fetch {ORIGIN}', shell=True) else:", "fetch anything but rather use the directory as-is. STARTDIR =", "checkout {branch}', shell=True) if ORIGIN: subprocess.call(f'git reset --hard {ORIGIN}/{branch}', shell=True)", "if os.path.isdir(NAME): # already exists... assume its the right thing", "= tempfile.mkdtemp() # set this to a non-temp directory to", "# list of all branches in which it is included.", "all the PRs with open(f'merged_pull_requests_{NAME}.json') as merged: merged_prs = json.load(merged)", "# Set up repository color_print(f'Cloning {REPOSITORY}', 'green') os.chdir(DIRTOCLONEIN) if os.path.isdir(NAME):", "log)): pr_branches[pr].append(branch) finally: os.chdir(STARTDIR) with open(f'pull_requests_branches_{NAME}.json', 'w') as f: json.dump(pr_branches,", "log = subprocess.check_output('git log', shell=True).decode('utf-8') # Check for the presence", "ORIGIN: subprocess.call(f'git reset --hard {ORIGIN}/{branch}', shell=True) # Extract log: log", "branches in which it is included. We look specifically for", "fetch {ORIGIN}', shell=True) else: subprocess.call(f'git clone {REPOSITORY}', shell=True) os.chdir(NAME) #", "merged: merged_prs = json.load(merged) # Set up a dictionary where", "included in which # branches. The output is a JSON", "# completely foolproof, but seems to work for now. import", "'astropy/astropy' print(\"The repository this script currently works with is '{}'.\\n\"", "seems to work for now. import os import sys import", "The output is a JSON file that contains for each", "import defaultdict from astropy.utils.console import color_print from common import get_branches", "= get_branches(REPOSITORY_NAME) # Read in a list of all the", "get_branches if sys.argv[1:]: REPOSITORY_NAME = sys.argv[1] else: REPOSITORY_NAME = 'astropy/astropy'", "is included. We look specifically for the # message \"Merge", "use the directory as-is. STARTDIR = os.path.abspath('.') # The branches", "branch color_print(f'Switching to branch {branch}', 'green') subprocess.call('git reset --hard', shell=True)", "in the log for pr in (re.findall(r'Merge pull request #(\\d+)", "anything but rather use the directory as-is. STARTDIR = os.path.abspath('.')", "which pull requests are included in which # branches. The", "it is included. We look specifically for the # message", "set this to a non-temp directory to retain the clone", "directory to retain the clone between runs ORIGIN = 'origin'", "script is to check all the maintenance branches of the", "PRs in the branch for branch in BRANCHES: # Change", "we are interested in BRANCHES = get_branches(REPOSITORY_NAME) # Read in", "currently works with is '{}'.\\n\" .format(REPOSITORY_NAME)) REPOSITORY = f'git://github.com/{REPOSITORY_NAME}.git' NAME", "log', shell=True).decode('utf-8') # Check for the presence of the PR", "with is '{}'.\\n\" .format(REPOSITORY_NAME)) REPOSITORY = f'git://github.com/{REPOSITORY_NAME}.git' NAME = os.path.basename(REPOSITORY_NAME)", "in BRANCHES = get_branches(REPOSITORY_NAME) # Read in a list of", "json.load(merged) # Set up a dictionary where each key will", "to check all the maintenance branches of the # given", "import sys import json import re import subprocess import tempfile", "set this to None to not fetch anything but rather", "the PRs with open(f'merged_pull_requests_{NAME}.json') as merged: merged_prs = json.load(merged) #", "a list of all the PRs with open(f'merged_pull_requests_{NAME}.json') as merged:", "import get_branches if sys.argv[1:]: REPOSITORY_NAME = sys.argv[1] else: REPOSITORY_NAME =", "exists - assuming it is an already ' 'existing clone'.format(NAME),", "the presence of the PR in the log for pr", "# given repository, and find which pull requests are included", "BRANCHES: # Change branch color_print(f'Switching to branch {branch}', 'green') subprocess.call('git", "all PRs in the branch for branch in BRANCHES: #", "messages, so this is not # completely foolproof, but seems", "reset --hard {ORIGIN}/{branch}', shell=True) # Extract log: log = subprocess.check_output('git", "# branches. The output is a JSON file that contains", "from astropy.utils.console import color_print from common import get_branches if sys.argv[1:]:", "os.path.abspath('.') # The branches we are interested in BRANCHES =", "The branches we are interested in BRANCHES = get_branches(REPOSITORY_NAME) #", "for branch in BRANCHES: # Change branch color_print(f'Switching to branch", "script currently works with is '{}'.\\n\" .format(REPOSITORY_NAME)) REPOSITORY = f'git://github.com/{REPOSITORY_NAME}.git'", "os.chdir(NAME) # Loop over branches and find all PRs in", "the PR is present pr_branches = defaultdict(list) try: # Set", "each value will be a list # of branches in", "the maintenance branches of the # given repository, and find", "branches we are interested in BRANCHES = get_branches(REPOSITORY_NAME) # Read", "{ORIGIN}/{branch}', shell=True) # Extract log: log = subprocess.check_output('git log', shell=True).decode('utf-8')", "pr in (re.findall(r'Merge pull request #(\\d+) ', log) + re.findall(r'Backport", "color_print(f'Switching to branch {branch}', 'green') subprocess.call('git reset --hard', shell=True) subprocess.call('git", "\"Merge pull request #xxxx \" in commit messages, so this", "os.path.isdir(NAME): # already exists... assume its the right thing color_print('\"{}\"", "'green') subprocess.call('git reset --hard', shell=True) subprocess.call('git clean -fxd', shell=True) subprocess.call(f'git", "# message \"Merge pull request #xxxx \" in commit messages,", "will be a list # of branches in which the", "so this is not # completely foolproof, but seems to", ".format(REPOSITORY_NAME)) REPOSITORY = f'git://github.com/{REPOSITORY_NAME}.git' NAME = os.path.basename(REPOSITORY_NAME) DIRTOCLONEIN = tempfile.mkdtemp()", "the branch for branch in BRANCHES: # Change branch color_print(f'Switching", "in (re.findall(r'Merge pull request #(\\d+) ', log) + re.findall(r'Backport PR", "pull request #xxxx \" in commit messages, so this is", "'yellow') os.chdir(NAME) if ORIGIN: subprocess.call(f'git fetch {ORIGIN}', shell=True) else: subprocess.call(f'git", "of this script is to check all the maintenance branches", "clone {REPOSITORY}', shell=True) os.chdir(NAME) # Loop over branches and find", "of the PR in the log for pr in (re.findall(r'Merge", "# Extract log: log = subprocess.check_output('git log', shell=True).decode('utf-8') # Check", "the clone between runs ORIGIN = 'origin' # set this", "pull request #(\\d+) ', log) + re.findall(r'Backport PR #(\\d+):', log)):", "to None to not fetch anything but rather use the", "up repository color_print(f'Cloning {REPOSITORY}', 'green') os.chdir(DIRTOCLONEIN) if os.path.isdir(NAME): # already", "{ORIGIN}', shell=True) else: subprocess.call(f'git clone {REPOSITORY}', shell=True) os.chdir(NAME) # Loop", "os.path.basename(REPOSITORY_NAME) DIRTOCLONEIN = tempfile.mkdtemp() # set this to a non-temp", "which the PR is present pr_branches = defaultdict(list) try: #", "non-temp directory to retain the clone between runs ORIGIN =", "is '{}'.\\n\" .format(REPOSITORY_NAME)) REPOSITORY = f'git://github.com/{REPOSITORY_NAME}.git' NAME = os.path.basename(REPOSITORY_NAME) DIRTOCLONEIN", "exists... assume its the right thing color_print('\"{}\" directory already exists", "#xxxx \" in commit messages, so this is not #", "PR is present pr_branches = defaultdict(list) try: # Set up", "this script is to check all the maintenance branches of", "for now. import os import sys import json import re", "as merged: merged_prs = json.load(merged) # Set up a dictionary", "each key will be a PR and each value will", "color_print from common import get_branches if sys.argv[1:]: REPOSITORY_NAME = sys.argv[1]", "all the maintenance branches of the # given repository, and", "subprocess.call(f'git reset --hard {ORIGIN}/{branch}', shell=True) # Extract log: log =", "branch for branch in BRANCHES: # Change branch color_print(f'Switching to", "= defaultdict(list) try: # Set up repository color_print(f'Cloning {REPOSITORY}', 'green')", "request the # list of all branches in which it", "if ORIGIN: subprocess.call(f'git reset --hard {ORIGIN}/{branch}', shell=True) # Extract log:", "BRANCHES = get_branches(REPOSITORY_NAME) # Read in a list of all", "works with is '{}'.\\n\" .format(REPOSITORY_NAME)) REPOSITORY = f'git://github.com/{REPOSITORY_NAME}.git' NAME =", "merged_prs = json.load(merged) # Set up a dictionary where each", "', log) + re.findall(r'Backport PR #(\\d+):', log)): pr_branches[pr].append(branch) finally: os.chdir(STARTDIR)", "thing color_print('\"{}\" directory already exists - assuming it is an", "{branch}', shell=True) if ORIGIN: subprocess.call(f'git reset --hard {ORIGIN}/{branch}', shell=True) #", "= subprocess.check_output('git log', shell=True).decode('utf-8') # Check for the presence of", "(re.findall(r'Merge pull request #(\\d+) ', log) + re.findall(r'Backport PR #(\\d+):',", "the # message \"Merge pull request #xxxx \" in commit", "a list # of branches in which the PR is", "for the presence of the PR in the log for", "DIRTOCLONEIN = tempfile.mkdtemp() # set this to a non-temp directory", "{branch}', 'green') subprocess.call('git reset --hard', shell=True) subprocess.call('git clean -fxd', shell=True)", "{REPOSITORY}', 'green') os.chdir(DIRTOCLONEIN) if os.path.isdir(NAME): # already exists... assume its", "a non-temp directory to retain the clone between runs ORIGIN", "specifically for the # message \"Merge pull request #xxxx \"", "Read in a list of all the PRs with open(f'merged_pull_requests_{NAME}.json')", "list of all branches in which it is included. We", "that contains for each pull request the # list of", "shell=True) else: subprocess.call(f'git clone {REPOSITORY}', shell=True) os.chdir(NAME) # Loop over", "directory already exists - assuming it is an already '", "to work for now. import os import sys import json", "log: log = subprocess.check_output('git log', shell=True).decode('utf-8') # Check for the", "and each value will be a list # of branches", "find all PRs in the branch for branch in BRANCHES:", "shell=True) subprocess.call('git clean -fxd', shell=True) subprocess.call(f'git checkout {branch}', shell=True) if", "# The branches we are interested in BRANCHES = get_branches(REPOSITORY_NAME)", "output is a JSON file that contains for each pull", "{REPOSITORY}', shell=True) os.chdir(NAME) # Loop over branches and find all", "<reponame>adrn/astropy-tools # The purpose of this script is to check", "requests are included in which # branches. The output is", "re import subprocess import tempfile from collections import defaultdict from", "common import get_branches if sys.argv[1:]: REPOSITORY_NAME = sys.argv[1] else: REPOSITORY_NAME", "color_print('\"{}\" directory already exists - assuming it is an already", "runs ORIGIN = 'origin' # set this to None to", "defaultdict(list) try: # Set up repository color_print(f'Cloning {REPOSITORY}', 'green') os.chdir(DIRTOCLONEIN)", "but rather use the directory as-is. STARTDIR = os.path.abspath('.') #", "os.chdir(DIRTOCLONEIN) if os.path.isdir(NAME): # already exists... assume its the right", "in BRANCHES: # Change branch color_print(f'Switching to branch {branch}', 'green')", "finally: os.chdir(STARTDIR) with open(f'pull_requests_branches_{NAME}.json', 'w') as f: json.dump(pr_branches, f, sort_keys=True,", "given repository, and find which pull requests are included in", "pr_branches = defaultdict(list) try: # Set up repository color_print(f'Cloning {REPOSITORY}',", "REPOSITORY_NAME = sys.argv[1] else: REPOSITORY_NAME = 'astropy/astropy' print(\"The repository this", "- assuming it is an already ' 'existing clone'.format(NAME), 'yellow')", "repository this script currently works with is '{}'.\\n\" .format(REPOSITORY_NAME)) REPOSITORY", "in which # branches. The output is a JSON file", "all branches in which it is included. We look specifically", "We look specifically for the # message \"Merge pull request", "presence of the PR in the log for pr in", "as-is. STARTDIR = os.path.abspath('.') # The branches we are interested", "subprocess.call('git reset --hard', shell=True) subprocess.call('git clean -fxd', shell=True) subprocess.call(f'git checkout", "Extract log: log = subprocess.check_output('git log', shell=True).decode('utf-8') # Check for", "sys import json import re import subprocess import tempfile from", "for each pull request the # list of all branches", "re.findall(r'Backport PR #(\\d+):', log)): pr_branches[pr].append(branch) finally: os.chdir(STARTDIR) with open(f'pull_requests_branches_{NAME}.json', 'w')", "key will be a PR and each value will be", "#(\\d+) ', log) + re.findall(r'Backport PR #(\\d+):', log)): pr_branches[pr].append(branch) finally:", "is to check all the maintenance branches of the #", "not fetch anything but rather use the directory as-is. STARTDIR", "is an already ' 'existing clone'.format(NAME), 'yellow') os.chdir(NAME) if ORIGIN:", "purpose of this script is to check all the maintenance", "and find which pull requests are included in which #", "REPOSITORY_NAME = 'astropy/astropy' print(\"The repository this script currently works with", "ORIGIN: subprocess.call(f'git fetch {ORIGIN}', shell=True) else: subprocess.call(f'git clone {REPOSITORY}', shell=True)", "this to a non-temp directory to retain the clone between", "--hard {ORIGIN}/{branch}', shell=True) # Extract log: log = subprocess.check_output('git log',", "The purpose of this script is to check all the", "shell=True).decode('utf-8') # Check for the presence of the PR in", "completely foolproof, but seems to work for now. import os", "# already exists... assume its the right thing color_print('\"{}\" directory", "branches in which the PR is present pr_branches = defaultdict(list)", "STARTDIR = os.path.abspath('.') # The branches we are interested in", "# set this to a non-temp directory to retain the", "astropy.utils.console import color_print from common import get_branches if sys.argv[1:]: REPOSITORY_NAME", "log for pr in (re.findall(r'Merge pull request #(\\d+) ', log)", "# Change branch color_print(f'Switching to branch {branch}', 'green') subprocess.call('git reset", "= os.path.basename(REPOSITORY_NAME) DIRTOCLONEIN = tempfile.mkdtemp() # set this to a", "subprocess.call(f'git checkout {branch}', shell=True) if ORIGIN: subprocess.call(f'git reset --hard {ORIGIN}/{branch}',", "color_print(f'Cloning {REPOSITORY}', 'green') os.chdir(DIRTOCLONEIN) if os.path.isdir(NAME): # already exists... assume", "from collections import defaultdict from astropy.utils.console import color_print from common", "None to not fetch anything but rather use the directory", "from common import get_branches if sys.argv[1:]: REPOSITORY_NAME = sys.argv[1] else:", "find which pull requests are included in which # branches.", "branches. The output is a JSON file that contains for", "import re import subprocess import tempfile from collections import defaultdict", "check all the maintenance branches of the # given repository,", "this script currently works with is '{}'.\\n\" .format(REPOSITORY_NAME)) REPOSITORY =", "' 'existing clone'.format(NAME), 'yellow') os.chdir(NAME) if ORIGIN: subprocess.call(f'git fetch {ORIGIN}',", "now. import os import sys import json import re import", "'{}'.\\n\" .format(REPOSITORY_NAME)) REPOSITORY = f'git://github.com/{REPOSITORY_NAME}.git' NAME = os.path.basename(REPOSITORY_NAME) DIRTOCLONEIN =", "# Loop over branches and find all PRs in the", "maintenance branches of the # given repository, and find which", "clean -fxd', shell=True) subprocess.call(f'git checkout {branch}', shell=True) if ORIGIN: subprocess.call(f'git", "os import sys import json import re import subprocess import", "of all branches in which it is included. We look", "import color_print from common import get_branches if sys.argv[1:]: REPOSITORY_NAME =", "repository, and find which pull requests are included in which", "shell=True) if ORIGIN: subprocess.call(f'git reset --hard {ORIGIN}/{branch}', shell=True) # Extract", "open(f'merged_pull_requests_{NAME}.json') as merged: merged_prs = json.load(merged) # Set up a", "for the # message \"Merge pull request #xxxx \" in", "rather use the directory as-is. STARTDIR = os.path.abspath('.') # The", "NAME = os.path.basename(REPOSITORY_NAME) DIRTOCLONEIN = tempfile.mkdtemp() # set this to", "which # branches. The output is a JSON file that", "which it is included. We look specifically for the #", "defaultdict from astropy.utils.console import color_print from common import get_branches if", "branch in BRANCHES: # Change branch color_print(f'Switching to branch {branch}',", "foolproof, but seems to work for now. import os import", "= os.path.abspath('.') # The branches we are interested in BRANCHES", "PRs with open(f'merged_pull_requests_{NAME}.json') as merged: merged_prs = json.load(merged) # Set", "between runs ORIGIN = 'origin' # set this to None", "value will be a list # of branches in which", "to retain the clone between runs ORIGIN = 'origin' #", "already exists - assuming it is an already ' 'existing", "# Check for the presence of the PR in the", "import subprocess import tempfile from collections import defaultdict from astropy.utils.console", "of the # given repository, and find which pull requests", "import tempfile from collections import defaultdict from astropy.utils.console import color_print", "clone between runs ORIGIN = 'origin' # set this to", "and find all PRs in the branch for branch in", "branch {branch}', 'green') subprocess.call('git reset --hard', shell=True) subprocess.call('git clean -fxd',", "Set up a dictionary where each key will be a", "'existing clone'.format(NAME), 'yellow') os.chdir(NAME) if ORIGIN: subprocess.call(f'git fetch {ORIGIN}', shell=True)", "subprocess import tempfile from collections import defaultdict from astropy.utils.console import", "assuming it is an already ' 'existing clone'.format(NAME), 'yellow') os.chdir(NAME)", "the # given repository, and find which pull requests are", "the PR in the log for pr in (re.findall(r'Merge pull", "to not fetch anything but rather use the directory as-is.", "the # list of all branches in which it is" ]
[ "import os import numpy as np import settings def mkdir():", "import numpy as np import settings def mkdir(): now =", "os import numpy as np import settings def mkdir(): now", "mkdir(): now = dt.now().replace(second=0, microsecond=0) name_dir = \"q_agent_train_\" + now.strftime(\"%Y-%m-%d_%H:%M:%S\")", "datetime import datetime as dt import os import numpy as", "except FileExistsError: name_dir += \"_2\" path = os.path.join(settings.MODELS_DIR, name_dir) os.mkdir(path)", "import settings def mkdir(): now = dt.now().replace(second=0, microsecond=0) name_dir =", "name_dir) os.mkdir(path) return path def save_model(q_table: str, directory: str, file_name:", "= os.path.join(settings.MODELS_DIR, name_dir) try: os.mkdir(path) except FileExistsError: name_dir += \"_2\"", "try: os.mkdir(path) except FileExistsError: name_dir += \"_2\" path = os.path.join(settings.MODELS_DIR,", "as np import settings def mkdir(): now = dt.now().replace(second=0, microsecond=0)", "now = dt.now().replace(second=0, microsecond=0) name_dir = \"q_agent_train_\" + now.strftime(\"%Y-%m-%d_%H:%M:%S\") path", "str, directory: str, file_name: str): file_path = os.path.join(directory, file_name) np.save(file_path,", "= os.path.join(settings.MODELS_DIR, name_dir) os.mkdir(path) return path def save_model(q_table: str, directory:", "save_model(q_table: str, directory: str, file_name: str): file_path = os.path.join(directory, file_name)", "name_dir = \"q_agent_train_\" + now.strftime(\"%Y-%m-%d_%H:%M:%S\") path = os.path.join(settings.MODELS_DIR, name_dir) try:", "dt.now().replace(second=0, microsecond=0) name_dir = \"q_agent_train_\" + now.strftime(\"%Y-%m-%d_%H:%M:%S\") path = os.path.join(settings.MODELS_DIR,", "path def save_model(q_table: str, directory: str, file_name: str): file_path =", "+ now.strftime(\"%Y-%m-%d_%H:%M:%S\") path = os.path.join(settings.MODELS_DIR, name_dir) try: os.mkdir(path) except FileExistsError:", "\"_2\" path = os.path.join(settings.MODELS_DIR, name_dir) os.mkdir(path) return path def save_model(q_table:", "microsecond=0) name_dir = \"q_agent_train_\" + now.strftime(\"%Y-%m-%d_%H:%M:%S\") path = os.path.join(settings.MODELS_DIR, name_dir)", "os.path.join(settings.MODELS_DIR, name_dir) os.mkdir(path) return path def save_model(q_table: str, directory: str,", "<reponame>pedMatias/matias_hfo from datetime import datetime as dt import os import", "settings def mkdir(): now = dt.now().replace(second=0, microsecond=0) name_dir = \"q_agent_train_\"", "= \"q_agent_train_\" + now.strftime(\"%Y-%m-%d_%H:%M:%S\") path = os.path.join(settings.MODELS_DIR, name_dir) try: os.mkdir(path)", "import datetime as dt import os import numpy as np", "path = os.path.join(settings.MODELS_DIR, name_dir) os.mkdir(path) return path def save_model(q_table: str,", "dt import os import numpy as np import settings def", "path = os.path.join(settings.MODELS_DIR, name_dir) try: os.mkdir(path) except FileExistsError: name_dir +=", "\"q_agent_train_\" + now.strftime(\"%Y-%m-%d_%H:%M:%S\") path = os.path.join(settings.MODELS_DIR, name_dir) try: os.mkdir(path) except", "as dt import os import numpy as np import settings", "os.mkdir(path) return path def save_model(q_table: str, directory: str, file_name: str):", "return path def save_model(q_table: str, directory: str, file_name: str): file_path", "FileExistsError: name_dir += \"_2\" path = os.path.join(settings.MODELS_DIR, name_dir) os.mkdir(path) return", "datetime as dt import os import numpy as np import", "def mkdir(): now = dt.now().replace(second=0, microsecond=0) name_dir = \"q_agent_train_\" +", "from datetime import datetime as dt import os import numpy", "+= \"_2\" path = os.path.join(settings.MODELS_DIR, name_dir) os.mkdir(path) return path def", "os.path.join(settings.MODELS_DIR, name_dir) try: os.mkdir(path) except FileExistsError: name_dir += \"_2\" path", "name_dir) try: os.mkdir(path) except FileExistsError: name_dir += \"_2\" path =", "def save_model(q_table: str, directory: str, file_name: str): file_path = os.path.join(directory,", "os.mkdir(path) except FileExistsError: name_dir += \"_2\" path = os.path.join(settings.MODELS_DIR, name_dir)", "name_dir += \"_2\" path = os.path.join(settings.MODELS_DIR, name_dir) os.mkdir(path) return path", "numpy as np import settings def mkdir(): now = dt.now().replace(second=0,", "np import settings def mkdir(): now = dt.now().replace(second=0, microsecond=0) name_dir", "now.strftime(\"%Y-%m-%d_%H:%M:%S\") path = os.path.join(settings.MODELS_DIR, name_dir) try: os.mkdir(path) except FileExistsError: name_dir", "= dt.now().replace(second=0, microsecond=0) name_dir = \"q_agent_train_\" + now.strftime(\"%Y-%m-%d_%H:%M:%S\") path =", "directory: str, file_name: str): file_path = os.path.join(directory, file_name) np.save(file_path, q_table)" ]
[ "version of Qt libraries when there is installed another application", "there is installed another application (e.g. QtCreator) if is_win: from", "Qt libraries when there is installed another application (e.g. QtCreator)", "to point to the PyQt4 directory. # The PySide directory", "with exception for distributing the bootloader. # # The full", "under the terms of the GNU General Public License (version", "On Windows system PATH has to be extended to point", "# SPDX-License-Identifier: (GPL-2.0-or-later WITH Bootloader-exception) #----------------------------------------------------------------------------- import os from PyInstaller.utils.hooks", "of the GNU General Public License (version 2 # or", "# or later) with exception for distributing the bootloader. #", "QtCreator) if is_win: from PyInstaller.utils.win32.winutils import extend_system_path extend_system_path([os.path.join(x, 'PyQt4') for", "Mac OS X it is necessary to include directory qt_menu.nib.", "Windows system PATH has to be extended to point to", "getsitepackages, is_darwin, is_win # On Windows system PATH has to", "has to be extended to point to the PyQt4 directory.", "need to avoid including different # version of Qt libraries", "this software. # # SPDX-License-Identifier: (GPL-2.0-or-later WITH Bootloader-exception) #----------------------------------------------------------------------------- import", "WITH Bootloader-exception) #----------------------------------------------------------------------------- import os from PyInstaller.utils.hooks import qt_menu_nib_dir from", "import extend_system_path extend_system_path([os.path.join(x, 'PyQt4') for x in getsitepackages()]) hiddenimports =", "os from PyInstaller.utils.hooks import qt_menu_nib_dir from PyInstaller.compat import getsitepackages, is_darwin,", "PATH has to be extended to point to the PyQt4", "if is_win: from PyInstaller.utils.win32.winutils import extend_system_path extend_system_path([os.path.join(x, 'PyQt4') for x", "2 # or later) with exception for distributing the bootloader.", "system PATH has to be extended to point to the", "directory. # The PySide directory contains Qt dlls. We need", "in getsitepackages()]) hiddenimports = ['sip'] # For Qt to work", "PyQt or PySide # app. if is_darwin: datas = [", "PyInstaller.utils.hooks import qt_menu_nib_dir from PyInstaller.compat import getsitepackages, is_darwin, is_win #", "or PySide # app. if is_darwin: datas = [ (qt_menu_nib_dir('PyQt4'),", "for distributing the bootloader. # # The full license is", "import getsitepackages, is_darwin, is_win # On Windows system PATH has", "Distributed under the terms of the GNU General Public License", "License (version 2 # or later) with exception for distributing", "the PyQt4 directory. # The PySide directory contains Qt dlls.", "#----------------------------------------------------------------------------- # Copyright (c) 2013-2020, PyInstaller Development Team. # #", "PyInstaller Development Team. # # Distributed under the terms of", "General Public License (version 2 # or later) with exception", "some resource files necessary to run PyQt or PySide #", "is necessary to include directory qt_menu.nib. # This directory contains", "extended to point to the PyQt4 directory. # The PySide", "#----------------------------------------------------------------------------- import os from PyInstaller.utils.hooks import qt_menu_nib_dir from PyInstaller.compat import", "# version of Qt libraries when there is installed another", "is_win # On Windows system PATH has to be extended", "# # The full license is in the file COPYING.txt,", "when there is installed another application (e.g. QtCreator) if is_win:", "For Qt to work on Mac OS X it is", "<filename>Python38/Lib/site-packages/PyInstaller/hooks/hook-PyQt4.py #----------------------------------------------------------------------------- # Copyright (c) 2013-2020, PyInstaller Development Team. #", "to run PyQt or PySide # app. if is_darwin: datas", "point to the PyQt4 directory. # The PySide directory contains", "Development Team. # # Distributed under the terms of the", "in the file COPYING.txt, distributed with this software. # #", "work on Mac OS X it is necessary to include", "it is necessary to include directory qt_menu.nib. # This directory", "distributing the bootloader. # # The full license is in", "avoid including different # version of Qt libraries when there", "extend_system_path([os.path.join(x, 'PyQt4') for x in getsitepackages()]) hiddenimports = ['sip'] #", "hiddenimports = ['sip'] # For Qt to work on Mac", "to include directory qt_menu.nib. # This directory contains some resource", "This directory contains some resource files necessary to run PyQt", "the bootloader. # # The full license is in the", "# The full license is in the file COPYING.txt, distributed", "file COPYING.txt, distributed with this software. # # SPDX-License-Identifier: (GPL-2.0-or-later", "extend_system_path extend_system_path([os.path.join(x, 'PyQt4') for x in getsitepackages()]) hiddenimports = ['sip']", "SPDX-License-Identifier: (GPL-2.0-or-later WITH Bootloader-exception) #----------------------------------------------------------------------------- import os from PyInstaller.utils.hooks import", "terms of the GNU General Public License (version 2 #", "to avoid including different # version of Qt libraries when", "directory contains Qt dlls. We need to avoid including different", "import qt_menu_nib_dir from PyInstaller.compat import getsitepackages, is_darwin, is_win # On", "X it is necessary to include directory qt_menu.nib. # This", "from PyInstaller.utils.hooks import qt_menu_nib_dir from PyInstaller.compat import getsitepackages, is_darwin, is_win", "PyInstaller.utils.win32.winutils import extend_system_path extend_system_path([os.path.join(x, 'PyQt4') for x in getsitepackages()]) hiddenimports", "GNU General Public License (version 2 # or later) with", "Bootloader-exception) #----------------------------------------------------------------------------- import os from PyInstaller.utils.hooks import qt_menu_nib_dir from PyInstaller.compat", "Public License (version 2 # or later) with exception for", "distributed with this software. # # SPDX-License-Identifier: (GPL-2.0-or-later WITH Bootloader-exception)", "is in the file COPYING.txt, distributed with this software. #", "from PyInstaller.compat import getsitepackages, is_darwin, is_win # On Windows system", "the GNU General Public License (version 2 # or later)", "another application (e.g. QtCreator) if is_win: from PyInstaller.utils.win32.winutils import extend_system_path", "# # SPDX-License-Identifier: (GPL-2.0-or-later WITH Bootloader-exception) #----------------------------------------------------------------------------- import os from", "The full license is in the file COPYING.txt, distributed with", "software. # # SPDX-License-Identifier: (GPL-2.0-or-later WITH Bootloader-exception) #----------------------------------------------------------------------------- import os", "# On Windows system PATH has to be extended to", "application (e.g. QtCreator) if is_win: from PyInstaller.utils.win32.winutils import extend_system_path extend_system_path([os.path.join(x,", "later) with exception for distributing the bootloader. # # The", "OS X it is necessary to include directory qt_menu.nib. #", "# The PySide directory contains Qt dlls. We need to", "directory contains some resource files necessary to run PyQt or", "import os from PyInstaller.utils.hooks import qt_menu_nib_dir from PyInstaller.compat import getsitepackages,", "['sip'] # For Qt to work on Mac OS X", "of Qt libraries when there is installed another application (e.g.", "resource files necessary to run PyQt or PySide # app.", "Qt to work on Mac OS X it is necessary", "exception for distributing the bootloader. # # The full license", "(GPL-2.0-or-later WITH Bootloader-exception) #----------------------------------------------------------------------------- import os from PyInstaller.utils.hooks import qt_menu_nib_dir", "be extended to point to the PyQt4 directory. # The", "contains Qt dlls. We need to avoid including different #", "PyQt4 directory. # The PySide directory contains Qt dlls. We", "(e.g. QtCreator) if is_win: from PyInstaller.utils.win32.winutils import extend_system_path extend_system_path([os.path.join(x, 'PyQt4')", "is_darwin, is_win # On Windows system PATH has to be", "include directory qt_menu.nib. # This directory contains some resource files", "The PySide directory contains Qt dlls. We need to avoid", "# For Qt to work on Mac OS X it", "to work on Mac OS X it is necessary to", "# Copyright (c) 2013-2020, PyInstaller Development Team. # # Distributed", "qt_menu.nib. # This directory contains some resource files necessary to", "dlls. We need to avoid including different # version of", "contains some resource files necessary to run PyQt or PySide", "different # version of Qt libraries when there is installed", "bootloader. # # The full license is in the file", "to be extended to point to the PyQt4 directory. #", "is_win: from PyInstaller.utils.win32.winutils import extend_system_path extend_system_path([os.path.join(x, 'PyQt4') for x in", "x in getsitepackages()]) hiddenimports = ['sip'] # For Qt to", "Copyright (c) 2013-2020, PyInstaller Development Team. # # Distributed under", "or later) with exception for distributing the bootloader. # #", "run PyQt or PySide # app. if is_darwin: datas =", "(c) 2013-2020, PyInstaller Development Team. # # Distributed under the", "2013-2020, PyInstaller Development Team. # # Distributed under the terms", "necessary to run PyQt or PySide # app. if is_darwin:", "PySide directory contains Qt dlls. We need to avoid including", "license is in the file COPYING.txt, distributed with this software.", "on Mac OS X it is necessary to include directory", "# Distributed under the terms of the GNU General Public", "COPYING.txt, distributed with this software. # # SPDX-License-Identifier: (GPL-2.0-or-later WITH", "for x in getsitepackages()]) hiddenimports = ['sip'] # For Qt", "necessary to include directory qt_menu.nib. # This directory contains some", "files necessary to run PyQt or PySide # app. if", "is installed another application (e.g. QtCreator) if is_win: from PyInstaller.utils.win32.winutils", "with this software. # # SPDX-License-Identifier: (GPL-2.0-or-later WITH Bootloader-exception) #-----------------------------------------------------------------------------", "the file COPYING.txt, distributed with this software. # # SPDX-License-Identifier:", "Team. # # Distributed under the terms of the GNU", "qt_menu_nib_dir from PyInstaller.compat import getsitepackages, is_darwin, is_win # On Windows", "# # Distributed under the terms of the GNU General", "We need to avoid including different # version of Qt", "# app. if is_darwin: datas = [ (qt_menu_nib_dir('PyQt4'), 'qt_menu.nib'), ]", "libraries when there is installed another application (e.g. QtCreator) if", "= ['sip'] # For Qt to work on Mac OS", "installed another application (e.g. QtCreator) if is_win: from PyInstaller.utils.win32.winutils import", "Qt dlls. We need to avoid including different # version", "directory qt_menu.nib. # This directory contains some resource files necessary", "(version 2 # or later) with exception for distributing the", "including different # version of Qt libraries when there is", "getsitepackages()]) hiddenimports = ['sip'] # For Qt to work on", "'PyQt4') for x in getsitepackages()]) hiddenimports = ['sip'] # For", "from PyInstaller.utils.win32.winutils import extend_system_path extend_system_path([os.path.join(x, 'PyQt4') for x in getsitepackages()])", "PyInstaller.compat import getsitepackages, is_darwin, is_win # On Windows system PATH", "PySide # app. if is_darwin: datas = [ (qt_menu_nib_dir('PyQt4'), 'qt_menu.nib'),", "# This directory contains some resource files necessary to run", "full license is in the file COPYING.txt, distributed with this", "the terms of the GNU General Public License (version 2", "to the PyQt4 directory. # The PySide directory contains Qt" ]
[ "k: v.default for k, v in signature.parameters.items() if v.default is", "v.default for k, v in signature.parameters.items() if v.default is not", "default arguments of a function. \"\"\" signature = inspect.signature(func) return", "a function. \"\"\" signature = inspect.signature(func) return { k: v.default", "\"\"\" signature = inspect.signature(func) return { k: v.default for k,", "of a function. \"\"\" signature = inspect.signature(func) return { k:", "get_default_args(func): \"\"\"Get default arguments of a function. \"\"\" signature =", "\"\"\"Get default arguments of a function. \"\"\" signature = inspect.signature(func)", "k, v in signature.parameters.items() if v.default is not inspect.Parameter.empty }", "def get_default_args(func): \"\"\"Get default arguments of a function. \"\"\" signature", "return { k: v.default for k, v in signature.parameters.items() if", "signature = inspect.signature(func) return { k: v.default for k, v", "for k, v in signature.parameters.items() if v.default is not inspect.Parameter.empty", "inspect def get_default_args(func): \"\"\"Get default arguments of a function. \"\"\"", "function. \"\"\" signature = inspect.signature(func) return { k: v.default for", "inspect.signature(func) return { k: v.default for k, v in signature.parameters.items()", "= inspect.signature(func) return { k: v.default for k, v in", "{ k: v.default for k, v in signature.parameters.items() if v.default", "import inspect def get_default_args(func): \"\"\"Get default arguments of a function.", "arguments of a function. \"\"\" signature = inspect.signature(func) return {" ]
[ "lambda x1, x2, ..., xn: <expressão> print(hello()) print(uma(6)) print(duas(5, 7))", "1 / 7 + 1 / z) # n =", "' + sobrenome.strip().title() print(nome_compelto(' paulo', ' SILVA ')) print(nome_compelto(' MARIA", "passarmos mais argumentos do que parâmetros esperados teremos TypeError #", "x + c teste = geradora_funcao_quadratica(2, 3, -5) print(teste(0)) print(teste(1))", "# '<NAME>', 'In<NAME>', '<NAME>', '<NAME>', '<NAME>'] # Ordenar pelo sobrenome", "+ b * x + c # Definindo a função", "duas = lambda x, y: (x * y) ** 0.5", "ou seja, funções anónimas. # Função em Python def funcao(x):", "b * x + c \"\"\" return lambda x: a", "c teste = geradora_funcao_quadratica(2, 3, -5) print(teste(0)) print(teste(1)) print(teste(2)) print(geradora_funcao_quadratica(3,", "(1 / x + 1 / 7 + 1 /", "* x + 1 # Como utlizar a expressão lambda?", "x: 3 * x + 1 print(calc(4)) print(calc(7)) # Podemos", "y, z: 3 / (1 / x + 1 /", "'<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>'] print(autores) # ['<NAME>',", "= lambda x: 3 * x + 1 duas =", "# '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>'] \"\"\" # Função Quadrática", "= lambda nome, sobrenome: nome.strip().title() + ' ' + sobrenome.strip().title()", "entradas. Em Lambdas também hello = lambda: 'Hello World!' uma", "# Função Quadrática # f(x) = a * x **", "# ['<NAME>', '<NAME>', '<NAME>', '<NAME>', # '<NAME>', 'In<NAME>', '<NAME>', '<NAME>',", "def geradora_funcao_quadratica(a, b, c): \"\"\" Retorna a função f(x) =", "+ b * x + c \"\"\" return lambda x:", "<expressão> print(hello()) print(uma(6)) print(duas(5, 7)) print(tres(3, 6, 9)) # OBS:", "print(autores) # ['<NAME>', '<NAME>', 'In<NAME>', '<NAME>', # '<NAME>', '<NAME>', '<NAME>',", "+ 1 # Como utlizar a expressão lambda? calc =", "Expressão Lambda lambda x: 3 * x + 1 #", "Expressões Lambdas, ou simplesmente Lambdas, são funções sem nome, ou", "** 2 + b * x + c # Definindo", "lambda x: 3 * x + 1 # Como utlizar", "nenhuma ou várias entradas. Em Lambdas também hello = lambda:", "c # Definindo a função def geradora_funcao_quadratica(a, b, c): \"\"\"", "Utilizando Lambdas Conhecidas por Expressões Lambdas, ou simplesmente Lambdas, são", "')) # Em funções Python podemos ter nenhuma ou várias", "lambda x: 3 * x + 1 duas = lambda", "lambda x: a * x ** 2 + b *", "b, c): \"\"\" Retorna a função f(x) = a *", "a * x ** 2 + b * x +", "+ 1 duas = lambda x, y: (x * y)", "podemos ter nenhuma ou várias entradas. Em Lambdas também hello", "def funcao(x): return 3 * x + 1 print(funcao(4)) print(funcao(7))", "'<NAME>', '<NAME>', '<NAME>'] \"\"\" # Função Quadrática # f(x) =", "\"\"\" return lambda x: a * x ** 2 +", "x + 1 print(funcao(4)) print(funcao(7)) # Expressão Lambda lambda x:", "funcao(x): return 3 * x + 1 print(funcao(4)) print(funcao(7)) #", "calc = lambda x: 3 * x + 1 print(calc(4))", "\"\"\" Retorna a função f(x) = a * x **", "uma = lambda x: 3 * x + 1 duas", "entradas nome_compelto = lambda nome, sobrenome: nome.strip().title() + ' '", "mais argumentos do que parâmetros esperados teremos TypeError # Exemplo", "autores = ['<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>',", "'<NAME>'] print(autores) # ['<NAME>', '<NAME>', '<NAME>', '<NAME>', # '<NAME>', 'In<NAME>',", "World!' uma = lambda x: 3 * x + 1", "Ordenar pelo sobrenome autores.sort(key=lambda sobrenome: sobrenome.split(' ')[-1].lower()) print(autores) # ['<NAME>',", "geradora_funcao_quadratica(a, b, c): \"\"\" Retorna a função f(x) = a", "return 3 * x + 1 print(funcao(4)) print(funcao(7)) # Expressão", "3 * x + 1 # Como utlizar a expressão", "múltiplas entradas nome_compelto = lambda nome, sobrenome: nome.strip().title() + '", "Em Lambdas também hello = lambda: 'Hello World!' uma =", "print(hello()) print(uma(6)) print(duas(5, 7)) print(tres(3, 6, 9)) # OBS: Se", "Lambda lambda x: 3 * x + 1 # Como", "x, y, z: 3 / (1 / x + 1", "OBS: Se passarmos mais argumentos do que parâmetros esperados teremos", "c): \"\"\" Retorna a função f(x) = a * x", "ou simplesmente Lambdas, são funções sem nome, ou seja, funções", "paulo', ' SILVA ')) print(nome_compelto(' MARIA ', ' albertina '))", "sobrenome: sobrenome.split(' ')[-1].lower()) print(autores) # ['<NAME>', '<NAME>', 'In<NAME>', '<NAME>', #", "'<NAME>', '<NAME>', '<NAME>'] print(autores) # ['<NAME>', '<NAME>', '<NAME>', '<NAME>', #", "Função em Python def funcao(x): return 3 * x +", "b * x + c # Definindo a função def", "também hello = lambda: 'Hello World!' uma = lambda x:", "1 # Como utlizar a expressão lambda? calc = lambda", "+ 1 / z) # n = lambda x1, x2,", "do que parâmetros esperados teremos TypeError # Exemplo autores =", "+ 1 print(funcao(4)) print(funcao(7)) # Expressão Lambda lambda x: 3", "'<NAME>', '<NAME>'] # Ordenar pelo sobrenome autores.sort(key=lambda sobrenome: sobrenome.split(' ')[-1].lower())", "print(duas(5, 7)) print(tres(3, 6, 9)) # OBS: Se passarmos mais", "# Definindo a função def geradora_funcao_quadratica(a, b, c): \"\"\" Retorna", "a expressão lambda? calc = lambda x: 3 * x", "* y) ** 0.5 tres = lambda x, y, z:", "Definindo a função def geradora_funcao_quadratica(a, b, c): \"\"\" Retorna a", "+ b * x + c teste = geradora_funcao_quadratica(2, 3,", "9)) # OBS: Se passarmos mais argumentos do que parâmetros", "lambda nome, sobrenome: nome.strip().title() + ' ' + sobrenome.strip().title() print(nome_compelto('", "funções sem nome, ou seja, funções anónimas. # Função em", "Lambdas Conhecidas por Expressões Lambdas, ou simplesmente Lambdas, são funções", "'<NAME>', 'In<NAME>', '<NAME>', # '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>'] \"\"\"", "em Python def funcao(x): return 3 * x + 1", "# ['<NAME>', '<NAME>', 'In<NAME>', '<NAME>', # '<NAME>', '<NAME>', '<NAME>', '<NAME>',", "b * x + c teste = geradora_funcao_quadratica(2, 3, -5)", "print(calc(7)) # Podemos ter expressões lambdas com múltiplas entradas nome_compelto", "* x + 1 duas = lambda x, y: (x", "3 / (1 / x + 1 / 7 +", "'<NAME>', 'In<NAME>', '<NAME>', '<NAME>', '<NAME>'] # Ordenar pelo sobrenome autores.sort(key=lambda", "3 * x + 1 print(funcao(4)) print(funcao(7)) # Expressão Lambda", "* x ** 2 + b * x + c", "n = lambda x1, x2, ..., xn: <expressão> print(hello()) print(uma(6))", "# Expressão Lambda lambda x: 3 * x + 1", "# Como utlizar a expressão lambda? calc = lambda x:", "Como utlizar a expressão lambda? calc = lambda x: 3", "TypeError # Exemplo autores = ['<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>',", "Em funções Python podemos ter nenhuma ou várias entradas. Em", "x ** 2 + b * x + c teste", "z: 3 / (1 / x + 1 / 7", "ter nenhuma ou várias entradas. Em Lambdas também hello =", "'Hello World!' uma = lambda x: 3 * x +", "print(uma(6)) print(duas(5, 7)) print(tres(3, 6, 9)) # OBS: Se passarmos", "'<NAME>', '<NAME>', '<NAME>', '<NAME>'] \"\"\" # Função Quadrática # f(x)", "Python podemos ter nenhuma ou várias entradas. Em Lambdas também", "'<NAME>', '<NAME>', '<NAME>', '<NAME>'] print(autores) # ['<NAME>', '<NAME>', '<NAME>', '<NAME>',", "= lambda x: 3 * x + 1 print(calc(4)) print(calc(7))", "que parâmetros esperados teremos TypeError # Exemplo autores = ['<NAME>',", "print(autores) # ['<NAME>', '<NAME>', '<NAME>', '<NAME>', # '<NAME>', 'In<NAME>', '<NAME>',", "a função f(x) = a * x ** 2 +", "x + 1 print(calc(4)) print(calc(7)) # Podemos ter expressões lambdas", "1 duas = lambda x, y: (x * y) **", "'<NAME>', # '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>'] \"\"\" # Função", "' ' + sobrenome.strip().title() print(nome_compelto(' paulo', ' SILVA ')) print(nome_compelto('", "funções anónimas. # Função em Python def funcao(x): return 3", "sobrenome: nome.strip().title() + ' ' + sobrenome.strip().title() print(nome_compelto(' paulo', '", "SILVA ')) print(nome_compelto(' MARIA ', ' albertina ')) # Em", "'<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>'] \"\"\" # Função Quadrática #", "x1, x2, ..., xn: <expressão> print(hello()) print(uma(6)) print(duas(5, 7)) print(tres(3,", "= lambda x, y, z: 3 / (1 / x", "/ z) # n = lambda x1, x2, ..., xn:", "lambda x, y: (x * y) ** 0.5 tres =", "'<NAME>', '<NAME>'] print(autores) # ['<NAME>', '<NAME>', '<NAME>', '<NAME>', # '<NAME>',", "['<NAME>', '<NAME>', 'In<NAME>', '<NAME>', # '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>']", "Retorna a função f(x) = a * x ** 2", "c \"\"\" return lambda x: a * x ** 2", "f(x) = a * x ** 2 + b *", "# Exemplo autores = ['<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>',", "lambda? calc = lambda x: 3 * x + 1", "MARIA ', ' albertina ')) # Em funções Python podemos", "utlizar a expressão lambda? calc = lambda x: 3 *", "autores.sort(key=lambda sobrenome: sobrenome.split(' ')[-1].lower()) print(autores) # ['<NAME>', '<NAME>', 'In<NAME>', '<NAME>',", "Lambdas, ou simplesmente Lambdas, são funções sem nome, ou seja,", "6, 9)) # OBS: Se passarmos mais argumentos do que", "* x + c \"\"\" return lambda x: a *", "print(tres(3, 6, 9)) # OBS: Se passarmos mais argumentos do", "albertina ')) # Em funções Python podemos ter nenhuma ou", "'<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>'] print(autores) # ['<NAME>', '<NAME>', '<NAME>',", "nome, sobrenome: nome.strip().title() + ' ' + sobrenome.strip().title() print(nome_compelto(' paulo',", "lambdas com múltiplas entradas nome_compelto = lambda nome, sobrenome: nome.strip().title()", "# Ordenar pelo sobrenome autores.sort(key=lambda sobrenome: sobrenome.split(' ')[-1].lower()) print(autores) #", "** 2 + b * x + c \"\"\" return", "tres = lambda x, y, z: 3 / (1 /", "expressão lambda? calc = lambda x: 3 * x +", "x2, ..., xn: <expressão> print(hello()) print(uma(6)) print(duas(5, 7)) print(tres(3, 6,", "parâmetros esperados teremos TypeError # Exemplo autores = ['<NAME>', '<NAME>',", "print(funcao(7)) # Expressão Lambda lambda x: 3 * x +", "+ c \"\"\" return lambda x: a * x **", "sobrenome.strip().title() print(nome_compelto(' paulo', ' SILVA ')) print(nome_compelto(' MARIA ', '", "+ 1 / 7 + 1 / z) # n", "'<NAME>', '<NAME>', '<NAME>', # '<NAME>', 'In<NAME>', '<NAME>', '<NAME>', '<NAME>'] #", "são funções sem nome, ou seja, funções anónimas. # Função", "7 + 1 / z) # n = lambda x1,", "7)) print(tres(3, 6, 9)) # OBS: Se passarmos mais argumentos", "teremos TypeError # Exemplo autores = ['<NAME>', '<NAME>', '<NAME>', '<NAME>',", "Função Quadrática # f(x) = a * x ** 2", "com múltiplas entradas nome_compelto = lambda nome, sobrenome: nome.strip().title() +", "x + 1 duas = lambda x, y: (x *", "= ['<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>']", "['<NAME>', '<NAME>', '<NAME>', '<NAME>', # '<NAME>', 'In<NAME>', '<NAME>', '<NAME>', '<NAME>']", "lambda x: 3 * x + 1 print(calc(4)) print(calc(7)) #", "# f(x) = a * x ** 2 + b", "x: a * x ** 2 + b * x", "teste = geradora_funcao_quadratica(2, 3, -5) print(teste(0)) print(teste(1)) print(teste(2)) print(geradora_funcao_quadratica(3, 0,", "1 / z) # n = lambda x1, x2, ...,", "= lambda: 'Hello World!' uma = lambda x: 3 *", "# OBS: Se passarmos mais argumentos do que parâmetros esperados", "função f(x) = a * x ** 2 + b", "x + c \"\"\" return lambda x: a * x", "2 + b * x + c teste = geradora_funcao_quadratica(2,", "hello = lambda: 'Hello World!' uma = lambda x: 3", "sobrenome autores.sort(key=lambda sobrenome: sobrenome.split(' ')[-1].lower()) print(autores) # ['<NAME>', '<NAME>', 'In<NAME>',", "x ** 2 + b * x + c #", "')) print(nome_compelto(' MARIA ', ' albertina ')) # Em funções", "simplesmente Lambdas, são funções sem nome, ou seja, funções anónimas.", "** 0.5 tres = lambda x, y, z: 3 /", "/ 7 + 1 / z) # n = lambda", "(x * y) ** 0.5 tres = lambda x, y,", "' SILVA ')) print(nome_compelto(' MARIA ', ' albertina ')) #", "Exemplo autores = ['<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>',", "nome.strip().title() + ' ' + sobrenome.strip().title() print(nome_compelto(' paulo', ' SILVA", "várias entradas. Em Lambdas também hello = lambda: 'Hello World!'", "print(nome_compelto(' MARIA ', ' albertina ')) # Em funções Python", "# Função em Python def funcao(x): return 3 * x", "\"\"\" Utilizando Lambdas Conhecidas por Expressões Lambdas, ou simplesmente Lambdas,", "3 * x + 1 print(calc(4)) print(calc(7)) # Podemos ter", "= geradora_funcao_quadratica(2, 3, -5) print(teste(0)) print(teste(1)) print(teste(2)) print(geradora_funcao_quadratica(3, 0, 1)(2))", "sobrenome.split(' ')[-1].lower()) print(autores) # ['<NAME>', '<NAME>', 'In<NAME>', '<NAME>', # '<NAME>',", "lambda: 'Hello World!' uma = lambda x: 3 * x", "seja, funções anónimas. # Função em Python def funcao(x): return", "lambda x, y, z: 3 / (1 / x +", "esperados teremos TypeError # Exemplo autores = ['<NAME>', '<NAME>', '<NAME>',", "')[-1].lower()) print(autores) # ['<NAME>', '<NAME>', 'In<NAME>', '<NAME>', # '<NAME>', '<NAME>',", "y: (x * y) ** 0.5 tres = lambda x,", "x + c # Definindo a função def geradora_funcao_quadratica(a, b,", "** 2 + b * x + c teste =", "Conhecidas por Expressões Lambdas, ou simplesmente Lambdas, são funções sem", "argumentos do que parâmetros esperados teremos TypeError # Exemplo autores", "'<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>'] print(autores) # ['<NAME>', '<NAME>',", "2 + b * x + c # Definindo a", "por Expressões Lambdas, ou simplesmente Lambdas, são funções sem nome,", "print(calc(4)) print(calc(7)) # Podemos ter expressões lambdas com múltiplas entradas", "z) # n = lambda x1, x2, ..., xn: <expressão>", "Quadrática # f(x) = a * x ** 2 +", "/ (1 / x + 1 / 7 + 1", "ou várias entradas. Em Lambdas também hello = lambda: 'Hello", "+ sobrenome.strip().title() print(nome_compelto(' paulo', ' SILVA ')) print(nome_compelto(' MARIA ',", "x + 1 # Como utlizar a expressão lambda? calc", "x ** 2 + b * x + c \"\"\"", "2 + b * x + c \"\"\" return lambda", "funções Python podemos ter nenhuma ou várias entradas. Em Lambdas", "\"\"\" # Função Quadrática # f(x) = a * x", "a função def geradora_funcao_quadratica(a, b, c): \"\"\" Retorna a função", "função def geradora_funcao_quadratica(a, b, c): \"\"\" Retorna a função f(x)", "Lambdas, são funções sem nome, ou seja, funções anónimas. #", "* x + 1 print(funcao(4)) print(funcao(7)) # Expressão Lambda lambda", "/ x + 1 / 7 + 1 / z)", "y) ** 0.5 tres = lambda x, y, z: 3", "'In<NAME>', '<NAME>', '<NAME>', '<NAME>'] # Ordenar pelo sobrenome autores.sort(key=lambda sobrenome:", "print(funcao(4)) print(funcao(7)) # Expressão Lambda lambda x: 3 * x", "', ' albertina ')) # Em funções Python podemos ter", "= lambda x, y: (x * y) ** 0.5 tres", "* x + c # Definindo a função def geradora_funcao_quadratica(a,", "+ c teste = geradora_funcao_quadratica(2, 3, -5) print(teste(0)) print(teste(1)) print(teste(2))", "+ 1 print(calc(4)) print(calc(7)) # Podemos ter expressões lambdas com", "expressões lambdas com múltiplas entradas nome_compelto = lambda nome, sobrenome:", "x, y: (x * y) ** 0.5 tres = lambda", "= a * x ** 2 + b * x", "Lambdas também hello = lambda: 'Hello World!' uma = lambda", "3 * x + 1 duas = lambda x, y:", "'<NAME>', '<NAME>', # '<NAME>', 'In<NAME>', '<NAME>', '<NAME>', '<NAME>'] # Ordenar", "'<NAME>', '<NAME>'] \"\"\" # Função Quadrática # f(x) = a", "['<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>'] print(autores)", "return lambda x: a * x ** 2 + b", "'<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>'] print(autores) #", "* x + c teste = geradora_funcao_quadratica(2, 3, -5) print(teste(0))", "Python def funcao(x): return 3 * x + 1 print(funcao(4))", "Se passarmos mais argumentos do que parâmetros esperados teremos TypeError", "ter expressões lambdas com múltiplas entradas nome_compelto = lambda nome,", "'In<NAME>', '<NAME>', # '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>'] \"\"\" #", "1 print(funcao(4)) print(funcao(7)) # Expressão Lambda lambda x: 3 *", "x: 3 * x + 1 # Como utlizar a", "+ ' ' + sobrenome.strip().title() print(nome_compelto(' paulo', ' SILVA '))", "'<NAME>'] # Ordenar pelo sobrenome autores.sort(key=lambda sobrenome: sobrenome.split(' ')[-1].lower()) print(autores)", "x + 1 / 7 + 1 / z) #", "'<NAME>', # '<NAME>', 'In<NAME>', '<NAME>', '<NAME>', '<NAME>'] # Ordenar pelo", "'<NAME>', '<NAME>', '<NAME>'] # Ordenar pelo sobrenome autores.sort(key=lambda sobrenome: sobrenome.split('", "+ c # Definindo a função def geradora_funcao_quadratica(a, b, c):", "1 print(calc(4)) print(calc(7)) # Podemos ter expressões lambdas com múltiplas", "# n = lambda x1, x2, ..., xn: <expressão> print(hello())", "<filename>Sec_10_expr_lambdas_fun_integradas/a_lambdas.py \"\"\" Utilizando Lambdas Conhecidas por Expressões Lambdas, ou simplesmente", "'<NAME>'] \"\"\" # Função Quadrática # f(x) = a *", "..., xn: <expressão> print(hello()) print(uma(6)) print(duas(5, 7)) print(tres(3, 6, 9))", "# Podemos ter expressões lambdas com múltiplas entradas nome_compelto =", "* x + 1 print(calc(4)) print(calc(7)) # Podemos ter expressões", "= lambda x1, x2, ..., xn: <expressão> print(hello()) print(uma(6)) print(duas(5,", "Podemos ter expressões lambdas com múltiplas entradas nome_compelto = lambda", "pelo sobrenome autores.sort(key=lambda sobrenome: sobrenome.split(' ')[-1].lower()) print(autores) # ['<NAME>', '<NAME>',", "anónimas. # Função em Python def funcao(x): return 3 *", "print(nome_compelto(' paulo', ' SILVA ')) print(nome_compelto(' MARIA ', ' albertina", "' albertina ')) # Em funções Python podemos ter nenhuma", "xn: <expressão> print(hello()) print(uma(6)) print(duas(5, 7)) print(tres(3, 6, 9)) #", "nome_compelto = lambda nome, sobrenome: nome.strip().title() + ' ' +", "0.5 tres = lambda x, y, z: 3 / (1", "sem nome, ou seja, funções anónimas. # Função em Python", "x: 3 * x + 1 duas = lambda x,", "# Em funções Python podemos ter nenhuma ou várias entradas.", "nome, ou seja, funções anónimas. # Função em Python def" ]
[ "print(f'O campo {k} tem o valor: {v}') print() print('=' *", "{i + 1}? ')) gol.append(aux) print() campeonato['Gols'] = gol[:] campeonato['Total']", "na partida {i + 1}? ')) gol.append(aux) print() campeonato['Gols'] =", "fez {gol[i]} gol(s).') print() print(f'No total ele fez {campeonato[\"Total\"]} gols.')", "dict() gol = [] aux = 0 campeonato['Jogador'] = str(input('Digite", "gol[:] campeonato['Total'] = sum(gol) print('=' * 55) print() print(campeonato) print()", "dicionário campeonato = dict() gol = [] aux = 0", "ele fez {gol[i]} gol(s).') print() print(f'No total ele fez {campeonato[\"Total\"]}", "aux = 0 campeonato['Jogador'] = str(input('Digite o nome do jogador:", "* 55) print(f'O jogador {campeonato[\"Jogador\"]} jogou {partidas} partidas.') print() for", "int(input(f'Quantos gols na partida {i + 1}? ')) gol.append(aux) print()", "i in range(0, partidas): print(f'Na partida {i + 1} ele", "55) print(f'O jogador {campeonato[\"Jogador\"]} jogou {partidas} partidas.') print() for i", "{partidas} partidas.') print() for i in range(0, partidas): print(f'Na partida", "k, v in campeonato.items(): print(f'O campo {k} tem o valor:", "* 55) print() for k, v in campeonato.items(): print(f'O campo", "nome do jogador: ')) print() partidas = int(input('Quantas partidas ele", "+ 1}? ')) gol.append(aux) print() campeonato['Gols'] = gol[:] campeonato['Total'] =", "campeonato['Jogador'] = str(input('Digite o nome do jogador: ')) print() partidas", "{campeonato[\"Jogador\"]} jogou {partidas} partidas.') print() for i in range(0, partidas):", "dentro de dicionário campeonato = dict() gol = [] aux", "jogou? ')) print() for i in range(0, partidas): aux =", "partidas.') print() for i in range(0, partidas): print(f'Na partida {i", "print() print(campeonato) print() print('=' * 55) print() for k, v", "gol.append(aux) print() campeonato['Gols'] = gol[:] campeonato['Total'] = sum(gol) print('=' *", "for i in range(0, partidas): aux = int(input(f'Quantos gols na", "* 55) print() print(campeonato) print() print('=' * 55) print() for", "print() print(f'No total ele fez {campeonato[\"Total\"]} gols.') print('=' * 55)", "')) print() partidas = int(input('Quantas partidas ele jogou? ')) print()", "= gol[:] campeonato['Total'] = sum(gol) print('=' * 55) print() print(campeonato)", "v in campeonato.items(): print(f'O campo {k} tem o valor: {v}')", "55) print() print(campeonato) print() print('=' * 55) print() for k,", "range(0, partidas): aux = int(input(f'Quantos gols na partida {i +", "1}? ')) gol.append(aux) print() campeonato['Gols'] = gol[:] campeonato['Total'] = sum(gol)", "campeonato = dict() gol = [] aux = 0 campeonato['Jogador']", "de dicionário campeonato = dict() gol = [] aux =", "gols na partida {i + 1}? ')) gol.append(aux) print() campeonato['Gols']", "partidas): print(f'Na partida {i + 1} ele fez {gol[i]} gol(s).')", "for i in range(0, partidas): print(f'Na partida {i + 1}", "o nome do jogador: ')) print() partidas = int(input('Quantas partidas", "= dict() gol = [] aux = 0 campeonato['Jogador'] =", "{k} tem o valor: {v}') print() print('=' * 55) print(f'O", "for k, v in campeonato.items(): print(f'O campo {k} tem o", "aux = int(input(f'Quantos gols na partida {i + 1}? '))", "jogou {partidas} partidas.') print() for i in range(0, partidas): print(f'Na", "print(f'O jogador {campeonato[\"Jogador\"]} jogou {partidas} partidas.') print() for i in", "str(input('Digite o nome do jogador: ')) print() partidas = int(input('Quantas", "print() print('=' * 55) print(f'O jogador {campeonato[\"Jogador\"]} jogou {partidas} partidas.')", "print() for i in range(0, partidas): aux = int(input(f'Quantos gols", "partidas ele jogou? ')) print() for i in range(0, partidas):", "campeonato['Gols'] = gol[:] campeonato['Total'] = sum(gol) print('=' * 55) print()", "print('=' * 55) print() print(campeonato) print() print('=' * 55) print()", "in campeonato.items(): print(f'O campo {k} tem o valor: {v}') print()", "gol(s).') print() print(f'No total ele fez {campeonato[\"Total\"]} gols.') print('=' *", "# Lista dentro de dicionário campeonato = dict() gol =", "print() partidas = int(input('Quantas partidas ele jogou? ')) print() for", "valor: {v}') print() print('=' * 55) print(f'O jogador {campeonato[\"Jogador\"]} jogou", "do jogador: ')) print() partidas = int(input('Quantas partidas ele jogou?", "1} ele fez {gol[i]} gol(s).') print() print(f'No total ele fez", "Lista dentro de dicionário campeonato = dict() gol = []", "int(input('Quantas partidas ele jogou? ')) print() for i in range(0,", "campeonato.items(): print(f'O campo {k} tem o valor: {v}') print() print('='", "print() print('=' * 55) print() for k, v in campeonato.items():", "{v}') print() print('=' * 55) print(f'O jogador {campeonato[\"Jogador\"]} jogou {partidas}", "sum(gol) print('=' * 55) print() print(campeonato) print() print('=' * 55)", "in range(0, partidas): print(f'Na partida {i + 1} ele fez", "+ 1} ele fez {gol[i]} gol(s).') print() print(f'No total ele", "')) print() for i in range(0, partidas): aux = int(input(f'Quantos", "= str(input('Digite o nome do jogador: ')) print() partidas =", "ele jogou? ')) print() for i in range(0, partidas): aux", "o valor: {v}') print() print('=' * 55) print(f'O jogador {campeonato[\"Jogador\"]}", "partidas = int(input('Quantas partidas ele jogou? ')) print() for i", "0 campeonato['Jogador'] = str(input('Digite o nome do jogador: ')) print()", "print() for i in range(0, partidas): print(f'Na partida {i +", "[] aux = 0 campeonato['Jogador'] = str(input('Digite o nome do", "in range(0, partidas): aux = int(input(f'Quantos gols na partida {i", "= [] aux = 0 campeonato['Jogador'] = str(input('Digite o nome", "i in range(0, partidas): aux = int(input(f'Quantos gols na partida", "= int(input(f'Quantos gols na partida {i + 1}? ')) gol.append(aux)", "partida {i + 1}? ')) gol.append(aux) print() campeonato['Gols'] = gol[:]", "partida {i + 1} ele fez {gol[i]} gol(s).') print() print(f'No", "{i + 1} ele fez {gol[i]} gol(s).') print() print(f'No total", "campo {k} tem o valor: {v}') print() print('=' * 55)", "tem o valor: {v}') print() print('=' * 55) print(f'O jogador", "print('=' * 55) print() for k, v in campeonato.items(): print(f'O", "= int(input('Quantas partidas ele jogou? ')) print() for i in", "gol = [] aux = 0 campeonato['Jogador'] = str(input('Digite o", "print('=' * 55) print(f'O jogador {campeonato[\"Jogador\"]} jogou {partidas} partidas.') print()", "print() for k, v in campeonato.items(): print(f'O campo {k} tem", "print(campeonato) print() print('=' * 55) print() for k, v in", "55) print() for k, v in campeonato.items(): print(f'O campo {k}", "jogador: ')) print() partidas = int(input('Quantas partidas ele jogou? '))", "print() campeonato['Gols'] = gol[:] campeonato['Total'] = sum(gol) print('=' * 55)", "{gol[i]} gol(s).') print() print(f'No total ele fez {campeonato[\"Total\"]} gols.') print('='", "campeonato['Total'] = sum(gol) print('=' * 55) print() print(campeonato) print() print('='", "jogador {campeonato[\"Jogador\"]} jogou {partidas} partidas.') print() for i in range(0,", "range(0, partidas): print(f'Na partida {i + 1} ele fez {gol[i]}", "print(f'Na partida {i + 1} ele fez {gol[i]} gol(s).') print()", "partidas): aux = int(input(f'Quantos gols na partida {i + 1}?", "')) gol.append(aux) print() campeonato['Gols'] = gol[:] campeonato['Total'] = sum(gol) print('='", "= 0 campeonato['Jogador'] = str(input('Digite o nome do jogador: '))", "<gh_stars>0 # Lista dentro de dicionário campeonato = dict() gol", "= sum(gol) print('=' * 55) print() print(campeonato) print() print('=' *" ]
[ "def __call__(self, x): u = numpy.zeros_like(x) for k, coefficient in", "coefficients def __call__(self, x): u = numpy.zeros_like(x) for k, coefficient", "(k * numpy.pi) ** 2 * t) * numpy.sin( k", "+= coefficient * numpy.sin(k * numpy.pi * x) return u", "return sum(coefficient * numpy.exp(-q * (k * numpy.pi) ** 2", "k * numpy.pi * x) for k, coefficient in enumerate(self.coefficients))", "2 * t) * numpy.sin( k * numpy.pi * x)", "numpy class InitialDataControlSine: def __init__(self, coefficients): self.coefficients = coefficients def", "self.coefficients = coefficients def __call__(self, x): u = numpy.zeros_like(x) for", "* t) * numpy.sin( k * numpy.pi * x) for", "numpy.pi * x) return u def exact_solution(self, x, t, q=1):", "numpy.pi) ** 2 * t) * numpy.sin( k * numpy.pi", "x) return u def exact_solution(self, x, t, q=1): return sum(coefficient", "q=1): return sum(coefficient * numpy.exp(-q * (k * numpy.pi) **", "numpy.exp(-q * (k * numpy.pi) ** 2 * t) *", "** 2 * t) * numpy.sin( k * numpy.pi *", "def __init__(self, coefficients): self.coefficients = coefficients def __call__(self, x): u", "numpy.sin(k * numpy.pi * x) return u def exact_solution(self, x,", "x): u = numpy.zeros_like(x) for k, coefficient in enumerate(self.coefficients): u", "* numpy.sin(k * numpy.pi * x) return u def exact_solution(self,", "* numpy.pi * x) return u def exact_solution(self, x, t,", "* numpy.exp(-q * (k * numpy.pi) ** 2 * t)", "__init__(self, coefficients): self.coefficients = coefficients def __call__(self, x): u =", "u += coefficient * numpy.sin(k * numpy.pi * x) return", "sum(coefficient * numpy.exp(-q * (k * numpy.pi) ** 2 *", "coefficients): self.coefficients = coefficients def __call__(self, x): u = numpy.zeros_like(x)", "numpy.sin( k * numpy.pi * x) for k, coefficient in", "= numpy.zeros_like(x) for k, coefficient in enumerate(self.coefficients): u += coefficient", "x, t, q=1): return sum(coefficient * numpy.exp(-q * (k *", "= coefficients def __call__(self, x): u = numpy.zeros_like(x) for k,", "__call__(self, x): u = numpy.zeros_like(x) for k, coefficient in enumerate(self.coefficients):", "coefficient in enumerate(self.coefficients): u += coefficient * numpy.sin(k * numpy.pi", "return u def exact_solution(self, x, t, q=1): return sum(coefficient *", "* x) return u def exact_solution(self, x, t, q=1): return", "* numpy.pi) ** 2 * t) * numpy.sin( k *", "t) * numpy.sin( k * numpy.pi * x) for k,", "def exact_solution(self, x, t, q=1): return sum(coefficient * numpy.exp(-q *", "* numpy.sin( k * numpy.pi * x) for k, coefficient", "coefficient * numpy.sin(k * numpy.pi * x) return u def", "* (k * numpy.pi) ** 2 * t) * numpy.sin(", "u def exact_solution(self, x, t, q=1): return sum(coefficient * numpy.exp(-q", "in enumerate(self.coefficients): u += coefficient * numpy.sin(k * numpy.pi *", "t, q=1): return sum(coefficient * numpy.exp(-q * (k * numpy.pi)", "k, coefficient in enumerate(self.coefficients): u += coefficient * numpy.sin(k *", "exact_solution(self, x, t, q=1): return sum(coefficient * numpy.exp(-q * (k", "InitialDataControlSine: def __init__(self, coefficients): self.coefficients = coefficients def __call__(self, x):", "enumerate(self.coefficients): u += coefficient * numpy.sin(k * numpy.pi * x)", "import numpy class InitialDataControlSine: def __init__(self, coefficients): self.coefficients = coefficients", "numpy.zeros_like(x) for k, coefficient in enumerate(self.coefficients): u += coefficient *", "class InitialDataControlSine: def __init__(self, coefficients): self.coefficients = coefficients def __call__(self,", "for k, coefficient in enumerate(self.coefficients): u += coefficient * numpy.sin(k", "u = numpy.zeros_like(x) for k, coefficient in enumerate(self.coefficients): u +=", "<reponame>kjetil-lye/ismo_heat<gh_stars>0 import numpy class InitialDataControlSine: def __init__(self, coefficients): self.coefficients =" ]
[ "pre-GitHub commits for '%s'\" % (repo)) outObj[\"data\"] = [] #", "in repolist: # History doesn't change, only update new repos", "[] print(\"Getting internal repos ...\") repolist = sorted(dataObj[\"data\"].keys()) print(\"Repo list", "helpers.query_githubrest(authhead, gitquery) if outObj[\"errors\"]: print(tab + \"Could not get pre-GitHub", "= \" \" for repo in repolist: # History doesn't", "= re.sub('REPONAME', repoSplit[1], gitquery) gitquery = re.sub('CREATETIME', collective[\"data\"][repo][\"createdAt\"], gitquery) print(tab", "outObj[\"data\"]: collective[\"data\"][repo][\"commitTimestamps\"].append(commit[\"commit\"][\"committer\"][\"date\"]) hasNext = (\"next\" in outObj) # Sort dates", "previous commits if \"data\" in allData.keys() and repo in allData[\"data\"].keys():", "re.sub('CREATETIME', collective[\"data\"][repo][\"createdAt\"], gitquery) print(tab + \"Query ready!\") # Actual query", "full history\") collective[\"data\"][repo][\"initBeforeGitHubRepo\"] = False # Query 3 print(tab +", "{} for repo in collective[\"data\"].keys(): allData[\"data\"][repo] = collective[\"data\"][repo] allDataString =", "Populate repo list repolist = [] print(\"Getting internal repos ...\")", "True else: print(tab + \"No pre-GitHub commits found, getting full", "\"Could not get pre-GitHub commits for '%s'\" % (repo)) outObj[\"data\"]", "use as repo list) dataObj = helpers.read_json(\"../github-data/labReposInfo.json\") # Populate repo", "repo list repolist = [] print(\"Getting internal repos ...\") repolist", "\"Query ready!\") # Actual query exchange outObj = helpers.query_github(authhead, gitquery)", "exchange outObj = helpers.query_githubrest(authhead, newquery) if outObj[\"errors\"]: print(tab + \"Could", "[] # Update collective data collective[\"data\"][repo][\"commitTimestamps\"] = [] for commit", "repoSplit = repo.split(\"/\") # Query 1 print(tab + \"Get creation", "collective[\"data\"].pop(repo, None) continue # Update collective data for commit in", "\"Get pre-GitHub commit timestamps\") print(tab + \"Modifying query...\") gitquery =", "2 print(tab + \"Get pre-GitHub commit timestamps\") print(tab + \"Modifying", "collective[\"data\"][repo][\"commitTimestamps\"].sort() # Save earliest commit date firstdate = None if", "data for '%s'\" % (repo)) continue pageNum = 1 print(\"\\n'%s'\"", "# Retrieve authorization token authhead = helpers.get_gitauth() # Iterate through", "read existing data file allData = helpers.read_existing(datfilepath) # Read repo", "query_commits_in) gitquery = re.sub('REPONAME', repoSplit[1], gitquery) gitquery = re.sub('CREATETIME', collective[\"data\"][repo][\"createdAt\"],", "print(tab + \"Get creation date and default branch\") print(tab +", "tab = \" \" for repo in repolist: # History", "pre-GitHub commit timestamps\") print(tab + \"Modifying query...\") gitquery = re.sub('OWNNAME',", "greater commit history if len(collective[\"data\"][repo][\"commitTimestamps\"]) > 0 and collective[\"data\"][repo][\"commitTimestamps\"][0]: collective[\"data\"][repo][\"initBeforeGitHubRepo\"]", "repoSplit[0], query_commits_in) gitquery = re.sub('REPONAME', repoSplit[1], gitquery) gitquery = re.sub('CREATETIME',", "queries...\") collective = {u'data': {}} tab = \" \" for", "repolist = sorted(dataObj[\"data\"].keys()) print(\"Repo list complete. Found %d repos.\" %", "# Query 2 print(tab + \"Get pre-GitHub commit timestamps\") print(tab", "query_commits_in2) gitquery = re.sub('REPONAME', repoSplit[1], gitquery) print(tab + \"Query ready!\")", "Update collective data for commit in outObj[\"data\"]: collective[\"data\"][repo][\"commitTimestamps\"].append(commit[\"commit\"][\"committer\"][\"date\"]) hasNext =", "gitquery) print(tab + \"Query ready!\") # Actual query exchange outObj", "= firstdate del collective[\"data\"][repo][\"commitTimestamps\"] print(\"'%s' Done!\" % (repo)) print(\"\\nCollective data", "json.dumps(allData, indent=4, sort_keys=True) # Write output file print(\"\\nWriting file '%s'\"", "repolist = [] print(\"Getting internal repos ...\") repolist = sorted(dataObj[\"data\"].keys())", "print(tab + \"Modifying query...\") newquery = gitquery + \"&page=\" +", "# Populate repo list repolist = [] print(\"Getting internal repos", "% (repo)) outObj[\"data\"] = [] # Update collective data collective[\"data\"][repo][\"commitTimestamps\"]", "hasNext = (\"next\" in outObj) while hasNext: pageNum += 1", "repoSplit[1], newquery) gitquery = json.dumps({'query': newquery}) print(tab + \"Query ready!\")", "history if len(collective[\"data\"][repo][\"commitTimestamps\"]) > 0 and collective[\"data\"][repo][\"commitTimestamps\"][0]: collective[\"data\"][repo][\"initBeforeGitHubRepo\"] = True", "history\") collective[\"data\"][repo][\"initBeforeGitHubRepo\"] = False # Query 3 print(tab + \"Modifying", "if needed hasNext = (\"next\" in outObj) while hasNext: pageNum", "continue pageNum = 1 print(\"\\n'%s'\" % (repo)) print(tab + \"page", "newquery = gitquery + \"&page=\" + str(pageNum) print(tab + \"Query", "gitquery = json.dumps({'query': newquery}) print(tab + \"Query ready!\") # Actual", "helpers.query_github(authhead, gitquery) if outObj[\"errors\"]: print(tab + \"Could not complete '%s'\"", "collective data collective[\"data\"][repo] = outObj[\"data\"][\"repository\"] # Query 2 print(tab +", "query exchange outObj = helpers.query_githubrest(authhead, gitquery) if outObj[\"errors\"]: print(tab +", "allData = helpers.read_existing(datfilepath) # Read repo info data file (to", "sorted(dataObj[\"data\"].keys()) print(\"Repo list complete. Found %d repos.\" % (len(repolist))) #", "if \"data\" in allData.keys() and repo in allData[\"data\"].keys(): if allData[\"data\"][repo][\"firstCommitAt\"]:", "print(\"\\nWriting file '%s'\" % (datfilepath)) with open(datfilepath, \"w\") as fileout:", "\"/repos/OWNNAME/REPONAME/commits?per_page=100\" # Retrieve authorization token authhead = helpers.get_gitauth() # Iterate", "Save earliest commit date firstdate = None if len(collective[\"data\"][repo][\"commitTimestamps\"]) >", "+ \"Query ready!\") # Actual query exchange outObj = helpers.query_githubrest(authhead,", "= {} # Check for and read existing data file", "query...\") gitquery = re.sub('OWNNAME', repoSplit[0], query_commits_in) gitquery = re.sub('REPONAME', repoSplit[1],", "print(\"Repo list complete. Found %d repos.\" % (len(repolist))) # Read", "collective = {u'data': {}} tab = \" \" for repo", "+= 1 print(tab + \"page %d\" % (pageNum)) print(tab +", "{}} tab = \" \" for repo in repolist: #", "pageNum = 1 print(\"\\n'%s'\" % (repo)) print(tab + \"page %d\"", "collective[\"data\"][repo][\"commitTimestamps\"].append(commit[\"commit\"][\"committer\"][\"date\"]) hasNext = (\"next\" in outObj) # Sort dates collective[\"data\"][repo][\"commitTimestamps\"].sort()", "{} # Check for and read existing data file allData", "if len(collective[\"data\"][repo][\"commitTimestamps\"]) > 0: firstdate = collective[\"data\"][repo][\"commitTimestamps\"][0] collective[\"data\"][repo][\"firstCommitAt\"] = firstdate", "= helpers.query_githubrest(authhead, gitquery) if outObj[\"errors\"]: print(tab + \"Could not complete", "gathering complete!\") # Combine new data with existing data if", "print(tab + \"Query ready!\") # Actual query exchange outObj =", "in outObj[\"data\"]: collective[\"data\"][repo][\"commitTimestamps\"].append(commit[\"commit\"][\"committer\"][\"date\"]) # If no pre-GitHub commits, check the", "If no pre-GitHub commits, check the greater commit history if", "in outObj[\"data\"]: collective[\"data\"][repo][\"commitTimestamps\"].append(commit[\"commit\"][\"committer\"][\"date\"]) # Paginate if needed hasNext = (\"next\"", "\"Modifying query...\") newquery = re.sub('OWNNAME', repoSplit[0], query_in) newquery = re.sub('REPONAME',", "= helpers.query_githubrest(authhead, newquery) if outObj[\"errors\"]: print(tab + \"Could not complete", "helpers.query_githubrest(authhead, gitquery) if outObj[\"errors\"]: print(tab + \"Could not complete '%s'\"", "update new repos or those that had no previous commits", "sort_keys=True) # Write output file print(\"\\nWriting file '%s'\" % (datfilepath))", "allData[\"data\"] = {} for repo in collective[\"data\"].keys(): allData[\"data\"][repo] = collective[\"data\"][repo]", "get pre-GitHub commits for '%s'\" % (repo)) outObj[\"data\"] = []", "# Check for and read existing data file allData =", "History doesn't change, only update new repos or those that", "collective[\"data\"][repo][\"commitTimestamps\"][0]: collective[\"data\"][repo][\"initBeforeGitHubRepo\"] = True else: print(tab + \"No pre-GitHub commits", "list complete. Found %d repos.\" % (len(repolist))) # Read pretty", "for commit in outObj[\"data\"]: collective[\"data\"][repo][\"commitTimestamps\"].append(commit[\"commit\"][\"committer\"][\"date\"]) # Paginate if needed hasNext", "helpers.read_json(\"../github-data/labReposInfo.json\") # Populate repo list repolist = [] print(\"Getting internal", "hasNext: pageNum += 1 print(tab + \"page %d\" % (pageNum))", "+ \"No pre-GitHub commits found, getting full history\") collective[\"data\"][repo][\"initBeforeGitHubRepo\"] =", "repoSplit[1], gitquery) gitquery = re.sub('CREATETIME', collective[\"data\"][repo][\"createdAt\"], gitquery) print(tab + \"Query", "collective[\"data\"][repo][\"firstCommitAt\"] = firstdate del collective[\"data\"][repo][\"commitTimestamps\"] print(\"'%s' Done!\" % (repo)) print(\"\\nCollective", "data file (to use as repo list) dataObj = helpers.read_json(\"../github-data/labReposInfo.json\")", "# Actual query exchange outObj = helpers.query_githubrest(authhead, gitquery) if outObj[\"errors\"]:", "Actual query exchange outObj = helpers.query_github(authhead, gitquery) if outObj[\"errors\"]: print(tab", "= (\"next\" in outObj) # Sort dates collective[\"data\"][repo][\"commitTimestamps\"].sort() # Save", "= [] print(\"Getting internal repos ...\") repolist = sorted(dataObj[\"data\"].keys()) print(\"Repo", "print(\"\\n'%s'\" % (repo)) print(tab + \"page %d\" % (pageNum)) repoSplit", "collective[\"data\"][repo] allDataString = json.dumps(allData, indent=4, sort_keys=True) # Write output file", "collective[\"data\"][repo][\"createdAt\"], gitquery) print(tab + \"Query ready!\") # Actual query exchange", "file allData = helpers.read_existing(datfilepath) # Read repo info data file", "repo in repolist: # History doesn't change, only update new", "dataObj = helpers.read_json(\"../github-data/labReposInfo.json\") # Populate repo list repolist = []", "outObj[\"data\"]: collective[\"data\"][repo][\"commitTimestamps\"].append(commit[\"commit\"][\"committer\"][\"date\"]) # If no pre-GitHub commits, check the greater", "= [] for commit in outObj[\"data\"]: collective[\"data\"][repo][\"commitTimestamps\"].append(commit[\"commit\"][\"committer\"][\"date\"]) # If no", "Sort dates collective[\"data\"][repo][\"commitTimestamps\"].sort() # Save earliest commit date firstdate =", "commit timestamps\") print(tab + \"Modifying query...\") gitquery = re.sub('OWNNAME', repoSplit[0],", "% (datfilepath)) with open(datfilepath, \"w\") as fileout: fileout.write(allDataString) print(\"Wrote file!\")", "helpers.read_gql(\"../queries/repo-CreationDate.gql\") # Rest endpoint query query_commits_in = \"/repos/OWNNAME/REPONAME/commits?until=CREATETIME&per_page=100\" query_commits_in2 =", "data for commit in outObj[\"data\"]: collective[\"data\"][repo][\"commitTimestamps\"].append(commit[\"commit\"][\"committer\"][\"date\"]) hasNext = (\"next\" in", "# Update collective data collective[\"data\"][repo] = outObj[\"data\"][\"repository\"] # Query 2", "print(tab + \"page %d\" % (pageNum)) repoSplit = repo.split(\"/\") #", "collective[\"data\"][repo][\"commitTimestamps\"] print(\"'%s' Done!\" % (repo)) print(\"\\nCollective data gathering complete!\") #", "% (len(repolist))) # Read pretty GraphQL query query_in = helpers.read_gql(\"../queries/repo-CreationDate.gql\")", "Check for and read existing data file allData = helpers.read_existing(datfilepath)", "gitquery + \"&page=\" + str(pageNum) print(tab + \"Query ready!\") #", "data with existing data if \"data\" not in allData.keys(): allData[\"data\"]", "= \"/repos/OWNNAME/REPONAME/commits?until=CREATETIME&per_page=100\" query_commits_in2 = \"/repos/OWNNAME/REPONAME/commits?per_page=100\" # Retrieve authorization token authhead", "commits, check the greater commit history if len(collective[\"data\"][repo][\"commitTimestamps\"]) > 0", "branch\") print(tab + \"Modifying query...\") newquery = re.sub('OWNNAME', repoSplit[0], query_in)", "outObj[\"data\"][\"repository\"] # Query 2 print(tab + \"Get pre-GitHub commit timestamps\")", "repos or those that had no previous commits if \"data\"", "repos.\" % (len(repolist))) # Read pretty GraphQL query query_in =", "authorization token authhead = helpers.get_gitauth() # Iterate through internal repos", "getting full history\") collective[\"data\"][repo][\"initBeforeGitHubRepo\"] = False # Query 3 print(tab", "needed hasNext = (\"next\" in outObj) while hasNext: pageNum +=", "repoSplit[0], query_commits_in2) gitquery = re.sub('REPONAME', repoSplit[1], gitquery) print(tab + \"Query", "allData.keys(): allData[\"data\"] = {} for repo in collective[\"data\"].keys(): allData[\"data\"][repo] =", "(datfilepath)) with open(datfilepath, \"w\") as fileout: fileout.write(allDataString) print(\"Wrote file!\") print(\"\\nDone!\\n\")", "# Rest endpoint query query_commits_in = \"/repos/OWNNAME/REPONAME/commits?until=CREATETIME&per_page=100\" query_commits_in2 = \"/repos/OWNNAME/REPONAME/commits?per_page=100\"", "= 1 print(\"\\n'%s'\" % (repo)) print(tab + \"page %d\" %", "Read repo info data file (to use as repo list)", "= helpers.query_githubrest(authhead, gitquery) if outObj[\"errors\"]: print(tab + \"Could not get", "authhead = helpers.get_gitauth() # Iterate through internal repos print(\"Gathering data", "Done!\" % (repo)) print(\"\\nCollective data gathering complete!\") # Combine new", "ready!\") # Actual query exchange outObj = helpers.query_githubrest(authhead, newquery) if", "had no previous commits if \"data\" in allData.keys() and repo", "query...\") newquery = gitquery + \"&page=\" + str(pageNum) print(tab +", "+ \"Get pre-GitHub commit timestamps\") print(tab + \"Modifying query...\") gitquery", "# Paginate if needed hasNext = (\"next\" in outObj) while", "outObj[\"errors\"]: print(tab + \"Could not get pre-GitHub commits for '%s'\"", "firstdate del collective[\"data\"][repo][\"commitTimestamps\"] print(\"'%s' Done!\" % (repo)) print(\"\\nCollective data gathering", "\"data\" in allData.keys() and repo in allData[\"data\"].keys(): if allData[\"data\"][repo][\"firstCommitAt\"]: print(tab", "default branch\") print(tab + \"Modifying query...\") newquery = re.sub('OWNNAME', repoSplit[0],", "commit in outObj[\"data\"]: collective[\"data\"][repo][\"commitTimestamps\"].append(commit[\"commit\"][\"committer\"][\"date\"]) # If no pre-GitHub commits, check", "while hasNext: pageNum += 1 print(tab + \"page %d\" %", "\"Could not complete '%s'\" % (repo)) collective[\"data\"].pop(repo, None) continue #", "0 and collective[\"data\"][repo][\"commitTimestamps\"][0]: collective[\"data\"][repo][\"initBeforeGitHubRepo\"] = True else: print(tab + \"No", "query exchange outObj = helpers.query_github(authhead, gitquery) if outObj[\"errors\"]: print(tab +", "for repo in repolist: # History doesn't change, only update", "with existing data if \"data\" not in allData.keys(): allData[\"data\"] =", "{u'data': {}} tab = \" \" for repo in repolist:", "file (to use as repo list) dataObj = helpers.read_json(\"../github-data/labReposInfo.json\") #", "str(pageNum) print(tab + \"Query ready!\") # Actual query exchange outObj", "pageNum += 1 print(tab + \"page %d\" % (pageNum)) print(tab", "(\"next\" in outObj) # Sort dates collective[\"data\"][repo][\"commitTimestamps\"].sort() # Save earliest", "in allData[\"data\"].keys(): if allData[\"data\"][repo][\"firstCommitAt\"]: print(tab + \"Already recorded data for", "re.sub('OWNNAME', repoSplit[0], query_in) newquery = re.sub('REPONAME', repoSplit[1], newquery) gitquery =", "outObj = helpers.query_github(authhead, gitquery) if outObj[\"errors\"]: print(tab + \"Could not", "+ \"Modifying query...\") newquery = gitquery + \"&page=\" + str(pageNum)", "query query_commits_in = \"/repos/OWNNAME/REPONAME/commits?until=CREATETIME&per_page=100\" query_commits_in2 = \"/repos/OWNNAME/REPONAME/commits?per_page=100\" # Retrieve authorization", "len(collective[\"data\"][repo][\"commitTimestamps\"]) > 0 and collective[\"data\"][repo][\"commitTimestamps\"][0]: collective[\"data\"][repo][\"initBeforeGitHubRepo\"] = True else: print(tab", "query exchange outObj = helpers.query_githubrest(authhead, newquery) if outObj[\"errors\"]: print(tab +", "= outObj[\"data\"][\"repository\"] # Query 2 print(tab + \"Get pre-GitHub commit", "GraphQL query query_in = helpers.read_gql(\"../queries/repo-CreationDate.gql\") # Rest endpoint query query_commits_in", "(repo)) collective[\"data\"].pop(repo, None) continue # Update collective data collective[\"data\"][repo] =", "multiple paginated queries...\") collective = {u'data': {}} tab = \"", "False # Query 3 print(tab + \"Modifying query...\") gitquery =", "repo in collective[\"data\"].keys(): allData[\"data\"][repo] = collective[\"data\"][repo] allDataString = json.dumps(allData, indent=4,", "for repo in collective[\"data\"].keys(): allData[\"data\"][repo] = collective[\"data\"][repo] allDataString = json.dumps(allData,", "% (repo)) print(\"\\nCollective data gathering complete!\") # Combine new data", "file '%s'\" % (datfilepath)) with open(datfilepath, \"w\") as fileout: fileout.write(allDataString)", "'%s'\" % (datfilepath)) with open(datfilepath, \"w\") as fileout: fileout.write(allDataString) print(\"Wrote", "\"/repos/OWNNAME/REPONAME/commits?until=CREATETIME&per_page=100\" query_commits_in2 = \"/repos/OWNNAME/REPONAME/commits?per_page=100\" # Retrieve authorization token authhead =", "change, only update new repos or those that had no", "data for commit in outObj[\"data\"]: collective[\"data\"][repo][\"commitTimestamps\"].append(commit[\"commit\"][\"committer\"][\"date\"]) # Paginate if needed", "gitquery = re.sub('OWNNAME', repoSplit[0], query_commits_in2) gitquery = re.sub('REPONAME', repoSplit[1], gitquery)", "outObj = helpers.query_githubrest(authhead, newquery) if outObj[\"errors\"]: print(tab + \"Could not", "for commit in outObj[\"data\"]: collective[\"data\"][repo][\"commitTimestamps\"].append(commit[\"commit\"][\"committer\"][\"date\"]) hasNext = (\"next\" in outObj)", "commit history if len(collective[\"data\"][repo][\"commitTimestamps\"]) > 0 and collective[\"data\"][repo][\"commitTimestamps\"][0]: collective[\"data\"][repo][\"initBeforeGitHubRepo\"] =", "in outObj[\"data\"]: collective[\"data\"][repo][\"commitTimestamps\"].append(commit[\"commit\"][\"committer\"][\"date\"]) hasNext = (\"next\" in outObj) # Sort", "collective[\"data\"][repo][\"initBeforeGitHubRepo\"] = True else: print(tab + \"No pre-GitHub commits found,", "internal repos print(\"Gathering data across multiple paginated queries...\") collective =", "(\"next\" in outObj) while hasNext: pageNum += 1 print(tab +", "gitquery) gitquery = re.sub('CREATETIME', collective[\"data\"][repo][\"createdAt\"], gitquery) print(tab + \"Query ready!\")", "and collective[\"data\"][repo][\"commitTimestamps\"][0]: collective[\"data\"][repo][\"initBeforeGitHubRepo\"] = True else: print(tab + \"No pre-GitHub", "collective[\"data\"][repo][\"commitTimestamps\"].append(commit[\"commit\"][\"committer\"][\"date\"]) # If no pre-GitHub commits, check the greater commit", "# Update collective data for commit in outObj[\"data\"]: collective[\"data\"][repo][\"commitTimestamps\"].append(commit[\"commit\"][\"committer\"][\"date\"]) #", "json import re datfilepath = \"../github-data/labRepos_CreationHistory.json\" allData = {} #", "<filename>explore/scripts/get_repos_creationhistory.py import helpers import json import re datfilepath = \"../github-data/labRepos_CreationHistory.json\"", "Actual query exchange outObj = helpers.query_githubrest(authhead, gitquery) if outObj[\"errors\"]: print(tab", "date firstdate = None if len(collective[\"data\"][repo][\"commitTimestamps\"]) > 0: firstdate =", "data across multiple paginated queries...\") collective = {u'data': {}} tab", "(repo)) collective[\"data\"].pop(repo, None) continue # Update collective data for commit", "and repo in allData[\"data\"].keys(): if allData[\"data\"][repo][\"firstCommitAt\"]: print(tab + \"Already recorded", "= True else: print(tab + \"No pre-GitHub commits found, getting", "gitquery = re.sub('CREATETIME', collective[\"data\"][repo][\"createdAt\"], gitquery) print(tab + \"Query ready!\") #", "\"&page=\" + str(pageNum) print(tab + \"Query ready!\") # Actual query", "collective data collective[\"data\"][repo][\"commitTimestamps\"] = [] for commit in outObj[\"data\"]: collective[\"data\"][repo][\"commitTimestamps\"].append(commit[\"commit\"][\"committer\"][\"date\"])", "Write output file print(\"\\nWriting file '%s'\" % (datfilepath)) with open(datfilepath,", "\"Modifying query...\") gitquery = re.sub('OWNNAME', repoSplit[0], query_commits_in2) gitquery = re.sub('REPONAME',", "print(tab + \"No pre-GitHub commits found, getting full history\") collective[\"data\"][repo][\"initBeforeGitHubRepo\"]", "firstdate = None if len(collective[\"data\"][repo][\"commitTimestamps\"]) > 0: firstdate = collective[\"data\"][repo][\"commitTimestamps\"][0]", "collective[\"data\"].keys(): allData[\"data\"][repo] = collective[\"data\"][repo] allDataString = json.dumps(allData, indent=4, sort_keys=True) #", "commits if \"data\" in allData.keys() and repo in allData[\"data\"].keys(): if", "# Update collective data collective[\"data\"][repo][\"commitTimestamps\"] = [] for commit in", "pre-GitHub commits, check the greater commit history if len(collective[\"data\"][repo][\"commitTimestamps\"]) >", "in allData.keys() and repo in allData[\"data\"].keys(): if allData[\"data\"][repo][\"firstCommitAt\"]: print(tab +", "= collective[\"data\"][repo][\"commitTimestamps\"][0] collective[\"data\"][repo][\"firstCommitAt\"] = firstdate del collective[\"data\"][repo][\"commitTimestamps\"] print(\"'%s' Done!\" %", "'%s'\" % (repo)) continue pageNum = 1 print(\"\\n'%s'\" % (repo))", "helpers.get_gitauth() # Iterate through internal repos print(\"Gathering data across multiple", "creation date and default branch\") print(tab + \"Modifying query...\") newquery", "complete!\") # Combine new data with existing data if \"data\"", "...\") repolist = sorted(dataObj[\"data\"].keys()) print(\"Repo list complete. Found %d repos.\"", "(pageNum)) print(tab + \"Modifying query...\") newquery = gitquery + \"&page=\"", "= json.dumps({'query': newquery}) print(tab + \"Query ready!\") # Actual query", "# Read pretty GraphQL query query_in = helpers.read_gql(\"../queries/repo-CreationDate.gql\") # Rest", "1 print(tab + \"Get creation date and default branch\") print(tab", "(repo)) continue pageNum = 1 print(\"\\n'%s'\" % (repo)) print(tab +", "Query 3 print(tab + \"Modifying query...\") gitquery = re.sub('OWNNAME', repoSplit[0],", "0: firstdate = collective[\"data\"][repo][\"commitTimestamps\"][0] collective[\"data\"][repo][\"firstCommitAt\"] = firstdate del collective[\"data\"][repo][\"commitTimestamps\"] print(\"'%s'", "import json import re datfilepath = \"../github-data/labRepos_CreationHistory.json\" allData = {}", "# Update collective data for commit in outObj[\"data\"]: collective[\"data\"][repo][\"commitTimestamps\"].append(commit[\"commit\"][\"committer\"][\"date\"]) hasNext", "None if len(collective[\"data\"][repo][\"commitTimestamps\"]) > 0: firstdate = collective[\"data\"][repo][\"commitTimestamps\"][0] collective[\"data\"][repo][\"firstCommitAt\"] =", "for and read existing data file allData = helpers.read_existing(datfilepath) #", "# Sort dates collective[\"data\"][repo][\"commitTimestamps\"].sort() # Save earliest commit date firstdate", "gitquery) if outObj[\"errors\"]: print(tab + \"Could not get pre-GitHub commits", "only update new repos or those that had no previous", "that had no previous commits if \"data\" in allData.keys() and", "\"data\" not in allData.keys(): allData[\"data\"] = {} for repo in", "re.sub('OWNNAME', repoSplit[0], query_commits_in2) gitquery = re.sub('REPONAME', repoSplit[1], gitquery) print(tab +", "print(tab + \"Modifying query...\") newquery = re.sub('OWNNAME', repoSplit[0], query_in) newquery", "collective data for commit in outObj[\"data\"]: collective[\"data\"][repo][\"commitTimestamps\"].append(commit[\"commit\"][\"committer\"][\"date\"]) hasNext = (\"next\"", "query query_in = helpers.read_gql(\"../queries/repo-CreationDate.gql\") # Rest endpoint query query_commits_in =", "Iterate through internal repos print(\"Gathering data across multiple paginated queries...\")", "as repo list) dataObj = helpers.read_json(\"../github-data/labReposInfo.json\") # Populate repo list", "\" for repo in repolist: # History doesn't change, only", "not get pre-GitHub commits for '%s'\" % (repo)) outObj[\"data\"] =", "collective[\"data\"][repo][\"commitTimestamps\"][0] collective[\"data\"][repo][\"firstCommitAt\"] = firstdate del collective[\"data\"][repo][\"commitTimestamps\"] print(\"'%s' Done!\" % (repo))", "if \"data\" not in allData.keys(): allData[\"data\"] = {} for repo", "timestamps\") print(tab + \"Modifying query...\") gitquery = re.sub('OWNNAME', repoSplit[0], query_commits_in)", "in allData.keys(): allData[\"data\"] = {} for repo in collective[\"data\"].keys(): allData[\"data\"][repo]", "pre-GitHub commits found, getting full history\") collective[\"data\"][repo][\"initBeforeGitHubRepo\"] = False #", "# Actual query exchange outObj = helpers.query_githubrest(authhead, newquery) if outObj[\"errors\"]:", "hasNext = (\"next\" in outObj) # Sort dates collective[\"data\"][repo][\"commitTimestamps\"].sort() #", "+ \"Could not get pre-GitHub commits for '%s'\" % (repo))", "pretty GraphQL query query_in = helpers.read_gql(\"../queries/repo-CreationDate.gql\") # Rest endpoint query", "= re.sub('REPONAME', repoSplit[1], gitquery) print(tab + \"Query ready!\") # Actual", "dates collective[\"data\"][repo][\"commitTimestamps\"].sort() # Save earliest commit date firstdate = None", "> 0: firstdate = collective[\"data\"][repo][\"commitTimestamps\"][0] collective[\"data\"][repo][\"firstCommitAt\"] = firstdate del collective[\"data\"][repo][\"commitTimestamps\"]", "print(tab + \"Could not get pre-GitHub commits for '%s'\" %", "repo in allData[\"data\"].keys(): if allData[\"data\"][repo][\"firstCommitAt\"]: print(tab + \"Already recorded data", "% (pageNum)) print(tab + \"Modifying query...\") newquery = gitquery +", "json.dumps({'query': newquery}) print(tab + \"Query ready!\") # Actual query exchange", "\"Get creation date and default branch\") print(tab + \"Modifying query...\")", "query_commits_in2 = \"/repos/OWNNAME/REPONAME/commits?per_page=100\" # Retrieve authorization token authhead = helpers.get_gitauth()", "through internal repos print(\"Gathering data across multiple paginated queries...\") collective", "commit in outObj[\"data\"]: collective[\"data\"][repo][\"commitTimestamps\"].append(commit[\"commit\"][\"committer\"][\"date\"]) # Paginate if needed hasNext =", "None) continue # Update collective data collective[\"data\"][repo] = outObj[\"data\"][\"repository\"] #", "= re.sub('CREATETIME', collective[\"data\"][repo][\"createdAt\"], gitquery) print(tab + \"Query ready!\") # Actual", "outObj[\"data\"]: collective[\"data\"][repo][\"commitTimestamps\"].append(commit[\"commit\"][\"committer\"][\"date\"]) # Paginate if needed hasNext = (\"next\" in", "'%s'\" % (repo)) collective[\"data\"].pop(repo, None) continue # Update collective data", "# History doesn't change, only update new repos or those", "outObj = helpers.query_githubrest(authhead, gitquery) if outObj[\"errors\"]: print(tab + \"Could not", "commits for '%s'\" % (repo)) outObj[\"data\"] = [] # Update", "None) continue # Update collective data for commit in outObj[\"data\"]:", "repo list) dataObj = helpers.read_json(\"../github-data/labReposInfo.json\") # Populate repo list repolist", "data collective[\"data\"][repo] = outObj[\"data\"][\"repository\"] # Query 2 print(tab + \"Get", "query_commits_in = \"/repos/OWNNAME/REPONAME/commits?until=CREATETIME&per_page=100\" query_commits_in2 = \"/repos/OWNNAME/REPONAME/commits?per_page=100\" # Retrieve authorization token", "internal repos ...\") repolist = sorted(dataObj[\"data\"].keys()) print(\"Repo list complete. Found", "not complete '%s'\" % (repo)) collective[\"data\"].pop(repo, None) continue # Update", "gitquery = re.sub('REPONAME', repoSplit[1], gitquery) print(tab + \"Query ready!\") #", "if outObj[\"errors\"]: print(tab + \"Could not complete '%s'\" % (repo))", "paginated queries...\") collective = {u'data': {}} tab = \" \"", "%d\" % (pageNum)) repoSplit = repo.split(\"/\") # Query 1 print(tab", "% (repo)) collective[\"data\"].pop(repo, None) continue # Update collective data collective[\"data\"][repo]", "# Actual query exchange outObj = helpers.query_github(authhead, gitquery) if outObj[\"errors\"]:", "ready!\") # Actual query exchange outObj = helpers.query_githubrest(authhead, gitquery) if", "Combine new data with existing data if \"data\" not in", "re.sub('OWNNAME', repoSplit[0], query_commits_in) gitquery = re.sub('REPONAME', repoSplit[1], gitquery) gitquery =", "\"Already recorded data for '%s'\" % (repo)) continue pageNum =", "if outObj[\"errors\"]: print(tab + \"Could not get pre-GitHub commits for", "list) dataObj = helpers.read_json(\"../github-data/labReposInfo.json\") # Populate repo list repolist =", "= json.dumps(allData, indent=4, sort_keys=True) # Write output file print(\"\\nWriting file", "and default branch\") print(tab + \"Modifying query...\") newquery = re.sub('OWNNAME',", "= [] # Update collective data collective[\"data\"][repo][\"commitTimestamps\"] = [] for", "(to use as repo list) dataObj = helpers.read_json(\"../github-data/labReposInfo.json\") # Populate", "= \"../github-data/labRepos_CreationHistory.json\" allData = {} # Check for and read", "% (repo)) collective[\"data\"].pop(repo, None) continue # Update collective data for", "> 0 and collective[\"data\"][repo][\"commitTimestamps\"][0]: collective[\"data\"][repo][\"initBeforeGitHubRepo\"] = True else: print(tab +", "gitquery = re.sub('OWNNAME', repoSplit[0], query_commits_in) gitquery = re.sub('REPONAME', repoSplit[1], gitquery)", "exchange outObj = helpers.query_github(authhead, gitquery) if outObj[\"errors\"]: print(tab + \"Could", "continue # Update collective data collective[\"data\"][repo] = outObj[\"data\"][\"repository\"] # Query", "date and default branch\") print(tab + \"Modifying query...\") newquery =", "list repolist = [] print(\"Getting internal repos ...\") repolist =", "del collective[\"data\"][repo][\"commitTimestamps\"] print(\"'%s' Done!\" % (repo)) print(\"\\nCollective data gathering complete!\")", "file print(\"\\nWriting file '%s'\" % (datfilepath)) with open(datfilepath, \"w\") as", "re.sub('REPONAME', repoSplit[1], gitquery) gitquery = re.sub('CREATETIME', collective[\"data\"][repo][\"createdAt\"], gitquery) print(tab +", "% (repo)) print(tab + \"page %d\" % (pageNum)) repoSplit =", "repo info data file (to use as repo list) dataObj", "import re datfilepath = \"../github-data/labRepos_CreationHistory.json\" allData = {} # Check", "outObj) # Sort dates collective[\"data\"][repo][\"commitTimestamps\"].sort() # Save earliest commit date", "earliest commit date firstdate = None if len(collective[\"data\"][repo][\"commitTimestamps\"]) > 0:", "print(\"'%s' Done!\" % (repo)) print(\"\\nCollective data gathering complete!\") # Combine", "\"Modifying query...\") gitquery = re.sub('OWNNAME', repoSplit[0], query_commits_in) gitquery = re.sub('REPONAME',", "if len(collective[\"data\"][repo][\"commitTimestamps\"]) > 0 and collective[\"data\"][repo][\"commitTimestamps\"][0]: collective[\"data\"][repo][\"initBeforeGitHubRepo\"] = True else:", "helpers.query_githubrest(authhead, newquery) if outObj[\"errors\"]: print(tab + \"Could not complete '%s'\"", "= gitquery + \"&page=\" + str(pageNum) print(tab + \"Query ready!\")", "+ \"page %d\" % (pageNum)) print(tab + \"Modifying query...\") newquery", "% (pageNum)) repoSplit = repo.split(\"/\") # Query 1 print(tab +", "outObj[\"errors\"]: print(tab + \"Could not complete '%s'\" % (repo)) collective[\"data\"].pop(repo,", "= helpers.query_github(authhead, gitquery) if outObj[\"errors\"]: print(tab + \"Could not complete", "= (\"next\" in outObj) while hasNext: pageNum += 1 print(tab", "= collective[\"data\"][repo] allDataString = json.dumps(allData, indent=4, sort_keys=True) # Write output", "+ \"&page=\" + str(pageNum) print(tab + \"Query ready!\") # Actual", "existing data file allData = helpers.read_existing(datfilepath) # Read repo info", "print(\"Gathering data across multiple paginated queries...\") collective = {u'data': {}}", "those that had no previous commits if \"data\" in allData.keys()", "\"../github-data/labRepos_CreationHistory.json\" allData = {} # Check for and read existing", "+ \"Modifying query...\") gitquery = re.sub('OWNNAME', repoSplit[0], query_commits_in) gitquery =", "Actual query exchange outObj = helpers.query_githubrest(authhead, newquery) if outObj[\"errors\"]: print(tab", "# Write output file print(\"\\nWriting file '%s'\" % (datfilepath)) with", "\"Query ready!\") # Actual query exchange outObj = helpers.query_githubrest(authhead, newquery)", "indent=4, sort_keys=True) # Write output file print(\"\\nWriting file '%s'\" %", "or those that had no previous commits if \"data\" in", "commits found, getting full history\") collective[\"data\"][repo][\"initBeforeGitHubRepo\"] = False # Query", "%d\" % (pageNum)) print(tab + \"Modifying query...\") newquery = gitquery", "re datfilepath = \"../github-data/labRepos_CreationHistory.json\" allData = {} # Check for", "= re.sub('OWNNAME', repoSplit[0], query_commits_in2) gitquery = re.sub('REPONAME', repoSplit[1], gitquery) print(tab", "firstdate = collective[\"data\"][repo][\"commitTimestamps\"][0] collective[\"data\"][repo][\"firstCommitAt\"] = firstdate del collective[\"data\"][repo][\"commitTimestamps\"] print(\"'%s' Done!\"", "= helpers.read_json(\"../github-data/labReposInfo.json\") # Populate repo list repolist = [] print(\"Getting", "= {} for repo in collective[\"data\"].keys(): allData[\"data\"][repo] = collective[\"data\"][repo] allDataString", "no previous commits if \"data\" in allData.keys() and repo in", "1 print(tab + \"page %d\" % (pageNum)) print(tab + \"Modifying", "newquery}) print(tab + \"Query ready!\") # Actual query exchange outObj", "query...\") gitquery = re.sub('OWNNAME', repoSplit[0], query_commits_in2) gitquery = re.sub('REPONAME', repoSplit[1],", "Read pretty GraphQL query query_in = helpers.read_gql(\"../queries/repo-CreationDate.gql\") # Rest endpoint", "= sorted(dataObj[\"data\"].keys()) print(\"Repo list complete. Found %d repos.\" % (len(repolist)))", "doesn't change, only update new repos or those that had", "new repos or those that had no previous commits if", "[] for commit in outObj[\"data\"]: collective[\"data\"][repo][\"commitTimestamps\"].append(commit[\"commit\"][\"committer\"][\"date\"]) # If no pre-GitHub", "allData.keys() and repo in allData[\"data\"].keys(): if allData[\"data\"][repo][\"firstCommitAt\"]: print(tab + \"Already", "repos ...\") repolist = sorted(dataObj[\"data\"].keys()) print(\"Repo list complete. Found %d", "% (repo)) continue pageNum = 1 print(\"\\n'%s'\" % (repo)) print(tab", "commit in outObj[\"data\"]: collective[\"data\"][repo][\"commitTimestamps\"].append(commit[\"commit\"][\"committer\"][\"date\"]) hasNext = (\"next\" in outObj) #", "%d repos.\" % (len(repolist))) # Read pretty GraphQL query query_in", "newquery = re.sub('REPONAME', repoSplit[1], newquery) gitquery = json.dumps({'query': newquery}) print(tab", "re.sub('REPONAME', repoSplit[1], newquery) gitquery = json.dumps({'query': newquery}) print(tab + \"Query", "Update collective data for commit in outObj[\"data\"]: collective[\"data\"][repo][\"commitTimestamps\"].append(commit[\"commit\"][\"committer\"][\"date\"]) # Paginate", "collective[\"data\"][repo][\"initBeforeGitHubRepo\"] = False # Query 3 print(tab + \"Modifying query...\")", "and read existing data file allData = helpers.read_existing(datfilepath) # Read", "Retrieve authorization token authhead = helpers.get_gitauth() # Iterate through internal", "# Query 1 print(tab + \"Get creation date and default", "print(tab + \"Already recorded data for '%s'\" % (repo)) continue", "data gathering complete!\") # Combine new data with existing data", "Query 1 print(tab + \"Get creation date and default branch\")", "\"Query ready!\") # Actual query exchange outObj = helpers.query_githubrest(authhead, gitquery)", "info data file (to use as repo list) dataObj =", "= helpers.get_gitauth() # Iterate through internal repos print(\"Gathering data across", "newquery = re.sub('OWNNAME', repoSplit[0], query_in) newquery = re.sub('REPONAME', repoSplit[1], newquery)", "+ \"Could not complete '%s'\" % (repo)) collective[\"data\"].pop(repo, None) continue", "Rest endpoint query query_commits_in = \"/repos/OWNNAME/REPONAME/commits?until=CREATETIME&per_page=100\" query_commits_in2 = \"/repos/OWNNAME/REPONAME/commits?per_page=100\" #", "3 print(tab + \"Modifying query...\") gitquery = re.sub('OWNNAME', repoSplit[0], query_commits_in2)", "Update collective data collective[\"data\"][repo][\"commitTimestamps\"] = [] for commit in outObj[\"data\"]:", "in collective[\"data\"].keys(): allData[\"data\"][repo] = collective[\"data\"][repo] allDataString = json.dumps(allData, indent=4, sort_keys=True)", "\"page %d\" % (pageNum)) repoSplit = repo.split(\"/\") # Query 1", "collective[\"data\"][repo][\"commitTimestamps\"].append(commit[\"commit\"][\"committer\"][\"date\"]) # Paginate if needed hasNext = (\"next\" in outObj)", "+ \"Modifying query...\") newquery = re.sub('OWNNAME', repoSplit[0], query_in) newquery =", "output file print(\"\\nWriting file '%s'\" % (datfilepath)) with open(datfilepath, \"w\")", "Update collective data collective[\"data\"][repo] = outObj[\"data\"][\"repository\"] # Query 2 print(tab", "not in allData.keys(): allData[\"data\"] = {} for repo in collective[\"data\"].keys():", "\"Modifying query...\") newquery = gitquery + \"&page=\" + str(pageNum) print(tab", "print(tab + \"Could not complete '%s'\" % (repo)) collective[\"data\"].pop(repo, None)", "endpoint query query_commits_in = \"/repos/OWNNAME/REPONAME/commits?until=CREATETIME&per_page=100\" query_commits_in2 = \"/repos/OWNNAME/REPONAME/commits?per_page=100\" # Retrieve", "for '%s'\" % (repo)) outObj[\"data\"] = [] # Update collective", "= re.sub('OWNNAME', repoSplit[0], query_in) newquery = re.sub('REPONAME', repoSplit[1], newquery) gitquery", "new data with existing data if \"data\" not in allData.keys():", "repo.split(\"/\") # Query 1 print(tab + \"Get creation date and", "Paginate if needed hasNext = (\"next\" in outObj) while hasNext:", "helpers import json import re datfilepath = \"../github-data/labRepos_CreationHistory.json\" allData =", "gitquery) if outObj[\"errors\"]: print(tab + \"Could not complete '%s'\" %", "print(tab + \"Get pre-GitHub commit timestamps\") print(tab + \"Modifying query...\")", "print(\"\\nCollective data gathering complete!\") # Combine new data with existing", "= repo.split(\"/\") # Query 1 print(tab + \"Get creation date", "data collective[\"data\"][repo][\"commitTimestamps\"] = [] for commit in outObj[\"data\"]: collective[\"data\"][repo][\"commitTimestamps\"].append(commit[\"commit\"][\"committer\"][\"date\"]) #", "collective[\"data\"][repo][\"commitTimestamps\"] = [] for commit in outObj[\"data\"]: collective[\"data\"][repo][\"commitTimestamps\"].append(commit[\"commit\"][\"committer\"][\"date\"]) # If", "complete '%s'\" % (repo)) collective[\"data\"].pop(repo, None) continue # Update collective", "token authhead = helpers.get_gitauth() # Iterate through internal repos print(\"Gathering", "'%s'\" % (repo)) outObj[\"data\"] = [] # Update collective data", "data if \"data\" not in allData.keys(): allData[\"data\"] = {} for", "(repo)) print(tab + \"page %d\" % (pageNum)) repoSplit = repo.split(\"/\")", "complete. Found %d repos.\" % (len(repolist))) # Read pretty GraphQL", "re.sub('REPONAME', repoSplit[1], gitquery) print(tab + \"Query ready!\") # Actual query", "the greater commit history if len(collective[\"data\"][repo][\"commitTimestamps\"]) > 0 and collective[\"data\"][repo][\"commitTimestamps\"][0]:", "= \"/repos/OWNNAME/REPONAME/commits?per_page=100\" # Retrieve authorization token authhead = helpers.get_gitauth() #", "print(\"Getting internal repos ...\") repolist = sorted(dataObj[\"data\"].keys()) print(\"Repo list complete.", "= {u'data': {}} tab = \" \" for repo in", "collective[\"data\"].pop(repo, None) continue # Update collective data collective[\"data\"][repo] = outObj[\"data\"][\"repository\"]", "allData[\"data\"][repo] = collective[\"data\"][repo] allDataString = json.dumps(allData, indent=4, sort_keys=True) # Write", "across multiple paginated queries...\") collective = {u'data': {}} tab =", "(repo)) outObj[\"data\"] = [] # Update collective data collective[\"data\"][repo][\"commitTimestamps\"] =", "len(collective[\"data\"][repo][\"commitTimestamps\"]) > 0: firstdate = collective[\"data\"][repo][\"commitTimestamps\"][0] collective[\"data\"][repo][\"firstCommitAt\"] = firstdate del", "collective data for commit in outObj[\"data\"]: collective[\"data\"][repo][\"commitTimestamps\"].append(commit[\"commit\"][\"committer\"][\"date\"]) # Paginate if", "import helpers import json import re datfilepath = \"../github-data/labRepos_CreationHistory.json\" allData", "\"No pre-GitHub commits found, getting full history\") collective[\"data\"][repo][\"initBeforeGitHubRepo\"] = False", "helpers.read_existing(datfilepath) # Read repo info data file (to use as", "# Save earliest commit date firstdate = None if len(collective[\"data\"][repo][\"commitTimestamps\"])", "gitquery = re.sub('REPONAME', repoSplit[1], gitquery) gitquery = re.sub('CREATETIME', collective[\"data\"][repo][\"createdAt\"], gitquery)", "repoSplit[1], gitquery) print(tab + \"Query ready!\") # Actual query exchange", "continue # Update collective data for commit in outObj[\"data\"]: collective[\"data\"][repo][\"commitTimestamps\"].append(commit[\"commit\"][\"committer\"][\"date\"])", "(len(repolist))) # Read pretty GraphQL query query_in = helpers.read_gql(\"../queries/repo-CreationDate.gql\") #", "query_in) newquery = re.sub('REPONAME', repoSplit[1], newquery) gitquery = json.dumps({'query': newquery})", "outObj) while hasNext: pageNum += 1 print(tab + \"page %d\"", "for commit in outObj[\"data\"]: collective[\"data\"][repo][\"commitTimestamps\"].append(commit[\"commit\"][\"committer\"][\"date\"]) # If no pre-GitHub commits,", "allData[\"data\"].keys(): if allData[\"data\"][repo][\"firstCommitAt\"]: print(tab + \"Already recorded data for '%s'\"", "# Query 3 print(tab + \"Modifying query...\") gitquery = re.sub('OWNNAME',", "\"page %d\" % (pageNum)) print(tab + \"Modifying query...\") newquery =", "# Iterate through internal repos print(\"Gathering data across multiple paginated", "= re.sub('OWNNAME', repoSplit[0], query_commits_in) gitquery = re.sub('REPONAME', repoSplit[1], gitquery) gitquery", "+ \"Query ready!\") # Actual query exchange outObj = helpers.query_github(authhead,", "print(tab + \"Modifying query...\") gitquery = re.sub('OWNNAME', repoSplit[0], query_commits_in2) gitquery", "outObj[\"data\"] = [] # Update collective data collective[\"data\"][repo][\"commitTimestamps\"] = []", "(repo)) print(\"\\nCollective data gathering complete!\") # Combine new data with", "exchange outObj = helpers.query_githubrest(authhead, gitquery) if outObj[\"errors\"]: print(tab + \"Could", "# Combine new data with existing data if \"data\" not", "in outObj) while hasNext: pageNum += 1 print(tab + \"page", "# If no pre-GitHub commits, check the greater commit history", "data file allData = helpers.read_existing(datfilepath) # Read repo info data", "repoSplit[0], query_in) newquery = re.sub('REPONAME', repoSplit[1], newquery) gitquery = json.dumps({'query':", "Query 2 print(tab + \"Get pre-GitHub commit timestamps\") print(tab +", "check the greater commit history if len(collective[\"data\"][repo][\"commitTimestamps\"]) > 0 and", "repos print(\"Gathering data across multiple paginated queries...\") collective = {u'data':", "recorded data for '%s'\" % (repo)) continue pageNum = 1", "+ \"Get creation date and default branch\") print(tab + \"Modifying", "repolist: # History doesn't change, only update new repos or", "no pre-GitHub commits, check the greater commit history if len(collective[\"data\"][repo][\"commitTimestamps\"])", "print(tab + \"page %d\" % (pageNum)) print(tab + \"Modifying query...\")", "commit date firstdate = None if len(collective[\"data\"][repo][\"commitTimestamps\"]) > 0: firstdate", "1 print(\"\\n'%s'\" % (repo)) print(tab + \"page %d\" % (pageNum))", "= helpers.read_existing(datfilepath) # Read repo info data file (to use", "in outObj) # Sort dates collective[\"data\"][repo][\"commitTimestamps\"].sort() # Save earliest commit", "ready!\") # Actual query exchange outObj = helpers.query_github(authhead, gitquery) if", "# Read repo info data file (to use as repo", "print(tab + \"Modifying query...\") gitquery = re.sub('OWNNAME', repoSplit[0], query_commits_in) gitquery", "= False # Query 3 print(tab + \"Modifying query...\") gitquery", "newquery) gitquery = json.dumps({'query': newquery}) print(tab + \"Query ready!\") #", "allDataString = json.dumps(allData, indent=4, sort_keys=True) # Write output file print(\"\\nWriting", "+ \"page %d\" % (pageNum)) repoSplit = repo.split(\"/\") # Query", "= None if len(collective[\"data\"][repo][\"commitTimestamps\"]) > 0: firstdate = collective[\"data\"][repo][\"commitTimestamps\"][0] collective[\"data\"][repo][\"firstCommitAt\"]", "newquery) if outObj[\"errors\"]: print(tab + \"Could not complete '%s'\" %", "+ \"Modifying query...\") gitquery = re.sub('OWNNAME', repoSplit[0], query_commits_in2) gitquery =", "= re.sub('REPONAME', repoSplit[1], newquery) gitquery = json.dumps({'query': newquery}) print(tab +", "allData[\"data\"][repo][\"firstCommitAt\"]: print(tab + \"Already recorded data for '%s'\" % (repo))", "+ \"Already recorded data for '%s'\" % (repo)) continue pageNum", "found, getting full history\") collective[\"data\"][repo][\"initBeforeGitHubRepo\"] = False # Query 3", "\" \" for repo in repolist: # History doesn't change,", "query_in = helpers.read_gql(\"../queries/repo-CreationDate.gql\") # Rest endpoint query query_commits_in = \"/repos/OWNNAME/REPONAME/commits?until=CREATETIME&per_page=100\"", "allData = {} # Check for and read existing data", "+ str(pageNum) print(tab + \"Query ready!\") # Actual query exchange", "(pageNum)) repoSplit = repo.split(\"/\") # Query 1 print(tab + \"Get", "collective[\"data\"][repo] = outObj[\"data\"][\"repository\"] # Query 2 print(tab + \"Get pre-GitHub", "datfilepath = \"../github-data/labRepos_CreationHistory.json\" allData = {} # Check for and", "= helpers.read_gql(\"../queries/repo-CreationDate.gql\") # Rest endpoint query query_commits_in = \"/repos/OWNNAME/REPONAME/commits?until=CREATETIME&per_page=100\" query_commits_in2", "for '%s'\" % (repo)) continue pageNum = 1 print(\"\\n'%s'\" %", "else: print(tab + \"No pre-GitHub commits found, getting full history\")", "query...\") newquery = re.sub('OWNNAME', repoSplit[0], query_in) newquery = re.sub('REPONAME', repoSplit[1],", "existing data if \"data\" not in allData.keys(): allData[\"data\"] = {}", "if allData[\"data\"][repo][\"firstCommitAt\"]: print(tab + \"Already recorded data for '%s'\" %", "Found %d repos.\" % (len(repolist))) # Read pretty GraphQL query" ]
[ "Bool.parse_std(\"input.txt\") expr = expr[\"main_expr\"] expr = Bool.simplify(expr) expr = Bool.nne(expr)", "sys.path.append(\"../../include\") import PyBool_public_interface as Bool if __name__ == \"__main__\": expr", "expr = expr[\"main_expr\"] expr = Bool.simplify(expr) expr = Bool.nne(expr) print(Bool.print_expr(expr))", "== \"__main__\": expr = Bool.parse_std(\"input.txt\") expr = expr[\"main_expr\"] expr =", "Bool if __name__ == \"__main__\": expr = Bool.parse_std(\"input.txt\") expr =", "<gh_stars>0 #! /usr/bin/env python2.7 from __future__ import print_function import sys", "as Bool if __name__ == \"__main__\": expr = Bool.parse_std(\"input.txt\") expr", "__name__ == \"__main__\": expr = Bool.parse_std(\"input.txt\") expr = expr[\"main_expr\"] expr", "= Bool.parse_std(\"input.txt\") expr = expr[\"main_expr\"] expr = Bool.simplify(expr) expr =", "sys sys.path.append(\"../../include\") import PyBool_public_interface as Bool if __name__ == \"__main__\":", "print_function import sys sys.path.append(\"../../include\") import PyBool_public_interface as Bool if __name__", "if __name__ == \"__main__\": expr = Bool.parse_std(\"input.txt\") expr = expr[\"main_expr\"]", "\"__main__\": expr = Bool.parse_std(\"input.txt\") expr = expr[\"main_expr\"] expr = Bool.simplify(expr)", "from __future__ import print_function import sys sys.path.append(\"../../include\") import PyBool_public_interface as", "import print_function import sys sys.path.append(\"../../include\") import PyBool_public_interface as Bool if", "import sys sys.path.append(\"../../include\") import PyBool_public_interface as Bool if __name__ ==", "/usr/bin/env python2.7 from __future__ import print_function import sys sys.path.append(\"../../include\") import", "#! /usr/bin/env python2.7 from __future__ import print_function import sys sys.path.append(\"../../include\")", "__future__ import print_function import sys sys.path.append(\"../../include\") import PyBool_public_interface as Bool", "python2.7 from __future__ import print_function import sys sys.path.append(\"../../include\") import PyBool_public_interface", "PyBool_public_interface as Bool if __name__ == \"__main__\": expr = Bool.parse_std(\"input.txt\")", "expr = Bool.parse_std(\"input.txt\") expr = expr[\"main_expr\"] expr = Bool.simplify(expr) expr", "import PyBool_public_interface as Bool if __name__ == \"__main__\": expr =" ]
[ "str(d.second) between = str(\":\")''' '''def __time(infos): time = datetime.now() day", "in col: call=cal+1 return call #def yes_y(): # rupe =", "\") da += data print(data) da = int(da) file.write(da) try:", "Entry(dframe,font=(\"arial\",16, \"bold\"),bd=5,fg=\"white\",bg=\"black\",textvariable=semail,insertwidth=1).pack(side=LEFT) label3 = Label(dframe,font=(\"arial\",16,\"bold\"),fg=\"white\",bg=\"black\",text=\"sender_password\", relief=SUNKEN).pack(side=LEFT) entry3= Entry(dframe,font=(\"arial\",16,\"bold\"),fg=\"white\",textvariable=spassword,insertwidth=1,relief=SUNKEN).pack() dialog.mainloop() #btnEmail", "second = time.second year = time.year minute = time.minute #setting", "shrting.get() d = pant.get() e = sari.get() f = order_info.get()", "* from random import randint root = Tk() root.geometry(\"1600x800+0+0\") root.title(\"Suman_dai_ko_DHOKAN\")", "insertwidth=1, justify=\"left\",bd=10).grid(row=6,column=0) lablsari=Label(f1,font=(\"arial\", 16, \"bold\"), bg=\"powder blue\",text=\"sari mm:\", fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=5,column=1) sarix=Entry(f1,", "order_info = IntVar() delivery_report = IntVar() daily_info = IntVar() sales", "= IntVar() total_bank = IntVar() bank_deposite = IntVar() bank_withdraw =", "k = total_bank.get() l = bank_deposite.get() m = bank_withdraw.get() n", "file.close() #after wards set the total from here total.set #++++++++++++++++++++++++++++++Varibales_inset+++++++++++++++++++++++++++++++++", "= Frame(win1, width=100, height=100,bg=\"RoyalBlue4\",relief=GROOVE) others_info.pack(side=BOTTOM) all_info = Frame(win1, width=50, height=50,bg=\"RoyalBlue4\",relief=RAISED)", "\"/root/Desktop/Desktop/python/projects/prj1_Botik/1.jpg\" #root.ima = Image.open(img) #Label (root,bg=\"white\",width=120,height=120, image=ima).pack() bill_in = StringVar()", "font=(\"arial\",16,\"bold\"),bg=\"powder blue\",text=\"monthly:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=5,column=2) monthly=StringVar() monthx=Entry(f1,font=(\"arial\",16,\"bold\"),show=\"blank\",bg=\"black\",textvariable=monthly,insertwidth=1,fg=\"white\",bd=10).grid(row=6,column=2) lbltotal=Label(f1, font=(\"arial\", 16, \"bold\"),bg=\"powder blue\",text=\"Total:\",fg=\"black\").grid(row=7,column=2) totalx=Entry(f1,", "files = {\"a\":\"\", \"b\":\"\",\"c\":\"\",\"d\":\"\",\"e\":\"\",\"f\":\"\",\"g\":\"\",\"h\":\"\",\"i\":\"\",\"j\":\"\" ,\"k\":\"\",\"l\":\"\",\"m\":\"\",\"n\":\"\",\"o\":\"\",\"p\":\"\",\"q\":\"\",\"r\":\"\",\"s\":\"\"}''' #files = list(files) '''for data", "font(\"arial\",5,\"bold\"), # text=\"rupen\",bg=\"powder blue\", command=rupen).grid(row=3,column=5) #def function(): # pass(): #", "coat_mm = coat.get() order_mm = order.get() total_mm = total.get() time", "= Frame(win1, width=600, height=700,bg=\"RoyalBlue4\",relief=GROOVE) my_info.pack(side=LEFT) customer_info = Frame(win1, width=600, height=500,bg=\"RoyalBlue4\",", "= IntVar() daily_cash = IntVar() cus_name = IntVar() cus_no =", "Label(win1,font=(\"arial\", 20,\"italic\"),width=300, height=168,bg=\"black\",fg=\"white\", text=image,relief=FLAT).pack() win1.mainloop()''' #=============================getting all the infos ========================", "print(reading) file.close() #db.insert({\"name\":\"<NAME>\"}) name = Query() #db(name.type == \"changed\") d", "#of the system on the support in teh main loop", "pass main(): # root.mainloop() #for the revies of the follow", "with name {}\".format(file))''' #creating the filenames with append =1 if", "datetime() self.hour = now.hour self.minute = now.minute self.second = now.second", "* 60 * 60 minuteSec = 60 * 60 files", "stock_full = IntVar() shrting = IntVar() pant = IntVar() sari", "command=btnEqualsInput).grid(row=5,column=2) #btn2=Button(f2,padx=16,pady=16,bd=8,fg=\"black\",text=\"2\",bg=\"dim gray\", command=lambda: btnClick(2)).grid(row=5,column=3) division=Button(f2,padx=16,pady=16,bd=8,fg=\"black\", text=\"/\", bg=\"dim gray\", command=lambda:", "= shirt.get() pant_mm = pant.get() sale_mm = sale.get() buy_mm =", "before the #60 hours #changing all the formats to the", "for the #calculation #first calculating seconds in one day that", "Entry(f2,font=(\"arial\", 20,\"bold\"), textvariable=text_Input, bd=30, insertwidth=4, bg=\"dark slate blue\",fg=\"white\", justify=\"right\").grid(columnspan=4) btn7=Button(f2,padx=16,pady=16,bd=8,", "btnEquals=Button(f2,padx=16,pady=16,fg=\"black\",bd=8,text=\"=\",bg=\"dim gray\", font=(\"arial\", 20,\"bold\"), command=btnEqualsInput).grid(row=5,column=2) #btn2=Button(f2,padx=16,pady=16,bd=8,fg=\"black\",text=\"2\",bg=\"dim gray\", command=lambda: btnClick(2)).grid(row=5,column=3) division=Button(f2,padx=16,pady=16,bd=8,fg=\"black\",", "pantx=Entry(f1,font=(\"arial\",16, \"bold\"), textvariable=pant, insertwidth=1, bd=10,bg=\"black\",fg=\"white\", justify=\"left\").grid(row=2,column=1) sales=Label(f1,font=(\"arial\",16, \"bold\"), text=\"sales_total:\",bg=\"powder blue\",fg=\"black\",anchor=\"w\",bd=8,relief=GROOVE).grid(row=1,column=2)", "in db: data = open(\"/records.txt\",\"wb\") #with open(\"/records.txt\",\"wb\") as file: #pickle.dump(item,", "'''def malware_activate(): global cmd_active if \"rupen\" in cmd_active: if \"rupen\"", "\"bold\"),textvariable=out, bd=8,fg=\"white\",bg=\"black\",insertwidth=1).grid(row=8,column=1) ordering=Label(f1,font=(\"arial\",16,\"bold\"),bg=\"powder blue\",text=\"order_info:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=9,column=0) orderx=Entry(f1,font=(\"arial\",16,\"bold\"),insertwidth=1, textvariable=order,bd=8,fg=\"white\",bg=\"black\").grid(row=10,column=0) lblcustomer=Label(f1,font=(\"arial\",16,\"bold\"),bg=\"powder blue\",text=\"cus_name:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=9,column=1) no=Entry(f1,font=(\"arial\",16, \"bold\"),bd=8,bg=\"black\",fg=\"white\",insertwidth=1,", "text=image,relief=FLAT).pack() win1.mainloop()''' #=============================getting all the infos ======================== def _price_inputs(): win2", "= IntVar() due_amount = IntVar() order_info = IntVar() daily_cash =", "print(data) da = int(da) file.write(da) try: file = open(\"/records.txt\", \"r\")", "20,\"italic\"),bg=\"powder blue\",fg=\"green\",text=\"INPUT THE PRICES\",relief=GROOVE).pack() win2.mainloop() ###########################sending emails############################ def __send_email(): '''import", "= open(\"{}\".format(file_name),\"w+\") totalx = shirt_mm+pant_mm+sale_mm+buy_mm+deposite_mm+withdraw_mm+coat_mm+order_mm file.write(\"Total:-{}\".format(totalx)) file.write(\"shirt:-{}\".format(shirt_mm)) file.write(\"pant_mm:-{}\".format(pant_mm)) file.write(\"sale_mm:-{}\".format(sale_mm)) file.write(\"buy_mm:-{}\".format(buy_mm))", "no=\"\" Tops = Frame(root, width=1600 ,height=50,bg=\"goldenrod4\", relief=RIDGE) Tops.pack(side=TOP) f1 =", "= Label(Tops, font=(\"arial\",60, \"italic bold\"),text=\"Botique Management Systewm\",fg=\"white\", bg=\"dark slate blue\",", "file_name = \"r.txt\" if os.path.isfile(file_name): expand = 1 while True:", "win2.mainloop() ###########################sending emails############################ def __send_email(): '''import smtplib gmail = smtplib.SMTP(\"smtp.gmail.com\",", "that will be easy for the #calculation #first calculating seconds", "break if item != file: #item = str(item) file.write(\"%s\" %(item))", "relief=RIDGE) lblInfo.pack() lblInfo = Label(Tops, font=(\"arial\",30, \"bold\"),text=localtime,fg=\"white\",bg=\"black\", bd=10, anchor=\"w\", relief=RIDGE)", "= 300,height = 700,bg=\"dark slate blue\",relief=SUNKEN) f2.pack(side=RIGHT) #f3= Frame(root,width=1600,height=300,fg=\"blue\", bg=\"powder", "\"bold\"),bd=5,fg=\"white\",bg=\"black\",textvariable=semail,insertwidth=1).pack(side=LEFT) label3 = Label(dframe,font=(\"arial\",16,\"bold\"),fg=\"white\",bg=\"black\",text=\"sender_password\", relief=SUNKEN).pack(side=LEFT) entry3= Entry(dframe,font=(\"arial\",16,\"bold\"),fg=\"white\",textvariable=spassword,insertwidth=1,relief=SUNKEN).pack() dialog.mainloop() #btnEmail =", "= os.getcwd() print(DIR) lblInfo = Label(Tops, font=(\"arial\",60, \"italic\"),text=current_dir,fg=\"black\",bg=\"powder blue\",bd=10, anchor=\"W\")", "#creating the filenames with append =1 if the name already", "gray\", command=lambda: btnClick(2)).grid(row=4,column=1) btn1=Button(f2,padx=16,pady=16,bd=8,text=\"1\",font=(\"arial\", 20, \"bold\") ,bg=\"dim gray\", command=lambda: btnClick(1)).grid(row=4,column=2)", "\"cus_name\":\"rupen\"}) #def no_y(): # lis = db.all() ################Info=============== lblInfo =", "16, \"bold\"), textvariable=buy, insertwidth=1, bd=10,bg=\"black\", fg=\"white\", justify=\"left\").grid(row=4,column=0) Bank_Total=Label(f1,font=(\"arial\",16,\"bold\"),text=\"Bank_Deposite: \", bg=\"powder", "#img = \"/root/Desktop/Desktop/python/projects/prj1_Botik/1.jpg\" #root.ima = Image.open(img) #Label (root,bg=\"white\",width=120,height=120, image=ima).pack() bill_in", "= time.year minute = time.minute #setting the filename using the", "= Entry(dframe,font=(\"arial\",16, \"bold\"),bd=5,fg=\"white\",bg=\"black\",textvariable=semail,insertwidth=1).pack(side=LEFT) label3 = Label(dframe,font=(\"arial\",16,\"bold\"),fg=\"white\",bg=\"black\",text=\"sender_password\", relief=SUNKEN).pack(side=LEFT) entry3= Entry(dframe,font=(\"arial\",16,\"bold\"),fg=\"white\",textvariable=spassword,insertwidth=1,relief=SUNKEN).pack() dialog.mainloop()", "= \"/root/Desktop/Desktop/python/projects/prj1_Botik/1.jpg\" #root.ima = Image.open(img) #Label (root,bg=\"white\",width=120,height=120, image=ima).pack() bill_in =", "yes=Button(root,padx=16,pady=16,font=(\"arial\",12, \"bold\"),text=\"Done\",bd=8,bg=\"black\", fg=\"white\", command=_calculation(),relief=RAISED).pack(side=RIGHT) panting=Label(f1,font=(\"arial\",20, \"bold\"), text=\"pant_mm:\", bg=\"powder blue\",fg=\"black\",anchor=\"w\",relief=GROOVE).grid(row=1,column=1) pantx=Entry(f1,font=(\"arial\",16,", "same of the tkinter in the main function of the", "employx= Entry(f1,font=(\"arial\", 16,\"bold\"),textvariable=employee,insertwidth=1,bg=\"black\",fg=\"white\",bd=10).grid(row=10,column=2) ###############################database for the project###################### '''def __database(): db", "daysec hourSec = 60 * 60 * 60 minuteSec =", "\"bold\"),fg=\"black\",bg=\"powder blue\",text=\"Bank_Withdraw\", anchor=\"e\",relief=GROOVE).grid(row=3,column=2) withdrawx=Entry(f1,font=(\"arial\",16, \"bold\"),bd=10, fg=\"white\",bg=\"black\", textvariable=withdraw, insertwidth=1).grid(row=4,column=2) coating=Label(f1, font=(\"arial\",", "\"\" for data in files: if len(data) != 0: print(\"this", "in range(1): print(db) files = list(files) file = open(\"/file.txt\", \"wb\")", "pass(): # pass main(): # root.mainloop() #for the revies of", "= daysec * 30 daySec = daysec hourSec = 60", "list(files) '''for data in files: if len(data) != 0: print(data)'''", "textvariable=rand, bd=10,insertwidth=4,fg=\"white\",bg=\"black\", justify = \"left\") b.grid(row=0,column=1) #img = \"/root/Desktop/Desktop/python/projects/prj1_Botik/1.jpg\" #root.ima", "fg=\"black\", font=(\"arial\",20,\"bold\"), text=\"8\",bg=\"dim gray\", command=lambda: btnClick(8)).grid(row=2,column=1) btn9=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"), text=\"9\",bg=\"dim", "fg=\"white\",textvariable=sari, insertwidth=1).grid(row=6,column=1) buying=Label(f1,font=(\"arial\", 16, \"bold\"), bg=\"powder blue\",text=\"buy_info:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=7,column=0) buyx=Entry(f1,font=(\"arial\",16, \"bold\"),bd=8, fg=\"white\",bg=\"black\",textvariable=buy,insertwidth=1).grid(row=8,column=0)", "command=rupen).grid(row=3,column=5) #def function(): # pass(): # pass main(): # root.mainloop()", "#changing all the formats to the seconds that will be", "_price_inputs(): win2 = Toplevel() win2.title(\"This is going to the section", "text=\"your_email\").pack(side=LEFT) entry1 = Entry(dframe, font=(\"arial\",16,\"bold\"), fg=\"white\",bg=\"black\", textvariable=email,insertwidth=1,bd=5).pack(side=RIGHT) label1 = Label(dframe,", "btnru = Button(root, font=(\"arial 20 bold\"),bd=20, bg=\"black\",fg=\"white\",text=\"click\",command=ano_win1,relief=GROOVE).pack(side=BOTTOM) #fucking mazing yr", "rand = StringVar() #lblReference = Label(f1,font=(\"arial\", 16,\"bold\"), text=\"Reference\",bd=16,fg=\"red\",bg=\"red\",anchor=\"w\",relief=RIDGE).grid(row=0,column=0) #txtReference=Entry(f1,font=(\"arial\", 16,", "font=(\"arial\",20,\"bold\"),text=\"4\", bg=\"dim gray\", command=lambda: btnClick(4)).grid(row=3,column=0) btn5=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"),text=\"5\", bg=\"dim gray\",", "lblInfo.pack() #DIR = dir #return dir \"\"\" #randomBtn=Button(f1,pady=16,padx=16,bd=8,bg=\"powder blue\", text=\"C_dir\",", "# rupe.title(\"this is second window\") # return #def no_y(): #nos", "= order_info.get() g = delivery_report.get() h = daily_info.get() i =", "MESSAGE\" gmail.sendmail(\"your email adress\", \"the\") gmail.quit()''' dialog = Tk() dialog.title(\"Send", "name:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=9,column=2) employx= Entry(f1,font=(\"arial\", 16,\"bold\"),textvariable=employee,insertwidth=1,bg=\"black\",fg=\"white\",bd=10).grid(row=10,column=2) ###############################database for the project###################### '''def __database():", "lblInfo = Label(Tops, font=(\"arial\",60, \"italic\"),text=current_dir,fg=\"black\",bg=\"powder blue\",bd=10, anchor=\"W\") lblInfo.pack() #DIR =", "#file = open(\"{}\".format(new_file_name), \"w+\") continue else: file_name = open(new_file_name, \"w+\")", "\",bg=\"powder blue\",fg=\"black\", anchor=\"e\", relief=GROOVE).grid(row=3,column=0) buyx=Entry(f1,font=(\"arial\", 16, \"bold\"), textvariable=buy, insertwidth=1, bd=10,bg=\"black\",", "16, \"bold\"), bg=\"black\",bd=10, fg=\"white\",textvariable=sari, insertwidth=1).grid(row=6,column=1) buying=Label(f1,font=(\"arial\", 16, \"bold\"), bg=\"powder blue\",text=\"buy_info:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=7,column=0)", "\"bold\"), text=\"Shirting:\",bg=\"powder blue\", fg=\"black\",anchor=\"w\",relief=GROOVE).grid(row=1,column=0) shirts=Entry(f1,font=(\"arial\", 16, \"italic\"), bd=10, textvariable=shirt, insertwidth=1,bg=\"black\",fg=\"white\",", "= now.minute self.second = now.second self.year = now.year self.month =", "f = order_info.get() g = delivery_report.get() h = daily_info.get() i", "as bill number .get var bill = bill_in.get() billo =", "stock_full.get() c = shrting.get() d = pant.get() e = sari.get()", "image = image.set(imageloc) return image #image = Image.open(\"/root/Desktop/Desktop/anonymous/5.png\") imae =", "record_time if self.hour == self.record_timeD: print(\"the time for the product", "insertwidth=1).grid(row=4,column=2) coating=Label(f1, font=(\"arial\", 16, \"bold\"),text=\"coat_mm:\", bg=\"powder blue\",fg=\"black\",anchor=\"e\").grid(row=5,column=0) coatx=Entry(f1, font=(\"arial\", 16,", "16, \"bold\"),bg=\"powder blue\",text=\"Total:\",fg=\"black\").grid(row=7,column=2) totalx=Entry(f1, font=(\"arial\", 16, \"bold\"),bg=\"black\",textvariable=total,fg=\"white\",insertwidth=1,bd=10).grid(row=8,column=2) lblemployee = Label(f1,font=(\"arial\",", "\"s\": \"\"} db.insert({\"total\": a }), db.insert({\"regrds\":\"reference\"}), db.insert({\"day_income\":\"billion\"}), db.insert({\"day_outgoing\":\"billout\"}), db.insert({\"bankdeposit\":\"bankdepo\"}), db.insert({\"full_stock\":\"stock\"}),", "#def yes_y(): # rupe = Toplevel(root) # rupe.title(\"this is second", "btnEqualsInput(): global operator sumup=str(eval(operator)) text_Input.set(sumup) operator=\"\" def bill_entry(): global bill_in", "range(5): if os.path.isfile(i): pass else: file = open(\"{}.txt\".format(i+1), \"w+\") created", "win2.title(\"This is going to the section for the price inputs\")", "file_name = \"fil.txt\" file = open(\"{}\".format(file_name),\"w+\") totalx = shirt_mm+pant_mm+sale_mm+buy_mm+deposite_mm+withdraw_mm+coat_mm+order_mm file.write(\"Total:-{}\".format(totalx))", "open(\"/records.txt\",\"w\") finally: pass check = os.path.isfile(\"/records.txt\") if check: for item", "rupe.title(\"this is second window\") # return #def no_y(): #nos =", "}), db.insert({\"regrds\":\"reference\"}), db.insert({\"day_income\":\"billion\"}), db.insert({\"day_outgoing\":\"billout\"}), db.insert({\"bankdeposit\":\"bankdepo\"}), db.insert({\"full_stock\":\"stock\"}), db.insert({\"shirt_mm\":\"shirt\"}), db.insert({\"bankwithdraw\":\"bankwith\"}), db.insert({\"pantmm\":\"pant\"}), db.insert({\"sarimm\":\"sari\"}),", "rupen(): global rupen rupen = rupen ronley = StringVar() '''def", "the follow in the sorry of the same of the", "bd=10,bg=\"black\",fg=\"white\", justify=\"left\").grid(row=2,column=1) sales=Label(f1,font=(\"arial\",16, \"bold\"), text=\"sales_total:\",bg=\"powder blue\",fg=\"black\",anchor=\"w\",bd=8,relief=GROOVE).grid(row=1,column=2) salex=Entry(f1,font=(\"arial\",16, \"bold\"),bg=\"black\",fg=\"white\",textvariable=sale,insertwidth=1,bd=10,justify=\"left\").grid(row=2,column=2) buying=Label(f1,font=(\"arial\",16, \"bold\"),", "minute = str(time.minute) #assuming the infos as the order taken", "\"\"\"def current_dir(): import os import sys DIR = os.getcwd() print(DIR)", "\"w+\") continue else: file_name = open(new_file_name, \"w+\") print(\"creating the file", "coll in col: call=cal+1 return call #def yes_y(): # rupe", "##this is will be easy now yearSec = daysec *", "= IntVar() sale = IntVar() buy = IntVar() deposite =", "gray\", command=lambda: btnClick(4)).grid(row=3,column=0) btn5=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"),text=\"5\", bg=\"dim gray\", command=lambda: btnClick(5)).grid(row=3,column=1)", "file: #pickle.dump(item, data) #file.close() #file1 = pickle.load(file) if len(item) ==", "minuteSec = 60 * 60 files = {\"a\":\"\", \"b\":\"\",\"c\":\"\",\"d\":\"\",\"e\":\"\",\"f\":\"\",\"g\":\"\",\"h\":\"\",\"i\":\"\",\"j\":\"\" ,\"k\":\"\",\"l\":\"\",\"m\":\"\",\"n\":\"\",\"o\":\"\",\"p\":\"\",\"q\":\"\",\"r\":\"\",\"s\":\"\"}'''", "+= 1 new_file_name = file_name.split(\".txt\")[0] + str(expand) + \".txt\" if", "db = TinyDB(\"/records.json\") #print(monthly) #print(b) #fuck = c.get() a =", "random import randint root = Tk() root.geometry(\"1600x800+0+0\") root.title(\"Suman_dai_ko_DHOKAN\") root.configure(bg=\"goldenrod4\") text_Input", "IntVar() bank_withdraw = IntVar() due_amount = IntVar() order_info = IntVar()", "as the order taken that will be notified before the", "the tkinter in the main function of the sollow #main()", "* 60 minuteSec = 60 * 60 files = {\"a\":\"\",", "Entry(f1,font=(\"arial\", 16,\"bold\"),textvariable=employee,insertwidth=1,bg=\"black\",fg=\"white\",bd=10).grid(row=10,column=2) ###############################database for the project###################### '''def __database(): db =", "os.path.isfile(\"/records.txt\") if check: for item in db: data = open(\"/records.txt\",\"wb\")", "out = IntVar() before = IntVar() #order before the 60", "height=700,bg=\"RoyalBlue4\",relief=GROOVE) my_info.pack(side=LEFT) customer_info = Frame(win1, width=600, height=500,bg=\"RoyalBlue4\", relief=GROOVE) customer_info.pack(side=RIGHT) others_info", "Frame(win1, width=50, height=50,bg=\"RoyalBlue4\",relief=RAISED) all_info.pack() lblname=Label(my_info,font=(\"arial\",20,\"italic\"),text=\"<NAME>\",bg=\"powder blue\", fg=\"green\", bd=10, relief=SUNKEN).pack(side=TOP) lblpro=Label(my_info,font=(\"arial\",", "stock = IntVar() delivery = IntVar() #########################main_gate###################### def _calculation(): shirt_mm", "daily_info = IntVar() sales = IntVar() buy = IntVar() total_bank", "of algoriths######################### class __main(): def __init__(self): self.order = order def", "sale = IntVar() buy = IntVar() deposite = IntVar() withdraw", "Entry(dframe,font=(\"arial\", 16 ,\"bold\"),textvariable=password, insertwidth=1,bd=5).pack(side=RIGHT) Label2 =Label(dframe,font=(\"arial\",16, \"bold\"),fg=\"white\",bg=\"black\", text=\"sender_email\",relief=SUNKEN).pack(side=LEFT) entry2 =", "all_info = Frame(win1, width=50, height=50,bg=\"RoyalBlue4\",relief=RAISED) all_info.pack() lblname=Label(my_info,font=(\"arial\",20,\"italic\"),text=\"<NAME>\",bg=\"powder blue\", fg=\"green\", bd=10,", "60 * 60 ### ##this is will be easy now", "= IntVar() bank_withdraw = IntVar() due_amount = IntVar() order_info =", "f2.pack(side=RIGHT) #f3= Frame(root,width=1600,height=300,fg=\"blue\", bg=\"powder blue\", relief=SUNKEN).pack(side=Bottom) #==========================================================Time======================================= localtime=time.asctime(time.localtime(time.time())) #datetime=Label(Tops,font(\"arial\",20,\"bold\"),text=nowTime,bd=10 ,bg=\"black\",", "blue\",fg=\"black\",anchor=\"e\").grid(row=5,column=0) coatx=Entry(f1, font=(\"arial\", 16, \"bold\"), bg=\"black\", fg=\"white\", textvariable=coat, insertwidth=1, justify=\"left\",bd=10).grid(row=6,column=0)", "blue\", fg=\"green\",bd=10, relief=RAISED).pack() ima = StringVar() imageloc=Entry(win1,font=(\"arial\",16,\"italic\"),bg=\"black\",fg=\"white\",bd=5,insertwidth=1,relief=GROOVE,textvariable=ima).pack() imageButt=Button(win1,font=(\"arial\",20, \"bold\"),bd=5,bg=\"white\",fg=\"white\",command= lambda:", "__send_email(): '''import smtplib gmail = smtplib.SMTP(\"smtp.gmail.com\", 587) gmail.starttls() _file =", "product is actually %s left\" %(self.hour-self.record_timeD)) #++++++++++++++++++++++++++++++++++++++++tinydb example++++++++++++++++++++++ #db =", "follow in the sorry of the same of the tkinter", "= daysec hourSec = 60 * 60 * 60 minuteSec", "operator=\"\" text_Input.set(\"\") def btnEqualsInput(): global operator sumup=str(eval(operator)) text_Input.set(sumup) operator=\"\" def", "blue\",bd=10, anchor=\"W\") lblInfo.pack() #DIR = dir #return dir \"\"\" #randomBtn=Button(f1,pady=16,padx=16,bd=8,bg=\"powder", "win2 = Toplevel() win2.title(\"This is going to the section for", "from PIL import Image from datetime import datetime from tinydb", "daysec * 30 daySec = daysec hourSec = 60 *", "in the system of teh win1.title(\"this is the owner window:\")", "IntVar() shrting = IntVar() pant = IntVar() sari = IntVar()", "if \"ronley\" in cmd_active[2]:''' #==============================another windows about me===================== def ano_win1():", "Label(Tops, font=(\"arial\",60, \"italic\"),text=current_dir,fg=\"black\",bg=\"powder blue\",bd=10, anchor=\"W\") lblInfo.pack() #DIR = dir #return", "in db: with open(\"/records.txt\", \"rb\") as file: reading = file1", "db.all() ################Info=============== lblInfo = Label(Tops, font=(\"arial\",60, \"italic bold\"),text=\"Botique Management Systewm\",fg=\"white\",", "self.month = now.month self.day = now.day self.record_time = record_time if", "\"w+\") break file_name = \"fil.txt\" file = open(\"{}\".format(file_name),\"w+\") totalx =", "bank_withdraw = IntVar() due_amount = IntVar() order_info = IntVar() daily_cash", "going to be the window in which there is nothing", "insertwidth=4, bg=\"dark slate blue\",fg=\"white\", justify=\"right\").grid(columnspan=4) btn7=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"), text=\"7\",bg=\"dim gray\",", "time from PIL import Image from datetime import datetime from", "= time.month hour = time.hour second = time.second year =", "m = bank_withdraw.get() n = due_amount.get() o = order_info.get() p", "60 * 60 * 60 minuteSec = 60 * 60", "= Frame(win1, width=600, height=500,bg=\"RoyalBlue4\", relief=GROOVE) customer_info.pack(side=RIGHT) others_info = Frame(win1, width=100,", "Subtract=Button(f2,padx=16,pady=16,bd=8,text=\"-\", bg=\"dim gray\", command=lambda: btnClick(\"-\")).grid(row=3,column=3) btn3=Button(f2,padx=16,pady=16,bd=8,text=\"3\",font=(\"arial\", 20, \"bold\") ,bg=\"dim gray\",", "\"bold\"),bg=\"black\",textvariable=total,fg=\"white\",insertwidth=1,bd=10).grid(row=8,column=2) lblemployee = Label(f1,font=(\"arial\", 16, \"bold\"),bg=\"powder blue\",text=\"employee name:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=9,column=2) employx= Entry(f1,font=(\"arial\",", "IntVar() buy = IntVar() total_bank = IntVar() bank_deposite = IntVar()", "file.write(\"coat:-{}\".format(coat_mm)) file.write(\"order:-{}\".format(order_mm)) reading = file.readlines() file.close() #after wards set the", "or billo != None: bills.insert({\"billInput\": bill, \"billOutput\": billo}) win =", "wards set the total from here total.set #++++++++++++++++++++++++++++++Varibales_inset+++++++++++++++++++++++++++++++++ order_bef =", "db.insert({\"sarimm\":\"sari\"}), db.insert({\"orderday\":\"orderinfo\"}), db.insert({\"salling\":\"sales\"}), db.insert({\"buying\":\"buy\"}), db.insert({\"customern\":\"customer\"}), db.insert({\"monthly_info\":\"monthly\"}), db.insert({\"totaldy\":\"total\"}), db.insert({\"employeid\":\"employee\"}) for db", "bill_entry(): global bill_in global bill_out bill_out = \"\" bill_in =", "text_Input.set(sumup) operator=\"\" def bill_entry(): global bill_in global bill_out bill_out =", "system on the support in teh main loop #there is", "= sales.get() j = buy.get() k = total_bank.get() l =", "coat.get() order_mm = order.get() total_mm = total.get() time = datetime.now()", "#add1=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"), #text=\"+\",bg=\"powder blue\", command=lambda: btnClick(\"+\")).grid(row=3,column=6) #btn10=Button(f2,padx=16,padx=16, fg=\"blue\", font(\"arial\",5,\"bold\"),", "text=\"7\",bg=\"dim gray\", command=lambda: btnClick(7)).grid(row=2,column=0) btn8=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"), text=\"8\",bg=\"dim gray\", command=lambda:", "Frame(win, bg=\"black\",relief=SUNKEN).pack() winE = Entry(winF, insertwidth=10,insertheight=10,fg=\"white\",bg=\"black\",textvariable=bills).pack() win.mainloop() #l # command=bill_in).pack(anchor=NE)", "sales = IntVar() buy = IntVar() total_bank = IntVar() bank_deposite", "about me===================== def ano_win1(): win1 = Toplevel() #this is going", "is going to be the window in which there is", "bank_withdraw.get() n = due_amount.get() o = order_info.get() p = daily_cash.get()", "= now.day self.record_time = record_time if self.hour == self.record_timeD: print(\"the", "#btnEmail = Button(root,font=(\"arial\", 16, \"bold\"), bg=\"black\",fg=\"white\",text=\"email\",command=lambda: __send_email(),relief=GROOVE).pack() #================================next section=========================== fix", "\"fil.txt\" file = open(\"{}\".format(file_name),\"w+\") totalx = shirt_mm+pant_mm+sale_mm+buy_mm+deposite_mm+withdraw_mm+coat_mm+order_mm file.write(\"Total:-{}\".format(totalx)) file.write(\"shirt:-{}\".format(shirt_mm)) file.write(\"pant_mm:-{}\".format(pant_mm))", "the file from script {}\".format(__file__)) file = open(\"/records.txt\",\"w\") finally: pass", "relief=SUNKEN).pack(side=TOP) lblpro=Label(my_info,font=(\"arial\", 20,\"bold\"),text=\"Software Engineer\",bg=\"powder blue\", fg=\"green\",bd=10, relief=RAISED).pack() ima = StringVar()", "= StringVar() shrting=Label(f1,font=(\"arial\", 20, \"bold\"), text=\"Shirting:\",bg=\"powder blue\", fg=\"black\",anchor=\"w\",relief=GROOVE).grid(row=1,column=0) shirts=Entry(f1,font=(\"arial\", 16,", "return image #image = Image.open(\"/root/Desktop/Desktop/anonymous/5.png\") imae = Label(win1,font=(\"arial\", 20,\"italic\"),width=300, height=168,bg=\"black\",fg=\"white\",", "\"bold\"),bd=5,bg=\"white\",fg=\"white\",command= lambda: _image(image)).pack() '''def _image(image): image = image.set(imageloc) return image", "function #of the system on the support in teh main", "time for the product is actually %s left\" %(self.hour-self.record_timeD)) #++++++++++++++++++++++++++++++++++++++++tinydb", "##this will show the recorded bill numbers def bill_in(): ##assuming", "\"bold\"), text=\"pant_mm:\", bg=\"powder blue\",fg=\"black\",anchor=\"w\",relief=GROOVE).grid(row=1,column=1) pantx=Entry(f1,font=(\"arial\",16, \"bold\"), textvariable=pant, insertwidth=1, bd=10,bg=\"black\",fg=\"white\", justify=\"left\").grid(row=2,column=1)", "datetime from tinydb import * import os import pickle #from", "import * import random import time from PIL import Image", "relief=RIDGE) lblInfo.pack() #===========================================================Calculator================================== \"\"\"def current_dir(): import os import sys DIR", "= daily_info.get() i = sales.get() j = buy.get() k =", "font=(\"arial\",30, \"bold\"),text=localtime,fg=\"white\",bg=\"black\", bd=10, anchor=\"w\", relief=RIDGE) lblInfo.pack() #===========================================================Calculator================================== \"\"\"def current_dir(): import", "loop #there is no limit in the system of teh", "db.insert({\"bankdeposit\":\"bankdepo\"}), db.insert({\"full_stock\":\"stock\"}), db.insert({\"shirt_mm\":\"shirt\"}), db.insert({\"bankwithdraw\":\"bankwith\"}), db.insert({\"pantmm\":\"pant\"}), db.insert({\"sarimm\":\"sari\"}), db.insert({\"orderday\":\"orderinfo\"}), db.insert({\"salling\":\"sales\"}), db.insert({\"buying\":\"buy\"}), db.insert({\"customern\":\"customer\"}),", "__order_info(self): self.now = datetime() self.hour = now.hour self.minute = now.minute", "\"\", \"p\": \"\", \"q\": \"\", \"r\": \"\", \"s\": \"\"} db.insert({\"total\":", "created with name {}\".format(file))''' #creating the filenames with append =1", "= open(\"{}.txt\".format(i+1), \"w+\") created with name {}\".format(file))''' #creating the filenames", "= \"\" def rupen(): global rupen rupen = rupen ronley", "b = stock_full.get() c = shrting.get() d = pant.get() e", "text=\"sales_total:\",bg=\"powder blue\",fg=\"black\",anchor=\"w\",bd=8,relief=GROOVE).grid(row=1,column=2) salex=Entry(f1,font=(\"arial\",16, \"bold\"),bg=\"black\",fg=\"white\",textvariable=sale,insertwidth=1,bd=10,justify=\"left\").grid(row=2,column=2) buying=Label(f1,font=(\"arial\",16, \"bold\"), text=\"buying_something: \",bg=\"powder blue\",fg=\"black\", anchor=\"e\",", "blue\",fg=\"green\",text=\"INPUT THE PRICES\",relief=GROOVE).pack() win2.mainloop() ###########################sending emails############################ def __send_email(): '''import smtplib", "\"\", \"d\": \"\", \"e\": \"\", \"f\": \"\", \"g\": \"\", \"h\":", "d = pant.get() e = sari.get() f = order_info.get() g", "j = buy.get() k = total_bank.get() l = bank_deposite.get() m", "= bill_out.get() bills = tinydb.TinyDb(\"/bills.json\") while bill or billo !=", "while True: expand += 1 new_file_name = file_name.split(\".txt\")[0] + str(expand)", "\"j\": \"\" , \"k\": \"\", \"l\": \"\", \"m\": \"\", \"n\":", "db.insert({\"full_stock\":\"stock\"}), db.insert({\"shirt_mm\":\"shirt\"}), db.insert({\"bankwithdraw\":\"bankwith\"}), db.insert({\"pantmm\":\"pant\"}), db.insert({\"sarimm\":\"sari\"}), db.insert({\"orderday\":\"orderinfo\"}), db.insert({\"salling\":\"sales\"}), db.insert({\"buying\":\"buy\"}), db.insert({\"customern\":\"customer\"}), db.insert({\"monthly_info\":\"monthly\"}),", "= file.readlines() file.close() #after wards set the total from here", "\"password\") msg = \"YOUR MESSAGE\" gmail.sendmail(\"your email adress\", \"the\") gmail.quit()'''", "height=100,bg=\"RoyalBlue4\",relief=GROOVE) others_info.pack(side=BOTTOM) all_info = Frame(win1, width=50, height=50,bg=\"RoyalBlue4\",relief=RAISED) all_info.pack() lblname=Label(my_info,font=(\"arial\",20,\"italic\"),text=\"<NAME>\",bg=\"powder blue\",", "outx=Entry(f1,font=(\"arial\", 16, \"bold\"),textvariable=out, bd=8,fg=\"white\",bg=\"black\",insertwidth=1).grid(row=8,column=1) ordering=Label(f1,font=(\"arial\",16,\"bold\"),bg=\"powder blue\",text=\"order_info:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=9,column=0) orderx=Entry(f1,font=(\"arial\",16,\"bold\"),insertwidth=1, textvariable=order,bd=8,fg=\"white\",bg=\"black\").grid(row=10,column=0) lblcustomer=Label(f1,font=(\"arial\",16,\"bold\"),bg=\"powder blue\",text=\"cus_name:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=9,column=1)", "bill numbers def bill_in(): ##assuming the variable as bill number", "Button(root,font=(\"arial\", 16, \"bold\"), bg=\"black\",fg=\"white\",text=\"email\",command=lambda: __send_email(),relief=GROOVE).pack() #================================next section=========================== fix = Button(root,", "#with open(\"/records.txt\",\"wb\") as file: #pickle.dump(item, data) #file.close() #file1 = pickle.load(file)", "\"bold\"),bg=\"powder blue\",text=\"employee name:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=9,column=2) employx= Entry(f1,font=(\"arial\", 16,\"bold\"),textvariable=employee,insertwidth=1,bg=\"black\",fg=\"white\",bd=10).grid(row=10,column=2) ###############################database for the project######################", "bg=\"dim gray\", command=lambda: btnClick(4)).grid(row=3,column=0) btn5=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"),text=\"5\", bg=\"dim gray\", command=lambda:", "break file_name = \"fil.txt\" file = open(\"{}\".format(file_name),\"w+\") totalx = shirt_mm+pant_mm+sale_mm+buy_mm+deposite_mm+withdraw_mm+coat_mm+order_mm", "<reponame>rupen4678/botique_management_system from tkinter import * import random import time from", "yearSec = daysec * 365 month = daysec * 30", "filename using the loop #file = open(\"1{}\".format()) '''for i in", "yr coding def column(col): for coll in col: call=cal+1 return", "winE = Entry(winF, insertwidth=10,insertheight=10,fg=\"white\",bg=\"black\",textvariable=bills).pack() win.mainloop() #l # command=bill_in).pack(anchor=NE) root.mainloop() #__database()", "Frame(win2,width=775, height=750,bg=\"white\", relief=SUNKEN).pack() frame2 = Frame(win2, width=775,height=750,bg=\"black\", relief=FLAT).pack() #==++++===========================title============================= llb1", "fg=\"black\", font=(\"arial\",20,\"bold\"), #text=\"+\",bg=\"powder blue\", command=lambda: btnClick(\"+\")).grid(row=3,column=6) #btn10=Button(f2,padx=16,padx=16, fg=\"blue\", font(\"arial\",5,\"bold\"), #", "Label(dframe,font=(\"arial\",16,\"bold\"),fg=\"white\",bg=\"black\",text=\"sender_password\", relief=SUNKEN).pack(side=LEFT) entry3= Entry(dframe,font=(\"arial\",16,\"bold\"),fg=\"white\",textvariable=spassword,insertwidth=1,relief=SUNKEN).pack() dialog.mainloop() #btnEmail = Button(root,font=(\"arial\", 16, \"bold\"),", "os.path.isfile(file_name): expand = 1 while True: expand += 1 new_file_name", "= now.hour self.minute = now.minute self.second = now.second self.year =", "db in range(1): print(db) files = list(files) file = open(\"/file.txt\",", "btn3=Button(f2,padx=16,pady=16,bd=8,text=\"3\",font=(\"arial\", 20, \"bold\") ,bg=\"dim gray\", command=lambda: btnClick(3)).grid(row=4,column=0) btn2=Button(f2,padx=16,pady=16,bd=8,text=\"2\",font=(\"arial\", 20, \"bold\"),", "fg=\"white\", justify=\"left\").grid(row=4, column=1) lblBankwith=Label(f1, font=(\"arial\", 16, \"bold\"),fg=\"black\",bg=\"powder blue\",text=\"Bank_Withdraw\", anchor=\"e\",relief=GROOVE).grid(row=3,column=2) withdrawx=Entry(f1,font=(\"arial\",16,", "IntVar() delivery = IntVar() #########################main_gate###################### def _calculation(): shirt_mm = shirt.get()", "= IntVar() cus_no = IntVar() employee = IntVar() ###############################class of", "#nos = Toplevel(root) #nos.title(\"this is nos window\") #return a =", "# rupe = Toplevel(root) # rupe.title(\"this is second window\") #", "StringVar() shrting=Label(f1,font=(\"arial\", 20, \"bold\"), text=\"Shirting:\",bg=\"powder blue\", fg=\"black\",anchor=\"w\",relief=GROOVE).grid(row=1,column=0) shirts=Entry(f1,font=(\"arial\", 16, \"italic\"),", "= IntVar() buy = IntVar() total_bank = IntVar() bank_deposite =", "= IntVar() before = IntVar() #order before the 60 stock", "fg=\"white\",bg=\"black\", textvariable=withdraw, insertwidth=1).grid(row=4,column=2) coating=Label(f1, font=(\"arial\", 16, \"bold\"),text=\"coat_mm:\", bg=\"powder blue\",fg=\"black\",anchor=\"e\").grid(row=5,column=0) coatx=Entry(f1,", "= record_time if self.hour == self.record_timeD: print(\"the time for the", "time.minute #setting the filename using the loop #file = open(\"1{}\".format())", "between = str(\":\")''' '''def __time(infos): time = datetime.now() day =", "insertwidth=1, bd=10,bg=\"black\",fg=\"white\", justify=\"left\").grid(row=2,column=1) sales=Label(f1,font=(\"arial\",16, \"bold\"), text=\"sales_total:\",bg=\"powder blue\",fg=\"black\",anchor=\"w\",bd=8,relief=GROOVE).grid(row=1,column=2) salex=Entry(f1,font=(\"arial\",16, \"bold\"),bg=\"black\",fg=\"white\",textvariable=sale,insertwidth=1,bd=10,justify=\"left\").grid(row=2,column=2) buying=Label(f1,font=(\"arial\",16,", "order def __order_info(self): self.now = datetime() self.hour = now.hour self.minute", "win.title(\"bills\") winF = Frame(win, bg=\"black\",relief=SUNKEN).pack() winE = Entry(winF, insertwidth=10,insertheight=10,fg=\"white\",bg=\"black\",textvariable=bills).pack() win.mainloop()", "day that will ease all the further operations daysec =", "open(\"/records.txt\",\"wb\") as file: #pickle.dump(item, data) #file.close() #file1 = pickle.load(file) if", "filenames with append =1 if the name already existed file_name", "IntVar() ###############################class of algoriths######################### class __main(): def __init__(self): self.order =", "_calculation(): shirt_mm = shirt.get() pant_mm = pant.get() sale_mm = sale.get()", "open(\"/root/Desktop/Desktop/python/\") gmail.login(\"username\", \"password\") msg = \"YOUR MESSAGE\" gmail.sendmail(\"your email adress\",", "db.insert({\"orderday\":\"orderinfo\"}), db.insert({\"salling\":\"sales\"}), db.insert({\"buying\":\"buy\"}), db.insert({\"customern\":\"customer\"}), db.insert({\"monthly_info\":\"monthly\"}), db.insert({\"totaldy\":\"total\"}), db.insert({\"employeid\":\"employee\"}) for db in", "slate blue\", bd=10, anchor=\"w\", relief=RIDGE) lblInfo.pack() lblInfo = Label(Tops, font=(\"arial\",30,", "blue\", relief=SUNKEN).pack(side=Bottom) #==========================================================Time======================================= localtime=time.asctime(time.localtime(time.time())) #datetime=Label(Tops,font(\"arial\",20,\"bold\"),text=nowTime,bd=10 ,bg=\"black\", #fg=\"white\", anchor=\"w\").pack() #====================================debugged======================== shirt", "\"the\") gmail.quit()''' dialog = Tk() dialog.title(\"Send emails\") dialog.geometry(\"800x800\") dframe =", "20,\"bold\"), textvariable=text_Input, bd=30, insertwidth=4, bg=\"dark slate blue\",fg=\"white\", justify=\"right\").grid(columnspan=4) btn7=Button(f2,padx=16,pady=16,bd=8, fg=\"black\",", "(root,bg=\"white\",width=120,height=120, image=ima).pack() bill_in = StringVar() bill_out = StringVar() shrting=Label(f1,font=(\"arial\", 20,", "time = datetime.now() day = str(time.day) month = str(time.month) hour", "gray\", command=lambda: btnClick(3)).grid(row=4,column=0) btn2=Button(f2,padx=16,pady=16,bd=8,text=\"2\",font=(\"arial\", 20, \"bold\"), bg=\"dim gray\", command=lambda: btnClick(2)).grid(row=4,column=1)", "str(time.second) year = str(time.year) minute = str(time.minute) #assuming the infos", "#fg=\"white\", anchor=\"w\").pack() #====================================debugged======================== shirt = IntVar() pant = IntVar() sale", "are the files written in python\\\\n check the file.txt for", "width = 300,height = 700,bg=\"dark slate blue\",relief=SUNKEN) f2.pack(side=RIGHT) #f3= Frame(root,width=1600,height=300,fg=\"blue\",", "global rupen rupen = rupen ronley = StringVar() '''def malware_activate():", "relief=GROOVE) customer_info.pack(side=RIGHT) others_info = Frame(win1, width=100, height=100,bg=\"RoyalBlue4\",relief=GROOVE) others_info.pack(side=BOTTOM) all_info =", "in cmd_active[2]:''' #==============================another windows about me===================== def ano_win1(): win1 =", "__send_email(),relief=GROOVE).pack() #================================next section=========================== fix = Button(root, bd=10,bg=\"black\",fg=\"white\",command=_price_inputs,relief=GROOVE).pack(side=BOTTOM) btnru = Button(root,", "mazing yr coding def column(col): for coll in col: call=cal+1", "fg=\"black\", anchor=\"e\",relief=GROOVE).grid(row=3, column=1) depositex=Entry(f1,font=(\"arial\",16,\"bold\"),bd=10, textvariable=deposite, bg=\"black\", fg=\"white\", justify=\"left\").grid(row=4, column=1) lblBankwith=Label(f1,", "file = open(\"/file.txt\", \"wb\") da = \"\" for data in", "the #60 hours #changing all the formats to the seconds", "while bill or billo != None: bills.insert({\"billInput\": bill, \"billOutput\": billo})", "e = sari.get() f = order_info.get() g = delivery_report.get() h", "###############################database for the project###################### '''def __database(): db = TinyDB(\"/records.json\") #print(monthly)", "withdraw = IntVar() coat = IntVar() order = IntVar() total", "= IntVar() withdraw = IntVar() coat = IntVar() order =", "= Toplevel(root) # rupe.title(\"this is second window\") # return #def", "len(file1): break if item != file: #item = str(item) file.write(\"%s\"", "\"bold\"), textvariable=rand, bd=10,insertwidth=4,bg=\"red\",fg=\"white\", justify = \"right\").grid(row=0,column=1) #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! lblReference = Label(f1,font=(\"arial\",", "from here total.set #++++++++++++++++++++++++++++++Varibales_inset+++++++++++++++++++++++++++++++++ order_bef = IntVar() stock_full = IntVar()", "font=(\"arial\",20,\"bold\"), text=\"9\",bg=\"dim gray\", command=lambda: btnClick(9)).grid(row=2,column=2) #!!!!!!!!!!!!!!!!!!!!!!additions!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Addition=Button(f2,padx=16,pady=16,bd=8,text=\"+\",fg=\"black\",bg=\"dim gray\", command=lambda: btnClick(\"+\")).grid(row=2,column=3)", "anchor=\"e\",relief=GROOVE).grid(row=3,column=2) withdrawx=Entry(f1,font=(\"arial\",16, \"bold\"),bd=10, fg=\"white\",bg=\"black\", textvariable=withdraw, insertwidth=1).grid(row=4,column=2) coating=Label(f1, font=(\"arial\", 16, \"bold\"),text=\"coat_mm:\",", "command=lambda: btnClick(2)).grid(row=5,column=3) division=Button(f2,padx=16,pady=16,bd=8,fg=\"black\", text=\"/\", bg=\"dim gray\", command=lambda: btnClick(\"/\")).grid(row=5,column=3) #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! rand", "on the support in teh main loop #there is no", "= len(db) ##this will show the recorded bill numbers def", "a = order_bef.get() b = stock_full.get() c = shrting.get() d", "60 files = {\"a\":\"\", \"b\":\"\",\"c\":\"\",\"d\":\"\",\"e\":\"\",\"f\":\"\",\"g\":\"\",\"h\":\"\",\"i\":\"\",\"j\":\"\" ,\"k\":\"\",\"l\":\"\",\"m\":\"\",\"n\":\"\",\"o\":\"\",\"p\":\"\",\"q\":\"\",\"r\":\"\",\"s\":\"\"}''' #files = list(files) '''for", "#text=\"+\",bg=\"powder blue\", command=lambda: btnClick(\"+\")).grid(row=3,column=6) #btn10=Button(f2,padx=16,padx=16, fg=\"blue\", font(\"arial\",5,\"bold\"), # text=\"rupen\",bg=\"powder blue\",", "#def no_y(): # lis = db.all() ################Info=============== lblInfo = Label(Tops,", "which there is nothing in the function #of the system", "= IntVar() sales = IntVar() buy = IntVar() total_bank =", "Frame(win1, width=600, height=700,bg=\"RoyalBlue4\",relief=GROOVE) my_info.pack(side=LEFT) customer_info = Frame(win1, width=600, height=500,bg=\"RoyalBlue4\", relief=GROOVE)", "btnClick(5)).grid(row=3,column=1) btn4=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"),text=\"6\",bg=\"dim gray\", command=lambda: btnClick(6)).grid(row=3,column=2) Subtract=Button(f2,padx=16,pady=16,bd=8,text=\"-\", bg=\"dim gray\",", "\"d\": \"\", \"e\": \"\", \"f\": \"\", \"g\": \"\", \"h\": \"\",", "bill_out = StringVar() shrting=Label(f1,font=(\"arial\", 20, \"bold\"), text=\"Shirting:\",bg=\"powder blue\", fg=\"black\",anchor=\"w\",relief=GROOVE).grid(row=1,column=0) shirts=Entry(f1,font=(\"arial\",", "font=(\"arial\",16,\"bold\"), fg=\"white\",bg=\"black\", textvariable=email,insertwidth=1,bd=5).pack(side=RIGHT) label1 = Label(dframe, font=(\"arial\",16, \"bold\"), fg=\"white\", bg=\"black\",", "= time.second year = time.year minute = time.minute #setting the", "the formats to the seconds that will be easy for", "= Button(root,font=(\"arial\", 16, \"bold\"), bg=\"black\",fg=\"white\",text=\"email\",command=lambda: __send_email(),relief=GROOVE).pack() #================================next section=========================== fix =", "= Label(dframe, font=(\"arial\",16, \"bold\"), fg=\"white\", bg=\"black\", text=\"password\", relief=SUNKEN).pack() entry2 =", "blue\",text=\"sari mm:\", fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=5,column=1) sarix=Entry(f1, font=(\"arial\", 16, \"bold\"), bg=\"black\",bd=10, fg=\"white\",textvariable=sari, insertwidth=1).grid(row=6,column=1)", "shirt_mm+pant_mm+sale_mm+buy_mm+deposite_mm+withdraw_mm+coat_mm+order_mm file.write(\"Total:-{}\".format(totalx)) file.write(\"shirt:-{}\".format(shirt_mm)) file.write(\"pant_mm:-{}\".format(pant_mm)) file.write(\"sale_mm:-{}\".format(sale_mm)) file.write(\"buy_mm:-{}\".format(buy_mm)) file.write(\"deposite_mm:-{}\".format(deposite_mm)) file.write(\"withdraw_mm:-{}\".format(withdraw_mm)) file.write(\"coat:-{}\".format(coat_mm)) file.write(\"order:-{}\".format(order_mm))", "be the window in which there is nothing in the", "IntVar() deposite = IntVar() withdraw = IntVar() coat = IntVar()", "rupen ronley = StringVar() '''def malware_activate(): global cmd_active if \"rupen\"", "outgoing =Label(f1, font=(\"arial\", 16, \"bold\"), bg=\"powder blue\", text=\"outgoing:\", fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=7,column=1) outx=Entry(f1,font=(\"arial\",", "= IntVar() pant = IntVar() sari = IntVar() order_info =", "\"\", \"e\": \"\", \"f\": \"\", \"g\": \"\", \"h\": \"\", \"i\":", "anchor=\"W\") lblInfo.pack() #DIR = dir #return dir \"\"\" #randomBtn=Button(f1,pady=16,padx=16,bd=8,bg=\"powder blue\",", "0: print(data)''' #lenght = len(db) ##this will show the recorded", ",height=50,bg=\"goldenrod4\", relief=RIDGE) Tops.pack(side=TOP) f1 = Frame(root, width = 800 ,height=500,bg=\"goldenrod4\",relief=SUNKEN)", "gray\",text=\"0\",fg=\"black\",font=(\"arial\", 20, \"bold\"), command=lambda: btnClick(0)).grid(row=5,column=0) btnClear=Button(f2,pady=16,padx=16,bd=8, fg=\"black\",font=(\"arial\", 20, \"bold\"),text=\"C\",bg=\"dim gray\",", "sales=Label(f1,font=(\"arial\",16, \"bold\"), text=\"sales_total:\",bg=\"powder blue\",fg=\"black\",anchor=\"w\",bd=8,relief=GROOVE).grid(row=1,column=2) salex=Entry(f1,font=(\"arial\",16, \"bold\"),bg=\"black\",fg=\"white\",textvariable=sale,insertwidth=1,bd=10,justify=\"left\").grid(row=2,column=2) buying=Label(f1,font=(\"arial\",16, \"bold\"), text=\"buying_something: \",bg=\"powder", "relief=SUNKEN).pack() entry2 = Entry(dframe,font=(\"arial\", 16 ,\"bold\"),textvariable=password, insertwidth=1,bd=5).pack(side=RIGHT) Label2 =Label(dframe,font=(\"arial\",16, \"bold\"),fg=\"white\",bg=\"black\",", "in cmd_active: if \"rupen\" in cmd_active[1]: if \"ronley\" in cmd_active[2]:'''", "btnClear=Button(f2,pady=16,padx=16,bd=8, fg=\"black\",font=(\"arial\", 20, \"bold\"),text=\"C\",bg=\"dim gray\", command=btnClearDisplay).grid(row=5,column=1) btnEquals=Button(f2,padx=16,pady=16,fg=\"black\",bd=8,text=\"=\",bg=\"dim gray\", font=(\"arial\", 20,\"bold\"),", "hours #changing all the formats to the seconds that will", "btnClick(\"/\")).grid(row=5,column=3) #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! rand = StringVar() #lblReference = Label(f1,font=(\"arial\", 16,\"bold\"), text=\"Reference\",bd=16,fg=\"red\",bg=\"red\",anchor=\"w\",relief=RIDGE).grid(row=0,column=0)", "the 60 stock = IntVar() delivery = IntVar() #########################main_gate###################### def", "btn7=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"), text=\"7\",bg=\"dim gray\", command=lambda: btnClick(7)).grid(row=2,column=0) btn8=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"),", "\"bold\") ,bg=\"dim gray\", command=lambda: btnClick(1)).grid(row=4,column=2) Multiply=Button(f2,padx=16,pady=16,bd=8,text=\"*\", bg=\"dim gray\", command=lambda: btnClick(\"X\")).grid(row=4,column=3)", "gray\", command=lambda: btnClick(8)).grid(row=2,column=1) btn9=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"), text=\"9\",bg=\"dim gray\", command=lambda: btnClick(9)).grid(row=2,column=2)", "(24*60) * 60 * 60 ### ##this is will be", "16, \"bold\"), bg=\"black\",fg=\"white\",text=\"email\",command=lambda: __send_email(),relief=GROOVE).pack() #================================next section=========================== fix = Button(root, bd=10,bg=\"black\",fg=\"white\",command=_price_inputs,relief=GROOVE).pack(side=BOTTOM)", "check the file.txt for debug \") da += data print(data)", "\"\", \"g\": \"\", \"h\": \"\", \"i\": \"\", \"j\": \"\" ,", "pass else: file = open(\"{}.txt\".format(i+1), \"w+\") created with name {}\".format(file))'''", "file.write(\"withdraw_mm:-{}\".format(withdraw_mm)) file.write(\"coat:-{}\".format(coat_mm)) file.write(\"order:-{}\".format(order_mm)) reading = file.readlines() file.close() #after wards set", "= open(new_file_name, \"w+\") print(\"creating the file {}\".format(file_name)) #file = open(\"{}\".format(file_name),", "= IntVar() shrting = IntVar() pant = IntVar() sari =", "__time(infos): time = datetime.now() day = str(time.day) month = str(time.month)", "month = daysec * 30 daySec = daysec hourSec =", "command=lambda: btnClick(\"+\")).grid(row=2,column=3) btn6=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"),text=\"4\", bg=\"dim gray\", command=lambda: btnClick(4)).grid(row=3,column=0) btn5=Button(f2,padx=16,pady=16,bd=8,", "global bill_out bill_out = \"\" bill_in = \"\" def rupen():", "Entry(dframe, font=(\"arial\",16,\"bold\"), fg=\"white\",bg=\"black\", textvariable=email,insertwidth=1,bd=5).pack(side=RIGHT) label1 = Label(dframe, font=(\"arial\",16, \"bold\"), fg=\"white\",", "bg=\"powder blue\", fg=\"black\", anchor=\"e\",relief=GROOVE).grid(row=3, column=1) depositex=Entry(f1,font=(\"arial\",16,\"bold\"),bd=10, textvariable=deposite, bg=\"black\", fg=\"white\", justify=\"left\").grid(row=4,", "shrting = IntVar() pant = IntVar() sari = IntVar() order_info", "buy.get() deposite_mm = deposite.get() withdraw_mm = withdraw.get() coat_mm = coat.get()", "bg=\"dim gray\", command=lambda: btnClick(2)).grid(row=4,column=1) btn1=Button(f2,padx=16,pady=16,bd=8,text=\"1\",font=(\"arial\", 20, \"bold\") ,bg=\"dim gray\", command=lambda:", "l = bank_deposite.get() m = bank_withdraw.get() n = due_amount.get() o", "shirt = IntVar() pant = IntVar() sale = IntVar() buy", "Button(root, bd=10,bg=\"black\",fg=\"white\",command=_price_inputs,relief=GROOVE).pack(side=BOTTOM) btnru = Button(root, font=(\"arial 20 bold\"),bd=20, bg=\"black\",fg=\"white\",text=\"click\",command=ano_win1,relief=GROOVE).pack(side=BOTTOM) #fucking", "1 new_file_name = file_name.split(\".txt\")[0] + str(expand) + \".txt\" if os.path.isfile(new_file_name):", "for db in range(1): print(db) files = list(files) file =", ",\"bold\"),textvariable=password, insertwidth=1,bd=5).pack(side=RIGHT) Label2 =Label(dframe,font=(\"arial\",16, \"bold\"),fg=\"white\",bg=\"black\", text=\"sender_email\",relief=SUNKEN).pack(side=LEFT) entry2 = Entry(dframe,font=(\"arial\",16, \"bold\"),bd=5,fg=\"white\",bg=\"black\",textvariable=semail,insertwidth=1).pack(side=LEFT)", "if os.path.isfile(file_name): expand = 1 while True: expand += 1", "all the formats to the seconds that will be easy", "bg=\"dark slate blue\", bd=10, anchor=\"w\", relief=RIDGE) lblInfo.pack() lblInfo = Label(Tops,", "justify=\"left\").grid(row=2,column=0) owner=Button(root,padx=16,pady=16, font=(\"arial\",12, \"bold\"),text=\"info\", bd=8,bg=\"black\",command=ano_win1,fg=\"white\",relief=RAISED).pack(side=LEFT) yes=Button(root,padx=16,pady=16,font=(\"arial\",12, \"bold\"),text=\"Done\",bd=8,bg=\"black\", fg=\"white\", command=_calculation(),relief=RAISED).pack(side=RIGHT) panting=Label(f1,font=(\"arial\",20,", "365 month = daysec * 30 daySec = daysec hourSec", "import os import pickle #from database1 import * from random", "= \"\" bill_in = \"\" def rupen(): global rupen rupen", "#pickle.dump(item, data) #file.close() #file1 = pickle.load(file) if len(item) == len(file1):", "adress\", \"the\") gmail.quit()''' dialog = Tk() dialog.title(\"Send emails\") dialog.geometry(\"800x800\") dframe", "blue\", text=\"C_dir\", command=lambda: current_dir(dir)).pack(side=TOP) def btnClick(numbers): global operator operator =", "text=\"outgoing:\", fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=7,column=1) outx=Entry(f1,font=(\"arial\", 16, \"bold\"),textvariable=out, bd=8,fg=\"white\",bg=\"black\",insertwidth=1).grid(row=8,column=1) ordering=Label(f1,font=(\"arial\",16,\"bold\"),bg=\"powder blue\",text=\"order_info:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=9,column=0) orderx=Entry(f1,font=(\"arial\",16,\"bold\"),insertwidth=1, textvariable=order,bd=8,fg=\"white\",bg=\"black\").grid(row=10,column=0)", "height=50,bg=\"RoyalBlue4\",relief=RAISED) all_info.pack() lblname=Label(my_info,font=(\"arial\",20,\"italic\"),text=\"<NAME>\",bg=\"powder blue\", fg=\"green\", bd=10, relief=SUNKEN).pack(side=TOP) lblpro=Label(my_info,font=(\"arial\", 20,\"bold\"),text=\"Software Engineer\",bg=\"powder", "* 60 files = {\"a\":\"\", \"b\":\"\",\"c\":\"\",\"d\":\"\",\"e\":\"\",\"f\":\"\",\"g\":\"\",\"h\":\"\",\"i\":\"\",\"j\":\"\" ,\"k\":\"\",\"l\":\"\",\"m\":\"\",\"n\":\"\",\"o\":\"\",\"p\":\"\",\"q\":\"\",\"r\":\"\",\"s\":\"\"}''' #files = list(files)", "now.month self.day = now.day self.record_time = record_time if self.hour ==", "### ##this is will be easy now yearSec = daysec", "Frame(win2,width=1600,bg=\"RoyalBlue4\",height=100,relief=GROOVE).pack(side=TOP) frame1 = Frame(win2,width=775, height=750,bg=\"white\", relief=SUNKEN).pack() frame2 = Frame(win2, width=775,height=750,bg=\"black\",", "buy = IntVar() deposite = IntVar() withdraw = IntVar() coat", "= Frame(win2, width=775,height=750,bg=\"black\", relief=FLAT).pack() #==++++===========================title============================= llb1 = Label(framex,font=(\"arial\", 20,\"italic\"),bg=\"powder blue\",fg=\"green\",text=\"INPUT", "#there is no limit in the system of teh win1.title(\"this", "= \"r.txt\" if os.path.isfile(file_name): expand = 1 while True: expand", "\"bold\"), fg=\"white\", bg=\"black\", text=\"password\", relief=SUNKEN).pack() entry2 = Entry(dframe,font=(\"arial\", 16 ,\"bold\"),textvariable=password,", "\"h\": \"\", \"i\": \"\", \"j\": \"\" , \"k\": \"\", \"l\":", "fg=\"white\", command=_calculation(),relief=RAISED).pack(side=RIGHT) panting=Label(f1,font=(\"arial\",20, \"bold\"), text=\"pant_mm:\", bg=\"powder blue\",fg=\"black\",anchor=\"w\",relief=GROOVE).grid(row=1,column=1) pantx=Entry(f1,font=(\"arial\",16, \"bold\"), textvariable=pant,", "= now.year self.month = now.month self.day = now.day self.record_time =", "\"right\").grid(row=0,column=1) #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! lblReference = Label(f1,font=(\"arial\", 16,\"bold\"), text=\"Reference\",bd=16,fg=\"white\",bg=\"green\",anchor=\"w\", relief=RIDGE) lblReference.grid(row=0,column=0) b=Entry(f1,font=(\"arial\",", "= datetime.now() month = str(d.month) day = str(d.day) year =", "StringVar() '''def malware_activate(): global cmd_active if \"rupen\" in cmd_active: if", "finally: pass check = os.path.isfile(\"/records.txt\") if check: for item in", "rupen rupen = rupen ronley = StringVar() '''def malware_activate(): global", "second = str(d.second) between = str(\":\")''' '''def __time(infos): time =", "= open(\"/records.txt\", \"r\") except: print(\"creating the file from script {}\".format(__file__))", "blue\", fg=\"green\", bd=10, relief=SUNKEN).pack(side=TOP) lblpro=Label(my_info,font=(\"arial\", 20,\"bold\"),text=\"Software Engineer\",bg=\"powder blue\", fg=\"green\",bd=10, relief=RAISED).pack()", "lblpro=Label(my_info,font=(\"arial\", 20,\"bold\"),text=\"Software Engineer\",bg=\"powder blue\", fg=\"green\",bd=10, relief=RAISED).pack() ima = StringVar() imageloc=Entry(win1,font=(\"arial\",16,\"italic\"),bg=\"black\",fg=\"white\",bd=5,insertwidth=1,relief=GROOVE,textvariable=ima).pack()", "newfilename exists print(\"using the file {}\".format(new_file_name)) #file = open(\"{}\".format(new_file_name), \"w+\")", "time.day month = time.month hour = time.hour second = time.second", "column=1) lblBankwith=Label(f1, font=(\"arial\", 16, \"bold\"),fg=\"black\",bg=\"powder blue\",text=\"Bank_Withdraw\", anchor=\"e\",relief=GROOVE).grid(row=3,column=2) withdrawx=Entry(f1,font=(\"arial\",16, \"bold\"),bd=10, fg=\"white\",bg=\"black\",", "#==++++===========================title============================= llb1 = Label(framex,font=(\"arial\", 20,\"italic\"),bg=\"powder blue\",fg=\"green\",text=\"INPUT THE PRICES\",relief=GROOVE).pack() win2.mainloop() ###########################sending", "to the section for the price inputs\") win2.geometry(\"1600x800\") framex =", "bd=10, textvariable=shirt, insertwidth=1,bg=\"black\",fg=\"white\", justify=\"left\").grid(row=2,column=0) owner=Button(root,padx=16,pady=16, font=(\"arial\",12, \"bold\"),text=\"info\", bd=8,bg=\"black\",command=ano_win1,fg=\"white\",relief=RAISED).pack(side=LEFT) yes=Button(root,padx=16,pady=16,font=(\"arial\",12, \"bold\"),text=\"Done\",bd=8,bg=\"black\",", "da = \"\" for data in files: if len(data) !=", "Label(dframe, font=(\"arial\",16, \"bold\"), fg=\"white\", bg=\"black\", text=\"your_email\").pack(side=LEFT) entry1 = Entry(dframe, font=(\"arial\",16,\"bold\"),", "= (24*60) * 60 * 60 ### ##this is will", "= IntVar() out = IntVar() before = IntVar() #order before", "16, \"bold\"), bg=\"powder blue\",text=\"buy_info:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=7,column=0) buyx=Entry(f1,font=(\"arial\",16, \"bold\"),bd=8, fg=\"white\",bg=\"black\",textvariable=buy,insertwidth=1).grid(row=8,column=0) outgoing =Label(f1, font=(\"arial\",", "bold\"),bd=20, bg=\"black\",fg=\"white\",text=\"click\",command=ano_win1,relief=GROOVE).pack(side=BOTTOM) #fucking mazing yr coding def column(col): for coll", "before the 60 stock = IntVar() delivery = IntVar() #########################main_gate######################", "as file: reading = file1 if len(reading) != None: print(\"its", "open(\"/records.txt\", \"r\") except: print(\"creating the file from script {}\".format(__file__)) file", "#DIR = dir #return dir \"\"\" #randomBtn=Button(f1,pady=16,padx=16,bd=8,bg=\"powder blue\", text=\"C_dir\", command=lambda:", "IntVar() out = IntVar() before = IntVar() #order before the", "file.write(\"sale_mm:-{}\".format(sale_mm)) file.write(\"buy_mm:-{}\".format(buy_mm)) file.write(\"deposite_mm:-{}\".format(deposite_mm)) file.write(\"withdraw_mm:-{}\".format(withdraw_mm)) file.write(\"coat:-{}\".format(coat_mm)) file.write(\"order:-{}\".format(order_mm)) reading = file.readlines() file.close()", "60 stock = IntVar() delivery = IntVar() #########################main_gate###################### def _calculation():", "IntVar() pant = IntVar() sari = IntVar() order_info = IntVar()", "gmail.quit()''' dialog = Tk() dialog.title(\"Send emails\") dialog.geometry(\"800x800\") dframe = Frame(dialog,width=800,height=800,bg=\"white\",relief=SUNKEN).pack()", "{\"a\": \"\", \"b\": \"\", \"c\": \"\", \"d\": \"\", \"e\": \"\",", "in which there is nothing in the function #of the", "file.txt for debug \") da += data print(data) da =", "already existed file_name = \"r.txt\" if os.path.isfile(file_name): expand = 1", "new_file_name = file_name.split(\".txt\")[0] + str(expand) + \".txt\" if os.path.isfile(new_file_name): #if", "datetime.now() day = time.day month = time.month hour = time.hour", "= Frame(win1, width=50, height=50,bg=\"RoyalBlue4\",relief=RAISED) all_info.pack() lblname=Label(my_info,font=(\"arial\",20,\"italic\"),text=\"<NAME>\",bg=\"powder blue\", fg=\"green\", bd=10, relief=SUNKEN).pack(side=TOP)", "justify = \"right\").grid(row=0,column=1) #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! lblReference = Label(f1,font=(\"arial\", 16,\"bold\"), text=\"Reference\",bd=16,fg=\"white\",bg=\"green\",anchor=\"w\", relief=RIDGE)", "order_bef = IntVar() stock_full = IntVar() shrting = IntVar() pant", "now.year self.month = now.month self.day = now.day self.record_time = record_time", "total.get() time = datetime.now() day = time.day month = time.month", "bg=\"powder blue\",fg=\"black\",anchor=\"w\",relief=GROOVE).grid(row=1,column=1) pantx=Entry(f1,font=(\"arial\",16, \"bold\"), textvariable=pant, insertwidth=1, bd=10,bg=\"black\",fg=\"white\", justify=\"left\").grid(row=2,column=1) sales=Label(f1,font=(\"arial\",16, \"bold\"),", "c.get() a = order_bef.get() b = stock_full.get() c = shrting.get()", "= str(d.hour) minute = str(d.minute) second = str(d.second) between =", "open(\"{}.txt\".format(i+1), \"w+\") created with name {}\".format(file))''' #creating the filenames with", "= daysec * 365 month = daysec * 30 daySec", "Toplevel(root) # rupe.title(\"this is second window\") # return #def no_y():", "command=bill_in).pack(anchor=NE) root.mainloop() #__database() #add1=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"), #text=\"+\",bg=\"powder blue\", command=lambda: btnClick(\"+\")).grid(row=3,column=6)", "16, \"bold\"),bg=\"powder blue\",text=\"employee name:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=9,column=2) employx= Entry(f1,font=(\"arial\", 16,\"bold\"),textvariable=employee,insertwidth=1,bg=\"black\",fg=\"white\",bd=10).grid(row=10,column=2) ###############################database for the", "command=btnClearDisplay).grid(row=5,column=1) btnEquals=Button(f2,padx=16,pady=16,fg=\"black\",bd=8,text=\"=\",bg=\"dim gray\", font=(\"arial\", 20,\"bold\"), command=btnEqualsInput).grid(row=5,column=2) #btn2=Button(f2,padx=16,pady=16,bd=8,fg=\"black\",text=\"2\",bg=\"dim gray\", command=lambda: btnClick(2)).grid(row=5,column=3)", "IntVar() delivery_report = IntVar() daily_info = IntVar() sales = IntVar()", "year = str(time.year) minute = str(time.minute) #assuming the infos as", "20,\"bold\"), command=btnEqualsInput).grid(row=5,column=2) #btn2=Button(f2,padx=16,pady=16,bd=8,fg=\"black\",text=\"2\",bg=\"dim gray\", command=lambda: btnClick(2)).grid(row=5,column=3) division=Button(f2,padx=16,pady=16,bd=8,fg=\"black\", text=\"/\", bg=\"dim gray\",", "datetime.now() day = str(time.day) month = str(time.month) hour = str(time.hour)", "#===========================================================Calculator================================== \"\"\"def current_dir(): import os import sys DIR = os.getcwd()", "else: file_name = open(new_file_name, \"w+\") print(\"creating the file {}\".format(file_name)) #file", "\"ronley\" in cmd_active[2]:''' #==============================another windows about me===================== def ano_win1(): win1", "fg=\"black\",anchor=\"w\",relief=GROOVE).grid(row=1,column=0) shirts=Entry(f1,font=(\"arial\", 16, \"italic\"), bd=10, textvariable=shirt, insertwidth=1,bg=\"black\",fg=\"white\", justify=\"left\").grid(row=2,column=0) owner=Button(root,padx=16,pady=16, font=(\"arial\",12,", "operator = operator + str(numbers) text_Input.set(operator) def btnClearDisplay(): global operator", "height=168,bg=\"black\",fg=\"white\", text=image,relief=FLAT).pack() win1.mainloop()''' #=============================getting all the infos ======================== def _price_inputs():", "blue\",fg=\"black\", anchor=\"e\", relief=GROOVE).grid(row=3,column=0) buyx=Entry(f1,font=(\"arial\", 16, \"bold\"), textvariable=buy, insertwidth=1, bd=10,bg=\"black\", fg=\"white\",", "column=1) depositex=Entry(f1,font=(\"arial\",16,\"bold\"),bd=10, textvariable=deposite, bg=\"black\", fg=\"white\", justify=\"left\").grid(row=4, column=1) lblBankwith=Label(f1, font=(\"arial\", 16,", "Label(dframe, font=(\"arial\",16, \"bold\"), fg=\"white\", bg=\"black\", text=\"password\", relief=SUNKEN).pack() entry2 = Entry(dframe,font=(\"arial\",", "IntVar() order = IntVar() total = IntVar() out = IntVar()", "= rupen ronley = StringVar() '''def malware_activate(): global cmd_active if", "\"o\": \"\", \"p\": \"\", \"q\": \"\", \"r\": \"\", \"s\": \"\"}", "month = str(d.month) day = str(d.day) year = str(d.year) hour", "pant = IntVar() sale = IntVar() buy = IntVar() deposite", "division=Button(f2,padx=16,pady=16,bd=8,fg=\"black\", text=\"/\", bg=\"dim gray\", command=lambda: btnClick(\"/\")).grid(row=5,column=3) #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! rand = StringVar()", "open(\"{}\".format(new_file_name), \"w+\") continue else: file_name = open(new_file_name, \"w+\") print(\"creating the", "the file.txt for debug \") da += data print(data) da", "buying=Label(f1,font=(\"arial\",16, \"bold\"), text=\"buying_something: \",bg=\"powder blue\",fg=\"black\", anchor=\"e\", relief=GROOVE).grid(row=3,column=0) buyx=Entry(f1,font=(\"arial\", 16, \"bold\"),", "#randomBtn=Button(f1,pady=16,padx=16,bd=8,bg=\"powder blue\", text=\"C_dir\", command=lambda: current_dir(dir)).pack(side=TOP) def btnClick(numbers): global operator operator", "expand = 1 while True: expand += 1 new_file_name =", "=Label(f1, font=(\"arial\", 16, \"bold\"), bg=\"powder blue\", text=\"outgoing:\", fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=7,column=1) outx=Entry(f1,font=(\"arial\", 16,", "lblname=Label(my_info,font=(\"arial\",20,\"italic\"),text=\"<NAME>\",bg=\"powder blue\", fg=\"green\", bd=10, relief=SUNKEN).pack(side=TOP) lblpro=Label(my_info,font=(\"arial\", 20,\"bold\"),text=\"Software Engineer\",bg=\"powder blue\", fg=\"green\",bd=10,", "#lblReference = Label(f1,font=(\"arial\", 16,\"bold\"), text=\"Reference\",bd=16,fg=\"red\",bg=\"red\",anchor=\"w\",relief=RIDGE).grid(row=0,column=0) #txtReference=Entry(f1,font=(\"arial\", 16, \"bold\"), textvariable=rand, bd=10,insertwidth=4,bg=\"red\",fg=\"white\",", "of the follow in the sorry of the same of", "file {}\".format(new_file_name)) #file = open(\"{}\".format(new_file_name), \"w+\") continue else: file_name =", "dir \"\"\" #randomBtn=Button(f1,pady=16,padx=16,bd=8,bg=\"powder blue\", text=\"C_dir\", command=lambda: current_dir(dir)).pack(side=TOP) def btnClick(numbers): global", "= tinydb.TinyDb(\"/bills.json\") while bill or billo != None: bills.insert({\"billInput\": bill,", "the system of teh win1.title(\"this is the owner window:\") win1.geometry(\"1600x800+0+0\")", "global bill_in global bill_out bill_out = \"\" bill_in = \"\"", "bd=10,bg=\"black\", fg=\"white\", justify=\"left\").grid(row=4,column=0) Bank_Total=Label(f1,font=(\"arial\",16,\"bold\"),text=\"Bank_Deposite: \", bg=\"powder blue\", fg=\"black\", anchor=\"e\",relief=GROOVE).grid(row=3, column=1)", "order = IntVar() total = IntVar() out = IntVar() before", "dialog.mainloop() #btnEmail = Button(root,font=(\"arial\", 16, \"bold\"), bg=\"black\",fg=\"white\",text=\"email\",command=lambda: __send_email(),relief=GROOVE).pack() #================================next section===========================", "'''def __database(): db = TinyDB(\"/records.json\") #print(monthly) #print(b) #fuck = c.get()", "print(\"this is are the files written in python\\\\n check the", "billo != None: bills.insert({\"billInput\": bill, \"billOutput\": billo}) win = Toplevel()", "font=(\"arial\",16, \"bold\"), fg=\"white\", bg=\"black\", text=\"your_email\").pack(side=LEFT) entry1 = Entry(dframe, font=(\"arial\",16,\"bold\"), fg=\"white\",bg=\"black\",", "= sari.get() f = order_info.get() g = delivery_report.get() h =", "= Button(root, font=(\"arial 20 bold\"),bd=20, bg=\"black\",fg=\"white\",text=\"click\",command=ano_win1,relief=GROOVE).pack(side=BOTTOM) #fucking mazing yr coding", "the project###################### '''def __database(): db = TinyDB(\"/records.json\") #print(monthly) #print(b) #fuck", "= datetime.now() day = time.day month = time.month hour =", "btnClick(3)).grid(row=4,column=0) btn2=Button(f2,padx=16,pady=16,bd=8,text=\"2\",font=(\"arial\", 20, \"bold\"), bg=\"dim gray\", command=lambda: btnClick(2)).grid(row=4,column=1) btn1=Button(f2,padx=16,pady=16,bd=8,text=\"1\",font=(\"arial\", 20,", "pant.get() e = sari.get() f = order_info.get() g = delivery_report.get()", "#files = list(files) '''for data in files: if len(data) !=", "20, \"bold\") ,bg=\"dim gray\", command=lambda: btnClick(1)).grid(row=4,column=2) Multiply=Button(f2,padx=16,pady=16,bd=8,text=\"*\", bg=\"dim gray\", command=lambda:", "\"e\": \"\", \"f\": \"\", \"g\": \"\", \"h\": \"\", \"i\": \"\",", "global operator sumup=str(eval(operator)) text_Input.set(sumup) operator=\"\" def bill_entry(): global bill_in global", "set the total from here total.set #++++++++++++++++++++++++++++++Varibales_inset+++++++++++++++++++++++++++++++++ order_bef = IntVar()", "= StringVar() spassword = StringVar() label = Label(dframe, font=(\"arial\",16, \"bold\"),", "#calculation #first calculating seconds in one day that will ease", "lblReference.grid(row=0,column=0) b=Entry(f1,font=(\"arial\", 16, \"bold\"), textvariable=rand, bd=10,insertwidth=4,fg=\"white\",bg=\"black\", justify = \"left\") b.grid(row=0,column=1)", "=\"\" no=\"\" Tops = Frame(root, width=1600 ,height=50,bg=\"goldenrod4\", relief=RIDGE) Tops.pack(side=TOP) f1", "bd=10,insertwidth=4,bg=\"red\",fg=\"white\", justify = \"right\").grid(row=0,column=1) #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! lblReference = Label(f1,font=(\"arial\", 16,\"bold\"), text=\"Reference\",bd=16,fg=\"white\",bg=\"green\",anchor=\"w\",", "= cus_no.get() s = employee.get() files = {\"a\": \"\", \"b\":", "\"k\": \"\", \"l\": \"\", \"m\": \"\", \"n\": \"\", \"o\": \"\",", "import os import sys DIR = os.getcwd() print(DIR) lblInfo =", "bill_in = \"\" def rupen(): global rupen rupen = rupen", "inputs\") win2.geometry(\"1600x800\") framex = Frame(win2,width=1600,bg=\"RoyalBlue4\",height=100,relief=GROOVE).pack(side=TOP) frame1 = Frame(win2,width=775, height=750,bg=\"white\", relief=SUNKEN).pack()", "label3 = Label(dframe,font=(\"arial\",16,\"bold\"),fg=\"white\",bg=\"black\",text=\"sender_password\", relief=SUNKEN).pack(side=LEFT) entry3= Entry(dframe,font=(\"arial\",16,\"bold\"),fg=\"white\",textvariable=spassword,insertwidth=1,relief=SUNKEN).pack() dialog.mainloop() #btnEmail = Button(root,font=(\"arial\",", "for the product is actually %s left\" %(self.hour-self.record_timeD)) #++++++++++++++++++++++++++++++++++++++++tinydb example++++++++++++++++++++++", "= shirt_mm+pant_mm+sale_mm+buy_mm+deposite_mm+withdraw_mm+coat_mm+order_mm file.write(\"Total:-{}\".format(totalx)) file.write(\"shirt:-{}\".format(shirt_mm)) file.write(\"pant_mm:-{}\".format(pant_mm)) file.write(\"sale_mm:-{}\".format(sale_mm)) file.write(\"buy_mm:-{}\".format(buy_mm)) file.write(\"deposite_mm:-{}\".format(deposite_mm)) file.write(\"withdraw_mm:-{}\".format(withdraw_mm)) file.write(\"coat:-{}\".format(coat_mm))", "'''def _image(image): image = image.set(imageloc) return image #image = Image.open(\"/root/Desktop/Desktop/anonymous/5.png\")", "lblInfo.pack() #===========================================================Calculator================================== \"\"\"def current_dir(): import os import sys DIR =", "da = int(da) file.write(da) try: file = open(\"/records.txt\", \"r\") except:", "sys DIR = os.getcwd() print(DIR) lblInfo = Label(Tops, font=(\"arial\",60, \"italic\"),text=current_dir,fg=\"black\",bg=\"powder", "except: print(\"creating the file from script {}\".format(__file__)) file = open(\"/records.txt\",\"w\")", "from tinydb import * import os import pickle #from database1", "font=(\"arial\",20,\"bold\"), text=\"8\",bg=\"dim gray\", command=lambda: btnClick(8)).grid(row=2,column=1) btn9=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"), text=\"9\",bg=\"dim gray\",", "IntVar() daily_info = IntVar() sales = IntVar() buy = IntVar()", "command=lambda: btnClick(\"/\")).grid(row=5,column=3) #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! rand = StringVar() #lblReference = Label(f1,font=(\"arial\", 16,\"bold\"),", "TinyDB(\"/records.json\") #print(monthly) #print(b) #fuck = c.get() a = order_bef.get() b", "the price inputs\") win2.geometry(\"1600x800\") framex = Frame(win2,width=1600,bg=\"RoyalBlue4\",height=100,relief=GROOVE).pack(side=TOP) frame1 = Frame(win2,width=775,", "from tkinter import * import random import time from PIL", "textvariable=order,bd=8,fg=\"white\",bg=\"black\").grid(row=10,column=0) lblcustomer=Label(f1,font=(\"arial\",16,\"bold\"),bg=\"powder blue\",text=\"cus_name:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=9,column=1) no=Entry(f1,font=(\"arial\",16, \"bold\"),bd=8,bg=\"black\",fg=\"white\",insertwidth=1, textvariable=cus_name).grid(row=10,column=1) lblmonthly=Label(f1, font=(\"arial\",16,\"bold\"),bg=\"powder blue\",text=\"monthly:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=5,column=2) monthly=StringVar()", "textvariable=deposite, bg=\"black\", fg=\"white\", justify=\"left\").grid(row=4, column=1) lblBankwith=Label(f1, font=(\"arial\", 16, \"bold\"),fg=\"black\",bg=\"powder blue\",text=\"Bank_Withdraw\",", "= total.get() time = datetime.now() day = time.day month =", "db.insert({\"totaldy\":\"total\"}), db.insert({\"employeid\":\"employee\"}) for db in range(1): print(db) files = list(files)", "relief=SUNKEN).pack() frame2 = Frame(win2, width=775,height=750,bg=\"black\", relief=FLAT).pack() #==++++===========================title============================= llb1 = Label(framex,font=(\"arial\",", "= total_bank.get() l = bank_deposite.get() m = bank_withdraw.get() n =", "IntVar() #order before the 60 stock = IntVar() delivery =", "\".txt\" if os.path.isfile(new_file_name): #if the newfilename exists print(\"using the file", "root.mainloop() #for the revies of the follow in the sorry", "main(): # root.mainloop() #for the revies of the follow in", "btnClick(\"+\")).grid(row=3,column=6) #btn10=Button(f2,padx=16,padx=16, fg=\"blue\", font(\"arial\",5,\"bold\"), # text=\"rupen\",bg=\"powder blue\", command=rupen).grid(row=3,column=5) #def function():", "= TinyDB(\"/databse/d4ta.json\") #db.insert({\"cus_number\":\"98938232\", \"cus_name\":\"rupen\"}) #def no_y(): # lis = db.all()", "withdraw_mm = withdraw.get() coat_mm = coat.get() order_mm = order.get() total_mm", "IntVar() stock_full = IntVar() shrting = IntVar() pant = IntVar()", "relief=FLAT).pack() #==++++===========================title============================= llb1 = Label(framex,font=(\"arial\", 20,\"italic\"),bg=\"powder blue\",fg=\"green\",text=\"INPUT THE PRICES\",relief=GROOVE).pack() win2.mainloop()", "btn1=Button(f2,padx=16,pady=16,bd=8,text=\"1\",font=(\"arial\", 20, \"bold\") ,bg=\"dim gray\", command=lambda: btnClick(1)).grid(row=4,column=2) Multiply=Button(f2,padx=16,pady=16,bd=8,text=\"*\", bg=\"dim gray\",", "= Tk() root.geometry(\"1600x800+0+0\") root.title(\"Suman_dai_ko_DHOKAN\") root.configure(bg=\"goldenrod4\") text_Input = StringVar() operator =\"\"", "win = Toplevel() win.title(\"bills\") winF = Frame(win, bg=\"black\",relief=SUNKEN).pack() winE =", "Frame(root, width = 300,height = 700,bg=\"dark slate blue\",relief=SUNKEN) f2.pack(side=RIGHT) #f3=", "= IntVar() employee = IntVar() ###############################class of algoriths######################### class __main():", "16, \"bold\"), textvariable=rand, bd=10,insertwidth=4,bg=\"red\",fg=\"white\", justify = \"right\").grid(row=0,column=1) #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! lblReference =", "hourSec = 60 * 60 * 60 minuteSec = 60", "here total.set #++++++++++++++++++++++++++++++Varibales_inset+++++++++++++++++++++++++++++++++ order_bef = IntVar() stock_full = IntVar() shrting", "bold\"),text=\"Botique Management Systewm\",fg=\"white\", bg=\"dark slate blue\", bd=10, anchor=\"w\", relief=RIDGE) lblInfo.pack()", "font=(\"arial\", 16, \"bold\"),bg=\"powder blue\",text=\"Total:\",fg=\"black\").grid(row=7,column=2) totalx=Entry(f1, font=(\"arial\", 16, \"bold\"),bg=\"black\",textvariable=total,fg=\"white\",insertwidth=1,bd=10).grid(row=8,column=2) lblemployee =", "self.now = datetime() self.hour = now.hour self.minute = now.minute self.second", "fg=\"white\", bg=\"black\", text=\"your_email\").pack(side=LEFT) entry1 = Entry(dframe, font=(\"arial\",16,\"bold\"), fg=\"white\",bg=\"black\", textvariable=email,insertwidth=1,bd=5).pack(side=RIGHT) label1", "if \"rupen\" in cmd_active: if \"rupen\" in cmd_active[1]: if \"ronley\"", "Label(framex,font=(\"arial\", 20,\"italic\"),bg=\"powder blue\",fg=\"green\",text=\"INPUT THE PRICES\",relief=GROOVE).pack() win2.mainloop() ###########################sending emails############################ def __send_email():", "hour = str(time.hour) second = str(time.second) year = str(time.year) minute", "\"bold\"),bd=10, fg=\"white\",bg=\"black\", textvariable=withdraw, insertwidth=1).grid(row=4,column=2) coating=Label(f1, font=(\"arial\", 16, \"bold\"),text=\"coat_mm:\", bg=\"powder blue\",fg=\"black\",anchor=\"e\").grid(row=5,column=0)", "# command=bill_in).pack(anchor=NE) root.mainloop() #__database() #add1=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"), #text=\"+\",bg=\"powder blue\", command=lambda:", "def bill_in(): ##assuming the variable as bill number .get var", "llb1 = Label(framex,font=(\"arial\", 20,\"italic\"),bg=\"powder blue\",fg=\"green\",text=\"INPUT THE PRICES\",relief=GROOVE).pack() win2.mainloop() ###########################sending emails############################", "day = str(d.day) year = str(d.year) hour = str(d.hour) minute", "import randint root = Tk() root.geometry(\"1600x800+0+0\") root.title(\"Suman_dai_ko_DHOKAN\") root.configure(bg=\"goldenrod4\") text_Input =", "= StringVar() imageloc=Entry(win1,font=(\"arial\",16,\"italic\"),bg=\"black\",fg=\"white\",bd=5,insertwidth=1,relief=GROOVE,textvariable=ima).pack() imageButt=Button(win1,font=(\"arial\",20, \"bold\"),bd=5,bg=\"white\",fg=\"white\",command= lambda: _image(image)).pack() '''def _image(image): image", "= dir #return dir \"\"\" #randomBtn=Button(f1,pady=16,padx=16,bd=8,bg=\"powder blue\", text=\"C_dir\", command=lambda: current_dir(dir)).pack(side=TOP)", "#++++++++++++++++++++++++++++++Varibales_inset+++++++++++++++++++++++++++++++++ order_bef = IntVar() stock_full = IntVar() shrting = IntVar()", "import datetime from tinydb import * import os import pickle", "open(\"{}\".format(file_name),\"w+\") totalx = shirt_mm+pant_mm+sale_mm+buy_mm+deposite_mm+withdraw_mm+coat_mm+order_mm file.write(\"Total:-{}\".format(totalx)) file.write(\"shirt:-{}\".format(shirt_mm)) file.write(\"pant_mm:-{}\".format(pant_mm)) file.write(\"sale_mm:-{}\".format(sale_mm)) file.write(\"buy_mm:-{}\".format(buy_mm)) file.write(\"deposite_mm:-{}\".format(deposite_mm))", "!= 0: print(\"this is are the files written in python\\\\n", "0: print(\"this is are the files written in python\\\\n check", "= now.second self.year = now.year self.month = now.month self.day =", "sale.get() buy_mm = buy.get() deposite_mm = deposite.get() withdraw_mm = withdraw.get()", "= IntVar() ###############################class of algoriths######################### class __main(): def __init__(self): self.order", "def btnClick(numbers): global operator operator = operator + str(numbers) text_Input.set(operator)", "blue\",text=\"employee name:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=9,column=2) employx= Entry(f1,font=(\"arial\", 16,\"bold\"),textvariable=employee,insertwidth=1,bg=\"black\",fg=\"white\",bd=10).grid(row=10,column=2) ###############################database for the project###################### '''def", "btnClick(9)).grid(row=2,column=2) #!!!!!!!!!!!!!!!!!!!!!!additions!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Addition=Button(f2,padx=16,pady=16,bd=8,text=\"+\",fg=\"black\",bg=\"dim gray\", command=lambda: btnClick(\"+\")).grid(row=2,column=3) btn6=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"),text=\"4\", bg=\"dim", "font=(\"arial\", 16, \"bold\"), bg=\"powder blue\", text=\"outgoing:\", fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=7,column=1) outx=Entry(f1,font=(\"arial\", 16, \"bold\"),textvariable=out,", "else: file = open(\"{}.txt\".format(i+1), \"w+\") created with name {}\".format(file))''' #creating", "60 minuteSec = 60 * 60 files = {\"a\":\"\", \"b\":\"\",\"c\":\"\",\"d\":\"\",\"e\":\"\",\"f\":\"\",\"g\":\"\",\"h\":\"\",\"i\":\"\",\"j\":\"\"", "Image.open(\"/root/Desktop/Desktop/anonymous/5.png\") imae = Label(win1,font=(\"arial\", 20,\"italic\"),width=300, height=168,bg=\"black\",fg=\"white\", text=image,relief=FLAT).pack() win1.mainloop()''' #=============================getting all", "is no limit in the system of teh win1.title(\"this is", "\"\"\" #randomBtn=Button(f1,pady=16,padx=16,bd=8,bg=\"powder blue\", text=\"C_dir\", command=lambda: current_dir(dir)).pack(side=TOP) def btnClick(numbers): global operator", "window in which there is nothing in the function #of", "written in python\\\\n check the file.txt for debug \") da", "fg=\"green\",bd=10, relief=RAISED).pack() ima = StringVar() imageloc=Entry(win1,font=(\"arial\",16,\"italic\"),bg=\"black\",fg=\"white\",bd=5,insertwidth=1,relief=GROOVE,textvariable=ima).pack() imageButt=Button(win1,font=(\"arial\",20, \"bold\"),bd=5,bg=\"white\",fg=\"white\",command= lambda: _image(image)).pack()", "height=500,bg=\"RoyalBlue4\", relief=GROOVE) customer_info.pack(side=RIGHT) others_info = Frame(win1, width=100, height=100,bg=\"RoyalBlue4\",relief=GROOVE) others_info.pack(side=BOTTOM) all_info", "\"bold\"), textvariable=pant, insertwidth=1, bd=10,bg=\"black\",fg=\"white\", justify=\"left\").grid(row=2,column=1) sales=Label(f1,font=(\"arial\",16, \"bold\"), text=\"sales_total:\",bg=\"powder blue\",fg=\"black\",anchor=\"w\",bd=8,relief=GROOVE).grid(row=1,column=2) salex=Entry(f1,font=(\"arial\",16,", "os.getcwd() print(DIR) lblInfo = Label(Tops, font=(\"arial\",60, \"italic\"),text=current_dir,fg=\"black\",bg=\"powder blue\",bd=10, anchor=\"W\") lblInfo.pack()", "dialog.title(\"Send emails\") dialog.geometry(\"800x800\") dframe = Frame(dialog,width=800,height=800,bg=\"white\",relief=SUNKEN).pack() email = StringVar() password", "\"f\": \"\", \"g\": \"\", \"h\": \"\", \"i\": \"\", \"j\": \"\"", "16, \"bold\"),bg=\"black\",textvariable=total,fg=\"white\",insertwidth=1,bd=10).grid(row=8,column=2) lblemployee = Label(f1,font=(\"arial\", 16, \"bold\"),bg=\"powder blue\",text=\"employee name:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=9,column=2) employx=", "fg=\"black\",font=(\"arial\", 20, \"bold\"),text=\"C\",bg=\"dim gray\", command=btnClearDisplay).grid(row=5,column=1) btnEquals=Button(f2,padx=16,pady=16,fg=\"black\",bd=8,text=\"=\",bg=\"dim gray\", font=(\"arial\", 20,\"bold\"), command=btnEqualsInput).grid(row=5,column=2)", "None: bills.insert({\"billInput\": bill, \"billOutput\": billo}) win = Toplevel() win.title(\"bills\") winF", "db.insert({\"employeid\":\"employee\"}) for db in range(1): print(db) files = list(files) file", "emails############################ def __send_email(): '''import smtplib gmail = smtplib.SMTP(\"smtp.gmail.com\", 587) gmail.starttls()", "daySec = daysec hourSec = 60 * 60 * 60", "command=lambda: btnClick(6)).grid(row=3,column=2) Subtract=Button(f2,padx=16,pady=16,bd=8,text=\"-\", bg=\"dim gray\", command=lambda: btnClick(\"-\")).grid(row=3,column=3) btn3=Button(f2,padx=16,pady=16,bd=8,text=\"3\",font=(\"arial\", 20, \"bold\")", "taken that will be notified before the #60 hours #changing", "blue\", bd=10, anchor=\"w\", relief=RIDGE) lblInfo.pack() lblInfo = Label(Tops, font=(\"arial\",30, \"bold\"),text=localtime,fg=\"white\",bg=\"black\",", "random import time from PIL import Image from datetime import", "window:\") win1.geometry(\"1600x800+0+0\") #win1.configure(bg=\"silver\") my_info = Frame(win1, width=600, height=700,bg=\"RoyalBlue4\",relief=GROOVE) my_info.pack(side=LEFT) customer_info", "Toplevel(root) #nos.title(\"this is nos window\") #return a = Entry(f2,font=(\"arial\", 20,\"bold\"),", "\"bold\"),text=\"C\",bg=\"dim gray\", command=btnClearDisplay).grid(row=5,column=1) btnEquals=Button(f2,padx=16,pady=16,fg=\"black\",bd=8,text=\"=\",bg=\"dim gray\", font=(\"arial\", 20,\"bold\"), command=btnEqualsInput).grid(row=5,column=2) #btn2=Button(f2,padx=16,pady=16,bd=8,fg=\"black\",text=\"2\",bg=\"dim gray\",", "#Label (root,bg=\"white\",width=120,height=120, image=ima).pack() bill_in = StringVar() bill_out = StringVar() shrting=Label(f1,font=(\"arial\",", "notified before the #60 hours #changing all the formats to", "file = open(\"{}\".format(file_name),\"w+\") totalx = shirt_mm+pant_mm+sale_mm+buy_mm+deposite_mm+withdraw_mm+coat_mm+order_mm file.write(\"Total:-{}\".format(totalx)) file.write(\"shirt:-{}\".format(shirt_mm)) file.write(\"pant_mm:-{}\".format(pant_mm)) file.write(\"sale_mm:-{}\".format(sale_mm))", "height=750,bg=\"white\", relief=SUNKEN).pack() frame2 = Frame(win2, width=775,height=750,bg=\"black\", relief=FLAT).pack() #==++++===========================title============================= llb1 =", "bg=\"black\", fg=\"white\", textvariable=coat, insertwidth=1, justify=\"left\",bd=10).grid(row=6,column=0) lablsari=Label(f1,font=(\"arial\", 16, \"bold\"), bg=\"powder blue\",text=\"sari", "window\") # return #def no_y(): #nos = Toplevel(root) #nos.title(\"this is", "Entry(dframe,font=(\"arial\",16,\"bold\"),fg=\"white\",textvariable=spassword,insertwidth=1,relief=SUNKEN).pack() dialog.mainloop() #btnEmail = Button(root,font=(\"arial\", 16, \"bold\"), bg=\"black\",fg=\"white\",text=\"email\",command=lambda: __send_email(),relief=GROOVE).pack() #================================next", "= 60 * 60 * 60 minuteSec = 60 *", "lblcustomer=Label(f1,font=(\"arial\",16,\"bold\"),bg=\"powder blue\",text=\"cus_name:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=9,column=1) no=Entry(f1,font=(\"arial\",16, \"bold\"),bd=8,bg=\"black\",fg=\"white\",insertwidth=1, textvariable=cus_name).grid(row=10,column=1) lblmonthly=Label(f1, font=(\"arial\",16,\"bold\"),bg=\"powder blue\",text=\"monthly:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=5,column=2) monthly=StringVar() monthx=Entry(f1,font=(\"arial\",16,\"bold\"),show=\"blank\",bg=\"black\",textvariable=monthly,insertwidth=1,fg=\"white\",bd=10).grid(row=6,column=2)", "16, \"bold\"),fg=\"black\",bg=\"powder blue\",text=\"Bank_Withdraw\", anchor=\"e\",relief=GROOVE).grid(row=3,column=2) withdrawx=Entry(f1,font=(\"arial\",16, \"bold\"),bd=10, fg=\"white\",bg=\"black\", textvariable=withdraw, insertwidth=1).grid(row=4,column=2) coating=Label(f1,", "cmd_active: if \"rupen\" in cmd_active[1]: if \"ronley\" in cmd_active[2]:''' #==============================another", "check: for item in db: data = open(\"/records.txt\",\"wb\") #with open(\"/records.txt\",\"wb\")", "datetime import datetime from tinydb import * import os import", "= Label(f1,font=(\"arial\", 16, \"bold\"),bg=\"powder blue\",text=\"employee name:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=9,column=2) employx= Entry(f1,font=(\"arial\", 16,\"bold\"),textvariable=employee,insertwidth=1,bg=\"black\",fg=\"white\",bd=10).grid(row=10,column=2) ###############################database", "16 ,\"bold\"),textvariable=password, insertwidth=1,bd=5).pack(side=RIGHT) Label2 =Label(dframe,font=(\"arial\",16, \"bold\"),fg=\"white\",bg=\"black\", text=\"sender_email\",relief=SUNKEN).pack(side=LEFT) entry2 = Entry(dframe,font=(\"arial\",16,", "delivery_report = IntVar() daily_info = IntVar() sales = IntVar() buy", "print(\"the time for the product is actually %s left\" %(self.hour-self.record_timeD))", "Image.open(img) #Label (root,bg=\"white\",width=120,height=120, image=ima).pack() bill_in = StringVar() bill_out = StringVar()", "i in range(5): if os.path.isfile(i): pass else: file = open(\"{}.txt\".format(i+1),", "localtime=time.asctime(time.localtime(time.time())) #datetime=Label(Tops,font(\"arial\",20,\"bold\"),text=nowTime,bd=10 ,bg=\"black\", #fg=\"white\", anchor=\"w\").pack() #====================================debugged======================== shirt = IntVar() pant", "= {\"a\":\"\", \"b\":\"\",\"c\":\"\",\"d\":\"\",\"e\":\"\",\"f\":\"\",\"g\":\"\",\"h\":\"\",\"i\":\"\",\"j\":\"\" ,\"k\":\"\",\"l\":\"\",\"m\":\"\",\"n\":\"\",\"o\":\"\",\"p\":\"\",\"q\":\"\",\"r\":\"\",\"s\":\"\"}''' #files = list(files) '''for data in", "the further operations daysec = (24*60) * 60 * 60", "= Frame(win2,width=775, height=750,bg=\"white\", relief=SUNKEN).pack() frame2 = Frame(win2, width=775,height=750,bg=\"black\", relief=FLAT).pack() #==++++===========================title=============================", "= operator + str(numbers) text_Input.set(operator) def btnClearDisplay(): global operator operator=\"\"", "file = open(\"/records.txt\", \"r\") except: print(\"creating the file from script", "if len(item) == len(file1): break if item != file: #item", "= Entry(dframe,font=(\"arial\", 16 ,\"bold\"),textvariable=password, insertwidth=1,bd=5).pack(side=RIGHT) Label2 =Label(dframe,font=(\"arial\",16, \"bold\"),fg=\"white\",bg=\"black\", text=\"sender_email\",relief=SUNKEN).pack(side=LEFT) entry2", "#db.insert({\"name\":\"<NAME>\"}) name = Query() #db(name.type == \"changed\") d = datetime.now()", "command=lambda: btnClick(8)).grid(row=2,column=1) btn9=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"), text=\"9\",bg=\"dim gray\", command=lambda: btnClick(9)).grid(row=2,column=2) #!!!!!!!!!!!!!!!!!!!!!!additions!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", "= stock_full.get() c = shrting.get() d = pant.get() e =", "Label2 =Label(dframe,font=(\"arial\",16, \"bold\"),fg=\"white\",bg=\"black\", text=\"sender_email\",relief=SUNKEN).pack(side=LEFT) entry2 = Entry(dframe,font=(\"arial\",16, \"bold\"),bd=5,fg=\"white\",bg=\"black\",textvariable=semail,insertwidth=1).pack(side=LEFT) label3 =", "recorded bill numbers def bill_in(): ##assuming the variable as bill", "lblemployee = Label(f1,font=(\"arial\", 16, \"bold\"),bg=\"powder blue\",text=\"employee name:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=9,column=2) employx= Entry(f1,font=(\"arial\", 16,\"bold\"),textvariable=employee,insertwidth=1,bg=\"black\",fg=\"white\",bd=10).grid(row=10,column=2)", "PIL import Image from datetime import datetime from tinydb import", "IntVar() withdraw = IntVar() coat = IntVar() order = IntVar()", "\"r.txt\" if os.path.isfile(file_name): expand = 1 while True: expand +=", "q = cus_name.get() r = cus_no.get() s = employee.get() files", "bg=\"powder blue\", text=\"outgoing:\", fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=7,column=1) outx=Entry(f1,font=(\"arial\", 16, \"bold\"),textvariable=out, bd=8,fg=\"white\",bg=\"black\",insertwidth=1).grid(row=8,column=1) ordering=Label(f1,font=(\"arial\",16,\"bold\"),bg=\"powder blue\",text=\"order_info:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=9,column=0)", "str(time.month) hour = str(time.hour) second = str(time.second) year = str(time.year)", "bill number .get var bill = bill_in.get() billo = bill_out.get()", "= open(\"/file.txt\", \"wb\") da = \"\" for data in files:", "\"\", \"m\": \"\", \"n\": \"\", \"o\": \"\", \"p\": \"\", \"q\":", "= str(time.hour) second = str(time.second) year = str(time.year) minute =", "fg=\"white\", textvariable=coat, insertwidth=1, justify=\"left\",bd=10).grid(row=6,column=0) lablsari=Label(f1,font=(\"arial\", 16, \"bold\"), bg=\"powder blue\",text=\"sari mm:\",", "spassword = StringVar() label = Label(dframe, font=(\"arial\",16, \"bold\"), fg=\"white\", bg=\"black\",", "Engineer\",bg=\"powder blue\", fg=\"green\",bd=10, relief=RAISED).pack() ima = StringVar() imageloc=Entry(win1,font=(\"arial\",16,\"italic\"),bg=\"black\",fg=\"white\",bd=5,insertwidth=1,relief=GROOVE,textvariable=ima).pack() imageButt=Button(win1,font=(\"arial\",20, \"bold\"),bd=5,bg=\"white\",fg=\"white\",command=", "in the sorry of the same of the tkinter in", "Tops.pack(side=TOP) f1 = Frame(root, width = 800 ,height=500,bg=\"goldenrod4\",relief=SUNKEN) f1.pack(side=LEFT) f2", "bg=\"black\",bd=10, fg=\"white\",textvariable=sari, insertwidth=1).grid(row=6,column=1) buying=Label(f1,font=(\"arial\", 16, \"bold\"), bg=\"powder blue\",text=\"buy_info:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=7,column=0) buyx=Entry(f1,font=(\"arial\",16, \"bold\"),bd=8,", "Tops = Frame(root, width=1600 ,height=50,bg=\"goldenrod4\", relief=RIDGE) Tops.pack(side=TOP) f1 = Frame(root,", "font=(\"arial\",12, \"bold\"),text=\"info\", bd=8,bg=\"black\",command=ano_win1,fg=\"white\",relief=RAISED).pack(side=LEFT) yes=Button(root,padx=16,pady=16,font=(\"arial\",12, \"bold\"),text=\"Done\",bd=8,bg=\"black\", fg=\"white\", command=_calculation(),relief=RAISED).pack(side=RIGHT) panting=Label(f1,font=(\"arial\",20, \"bold\"), text=\"pant_mm:\",", "db.insert({\"salling\":\"sales\"}), db.insert({\"buying\":\"buy\"}), db.insert({\"customern\":\"customer\"}), db.insert({\"monthly_info\":\"monthly\"}), db.insert({\"totaldy\":\"total\"}), db.insert({\"employeid\":\"employee\"}) for db in range(1):", "#file1 = pickle.load(file) if len(item) == len(file1): break if item", "import * from random import randint root = Tk() root.geometry(\"1600x800+0+0\")", "the name already existed file_name = \"r.txt\" if os.path.isfile(file_name): expand", "text=\"sender_email\",relief=SUNKEN).pack(side=LEFT) entry2 = Entry(dframe,font=(\"arial\",16, \"bold\"),bd=5,fg=\"white\",bg=\"black\",textvariable=semail,insertwidth=1).pack(side=LEFT) label3 = Label(dframe,font=(\"arial\",16,\"bold\"),fg=\"white\",bg=\"black\",text=\"sender_password\", relief=SUNKEN).pack(side=LEFT) entry3=", "the #calculation #first calculating seconds in one day that will", "print(\"using the file {}\".format(new_file_name)) #file = open(\"{}\".format(new_file_name), \"w+\") continue else:", "imae = Label(win1,font=(\"arial\", 20,\"italic\"),width=300, height=168,bg=\"black\",fg=\"white\", text=image,relief=FLAT).pack() win1.mainloop()''' #=============================getting all the", "1 while True: expand += 1 new_file_name = file_name.split(\".txt\")[0] +", "20, \"bold\"), command=lambda: btnClick(0)).grid(row=5,column=0) btnClear=Button(f2,pady=16,padx=16,bd=8, fg=\"black\",font=(\"arial\", 20, \"bold\"),text=\"C\",bg=\"dim gray\", command=btnClearDisplay).grid(row=5,column=1)", "btn8=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"), text=\"8\",bg=\"dim gray\", command=lambda: btnClick(8)).grid(row=2,column=1) btn9=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"),", "the files written in python\\\\n check the file.txt for debug", "blue\", fg=\"black\",anchor=\"w\",relief=GROOVE).grid(row=1,column=0) shirts=Entry(f1,font=(\"arial\", 16, \"italic\"), bd=10, textvariable=shirt, insertwidth=1,bg=\"black\",fg=\"white\", justify=\"left\").grid(row=2,column=0) owner=Button(root,padx=16,pady=16,", "coating=Label(f1, font=(\"arial\", 16, \"bold\"),text=\"coat_mm:\", bg=\"powder blue\",fg=\"black\",anchor=\"e\").grid(row=5,column=0) coatx=Entry(f1, font=(\"arial\", 16, \"bold\"),", "data in files: if len(data) != 0: print(\"this is are", "StringVar() #lblReference = Label(f1,font=(\"arial\", 16,\"bold\"), text=\"Reference\",bd=16,fg=\"red\",bg=\"red\",anchor=\"w\",relief=RIDGE).grid(row=0,column=0) #txtReference=Entry(f1,font=(\"arial\", 16, \"bold\"), textvariable=rand,", "the order taken that will be notified before the #60", "fix = Button(root, bd=10,bg=\"black\",fg=\"white\",command=_price_inputs,relief=GROOVE).pack(side=BOTTOM) btnru = Button(root, font=(\"arial 20 bold\"),bd=20,", "project###################### '''def __database(): db = TinyDB(\"/records.json\") #print(monthly) #print(b) #fuck =", "587) gmail.starttls() _file = open(\"/root/Desktop/Desktop/python/\") gmail.login(\"username\", \"password\") msg = \"YOUR", "Management Systewm\",fg=\"white\", bg=\"dark slate blue\", bd=10, anchor=\"w\", relief=RIDGE) lblInfo.pack() lblInfo", "blue\", fg=\"black\", anchor=\"e\",relief=GROOVE).grid(row=3, column=1) depositex=Entry(f1,font=(\"arial\",16,\"bold\"),bd=10, textvariable=deposite, bg=\"black\", fg=\"white\", justify=\"left\").grid(row=4, column=1)", "btn6=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"),text=\"4\", bg=\"dim gray\", command=lambda: btnClick(4)).grid(row=3,column=0) btn5=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"),text=\"5\",", "#==============================another windows about me===================== def ano_win1(): win1 = Toplevel() #this", "print(\"its printed\") print(reading) file.close() #db.insert({\"name\":\"<NAME>\"}) name = Query() #db(name.type ==", "= StringVar() password = StringVar() semail = StringVar() spassword =", "= cus_name.get() r = cus_no.get() s = employee.get() files =", "file.write(\"Total:-{}\".format(totalx)) file.write(\"shirt:-{}\".format(shirt_mm)) file.write(\"pant_mm:-{}\".format(pant_mm)) file.write(\"sale_mm:-{}\".format(sale_mm)) file.write(\"buy_mm:-{}\".format(buy_mm)) file.write(\"deposite_mm:-{}\".format(deposite_mm)) file.write(\"withdraw_mm:-{}\".format(withdraw_mm)) file.write(\"coat:-{}\".format(coat_mm)) file.write(\"order:-{}\".format(order_mm)) reading", "justify=\"right\").grid(columnspan=4) btn7=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"), text=\"7\",bg=\"dim gray\", command=lambda: btnClick(7)).grid(row=2,column=0) btn8=Button(f2,padx=16,pady=16,bd=8, fg=\"black\",", "to the seconds that will be easy for the #calculation", "Query() #db(name.type == \"changed\") d = datetime.now() month = str(d.month)", "if os.path.isfile(i): pass else: file = open(\"{}.txt\".format(i+1), \"w+\") created with", "\"\", \"h\": \"\", \"i\": \"\", \"j\": \"\" , \"k\": \"\",", "if os.path.isfile(new_file_name): #if the newfilename exists print(\"using the file {}\".format(new_file_name))", "pickle.load(file) if len(item) == len(file1): break if item != file:", "width=775,height=750,bg=\"black\", relief=FLAT).pack() #==++++===========================title============================= llb1 = Label(framex,font=(\"arial\", 20,\"italic\"),bg=\"powder blue\",fg=\"green\",text=\"INPUT THE PRICES\",relief=GROOVE).pack()", "if self.hour == self.record_timeD: print(\"the time for the product is", "btnClearDisplay(): global operator operator=\"\" text_Input.set(\"\") def btnEqualsInput(): global operator sumup=str(eval(operator))", "self.day = now.day self.record_time = record_time if self.hour == self.record_timeD:", "time.year minute = time.minute #setting the filename using the loop", "datetime.now() month = str(d.month) day = str(d.day) year = str(d.year)", "item != file: #item = str(item) file.write(\"%s\" %(item)) time.sleep(1) print(\"done", "\"bold\"),text=\"Done\",bd=8,bg=\"black\", fg=\"white\", command=_calculation(),relief=RAISED).pack(side=RIGHT) panting=Label(f1,font=(\"arial\",20, \"bold\"), text=\"pant_mm:\", bg=\"powder blue\",fg=\"black\",anchor=\"w\",relief=GROOVE).grid(row=1,column=1) pantx=Entry(f1,font=(\"arial\",16, \"bold\"),", "= shrting.get() d = pant.get() e = sari.get() f =", "total_mm = total.get() time = datetime.now() day = time.day month", "* 30 daySec = daysec hourSec = 60 * 60", "Frame(win2, width=775,height=750,bg=\"black\", relief=FLAT).pack() #==++++===========================title============================= llb1 = Label(framex,font=(\"arial\", 20,\"italic\"),bg=\"powder blue\",fg=\"green\",text=\"INPUT THE", "main loop #there is no limit in the system of", "password = StringVar() semail = StringVar() spassword = StringVar() label", "IntVar() order_info = IntVar() daily_cash = IntVar() cus_name = IntVar()", "width=100, height=100,bg=\"RoyalBlue4\",relief=GROOVE) others_info.pack(side=BOTTOM) all_info = Frame(win1, width=50, height=50,bg=\"RoyalBlue4\",relief=RAISED) all_info.pack() lblname=Label(my_info,font=(\"arial\",20,\"italic\"),text=\"<NAME>\",bg=\"powder", "str(time.day) month = str(time.month) hour = str(time.hour) second = str(time.second)", "* import random import time from PIL import Image from", "self.year = now.year self.month = now.month self.day = now.day self.record_time", "blue\",fg=\"black\",anchor=\"w\",bd=8,relief=GROOVE).grid(row=1,column=2) salex=Entry(f1,font=(\"arial\",16, \"bold\"),bg=\"black\",fg=\"white\",textvariable=sale,insertwidth=1,bd=10,justify=\"left\").grid(row=2,column=2) buying=Label(f1,font=(\"arial\",16, \"bold\"), text=\"buying_something: \",bg=\"powder blue\",fg=\"black\", anchor=\"e\", relief=GROOVE).grid(row=3,column=0)", "imageloc=Entry(win1,font=(\"arial\",16,\"italic\"),bg=\"black\",fg=\"white\",bd=5,insertwidth=1,relief=GROOVE,textvariable=ima).pack() imageButt=Button(win1,font=(\"arial\",20, \"bold\"),bd=5,bg=\"white\",fg=\"white\",command= lambda: _image(image)).pack() '''def _image(image): image = image.set(imageloc)", "day = time.day month = time.month hour = time.hour second", "= file_name.split(\".txt\")[0] + str(expand) + \".txt\" if os.path.isfile(new_file_name): #if the", "continue else: file_name = open(new_file_name, \"w+\") print(\"creating the file {}\".format(file_name))", "call #def yes_y(): # rupe = Toplevel(root) # rupe.title(\"this is", "== self.record_timeD: print(\"the time for the product is actually %s", "Entry(winF, insertwidth=10,insertheight=10,fg=\"white\",bg=\"black\",textvariable=bills).pack() win.mainloop() #l # command=bill_in).pack(anchor=NE) root.mainloop() #__database() #add1=Button(f2,padx=16,pady=16,bd=8, fg=\"black\",", "entry1 = Entry(dframe, font=(\"arial\",16,\"bold\"), fg=\"white\",bg=\"black\", textvariable=email,insertwidth=1,bd=5).pack(side=RIGHT) label1 = Label(dframe, font=(\"arial\",16,", "= IntVar() order_info = IntVar() delivery_report = IntVar() daily_info =", "import Image from datetime import datetime from tinydb import *", "= Frame(root, width = 800 ,height=500,bg=\"goldenrod4\",relief=SUNKEN) f1.pack(side=LEFT) f2 = Frame(root,", "ordering=Label(f1,font=(\"arial\",16,\"bold\"),bg=\"powder blue\",text=\"order_info:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=9,column=0) orderx=Entry(f1,font=(\"arial\",16,\"bold\"),insertwidth=1, textvariable=order,bd=8,fg=\"white\",bg=\"black\").grid(row=10,column=0) lblcustomer=Label(f1,font=(\"arial\",16,\"bold\"),bg=\"powder blue\",text=\"cus_name:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=9,column=1) no=Entry(f1,font=(\"arial\",16, \"bold\"),bd=8,bg=\"black\",fg=\"white\",insertwidth=1, textvariable=cus_name).grid(row=10,column=1) lblmonthly=Label(f1,", "daily_cash.get() q = cus_name.get() r = cus_no.get() s = employee.get()", "= 1 while True: expand += 1 new_file_name = file_name.split(\".txt\")[0]", "\"wb\") da = \"\" for data in files: if len(data)", "bd=10, anchor=\"w\", relief=RIDGE) lblInfo.pack() #===========================================================Calculator================================== \"\"\"def current_dir(): import os import", "\"b\":\"\",\"c\":\"\",\"d\":\"\",\"e\":\"\",\"f\":\"\",\"g\":\"\",\"h\":\"\",\"i\":\"\",\"j\":\"\" ,\"k\":\"\",\"l\":\"\",\"m\":\"\",\"n\":\"\",\"o\":\"\",\"p\":\"\",\"q\":\"\",\"r\":\"\",\"s\":\"\"}''' #files = list(files) '''for data in files: if", "blue\",text=\"cus_name:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=9,column=1) no=Entry(f1,font=(\"arial\",16, \"bold\"),bd=8,bg=\"black\",fg=\"white\",insertwidth=1, textvariable=cus_name).grid(row=10,column=1) lblmonthly=Label(f1, font=(\"arial\",16,\"bold\"),bg=\"powder blue\",text=\"monthly:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=5,column=2) monthly=StringVar() monthx=Entry(f1,font=(\"arial\",16,\"bold\"),show=\"blank\",bg=\"black\",textvariable=monthly,insertwidth=1,fg=\"white\",bd=10).grid(row=6,column=2) lbltotal=Label(f1,", "file.close() #db.insert({\"name\":\"<NAME>\"}) name = Query() #db(name.type == \"changed\") d =", "if len(reading) != None: print(\"its printed\") print(reading) file.close() #db.insert({\"name\":\"<NAME>\"}) name", "20, \"bold\"), text=\"Shirting:\",bg=\"powder blue\", fg=\"black\",anchor=\"w\",relief=GROOVE).grid(row=1,column=0) shirts=Entry(f1,font=(\"arial\", 16, \"italic\"), bd=10, textvariable=shirt,", "\"bold\"), text=\"buying_something: \",bg=\"powder blue\",fg=\"black\", anchor=\"e\", relief=GROOVE).grid(row=3,column=0) buyx=Entry(f1,font=(\"arial\", 16, \"bold\"), textvariable=buy,", "lblReference = Label(f1,font=(\"arial\", 16,\"bold\"), text=\"Reference\",bd=16,fg=\"white\",bg=\"green\",anchor=\"w\", relief=RIDGE) lblReference.grid(row=0,column=0) b=Entry(f1,font=(\"arial\", 16, \"bold\"),", "= Entry(dframe, font=(\"arial\",16,\"bold\"), fg=\"white\",bg=\"black\", textvariable=email,insertwidth=1,bd=5).pack(side=RIGHT) label1 = Label(dframe, font=(\"arial\",16, \"bold\"),", "s = employee.get() files = {\"a\": \"\", \"b\": \"\", \"c\":", "#root.ima = Image.open(img) #Label (root,bg=\"white\",width=120,height=120, image=ima).pack() bill_in = StringVar() bill_out", "def bill_entry(): global bill_in global bill_out bill_out = \"\" bill_in", "the newfilename exists print(\"using the file {}\".format(new_file_name)) #file = open(\"{}\".format(new_file_name),", "print(\"creating the file from script {}\".format(__file__)) file = open(\"/records.txt\",\"w\") finally:", "hour = time.hour second = time.second year = time.year minute", "blue\",text=\"buy_info:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=7,column=0) buyx=Entry(f1,font=(\"arial\",16, \"bold\"),bd=8, fg=\"white\",bg=\"black\",textvariable=buy,insertwidth=1).grid(row=8,column=0) outgoing =Label(f1, font=(\"arial\", 16, \"bold\"), bg=\"powder", "smtplib gmail = smtplib.SMTP(\"smtp.gmail.com\", 587) gmail.starttls() _file = open(\"/root/Desktop/Desktop/python/\") gmail.login(\"username\",", "employee = IntVar() ###############################class of algoriths######################### class __main(): def __init__(self):", "Bank_Total=Label(f1,font=(\"arial\",16,\"bold\"),text=\"Bank_Deposite: \", bg=\"powder blue\", fg=\"black\", anchor=\"e\",relief=GROOVE).grid(row=3, column=1) depositex=Entry(f1,font=(\"arial\",16,\"bold\"),bd=10, textvariable=deposite, bg=\"black\",", "= str(time.month) hour = str(time.hour) second = str(time.second) year =", "infos as the order taken that will be notified before", "is actually %s left\" %(self.hour-self.record_timeD)) #++++++++++++++++++++++++++++++++++++++++tinydb example++++++++++++++++++++++ #db = TinyDB(\"/databse/d4ta.json\")", "root = Tk() root.geometry(\"1600x800+0+0\") root.title(\"Suman_dai_ko_DHOKAN\") root.configure(bg=\"goldenrod4\") text_Input = StringVar() operator", "'''def __time(infos): time = datetime.now() day = str(time.day) month =", "###########################sending emails############################ def __send_email(): '''import smtplib gmail = smtplib.SMTP(\"smtp.gmail.com\", 587)", ",bg=\"dim gray\", command=lambda: btnClick(1)).grid(row=4,column=2) Multiply=Button(f2,padx=16,pady=16,bd=8,text=\"*\", bg=\"dim gray\", command=lambda: btnClick(\"X\")).grid(row=4,column=3) #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++", "is nos window\") #return a = Entry(f2,font=(\"arial\", 20,\"bold\"), textvariable=text_Input, bd=30,", "blue\",text=\"monthly:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=5,column=2) monthly=StringVar() monthx=Entry(f1,font=(\"arial\",16,\"bold\"),show=\"blank\",bg=\"black\",textvariable=monthly,insertwidth=1,fg=\"white\",bd=10).grid(row=6,column=2) lbltotal=Label(f1, font=(\"arial\", 16, \"bold\"),bg=\"powder blue\",text=\"Total:\",fg=\"black\").grid(row=7,column=2) totalx=Entry(f1, font=(\"arial\",", "IntVar() sari = IntVar() order_info = IntVar() delivery_report = IntVar()", "cmd_active if \"rupen\" in cmd_active: if \"rupen\" in cmd_active[1]: if", "db.insert({\"customern\":\"customer\"}), db.insert({\"monthly_info\":\"monthly\"}), db.insert({\"totaldy\":\"total\"}), db.insert({\"employeid\":\"employee\"}) for db in range(1): print(db) files", "str(d.month) day = str(d.day) year = str(d.year) hour = str(d.hour)", "self.second = now.second self.year = now.year self.month = now.month self.day", "from random import randint root = Tk() root.geometry(\"1600x800+0+0\") root.title(\"Suman_dai_ko_DHOKAN\") root.configure(bg=\"goldenrod4\")", "semail = StringVar() spassword = StringVar() label = Label(dframe, font=(\"arial\",16,", "dialog = Tk() dialog.title(\"Send emails\") dialog.geometry(\"800x800\") dframe = Frame(dialog,width=800,height=800,bg=\"white\",relief=SUNKEN).pack() email", "sarix=Entry(f1, font=(\"arial\", 16, \"bold\"), bg=\"black\",bd=10, fg=\"white\",textvariable=sari, insertwidth=1).grid(row=6,column=1) buying=Label(f1,font=(\"arial\", 16, \"bold\"),", "== len(file1): break if item != file: #item = str(item)", "root.geometry(\"1600x800+0+0\") root.title(\"Suman_dai_ko_DHOKAN\") root.configure(bg=\"goldenrod4\") text_Input = StringVar() operator =\"\" yes =\"\"", "#__database() #add1=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"), #text=\"+\",bg=\"powder blue\", command=lambda: btnClick(\"+\")).grid(row=3,column=6) #btn10=Button(f2,padx=16,padx=16, fg=\"blue\",", "\"\" def rupen(): global rupen rupen = rupen ronley =", "all_info.pack() lblname=Label(my_info,font=(\"arial\",20,\"italic\"),text=\"<NAME>\",bg=\"powder blue\", fg=\"green\", bd=10, relief=SUNKEN).pack(side=TOP) lblpro=Label(my_info,font=(\"arial\", 20,\"bold\"),text=\"Software Engineer\",bg=\"powder blue\",", "{}\".format(__file__)) file = open(\"/records.txt\",\"w\") finally: pass check = os.path.isfile(\"/records.txt\") if", "# lis = db.all() ################Info=============== lblInfo = Label(Tops, font=(\"arial\",60, \"italic", "Tk() dialog.title(\"Send emails\") dialog.geometry(\"800x800\") dframe = Frame(dialog,width=800,height=800,bg=\"white\",relief=SUNKEN).pack() email = StringVar()", "#return a = Entry(f2,font=(\"arial\", 20,\"bold\"), textvariable=text_Input, bd=30, insertwidth=4, bg=\"dark slate", "text=\"/\", bg=\"dim gray\", command=lambda: btnClick(\"/\")).grid(row=5,column=3) #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! rand = StringVar() #lblReference", "global operator operator=\"\" text_Input.set(\"\") def btnEqualsInput(): global operator sumup=str(eval(operator)) text_Input.set(sumup)", "=1 if the name already existed file_name = \"r.txt\" if", "= \"fil.txt\" file = open(\"{}\".format(file_name),\"w+\") totalx = shirt_mm+pant_mm+sale_mm+buy_mm+deposite_mm+withdraw_mm+coat_mm+order_mm file.write(\"Total:-{}\".format(totalx)) file.write(\"shirt:-{}\".format(shirt_mm))", "import * import os import pickle #from database1 import *", "blue\",text=\"Total:\",fg=\"black\").grid(row=7,column=2) totalx=Entry(f1, font=(\"arial\", 16, \"bold\"),bg=\"black\",textvariable=total,fg=\"white\",insertwidth=1,bd=10).grid(row=8,column=2) lblemployee = Label(f1,font=(\"arial\", 16, \"bold\"),bg=\"powder", "bd=10, anchor=\"w\", relief=RIDGE) lblInfo.pack() lblInfo = Label(Tops, font=(\"arial\",30, \"bold\"),text=localtime,fg=\"white\",bg=\"black\", bd=10,", "font=(\"arial\", 16, \"bold\"),text=\"coat_mm:\", bg=\"powder blue\",fg=\"black\",anchor=\"e\").grid(row=5,column=0) coatx=Entry(f1, font=(\"arial\", 16, \"bold\"), bg=\"black\",", "!= None: print(\"its printed\") print(reading) file.close() #db.insert({\"name\":\"<NAME>\"}) name = Query()", "loop #file = open(\"1{}\".format()) '''for i in range(5): if os.path.isfile(i):", "+ str(numbers) text_Input.set(operator) def btnClearDisplay(): global operator operator=\"\" text_Input.set(\"\") def", "\"italic\"), bd=10, textvariable=shirt, insertwidth=1,bg=\"black\",fg=\"white\", justify=\"left\").grid(row=2,column=0) owner=Button(root,padx=16,pady=16, font=(\"arial\",12, \"bold\"),text=\"info\", bd=8,bg=\"black\",command=ano_win1,fg=\"white\",relief=RAISED).pack(side=LEFT) yes=Button(root,padx=16,pady=16,font=(\"arial\",12,", "fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=5,column=1) sarix=Entry(f1, font=(\"arial\", 16, \"bold\"), bg=\"black\",bd=10, fg=\"white\",textvariable=sari, insertwidth=1).grid(row=6,column=1) buying=Label(f1,font=(\"arial\", 16,", "%(item)) time.sleep(1) print(\"done writing to the file\") #for item in", "due_amount = IntVar() order_info = IntVar() daily_cash = IntVar() cus_name", "buying=Label(f1,font=(\"arial\", 16, \"bold\"), bg=\"powder blue\",text=\"buy_info:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=7,column=0) buyx=Entry(f1,font=(\"arial\",16, \"bold\"),bd=8, fg=\"white\",bg=\"black\",textvariable=buy,insertwidth=1).grid(row=8,column=0) outgoing =Label(f1,", "is going to the section for the price inputs\") win2.geometry(\"1600x800\")", "no_y(): #nos = Toplevel(root) #nos.title(\"this is nos window\") #return a", "Label(Tops, font=(\"arial\",60, \"italic bold\"),text=\"Botique Management Systewm\",fg=\"white\", bg=\"dark slate blue\", bd=10,", "str(d.hour) minute = str(d.minute) second = str(d.second) between = str(\":\")'''", "order.get() total_mm = total.get() time = datetime.now() day = time.day", "daily_info.get() i = sales.get() j = buy.get() k = total_bank.get()", "ano_win1(): win1 = Toplevel() #this is going to be the", "msg = \"YOUR MESSAGE\" gmail.sendmail(\"your email adress\", \"the\") gmail.quit()''' dialog", "len(data) != 0: print(\"this is are the files written in", "= IntVar() order = IntVar() total = IntVar() out =", "emails\") dialog.geometry(\"800x800\") dframe = Frame(dialog,width=800,height=800,bg=\"white\",relief=SUNKEN).pack() email = StringVar() password =", "print(DIR) lblInfo = Label(Tops, font=(\"arial\",60, \"italic\"),text=current_dir,fg=\"black\",bg=\"powder blue\",bd=10, anchor=\"W\") lblInfo.pack() #DIR", "coatx=Entry(f1, font=(\"arial\", 16, \"bold\"), bg=\"black\", fg=\"white\", textvariable=coat, insertwidth=1, justify=\"left\",bd=10).grid(row=6,column=0) lablsari=Label(f1,font=(\"arial\",", "= str(time.year) minute = str(time.minute) #assuming the infos as the", "bg=\"dark slate blue\",fg=\"white\", justify=\"right\").grid(columnspan=4) btn7=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"), text=\"7\",bg=\"dim gray\", command=lambda:", "len(data) != 0: print(data)''' #lenght = len(db) ##this will show", "anchor=\"w\", relief=RIDGE) lblInfo.pack() lblInfo = Label(Tops, font=(\"arial\",30, \"bold\"),text=localtime,fg=\"white\",bg=\"black\", bd=10, anchor=\"w\",", "now.hour self.minute = now.minute self.second = now.second self.year = now.year", "btn9=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"), text=\"9\",bg=\"dim gray\", command=lambda: btnClick(9)).grid(row=2,column=2) #!!!!!!!!!!!!!!!!!!!!!!additions!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Addition=Button(f2,padx=16,pady=16,bd=8,text=\"+\",fg=\"black\",bg=\"dim gray\",", "btnClick(4)).grid(row=3,column=0) btn5=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"),text=\"5\", bg=\"dim gray\", command=lambda: btnClick(5)).grid(row=3,column=1) btn4=Button(f2,padx=16,pady=16,bd=8, fg=\"black\",", "a }), db.insert({\"regrds\":\"reference\"}), db.insert({\"day_income\":\"billion\"}), db.insert({\"day_outgoing\":\"billout\"}), db.insert({\"bankdeposit\":\"bankdepo\"}), db.insert({\"full_stock\":\"stock\"}), db.insert({\"shirt_mm\":\"shirt\"}), db.insert({\"bankwithdraw\":\"bankwith\"}), db.insert({\"pantmm\":\"pant\"}),", "further operations daysec = (24*60) * 60 * 60 ###", "order_bef.get() b = stock_full.get() c = shrting.get() d = pant.get()", "d = datetime.now() month = str(d.month) day = str(d.day) year", "will be easy for the #calculation #first calculating seconds in", "\"\", \"b\": \"\", \"c\": \"\", \"d\": \"\", \"e\": \"\", \"f\":", "= Query() #db(name.type == \"changed\") d = datetime.now() month =", "text=\"buying_something: \",bg=\"powder blue\",fg=\"black\", anchor=\"e\", relief=GROOVE).grid(row=3,column=0) buyx=Entry(f1,font=(\"arial\", 16, \"bold\"), textvariable=buy, insertwidth=1,", "file\") #for item in db: with open(\"/records.txt\", \"rb\") as file:", "win1.title(\"this is the owner window:\") win1.geometry(\"1600x800+0+0\") #win1.configure(bg=\"silver\") my_info = Frame(win1,", "fg=\"black\", font=(\"arial\",20,\"bold\"),text=\"4\", bg=\"dim gray\", command=lambda: btnClick(4)).grid(row=3,column=0) btn5=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"),text=\"5\", bg=\"dim", "= os.path.isfile(\"/records.txt\") if check: for item in db: data =", "\"YOUR MESSAGE\" gmail.sendmail(\"your email adress\", \"the\") gmail.quit()''' dialog = Tk()", "+ \".txt\" if os.path.isfile(new_file_name): #if the newfilename exists print(\"using the", "lblInfo.pack() lblInfo = Label(Tops, font=(\"arial\",30, \"bold\"),text=localtime,fg=\"white\",bg=\"black\", bd=10, anchor=\"w\", relief=RIDGE) lblInfo.pack()", "time.sleep(1) print(\"done writing to the file\") #for item in db:", "Frame(win1, width=100, height=100,bg=\"RoyalBlue4\",relief=GROOVE) others_info.pack(side=BOTTOM) all_info = Frame(win1, width=50, height=50,bg=\"RoyalBlue4\",relief=RAISED) all_info.pack()", "# root.mainloop() #for the revies of the follow in the", "\"bold\"), bg=\"powder blue\",text=\"buy_info:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=7,column=0) buyx=Entry(f1,font=(\"arial\",16, \"bold\"),bd=8, fg=\"white\",bg=\"black\",textvariable=buy,insertwidth=1).grid(row=8,column=0) outgoing =Label(f1, font=(\"arial\", 16,", "= Image.open(\"/root/Desktop/Desktop/anonymous/5.png\") imae = Label(win1,font=(\"arial\", 20,\"italic\"),width=300, height=168,bg=\"black\",fg=\"white\", text=image,relief=FLAT).pack() win1.mainloop()''' #=============================getting", "file1 if len(reading) != None: print(\"its printed\") print(reading) file.close() #db.insert({\"name\":\"<NAME>\"})", "= Frame(win2,width=1600,bg=\"RoyalBlue4\",height=100,relief=GROOVE).pack(side=TOP) frame1 = Frame(win2,width=775, height=750,bg=\"white\", relief=SUNKEN).pack() frame2 = Frame(win2,", "IntVar() total = IntVar() out = IntVar() before = IntVar()", "customer_info.pack(side=RIGHT) others_info = Frame(win1, width=100, height=100,bg=\"RoyalBlue4\",relief=GROOVE) others_info.pack(side=BOTTOM) all_info = Frame(win1,", "billo}) win = Toplevel() win.title(\"bills\") winF = Frame(win, bg=\"black\",relief=SUNKEN).pack() winE", "gray\", font=(\"arial\", 20,\"bold\"), command=btnEqualsInput).grid(row=5,column=2) #btn2=Button(f2,padx=16,pady=16,bd=8,fg=\"black\",text=\"2\",bg=\"dim gray\", command=lambda: btnClick(2)).grid(row=5,column=3) division=Button(f2,padx=16,pady=16,bd=8,fg=\"black\", text=\"/\",", "\"bold\") ,bg=\"dim gray\", command=lambda: btnClick(3)).grid(row=4,column=0) btn2=Button(f2,padx=16,pady=16,bd=8,text=\"2\",font=(\"arial\", 20, \"bold\"), bg=\"dim gray\",", "time.hour second = time.second year = time.year minute = time.minute", "the filename using the loop #file = open(\"1{}\".format()) '''for i", "column(col): for coll in col: call=cal+1 return call #def yes_y():", "#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! lblReference = Label(f1,font=(\"arial\", 16,\"bold\"), text=\"Reference\",bd=16,fg=\"white\",bg=\"green\",anchor=\"w\", relief=RIDGE) lblReference.grid(row=0,column=0) b=Entry(f1,font=(\"arial\", 16,", "text=\"pant_mm:\", bg=\"powder blue\",fg=\"black\",anchor=\"w\",relief=GROOVE).grid(row=1,column=1) pantx=Entry(f1,font=(\"arial\",16, \"bold\"), textvariable=pant, insertwidth=1, bd=10,bg=\"black\",fg=\"white\", justify=\"left\").grid(row=2,column=1) sales=Label(f1,font=(\"arial\",16,", "command=lambda: btnClick(2)).grid(row=4,column=1) btn1=Button(f2,padx=16,pady=16,bd=8,text=\"1\",font=(\"arial\", 20, \"bold\") ,bg=\"dim gray\", command=lambda: btnClick(1)).grid(row=4,column=2) Multiply=Button(f2,padx=16,pady=16,bd=8,text=\"*\",", "def _calculation(): shirt_mm = shirt.get() pant_mm = pant.get() sale_mm =", "{}\".format(new_file_name)) #file = open(\"{}\".format(new_file_name), \"w+\") continue else: file_name = open(new_file_name,", "300,height = 700,bg=\"dark slate blue\",relief=SUNKEN) f2.pack(side=RIGHT) #f3= Frame(root,width=1600,height=300,fg=\"blue\", bg=\"powder blue\",", "\"\", \"f\": \"\", \"g\": \"\", \"h\": \"\", \"i\": \"\", \"j\":", "db.insert({\"buying\":\"buy\"}), db.insert({\"customern\":\"customer\"}), db.insert({\"monthly_info\":\"monthly\"}), db.insert({\"totaldy\":\"total\"}), db.insert({\"employeid\":\"employee\"}) for db in range(1): print(db)", "btnClick(\"+\")).grid(row=2,column=3) btn6=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"),text=\"4\", bg=\"dim gray\", command=lambda: btnClick(4)).grid(row=3,column=0) btn5=Button(f2,padx=16,pady=16,bd=8, fg=\"black\",", "section for the price inputs\") win2.geometry(\"1600x800\") framex = Frame(win2,width=1600,bg=\"RoyalBlue4\",height=100,relief=GROOVE).pack(side=TOP) frame1", "print(\"done writing to the file\") #for item in db: with", "item in db: data = open(\"/records.txt\",\"wb\") #with open(\"/records.txt\",\"wb\") as file:", "exists print(\"using the file {}\".format(new_file_name)) #file = open(\"{}\".format(new_file_name), \"w+\") continue", "IntVar() sales = IntVar() buy = IntVar() total_bank = IntVar()", "= IntVar() cus_name = IntVar() cus_no = IntVar() employee =", "win1.geometry(\"1600x800+0+0\") #win1.configure(bg=\"silver\") my_info = Frame(win1, width=600, height=700,bg=\"RoyalBlue4\",relief=GROOVE) my_info.pack(side=LEFT) customer_info =", "will ease all the further operations daysec = (24*60) *", "for the project###################### '''def __database(): db = TinyDB(\"/records.json\") #print(monthly) #print(b)", "= IntVar() delivery = IntVar() #########################main_gate###################### def _calculation(): shirt_mm =", "# return #def no_y(): #nos = Toplevel(root) #nos.title(\"this is nos", "open(new_file_name, \"w+\") print(\"creating the file {}\".format(file_name)) #file = open(\"{}\".format(file_name), \"w+\")", "THE PRICES\",relief=GROOVE).pack() win2.mainloop() ###########################sending emails############################ def __send_email(): '''import smtplib gmail", "= StringVar() #lblReference = Label(f1,font=(\"arial\", 16,\"bold\"), text=\"Reference\",bd=16,fg=\"red\",bg=\"red\",anchor=\"w\",relief=RIDGE).grid(row=0,column=0) #txtReference=Entry(f1,font=(\"arial\", 16, \"bold\"),", "customer_info = Frame(win1, width=600, height=500,bg=\"RoyalBlue4\", relief=GROOVE) customer_info.pack(side=RIGHT) others_info = Frame(win1,", "StringVar() password = StringVar() semail = StringVar() spassword = StringVar()", "bd=8,bg=\"black\",command=ano_win1,fg=\"white\",relief=RAISED).pack(side=LEFT) yes=Button(root,padx=16,pady=16,font=(\"arial\",12, \"bold\"),text=\"Done\",bd=8,bg=\"black\", fg=\"white\", command=_calculation(),relief=RAISED).pack(side=RIGHT) panting=Label(f1,font=(\"arial\",20, \"bold\"), text=\"pant_mm:\", bg=\"powder blue\",fg=\"black\",anchor=\"w\",relief=GROOVE).grid(row=1,column=1)", "buy_mm = buy.get() deposite_mm = deposite.get() withdraw_mm = withdraw.get() coat_mm", "justify=\"left\").grid(row=4,column=0) Bank_Total=Label(f1,font=(\"arial\",16,\"bold\"),text=\"Bank_Deposite: \", bg=\"powder blue\", fg=\"black\", anchor=\"e\",relief=GROOVE).grid(row=3, column=1) depositex=Entry(f1,font=(\"arial\",16,\"bold\"),bd=10, textvariable=deposite,", "\"billOutput\": billo}) win = Toplevel() win.title(\"bills\") winF = Frame(win, bg=\"black\",relief=SUNKEN).pack()", "font=(\"arial\",20,\"bold\"), #text=\"+\",bg=\"powder blue\", command=lambda: btnClick(\"+\")).grid(row=3,column=6) #btn10=Button(f2,padx=16,padx=16, fg=\"blue\", font(\"arial\",5,\"bold\"), # text=\"rupen\",bg=\"powder", "= StringVar() bill_out = StringVar() shrting=Label(f1,font=(\"arial\", 20, \"bold\"), text=\"Shirting:\",bg=\"powder blue\",", "= db.all() ################Info=============== lblInfo = Label(Tops, font=(\"arial\",60, \"italic bold\"),text=\"Botique Management", "60 * 60 files = {\"a\":\"\", \"b\":\"\",\"c\":\"\",\"d\":\"\",\"e\":\"\",\"f\":\"\",\"g\":\"\",\"h\":\"\",\"i\":\"\",\"j\":\"\" ,\"k\":\"\",\"l\":\"\",\"m\":\"\",\"n\":\"\",\"o\":\"\",\"p\":\"\",\"q\":\"\",\"r\":\"\",\"s\":\"\"}''' #files =", "StringVar() imageloc=Entry(win1,font=(\"arial\",16,\"italic\"),bg=\"black\",fg=\"white\",bd=5,insertwidth=1,relief=GROOVE,textvariable=ima).pack() imageButt=Button(win1,font=(\"arial\",20, \"bold\"),bd=5,bg=\"white\",fg=\"white\",command= lambda: _image(image)).pack() '''def _image(image): image =", "Addition=Button(f2,padx=16,pady=16,bd=8,text=\"+\",fg=\"black\",bg=\"dim gray\", command=lambda: btnClick(\"+\")).grid(row=2,column=3) btn6=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"),text=\"4\", bg=\"dim gray\", command=lambda:", "as file: #pickle.dump(item, data) #file.close() #file1 = pickle.load(file) if len(item)", "command=lambda: btnClick(\"X\")).grid(row=4,column=3) #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ btn0=Button(f2,padx=16,pady=16,bd=8,bg=\"dim gray\",text=\"0\",fg=\"black\",font=(\"arial\", 20, \"bold\"), command=lambda: btnClick(0)).grid(row=5,column=0) btnClear=Button(f2,pady=16,padx=16,bd=8,", "= 700,bg=\"dark slate blue\",relief=SUNKEN) f2.pack(side=RIGHT) #f3= Frame(root,width=1600,height=300,fg=\"blue\", bg=\"powder blue\", relief=SUNKEN).pack(side=Bottom)", "\"b\": \"\", \"c\": \"\", \"d\": \"\", \"e\": \"\", \"f\": \"\",", "randint root = Tk() root.geometry(\"1600x800+0+0\") root.title(\"Suman_dai_ko_DHOKAN\") root.configure(bg=\"goldenrod4\") text_Input = StringVar()", "owner=Button(root,padx=16,pady=16, font=(\"arial\",12, \"bold\"),text=\"info\", bd=8,bg=\"black\",command=ano_win1,fg=\"white\",relief=RAISED).pack(side=LEFT) yes=Button(root,padx=16,pady=16,font=(\"arial\",12, \"bold\"),text=\"Done\",bd=8,bg=\"black\", fg=\"white\", command=_calculation(),relief=RAISED).pack(side=RIGHT) panting=Label(f1,font=(\"arial\",20, \"bold\"),", "is second window\") # return #def no_y(): #nos = Toplevel(root)", "b.grid(row=0,column=1) #img = \"/root/Desktop/Desktop/python/projects/prj1_Botik/1.jpg\" #root.ima = Image.open(img) #Label (root,bg=\"white\",width=120,height=120, image=ima).pack()", "'''for i in range(5): if os.path.isfile(i): pass else: file =", "None: print(\"its printed\") print(reading) file.close() #db.insert({\"name\":\"<NAME>\"}) name = Query() #db(name.type", "gray\", command=lambda: btnClick(\"X\")).grid(row=4,column=3) #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ btn0=Button(f2,padx=16,pady=16,bd=8,bg=\"dim gray\",text=\"0\",fg=\"black\",font=(\"arial\", 20, \"bold\"), command=lambda: btnClick(0)).grid(row=5,column=0)", "justify=\"left\").grid(row=4, column=1) lblBankwith=Label(f1, font=(\"arial\", 16, \"bold\"),fg=\"black\",bg=\"powder blue\",text=\"Bank_Withdraw\", anchor=\"e\",relief=GROOVE).grid(row=3,column=2) withdrawx=Entry(f1,font=(\"arial\",16, \"bold\"),bd=10,", "buyx=Entry(f1,font=(\"arial\",16, \"bold\"),bd=8, fg=\"white\",bg=\"black\",textvariable=buy,insertwidth=1).grid(row=8,column=0) outgoing =Label(f1, font=(\"arial\", 16, \"bold\"), bg=\"powder blue\",", "file.write(\"shirt:-{}\".format(shirt_mm)) file.write(\"pant_mm:-{}\".format(pant_mm)) file.write(\"sale_mm:-{}\".format(sale_mm)) file.write(\"buy_mm:-{}\".format(buy_mm)) file.write(\"deposite_mm:-{}\".format(deposite_mm)) file.write(\"withdraw_mm:-{}\".format(withdraw_mm)) file.write(\"coat:-{}\".format(coat_mm)) file.write(\"order:-{}\".format(order_mm)) reading =", "btn0=Button(f2,padx=16,pady=16,bd=8,bg=\"dim gray\",text=\"0\",fg=\"black\",font=(\"arial\", 20, \"bold\"), command=lambda: btnClick(0)).grid(row=5,column=0) btnClear=Button(f2,pady=16,padx=16,bd=8, fg=\"black\",font=(\"arial\", 20, \"bold\"),text=\"C\",bg=\"dim", "= StringVar() '''def malware_activate(): global cmd_active if \"rupen\" in cmd_active:", "#datetime=Label(Tops,font(\"arial\",20,\"bold\"),text=nowTime,bd=10 ,bg=\"black\", #fg=\"white\", anchor=\"w\").pack() #====================================debugged======================== shirt = IntVar() pant =", "gmail.sendmail(\"your email adress\", \"the\") gmail.quit()''' dialog = Tk() dialog.title(\"Send emails\")", "pass check = os.path.isfile(\"/records.txt\") if check: for item in db:", "self.minute = now.minute self.second = now.second self.year = now.year self.month", "order taken that will be notified before the #60 hours", "= open(\"1{}\".format()) '''for i in range(5): if os.path.isfile(i): pass else:", "= IntVar() total = IntVar() out = IntVar() before =", "col: call=cal+1 return call #def yes_y(): # rupe = Toplevel(root)", "root.mainloop() #__database() #add1=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"), #text=\"+\",bg=\"powder blue\", command=lambda: btnClick(\"+\")).grid(row=3,column=6) #btn10=Button(f2,padx=16,padx=16,", "bill_in(): ##assuming the variable as bill number .get var bill", "Toplevel() win2.title(\"This is going to the section for the price", "file from script {}\".format(__file__)) file = open(\"/records.txt\",\"w\") finally: pass check", "font=(\"arial\",60, \"italic\"),text=current_dir,fg=\"black\",bg=\"powder blue\",bd=10, anchor=\"W\") lblInfo.pack() #DIR = dir #return dir", "20 bold\"),bd=20, bg=\"black\",fg=\"white\",text=\"click\",command=ano_win1,relief=GROOVE).pack(side=BOTTOM) #fucking mazing yr coding def column(col): for", "for data in files: if len(data) != 0: print(\"this is", "#win1.configure(bg=\"silver\") my_info = Frame(win1, width=600, height=700,bg=\"RoyalBlue4\",relief=GROOVE) my_info.pack(side=LEFT) customer_info = Frame(win1,", "open(\"/records.txt\", \"rb\") as file: reading = file1 if len(reading) !=", "= Toplevel() win.title(\"bills\") winF = Frame(win, bg=\"black\",relief=SUNKEN).pack() winE = Entry(winF,", "__init__(self): self.order = order def __order_info(self): self.now = datetime() self.hour", "entry2 = Entry(dframe,font=(\"arial\", 16 ,\"bold\"),textvariable=password, insertwidth=1,bd=5).pack(side=RIGHT) Label2 =Label(dframe,font=(\"arial\",16, \"bold\"),fg=\"white\",bg=\"black\", text=\"sender_email\",relief=SUNKEN).pack(side=LEFT)", "blue\",fg=\"white\", justify=\"right\").grid(columnspan=4) btn7=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"), text=\"7\",bg=\"dim gray\", command=lambda: btnClick(7)).grid(row=2,column=0) btn8=Button(f2,padx=16,pady=16,bd=8,", "60 ### ##this is will be easy now yearSec =", "textvariable=cus_name).grid(row=10,column=1) lblmonthly=Label(f1, font=(\"arial\",16,\"bold\"),bg=\"powder blue\",text=\"monthly:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=5,column=2) monthly=StringVar() monthx=Entry(f1,font=(\"arial\",16,\"bold\"),show=\"blank\",bg=\"black\",textvariable=monthly,insertwidth=1,fg=\"white\",bd=10).grid(row=6,column=2) lbltotal=Label(f1, font=(\"arial\", 16, \"bold\"),bg=\"powder", "= datetime() self.hour = now.hour self.minute = now.minute self.second =", "IntVar() coat = IntVar() order = IntVar() total = IntVar()", "total.set #++++++++++++++++++++++++++++++Varibales_inset+++++++++++++++++++++++++++++++++ order_bef = IntVar() stock_full = IntVar() shrting =", "bd=10,bg=\"black\",fg=\"white\",command=_price_inputs,relief=GROOVE).pack(side=BOTTOM) btnru = Button(root, font=(\"arial 20 bold\"),bd=20, bg=\"black\",fg=\"white\",text=\"click\",command=ano_win1,relief=GROOVE).pack(side=BOTTOM) #fucking mazing", "image=ima).pack() bill_in = StringVar() bill_out = StringVar() shrting=Label(f1,font=(\"arial\", 20, \"bold\"),", "'''import smtplib gmail = smtplib.SMTP(\"smtp.gmail.com\", 587) gmail.starttls() _file = open(\"/root/Desktop/Desktop/python/\")", "btnClick(2)).grid(row=4,column=1) btn1=Button(f2,padx=16,pady=16,bd=8,text=\"1\",font=(\"arial\", 20, \"bold\") ,bg=\"dim gray\", command=lambda: btnClick(1)).grid(row=4,column=2) Multiply=Button(f2,padx=16,pady=16,bd=8,text=\"*\", bg=\"dim", "\"m\": \"\", \"n\": \"\", \"o\": \"\", \"p\": \"\", \"q\": \"\",", "operator =\"\" yes =\"\" no=\"\" Tops = Frame(root, width=1600 ,height=50,bg=\"goldenrod4\",", "=Label(dframe,font=(\"arial\",16, \"bold\"),fg=\"white\",bg=\"black\", text=\"sender_email\",relief=SUNKEN).pack(side=LEFT) entry2 = Entry(dframe,font=(\"arial\",16, \"bold\"),bd=5,fg=\"white\",bg=\"black\",textvariable=semail,insertwidth=1).pack(side=LEFT) label3 = Label(dframe,font=(\"arial\",16,\"bold\"),fg=\"white\",bg=\"black\",text=\"sender_password\",", "show the recorded bill numbers def bill_in(): ##assuming the variable", "import random import time from PIL import Image from datetime", "#====================================debugged======================== shirt = IntVar() pant = IntVar() sale = IntVar()", "will be easy now yearSec = daysec * 365 month", "order_mm = order.get() total_mm = total.get() time = datetime.now() day", "\"w+\") created with name {}\".format(file))''' #creating the filenames with append", "#++++++++++++++++++++++++++++++++++++++++tinydb example++++++++++++++++++++++ #db = TinyDB(\"/databse/d4ta.json\") #db.insert({\"cus_number\":\"98938232\", \"cus_name\":\"rupen\"}) #def no_y(): #", "len(item) == len(file1): break if item != file: #item =", "before = IntVar() #order before the 60 stock = IntVar()", "#file = open(\"{}\".format(file_name), \"w+\") break file_name = \"fil.txt\" file =", "blue\", text=\"outgoing:\", fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=7,column=1) outx=Entry(f1,font=(\"arial\", 16, \"bold\"),textvariable=out, bd=8,fg=\"white\",bg=\"black\",insertwidth=1).grid(row=8,column=1) ordering=Label(f1,font=(\"arial\",16,\"bold\"),bg=\"powder blue\",text=\"order_info:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=9,column=0) orderx=Entry(f1,font=(\"arial\",16,\"bold\"),insertwidth=1,", "anchor=\"e\", relief=GROOVE).grid(row=3,column=0) buyx=Entry(f1,font=(\"arial\", 16, \"bold\"), textvariable=buy, insertwidth=1, bd=10,bg=\"black\", fg=\"white\", justify=\"left\").grid(row=4,column=0)", "malware_activate(): global cmd_active if \"rupen\" in cmd_active: if \"rupen\" in", "30 daySec = daysec hourSec = 60 * 60 *", "sales.get() j = buy.get() k = total_bank.get() l = bank_deposite.get()", "\"changed\") d = datetime.now() month = str(d.month) day = str(d.day)", "for the price inputs\") win2.geometry(\"1600x800\") framex = Frame(win2,width=1600,bg=\"RoyalBlue4\",height=100,relief=GROOVE).pack(side=TOP) frame1 =", "no=Entry(f1,font=(\"arial\",16, \"bold\"),bd=8,bg=\"black\",fg=\"white\",insertwidth=1, textvariable=cus_name).grid(row=10,column=1) lblmonthly=Label(f1, font=(\"arial\",16,\"bold\"),bg=\"powder blue\",text=\"monthly:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=5,column=2) monthly=StringVar() monthx=Entry(f1,font=(\"arial\",16,\"bold\"),show=\"blank\",bg=\"black\",textvariable=monthly,insertwidth=1,fg=\"white\",bd=10).grid(row=6,column=2) lbltotal=Label(f1, font=(\"arial\",", "numbers def bill_in(): ##assuming the variable as bill number .get", "shrting=Label(f1,font=(\"arial\", 20, \"bold\"), text=\"Shirting:\",bg=\"powder blue\", fg=\"black\",anchor=\"w\",relief=GROOVE).grid(row=1,column=0) shirts=Entry(f1,font=(\"arial\", 16, \"italic\"), bd=10,", "Frame(root, width = 800 ,height=500,bg=\"goldenrod4\",relief=SUNKEN) f1.pack(side=LEFT) f2 = Frame(root, width", "#print(b) #fuck = c.get() a = order_bef.get() b = stock_full.get()", "g = delivery_report.get() h = daily_info.get() i = sales.get() j", "to the file\") #for item in db: with open(\"/records.txt\", \"rb\")", "bill_in = StringVar() bill_out = StringVar() shrting=Label(f1,font=(\"arial\", 20, \"bold\"), text=\"Shirting:\",bg=\"powder", "= str(d.day) year = str(d.year) hour = str(d.hour) minute =", "db.insert({\"day_outgoing\":\"billout\"}), db.insert({\"bankdeposit\":\"bankdepo\"}), db.insert({\"full_stock\":\"stock\"}), db.insert({\"shirt_mm\":\"shirt\"}), db.insert({\"bankwithdraw\":\"bankwith\"}), db.insert({\"pantmm\":\"pant\"}), db.insert({\"sarimm\":\"sari\"}), db.insert({\"orderday\":\"orderinfo\"}), db.insert({\"salling\":\"sales\"}), db.insert({\"buying\":\"buy\"}),", "self.order = order def __order_info(self): self.now = datetime() self.hour =", "Tk() root.geometry(\"1600x800+0+0\") root.title(\"Suman_dai_ko_DHOKAN\") root.configure(bg=\"goldenrod4\") text_Input = StringVar() operator =\"\" yes", "shirt_mm = shirt.get() pant_mm = pant.get() sale_mm = sale.get() buy_mm", "gray\", command=lambda: btnClick(9)).grid(row=2,column=2) #!!!!!!!!!!!!!!!!!!!!!!additions!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Addition=Button(f2,padx=16,pady=16,bd=8,text=\"+\",fg=\"black\",bg=\"dim gray\", command=lambda: btnClick(\"+\")).grid(row=2,column=3) btn6=Button(f2,padx=16,pady=16,bd=8, fg=\"black\",", "bills.insert({\"billInput\": bill, \"billOutput\": billo}) win = Toplevel() win.title(\"bills\") winF =", "def column(col): for coll in col: call=cal+1 return call #def", "#after wards set the total from here total.set #++++++++++++++++++++++++++++++Varibales_inset+++++++++++++++++++++++++++++++++ order_bef", "fg=\"black\", font=(\"arial\",20,\"bold\"), text=\"7\",bg=\"dim gray\", command=lambda: btnClick(7)).grid(row=2,column=0) btn8=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"), text=\"8\",bg=\"dim", "\"italic\"),text=current_dir,fg=\"black\",bg=\"powder blue\",bd=10, anchor=\"W\") lblInfo.pack() #DIR = dir #return dir \"\"\"", "#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ btn0=Button(f2,padx=16,pady=16,bd=8,bg=\"dim gray\",text=\"0\",fg=\"black\",font=(\"arial\", 20, \"bold\"), command=lambda: btnClick(0)).grid(row=5,column=0) btnClear=Button(f2,pady=16,padx=16,bd=8, fg=\"black\",font=(\"arial\", 20,", "\"i\": \"\", \"j\": \"\" , \"k\": \"\", \"l\": \"\", \"m\":", "easy for the #calculation #first calculating seconds in one day", "hour = str(d.hour) minute = str(d.minute) second = str(d.second) between", "global operator operator = operator + str(numbers) text_Input.set(operator) def btnClearDisplay():", "bill_in global bill_out bill_out = \"\" bill_in = \"\" def", "now.day self.record_time = record_time if self.hour == self.record_timeD: print(\"the time", "fg=\"black\", font=(\"arial\",20,\"bold\"),text=\"5\", bg=\"dim gray\", command=lambda: btnClick(5)).grid(row=3,column=1) btn4=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"),text=\"6\",bg=\"dim gray\",", "second = str(time.second) year = str(time.year) minute = str(time.minute) #assuming", "var bill = bill_in.get() billo = bill_out.get() bills = tinydb.TinyDb(\"/bills.json\")", "of the same of the tkinter in the main function", "\"\", \"q\": \"\", \"r\": \"\", \"s\": \"\"} db.insert({\"total\": a }),", "image.set(imageloc) return image #image = Image.open(\"/root/Desktop/Desktop/anonymous/5.png\") imae = Label(win1,font=(\"arial\", 20,\"italic\"),width=300,", "= Image.open(img) #Label (root,bg=\"white\",width=120,height=120, image=ima).pack() bill_in = StringVar() bill_out =", "expand += 1 new_file_name = file_name.split(\".txt\")[0] + str(expand) + \".txt\"", "gray\", command=lambda: btnClick(6)).grid(row=3,column=2) Subtract=Button(f2,padx=16,pady=16,bd=8,text=\"-\", bg=\"dim gray\", command=lambda: btnClick(\"-\")).grid(row=3,column=3) btn3=Button(f2,padx=16,pady=16,bd=8,text=\"3\",font=(\"arial\", 20,", "data in files: if len(data) != 0: print(data)''' #lenght =", "btnClick(7)).grid(row=2,column=0) btn8=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"), text=\"8\",bg=\"dim gray\", command=lambda: btnClick(8)).grid(row=2,column=1) btn9=Button(f2,padx=16,pady=16,bd=8, fg=\"black\",", "text=\"password\", relief=SUNKEN).pack() entry2 = Entry(dframe,font=(\"arial\", 16 ,\"bold\"),textvariable=password, insertwidth=1,bd=5).pack(side=RIGHT) Label2 =Label(dframe,font=(\"arial\",16,", "entry3= Entry(dframe,font=(\"arial\",16,\"bold\"),fg=\"white\",textvariable=spassword,insertwidth=1,relief=SUNKEN).pack() dialog.mainloop() #btnEmail = Button(root,font=(\"arial\", 16, \"bold\"), bg=\"black\",fg=\"white\",text=\"email\",command=lambda: __send_email(),relief=GROOVE).pack()", "i = sales.get() j = buy.get() k = total_bank.get() l", "= c.get() a = order_bef.get() b = stock_full.get() c =", "file = open(\"/records.txt\",\"w\") finally: pass check = os.path.isfile(\"/records.txt\") if check:", "{}\".format(file_name)) #file = open(\"{}\".format(file_name), \"w+\") break file_name = \"fil.txt\" file", "the support in teh main loop #there is no limit", "\"bold\"),text=\"info\", bd=8,bg=\"black\",command=ano_win1,fg=\"white\",relief=RAISED).pack(side=LEFT) yes=Button(root,padx=16,pady=16,font=(\"arial\",12, \"bold\"),text=\"Done\",bd=8,bg=\"black\", fg=\"white\", command=_calculation(),relief=RAISED).pack(side=RIGHT) panting=Label(f1,font=(\"arial\",20, \"bold\"), text=\"pant_mm:\", bg=\"powder", "== \"changed\") d = datetime.now() month = str(d.month) day =", "example++++++++++++++++++++++ #db = TinyDB(\"/databse/d4ta.json\") #db.insert({\"cus_number\":\"98938232\", \"cus_name\":\"rupen\"}) #def no_y(): # lis", "in cmd_active[1]: if \"ronley\" in cmd_active[2]:''' #==============================another windows about me=====================", "win2.geometry(\"1600x800\") framex = Frame(win2,width=1600,bg=\"RoyalBlue4\",height=100,relief=GROOVE).pack(side=TOP) frame1 = Frame(win2,width=775, height=750,bg=\"white\", relief=SUNKEN).pack() frame2", "= smtplib.SMTP(\"smtp.gmail.com\", 587) gmail.starttls() _file = open(\"/root/Desktop/Desktop/python/\") gmail.login(\"username\", \"password\") msg", "files = {\"a\": \"\", \"b\": \"\", \"c\": \"\", \"d\": \"\",", "= Tk() dialog.title(\"Send emails\") dialog.geometry(\"800x800\") dframe = Frame(dialog,width=800,height=800,bg=\"white\",relief=SUNKEN).pack() email =", "b=Entry(f1,font=(\"arial\", 16, \"bold\"), textvariable=rand, bd=10,insertwidth=4,fg=\"white\",bg=\"black\", justify = \"left\") b.grid(row=0,column=1) #img", "\"rb\") as file: reading = file1 if len(reading) != None:", "open(\"1{}\".format()) '''for i in range(5): if os.path.isfile(i): pass else: file", "\"bold\"), bg=\"black\", fg=\"white\", textvariable=coat, insertwidth=1, justify=\"left\",bd=10).grid(row=6,column=0) lablsari=Label(f1,font=(\"arial\", 16, \"bold\"), bg=\"powder", "cmd_active[1]: if \"ronley\" in cmd_active[2]:''' #==============================another windows about me===================== def", "class __main(): def __init__(self): self.order = order def __order_info(self): self.now", "relief=SUNKEN).pack(side=LEFT) entry3= Entry(dframe,font=(\"arial\",16,\"bold\"),fg=\"white\",textvariable=spassword,insertwidth=1,relief=SUNKEN).pack() dialog.mainloop() #btnEmail = Button(root,font=(\"arial\", 16, \"bold\"), bg=\"black\",fg=\"white\",text=\"email\",command=lambda:", "16, \"bold\"), bg=\"powder blue\",text=\"sari mm:\", fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=5,column=1) sarix=Entry(f1, font=(\"arial\", 16, \"bold\"),", "= Toplevel(root) #nos.title(\"this is nos window\") #return a = Entry(f2,font=(\"arial\",", "file_name.split(\".txt\")[0] + str(expand) + \".txt\" if os.path.isfile(new_file_name): #if the newfilename", "try: file = open(\"/records.txt\", \"r\") except: print(\"creating the file from", "totalx = shirt_mm+pant_mm+sale_mm+buy_mm+deposite_mm+withdraw_mm+coat_mm+order_mm file.write(\"Total:-{}\".format(totalx)) file.write(\"shirt:-{}\".format(shirt_mm)) file.write(\"pant_mm:-{}\".format(pant_mm)) file.write(\"sale_mm:-{}\".format(sale_mm)) file.write(\"buy_mm:-{}\".format(buy_mm)) file.write(\"deposite_mm:-{}\".format(deposite_mm)) file.write(\"withdraw_mm:-{}\".format(withdraw_mm))", "deposite_mm = deposite.get() withdraw_mm = withdraw.get() coat_mm = coat.get() order_mm", "bg=\"black\",fg=\"white\",text=\"click\",command=ano_win1,relief=GROOVE).pack(side=BOTTOM) #fucking mazing yr coding def column(col): for coll in", "= open(\"/records.txt\",\"wb\") #with open(\"/records.txt\",\"wb\") as file: #pickle.dump(item, data) #file.close() #file1", "#def function(): # pass(): # pass main(): # root.mainloop() #for", "font=(\"arial\",20,\"bold\"), text=\"7\",bg=\"dim gray\", command=lambda: btnClick(7)).grid(row=2,column=0) btn8=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"), text=\"8\",bg=\"dim gray\",", "check = os.path.isfile(\"/records.txt\") if check: for item in db: data", "blue\", command=rupen).grid(row=3,column=5) #def function(): # pass(): # pass main(): #", "+ str(expand) + \".txt\" if os.path.isfile(new_file_name): #if the newfilename exists", "str(numbers) text_Input.set(operator) def btnClearDisplay(): global operator operator=\"\" text_Input.set(\"\") def btnEqualsInput():", "total_bank = IntVar() bank_deposite = IntVar() bank_withdraw = IntVar() due_amount", "bill, \"billOutput\": billo}) win = Toplevel() win.title(\"bills\") winF = Frame(win,", "= Entry(winF, insertwidth=10,insertheight=10,fg=\"white\",bg=\"black\",textvariable=bills).pack() win.mainloop() #l # command=bill_in).pack(anchor=NE) root.mainloop() #__database() #add1=Button(f2,padx=16,pady=16,bd=8,", "now.minute self.second = now.second self.year = now.year self.month = now.month", "panting=Label(f1,font=(\"arial\",20, \"bold\"), text=\"pant_mm:\", bg=\"powder blue\",fg=\"black\",anchor=\"w\",relief=GROOVE).grid(row=1,column=1) pantx=Entry(f1,font=(\"arial\",16, \"bold\"), textvariable=pant, insertwidth=1, bd=10,bg=\"black\",fg=\"white\",", "#assuming the infos as the order taken that will be", "easy now yearSec = daysec * 365 month = daysec", "fg=\"green\", bd=10, relief=SUNKEN).pack(side=TOP) lblpro=Label(my_info,font=(\"arial\", 20,\"bold\"),text=\"Software Engineer\",bg=\"powder blue\", fg=\"green\",bd=10, relief=RAISED).pack() ima", "orderx=Entry(f1,font=(\"arial\",16,\"bold\"),insertwidth=1, textvariable=order,bd=8,fg=\"white\",bg=\"black\").grid(row=10,column=0) lblcustomer=Label(f1,font=(\"arial\",16,\"bold\"),bg=\"powder blue\",text=\"cus_name:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=9,column=1) no=Entry(f1,font=(\"arial\",16, \"bold\"),bd=8,bg=\"black\",fg=\"white\",insertwidth=1, textvariable=cus_name).grid(row=10,column=1) lblmonthly=Label(f1, font=(\"arial\",16,\"bold\"),bg=\"powder blue\",text=\"monthly:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=5,column=2)", "= str(time.minute) #assuming the infos as the order taken that", "def __order_info(self): self.now = datetime() self.hour = now.hour self.minute =", "= Label(framex,font=(\"arial\", 20,\"italic\"),bg=\"powder blue\",fg=\"green\",text=\"INPUT THE PRICES\",relief=GROOVE).pack() win2.mainloop() ###########################sending emails############################ def", "= str(\":\")''' '''def __time(infos): time = datetime.now() day = str(time.day)", "tinydb import * import os import pickle #from database1 import", "btnClick(numbers): global operator operator = operator + str(numbers) text_Input.set(operator) def", "the owner window:\") win1.geometry(\"1600x800+0+0\") #win1.configure(bg=\"silver\") my_info = Frame(win1, width=600, height=700,bg=\"RoyalBlue4\",relief=GROOVE)", "bg=\"black\", text=\"password\", relief=SUNKEN).pack() entry2 = Entry(dframe,font=(\"arial\", 16 ,\"bold\"),textvariable=password, insertwidth=1,bd=5).pack(side=RIGHT) Label2", "the variable as bill number .get var bill = bill_in.get()", "c = shrting.get() d = pant.get() e = sari.get() f", "r = cus_no.get() s = employee.get() files = {\"a\": \"\",", "writing to the file\") #for item in db: with open(\"/records.txt\",", "me===================== def ano_win1(): win1 = Toplevel() #this is going to", "textvariable=coat, insertwidth=1, justify=\"left\",bd=10).grid(row=6,column=0) lablsari=Label(f1,font=(\"arial\", 16, \"bold\"), bg=\"powder blue\",text=\"sari mm:\", fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=5,column=1)", "year = str(d.year) hour = str(d.hour) minute = str(d.minute) second", "insertwidth=10,insertheight=10,fg=\"white\",bg=\"black\",textvariable=bills).pack() win.mainloop() #l # command=bill_in).pack(anchor=NE) root.mainloop() #__database() #add1=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"),", "StringVar() spassword = StringVar() label = Label(dframe, font=(\"arial\",16, \"bold\"), fg=\"white\",", "os import sys DIR = os.getcwd() print(DIR) lblInfo = Label(Tops,", "= str(d.second) between = str(\":\")''' '''def __time(infos): time = datetime.now()", "deposite = IntVar() withdraw = IntVar() coat = IntVar() order", "str(time.year) minute = str(time.minute) #assuming the infos as the order", "#def no_y(): #nos = Toplevel(root) #nos.title(\"this is nos window\") #return", "= \"\" for data in files: if len(data) != 0:", "bill_in.get() billo = bill_out.get() bills = tinydb.TinyDb(\"/bills.json\") while bill or", "command=lambda: current_dir(dir)).pack(side=TOP) def btnClick(numbers): global operator operator = operator +", "will show the recorded bill numbers def bill_in(): ##assuming the", "pant = IntVar() sari = IntVar() order_info = IntVar() delivery_report", "shirt.get() pant_mm = pant.get() sale_mm = sale.get() buy_mm = buy.get()", "fg=\"white\", justify=\"left\").grid(row=4,column=0) Bank_Total=Label(f1,font=(\"arial\",16,\"bold\"),text=\"Bank_Deposite: \", bg=\"powder blue\", fg=\"black\", anchor=\"e\",relief=GROOVE).grid(row=3, column=1) depositex=Entry(f1,font=(\"arial\",16,\"bold\"),bd=10,", "str(d.year) hour = str(d.hour) minute = str(d.minute) second = str(d.second)", "= due_amount.get() o = order_info.get() p = daily_cash.get() q =", "= time.hour second = time.second year = time.year minute =", "= StringVar() label = Label(dframe, font=(\"arial\",16, \"bold\"), fg=\"white\", bg=\"black\", text=\"your_email\").pack(side=LEFT)", "monthx=Entry(f1,font=(\"arial\",16,\"bold\"),show=\"blank\",bg=\"black\",textvariable=monthly,insertwidth=1,fg=\"white\",bd=10).grid(row=6,column=2) lbltotal=Label(f1, font=(\"arial\", 16, \"bold\"),bg=\"powder blue\",text=\"Total:\",fg=\"black\").grid(row=7,column=2) totalx=Entry(f1, font=(\"arial\", 16, \"bold\"),bg=\"black\",textvariable=total,fg=\"white\",insertwidth=1,bd=10).grid(row=8,column=2)", "!= file: #item = str(item) file.write(\"%s\" %(item)) time.sleep(1) print(\"done writing", "gmail.login(\"username\", \"password\") msg = \"YOUR MESSAGE\" gmail.sendmail(\"your email adress\", \"the\")", "StringVar() operator =\"\" yes =\"\" no=\"\" Tops = Frame(root, width=1600", "minute = time.minute #setting the filename using the loop #file", "#!!!!!!!!!!!!!!!!!!!!!!additions!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Addition=Button(f2,padx=16,pady=16,bd=8,text=\"+\",fg=\"black\",bg=\"dim gray\", command=lambda: btnClick(\"+\")).grid(row=2,column=3) btn6=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"),text=\"4\", bg=\"dim gray\",", "be notified before the #60 hours #changing all the formats", "= Label(f1,font=(\"arial\", 16,\"bold\"), text=\"Reference\",bd=16,fg=\"red\",bg=\"red\",anchor=\"w\",relief=RIDGE).grid(row=0,column=0) #txtReference=Entry(f1,font=(\"arial\", 16, \"bold\"), textvariable=rand, bd=10,insertwidth=4,bg=\"red\",fg=\"white\", justify", "order_info.get() g = delivery_report.get() h = daily_info.get() i = sales.get()", "fg=\"black\", font=(\"arial\",20,\"bold\"),text=\"6\",bg=\"dim gray\", command=lambda: btnClick(6)).grid(row=3,column=2) Subtract=Button(f2,padx=16,pady=16,bd=8,text=\"-\", bg=\"dim gray\", command=lambda: btnClick(\"-\")).grid(row=3,column=3)", "= \"left\") b.grid(row=0,column=1) #img = \"/root/Desktop/Desktop/python/projects/prj1_Botik/1.jpg\" #root.ima = Image.open(img) #Label", "gmail.starttls() _file = open(\"/root/Desktop/Desktop/python/\") gmail.login(\"username\", \"password\") msg = \"YOUR MESSAGE\"", "20, \"bold\") ,bg=\"dim gray\", command=lambda: btnClick(3)).grid(row=4,column=0) btn2=Button(f2,padx=16,pady=16,bd=8,text=\"2\",font=(\"arial\", 20, \"bold\"), bg=\"dim", "textvariable=pant, insertwidth=1, bd=10,bg=\"black\",fg=\"white\", justify=\"left\").grid(row=2,column=1) sales=Label(f1,font=(\"arial\",16, \"bold\"), text=\"sales_total:\",bg=\"powder blue\",fg=\"black\",anchor=\"w\",bd=8,relief=GROOVE).grid(row=1,column=2) salex=Entry(f1,font=(\"arial\",16, \"bold\"),bg=\"black\",fg=\"white\",textvariable=sale,insertwidth=1,bd=10,justify=\"left\").grid(row=2,column=2)", "the revies of the follow in the sorry of the", "frame1 = Frame(win2,width=775, height=750,bg=\"white\", relief=SUNKEN).pack() frame2 = Frame(win2, width=775,height=750,bg=\"black\", relief=FLAT).pack()", "#================================next section=========================== fix = Button(root, bd=10,bg=\"black\",fg=\"white\",command=_price_inputs,relief=GROOVE).pack(side=BOTTOM) btnru = Button(root, font=(\"arial", "buyx=Entry(f1,font=(\"arial\", 16, \"bold\"), textvariable=buy, insertwidth=1, bd=10,bg=\"black\", fg=\"white\", justify=\"left\").grid(row=4,column=0) Bank_Total=Label(f1,font=(\"arial\",16,\"bold\"),text=\"Bank_Deposite: \",", "buy.get() k = total_bank.get() l = bank_deposite.get() m = bank_withdraw.get()", "self.record_timeD: print(\"the time for the product is actually %s left\"", "buy = IntVar() total_bank = IntVar() bank_deposite = IntVar() bank_withdraw", "= Frame(root, width = 300,height = 700,bg=\"dark slate blue\",relief=SUNKEN) f2.pack(side=RIGHT)", "btnClick(\"X\")).grid(row=4,column=3) #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ btn0=Button(f2,padx=16,pady=16,bd=8,bg=\"dim gray\",text=\"0\",fg=\"black\",font=(\"arial\", 20, \"bold\"), command=lambda: btnClick(0)).grid(row=5,column=0) btnClear=Button(f2,pady=16,padx=16,bd=8, fg=\"black\",font=(\"arial\",", "the same of the tkinter in the main function of", "text_Input = StringVar() operator =\"\" yes =\"\" no=\"\" Tops =", "60 * 60 minuteSec = 60 * 60 files =", "windows about me===================== def ano_win1(): win1 = Toplevel() #this is", "def rupen(): global rupen rupen = rupen ronley = StringVar()", "btnClick(6)).grid(row=3,column=2) Subtract=Button(f2,padx=16,pady=16,bd=8,text=\"-\", bg=\"dim gray\", command=lambda: btnClick(\"-\")).grid(row=3,column=3) btn3=Button(f2,padx=16,pady=16,bd=8,text=\"3\",font=(\"arial\", 20, \"bold\") ,bg=\"dim", ",bg=\"dim gray\", command=lambda: btnClick(3)).grid(row=4,column=0) btn2=Button(f2,padx=16,pady=16,bd=8,text=\"2\",font=(\"arial\", 20, \"bold\"), bg=\"dim gray\", command=lambda:", "file.write(\"order:-{}\".format(order_mm)) reading = file.readlines() file.close() #after wards set the total", "lablsari=Label(f1,font=(\"arial\", 16, \"bold\"), bg=\"powder blue\",text=\"sari mm:\", fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=5,column=1) sarix=Entry(f1, font=(\"arial\", 16,", "root.title(\"Suman_dai_ko_DHOKAN\") root.configure(bg=\"goldenrod4\") text_Input = StringVar() operator =\"\" yes =\"\" no=\"\"", "\"\", \"i\": \"\", \"j\": \"\" , \"k\": \"\", \"l\": \"\",", "python\\\\n check the file.txt for debug \") da += data", "of teh win1.title(\"this is the owner window:\") win1.geometry(\"1600x800+0+0\") #win1.configure(bg=\"silver\") my_info", "bg=\"dim gray\", command=lambda: btnClick(\"X\")).grid(row=4,column=3) #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ btn0=Button(f2,padx=16,pady=16,bd=8,bg=\"dim gray\",text=\"0\",fg=\"black\",font=(\"arial\", 20, \"bold\"), command=lambda:", "#==========================================================Time======================================= localtime=time.asctime(time.localtime(time.time())) #datetime=Label(Tops,font(\"arial\",20,\"bold\"),text=nowTime,bd=10 ,bg=\"black\", #fg=\"white\", anchor=\"w\").pack() #====================================debugged======================== shirt = IntVar()", "command=lambda: btnClick(4)).grid(row=3,column=0) btn5=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"),text=\"5\", bg=\"dim gray\", command=lambda: btnClick(5)).grid(row=3,column=1) btn4=Button(f2,padx=16,pady=16,bd=8,", "if len(data) != 0: print(data)''' #lenght = len(db) ##this will", "with append =1 if the name already existed file_name =", "gray\", command=lambda: btnClick(2)).grid(row=5,column=3) division=Button(f2,padx=16,pady=16,bd=8,fg=\"black\", text=\"/\", bg=\"dim gray\", command=lambda: btnClick(\"/\")).grid(row=5,column=3) #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", "range(1): print(db) files = list(files) file = open(\"/file.txt\", \"wb\") da", "\"q\": \"\", \"r\": \"\", \"s\": \"\"} db.insert({\"total\": a }), db.insert({\"regrds\":\"reference\"}),", "gray\", command=lambda: btnClick(\"-\")).grid(row=3,column=3) btn3=Button(f2,padx=16,pady=16,bd=8,text=\"3\",font=(\"arial\", 20, \"bold\") ,bg=\"dim gray\", command=lambda: btnClick(3)).grid(row=4,column=0)", "= withdraw.get() coat_mm = coat.get() order_mm = order.get() total_mm =", "data) #file.close() #file1 = pickle.load(file) if len(item) == len(file1): break", "= buy.get() k = total_bank.get() l = bank_deposite.get() m =", "imageButt=Button(win1,font=(\"arial\",20, \"bold\"),bd=5,bg=\"white\",fg=\"white\",command= lambda: _image(image)).pack() '''def _image(image): image = image.set(imageloc) return", "section=========================== fix = Button(root, bd=10,bg=\"black\",fg=\"white\",command=_price_inputs,relief=GROOVE).pack(side=BOTTOM) btnru = Button(root, font=(\"arial 20", "window\") #return a = Entry(f2,font=(\"arial\", 20,\"bold\"), textvariable=text_Input, bd=30, insertwidth=4, bg=\"dark", "\"r\") except: print(\"creating the file from script {}\".format(__file__)) file =", "# text=\"rupen\",bg=\"powder blue\", command=rupen).grid(row=3,column=5) #def function(): # pass(): # pass", "= now.month self.day = now.day self.record_time = record_time if self.hour", "open(\"/records.txt\",\"wb\") #with open(\"/records.txt\",\"wb\") as file: #pickle.dump(item, data) #file.close() #file1 =", "= Label(Tops, font=(\"arial\",30, \"bold\"),text=localtime,fg=\"white\",bg=\"black\", bd=10, anchor=\"w\", relief=RIDGE) lblInfo.pack() #===========================================================Calculator================================== \"\"\"def", "others_info.pack(side=BOTTOM) all_info = Frame(win1, width=50, height=50,bg=\"RoyalBlue4\",relief=RAISED) all_info.pack() lblname=Label(my_info,font=(\"arial\",20,\"italic\"),text=\"<NAME>\",bg=\"powder blue\", fg=\"green\",", "justify=\"left\",bd=10).grid(row=6,column=0) lablsari=Label(f1,font=(\"arial\", 16, \"bold\"), bg=\"powder blue\",text=\"sari mm:\", fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=5,column=1) sarix=Entry(f1, font=(\"arial\",", "database1 import * from random import randint root = Tk()", "{\"a\":\"\", \"b\":\"\",\"c\":\"\",\"d\":\"\",\"e\":\"\",\"f\":\"\",\"g\":\"\",\"h\":\"\",\"i\":\"\",\"j\":\"\" ,\"k\":\"\",\"l\":\"\",\"m\":\"\",\"n\":\"\",\"o\":\"\",\"p\":\"\",\"q\":\"\",\"r\":\"\",\"s\":\"\"}''' #files = list(files) '''for data in files:", "year = time.year minute = time.minute #setting the filename using", "in the function #of the system on the support in", "file: #item = str(item) file.write(\"%s\" %(item)) time.sleep(1) print(\"done writing to", "* 60 * 60 ### ##this is will be easy", "db.insert({\"total\": a }), db.insert({\"regrds\":\"reference\"}), db.insert({\"day_income\":\"billion\"}), db.insert({\"day_outgoing\":\"billout\"}), db.insert({\"bankdeposit\":\"bankdepo\"}), db.insert({\"full_stock\":\"stock\"}), db.insert({\"shirt_mm\":\"shirt\"}), db.insert({\"bankwithdraw\":\"bankwith\"}),", "file.readlines() file.close() #after wards set the total from here total.set", "StringVar() label = Label(dframe, font=(\"arial\",16, \"bold\"), fg=\"white\", bg=\"black\", text=\"your_email\").pack(side=LEFT) entry1", "salex=Entry(f1,font=(\"arial\",16, \"bold\"),bg=\"black\",fg=\"white\",textvariable=sale,insertwidth=1,bd=10,justify=\"left\").grid(row=2,column=2) buying=Label(f1,font=(\"arial\",16, \"bold\"), text=\"buying_something: \",bg=\"powder blue\",fg=\"black\", anchor=\"e\", relief=GROOVE).grid(row=3,column=0) buyx=Entry(f1,font=(\"arial\",", "= StringVar() operator =\"\" yes =\"\" no=\"\" Tops = Frame(root,", "if len(data) != 0: print(\"this is are the files written", "# pass(): # pass main(): # root.mainloop() #for the revies", "command=lambda: btnClick(5)).grid(row=3,column=1) btn4=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"),text=\"6\",bg=\"dim gray\", command=lambda: btnClick(6)).grid(row=3,column=2) Subtract=Button(f2,padx=16,pady=16,bd=8,text=\"-\", bg=\"dim", "employee.get() files = {\"a\": \"\", \"b\": \"\", \"c\": \"\", \"d\":", "#db(name.type == \"changed\") d = datetime.now() month = str(d.month) day", "delivery_report.get() h = daily_info.get() i = sales.get() j = buy.get()", "width=50, height=50,bg=\"RoyalBlue4\",relief=RAISED) all_info.pack() lblname=Label(my_info,font=(\"arial\",20,\"italic\"),text=\"<NAME>\",bg=\"powder blue\", fg=\"green\", bd=10, relief=SUNKEN).pack(side=TOP) lblpro=Label(my_info,font=(\"arial\", 20,\"bold\"),text=\"Software", "infos ======================== def _price_inputs(): win2 = Toplevel() win2.title(\"This is going", "relief=SUNKEN).pack(side=Bottom) #==========================================================Time======================================= localtime=time.asctime(time.localtime(time.time())) #datetime=Label(Tops,font(\"arial\",20,\"bold\"),text=nowTime,bd=10 ,bg=\"black\", #fg=\"white\", anchor=\"w\").pack() #====================================debugged======================== shirt =", "gray\", command=lambda: btnClick(5)).grid(row=3,column=1) btn4=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"),text=\"6\",bg=\"dim gray\", command=lambda: btnClick(6)).grid(row=3,column=2) Subtract=Button(f2,padx=16,pady=16,bd=8,text=\"-\",", "actually %s left\" %(self.hour-self.record_timeD)) #++++++++++++++++++++++++++++++++++++++++tinydb example++++++++++++++++++++++ #db = TinyDB(\"/databse/d4ta.json\") #db.insert({\"cus_number\":\"98938232\",", "bg=\"dim gray\", command=lambda: btnClick(\"/\")).grid(row=5,column=3) #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! rand = StringVar() #lblReference =", "\"bold\"), bg=\"dim gray\", command=lambda: btnClick(2)).grid(row=4,column=1) btn1=Button(f2,padx=16,pady=16,bd=8,text=\"1\",font=(\"arial\", 20, \"bold\") ,bg=\"dim gray\",", "justify=\"left\").grid(row=2,column=1) sales=Label(f1,font=(\"arial\",16, \"bold\"), text=\"sales_total:\",bg=\"powder blue\",fg=\"black\",anchor=\"w\",bd=8,relief=GROOVE).grid(row=1,column=2) salex=Entry(f1,font=(\"arial\",16, \"bold\"),bg=\"black\",fg=\"white\",textvariable=sale,insertwidth=1,bd=10,justify=\"left\").grid(row=2,column=2) buying=Label(f1,font=(\"arial\",16, \"bold\"), text=\"buying_something:", "20,\"bold\"),text=\"Software Engineer\",bg=\"powder blue\", fg=\"green\",bd=10, relief=RAISED).pack() ima = StringVar() imageloc=Entry(win1,font=(\"arial\",16,\"italic\"),bg=\"black\",fg=\"white\",bd=5,insertwidth=1,relief=GROOVE,textvariable=ima).pack() imageButt=Button(win1,font=(\"arial\",20,", "= IntVar() daily_info = IntVar() sales = IntVar() buy =", "IntVar() buy = IntVar() deposite = IntVar() withdraw = IntVar()", "bd=8,fg=\"white\",bg=\"black\",insertwidth=1).grid(row=8,column=1) ordering=Label(f1,font=(\"arial\",16,\"bold\"),bg=\"powder blue\",text=\"order_info:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=9,column=0) orderx=Entry(f1,font=(\"arial\",16,\"bold\"),insertwidth=1, textvariable=order,bd=8,fg=\"white\",bg=\"black\").grid(row=10,column=0) lblcustomer=Label(f1,font=(\"arial\",16,\"bold\"),bg=\"powder blue\",text=\"cus_name:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=9,column=1) no=Entry(f1,font=(\"arial\",16, \"bold\"),bd=8,bg=\"black\",fg=\"white\",insertwidth=1, textvariable=cus_name).grid(row=10,column=1)", "file_name = open(new_file_name, \"w+\") print(\"creating the file {}\".format(file_name)) #file =", "o = order_info.get() p = daily_cash.get() q = cus_name.get() r", "open(\"{}\".format(file_name), \"w+\") break file_name = \"fil.txt\" file = open(\"{}\".format(file_name),\"w+\") totalx", "slate blue\",relief=SUNKEN) f2.pack(side=RIGHT) #f3= Frame(root,width=1600,height=300,fg=\"blue\", bg=\"powder blue\", relief=SUNKEN).pack(side=Bottom) #==========================================================Time======================================= localtime=time.asctime(time.localtime(time.time()))", "insertwidth=1).grid(row=6,column=1) buying=Label(f1,font=(\"arial\", 16, \"bold\"), bg=\"powder blue\",text=\"buy_info:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=7,column=0) buyx=Entry(f1,font=(\"arial\",16, \"bold\"),bd=8, fg=\"white\",bg=\"black\",textvariable=buy,insertwidth=1).grid(row=8,column=0) outgoing", "\"bold\"), command=lambda: btnClick(0)).grid(row=5,column=0) btnClear=Button(f2,pady=16,padx=16,bd=8, fg=\"black\",font=(\"arial\", 20, \"bold\"),text=\"C\",bg=\"dim gray\", command=btnClearDisplay).grid(row=5,column=1) btnEquals=Button(f2,padx=16,pady=16,fg=\"black\",bd=8,text=\"=\",bg=\"dim", "data print(data) da = int(da) file.write(da) try: file = open(\"/records.txt\",", "gray\", command=lambda: btnClick(\"/\")).grid(row=5,column=3) #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! rand = StringVar() #lblReference = Label(f1,font=(\"arial\",", "bg=\"powder blue\", relief=SUNKEN).pack(side=Bottom) #==========================================================Time======================================= localtime=time.asctime(time.localtime(time.time())) #datetime=Label(Tops,font(\"arial\",20,\"bold\"),text=nowTime,bd=10 ,bg=\"black\", #fg=\"white\", anchor=\"w\").pack() #====================================debugged========================", "#lenght = len(db) ##this will show the recorded bill numbers", "#db.insert({\"cus_number\":\"98938232\", \"cus_name\":\"rupen\"}) #def no_y(): # lis = db.all() ################Info=============== lblInfo", "IntVar() due_amount = IntVar() order_info = IntVar() daily_cash = IntVar()", "relief=RAISED).pack() ima = StringVar() imageloc=Entry(win1,font=(\"arial\",16,\"italic\"),bg=\"black\",fg=\"white\",bd=5,insertwidth=1,relief=GROOVE,textvariable=ima).pack() imageButt=Button(win1,font=(\"arial\",20, \"bold\"),bd=5,bg=\"white\",fg=\"white\",command= lambda: _image(image)).pack() '''def", "#print(monthly) #print(b) #fuck = c.get() a = order_bef.get() b =", "= str(time.second) year = str(time.year) minute = str(time.minute) #assuming the", "str(d.day) year = str(d.year) hour = str(d.hour) minute = str(d.minute)", "font=(\"arial\",20,\"bold\"),text=\"6\",bg=\"dim gray\", command=lambda: btnClick(6)).grid(row=3,column=2) Subtract=Button(f2,padx=16,pady=16,bd=8,text=\"-\", bg=\"dim gray\", command=lambda: btnClick(\"-\")).grid(row=3,column=3) btn3=Button(f2,padx=16,pady=16,bd=8,text=\"3\",font=(\"arial\",", "totalx=Entry(f1, font=(\"arial\", 16, \"bold\"),bg=\"black\",textvariable=total,fg=\"white\",insertwidth=1,bd=10).grid(row=8,column=2) lblemployee = Label(f1,font=(\"arial\", 16, \"bold\"),bg=\"powder blue\",text=\"employee", "relief=GROOVE).grid(row=3,column=0) buyx=Entry(f1,font=(\"arial\", 16, \"bold\"), textvariable=buy, insertwidth=1, bd=10,bg=\"black\", fg=\"white\", justify=\"left\").grid(row=4,column=0) Bank_Total=Label(f1,font=(\"arial\",16,\"bold\"),text=\"Bank_Deposite:", "f2 = Frame(root, width = 300,height = 700,bg=\"dark slate blue\",relief=SUNKEN)", "no_y(): # lis = db.all() ################Info=============== lblInfo = Label(Tops, font=(\"arial\",60,", "bank_deposite.get() m = bank_withdraw.get() n = due_amount.get() o = order_info.get()", "\"\", \"s\": \"\"} db.insert({\"total\": a }), db.insert({\"regrds\":\"reference\"}), db.insert({\"day_income\":\"billion\"}), db.insert({\"day_outgoing\":\"billout\"}), db.insert({\"bankdeposit\":\"bankdepo\"}),", "= Frame(win, bg=\"black\",relief=SUNKEN).pack() winE = Entry(winF, insertwidth=10,insertheight=10,fg=\"white\",bg=\"black\",textvariable=bills).pack() win.mainloop() #l #", "anchor=\"w\", relief=RIDGE) lblInfo.pack() #===========================================================Calculator================================== \"\"\"def current_dir(): import os import sys", "ima = StringVar() imageloc=Entry(win1,font=(\"arial\",16,\"italic\"),bg=\"black\",fg=\"white\",bd=5,insertwidth=1,relief=GROOVE,textvariable=ima).pack() imageButt=Button(win1,font=(\"arial\",20, \"bold\"),bd=5,bg=\"white\",fg=\"white\",command= lambda: _image(image)).pack() '''def _image(image):", "the system on the support in teh main loop #there", "rupe = Toplevel(root) # rupe.title(\"this is second window\") # return", "text=\"9\",bg=\"dim gray\", command=lambda: btnClick(9)).grid(row=2,column=2) #!!!!!!!!!!!!!!!!!!!!!!additions!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Addition=Button(f2,padx=16,pady=16,bd=8,text=\"+\",fg=\"black\",bg=\"dim gray\", command=lambda: btnClick(\"+\")).grid(row=2,column=3) btn6=Button(f2,padx=16,pady=16,bd=8,", "month = str(time.month) hour = str(time.hour) second = str(time.second) year", "{}\".format(file))''' #creating the filenames with append =1 if the name", "algoriths######################### class __main(): def __init__(self): self.order = order def __order_info(self):", "= Toplevel() #this is going to be the window in", "16, \"italic\"), bd=10, textvariable=shirt, insertwidth=1,bg=\"black\",fg=\"white\", justify=\"left\").grid(row=2,column=0) owner=Button(root,padx=16,pady=16, font=(\"arial\",12, \"bold\"),text=\"info\", bd=8,bg=\"black\",command=ano_win1,fg=\"white\",relief=RAISED).pack(side=LEFT)", "IntVar() daily_cash = IntVar() cus_name = IntVar() cus_no = IntVar()", "n = due_amount.get() o = order_info.get() p = daily_cash.get() q", "= TinyDB(\"/records.json\") #print(monthly) #print(b) #fuck = c.get() a = order_bef.get()", "yes =\"\" no=\"\" Tops = Frame(root, width=1600 ,height=50,bg=\"goldenrod4\", relief=RIDGE) Tops.pack(side=TOP)", "# pass main(): # root.mainloop() #for the revies of the", "\"left\") b.grid(row=0,column=1) #img = \"/root/Desktop/Desktop/python/projects/prj1_Botik/1.jpg\" #root.ima = Image.open(img) #Label (root,bg=\"white\",width=120,height=120,", "#l # command=bill_in).pack(anchor=NE) root.mainloop() #__database() #add1=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"), #text=\"+\",bg=\"powder blue\",", "20,\"italic\"),width=300, height=168,bg=\"black\",fg=\"white\", text=image,relief=FLAT).pack() win1.mainloop()''' #=============================getting all the infos ======================== def", "#for the revies of the follow in the sorry of", "text_Input.set(\"\") def btnEqualsInput(): global operator sumup=str(eval(operator)) text_Input.set(sumup) operator=\"\" def bill_entry():", "= \"YOUR MESSAGE\" gmail.sendmail(\"your email adress\", \"the\") gmail.quit()''' dialog =", "* import os import pickle #from database1 import * from", "= IntVar() coat = IntVar() order = IntVar() total =", "anchor=\"w\").pack() #====================================debugged======================== shirt = IntVar() pant = IntVar() sale =", "fg=\"white\", bg=\"black\", text=\"password\", relief=SUNKEN).pack() entry2 = Entry(dframe,font=(\"arial\", 16 ,\"bold\"),textvariable=password, insertwidth=1,bd=5).pack(side=RIGHT)", "the section for the price inputs\") win2.geometry(\"1600x800\") framex = Frame(win2,width=1600,bg=\"RoyalBlue4\",height=100,relief=GROOVE).pack(side=TOP)", "\"bold\"),fg=\"white\",bg=\"black\", text=\"sender_email\",relief=SUNKEN).pack(side=LEFT) entry2 = Entry(dframe,font=(\"arial\",16, \"bold\"),bd=5,fg=\"white\",bg=\"black\",textvariable=semail,insertwidth=1).pack(side=LEFT) label3 = Label(dframe,font=(\"arial\",16,\"bold\"),fg=\"white\",bg=\"black\",text=\"sender_password\", relief=SUNKEN).pack(side=LEFT)", "font=(\"arial\", 16, \"bold\"), bg=\"black\",bd=10, fg=\"white\",textvariable=sari, insertwidth=1).grid(row=6,column=1) buying=Label(f1,font=(\"arial\", 16, \"bold\"), bg=\"powder", "yes_y(): # rupe = Toplevel(root) # rupe.title(\"this is second window\")", "os.path.isfile(new_file_name): #if the newfilename exists print(\"using the file {}\".format(new_file_name)) #file", "Image from datetime import datetime from tinydb import * import", "= buy.get() deposite_mm = deposite.get() withdraw_mm = withdraw.get() coat_mm =", "return #def no_y(): #nos = Toplevel(root) #nos.title(\"this is nos window\")", "IntVar() cus_no = IntVar() employee = IntVar() ###############################class of algoriths#########################", "= IntVar() buy = IntVar() deposite = IntVar() withdraw =", "command=lambda: btnClick(1)).grid(row=4,column=2) Multiply=Button(f2,padx=16,pady=16,bd=8,text=\"*\", bg=\"dim gray\", command=lambda: btnClick(\"X\")).grid(row=4,column=3) #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ btn0=Button(f2,padx=16,pady=16,bd=8,bg=\"dim gray\",text=\"0\",fg=\"black\",font=(\"arial\",", "textvariable=shirt, insertwidth=1,bg=\"black\",fg=\"white\", justify=\"left\").grid(row=2,column=0) owner=Button(root,padx=16,pady=16, font=(\"arial\",12, \"bold\"),text=\"info\", bd=8,bg=\"black\",command=ano_win1,fg=\"white\",relief=RAISED).pack(side=LEFT) yes=Button(root,padx=16,pady=16,font=(\"arial\",12, \"bold\"),text=\"Done\",bd=8,bg=\"black\", fg=\"white\",", "= pickle.load(file) if len(item) == len(file1): break if item !=", "= order_info.get() p = daily_cash.get() q = cus_name.get() r =", "= str(item) file.write(\"%s\" %(item)) time.sleep(1) print(\"done writing to the file\")", "file {}\".format(file_name)) #file = open(\"{}\".format(file_name), \"w+\") break file_name = \"fil.txt\"", "= daily_cash.get() q = cus_name.get() r = cus_no.get() s =", "#image = Image.open(\"/root/Desktop/Desktop/anonymous/5.png\") imae = Label(win1,font=(\"arial\", 20,\"italic\"),width=300, height=168,bg=\"black\",fg=\"white\", text=image,relief=FLAT).pack() win1.mainloop()'''", "lis = db.all() ################Info=============== lblInfo = Label(Tops, font=(\"arial\",60, \"italic bold\"),text=\"Botique", "if \"rupen\" in cmd_active[1]: if \"ronley\" in cmd_active[2]:''' #==============================another windows", "with open(\"/records.txt\", \"rb\") as file: reading = file1 if len(reading)", "#setting the filename using the loop #file = open(\"1{}\".format()) '''for", "font=(\"arial 20 bold\"),bd=20, bg=\"black\",fg=\"white\",text=\"click\",command=ano_win1,relief=GROOVE).pack(side=BOTTOM) #fucking mazing yr coding def column(col):", "16, \"bold\"), bg=\"black\", fg=\"white\", textvariable=coat, insertwidth=1, justify=\"left\",bd=10).grid(row=6,column=0) lablsari=Label(f1,font=(\"arial\", 16, \"bold\"),", "###############################class of algoriths######################### class __main(): def __init__(self): self.order = order", "cus_no = IntVar() employee = IntVar() ###############################class of algoriths######################### class", "btnClick(2)).grid(row=5,column=3) division=Button(f2,padx=16,pady=16,bd=8,fg=\"black\", text=\"/\", bg=\"dim gray\", command=lambda: btnClick(\"/\")).grid(row=5,column=3) #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! rand =", "db.insert({\"monthly_info\":\"monthly\"}), db.insert({\"totaldy\":\"total\"}), db.insert({\"employeid\":\"employee\"}) for db in range(1): print(db) files =", "for coll in col: call=cal+1 return call #def yes_y(): #", "text=\"Shirting:\",bg=\"powder blue\", fg=\"black\",anchor=\"w\",relief=GROOVE).grid(row=1,column=0) shirts=Entry(f1,font=(\"arial\", 16, \"italic\"), bd=10, textvariable=shirt, insertwidth=1,bg=\"black\",fg=\"white\", justify=\"left\").grid(row=2,column=0)", "left\" %(self.hour-self.record_timeD)) #++++++++++++++++++++++++++++++++++++++++tinydb example++++++++++++++++++++++ #db = TinyDB(\"/databse/d4ta.json\") #db.insert({\"cus_number\":\"98938232\", \"cus_name\":\"rupen\"}) #def", "debug \") da += data print(data) da = int(da) file.write(da)", "db.insert({\"bankwithdraw\":\"bankwith\"}), db.insert({\"pantmm\":\"pant\"}), db.insert({\"sarimm\":\"sari\"}), db.insert({\"orderday\":\"orderinfo\"}), db.insert({\"salling\":\"sales\"}), db.insert({\"buying\":\"buy\"}), db.insert({\"customern\":\"customer\"}), db.insert({\"monthly_info\":\"monthly\"}), db.insert({\"totaldy\":\"total\"}), db.insert({\"employeid\":\"employee\"})", "str(time.minute) #assuming the infos as the order taken that will", "now.second self.year = now.year self.month = now.month self.day = now.day", "total_bank.get() l = bank_deposite.get() m = bank_withdraw.get() n = due_amount.get()", "Label(Tops, font=(\"arial\",30, \"bold\"),text=localtime,fg=\"white\",bg=\"black\", bd=10, anchor=\"w\", relief=RIDGE) lblInfo.pack() #===========================================================Calculator================================== \"\"\"def current_dir():", "no limit in the system of teh win1.title(\"this is the", "20, \"bold\"),text=\"C\",bg=\"dim gray\", command=btnClearDisplay).grid(row=5,column=1) btnEquals=Button(f2,padx=16,pady=16,fg=\"black\",bd=8,text=\"=\",bg=\"dim gray\", font=(\"arial\", 20,\"bold\"), command=btnEqualsInput).grid(row=5,column=2) #btn2=Button(f2,padx=16,pady=16,bd=8,fg=\"black\",text=\"2\",bg=\"dim", "width = 800 ,height=500,bg=\"goldenrod4\",relief=SUNKEN) f1.pack(side=LEFT) f2 = Frame(root, width =", "= \"right\").grid(row=0,column=1) #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! lblReference = Label(f1,font=(\"arial\", 16,\"bold\"), text=\"Reference\",bd=16,fg=\"white\",bg=\"green\",anchor=\"w\", relief=RIDGE) lblReference.grid(row=0,column=0)", "image #image = Image.open(\"/root/Desktop/Desktop/anonymous/5.png\") imae = Label(win1,font=(\"arial\", 20,\"italic\"),width=300, height=168,bg=\"black\",fg=\"white\", text=image,relief=FLAT).pack()", "IntVar() before = IntVar() #order before the 60 stock =", "order_info = IntVar() daily_cash = IntVar() cus_name = IntVar() cus_no", "framex = Frame(win2,width=1600,bg=\"RoyalBlue4\",height=100,relief=GROOVE).pack(side=TOP) frame1 = Frame(win2,width=775, height=750,bg=\"white\", relief=SUNKEN).pack() frame2 =", "= 800 ,height=500,bg=\"goldenrod4\",relief=SUNKEN) f1.pack(side=LEFT) f2 = Frame(root, width = 300,height", "self.hour = now.hour self.minute = now.minute self.second = now.second self.year", "nothing in the function #of the system on the support", "= IntVar() order_info = IntVar() daily_cash = IntVar() cus_name =", "if item != file: #item = str(item) file.write(\"%s\" %(item)) time.sleep(1)", "\"\", \"r\": \"\", \"s\": \"\"} db.insert({\"total\": a }), db.insert({\"regrds\":\"reference\"}), db.insert({\"day_income\":\"billion\"}),", "\"bold\"),bd=8,bg=\"black\",fg=\"white\",insertwidth=1, textvariable=cus_name).grid(row=10,column=1) lblmonthly=Label(f1, font=(\"arial\",16,\"bold\"),bg=\"powder blue\",text=\"monthly:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=5,column=2) monthly=StringVar() monthx=Entry(f1,font=(\"arial\",16,\"bold\"),show=\"blank\",bg=\"black\",textvariable=monthly,insertwidth=1,fg=\"white\",bd=10).grid(row=6,column=2) lbltotal=Label(f1, font=(\"arial\", 16,", "_image(image): image = image.set(imageloc) return image #image = Image.open(\"/root/Desktop/Desktop/anonymous/5.png\") imae", "= order.get() total_mm = total.get() time = datetime.now() day =", "= IntVar() #order before the 60 stock = IntVar() delivery", "one day that will ease all the further operations daysec", "textvariable=text_Input, bd=30, insertwidth=4, bg=\"dark slate blue\",fg=\"white\", justify=\"right\").grid(columnspan=4) btn7=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"),", "second window\") # return #def no_y(): #nos = Toplevel(root) #nos.title(\"this", "minute = str(d.minute) second = str(d.second) between = str(\":\")''' '''def", "total from here total.set #++++++++++++++++++++++++++++++Varibales_inset+++++++++++++++++++++++++++++++++ order_bef = IntVar() stock_full =", "\"bold\"), textvariable=rand, bd=10,insertwidth=4,fg=\"white\",bg=\"black\", justify = \"left\") b.grid(row=0,column=1) #img = \"/root/Desktop/Desktop/python/projects/prj1_Botik/1.jpg\"", "= coat.get() order_mm = order.get() total_mm = total.get() time =", "import sys DIR = os.getcwd() print(DIR) lblInfo = Label(Tops, font=(\"arial\",60,", "IntVar() cus_name = IntVar() cus_no = IntVar() employee = IntVar()", "= Frame(root, width=1600 ,height=50,bg=\"goldenrod4\", relief=RIDGE) Tops.pack(side=TOP) f1 = Frame(root, width", "be easy now yearSec = daysec * 365 month =", "= image.set(imageloc) return image #image = Image.open(\"/root/Desktop/Desktop/anonymous/5.png\") imae = Label(win1,font=(\"arial\",", "db.insert({\"pantmm\":\"pant\"}), db.insert({\"sarimm\":\"sari\"}), db.insert({\"orderday\":\"orderinfo\"}), db.insert({\"salling\":\"sales\"}), db.insert({\"buying\":\"buy\"}), db.insert({\"customern\":\"customer\"}), db.insert({\"monthly_info\":\"monthly\"}), db.insert({\"totaldy\":\"total\"}), db.insert({\"employeid\":\"employee\"}) for", "operator operator=\"\" text_Input.set(\"\") def btnEqualsInput(): global operator sumup=str(eval(operator)) text_Input.set(sumup) operator=\"\"", "bd=30, insertwidth=4, bg=\"dark slate blue\",fg=\"white\", justify=\"right\").grid(columnspan=4) btn7=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"), text=\"7\",bg=\"dim", "rupen = rupen ronley = StringVar() '''def malware_activate(): global cmd_active", "btnClick(\"-\")).grid(row=3,column=3) btn3=Button(f2,padx=16,pady=16,bd=8,text=\"3\",font=(\"arial\", 20, \"bold\") ,bg=\"dim gray\", command=lambda: btnClick(3)).grid(row=4,column=0) btn2=Button(f2,padx=16,pady=16,bd=8,text=\"2\",font=(\"arial\", 20,", "bg=\"dim gray\", command=lambda: btnClick(\"-\")).grid(row=3,column=3) btn3=Button(f2,padx=16,pady=16,bd=8,text=\"3\",font=(\"arial\", 20, \"bold\") ,bg=\"dim gray\", command=lambda:", "that will be notified before the #60 hours #changing all", "str(d.minute) second = str(d.second) between = str(\":\")''' '''def __time(infos): time", "btnClick(8)).grid(row=2,column=1) btn9=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"), text=\"9\",bg=\"dim gray\", command=lambda: btnClick(9)).grid(row=2,column=2) #!!!!!!!!!!!!!!!!!!!!!!additions!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Addition=Button(f2,padx=16,pady=16,bd=8,text=\"+\",fg=\"black\",bg=\"dim", "IntVar() bank_deposite = IntVar() bank_withdraw = IntVar() due_amount = IntVar()", "16, \"bold\"), textvariable=rand, bd=10,insertwidth=4,fg=\"white\",bg=\"black\", justify = \"left\") b.grid(row=0,column=1) #img =", "Toplevel() win.title(\"bills\") winF = Frame(win, bg=\"black\",relief=SUNKEN).pack() winE = Entry(winF, insertwidth=10,insertheight=10,fg=\"white\",bg=\"black\",textvariable=bills).pack()", ".get var bill = bill_in.get() billo = bill_out.get() bills =", "\"\" bill_in = \"\" def rupen(): global rupen rupen =", "16,\"bold\"),textvariable=employee,insertwidth=1,bg=\"black\",fg=\"white\",bd=10).grid(row=10,column=2) ###############################database for the project###################### '''def __database(): db = TinyDB(\"/records.json\")", "bill_out = \"\" bill_in = \"\" def rupen(): global rupen", "blue\", command=lambda: btnClick(\"+\")).grid(row=3,column=6) #btn10=Button(f2,padx=16,padx=16, fg=\"blue\", font(\"arial\",5,\"bold\"), # text=\"rupen\",bg=\"powder blue\", command=rupen).grid(row=3,column=5)", "f1.pack(side=LEFT) f2 = Frame(root, width = 300,height = 700,bg=\"dark slate", "win.mainloop() #l # command=bill_in).pack(anchor=NE) root.mainloop() #__database() #add1=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"), #text=\"+\",bg=\"powder", "monthly=StringVar() monthx=Entry(f1,font=(\"arial\",16,\"bold\"),show=\"blank\",bg=\"black\",textvariable=monthly,insertwidth=1,fg=\"white\",bd=10).grid(row=6,column=2) lbltotal=Label(f1, font=(\"arial\", 16, \"bold\"),bg=\"powder blue\",text=\"Total:\",fg=\"black\").grid(row=7,column=2) totalx=Entry(f1, font=(\"arial\", 16,", "= bank_deposite.get() m = bank_withdraw.get() n = due_amount.get() o =", "print(db) files = list(files) file = open(\"/file.txt\", \"wb\") da =", "withdrawx=Entry(f1,font=(\"arial\",16, \"bold\"),bd=10, fg=\"white\",bg=\"black\", textvariable=withdraw, insertwidth=1).grid(row=4,column=2) coating=Label(f1, font=(\"arial\", 16, \"bold\"),text=\"coat_mm:\", bg=\"powder", "fg=\"blue\", font(\"arial\",5,\"bold\"), # text=\"rupen\",bg=\"powder blue\", command=rupen).grid(row=3,column=5) #def function(): # pass():", "sumup=str(eval(operator)) text_Input.set(sumup) operator=\"\" def bill_entry(): global bill_in global bill_out bill_out", "\"\", \"j\": \"\" , \"k\": \"\", \"l\": \"\", \"m\": \"\",", "the file\") #for item in db: with open(\"/records.txt\", \"rb\") as", "bd=10,insertwidth=4,fg=\"white\",bg=\"black\", justify = \"left\") b.grid(row=0,column=1) #img = \"/root/Desktop/Desktop/python/projects/prj1_Botik/1.jpg\" #root.ima =", "in files: if len(data) != 0: print(\"this is are the", "= str(d.month) day = str(d.day) year = str(d.year) hour =", "lambda: _image(image)).pack() '''def _image(image): image = image.set(imageloc) return image #image", "pant_mm = pant.get() sale_mm = sale.get() buy_mm = buy.get() deposite_mm", "now yearSec = daysec * 365 month = daysec *", "text=\"Reference\",bd=16,fg=\"white\",bg=\"green\",anchor=\"w\", relief=RIDGE) lblReference.grid(row=0,column=0) b=Entry(f1,font=(\"arial\", 16, \"bold\"), textvariable=rand, bd=10,insertwidth=4,fg=\"white\",bg=\"black\", justify =", "text=\"8\",bg=\"dim gray\", command=lambda: btnClick(8)).grid(row=2,column=1) btn9=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"), text=\"9\",bg=\"dim gray\", command=lambda:", "bank_deposite = IntVar() bank_withdraw = IntVar() due_amount = IntVar() order_info", "width=600, height=500,bg=\"RoyalBlue4\", relief=GROOVE) customer_info.pack(side=RIGHT) others_info = Frame(win1, width=100, height=100,bg=\"RoyalBlue4\",relief=GROOVE) others_info.pack(side=BOTTOM)", "is the owner window:\") win1.geometry(\"1600x800+0+0\") #win1.configure(bg=\"silver\") my_info = Frame(win1, width=600,", "= pant.get() e = sari.get() f = order_info.get() g =", "\"g\": \"\", \"h\": \"\", \"i\": \"\", \"j\": \"\" , \"k\":", "IntVar() sale = IntVar() buy = IntVar() deposite = IntVar()", "name already existed file_name = \"r.txt\" if os.path.isfile(file_name): expand =", "IntVar() order_info = IntVar() delivery_report = IntVar() daily_info = IntVar()", "lbltotal=Label(f1, font=(\"arial\", 16, \"bold\"),bg=\"powder blue\",text=\"Total:\",fg=\"black\").grid(row=7,column=2) totalx=Entry(f1, font=(\"arial\", 16, \"bold\"),bg=\"black\",textvariable=total,fg=\"white\",insertwidth=1,bd=10).grid(row=8,column=2) lblemployee", "existed file_name = \"r.txt\" if os.path.isfile(file_name): expand = 1 while", "command=_calculation(),relief=RAISED).pack(side=RIGHT) panting=Label(f1,font=(\"arial\",20, \"bold\"), text=\"pant_mm:\", bg=\"powder blue\",fg=\"black\",anchor=\"w\",relief=GROOVE).grid(row=1,column=1) pantx=Entry(f1,font=(\"arial\",16, \"bold\"), textvariable=pant, insertwidth=1,", "str(item) file.write(\"%s\" %(item)) time.sleep(1) print(\"done writing to the file\") #for", "files: if len(data) != 0: print(data)''' #lenght = len(db) ##this", "from script {}\".format(__file__)) file = open(\"/records.txt\",\"w\") finally: pass check =", "command=lambda: btnClick(\"-\")).grid(row=3,column=3) btn3=Button(f2,padx=16,pady=16,bd=8,text=\"3\",font=(\"arial\", 20, \"bold\") ,bg=\"dim gray\", command=lambda: btnClick(3)).grid(row=4,column=0) btn2=Button(f2,padx=16,pady=16,bd=8,text=\"2\",font=(\"arial\",", "time.second year = time.year minute = time.minute #setting the filename", "= Label(dframe,font=(\"arial\",16,\"bold\"),fg=\"white\",bg=\"black\",text=\"sender_password\", relief=SUNKEN).pack(side=LEFT) entry3= Entry(dframe,font=(\"arial\",16,\"bold\"),fg=\"white\",textvariable=spassword,insertwidth=1,relief=SUNKEN).pack() dialog.mainloop() #btnEmail = Button(root,font=(\"arial\", 16,", "operator + str(numbers) text_Input.set(operator) def btnClearDisplay(): global operator operator=\"\" text_Input.set(\"\")", "IntVar() #########################main_gate###################### def _calculation(): shirt_mm = shirt.get() pant_mm = pant.get()", "my_info = Frame(win1, width=600, height=700,bg=\"RoyalBlue4\",relief=GROOVE) my_info.pack(side=LEFT) customer_info = Frame(win1, width=600,", "mm:\", fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=5,column=1) sarix=Entry(f1, font=(\"arial\", 16, \"bold\"), bg=\"black\",bd=10, fg=\"white\",textvariable=sari, insertwidth=1).grid(row=6,column=1) buying=Label(f1,font=(\"arial\",", "#########################main_gate###################### def _calculation(): shirt_mm = shirt.get() pant_mm = pant.get() sale_mm", "\"bold\"),text=localtime,fg=\"white\",bg=\"black\", bd=10, anchor=\"w\", relief=RIDGE) lblInfo.pack() #===========================================================Calculator================================== \"\"\"def current_dir(): import os", "def __send_email(): '''import smtplib gmail = smtplib.SMTP(\"smtp.gmail.com\", 587) gmail.starttls() _file", "bill = bill_in.get() billo = bill_out.get() bills = tinydb.TinyDb(\"/bills.json\") while", "= open(\"/records.txt\",\"w\") finally: pass check = os.path.isfile(\"/records.txt\") if check: for", "\"bold\"), fg=\"white\", bg=\"black\", text=\"your_email\").pack(side=LEFT) entry1 = Entry(dframe, font=(\"arial\",16,\"bold\"), fg=\"white\",bg=\"black\", textvariable=email,insertwidth=1,bd=5).pack(side=RIGHT)", "#60 hours #changing all the formats to the seconds that", "= IntVar() deposite = IntVar() withdraw = IntVar() coat =", ",height=500,bg=\"goldenrod4\",relief=SUNKEN) f1.pack(side=LEFT) f2 = Frame(root, width = 300,height = 700,bg=\"dark", "relief=RIDGE) Tops.pack(side=TOP) f1 = Frame(root, width = 800 ,height=500,bg=\"goldenrod4\",relief=SUNKEN) f1.pack(side=LEFT)", "int(da) file.write(da) try: file = open(\"/records.txt\", \"r\") except: print(\"creating the", "def btnEqualsInput(): global operator sumup=str(eval(operator)) text_Input.set(sumup) operator=\"\" def bill_entry(): global", "return call #def yes_y(): # rupe = Toplevel(root) # rupe.title(\"this", "global cmd_active if \"rupen\" in cmd_active: if \"rupen\" in cmd_active[1]:", "the filenames with append =1 if the name already existed", "bills = tinydb.TinyDb(\"/bills.json\") while bill or billo != None: bills.insert({\"billInput\":", "%(self.hour-self.record_timeD)) #++++++++++++++++++++++++++++++++++++++++tinydb example++++++++++++++++++++++ #db = TinyDB(\"/databse/d4ta.json\") #db.insert({\"cus_number\":\"98938232\", \"cus_name\":\"rupen\"}) #def no_y():", "for item in db: data = open(\"/records.txt\",\"wb\") #with open(\"/records.txt\",\"wb\") as", "width=600, height=700,bg=\"RoyalBlue4\",relief=GROOVE) my_info.pack(side=LEFT) customer_info = Frame(win1, width=600, height=500,bg=\"RoyalBlue4\", relief=GROOVE) customer_info.pack(side=RIGHT)", "reading = file1 if len(reading) != None: print(\"its printed\") print(reading)", "the product is actually %s left\" %(self.hour-self.record_timeD)) #++++++++++++++++++++++++++++++++++++++++tinydb example++++++++++++++++++++++ #db", "nos window\") #return a = Entry(f2,font=(\"arial\", 20,\"bold\"), textvariable=text_Input, bd=30, insertwidth=4,", "#if the newfilename exists print(\"using the file {}\".format(new_file_name)) #file =", "textvariable=email,insertwidth=1,bd=5).pack(side=RIGHT) label1 = Label(dframe, font=(\"arial\",16, \"bold\"), fg=\"white\", bg=\"black\", text=\"password\", relief=SUNKEN).pack()", "\"\", \"o\": \"\", \"p\": \"\", \"q\": \"\", \"r\": \"\", \"s\":", "\"italic bold\"),text=\"Botique Management Systewm\",fg=\"white\", bg=\"dark slate blue\", bd=10, anchor=\"w\", relief=RIDGE)", "files: if len(data) != 0: print(\"this is are the files", "file: reading = file1 if len(reading) != None: print(\"its printed\")", "= bill_in.get() billo = bill_out.get() bills = tinydb.TinyDb(\"/bills.json\") while bill", "file.write(\"pant_mm:-{}\".format(pant_mm)) file.write(\"sale_mm:-{}\".format(sale_mm)) file.write(\"buy_mm:-{}\".format(buy_mm)) file.write(\"deposite_mm:-{}\".format(deposite_mm)) file.write(\"withdraw_mm:-{}\".format(withdraw_mm)) file.write(\"coat:-{}\".format(coat_mm)) file.write(\"order:-{}\".format(order_mm)) reading = file.readlines()", "\"r\": \"\", \"s\": \"\"} db.insert({\"total\": a }), db.insert({\"regrds\":\"reference\"}), db.insert({\"day_income\":\"billion\"}), db.insert({\"day_outgoing\":\"billout\"}),", "16,\"bold\"), text=\"Reference\",bd=16,fg=\"white\",bg=\"green\",anchor=\"w\", relief=RIDGE) lblReference.grid(row=0,column=0) b=Entry(f1,font=(\"arial\", 16, \"bold\"), textvariable=rand, bd=10,insertwidth=4,fg=\"white\",bg=\"black\", justify", ",\"k\":\"\",\"l\":\"\",\"m\":\"\",\"n\":\"\",\"o\":\"\",\"p\":\"\",\"q\":\"\",\"r\":\"\",\"s\":\"\"}''' #files = list(files) '''for data in files: if len(data)", "in python\\\\n check the file.txt for debug \") da +=", "deposite.get() withdraw_mm = withdraw.get() coat_mm = coat.get() order_mm = order.get()", "cus_name.get() r = cus_no.get() s = employee.get() files = {\"a\":", "blue\",text=\"order_info:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=9,column=0) orderx=Entry(f1,font=(\"arial\",16,\"bold\"),insertwidth=1, textvariable=order,bd=8,fg=\"white\",bg=\"black\").grid(row=10,column=0) lblcustomer=Label(f1,font=(\"arial\",16,\"bold\"),bg=\"powder blue\",text=\"cus_name:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=9,column=1) no=Entry(f1,font=(\"arial\",16, \"bold\"),bd=8,bg=\"black\",fg=\"white\",insertwidth=1, textvariable=cus_name).grid(row=10,column=1) lblmonthly=Label(f1, font=(\"arial\",16,\"bold\"),bg=\"powder", "StringVar() bill_out = StringVar() shrting=Label(f1,font=(\"arial\", 20, \"bold\"), text=\"Shirting:\",bg=\"powder blue\", fg=\"black\",anchor=\"w\",relief=GROOVE).grid(row=1,column=0)", "Label(f1,font=(\"arial\", 16,\"bold\"), text=\"Reference\",bd=16,fg=\"white\",bg=\"green\",anchor=\"w\", relief=RIDGE) lblReference.grid(row=0,column=0) b=Entry(f1,font=(\"arial\", 16, \"bold\"), textvariable=rand, bd=10,insertwidth=4,fg=\"white\",bg=\"black\",", "calculating seconds in one day that will ease all the", "16, \"bold\"), bg=\"powder blue\", text=\"outgoing:\", fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=7,column=1) outx=Entry(f1,font=(\"arial\", 16, \"bold\"),textvariable=out, bd=8,fg=\"white\",bg=\"black\",insertwidth=1).grid(row=8,column=1)", "delivery = IntVar() #########################main_gate###################### def _calculation(): shirt_mm = shirt.get() pant_mm", "#=============================getting all the infos ======================== def _price_inputs(): win2 = Toplevel()", "sari = IntVar() order_info = IntVar() delivery_report = IntVar() daily_info", "command=lambda: btnClick(0)).grid(row=5,column=0) btnClear=Button(f2,pady=16,padx=16,bd=8, fg=\"black\",font=(\"arial\", 20, \"bold\"),text=\"C\",bg=\"dim gray\", command=btnClearDisplay).grid(row=5,column=1) btnEquals=Button(f2,padx=16,pady=16,fg=\"black\",bd=8,text=\"=\",bg=\"dim gray\",", "daysec = (24*60) * 60 * 60 ### ##this is", "billo = bill_out.get() bills = tinydb.TinyDb(\"/bills.json\") while bill or billo", "sorry of the same of the tkinter in the main", "current_dir(): import os import sys DIR = os.getcwd() print(DIR) lblInfo", "= deposite.get() withdraw_mm = withdraw.get() coat_mm = coat.get() order_mm =", "withdraw.get() coat_mm = coat.get() order_mm = order.get() total_mm = total.get()", "the file {}\".format(file_name)) #file = open(\"{}\".format(file_name), \"w+\") break file_name =", "total = IntVar() out = IntVar() before = IntVar() #order", "700,bg=\"dark slate blue\",relief=SUNKEN) f2.pack(side=RIGHT) #f3= Frame(root,width=1600,height=300,fg=\"blue\", bg=\"powder blue\", relief=SUNKEN).pack(side=Bottom) #==========================================================Time=======================================", "insertwidth=1,bd=5).pack(side=RIGHT) Label2 =Label(dframe,font=(\"arial\",16, \"bold\"),fg=\"white\",bg=\"black\", text=\"sender_email\",relief=SUNKEN).pack(side=LEFT) entry2 = Entry(dframe,font=(\"arial\",16, \"bold\"),bd=5,fg=\"white\",bg=\"black\",textvariable=semail,insertwidth=1).pack(side=LEFT) label3", "PRICES\",relief=GROOVE).pack() win2.mainloop() ###########################sending emails############################ def __send_email(): '''import smtplib gmail =", "db.insert({\"regrds\":\"reference\"}), db.insert({\"day_income\":\"billion\"}), db.insert({\"day_outgoing\":\"billout\"}), db.insert({\"bankdeposit\":\"bankdepo\"}), db.insert({\"full_stock\":\"stock\"}), db.insert({\"shirt_mm\":\"shirt\"}), db.insert({\"bankwithdraw\":\"bankwith\"}), db.insert({\"pantmm\":\"pant\"}), db.insert({\"sarimm\":\"sari\"}), db.insert({\"orderday\":\"orderinfo\"}),", "blue\",fg=\"black\",anchor=\"w\",relief=GROOVE).grid(row=1,column=1) pantx=Entry(f1,font=(\"arial\",16, \"bold\"), textvariable=pant, insertwidth=1, bd=10,bg=\"black\",fg=\"white\", justify=\"left\").grid(row=2,column=1) sales=Label(f1,font=(\"arial\",16, \"bold\"), text=\"sales_total:\",bg=\"powder", "= Label(win1,font=(\"arial\", 20,\"italic\"),width=300, height=168,bg=\"black\",fg=\"white\", text=image,relief=FLAT).pack() win1.mainloop()''' #=============================getting all the infos", "revies of the follow in the sorry of the same", "\"p\": \"\", \"q\": \"\", \"r\": \"\", \"s\": \"\"} db.insert({\"total\": a", "command=lambda: btnClick(3)).grid(row=4,column=0) btn2=Button(f2,padx=16,pady=16,bd=8,text=\"2\",font=(\"arial\", 20, \"bold\"), bg=\"dim gray\", command=lambda: btnClick(2)).grid(row=4,column=1) btn1=Button(f2,padx=16,pady=16,bd=8,text=\"1\",font=(\"arial\",", "cus_no.get() s = employee.get() files = {\"a\": \"\", \"b\": \"\",", "lblInfo = Label(Tops, font=(\"arial\",30, \"bold\"),text=localtime,fg=\"white\",bg=\"black\", bd=10, anchor=\"w\", relief=RIDGE) lblInfo.pack() #===========================================================Calculator==================================", "gray\", command=lambda: btnClick(7)).grid(row=2,column=0) btn8=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"), text=\"8\",bg=\"dim gray\", command=lambda: btnClick(8)).grid(row=2,column=1)", "file.write(\"%s\" %(item)) time.sleep(1) print(\"done writing to the file\") #for item", "16, \"bold\"),text=\"coat_mm:\", bg=\"powder blue\",fg=\"black\",anchor=\"e\").grid(row=5,column=0) coatx=Entry(f1, font=(\"arial\", 16, \"bold\"), bg=\"black\", fg=\"white\",", "limit in the system of teh win1.title(\"this is the owner", "operator operator = operator + str(numbers) text_Input.set(operator) def btnClearDisplay(): global", "be easy for the #calculation #first calculating seconds in one", "lblmonthly=Label(f1, font=(\"arial\",16,\"bold\"),bg=\"powder blue\",text=\"monthly:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=5,column=2) monthly=StringVar() monthx=Entry(f1,font=(\"arial\",16,\"bold\"),show=\"blank\",bg=\"black\",textvariable=monthly,insertwidth=1,fg=\"white\",bd=10).grid(row=6,column=2) lbltotal=Label(f1, font=(\"arial\", 16, \"bold\"),bg=\"powder blue\",text=\"Total:\",fg=\"black\").grid(row=7,column=2)", "gray\", command=lambda: btnClick(\"+\")).grid(row=2,column=3) btn6=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"),text=\"4\", bg=\"dim gray\", command=lambda: btnClick(4)).grid(row=3,column=0)", "in range(5): if os.path.isfile(i): pass else: file = open(\"{}.txt\".format(i+1), \"w+\")", "= 60 * 60 files = {\"a\":\"\", \"b\":\"\",\"c\":\"\",\"d\":\"\",\"e\":\"\",\"f\":\"\",\"g\":\"\",\"h\":\"\",\"i\":\"\",\"j\":\"\" ,\"k\":\"\",\"l\":\"\",\"m\":\"\",\"n\":\"\",\"o\":\"\",\"p\":\"\",\"q\":\"\",\"r\":\"\",\"s\":\"\"}''' #files", "\"\" , \"k\": \"\", \"l\": \"\", \"m\": \"\", \"n\": \"\",", "db: with open(\"/records.txt\", \"rb\") as file: reading = file1 if", ",bg=\"black\", #fg=\"white\", anchor=\"w\").pack() #====================================debugged======================== shirt = IntVar() pant = IntVar()", "\"bold\"),bg=\"black\",fg=\"white\",textvariable=sale,insertwidth=1,bd=10,justify=\"left\").grid(row=2,column=2) buying=Label(f1,font=(\"arial\",16, \"bold\"), text=\"buying_something: \",bg=\"powder blue\",fg=\"black\", anchor=\"e\", relief=GROOVE).grid(row=3,column=0) buyx=Entry(f1,font=(\"arial\", 16,", "bg=\"powder blue\",text=\"sari mm:\", fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=5,column=1) sarix=Entry(f1, font=(\"arial\", 16, \"bold\"), bg=\"black\",bd=10, fg=\"white\",textvariable=sari,", "= IntVar() delivery_report = IntVar() daily_info = IntVar() sales =", "email = StringVar() password = StringVar() semail = StringVar() spassword", "Label(f1,font=(\"arial\", 16, \"bold\"),bg=\"powder blue\",text=\"employee name:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=9,column=2) employx= Entry(f1,font=(\"arial\", 16,\"bold\"),textvariable=employee,insertwidth=1,bg=\"black\",fg=\"white\",bd=10).grid(row=10,column=2) ###############################database for", "file = open(\"{}.txt\".format(i+1), \"w+\") created with name {}\".format(file))''' #creating the", "= file1 if len(reading) != None: print(\"its printed\") print(reading) file.close()", "self.hour == self.record_timeD: print(\"the time for the product is actually", "Frame(win1, width=600, height=500,bg=\"RoyalBlue4\", relief=GROOVE) customer_info.pack(side=RIGHT) others_info = Frame(win1, width=100, height=100,bg=\"RoyalBlue4\",relief=GROOVE)", "#order before the 60 stock = IntVar() delivery = IntVar()", "btn4=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"),text=\"6\",bg=\"dim gray\", command=lambda: btnClick(6)).grid(row=3,column=2) Subtract=Button(f2,padx=16,pady=16,bd=8,text=\"-\", bg=\"dim gray\", command=lambda:", "the sorry of the same of the tkinter in the", "db.insert({\"day_income\":\"billion\"}), db.insert({\"day_outgoing\":\"billout\"}), db.insert({\"bankdeposit\":\"bankdepo\"}), db.insert({\"full_stock\":\"stock\"}), db.insert({\"shirt_mm\":\"shirt\"}), db.insert({\"bankwithdraw\":\"bankwith\"}), db.insert({\"pantmm\":\"pant\"}), db.insert({\"sarimm\":\"sari\"}), db.insert({\"orderday\":\"orderinfo\"}), db.insert({\"salling\":\"sales\"}),", "Button(root, font=(\"arial 20 bold\"),bd=20, bg=\"black\",fg=\"white\",text=\"click\",command=ano_win1,relief=GROOVE).pack(side=BOTTOM) #fucking mazing yr coding def", "= Toplevel() win2.title(\"This is going to the section for the", "win1.mainloop()''' #=============================getting all the infos ======================== def _price_inputs(): win2 =", "of the tkinter in the main function of the sollow", "p = daily_cash.get() q = cus_name.get() r = cus_no.get() s", "\"bold\"),text=\"coat_mm:\", bg=\"powder blue\",fg=\"black\",anchor=\"e\").grid(row=5,column=0) coatx=Entry(f1, font=(\"arial\", 16, \"bold\"), bg=\"black\", fg=\"white\", textvariable=coat,", "function(): # pass(): # pass main(): # root.mainloop() #for the", "the total from here total.set #++++++++++++++++++++++++++++++Varibales_inset+++++++++++++++++++++++++++++++++ order_bef = IntVar() stock_full", "operator=\"\" def bill_entry(): global bill_in global bill_out bill_out = \"\"", "bd=10, relief=SUNKEN).pack(side=TOP) lblpro=Label(my_info,font=(\"arial\", 20,\"bold\"),text=\"Software Engineer\",bg=\"powder blue\", fg=\"green\",bd=10, relief=RAISED).pack() ima =", "smtplib.SMTP(\"smtp.gmail.com\", 587) gmail.starttls() _file = open(\"/root/Desktop/Desktop/python/\") gmail.login(\"username\", \"password\") msg =", "anchor=\"e\",relief=GROOVE).grid(row=3, column=1) depositex=Entry(f1,font=(\"arial\",16,\"bold\"),bd=10, textvariable=deposite, bg=\"black\", fg=\"white\", justify=\"left\").grid(row=4, column=1) lblBankwith=Label(f1, font=(\"arial\",", "time.month hour = time.hour second = time.second year = time.year", "= str(d.minute) second = str(d.second) between = str(\":\")''' '''def __time(infos):", "_image(image)).pack() '''def _image(image): image = image.set(imageloc) return image #image =", "#from database1 import * from random import randint root =", "\"c\": \"\", \"d\": \"\", \"e\": \"\", \"f\": \"\", \"g\": \"\",", "da += data print(data) da = int(da) file.write(da) try: file", "command=lambda: btnClick(7)).grid(row=2,column=0) btn8=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"), text=\"8\",bg=\"dim gray\", command=lambda: btnClick(8)).grid(row=2,column=1) btn9=Button(f2,padx=16,pady=16,bd=8,", "= IntVar() stock_full = IntVar() shrting = IntVar() pant =", "script {}\".format(__file__)) file = open(\"/records.txt\",\"w\") finally: pass check = os.path.isfile(\"/records.txt\")", "Frame(root,width=1600,height=300,fg=\"blue\", bg=\"powder blue\", relief=SUNKEN).pack(side=Bottom) #==========================================================Time======================================= localtime=time.asctime(time.localtime(time.time())) #datetime=Label(Tops,font(\"arial\",20,\"bold\"),text=nowTime,bd=10 ,bg=\"black\", #fg=\"white\", anchor=\"w\").pack()", "name = Query() #db(name.type == \"changed\") d = datetime.now() month", "\"bold\"), bg=\"black\",bd=10, fg=\"white\",textvariable=sari, insertwidth=1).grid(row=6,column=1) buying=Label(f1,font=(\"arial\", 16, \"bold\"), bg=\"powder blue\",text=\"buy_info:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=7,column=0) buyx=Entry(f1,font=(\"arial\",16,", "append =1 if the name already existed file_name = \"r.txt\"", "'''for data in files: if len(data) != 0: print(data)''' #lenght", "current_dir(dir)).pack(side=TOP) def btnClick(numbers): global operator operator = operator + str(numbers)", "that will ease all the further operations daysec = (24*60)", "insertwidth=1,bg=\"black\",fg=\"white\", justify=\"left\").grid(row=2,column=0) owner=Button(root,padx=16,pady=16, font=(\"arial\",12, \"bold\"),text=\"info\", bd=8,bg=\"black\",command=ano_win1,fg=\"white\",relief=RAISED).pack(side=LEFT) yes=Button(root,padx=16,pady=16,font=(\"arial\",12, \"bold\"),text=\"Done\",bd=8,bg=\"black\", fg=\"white\", command=_calculation(),relief=RAISED).pack(side=RIGHT)", "is will be easy now yearSec = daysec * 365", "justify = \"left\") b.grid(row=0,column=1) #img = \"/root/Desktop/Desktop/python/projects/prj1_Botik/1.jpg\" #root.ima = Image.open(img)", ", \"k\": \"\", \"l\": \"\", \"m\": \"\", \"n\": \"\", \"o\":", "the function #of the system on the support in teh", "True: expand += 1 new_file_name = file_name.split(\".txt\")[0] + str(expand) +", "======================== def _price_inputs(): win2 = Toplevel() win2.title(\"This is going to", "the loop #file = open(\"1{}\".format()) '''for i in range(5): if", "800 ,height=500,bg=\"goldenrod4\",relief=SUNKEN) f1.pack(side=LEFT) f2 = Frame(root, width = 300,height =", "#db = TinyDB(\"/databse/d4ta.json\") #db.insert({\"cus_number\":\"98938232\", \"cus_name\":\"rupen\"}) #def no_y(): # lis =", "Frame(root, width=1600 ,height=50,bg=\"goldenrod4\", relief=RIDGE) Tops.pack(side=TOP) f1 = Frame(root, width =", "the recorded bill numbers def bill_in(): ##assuming the variable as", "due_amount.get() o = order_info.get() p = daily_cash.get() q = cus_name.get()", "= list(files) '''for data in files: if len(data) != 0:", "= IntVar() bank_deposite = IntVar() bank_withdraw = IntVar() due_amount =", "= order_bef.get() b = stock_full.get() c = shrting.get() d =", "text_Input.set(operator) def btnClearDisplay(): global operator operator=\"\" text_Input.set(\"\") def btnEqualsInput(): global", "dframe = Frame(dialog,width=800,height=800,bg=\"white\",relief=SUNKEN).pack() email = StringVar() password = StringVar() semail", "fg=\"black\", font=(\"arial\",20,\"bold\"), text=\"9\",bg=\"dim gray\", command=lambda: btnClick(9)).grid(row=2,column=2) #!!!!!!!!!!!!!!!!!!!!!!additions!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Addition=Button(f2,padx=16,pady=16,bd=8,text=\"+\",fg=\"black\",bg=\"dim gray\", command=lambda:", "order_info.get() p = daily_cash.get() q = cus_name.get() r = cus_no.get()", "bill_out bill_out = \"\" bill_in = \"\" def rupen(): global", "= Label(dframe, font=(\"arial\",16, \"bold\"), fg=\"white\", bg=\"black\", text=\"your_email\").pack(side=LEFT) entry1 = Entry(dframe,", "gray\", command=btnClearDisplay).grid(row=5,column=1) btnEquals=Button(f2,padx=16,pady=16,fg=\"black\",bd=8,text=\"=\",bg=\"dim gray\", font=(\"arial\", 20,\"bold\"), command=btnEqualsInput).grid(row=5,column=2) #btn2=Button(f2,padx=16,pady=16,bd=8,fg=\"black\",text=\"2\",bg=\"dim gray\", command=lambda:", "winF = Frame(win, bg=\"black\",relief=SUNKEN).pack() winE = Entry(winF, insertwidth=10,insertheight=10,fg=\"white\",bg=\"black\",textvariable=bills).pack() win.mainloop() #l", "DIR = os.getcwd() print(DIR) lblInfo = Label(Tops, font=(\"arial\",60, \"italic\"),text=current_dir,fg=\"black\",bg=\"powder blue\",bd=10,", "files = list(files) file = open(\"/file.txt\", \"wb\") da = \"\"", "= str(time.day) month = str(time.month) hour = str(time.hour) second =", "* 365 month = daysec * 30 daySec = daysec", "!= None: bills.insert({\"billInput\": bill, \"billOutput\": billo}) win = Toplevel() win.title(\"bills\")", "\"bold\"), bg=\"powder blue\", text=\"outgoing:\", fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=7,column=1) outx=Entry(f1,font=(\"arial\", 16, \"bold\"),textvariable=out, bd=8,fg=\"white\",bg=\"black\",insertwidth=1).grid(row=8,column=1) ordering=Label(f1,font=(\"arial\",16,\"bold\"),bg=\"powder", "seconds in one day that will ease all the further", "#txtReference=Entry(f1,font=(\"arial\", 16, \"bold\"), textvariable=rand, bd=10,insertwidth=4,bg=\"red\",fg=\"white\", justify = \"right\").grid(row=0,column=1) #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! lblReference", "my_info.pack(side=LEFT) customer_info = Frame(win1, width=600, height=500,bg=\"RoyalBlue4\", relief=GROOVE) customer_info.pack(side=RIGHT) others_info =", "= StringVar() semail = StringVar() spassword = StringVar() label =", "= IntVar() #########################main_gate###################### def _calculation(): shirt_mm = shirt.get() pant_mm =", "in files: if len(data) != 0: print(data)''' #lenght = len(db)", "bill_out.get() bills = tinydb.TinyDb(\"/bills.json\") while bill or billo != None:", "in teh main loop #there is no limit in the", "coat = IntVar() order = IntVar() total = IntVar() out", "price inputs\") win2.geometry(\"1600x800\") framex = Frame(win2,width=1600,bg=\"RoyalBlue4\",height=100,relief=GROOVE).pack(side=TOP) frame1 = Frame(win2,width=775, height=750,bg=\"white\",", "bg=\"black\",relief=SUNKEN).pack() winE = Entry(winF, insertwidth=10,insertheight=10,fg=\"white\",bg=\"black\",textvariable=bills).pack() win.mainloop() #l # command=bill_in).pack(anchor=NE) root.mainloop()", "TinyDB(\"/databse/d4ta.json\") #db.insert({\"cus_number\":\"98938232\", \"cus_name\":\"rupen\"}) #def no_y(): # lis = db.all() ################Info===============", "call=cal+1 return call #def yes_y(): # rupe = Toplevel(root) #", "entry2 = Entry(dframe,font=(\"arial\",16, \"bold\"),bd=5,fg=\"white\",bg=\"black\",textvariable=semail,insertwidth=1).pack(side=LEFT) label3 = Label(dframe,font=(\"arial\",16,\"bold\"),fg=\"white\",bg=\"black\",text=\"sender_password\", relief=SUNKEN).pack(side=LEFT) entry3= Entry(dframe,font=(\"arial\",16,\"bold\"),fg=\"white\",textvariable=spassword,insertwidth=1,relief=SUNKEN).pack()", "= int(da) file.write(da) try: file = open(\"/records.txt\", \"r\") except: print(\"creating", "command=lambda: btnClick(\"+\")).grid(row=3,column=6) #btn10=Button(f2,padx=16,padx=16, fg=\"blue\", font(\"arial\",5,\"bold\"), # text=\"rupen\",bg=\"powder blue\", command=rupen).grid(row=3,column=5) #def", "font=(\"arial\",16, \"bold\"), fg=\"white\", bg=\"black\", text=\"password\", relief=SUNKEN).pack() entry2 = Entry(dframe,font=(\"arial\", 16", "seconds that will be easy for the #calculation #first calculating", "owner window:\") win1.geometry(\"1600x800+0+0\") #win1.configure(bg=\"silver\") my_info = Frame(win1, width=600, height=700,bg=\"RoyalBlue4\",relief=GROOVE) my_info.pack(side=LEFT)", "the window in which there is nothing in the function", "#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! rand = StringVar() #lblReference = Label(f1,font=(\"arial\", 16,\"bold\"), text=\"Reference\",bd=16,fg=\"red\",bg=\"red\",anchor=\"w\",relief=RIDGE).grid(row=0,column=0) #txtReference=Entry(f1,font=(\"arial\",", "= bank_withdraw.get() n = due_amount.get() o = order_info.get() p =", "\"bold\"), text=\"sales_total:\",bg=\"powder blue\",fg=\"black\",anchor=\"w\",bd=8,relief=GROOVE).grid(row=1,column=2) salex=Entry(f1,font=(\"arial\",16, \"bold\"),bg=\"black\",fg=\"white\",textvariable=sale,insertwidth=1,bd=10,justify=\"left\").grid(row=2,column=2) buying=Label(f1,font=(\"arial\",16, \"bold\"), text=\"buying_something: \",bg=\"powder blue\",fg=\"black\",", "fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=7,column=1) outx=Entry(f1,font=(\"arial\", 16, \"bold\"),textvariable=out, bd=8,fg=\"white\",bg=\"black\",insertwidth=1).grid(row=8,column=1) ordering=Label(f1,font=(\"arial\",16,\"bold\"),bg=\"powder blue\",text=\"order_info:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=9,column=0) orderx=Entry(f1,font=(\"arial\",16,\"bold\"),insertwidth=1, textvariable=order,bd=8,fg=\"white\",bg=\"black\").grid(row=10,column=0) lblcustomer=Label(f1,font=(\"arial\",16,\"bold\"),bg=\"powder", "file.write(\"deposite_mm:-{}\".format(deposite_mm)) file.write(\"withdraw_mm:-{}\".format(withdraw_mm)) file.write(\"coat:-{}\".format(coat_mm)) file.write(\"order:-{}\".format(order_mm)) reading = file.readlines() file.close() #after wards", "sari.get() f = order_info.get() g = delivery_report.get() h = daily_info.get()", "= list(files) file = open(\"/file.txt\", \"wb\") da = \"\" for", "def _price_inputs(): win2 = Toplevel() win2.title(\"This is going to the", "dir #return dir \"\"\" #randomBtn=Button(f1,pady=16,padx=16,bd=8,bg=\"powder blue\", text=\"C_dir\", command=lambda: current_dir(dir)).pack(side=TOP) def", "operator sumup=str(eval(operator)) text_Input.set(sumup) operator=\"\" def bill_entry(): global bill_in global bill_out", "= delivery_report.get() h = daily_info.get() i = sales.get() j =", "#file = open(\"1{}\".format()) '''for i in range(5): if os.path.isfile(i): pass", "str(\":\")''' '''def __time(infos): time = datetime.now() day = str(time.day) month", "label = Label(dframe, font=(\"arial\",16, \"bold\"), fg=\"white\", bg=\"black\", text=\"your_email\").pack(side=LEFT) entry1 =", "pickle #from database1 import * from random import randint root", "\"bold\"), bg=\"black\",fg=\"white\",text=\"email\",command=lambda: __send_email(),relief=GROOVE).pack() #================================next section=========================== fix = Button(root, bd=10,bg=\"black\",fg=\"white\",command=_price_inputs,relief=GROOVE).pack(side=BOTTOM) btnru", "gray\", command=lambda: btnClick(1)).grid(row=4,column=2) Multiply=Button(f2,padx=16,pady=16,bd=8,text=\"*\", bg=\"dim gray\", command=lambda: btnClick(\"X\")).grid(row=4,column=3) #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ btn0=Button(f2,padx=16,pady=16,bd=8,bg=\"dim", "\"bold\"), bg=\"powder blue\",text=\"sari mm:\", fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=5,column=1) sarix=Entry(f1, font=(\"arial\", 16, \"bold\"), bg=\"black\",bd=10,", "file.write(\"buy_mm:-{}\".format(buy_mm)) file.write(\"deposite_mm:-{}\".format(deposite_mm)) file.write(\"withdraw_mm:-{}\".format(withdraw_mm)) file.write(\"coat:-{}\".format(coat_mm)) file.write(\"order:-{}\".format(order_mm)) reading = file.readlines() file.close() #after", "Frame(dialog,width=800,height=800,bg=\"white\",relief=SUNKEN).pack() email = StringVar() password = StringVar() semail = StringVar()", "16, \"bold\"),textvariable=out, bd=8,fg=\"white\",bg=\"black\",insertwidth=1).grid(row=8,column=1) ordering=Label(f1,font=(\"arial\",16,\"bold\"),bg=\"powder blue\",text=\"order_info:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=9,column=0) orderx=Entry(f1,font=(\"arial\",16,\"bold\"),insertwidth=1, textvariable=order,bd=8,fg=\"white\",bg=\"black\").grid(row=10,column=0) lblcustomer=Label(f1,font=(\"arial\",16,\"bold\"),bg=\"powder blue\",text=\"cus_name:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=9,column=1) no=Entry(f1,font=(\"arial\",16,", "insertwidth=1, bd=10,bg=\"black\", fg=\"white\", justify=\"left\").grid(row=4,column=0) Bank_Total=Label(f1,font=(\"arial\",16,\"bold\"),text=\"Bank_Deposite: \", bg=\"powder blue\", fg=\"black\", anchor=\"e\",relief=GROOVE).grid(row=3,", "_file = open(\"/root/Desktop/Desktop/python/\") gmail.login(\"username\", \"password\") msg = \"YOUR MESSAGE\" gmail.sendmail(\"your", "tkinter import * import random import time from PIL import", "file.write(da) try: file = open(\"/records.txt\", \"r\") except: print(\"creating the file", "#first calculating seconds in one day that will ease all", "files written in python\\\\n check the file.txt for debug \")", "a = Entry(f2,font=(\"arial\", 20,\"bold\"), textvariable=text_Input, bd=30, insertwidth=4, bg=\"dark slate blue\",fg=\"white\",", "font=(\"arial\",20,\"bold\"),text=\"5\", bg=\"dim gray\", command=lambda: btnClick(5)).grid(row=3,column=1) btn4=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"),text=\"6\",bg=\"dim gray\", command=lambda:", "text=\"C_dir\", command=lambda: current_dir(dir)).pack(side=TOP) def btnClick(numbers): global operator operator = operator", "#return dir \"\"\" #randomBtn=Button(f1,pady=16,padx=16,bd=8,bg=\"powder blue\", text=\"C_dir\", command=lambda: current_dir(dir)).pack(side=TOP) def btnClick(numbers):", "slate blue\",fg=\"white\", justify=\"right\").grid(columnspan=4) btn7=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"), text=\"7\",bg=\"dim gray\", command=lambda: btnClick(7)).grid(row=2,column=0)", "btnClick(0)).grid(row=5,column=0) btnClear=Button(f2,pady=16,padx=16,bd=8, fg=\"black\",font=(\"arial\", 20, \"bold\"),text=\"C\",bg=\"dim gray\", command=btnClearDisplay).grid(row=5,column=1) btnEquals=Button(f2,padx=16,pady=16,fg=\"black\",bd=8,text=\"=\",bg=\"dim gray\", font=(\"arial\",", "daysec * 365 month = daysec * 30 daySec =", "relief=RIDGE) lblReference.grid(row=0,column=0) b=Entry(f1,font=(\"arial\", 16, \"bold\"), textvariable=rand, bd=10,insertwidth=4,fg=\"white\",bg=\"black\", justify = \"left\")", "lblInfo = Label(Tops, font=(\"arial\",60, \"italic bold\"),text=\"Botique Management Systewm\",fg=\"white\", bg=\"dark slate", "all the further operations daysec = (24*60) * 60 *", "\"rupen\" in cmd_active[1]: if \"ronley\" in cmd_active[2]:''' #==============================another windows about", "tinydb.TinyDb(\"/bills.json\") while bill or billo != None: bills.insert({\"billInput\": bill, \"billOutput\":", "#fucking mazing yr coding def column(col): for coll in col:", "= Frame(dialog,width=800,height=800,bg=\"white\",relief=SUNKEN).pack() email = StringVar() password = StringVar() semail =", "cmd_active[2]:''' #==============================another windows about me===================== def ano_win1(): win1 = Toplevel()", "IntVar() pant = IntVar() sale = IntVar() buy = IntVar()", "ronley = StringVar() '''def malware_activate(): global cmd_active if \"rupen\" in", "there is nothing in the function #of the system on", "= sale.get() buy_mm = buy.get() deposite_mm = deposite.get() withdraw_mm =", "db: data = open(\"/records.txt\",\"wb\") #with open(\"/records.txt\",\"wb\") as file: #pickle.dump(item, data)", "from datetime import datetime from tinydb import * import os", "\"\", \"n\": \"\", \"o\": \"\", \"p\": \"\", \"q\": \"\", \"r\":", "coding def column(col): for coll in col: call=cal+1 return call", "using the loop #file = open(\"1{}\".format()) '''for i in range(5):", "= IntVar() pant = IntVar() sale = IntVar() buy =", "= order def __order_info(self): self.now = datetime() self.hour = now.hour", "\"bold\"),bg=\"powder blue\",text=\"Total:\",fg=\"black\").grid(row=7,column=2) totalx=Entry(f1, font=(\"arial\", 16, \"bold\"),bg=\"black\",textvariable=total,fg=\"white\",insertwidth=1,bd=10).grid(row=8,column=2) lblemployee = Label(f1,font=(\"arial\", 16,", "if check: for item in db: data = open(\"/records.txt\",\"wb\") #with", "btnClick(1)).grid(row=4,column=2) Multiply=Button(f2,padx=16,pady=16,bd=8,text=\"*\", bg=\"dim gray\", command=lambda: btnClick(\"X\")).grid(row=4,column=3) #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ btn0=Button(f2,padx=16,pady=16,bd=8,bg=\"dim gray\",text=\"0\",fg=\"black\",font=(\"arial\", 20,", "= datetime.now() day = str(time.day) month = str(time.month) hour =", "str(expand) + \".txt\" if os.path.isfile(new_file_name): #if the newfilename exists print(\"using", "16,\"bold\"), text=\"Reference\",bd=16,fg=\"red\",bg=\"red\",anchor=\"w\",relief=RIDGE).grid(row=0,column=0) #txtReference=Entry(f1,font=(\"arial\", 16, \"bold\"), textvariable=rand, bd=10,insertwidth=4,bg=\"red\",fg=\"white\", justify = \"right\").grid(row=0,column=1)", "!= 0: print(data)''' #lenght = len(db) ##this will show the", "is nothing in the function #of the system on the", "bg=\"powder blue\",fg=\"black\",anchor=\"e\").grid(row=5,column=0) coatx=Entry(f1, font=(\"arial\", 16, \"bold\"), bg=\"black\", fg=\"white\", textvariable=coat, insertwidth=1,", "#f3= Frame(root,width=1600,height=300,fg=\"blue\", bg=\"powder blue\", relief=SUNKEN).pack(side=Bottom) #==========================================================Time======================================= localtime=time.asctime(time.localtime(time.time())) #datetime=Label(Tops,font(\"arial\",20,\"bold\"),text=nowTime,bd=10 ,bg=\"black\", #fg=\"white\",", "StringVar() semail = StringVar() spassword = StringVar() label = Label(dframe,", "going to the section for the price inputs\") win2.geometry(\"1600x800\") framex", "operations daysec = (24*60) * 60 * 60 ### ##this", "IntVar() employee = IntVar() ###############################class of algoriths######################### class __main(): def", "font=(\"arial\", 20,\"bold\"), command=btnEqualsInput).grid(row=5,column=2) #btn2=Button(f2,padx=16,pady=16,bd=8,fg=\"black\",text=\"2\",bg=\"dim gray\", command=lambda: btnClick(2)).grid(row=5,column=3) division=Button(f2,padx=16,pady=16,bd=8,fg=\"black\", text=\"/\", bg=\"dim", "%s left\" %(self.hour-self.record_timeD)) #++++++++++++++++++++++++++++++++++++++++tinydb example++++++++++++++++++++++ #db = TinyDB(\"/databse/d4ta.json\") #db.insert({\"cus_number\":\"98938232\", \"cus_name\":\"rupen\"})", "btn5=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"),text=\"5\", bg=\"dim gray\", command=lambda: btnClick(5)).grid(row=3,column=1) btn4=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"),text=\"6\",bg=\"dim", "width=1600 ,height=50,bg=\"goldenrod4\", relief=RIDGE) Tops.pack(side=TOP) f1 = Frame(root, width = 800", "##assuming the variable as bill number .get var bill =", "variable as bill number .get var bill = bill_in.get() billo", "__main(): def __init__(self): self.order = order def __order_info(self): self.now =", "gmail = smtplib.SMTP(\"smtp.gmail.com\", 587) gmail.starttls() _file = open(\"/root/Desktop/Desktop/python/\") gmail.login(\"username\", \"password\")", "blue\",text=\"Bank_Withdraw\", anchor=\"e\",relief=GROOVE).grid(row=3,column=2) withdrawx=Entry(f1,font=(\"arial\",16, \"bold\"),bd=10, fg=\"white\",bg=\"black\", textvariable=withdraw, insertwidth=1).grid(row=4,column=2) coating=Label(f1, font=(\"arial\", 16,", "bg=\"black\", text=\"your_email\").pack(side=LEFT) entry1 = Entry(dframe, font=(\"arial\",16,\"bold\"), fg=\"white\",bg=\"black\", textvariable=email,insertwidth=1,bd=5).pack(side=RIGHT) label1 =", "import time from PIL import Image from datetime import datetime", "\"n\": \"\", \"o\": \"\", \"p\": \"\", \"q\": \"\", \"r\": \"\",", "len(reading) != None: print(\"its printed\") print(reading) file.close() #db.insert({\"name\":\"<NAME>\"}) name =", "shirts=Entry(f1,font=(\"arial\", 16, \"italic\"), bd=10, textvariable=shirt, insertwidth=1,bg=\"black\",fg=\"white\", justify=\"left\").grid(row=2,column=0) owner=Button(root,padx=16,pady=16, font=(\"arial\",12, \"bold\"),text=\"info\",", "data = open(\"/records.txt\",\"wb\") #with open(\"/records.txt\",\"wb\") as file: #pickle.dump(item, data) #file.close()", "text=\"Reference\",bd=16,fg=\"red\",bg=\"red\",anchor=\"w\",relief=RIDGE).grid(row=0,column=0) #txtReference=Entry(f1,font=(\"arial\", 16, \"bold\"), textvariable=rand, bd=10,insertwidth=4,bg=\"red\",fg=\"white\", justify = \"right\").grid(row=0,column=1) #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", "the infos as the order taken that will be notified", "Label(f1,font=(\"arial\", 16,\"bold\"), text=\"Reference\",bd=16,fg=\"red\",bg=\"red\",anchor=\"w\",relief=RIDGE).grid(row=0,column=0) #txtReference=Entry(f1,font=(\"arial\", 16, \"bold\"), textvariable=rand, bd=10,insertwidth=4,bg=\"red\",fg=\"white\", justify =", "dialog.geometry(\"800x800\") dframe = Frame(dialog,width=800,height=800,bg=\"white\",relief=SUNKEN).pack() email = StringVar() password = StringVar()", "bg=\"dim gray\", command=lambda: btnClick(5)).grid(row=3,column=1) btn4=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"),text=\"6\",bg=\"dim gray\", command=lambda: btnClick(6)).grid(row=3,column=2)", "= Label(f1,font=(\"arial\", 16,\"bold\"), text=\"Reference\",bd=16,fg=\"white\",bg=\"green\",anchor=\"w\", relief=RIDGE) lblReference.grid(row=0,column=0) b=Entry(f1,font=(\"arial\", 16, \"bold\"), textvariable=rand,", "def __init__(self): self.order = order def __order_info(self): self.now = datetime()", "bg=\"powder blue\",text=\"buy_info:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=7,column=0) buyx=Entry(f1,font=(\"arial\",16, \"bold\"),bd=8, fg=\"white\",bg=\"black\",textvariable=buy,insertwidth=1).grid(row=8,column=0) outgoing =Label(f1, font=(\"arial\", 16, \"bold\"),", "= time.minute #setting the filename using the loop #file =", "item in db: with open(\"/records.txt\", \"rb\") as file: reading =", "= IntVar() sari = IntVar() order_info = IntVar() delivery_report =", "the seconds that will be easy for the #calculation #first", "h = daily_info.get() i = sales.get() j = buy.get() k", "fg=\"white\",bg=\"black\",textvariable=buy,insertwidth=1).grid(row=8,column=0) outgoing =Label(f1, font=(\"arial\", 16, \"bold\"), bg=\"powder blue\", text=\"outgoing:\", fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=7,column=1)", "depositex=Entry(f1,font=(\"arial\",16,\"bold\"),bd=10, textvariable=deposite, bg=\"black\", fg=\"white\", justify=\"left\").grid(row=4, column=1) lblBankwith=Label(f1, font=(\"arial\", 16, \"bold\"),fg=\"black\",bg=\"powder", "20, \"bold\"), bg=\"dim gray\", command=lambda: btnClick(2)).grid(row=4,column=1) btn1=Button(f2,padx=16,pady=16,bd=8,text=\"1\",font=(\"arial\", 20, \"bold\") ,bg=\"dim", "= open(\"{}\".format(file_name), \"w+\") break file_name = \"fil.txt\" file = open(\"{}\".format(file_name),\"w+\")", "print(data)''' #lenght = len(db) ##this will show the recorded bill", "import pickle #from database1 import * from random import randint", "def btnClearDisplay(): global operator operator=\"\" text_Input.set(\"\") def btnEqualsInput(): global operator", "Toplevel() #this is going to be the window in which", "formats to the seconds that will be easy for the", "fg=\"white\",bg=\"black\", textvariable=email,insertwidth=1,bd=5).pack(side=RIGHT) label1 = Label(dframe, font=(\"arial\",16, \"bold\"), fg=\"white\", bg=\"black\", text=\"password\",", "the infos ======================== def _price_inputs(): win2 = Toplevel() win2.title(\"This is", "system of teh win1.title(\"this is the owner window:\") win1.geometry(\"1600x800+0+0\") #win1.configure(bg=\"silver\")", "=\"\" yes =\"\" no=\"\" Tops = Frame(root, width=1600 ,height=50,bg=\"goldenrod4\", relief=RIDGE)", "= Label(Tops, font=(\"arial\",60, \"italic\"),text=current_dir,fg=\"black\",bg=\"powder blue\",bd=10, anchor=\"W\") lblInfo.pack() #DIR = dir", "#this is going to be the window in which there", "cus_name = IntVar() cus_no = IntVar() employee = IntVar() ###############################class", "* 60 ### ##this is will be easy now yearSec", "IntVar() total_bank = IntVar() bank_deposite = IntVar() bank_withdraw = IntVar()", "teh main loop #there is no limit in the system", "= time.day month = time.month hour = time.hour second =", "ease all the further operations daysec = (24*60) * 60", "others_info = Frame(win1, width=100, height=100,bg=\"RoyalBlue4\",relief=GROOVE) others_info.pack(side=BOTTOM) all_info = Frame(win1, width=50,", "font=(\"arial\", 16, \"bold\"), bg=\"black\", fg=\"white\", textvariable=coat, insertwidth=1, justify=\"left\",bd=10).grid(row=6,column=0) lablsari=Label(f1,font=(\"arial\", 16,", "\"l\": \"\", \"m\": \"\", \"n\": \"\", \"o\": \"\", \"p\": \"\",", "open(\"/file.txt\", \"wb\") da = \"\" for data in files: if", "Multiply=Button(f2,padx=16,pady=16,bd=8,text=\"*\", bg=\"dim gray\", command=lambda: btnClick(\"X\")).grid(row=4,column=3) #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ btn0=Button(f2,padx=16,pady=16,bd=8,bg=\"dim gray\",text=\"0\",fg=\"black\",font=(\"arial\", 20, \"bold\"),", "if the name already existed file_name = \"r.txt\" if os.path.isfile(file_name):", "len(db) ##this will show the recorded bill numbers def bill_in():", "font=(\"arial\", 16, \"bold\"),bg=\"black\",textvariable=total,fg=\"white\",insertwidth=1,bd=10).grid(row=8,column=2) lblemployee = Label(f1,font=(\"arial\", 16, \"bold\"),bg=\"powder blue\",text=\"employee name:\",fg=\"black\",anchor=\"e\",relief=GROOVE).grid(row=9,column=2)", "= {\"a\": \"\", \"b\": \"\", \"c\": \"\", \"d\": \"\", \"e\":", "db.insert({\"shirt_mm\":\"shirt\"}), db.insert({\"bankwithdraw\":\"bankwith\"}), db.insert({\"pantmm\":\"pant\"}), db.insert({\"sarimm\":\"sari\"}), db.insert({\"orderday\":\"orderinfo\"}), db.insert({\"salling\":\"sales\"}), db.insert({\"buying\":\"buy\"}), db.insert({\"customern\":\"customer\"}), db.insert({\"monthly_info\":\"monthly\"}), db.insert({\"totaldy\":\"total\"}),", "font=(\"arial\",60, \"italic bold\"),text=\"Botique Management Systewm\",fg=\"white\", bg=\"dark slate blue\", bd=10, anchor=\"w\",", "printed\") print(reading) file.close() #db.insert({\"name\":\"<NAME>\"}) name = Query() #db(name.type == \"changed\")", "print(\"creating the file {}\".format(file_name)) #file = open(\"{}\".format(file_name), \"w+\") break file_name", "self.record_time = record_time if self.hour == self.record_timeD: print(\"the time for", "+= data print(data) da = int(da) file.write(da) try: file =", "pant.get() sale_mm = sale.get() buy_mm = buy.get() deposite_mm = deposite.get()", "month = time.month hour = time.hour second = time.second year", "label1 = Label(dframe, font=(\"arial\",16, \"bold\"), fg=\"white\", bg=\"black\", text=\"password\", relief=SUNKEN).pack() entry2", "#nos.title(\"this is nos window\") #return a = Entry(f2,font=(\"arial\", 20,\"bold\"), textvariable=text_Input,", "Systewm\",fg=\"white\", bg=\"dark slate blue\", bd=10, anchor=\"w\", relief=RIDGE) lblInfo.pack() lblInfo =", "name {}\".format(file))''' #creating the filenames with append =1 if the", "\"rupen\" in cmd_active: if \"rupen\" in cmd_active[1]: if \"ronley\" in", "#fuck = c.get() a = order_bef.get() b = stock_full.get() c", "frame2 = Frame(win2, width=775,height=750,bg=\"black\", relief=FLAT).pack() #==++++===========================title============================= llb1 = Label(framex,font=(\"arial\", 20,\"italic\"),bg=\"powder", "font=(\"arial\", 16, \"bold\"),fg=\"black\",bg=\"powder blue\",text=\"Bank_Withdraw\", anchor=\"e\",relief=GROOVE).grid(row=3,column=2) withdrawx=Entry(f1,font=(\"arial\",16, \"bold\"),bd=10, fg=\"white\",bg=\"black\", textvariable=withdraw, insertwidth=1).grid(row=4,column=2)", "textvariable=withdraw, insertwidth=1).grid(row=4,column=2) coating=Label(f1, font=(\"arial\", 16, \"bold\"),text=\"coat_mm:\", bg=\"powder blue\",fg=\"black\",anchor=\"e\").grid(row=5,column=0) coatx=Entry(f1, font=(\"arial\",", "= Entry(f2,font=(\"arial\", 20,\"bold\"), textvariable=text_Input, bd=30, insertwidth=4, bg=\"dark slate blue\",fg=\"white\", justify=\"right\").grid(columnspan=4)", "reading = file.readlines() file.close() #after wards set the total from", "################Info=============== lblInfo = Label(Tops, font=(\"arial\",60, \"italic bold\"),text=\"Botique Management Systewm\",fg=\"white\", bg=\"dark", "to be the window in which there is nothing in", "text=\"rupen\",bg=\"powder blue\", command=rupen).grid(row=3,column=5) #def function(): # pass(): # pass main():", "\"bold\"),bd=8, fg=\"white\",bg=\"black\",textvariable=buy,insertwidth=1).grid(row=8,column=0) outgoing =Label(f1, font=(\"arial\", 16, \"bold\"), bg=\"powder blue\", text=\"outgoing:\",", "btn2=Button(f2,padx=16,pady=16,bd=8,text=\"2\",font=(\"arial\", 20, \"bold\"), bg=\"dim gray\", command=lambda: btnClick(2)).grid(row=4,column=1) btn1=Button(f2,padx=16,pady=16,bd=8,text=\"1\",font=(\"arial\", 20, \"bold\")", "daily_cash = IntVar() cus_name = IntVar() cus_no = IntVar() employee", "is are the files written in python\\\\n check the file.txt", "email adress\", \"the\") gmail.quit()''' dialog = Tk() dialog.title(\"Send emails\") dialog.geometry(\"800x800\")", "list(files) file = open(\"/file.txt\", \"wb\") da = \"\" for data", "#item = str(item) file.write(\"%s\" %(item)) time.sleep(1) print(\"done writing to the", "\"\", \"l\": \"\", \"m\": \"\", \"n\": \"\", \"o\": \"\", \"p\":", "#for item in db: with open(\"/records.txt\", \"rb\") as file: reading", "= pant.get() sale_mm = sale.get() buy_mm = buy.get() deposite_mm =", "number .get var bill = bill_in.get() billo = bill_out.get() bills", "will be notified before the #60 hours #changing all the", "win1 = Toplevel() #this is going to be the window", "= str(d.year) hour = str(d.hour) minute = str(d.minute) second =", "= employee.get() files = {\"a\": \"\", \"b\": \"\", \"c\": \"\",", "command=lambda: btnClick(9)).grid(row=2,column=2) #!!!!!!!!!!!!!!!!!!!!!!additions!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Addition=Button(f2,padx=16,pady=16,bd=8,text=\"+\",fg=\"black\",bg=\"dim gray\", command=lambda: btnClick(\"+\")).grid(row=2,column=3) btn6=Button(f2,padx=16,pady=16,bd=8, fg=\"black\", font=(\"arial\",20,\"bold\"),text=\"4\",", "os import pickle #from database1 import * from random import", "support in teh main loop #there is no limit in", "bill or billo != None: bills.insert({\"billInput\": bill, \"billOutput\": billo}) win", "#btn10=Button(f2,padx=16,padx=16, fg=\"blue\", font(\"arial\",5,\"bold\"), # text=\"rupen\",bg=\"powder blue\", command=rupen).grid(row=3,column=5) #def function(): #", "textvariable=buy, insertwidth=1, bd=10,bg=\"black\", fg=\"white\", justify=\"left\").grid(row=4,column=0) Bank_Total=Label(f1,font=(\"arial\",16,\"bold\"),text=\"Bank_Deposite: \", bg=\"powder blue\", fg=\"black\",", "#btn2=Button(f2,padx=16,pady=16,bd=8,fg=\"black\",text=\"2\",bg=\"dim gray\", command=lambda: btnClick(2)).grid(row=5,column=3) division=Button(f2,padx=16,pady=16,bd=8,fg=\"black\", text=\"/\", bg=\"dim gray\", command=lambda: btnClick(\"/\")).grid(row=5,column=3)", "time = datetime.now() day = time.day month = time.month hour", "#file.close() #file1 = pickle.load(file) if len(item) == len(file1): break if", "f1 = Frame(root, width = 800 ,height=500,bg=\"goldenrod4\",relief=SUNKEN) f1.pack(side=LEFT) f2 =", "def ano_win1(): win1 = Toplevel() #this is going to be", "= open(\"/root/Desktop/Desktop/python/\") gmail.login(\"username\", \"password\") msg = \"YOUR MESSAGE\" gmail.sendmail(\"your email", "bg=\"black\",fg=\"white\",text=\"email\",command=lambda: __send_email(),relief=GROOVE).pack() #================================next section=========================== fix = Button(root, bd=10,bg=\"black\",fg=\"white\",command=_price_inputs,relief=GROOVE).pack(side=BOTTOM) btnru =", "= Button(root, bd=10,bg=\"black\",fg=\"white\",command=_price_inputs,relief=GROOVE).pack(side=BOTTOM) btnru = Button(root, font=(\"arial 20 bold\"),bd=20, bg=\"black\",fg=\"white\",text=\"click\",command=ano_win1,relief=GROOVE).pack(side=BOTTOM)", "teh win1.title(\"this is the owner window:\") win1.geometry(\"1600x800+0+0\") #win1.configure(bg=\"silver\") my_info =", "\", bg=\"powder blue\", fg=\"black\", anchor=\"e\",relief=GROOVE).grid(row=3, column=1) depositex=Entry(f1,font=(\"arial\",16,\"bold\"),bd=10, textvariable=deposite, bg=\"black\", fg=\"white\",", "all the infos ======================== def _price_inputs(): win2 = Toplevel() win2.title(\"This", "__database(): db = TinyDB(\"/records.json\") #print(monthly) #print(b) #fuck = c.get() a", "the file {}\".format(new_file_name)) #file = open(\"{}\".format(new_file_name), \"w+\") continue else: file_name", "blue\",relief=SUNKEN) f2.pack(side=RIGHT) #f3= Frame(root,width=1600,height=300,fg=\"blue\", bg=\"powder blue\", relief=SUNKEN).pack(side=Bottom) #==========================================================Time======================================= localtime=time.asctime(time.localtime(time.time())) #datetime=Label(Tops,font(\"arial\",20,\"bold\"),text=nowTime,bd=10", "= open(\"{}\".format(new_file_name), \"w+\") continue else: file_name = open(new_file_name, \"w+\") print(\"creating", "\"\"} db.insert({\"total\": a }), db.insert({\"regrds\":\"reference\"}), db.insert({\"day_income\":\"billion\"}), db.insert({\"day_outgoing\":\"billout\"}), db.insert({\"bankdeposit\":\"bankdepo\"}), db.insert({\"full_stock\":\"stock\"}), db.insert({\"shirt_mm\":\"shirt\"}),", "textvariable=rand, bd=10,insertwidth=4,bg=\"red\",fg=\"white\", justify = \"right\").grid(row=0,column=1) #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! lblReference = Label(f1,font=(\"arial\", 16,\"bold\"),", "\"\", \"c\": \"\", \"d\": \"\", \"e\": \"\", \"f\": \"\", \"g\":", "\"w+\") print(\"creating the file {}\".format(file_name)) #file = open(\"{}\".format(file_name), \"w+\") break", "root.configure(bg=\"goldenrod4\") text_Input = StringVar() operator =\"\" yes =\"\" no=\"\" Tops", "sale_mm = sale.get() buy_mm = buy.get() deposite_mm = deposite.get() withdraw_mm", "in one day that will ease all the further operations", "os.path.isfile(i): pass else: file = open(\"{}.txt\".format(i+1), \"w+\") created with name", "str(time.hour) second = str(time.second) year = str(time.year) minute = str(time.minute)", "lblBankwith=Label(f1, font=(\"arial\", 16, \"bold\"),fg=\"black\",bg=\"powder blue\",text=\"Bank_Withdraw\", anchor=\"e\",relief=GROOVE).grid(row=3,column=2) withdrawx=Entry(f1,font=(\"arial\",16, \"bold\"),bd=10, fg=\"white\",bg=\"black\", textvariable=withdraw,", "bg=\"black\", fg=\"white\", justify=\"left\").grid(row=4, column=1) lblBankwith=Label(f1, font=(\"arial\", 16, \"bold\"),fg=\"black\",bg=\"powder blue\",text=\"Bank_Withdraw\", anchor=\"e\",relief=GROOVE).grid(row=3,column=2)", "\"bold\"), textvariable=buy, insertwidth=1, bd=10,bg=\"black\", fg=\"white\", justify=\"left\").grid(row=4,column=0) Bank_Total=Label(f1,font=(\"arial\",16,\"bold\"),text=\"Bank_Deposite: \", bg=\"powder blue\",", "day = str(time.day) month = str(time.month) hour = str(time.hour) second", "for debug \") da += data print(data) da = int(da)" ]
[ "flatten_bbox_preds[pos_inds] if num_pos > 0: pos_bbox_targets = flatten_bbox_targets[pos_inds] pos_points =", "torch.zeros(1, device=push_dist.device)) push_loss = push_loss / N_samples**2 # iou loss", "y_range = torch.arange( 0, h * stride, stride, dtype=dtype, device=device)", "bbox_pred.permute(0, 2, 3, 1).reshape(-1, 4) for bbox_pred in bbox_preds ]", "points according to feature map sizes. Args: featmap_sizes (list[tuple]): Multi-level", "dim=0) concat_points = torch.cat(points, dim=0) # get labels and bbox_targets", "mask for each obj for i in range(len(pos_decoded_target_preds)): if remove[i]", "mask = ((pos_decoded_target_preds == current_bbox).sum(1)==4).nonzero() instance_counter[mask] = obj_id remove[mask] =", "= nn.ModuleList() for i in range(self.stacked_convs): chn = self.in_channels if", "norm_cfg=dict(type='GN', num_groups=32, requires_grad=True)): super(EmbeddingNNmsHeadV2limited, self).__init__() self.num_classes = num_classes self.cls_out_channels =", "embedding_feat = embedding_layer(embedding_feat) embedding_pred = self.embedding_cls(embedding_feat) for reg_layer in self.reg_convs:", "regress_ranges self.loss_cls = build_loss(loss_cls) self.loss_bbox = build_loss(loss_bbox) self.conv_cfg = conv_cfg", "self.embedding_cls(embedding_feat) for reg_layer in self.reg_convs: reg_feat = reg_layer(reg_feat) # scale", "= cls_scores[0].size(0) # flatten cls_scores and bbox_preds flatten_cls_scores = [", "bias=self.norm_cfg is None)) self.reg_convs.append( ConvModule( chn, self.feat_channels, 3, stride=1, padding=1,", "num_classes self.cls_out_channels = num_classes - 1 self.in_channels = in_channels self.feat_channels", "areas = areas[None].expand(num_points, num_gts) areas = areas[None].repeat(num_points, 1) regress_ranges =", "bbox_pred = bbox_pred[topk_inds, :] scores = scores[topk_inds, :] bboxes =", "cls_score.permute(0, 2, 3, 1).reshape(-1, self.cls_out_channels) for cls_score in cls_scores ]", "gt_bboxes, gt_labels, points, regress_ranges): num_points = points.size(0) num_gts = gt_labels.size(0)", "self.reg_convs: reg_feat = reg_layer(reg_feat) # scale the bbox_pred of different", "'bbox_preds')) def loss(self, cls_scores, bbox_preds, embedding_preds, gt_bboxes, gt_labels, img_metas, cfg,", "= nn.Conv2d(self.feat_channels, 4, 3, padding=1) self.embedding_cls = nn.Conv2d(self.feat_channels, 1, 3,", "current_bbox = pos_decoded_target_preds[i] mask = ((pos_decoded_target_preds == current_bbox).sum(1)==4).nonzero() instance_counter[mask] =", "ranges to align with points expanded_regress_ranges = [ points[i].new_tensor(self.regress_ranges[i])[None].expand_as( points[i])", "= img_metas[img_id]['scale_factor'] det_bboxes = self.get_bboxes_single(cls_score_list, bbox_pred_list, mlvl_points, img_shape, scale_factor, cfg,", "nn.ModuleList([Scale(1.0) for _ in self.strides]) # Pull and Push loss", "img_shape = img_metas[img_id]['img_shape'] scale_factor = img_metas[img_id]['scale_factor'] det_bboxes = self.get_bboxes_single(cls_score_list, bbox_pred_list,", "ConvModule, Scale, bias_init_with_prob from IPython import embed INF = 1e8", "result_list.append(det_bboxes) return result_list def get_bboxes_single(self, cls_scores, bbox_preds, mlvl_points, img_shape, scale_factor,", "2] - xs top = ys - gt_bboxes[..., 1] bottom", "one objects for a location, # we choose the one", "repeat points to align with bbox_preds flatten_points = torch.cat( [points.repeat(num_imgs,", "reg_layer in self.reg_convs: reg_feat = reg_layer(reg_feat) # scale the bbox_pred", "Instance level op dist_conf_mask_list = [] # generate instance levels", "normal_init(m.conv, std=0.01) bias_cls = bias_init_with_prob(0.01) normal_init(self.fcos_cls, std=0.01, bias=bias_cls) normal_init(self.fcos_reg, std=0.01)", "[points.repeat(num_imgs, 1) for points in all_level_points]) pos_inds = flatten_labels.nonzero().reshape(-1) num_pos", "# repeat points to align with bbox_preds flatten_points = torch.cat(", "range(num_levels) ] # concat all levels points and regress ranges", "padding=1) self.embedding_cls = nn.Conv2d(self.feat_channels, 1, 3, padding=1) self.scales = nn.ModuleList([Scale(1.0)", "theta = 1 embedding_expand_means = torch.cat(obj_embedding_means_expand_list) pull_embedding = torch.cat(objs_embedding_list) pull_loss", "return cls_score, bbox_pred, embedding_pred @force_fp32(apply_to=('cls_scores', 'bbox_preds')) def loss(self, cls_scores, bbox_preds,", "FCOSHead(11, 7) >>> feats = [torch.rand(1, 7, s, s) for", "points to align with bbox_preds flatten_points = torch.cat( [points.repeat(num_imgs, 1)", "= torch.meshgrid(y_range, x_range) points = torch.stack( (x.reshape(-1), y.reshape(-1)), dim=-1) +", "still more than one objects for a location, # we", "= distance2bbox(pos_points, pos_bbox_targets) pos_iou_scores = bbox_overlaps(pos_decoded_bbox_preds, pos_decoded_target_preds, is_aligned=True).clamp(min=1e-6) max_scores, max_inds", "obj_embedding_preds.sum() / obj_embedding_preds.shape[0] obj_embedding_means_list.append(embedding_mean) obj_embedding_means_expand_list.append(torch.zeros_like(obj_embedding_preds).fill_(embedding_mean)) embed() # pull loss theta", "for reg_layer in self.reg_convs: reg_feat = reg_layer(reg_feat) # scale the", "cfg.nms, cfg.max_per_img) return det_bboxes, det_labels def get_points(self, featmap_sizes, dtype, device):", "a centerness measure is used to supress low-quality predictions. References:", "flatten_bbox_preds = torch.cat(flatten_bbox_preds) flatten_embedding_preds = torch.cat(flatten_embedding_preds) flatten_labels = torch.cat(labels) flatten_bbox_targets", "] bbox_pred_list = [ bbox_preds[i][img_id].detach() for i in range(num_levels) ]", "det_bboxes, det_labels = multiclass_nms( mlvl_bboxes, mlvl_scores, cfg.score_thr, cfg.nms, cfg.max_per_img) return", "flatten_labels = torch.cat(labels) flatten_bbox_targets = torch.cat(bbox_targets) # repeat points to", "flatten_bbox_targets[pos_inds] pos_points = flatten_points[pos_inds] pos_decoded_bbox_preds = distance2bbox(pos_points, pos_bbox_preds) pos_decoded_target_preds =", "nn.Conv2d( self.feat_channels, self.cls_out_channels, 3, padding=1) self.fcos_reg = nn.Conv2d(self.feat_channels, 4, 3,", "self.feat_channels = feat_channels self.stacked_convs = stacked_convs self.embedding_convs_num = embedding_convs_num self.strides", "are different # areas = areas[None].expand(num_points, num_gts) areas = areas[None].repeat(num_points,", "loss self.pull_loss = nn.MSELoss() def init_weights(self): for m in self.cls_convs:", ":].expand( num_points, num_gts, 2) gt_bboxes = gt_bboxes[None].expand(num_points, num_gts, 4) xs,", "self.fcos_target_single, gt_bboxes_list, gt_labels_list, points=concat_points, regress_ranges=concat_regress_ranges) # split to per img,", "= reg_layer(reg_feat) # scale the bbox_pred of different level #", "loss theta = 1 embedding_expand_means = torch.cat(obj_embedding_means_expand_list) pull_embedding = torch.cat(objs_embedding_list)", "scale_factor, cfg, rescale) result_list.append(det_bboxes) return result_list def get_bboxes_single(self, cls_scores, bbox_preds,", "num_points = points.size(0) num_gts = gt_labels.size(0) if num_gts == 0:", "two are different # areas = areas[None].expand(num_points, num_gts) areas =", "enabling FP16 bbox_pred = scale(self.fcos_reg(reg_feat)).float().exp() return cls_score, bbox_pred, embedding_pred @force_fp32(apply_to=('cls_scores',", "for obj_j_embedding_mean in obj_embedding_means_list: for obj_k_embedding_mean in obj_embedding_means_list: if torch.equal(obj_j_embedding_mean,", "loss_cls = self.loss_cls( flatten_cls_scores, flatten_labels, avg_factor=num_pos + num_imgs) # avoid", "torch.cat(bbox_targets) # repeat points to align with bbox_preds flatten_points =", "dist_conf_mask in dist_conf_mask_list: obj_mask_inds = dist_conf_mask.nonzero().reshape(-1) obj_embedding_preds = pos_embedding_preds[obj_mask_inds] objs_embedding_list.append(obj_embedding_preds)", "bbox_targets_list ] # concat per level image concat_lvl_labels = []", "pos_decoded_target_preds, is_aligned=True).clamp(min=1e-6) max_scores, max_inds = flatten_cls_scores.sigmoid().max(1) pos_embedding_preds = flatten_embedding_preds[pos_inds] #", "obj for i in range(len(pos_decoded_target_preds)): if remove[i] == 0: current_bbox", "self.cls_convs: normal_init(m.conv, std=0.01) for m in self.reg_convs: normal_init(m.conv, std=0.01) bias_cls", "each image. \"\"\" mlvl_points = [] for i in range(len(featmap_sizes)):", "loss_bbox=loss_bbox, push_loss=push_loss, pull_loss=pull_loss) @force_fp32(apply_to=('cls_scores', 'bbox_preds')) def get_bboxes(self, cls_scores, bbox_preds, img_metas,", "are predicted at each pixel and a centerness measure is", "map sizes. dtype (torch.dtype): Type of points. device (torch.device): Device", "at each pixel and a centerness measure is used to", "instance_counter.int() obj_ids = torch.bincount(instance_counter).nonzero().int() for obj_id in obj_ids: dist_conf_mask_list.append((instance_counter==obj_id).float()) #", "for bbox_targets in bbox_targets_list])) return concat_lvl_labels, concat_lvl_bbox_targets def fcos_target_single(self, gt_bboxes,", "def fcos_target(self, points, gt_bboxes_list, gt_labels_list): assert len(points) == len(self.regress_ranges) num_levels", "bbox_targets = torch.stack((left, top, right, bottom), -1) # condition1: inside", "in all_level_points]) pos_inds = flatten_labels.nonzero().reshape(-1) num_pos = len(pos_inds) loss_cls =", "according to feature map sizes. Args: featmap_sizes (list[tuple]): Multi-level feature", "0] + 1) * ( gt_bboxes[:, 3] - gt_bboxes[:, 1]", "[bbox_targets[i] for bbox_targets in bbox_targets_list])) return concat_lvl_labels, concat_lvl_bbox_targets def fcos_target_single(self,", "= torch.cat( [points.repeat(num_imgs, 1) for points in all_level_points]) pos_inds =", "cfg, rescale) result_list.append(det_bboxes) return result_list def get_bboxes_single(self, cls_scores, bbox_preds, mlvl_points,", "rescale) result_list.append(det_bboxes) return result_list def get_bboxes_single(self, cls_scores, bbox_preds, mlvl_points, img_shape,", "is 0 pos_bbox_preds = flatten_bbox_preds[pos_inds] if num_pos > 0: pos_bbox_targets", "2, 3, 1).reshape(-1, self.cls_out_channels) for cls_score in cls_scores ] flatten_bbox_preds", "op dist_conf_mask_list = [] # generate instance levels index instance_counter", "img_shape, scale_factor, cfg, rescale) result_list.append(det_bboxes) return result_list def get_bboxes_single(self, cls_scores,", "expand regress ranges to align with points expanded_regress_ranges = [", "points in all_level_points]) pos_inds = flatten_labels.nonzero().reshape(-1) num_pos = len(pos_inds) loss_cls", "= regress_ranges[:, None, :].expand( num_points, num_gts, 2) gt_bboxes = gt_bboxes[None].expand(num_points,", "pos_embedding_preds = flatten_embedding_preds[pos_inds] # Instance level op dist_conf_mask_list = []", "device=pos_points.device) obj_id = 0 # NOTE: get mask for each", "return points def fcos_target(self, points, gt_bboxes_list, gt_labels_list): assert len(points) ==", "- ys bbox_targets = torch.stack((left, top, right, bottom), -1) #", "0, h * stride, stride, dtype=dtype, device=device) y, x =", "cls_scores] mlvl_points = self.get_points(featmap_sizes, bbox_preds[0].dtype, bbox_preds[0].device) result_list = [] for", "flatten_labels.nonzero().reshape(-1) num_pos = len(pos_inds) loss_cls = self.loss_cls( flatten_cls_scores, flatten_labels, avg_factor=num_pos", "self.stacked_convs = stacked_convs self.embedding_convs_num = embedding_convs_num self.strides = strides self.delta", "instance_counter[mask] = obj_id remove[mask] = 1 obj_id += 1 instance_counter", "x for cls_layer in self.cls_convs: cls_feat = cls_layer(cls_feat) cls_score =", "[] for i in range(len(featmap_sizes)): mlvl_points.append( self.get_points_single(featmap_sizes[i], self.strides[i], dtype, device))", "embedding_preds ] flatten_cls_scores = torch.cat(flatten_cls_scores) flatten_bbox_preds = torch.cat(flatten_bbox_preds) flatten_embedding_preds =", "torch.cat(mlvl_bboxes) if rescale: mlvl_bboxes /= mlvl_bboxes.new_tensor(scale_factor) mlvl_scores = torch.cat(mlvl_scores) padding", "ys[:, None].expand(num_points, num_gts) left = xs - gt_bboxes[..., 0] right", "current_bbox).sum(1)==4).nonzero() instance_counter[mask] = obj_id remove[mask] = 1 obj_id += 1", "xs = xs[:, None].expand(num_points, num_gts) ys = ys[:, None].expand(num_points, num_gts)", "16, 32, 64), delta=2.0, regress_ranges=((-1, 64), (64, 128), (128, 256),", "= flatten_labels.nonzero().reshape(-1) num_pos = len(pos_inds) loss_cls = self.loss_cls( flatten_cls_scores, flatten_labels,", "= bbox_targets.max(-1)[0] inside_regress_range = ( max_regress_distance >= regress_ranges[..., 0]) &", "= [labels.split(num_points, 0) for labels in labels_list] bbox_targets_list = [", "in range(num_levels) ] # concat all levels points and regress", "get_points(self, featmap_sizes, dtype, device): \"\"\"Get points according to feature map", "bbox_targets in bbox_targets_list])) return concat_lvl_labels, concat_lvl_bbox_targets def fcos_target_single(self, gt_bboxes, gt_labels,", "reg_layer(reg_feat) # scale the bbox_pred of different level # float", "self.cls_out_channels = num_classes - 1 self.in_channels = in_channels self.feat_channels =", "0] right = gt_bboxes[..., 2] - xs top = ys", "img, per level num_points = [center.size(0) for center in points]", "the bbox_pred of different level # float to avoid overflow", "in self.embedding_convs: embedding_feat = embedding_layer(embedding_feat) embedding_pred = self.embedding_cls(embedding_feat) for reg_layer", "in self.reg_convs: reg_feat = reg_layer(reg_feat) # scale the bbox_pred of", "flatten_cls_scores = [ cls_score.permute(0, 2, 3, 1).reshape(-1, self.cls_out_channels) for cls_score", "points[:, 1] xs = xs[:, None].expand(num_points, num_gts) ys = ys[:,", "# push loss N_samples = len(dist_conf_mask_list) push_loss = 0 for", "0 pos_bbox_preds = flatten_bbox_preds[pos_inds] if num_pos > 0: pos_bbox_targets =", "pos_decoded_bbox_preds, pos_decoded_target_preds) else: loss_bbox = pos_bbox_preds.sum() push_loss = pos_bbox_preds.sum() pull_loss", "if torch.equal(obj_j_embedding_mean, obj_k_embedding_mean): continue else: push_dist = self.delta - torch.abs(obj_k_embedding_mean", "bbox_preds, mlvl_points): assert cls_score.size()[-2:] == bbox_pred.size()[-2:] scores = cls_score.permute(1, 2,", "remove = torch.zeros(num_pos, device=pos_points.device) obj_id = 0 # NOTE: get", "feats): return multi_apply(self.forward_single, feats, self.scales) def forward_single(self, x, scale): cls_feat", "loss_weight=1.0), loss_bbox=dict(type='IoULoss', loss_weight=1.0), conv_cfg=None, norm_cfg=dict(type='GN', num_groups=32, requires_grad=True)): super(EmbeddingNNmsHeadV2limited, self).__init__() self.num_classes", "cls_layer in self.cls_convs: cls_feat = cls_layer(cls_feat) cls_score = self.fcos_cls(cls_feat) for", "bbox_targets.min(-1)[0] > 0 # condition2: limit the regression range for", "3, 1).reshape(-1, 4) for bbox_pred in bbox_preds ] flatten_embedding_preds =", "pos_decoded_bbox_preds = distance2bbox(pos_points, pos_bbox_preds) pos_decoded_target_preds = distance2bbox(pos_points, pos_bbox_targets) pos_iou_scores =", "self.loss_bbox = build_loss(loss_bbox) self.conv_cfg = conv_cfg self.norm_cfg = norm_cfg self.fp16_enabled", "self.fcos_cls = nn.Conv2d( self.feat_channels, self.cls_out_channels, 3, padding=1) self.fcos_reg = nn.Conv2d(self.feat_channels,", "gt_labels_list): assert len(points) == len(self.regress_ranges) num_levels = len(points) # expand", "= len(cls_scores) featmap_sizes = [featmap.size()[-2:] for featmap in cls_scores] mlvl_points", "3, 1).reshape(-1, self.cls_out_channels) for cls_score in cls_scores ] flatten_bbox_preds =", "- gt_bboxes[..., 1] bottom = gt_bboxes[..., 3] - ys bbox_targets", "one with minimal area areas[inside_gt_bbox_mask == 0] = INF areas[inside_regress_range", "embedding_feat in embedding_preds ] flatten_cls_scores = torch.cat(flatten_cls_scores) flatten_bbox_preds = torch.cat(flatten_bbox_preds)", "delta=2.0, regress_ranges=((-1, 64), (64, 128), (128, 256), (256, 512), (512,", "= embedding_layer(embedding_feat) embedding_pred = self.embedding_cls(embedding_feat) for reg_layer in self.reg_convs: reg_feat", "import embed INF = 1e8 @HEADS.register_module class EmbeddingNNmsHeadV2limited(nn.Module): \"\"\" Fully", "in range(num_levels) ] bbox_pred_list = [ bbox_preds[i][img_id].detach() for i in", "the regression range for each location max_regress_distance = bbox_targets.max(-1)[0] inside_regress_range", "concat_lvl_bbox_targets.append( torch.cat( [bbox_targets[i] for bbox_targets in bbox_targets_list])) return concat_lvl_labels, concat_lvl_bbox_targets", "_ = scores.max(dim=1) _, topk_inds = max_scores.topk(nms_pre) points = points[topk_inds,", "mean value embedding_mean = obj_embedding_preds.sum() / obj_embedding_preds.shape[0] obj_embedding_means_list.append(embedding_mean) obj_embedding_means_expand_list.append(torch.zeros_like(obj_embedding_preds).fill_(embedding_mean)) embed()", "= False self._init_layers() def _init_layers(self): self.cls_convs = nn.ModuleList() self.reg_convs =", "normal_init(self.embedding_cls, std=0.01) def forward(self, feats): return multi_apply(self.forward_single, feats, self.scales) def", "why these two are different # areas = areas[None].expand(num_points, num_gts)", "pos_embedding_preds[obj_mask_inds] objs_embedding_list.append(obj_embedding_preds) # mean value embedding_mean = obj_embedding_preds.sum() / obj_embedding_preds.shape[0]", "0).reshape(-1, 4) nms_pre = cfg.get('nms_pre', -1) if nms_pre > 0", "self.strides]) # Pull and Push loss self.pull_loss = nn.MSELoss() def", "does not use anchor boxes. Instead bounding boxes are predicted", "= scores[topk_inds, :] bboxes = distance2bbox(points, bbox_pred, max_shape=img_shape) mlvl_bboxes.append(bboxes) mlvl_scores.append(scores)", "= x reg_feat = x embedding_feat = x for cls_layer", "3, padding=1) self.fcos_reg = nn.Conv2d(self.feat_channels, 4, 3, padding=1) self.embedding_cls =", "mlvl_points def get_points_single(self, featmap_size, stride, dtype, device): h, w =", "gt_bboxes[..., 1] bottom = gt_bboxes[..., 3] - ys bbox_targets =", "mlvl_bboxes, mlvl_scores, cfg.score_thr, cfg.nms, cfg.max_per_img) return det_bboxes, det_labels def get_points(self,", "for dist_conf_mask in dist_conf_mask_list: obj_mask_inds = dist_conf_mask.nonzero().reshape(-1) obj_embedding_preds = pos_embedding_preds[obj_mask_inds]", "instance levels index instance_counter = torch.zeros(num_pos, device=pos_points.device) remove = torch.zeros(num_pos,", "img_metas[img_id]['scale_factor'] det_bboxes = self.get_bboxes_single(cls_score_list, bbox_pred_list, mlvl_points, img_shape, scale_factor, cfg, rescale)", "[] concat_lvl_bbox_targets = [] for i in range(num_levels): concat_lvl_labels.append( torch.cat([labels[i]", "obj objs_embedding_list = [] obj_embedding_means_list = [] obj_embedding_means_expand_list = []", "s, s) for s in [4, 8, 16, 32, 64]]", "points.size(0) num_gts = gt_labels.size(0) if num_gts == 0: return gt_labels.new_zeros(num_points),", "torch.meshgrid(y_range, x_range) points = torch.stack( (x.reshape(-1), y.reshape(-1)), dim=-1) + stride", "areas[None].expand(num_points, num_gts) areas = areas[None].repeat(num_points, 1) regress_ranges = regress_ranges[:, None,", "embedding_feat = x for cls_layer in self.cls_convs: cls_feat = cls_layer(cls_feat)", "all levels points and regress ranges concat_regress_ranges = torch.cat(expanded_regress_ranges, dim=0)", "import ConvModule, Scale, bias_init_with_prob from IPython import embed INF =", "when enabling FP16 bbox_pred = scale(self.fcos_reg(reg_feat)).float().exp() return cls_score, bbox_pred, embedding_pred", "objs_embedding_list = [] obj_embedding_means_list = [] obj_embedding_means_expand_list = [] for", "rescale=None): assert len(cls_scores) == len(bbox_preds) num_levels = len(cls_scores) featmap_sizes =", "= multiclass_nms( mlvl_bboxes, mlvl_scores, cfg.score_thr, cfg.nms, cfg.max_per_img) return det_bboxes, det_labels", "cls_layer(cls_feat) cls_score = self.fcos_cls(cls_feat) for embedding_layer in self.embedding_convs: embedding_feat =", "det_labels = multiclass_nms( mlvl_bboxes, mlvl_scores, cfg.score_thr, cfg.nms, cfg.max_per_img) return det_bboxes,", "img_metas, cfg, rescale=None): assert len(cls_scores) == len(bbox_preds) num_levels = len(cls_scores)", "+ stride // 2 return points def fcos_target(self, points, gt_bboxes_list,", "1e8 @HEADS.register_module class EmbeddingNNmsHeadV2limited(nn.Module): \"\"\" Fully Convolutional One-Stage Object Detection", "= nn.Conv2d(self.feat_channels, 1, 3, padding=1) self.scales = nn.ModuleList([Scale(1.0) for _", "norm_cfg=self.norm_cfg, bias=self.norm_cfg is None)) self.embedding_convs.append( ConvModule( chn, self.feat_channels, 3, stride=1,", "objects for a location, # we choose the one with", "self.forward(feats) >>> assert len(cls_score) == len(self.scales) \"\"\" def __init__(self, num_classes,", "[] # generate instance levels index instance_counter = torch.zeros(num_pos, device=pos_points.device)", "avg_factor=num_pos + num_imgs) # avoid num_pos is 0 pos_bbox_preds =", "== 0] = INF areas[inside_regress_range == 0] = INF min_area,", "- obj_j_embedding_mean) push_loss += torch.max(push_dist, torch.zeros(1, device=push_dist.device)) push_loss = push_loss", "= conv_cfg self.norm_cfg = norm_cfg self.fp16_enabled = False self._init_layers() def", "= nn.Conv2d( self.feat_channels, self.cls_out_channels, 3, padding=1) self.fcos_reg = nn.Conv2d(self.feat_channels, 4,", "* self.pull_loss(pull_embedding, embedding_expand_means) # push loss N_samples = len(dist_conf_mask_list) push_loss", "stride=1, padding=1, conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg, bias=self.norm_cfg is None)) self.fcos_cls = nn.Conv2d(", "= ( max_regress_distance >= regress_ranges[..., 0]) & ( max_regress_distance <=", "avoid num_pos is 0 pos_bbox_preds = flatten_bbox_preds[pos_inds] if num_pos >", "def loss(self, cls_scores, bbox_preds, embedding_preds, gt_bboxes, gt_labels, img_metas, cfg, gt_bboxes_ignore=None):", ">>> cls_score, bbox_pred, centerness = self.forward(feats) >>> assert len(cls_score) ==", "self.pull_loss(pull_embedding, embedding_expand_means) # push loss N_samples = len(dist_conf_mask_list) push_loss =", "concat_lvl_bbox_targets def fcos_target_single(self, gt_bboxes, gt_labels, points, regress_ranges): num_points = points.size(0)", "bottom), -1) # condition1: inside a gt bbox inside_gt_bbox_mask =", "regress ranges to align with points expanded_regress_ranges = [ points[i].new_tensor(self.regress_ranges[i])[None].expand_as(", "predicted at each pixel and a centerness measure is used", "sizes. Args: featmap_sizes (list[tuple]): Multi-level feature map sizes. dtype (torch.dtype):", "None].expand(num_points, num_gts) ys = ys[:, None].expand(num_points, num_gts) left = xs", "128), (128, 256), (256, 512), (512, INF)), loss_cls=dict( type='FocalLoss', use_sigmoid=True,", "device=push_dist.device)) push_loss = push_loss / N_samples**2 # iou loss loss_bbox", "reg_feat = reg_layer(reg_feat) # scale the bbox_pred of different level", "to supress low-quality predictions. References: .. [1] https://arxiv.org/abs/1904.01355 Example: >>>", "in obj_embedding_means_list: for obj_k_embedding_mean in obj_embedding_means_list: if torch.equal(obj_j_embedding_mean, obj_k_embedding_mean): continue", "gt_labels.size(0) if num_gts == 0: return gt_labels.new_zeros(num_points), \\ gt_bboxes.new_zeros((num_points, 4))", "self.norm_cfg = norm_cfg self.fp16_enabled = False self._init_layers() def _init_layers(self): self.cls_convs", "padding=1) self.fcos_reg = nn.Conv2d(self.feat_channels, 4, 3, padding=1) self.embedding_cls = nn.Conv2d(self.feat_channels,", "= [ bbox_pred.permute(0, 2, 3, 1).reshape(-1, 4) for bbox_pred in", "self.get_points(featmap_sizes, bbox_preds[0].dtype, bbox_preds[0].device) result_list = [] for img_id in range(len(img_metas)):", "flatten_bbox_targets = torch.cat(bbox_targets) # repeat points to align with bbox_preds", "self.embedding_cls = nn.Conv2d(self.feat_channels, 1, 3, padding=1) self.scales = nn.ModuleList([Scale(1.0) for", "Device of points. Returns: tuple: points of each image. \"\"\"", "each location max_regress_distance = bbox_targets.max(-1)[0] inside_regress_range = ( max_regress_distance >=", "self.get_points(featmap_sizes, bbox_preds[0].dtype, bbox_preds[0].device) labels, bbox_targets = self.fcos_target(all_level_points, gt_bboxes, gt_labels) num_imgs", "from ..registry import HEADS from ..utils import ConvModule, Scale, bias_init_with_prob", "+= torch.max(push_dist, torch.zeros(1, device=push_dist.device)) push_loss = push_loss / N_samples**2 #", "= torch.arange( 0, h * stride, stride, dtype=dtype, device=device) y,", "EmbeddingNNmsHeadV2limited(nn.Module): \"\"\" Fully Convolutional One-Stage Object Detection head from [1]_.", "regress ranges concat_regress_ranges = torch.cat(expanded_regress_ranges, dim=0) concat_points = torch.cat(points, dim=0)", "[1]_. The FCOS head does not use anchor boxes. Instead", "= torch.cat(mlvl_scores) padding = mlvl_scores.new_zeros(mlvl_scores.shape[0], 1) mlvl_scores = torch.cat([padding, mlvl_scores],", "len(dist_conf_mask_list) push_loss = 0 for obj_j_embedding_mean in obj_embedding_means_list: for obj_k_embedding_mean", "= xs - gt_bboxes[..., 0] right = gt_bboxes[..., 2] -", "inside_regress_range = ( max_regress_distance >= regress_ranges[..., 0]) & ( max_regress_distance", "concat all levels points and regress ranges concat_regress_ranges = torch.cat(expanded_regress_ranges,", "with points expanded_regress_ranges = [ points[i].new_tensor(self.regress_ranges[i])[None].expand_as( points[i]) for i in", "else self.feat_channels self.cls_convs.append( ConvModule( chn, self.feat_channels, 3, stride=1, padding=1, conv_cfg=self.conv_cfg,", "= [] for dist_conf_mask in dist_conf_mask_list: obj_mask_inds = dist_conf_mask.nonzero().reshape(-1) obj_embedding_preds", "= gt_bboxes[..., 2] - xs top = ys - gt_bboxes[...,", "Convolutional One-Stage Object Detection head from [1]_. The FCOS head", "chn, self.feat_channels, 3, stride=1, padding=1, conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg, bias=self.norm_cfg is None))", "__init__(self, num_classes, in_channels, feat_channels=256, stacked_convs=4, embedding_convs_num=2, strides=(4, 8, 16, 32,", "mlvl_points): assert cls_score.size()[-2:] == bbox_pred.size()[-2:] scores = cls_score.permute(1, 2, 0).reshape(", "and Push loss self.pull_loss = nn.MSELoss() def init_weights(self): for m", "img_shape, scale_factor, cfg, rescale=False): assert len(cls_scores) == len(bbox_preds) == len(mlvl_points)", "dist_conf_mask_list.append((instance_counter==obj_id).float()) # Opt for each obj objs_embedding_list = [] obj_embedding_means_list", "in bbox_targets_list ] # concat per level image concat_lvl_labels =", "push_dist = self.delta - torch.abs(obj_k_embedding_mean - obj_j_embedding_mean) push_loss += torch.max(push_dist,", "torch.cat(flatten_cls_scores) flatten_bbox_preds = torch.cat(flatten_bbox_preds) flatten_embedding_preds = torch.cat(flatten_embedding_preds) flatten_labels = torch.cat(labels)", "else: loss_bbox = pos_bbox_preds.sum() push_loss = pos_bbox_preds.sum() pull_loss = pos_bbox_preds.sum()", "stride, dtype, device): h, w = featmap_size x_range = torch.arange(", "bbox_pred[topk_inds, :] scores = scores[topk_inds, :] bboxes = distance2bbox(points, bbox_pred,", "= flatten_cls_scores.sigmoid().max(1) pos_embedding_preds = flatten_embedding_preds[pos_inds] # Instance level op dist_conf_mask_list", "( max_regress_distance >= regress_ranges[..., 0]) & ( max_regress_distance <= regress_ranges[...,", "= self.fcos_target(all_level_points, gt_bboxes, gt_labels) num_imgs = cls_scores[0].size(0) # flatten cls_scores", "3, 1).reshape(-1, 1) for embedding_feat in embedding_preds ] flatten_cls_scores =", "different # areas = areas[None].expand(num_points, num_gts) areas = areas[None].repeat(num_points, 1)", "1) regress_ranges = regress_ranges[:, None, :].expand( num_points, num_gts, 2) gt_bboxes", "det_bboxes = self.get_bboxes_single(cls_score_list, bbox_pred_list, mlvl_points, img_shape, scale_factor, cfg, rescale) result_list.append(det_bboxes)", "= points[topk_inds, :] bbox_pred = bbox_pred[topk_inds, :] scores = scores[topk_inds,", "assert len(points) == len(self.regress_ranges) num_levels = len(points) # expand regress", "self.get_bboxes_single(cls_score_list, bbox_pred_list, mlvl_points, img_shape, scale_factor, cfg, rescale) result_list.append(det_bboxes) return result_list", "if there are still more than one objects for a", "pos_bbox_preds = flatten_bbox_preds[pos_inds] if num_pos > 0: pos_bbox_targets = flatten_bbox_targets[pos_inds]", "stride, dtype=dtype, device=device) y_range = torch.arange( 0, h * stride,", "self.delta = delta self.regress_ranges = regress_ranges self.loss_cls = build_loss(loss_cls) self.loss_bbox", "\\ gt_bboxes.new_zeros((num_points, 4)) areas = (gt_bboxes[:, 2] - gt_bboxes[:, 0]", "- gt_bboxes[:, 1] + 1) # TODO: figure out why", "generate instance levels index instance_counter = torch.zeros(num_pos, device=pos_points.device) remove =", "= [] concat_lvl_bbox_targets = [] for i in range(num_levels): concat_lvl_labels.append(", "16, 32, 64]] >>> cls_score, bbox_pred, centerness = self.forward(feats) >>>", "1).reshape(-1, 1) for embedding_feat in embedding_preds ] flatten_cls_scores = torch.cat(flatten_cls_scores)", "num_groups=32, requires_grad=True)): super(EmbeddingNNmsHeadV2limited, self).__init__() self.num_classes = num_classes self.cls_out_channels = num_classes", "bias_init_with_prob(0.01) normal_init(self.fcos_cls, std=0.01, bias=bias_cls) normal_init(self.fcos_reg, std=0.01) normal_init(self.embedding_cls, std=0.01) def forward(self,", "std=0.01) bias_cls = bias_init_with_prob(0.01) normal_init(self.fcos_cls, std=0.01, bias=bias_cls) normal_init(self.fcos_reg, std=0.01) normal_init(self.embedding_cls,", "mlvl_points, img_shape, scale_factor, cfg, rescale=False): assert len(cls_scores) == len(bbox_preds) ==", "num_gts, 2) gt_bboxes = gt_bboxes[None].expand(num_points, num_gts, 4) xs, ys =", "img_id in range(len(img_metas)): cls_score_list = [ cls_scores[i][img_id].detach() for i in", "= torch.cat([padding, mlvl_scores], dim=1) det_bboxes, det_labels = multiclass_nms( mlvl_bboxes, mlvl_scores,", "dict( loss_cls=loss_cls, loss_bbox=loss_bbox, push_loss=push_loss, pull_loss=pull_loss) @force_fp32(apply_to=('cls_scores', 'bbox_preds')) def get_bboxes(self, cls_scores,", "== len(self.regress_ranges) num_levels = len(points) # expand regress ranges to", "use anchor boxes. Instead bounding boxes are predicted at each", "torch.cat(mlvl_scores) padding = mlvl_scores.new_zeros(mlvl_scores.shape[0], 1) mlvl_scores = torch.cat([padding, mlvl_scores], dim=1)", "self.feat_channels, 3, stride=1, padding=1, conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg, bias=self.norm_cfg is None)) self.embedding_convs.append(", "One-Stage Object Detection head from [1]_. The FCOS head does", "points. device (torch.device): Device of points. Returns: tuple: points of", "32, 64), delta=2.0, regress_ranges=((-1, 64), (64, 128), (128, 256), (256,", "1]) # if there are still more than one objects", "i in range(self.stacked_convs): chn = self.in_channels if i == 0", "area areas[inside_gt_bbox_mask == 0] = INF areas[inside_regress_range == 0] =", "inside a gt bbox inside_gt_bbox_mask = bbox_targets.min(-1)[0] > 0 #", "num_imgs) # avoid num_pos is 0 pos_bbox_preds = flatten_bbox_preds[pos_inds] if", "= flatten_bbox_preds[pos_inds] if num_pos > 0: pos_bbox_targets = flatten_bbox_targets[pos_inds] pos_points", "gt bbox inside_gt_bbox_mask = bbox_targets.min(-1)[0] > 0 # condition2: limit", "torch.stack( (x.reshape(-1), y.reshape(-1)), dim=-1) + stride // 2 return points", "bbox_pred, points in zip( cls_scores, bbox_preds, mlvl_points): assert cls_score.size()[-2:] ==", "to feature map sizes. Args: featmap_sizes (list[tuple]): Multi-level feature map", "featmap in cls_scores] mlvl_points = self.get_points(featmap_sizes, bbox_preds[0].dtype, bbox_preds[0].device) result_list =", "len(cls_score) == len(self.scales) \"\"\" def __init__(self, num_classes, in_channels, feat_channels=256, stacked_convs=4,", "max_regress_distance = bbox_targets.max(-1)[0] inside_regress_range = ( max_regress_distance >= regress_ranges[..., 0])", "[4, 8, 16, 32, 64]] >>> cls_score, bbox_pred, centerness =", "embedding_feat.permute(0, 2, 3, 1).reshape(-1, 1) for embedding_feat in embedding_preds ]", "gt_labels_list, points=concat_points, regress_ranges=concat_regress_ranges) # split to per img, per level", "pull_embedding = torch.cat(objs_embedding_list) pull_loss = theta * self.pull_loss(pull_embedding, embedding_expand_means) #", "is None)) self.embedding_convs.append( ConvModule( chn, self.feat_channels, 3, stride=1, padding=1, conv_cfg=self.conv_cfg,", "= [] for i in range(num_levels): concat_lvl_labels.append( torch.cat([labels[i] for labels", "def init_weights(self): for m in self.cls_convs: normal_init(m.conv, std=0.01) for m", "use_sigmoid=True, gamma=2.0, alpha=0.25, loss_weight=1.0), loss_bbox=dict(type='IoULoss', loss_weight=1.0), conv_cfg=None, norm_cfg=dict(type='GN', num_groups=32, requires_grad=True)):", "for each obj for i in range(len(pos_decoded_target_preds)): if remove[i] ==", "in_channels, feat_channels=256, stacked_convs=4, embedding_convs_num=2, strides=(4, 8, 16, 32, 64), delta=2.0,", "mlvl_bboxes = torch.cat(mlvl_bboxes) if rescale: mlvl_bboxes /= mlvl_bboxes.new_tensor(scale_factor) mlvl_scores =", "256), (256, 512), (512, INF)), loss_cls=dict( type='FocalLoss', use_sigmoid=True, gamma=2.0, alpha=0.25,", "= [featmap.size()[-2:] for featmap in cls_scores] all_level_points = self.get_points(featmap_sizes, bbox_preds[0].dtype,", "len(cls_scores) featmap_sizes = [featmap.size()[-2:] for featmap in cls_scores] mlvl_points =", "alpha=0.25, loss_weight=1.0), loss_bbox=dict(type='IoULoss', loss_weight=1.0), conv_cfg=None, norm_cfg=dict(type='GN', num_groups=32, requires_grad=True)): super(EmbeddingNNmsHeadV2limited, self).__init__()", "feat_channels self.stacked_convs = stacked_convs self.embedding_convs_num = embedding_convs_num self.strides = strides", "# NOTE: get mask for each obj for i in", "Returns: tuple: points of each image. \"\"\" mlvl_points = []", "4)) areas = (gt_bboxes[:, 2] - gt_bboxes[:, 0] + 1)", "= feat_channels self.stacked_convs = stacked_convs self.embedding_convs_num = embedding_convs_num self.strides =", "4) for bbox_pred in bbox_preds ] flatten_embedding_preds = [ embedding_feat.permute(0,", "mlvl_points = [] for i in range(len(featmap_sizes)): mlvl_points.append( self.get_points_single(featmap_sizes[i], self.strides[i],", "def fcos_target_single(self, gt_bboxes, gt_labels, points, regress_ranges): num_points = points.size(0) num_gts", "= 0 # NOTE: get mask for each obj for", "for i in range(self.stacked_convs): chn = self.in_channels if i ==", "# pull loss theta = 1 embedding_expand_means = torch.cat(obj_embedding_means_expand_list) pull_embedding", "multi_apply, multiclass_nms, bbox_overlaps from ..builder import build_loss from ..registry import", "def forward(self, feats): return multi_apply(self.forward_single, feats, self.scales) def forward_single(self, x,", "get_bboxes_single(self, cls_scores, bbox_preds, mlvl_points, img_shape, scale_factor, cfg, rescale=False): assert len(cls_scores)", "build_loss from ..registry import HEADS from ..utils import ConvModule, Scale,", "FCOS head does not use anchor boxes. Instead bounding boxes", "= scale(self.fcos_reg(reg_feat)).float().exp() return cls_score, bbox_pred, embedding_pred @force_fp32(apply_to=('cls_scores', 'bbox_preds')) def loss(self,", "obj_embedding_preds.shape[0] obj_embedding_means_list.append(embedding_mean) obj_embedding_means_expand_list.append(torch.zeros_like(obj_embedding_preds).fill_(embedding_mean)) embed() # pull loss theta = 1", "obj_embedding_preds = pos_embedding_preds[obj_mask_inds] objs_embedding_list.append(obj_embedding_preds) # mean value embedding_mean = obj_embedding_preds.sum()", "x, scale): cls_feat = x reg_feat = x embedding_feat =", "stacked_convs self.embedding_convs_num = embedding_convs_num self.strides = strides self.delta = delta", "bbox_pred, embedding_pred @force_fp32(apply_to=('cls_scores', 'bbox_preds')) def loss(self, cls_scores, bbox_preds, embedding_preds, gt_bboxes,", "len(points) # expand regress ranges to align with points expanded_regress_ranges", "gt_bboxes_list, gt_labels_list): assert len(points) == len(self.regress_ranges) num_levels = len(points) #", "# Opt for each obj objs_embedding_list = [] obj_embedding_means_list =", "INF areas[inside_regress_range == 0] = INF min_area, min_area_inds = areas.min(dim=1)", "bbox_targets_list])) return concat_lvl_labels, concat_lvl_bbox_targets def fcos_target_single(self, gt_bboxes, gt_labels, points, regress_ranges):", "distance2bbox(pos_points, pos_bbox_targets) pos_iou_scores = bbox_overlaps(pos_decoded_bbox_preds, pos_decoded_target_preds, is_aligned=True).clamp(min=1e-6) max_scores, max_inds =", "cls_scores, bbox_preds, img_metas, cfg, rescale=None): assert len(cls_scores) == len(bbox_preds) num_levels", "range(len(featmap_sizes)): mlvl_points.append( self.get_points_single(featmap_sizes[i], self.strides[i], dtype, device)) return mlvl_points def get_points_single(self,", "for img_id in range(len(img_metas)): cls_score_list = [ cls_scores[i][img_id].detach() for i", "stride, dtype=dtype, device=device) y, x = torch.meshgrid(y_range, x_range) points =", "gt_bboxes = gt_bboxes[None].expand(num_points, num_gts, 4) xs, ys = points[:, 0],", "bbox_pred_list = [ bbox_preds[i][img_id].detach() for i in range(num_levels) ] img_shape", "= obj_embedding_preds.sum() / obj_embedding_preds.shape[0] obj_embedding_means_list.append(embedding_mean) obj_embedding_means_expand_list.append(torch.zeros_like(obj_embedding_preds).fill_(embedding_mean)) embed() # pull loss", "for m in self.cls_convs: normal_init(m.conv, std=0.01) for m in self.reg_convs:", "flatten_cls_scores, flatten_labels, avg_factor=num_pos + num_imgs) # avoid num_pos is 0", "image. \"\"\" mlvl_points = [] for i in range(len(featmap_sizes)): mlvl_points.append(", "labels and bbox_targets of each image labels_list, bbox_targets_list = multi_apply(", "2, 3, 1).reshape(-1, 4) for bbox_pred in bbox_preds ] flatten_embedding_preds", "stride=1, padding=1, conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg, bias=self.norm_cfg is None)) self.embedding_convs.append( ConvModule( chn,", "std=0.01) for m in self.reg_convs: normal_init(m.conv, std=0.01) bias_cls = bias_init_with_prob(0.01)", "sizes. dtype (torch.dtype): Type of points. device (torch.device): Device of", "points expanded_regress_ranges = [ points[i].new_tensor(self.regress_ranges[i])[None].expand_as( points[i]) for i in range(num_levels)", "concat_lvl_labels, concat_lvl_bbox_targets def fcos_target_single(self, gt_bboxes, gt_labels, points, regress_ranges): num_points =", "in bbox_targets_list])) return concat_lvl_labels, concat_lvl_bbox_targets def fcos_target_single(self, gt_bboxes, gt_labels, points,", "norm_cfg=self.norm_cfg, bias=self.norm_cfg is None)) self.reg_convs.append( ConvModule( chn, self.feat_channels, 3, stride=1,", "dist_conf_mask.nonzero().reshape(-1) obj_embedding_preds = pos_embedding_preds[obj_mask_inds] objs_embedding_list.append(obj_embedding_preds) # mean value embedding_mean =", "= gt_bboxes[None].expand(num_points, num_gts, 4) xs, ys = points[:, 0], points[:,", "len(bbox_preds) == len(mlvl_points) mlvl_bboxes = [] mlvl_scores = [] for", "== len(bbox_preds) == len(mlvl_points) mlvl_bboxes = [] mlvl_scores = []", "pull loss theta = 1 embedding_expand_means = torch.cat(obj_embedding_means_expand_list) pull_embedding =", "= torch.zeros(num_pos, device=pos_points.device) remove = torch.zeros(num_pos, device=pos_points.device) obj_id = 0", "normal_init(self.fcos_cls, std=0.01, bias=bias_cls) normal_init(self.fcos_reg, std=0.01) normal_init(self.embedding_cls, std=0.01) def forward(self, feats):", "= torch.cat(flatten_bbox_preds) flatten_embedding_preds = torch.cat(flatten_embedding_preds) flatten_labels = torch.cat(labels) flatten_bbox_targets =", "for i in range(len(pos_decoded_target_preds)): if remove[i] == 0: current_bbox =", "gt_bboxes, gt_labels, img_metas, cfg, gt_bboxes_ignore=None): assert len(cls_scores) == len(bbox_preds) ==", "boxes. Instead bounding boxes are predicted at each pixel and", "= instance_counter.int() obj_ids = torch.bincount(instance_counter).nonzero().int() for obj_id in obj_ids: dist_conf_mask_list.append((instance_counter==obj_id).float())", "if num_gts == 0: return gt_labels.new_zeros(num_points), \\ gt_bboxes.new_zeros((num_points, 4)) areas", "nn.Conv2d(self.feat_channels, 4, 3, padding=1) self.embedding_cls = nn.Conv2d(self.feat_channels, 1, 3, padding=1)", "split to per img, per level num_points = [center.size(0) for", "# condition2: limit the regression range for each location max_regress_distance", "levels points and regress ranges concat_regress_ranges = torch.cat(expanded_regress_ranges, dim=0) concat_points", "get mask for each obj for i in range(len(pos_decoded_target_preds)): if", "a gt bbox inside_gt_bbox_mask = bbox_targets.min(-1)[0] > 0 # condition2:", "bbox_targets.max(-1)[0] inside_regress_range = ( max_regress_distance >= regress_ranges[..., 0]) & (", "distance2bbox, force_fp32, multi_apply, multiclass_nms, bbox_overlaps from ..builder import build_loss from", "bbox_preds[0].dtype, bbox_preds[0].device) result_list = [] for img_id in range(len(img_metas)): cls_score_list", "# TODO: figure out why these two are different #", "build_loss(loss_cls) self.loss_bbox = build_loss(loss_bbox) self.conv_cfg = conv_cfg self.norm_cfg = norm_cfg", "from [1]_. The FCOS head does not use anchor boxes.", "num_classes - 1 self.in_channels = in_channels self.feat_channels = feat_channels self.stacked_convs", "regress_ranges = regress_ranges[:, None, :].expand( num_points, num_gts, 2) gt_bboxes =", "points. Returns: tuple: points of each image. \"\"\" mlvl_points =", "ConvModule( chn, self.feat_channels, 3, stride=1, padding=1, conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg, bias=self.norm_cfg is", "torch.cat([labels[i] for labels in labels_list])) concat_lvl_bbox_targets.append( torch.cat( [bbox_targets[i] for bbox_targets", "device): \"\"\"Get points according to feature map sizes. Args: featmap_sizes", "for cls_score, bbox_pred, points in zip( cls_scores, bbox_preds, mlvl_points): assert", "self.feat_channels, 3, stride=1, padding=1, conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg, bias=self.norm_cfg is None)) self.reg_convs.append(", "mlvl_scores = torch.cat(mlvl_scores) padding = mlvl_scores.new_zeros(mlvl_scores.shape[0], 1) mlvl_scores = torch.cat([padding,", "for _ in self.strides]) # Pull and Push loss self.pull_loss", "loss loss_bbox = self.loss_bbox( pos_decoded_bbox_preds, pos_decoded_target_preds) else: loss_bbox = pos_bbox_preds.sum()", "embedding_pred = self.embedding_cls(embedding_feat) for reg_layer in self.reg_convs: reg_feat = reg_layer(reg_feat)", "self.cls_out_channels) for cls_score in cls_scores ] flatten_bbox_preds = [ bbox_pred.permute(0,", "self.num_classes = num_classes self.cls_out_channels = num_classes - 1 self.in_channels =", "> 0 # condition2: limit the regression range for each", "gt_bboxes.new_zeros((num_points, 4)) areas = (gt_bboxes[:, 2] - gt_bboxes[:, 0] +", "https://arxiv.org/abs/1904.01355 Example: >>> self = FCOSHead(11, 7) >>> feats =", "= len(pos_inds) loss_cls = self.loss_cls( flatten_cls_scores, flatten_labels, avg_factor=num_pos + num_imgs)", "self.delta - torch.abs(obj_k_embedding_mean - obj_j_embedding_mean) push_loss += torch.max(push_dist, torch.zeros(1, device=push_dist.device))", "return dict( loss_cls=loss_cls, loss_bbox=loss_bbox, push_loss=push_loss, pull_loss=pull_loss) @force_fp32(apply_to=('cls_scores', 'bbox_preds')) def get_bboxes(self,", "_, topk_inds = max_scores.topk(nms_pre) points = points[topk_inds, :] bbox_pred =", "right, bottom), -1) # condition1: inside a gt bbox inside_gt_bbox_mask", "num_points = [center.size(0) for center in points] labels_list = [labels.split(num_points,", "[center.size(0) for center in points] labels_list = [labels.split(num_points, 0) for", "strides=(4, 8, 16, 32, 64), delta=2.0, regress_ranges=((-1, 64), (64, 128),", "'bbox_preds')) def get_bboxes(self, cls_scores, bbox_preds, img_metas, cfg, rescale=None): assert len(cls_scores)", "= obj_id remove[mask] = 1 obj_id += 1 instance_counter =", "of each image labels_list, bbox_targets_list = multi_apply( self.fcos_target_single, gt_bboxes_list, gt_labels_list,", "x = torch.meshgrid(y_range, x_range) points = torch.stack( (x.reshape(-1), y.reshape(-1)), dim=-1)", "Object Detection head from [1]_. The FCOS head does not", "torch.cat( [bbox_targets[i] for bbox_targets in bbox_targets_list])) return concat_lvl_labels, concat_lvl_bbox_targets def", "1 instance_counter = instance_counter.int() obj_ids = torch.bincount(instance_counter).nonzero().int() for obj_id in", "num_pos is 0 pos_bbox_preds = flatten_bbox_preds[pos_inds] if num_pos > 0:", "image concat_lvl_labels = [] concat_lvl_bbox_targets = [] for i in", "out why these two are different # areas = areas[None].expand(num_points,", "device=device) y, x = torch.meshgrid(y_range, x_range) points = torch.stack( (x.reshape(-1),", "8, 16, 32, 64), delta=2.0, regress_ranges=((-1, 64), (64, 128), (128,", "bbox_targets.split(num_points, 0) for bbox_targets in bbox_targets_list ] # concat per", "nn from mmcv.cnn import normal_init from mmdet.core import distance2bbox, force_fp32,", "= push_loss / N_samples**2 # iou loss loss_bbox = self.loss_bbox(", "N_samples**2 # iou loss loss_bbox = self.loss_bbox( pos_decoded_bbox_preds, pos_decoded_target_preds) else:", "featmap_size x_range = torch.arange( 0, w * stride, stride, dtype=dtype,", "= self.get_points(featmap_sizes, bbox_preds[0].dtype, bbox_preds[0].device) labels, bbox_targets = self.fcos_target(all_level_points, gt_bboxes, gt_labels)", "[] for img_id in range(len(img_metas)): cls_score_list = [ cls_scores[i][img_id].detach() for", "xs, ys = points[:, 0], points[:, 1] xs = xs[:,", "512), (512, INF)), loss_cls=dict( type='FocalLoss', use_sigmoid=True, gamma=2.0, alpha=0.25, loss_weight=1.0), loss_bbox=dict(type='IoULoss',", "def get_bboxes(self, cls_scores, bbox_preds, img_metas, cfg, rescale=None): assert len(cls_scores) ==", "push_loss += torch.max(push_dist, torch.zeros(1, device=push_dist.device)) push_loss = push_loss / N_samples**2", "= torch.stack( (x.reshape(-1), y.reshape(-1)), dim=-1) + stride // 2 return", "std=0.01) normal_init(self.embedding_cls, std=0.01) def forward(self, feats): return multi_apply(self.forward_single, feats, self.scales)", "3, stride=1, padding=1, conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg, bias=self.norm_cfg is None)) self.reg_convs.append( ConvModule(", "= nn.ModuleList() self.embedding_convs = nn.ModuleList() for i in range(self.stacked_convs): chn", "obj_ids: dist_conf_mask_list.append((instance_counter==obj_id).float()) # Opt for each obj objs_embedding_list = []", "= self.forward(feats) >>> assert len(cls_score) == len(self.scales) \"\"\" def __init__(self,", "= [] for cls_score, bbox_pred, points in zip( cls_scores, bbox_preds,", "= torch.zeros(num_pos, device=pos_points.device) obj_id = 0 # NOTE: get mask", "for labels in labels_list])) concat_lvl_bbox_targets.append( torch.cat( [bbox_targets[i] for bbox_targets in", "2] - gt_bboxes[:, 0] + 1) * ( gt_bboxes[:, 3]", "build_loss(loss_bbox) self.conv_cfg = conv_cfg self.norm_cfg = norm_cfg self.fp16_enabled = False", "len(mlvl_points) mlvl_bboxes = [] mlvl_scores = [] for cls_score, bbox_pred,", "IPython import embed INF = 1e8 @HEADS.register_module class EmbeddingNNmsHeadV2limited(nn.Module): \"\"\"", "pull_loss=pull_loss) @force_fp32(apply_to=('cls_scores', 'bbox_preds')) def get_bboxes(self, cls_scores, bbox_preds, img_metas, cfg, rescale=None):", "= img_metas[img_id]['img_shape'] scale_factor = img_metas[img_id]['scale_factor'] det_bboxes = self.get_bboxes_single(cls_score_list, bbox_pred_list, mlvl_points,", "loss_bbox = self.loss_bbox( pos_decoded_bbox_preds, pos_decoded_target_preds) else: loss_bbox = pos_bbox_preds.sum() push_loss", "normal_init from mmdet.core import distance2bbox, force_fp32, multi_apply, multiclass_nms, bbox_overlaps from", "7) >>> feats = [torch.rand(1, 7, s, s) for s", "[labels.split(num_points, 0) for labels in labels_list] bbox_targets_list = [ bbox_targets.split(num_points,", "if i == 0 else self.feat_channels self.cls_convs.append( ConvModule( chn, self.feat_channels,", "NOTE: get mask for each obj for i in range(len(pos_decoded_target_preds)):", "else: push_dist = self.delta - torch.abs(obj_k_embedding_mean - obj_j_embedding_mean) push_loss +=", "0 # condition2: limit the regression range for each location", "3, stride=1, padding=1, conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg, bias=self.norm_cfg is None)) self.fcos_cls =", "cls_score.size()[-2:] == bbox_pred.size()[-2:] scores = cls_score.permute(1, 2, 0).reshape( -1, self.cls_out_channels).sigmoid()", "torch.equal(obj_j_embedding_mean, obj_k_embedding_mean): continue else: push_dist = self.delta - torch.abs(obj_k_embedding_mean -", "= num_classes - 1 self.in_channels = in_channels self.feat_channels = feat_channels", "(64, 128), (128, 256), (256, 512), (512, INF)), loss_cls=dict( type='FocalLoss',", "each pixel and a centerness measure is used to supress", "bbox_pred, max_shape=img_shape) mlvl_bboxes.append(bboxes) mlvl_scores.append(scores) mlvl_bboxes = torch.cat(mlvl_bboxes) if rescale: mlvl_bboxes", "range(num_levels) ] bbox_pred_list = [ bbox_preds[i][img_id].detach() for i in range(num_levels)", "] flatten_embedding_preds = [ embedding_feat.permute(0, 2, 3, 1).reshape(-1, 1) for", "None, :].expand( num_points, num_gts, 2) gt_bboxes = gt_bboxes[None].expand(num_points, num_gts, 4)", "supress low-quality predictions. References: .. [1] https://arxiv.org/abs/1904.01355 Example: >>> self", "dtype, device): \"\"\"Get points according to feature map sizes. Args:", "distance2bbox(points, bbox_pred, max_shape=img_shape) mlvl_bboxes.append(bboxes) mlvl_scores.append(scores) mlvl_bboxes = torch.cat(mlvl_bboxes) if rescale:", "self.strides[i], dtype, device)) return mlvl_points def get_points_single(self, featmap_size, stride, dtype,", "= [ bbox_preds[i][img_id].detach() for i in range(num_levels) ] img_shape =", "i in range(num_levels) ] bbox_pred_list = [ bbox_preds[i][img_id].detach() for i", "nms_pre: max_scores, _ = scores.max(dim=1) _, topk_inds = max_scores.topk(nms_pre) points", "= torch.cat(mlvl_bboxes) if rescale: mlvl_bboxes /= mlvl_bboxes.new_tensor(scale_factor) mlvl_scores = torch.cat(mlvl_scores)", "the one with minimal area areas[inside_gt_bbox_mask == 0] = INF", "from ..builder import build_loss from ..registry import HEADS from ..utils", "points = points[topk_inds, :] bbox_pred = bbox_pred[topk_inds, :] scores =", "ys - gt_bboxes[..., 1] bottom = gt_bboxes[..., 3] - ys", "for m in self.reg_convs: normal_init(m.conv, std=0.01) bias_cls = bias_init_with_prob(0.01) normal_init(self.fcos_cls,", ">>> self = FCOSHead(11, 7) >>> feats = [torch.rand(1, 7,", "flatten_cls_scores.sigmoid().max(1) pos_embedding_preds = flatten_embedding_preds[pos_inds] # Instance level op dist_conf_mask_list =", "range(len(pos_decoded_target_preds)): if remove[i] == 0: current_bbox = pos_decoded_target_preds[i] mask =", "( max_regress_distance <= regress_ranges[..., 1]) # if there are still", "None)) self.embedding_convs.append( ConvModule( chn, self.feat_channels, 3, stride=1, padding=1, conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg,", "points in zip( cls_scores, bbox_preds, mlvl_points): assert cls_score.size()[-2:] == bbox_pred.size()[-2:]", "feat_channels=256, stacked_convs=4, embedding_convs_num=2, strides=(4, 8, 16, 32, 64), delta=2.0, regress_ranges=((-1,", ">= regress_ranges[..., 0]) & ( max_regress_distance <= regress_ranges[..., 1]) #", "+ num_imgs) # avoid num_pos is 0 pos_bbox_preds = flatten_bbox_preds[pos_inds]", "stride=1, padding=1, conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg, bias=self.norm_cfg is None)) self.reg_convs.append( ConvModule( chn,", "loss(self, cls_scores, bbox_preds, embedding_preds, gt_bboxes, gt_labels, img_metas, cfg, gt_bboxes_ignore=None): assert", "points[i]) for i in range(num_levels) ] # concat all levels", "padding=1, conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg, bias=self.norm_cfg is None)) self.reg_convs.append( ConvModule( chn, self.feat_channels,", "self.cls_out_channels).sigmoid() bbox_pred = bbox_pred.permute(1, 2, 0).reshape(-1, 4) nms_pre = cfg.get('nms_pre',", "self.loss_bbox( pos_decoded_bbox_preds, pos_decoded_target_preds) else: loss_bbox = pos_bbox_preds.sum() push_loss = pos_bbox_preds.sum()", "torch.cat(obj_embedding_means_expand_list) pull_embedding = torch.cat(objs_embedding_list) pull_loss = theta * self.pull_loss(pull_embedding, embedding_expand_means)", "7, s, s) for s in [4, 8, 16, 32,", "norm_cfg=self.norm_cfg, bias=self.norm_cfg is None)) self.fcos_cls = nn.Conv2d( self.feat_channels, self.cls_out_channels, 3,", "areas[inside_regress_range == 0] = INF min_area, min_area_inds = areas.min(dim=1) labels", "obj_id = 0 # NOTE: get mask for each obj", "(256, 512), (512, INF)), loss_cls=dict( type='FocalLoss', use_sigmoid=True, gamma=2.0, alpha=0.25, loss_weight=1.0),", "pull_loss = pos_bbox_preds.sum() return dict( loss_cls=loss_cls, loss_bbox=loss_bbox, push_loss=push_loss, pull_loss=pull_loss) @force_fp32(apply_to=('cls_scores',", "if nms_pre > 0 and scores.shape[0] > nms_pre: max_scores, _", "gt_labels.new_zeros(num_points), \\ gt_bboxes.new_zeros((num_points, 4)) areas = (gt_bboxes[:, 2] - gt_bboxes[:,", "max_regress_distance <= regress_ranges[..., 1]) # if there are still more", "= (gt_bboxes[:, 2] - gt_bboxes[:, 0] + 1) * (", "import build_loss from ..registry import HEADS from ..utils import ConvModule,", "return det_bboxes, det_labels def get_points(self, featmap_sizes, dtype, device): \"\"\"Get points", "s in [4, 8, 16, 32, 64]] >>> cls_score, bbox_pred,", "stride, stride, dtype=dtype, device=device) y_range = torch.arange( 0, h *", "max_scores, max_inds = flatten_cls_scores.sigmoid().max(1) pos_embedding_preds = flatten_embedding_preds[pos_inds] # Instance level", "return gt_labels.new_zeros(num_points), \\ gt_bboxes.new_zeros((num_points, 4)) areas = (gt_bboxes[:, 2] -", "push_loss / N_samples**2 # iou loss loss_bbox = self.loss_bbox( pos_decoded_bbox_preds,", "torch.bincount(instance_counter).nonzero().int() for obj_id in obj_ids: dist_conf_mask_list.append((instance_counter==obj_id).float()) # Opt for each", "device (torch.device): Device of points. Returns: tuple: points of each", "per img, per level num_points = [center.size(0) for center in", "torch.cat(flatten_embedding_preds) flatten_labels = torch.cat(labels) flatten_bbox_targets = torch.cat(bbox_targets) # repeat points", "loss_cls=loss_cls, loss_bbox=loss_bbox, push_loss=push_loss, pull_loss=pull_loss) @force_fp32(apply_to=('cls_scores', 'bbox_preds')) def get_bboxes(self, cls_scores, bbox_preds,", "cls_score, bbox_pred, embedding_pred @force_fp32(apply_to=('cls_scores', 'bbox_preds')) def loss(self, cls_scores, bbox_preds, embedding_preds,", "conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg, bias=self.norm_cfg is None)) self.reg_convs.append( ConvModule( chn, self.feat_channels, 3,", "device=pos_points.device) remove = torch.zeros(num_pos, device=pos_points.device) obj_id = 0 # NOTE:", "gt_bboxes[None].expand(num_points, num_gts, 4) xs, ys = points[:, 0], points[:, 1]", "== 0: return gt_labels.new_zeros(num_points), \\ gt_bboxes.new_zeros((num_points, 4)) areas = (gt_bboxes[:,", "[featmap.size()[-2:] for featmap in cls_scores] all_level_points = self.get_points(featmap_sizes, bbox_preds[0].dtype, bbox_preds[0].device)", "[] obj_embedding_means_expand_list = [] for dist_conf_mask in dist_conf_mask_list: obj_mask_inds =", "in_channels self.feat_channels = feat_channels self.stacked_convs = stacked_convs self.embedding_convs_num = embedding_convs_num", "instance_counter = torch.zeros(num_pos, device=pos_points.device) remove = torch.zeros(num_pos, device=pos_points.device) obj_id =", "ys = ys[:, None].expand(num_points, num_gts) left = xs - gt_bboxes[...,", "= theta * self.pull_loss(pull_embedding, embedding_expand_means) # push loss N_samples =", "= 1e8 @HEADS.register_module class EmbeddingNNmsHeadV2limited(nn.Module): \"\"\" Fully Convolutional One-Stage Object", "0).reshape( -1, self.cls_out_channels).sigmoid() bbox_pred = bbox_pred.permute(1, 2, 0).reshape(-1, 4) nms_pre", "@HEADS.register_module class EmbeddingNNmsHeadV2limited(nn.Module): \"\"\" Fully Convolutional One-Stage Object Detection head", "fcos_target_single(self, gt_bboxes, gt_labels, points, regress_ranges): num_points = points.size(0) num_gts =", "labels[min_area == INF] = 0 bbox_targets = bbox_targets[range(num_points), min_area_inds] return", "2) gt_bboxes = gt_bboxes[None].expand(num_points, num_gts, 4) xs, ys = points[:,", "range(num_levels): concat_lvl_labels.append( torch.cat([labels[i] for labels in labels_list])) concat_lvl_bbox_targets.append( torch.cat( [bbox_targets[i]", "num_points, num_gts, 2) gt_bboxes = gt_bboxes[None].expand(num_points, num_gts, 4) xs, ys", "xs[:, None].expand(num_points, num_gts) ys = ys[:, None].expand(num_points, num_gts) left =", "areas = areas[None].repeat(num_points, 1) regress_ranges = regress_ranges[:, None, :].expand( num_points,", "obj_embedding_means_expand_list.append(torch.zeros_like(obj_embedding_preds).fill_(embedding_mean)) embed() # pull loss theta = 1 embedding_expand_means =", "centerness = self.forward(feats) >>> assert len(cls_score) == len(self.scales) \"\"\" def", "and bbox_preds flatten_cls_scores = [ cls_score.permute(0, 2, 3, 1).reshape(-1, self.cls_out_channels)", "requires_grad=True)): super(EmbeddingNNmsHeadV2limited, self).__init__() self.num_classes = num_classes self.cls_out_channels = num_classes -", "Multi-level feature map sizes. dtype (torch.dtype): Type of points. device", "= num_classes self.cls_out_channels = num_classes - 1 self.in_channels = in_channels", "overflow when enabling FP16 bbox_pred = scale(self.fcos_reg(reg_feat)).float().exp() return cls_score, bbox_pred,", "i in range(num_levels) ] img_shape = img_metas[img_id]['img_shape'] scale_factor = img_metas[img_id]['scale_factor']", "= cls_score.permute(1, 2, 0).reshape( -1, self.cls_out_channels).sigmoid() bbox_pred = bbox_pred.permute(1, 2,", "stacked_convs=4, embedding_convs_num=2, strides=(4, 8, 16, 32, 64), delta=2.0, regress_ranges=((-1, 64),", "mmcv.cnn import normal_init from mmdet.core import distance2bbox, force_fp32, multi_apply, multiclass_nms,", "bounding boxes are predicted at each pixel and a centerness", "len(self.scales) \"\"\" def __init__(self, num_classes, in_channels, feat_channels=256, stacked_convs=4, embedding_convs_num=2, strides=(4,", "(torch.device): Device of points. Returns: tuple: points of each image.", "# concat all levels points and regress ranges concat_regress_ranges =", "concat_regress_ranges = torch.cat(expanded_regress_ranges, dim=0) concat_points = torch.cat(points, dim=0) # get", "limit the regression range for each location max_regress_distance = bbox_targets.max(-1)[0]", "if num_pos > 0: pos_bbox_targets = flatten_bbox_targets[pos_inds] pos_points = flatten_points[pos_inds]", "= points[:, 0], points[:, 1] xs = xs[:, None].expand(num_points, num_gts)", "in labels_list] bbox_targets_list = [ bbox_targets.split(num_points, 0) for bbox_targets in", "regress_ranges[..., 0]) & ( max_regress_distance <= regress_ranges[..., 1]) # if", "== current_bbox).sum(1)==4).nonzero() instance_counter[mask] = obj_id remove[mask] = 1 obj_id +=", "device)) return mlvl_points def get_points_single(self, featmap_size, stride, dtype, device): h,", "cls_scores] all_level_points = self.get_points(featmap_sizes, bbox_preds[0].dtype, bbox_preds[0].device) labels, bbox_targets = self.fcos_target(all_level_points,", "concat_lvl_bbox_targets = [] for i in range(num_levels): concat_lvl_labels.append( torch.cat([labels[i] for", "] flatten_bbox_preds = [ bbox_pred.permute(0, 2, 3, 1).reshape(-1, 4) for", "= in_channels self.feat_channels = feat_channels self.stacked_convs = stacked_convs self.embedding_convs_num =", "None)) self.reg_convs.append( ConvModule( chn, self.feat_channels, 3, stride=1, padding=1, conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg,", "# Pull and Push loss self.pull_loss = nn.MSELoss() def init_weights(self):", "= torch.cat(expanded_regress_ranges, dim=0) concat_points = torch.cat(points, dim=0) # get labels", "None)) self.fcos_cls = nn.Conv2d( self.feat_channels, self.cls_out_channels, 3, padding=1) self.fcos_reg =", "cls_scores[0].size(0) # flatten cls_scores and bbox_preds flatten_cls_scores = [ cls_score.permute(0,", "figure out why these two are different # areas =", "bbox_targets_list = multi_apply( self.fcos_target_single, gt_bboxes_list, gt_labels_list, points=concat_points, regress_ranges=concat_regress_ranges) # split", "= regress_ranges self.loss_cls = build_loss(loss_cls) self.loss_bbox = build_loss(loss_bbox) self.conv_cfg =", "labels_list])) concat_lvl_bbox_targets.append( torch.cat( [bbox_targets[i] for bbox_targets in bbox_targets_list])) return concat_lvl_labels,", "gt_bboxes, gt_labels) num_imgs = cls_scores[0].size(0) # flatten cls_scores and bbox_preds", "bbox_targets_list = [ bbox_targets.split(num_points, 0) for bbox_targets in bbox_targets_list ]", "- gt_bboxes[..., 0] right = gt_bboxes[..., 2] - xs top", "points, gt_bboxes_list, gt_labels_list): assert len(points) == len(self.regress_ranges) num_levels = len(points)", "2, 0).reshape( -1, self.cls_out_channels).sigmoid() bbox_pred = bbox_pred.permute(1, 2, 0).reshape(-1, 4)", "result_list def get_bboxes_single(self, cls_scores, bbox_preds, mlvl_points, img_shape, scale_factor, cfg, rescale=False):", "conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg, bias=self.norm_cfg is None)) self.fcos_cls = nn.Conv2d( self.feat_channels, self.cls_out_channels,", "cls_score = self.fcos_cls(cls_feat) for embedding_layer in self.embedding_convs: embedding_feat = embedding_layer(embedding_feat)", "= self.fcos_cls(cls_feat) for embedding_layer in self.embedding_convs: embedding_feat = embedding_layer(embedding_feat) embedding_pred", "def _init_layers(self): self.cls_convs = nn.ModuleList() self.reg_convs = nn.ModuleList() self.embedding_convs =", "gt_bboxes[:, 1] + 1) # TODO: figure out why these", "nn.ModuleList() self.embedding_convs = nn.ModuleList() for i in range(self.stacked_convs): chn =", "bias=self.norm_cfg is None)) self.embedding_convs.append( ConvModule( chn, self.feat_channels, 3, stride=1, padding=1,", "= [] mlvl_scores = [] for cls_score, bbox_pred, points in", "= pos_bbox_preds.sum() pull_loss = pos_bbox_preds.sum() return dict( loss_cls=loss_cls, loss_bbox=loss_bbox, push_loss=push_loss,", "if rescale: mlvl_bboxes /= mlvl_bboxes.new_tensor(scale_factor) mlvl_scores = torch.cat(mlvl_scores) padding =", "1) * ( gt_bboxes[:, 3] - gt_bboxes[:, 1] + 1)", "std=0.01) def forward(self, feats): return multi_apply(self.forward_single, feats, self.scales) def forward_single(self,", "(gt_bboxes[:, 2] - gt_bboxes[:, 0] + 1) * ( gt_bboxes[:,", "is_aligned=True).clamp(min=1e-6) max_scores, max_inds = flatten_cls_scores.sigmoid().max(1) pos_embedding_preds = flatten_embedding_preds[pos_inds] # Instance", "self.in_channels if i == 0 else self.feat_channels self.cls_convs.append( ConvModule( chn,", "# if there are still more than one objects for", "= torch.cat(flatten_embedding_preds) flatten_labels = torch.cat(labels) flatten_bbox_targets = torch.cat(bbox_targets) # repeat", "-1) # condition1: inside a gt bbox inside_gt_bbox_mask = bbox_targets.min(-1)[0]", "stride // 2 return points def fcos_target(self, points, gt_bboxes_list, gt_labels_list):", "nn.Conv2d(self.feat_channels, 1, 3, padding=1) self.scales = nn.ModuleList([Scale(1.0) for _ in", "pos_bbox_targets) pos_iou_scores = bbox_overlaps(pos_decoded_bbox_preds, pos_decoded_target_preds, is_aligned=True).clamp(min=1e-6) max_scores, max_inds = flatten_cls_scores.sigmoid().max(1)", "flatten_points[pos_inds] pos_decoded_bbox_preds = distance2bbox(pos_points, pos_bbox_preds) pos_decoded_target_preds = distance2bbox(pos_points, pos_bbox_targets) pos_iou_scores", "in embedding_preds ] flatten_cls_scores = torch.cat(flatten_cls_scores) flatten_bbox_preds = torch.cat(flatten_bbox_preds) flatten_embedding_preds", "\"\"\"Get points according to feature map sizes. Args: featmap_sizes (list[tuple]):", "bbox_preds[0].device) labels, bbox_targets = self.fcos_target(all_level_points, gt_bboxes, gt_labels) num_imgs = cls_scores[0].size(0)", "self.loss_cls( flatten_cls_scores, flatten_labels, avg_factor=num_pos + num_imgs) # avoid num_pos is", "pos_bbox_preds.sum() return dict( loss_cls=loss_cls, loss_bbox=loss_bbox, push_loss=push_loss, pull_loss=pull_loss) @force_fp32(apply_to=('cls_scores', 'bbox_preds')) def", "nms_pre = cfg.get('nms_pre', -1) if nms_pre > 0 and scores.shape[0]", "= x embedding_feat = x for cls_layer in self.cls_convs: cls_feat", "1] xs = xs[:, None].expand(num_points, num_gts) ys = ys[:, None].expand(num_points,", "minimal area areas[inside_gt_bbox_mask == 0] = INF areas[inside_regress_range == 0]", "0]) & ( max_regress_distance <= regress_ranges[..., 1]) # if there", "instance_counter = instance_counter.int() obj_ids = torch.bincount(instance_counter).nonzero().int() for obj_id in obj_ids:", ">>> feats = [torch.rand(1, 7, s, s) for s in", "- gt_bboxes[:, 0] + 1) * ( gt_bboxes[:, 3] -", "for i in range(num_levels) ] img_shape = img_metas[img_id]['img_shape'] scale_factor =", "& ( max_regress_distance <= regress_ranges[..., 1]) # if there are", "for i in range(num_levels): concat_lvl_labels.append( torch.cat([labels[i] for labels in labels_list]))", "for bbox_targets in bbox_targets_list ] # concat per level image", "2, 3, 1).reshape(-1, 1) for embedding_feat in embedding_preds ] flatten_cls_scores", "right = gt_bboxes[..., 2] - xs top = ys -", "for featmap in cls_scores] mlvl_points = self.get_points(featmap_sizes, bbox_preds[0].dtype, bbox_preds[0].device) result_list", "padding=1) self.scales = nn.ModuleList([Scale(1.0) for _ in self.strides]) # Pull", "center in points] labels_list = [labels.split(num_points, 0) for labels in", "len(cls_scores) == len(bbox_preds) == len(embedding_preds) featmap_sizes = [featmap.size()[-2:] for featmap", "= x for cls_layer in self.cls_convs: cls_feat = cls_layer(cls_feat) cls_score", "return concat_lvl_labels, concat_lvl_bbox_targets def fcos_target_single(self, gt_bboxes, gt_labels, points, regress_ranges): num_points", "pos_iou_scores = bbox_overlaps(pos_decoded_bbox_preds, pos_decoded_target_preds, is_aligned=True).clamp(min=1e-6) max_scores, max_inds = flatten_cls_scores.sigmoid().max(1) pos_embedding_preds", "Scale, bias_init_with_prob from IPython import embed INF = 1e8 @HEADS.register_module", "for a location, # we choose the one with minimal", "points def fcos_target(self, points, gt_bboxes_list, gt_labels_list): assert len(points) == len(self.regress_ranges)", "mlvl_bboxes.new_tensor(scale_factor) mlvl_scores = torch.cat(mlvl_scores) padding = mlvl_scores.new_zeros(mlvl_scores.shape[0], 1) mlvl_scores =", "False self._init_layers() def _init_layers(self): self.cls_convs = nn.ModuleList() self.reg_convs = nn.ModuleList()", "to align with points expanded_regress_ranges = [ points[i].new_tensor(self.regress_ranges[i])[None].expand_as( points[i]) for", "def __init__(self, num_classes, in_channels, feat_channels=256, stacked_convs=4, embedding_convs_num=2, strides=(4, 8, 16,", "bbox_preds[i][img_id].detach() for i in range(num_levels) ] img_shape = img_metas[img_id]['img_shape'] scale_factor", "concat_lvl_labels.append( torch.cat([labels[i] for labels in labels_list])) concat_lvl_bbox_targets.append( torch.cat( [bbox_targets[i] for", "is None)) self.reg_convs.append( ConvModule( chn, self.feat_channels, 3, stride=1, padding=1, conv_cfg=self.conv_cfg,", "[] for i in range(num_levels): concat_lvl_labels.append( torch.cat([labels[i] for labels in", "pixel and a centerness measure is used to supress low-quality", "= [] for i in range(len(featmap_sizes)): mlvl_points.append( self.get_points_single(featmap_sizes[i], self.strides[i], dtype,", "mlvl_points = self.get_points(featmap_sizes, bbox_preds[0].dtype, bbox_preds[0].device) result_list = [] for img_id", "scores = scores[topk_inds, :] bboxes = distance2bbox(points, bbox_pred, max_shape=img_shape) mlvl_bboxes.append(bboxes)", "and regress ranges concat_regress_ranges = torch.cat(expanded_regress_ranges, dim=0) concat_points = torch.cat(points,", "64]] >>> cls_score, bbox_pred, centerness = self.forward(feats) >>> assert len(cls_score)", "1).reshape(-1, 4) for bbox_pred in bbox_preds ] flatten_embedding_preds = [", "in bbox_preds ] flatten_embedding_preds = [ embedding_feat.permute(0, 2, 3, 1).reshape(-1,", "== len(mlvl_points) mlvl_bboxes = [] mlvl_scores = [] for cls_score,", "= torch.cat(bbox_targets) # repeat points to align with bbox_preds flatten_points", "+ 1) * ( gt_bboxes[:, 3] - gt_bboxes[:, 1] +", "super(EmbeddingNNmsHeadV2limited, self).__init__() self.num_classes = num_classes self.cls_out_channels = num_classes - 1", "num_levels = len(points) # expand regress ranges to align with", "cfg, rescale=False): assert len(cls_scores) == len(bbox_preds) == len(mlvl_points) mlvl_bboxes =", "Args: featmap_sizes (list[tuple]): Multi-level feature map sizes. dtype (torch.dtype): Type", "objs_embedding_list.append(obj_embedding_preds) # mean value embedding_mean = obj_embedding_preds.sum() / obj_embedding_preds.shape[0] obj_embedding_means_list.append(embedding_mean)", "location max_regress_distance = bbox_targets.max(-1)[0] inside_regress_range = ( max_regress_distance >= regress_ranges[...,", "areas[None].repeat(num_points, 1) regress_ranges = regress_ranges[:, None, :].expand( num_points, num_gts, 2)", "forward(self, feats): return multi_apply(self.forward_single, feats, self.scales) def forward_single(self, x, scale):", "torch.zeros(num_pos, device=pos_points.device) remove = torch.zeros(num_pos, device=pos_points.device) obj_id = 0 #", "and scores.shape[0] > nms_pre: max_scores, _ = scores.max(dim=1) _, topk_inds", "we choose the one with minimal area areas[inside_gt_bbox_mask == 0]", "bbox inside_gt_bbox_mask = bbox_targets.min(-1)[0] > 0 # condition2: limit the", "= [featmap.size()[-2:] for featmap in cls_scores] mlvl_points = self.get_points(featmap_sizes, bbox_preds[0].dtype,", "each obj for i in range(len(pos_decoded_target_preds)): if remove[i] == 0:", "flatten_embedding_preds = torch.cat(flatten_embedding_preds) flatten_labels = torch.cat(labels) flatten_bbox_targets = torch.cat(bbox_targets) #", "for obj_id in obj_ids: dist_conf_mask_list.append((instance_counter==obj_id).float()) # Opt for each obj", "in range(num_levels) ] img_shape = img_metas[img_id]['img_shape'] scale_factor = img_metas[img_id]['scale_factor'] det_bboxes", "bbox_targets = self.fcos_target(all_level_points, gt_bboxes, gt_labels) num_imgs = cls_scores[0].size(0) # flatten", "for bbox_pred in bbox_preds ] flatten_embedding_preds = [ embedding_feat.permute(0, 2,", "is used to supress low-quality predictions. References: .. [1] https://arxiv.org/abs/1904.01355", "((pos_decoded_target_preds == current_bbox).sum(1)==4).nonzero() instance_counter[mask] = obj_id remove[mask] = 1 obj_id", "torch.arange( 0, w * stride, stride, dtype=dtype, device=device) y_range =", "return result_list def get_bboxes_single(self, cls_scores, bbox_preds, mlvl_points, img_shape, scale_factor, cfg,", "featmap_sizes, dtype, device): \"\"\"Get points according to feature map sizes.", "INF = 1e8 @HEADS.register_module class EmbeddingNNmsHeadV2limited(nn.Module): \"\"\" Fully Convolutional One-Stage", "embedding_expand_means) # push loss N_samples = len(dist_conf_mask_list) push_loss = 0", "= build_loss(loss_cls) self.loss_bbox = build_loss(loss_bbox) self.conv_cfg = conv_cfg self.norm_cfg =", "[torch.rand(1, 7, s, s) for s in [4, 8, 16,", "> nms_pre: max_scores, _ = scores.max(dim=1) _, topk_inds = max_scores.topk(nms_pre)", "max_shape=img_shape) mlvl_bboxes.append(bboxes) mlvl_scores.append(scores) mlvl_bboxes = torch.cat(mlvl_bboxes) if rescale: mlvl_bboxes /=", "in self.reg_convs: normal_init(m.conv, std=0.01) bias_cls = bias_init_with_prob(0.01) normal_init(self.fcos_cls, std=0.01, bias=bias_cls)", "for embedding_layer in self.embedding_convs: embedding_feat = embedding_layer(embedding_feat) embedding_pred = self.embedding_cls(embedding_feat)", "32, 64]] >>> cls_score, bbox_pred, centerness = self.forward(feats) >>> assert", "featmap in cls_scores] all_level_points = self.get_points(featmap_sizes, bbox_preds[0].dtype, bbox_preds[0].device) labels, bbox_targets", "len(cls_scores) == len(bbox_preds) num_levels = len(cls_scores) featmap_sizes = [featmap.size()[-2:] for", "= torch.arange( 0, w * stride, stride, dtype=dtype, device=device) y_range", "= bbox_overlaps(pos_decoded_bbox_preds, pos_decoded_target_preds, is_aligned=True).clamp(min=1e-6) max_scores, max_inds = flatten_cls_scores.sigmoid().max(1) pos_embedding_preds =", "== 0 else self.feat_channels self.cls_convs.append( ConvModule( chn, self.feat_channels, 3, stride=1,", "[] obj_embedding_means_list = [] obj_embedding_means_expand_list = [] for dist_conf_mask in", "dim=0) # get labels and bbox_targets of each image labels_list,", "device=device) y_range = torch.arange( 0, h * stride, stride, dtype=dtype,", "bbox_pred = bbox_pred.permute(1, 2, 0).reshape(-1, 4) nms_pre = cfg.get('nms_pre', -1)", "self.loss_cls = build_loss(loss_cls) self.loss_bbox = build_loss(loss_bbox) self.conv_cfg = conv_cfg self.norm_cfg", "len(embedding_preds) featmap_sizes = [featmap.size()[-2:] for featmap in cls_scores] all_level_points =", "points and regress ranges concat_regress_ranges = torch.cat(expanded_regress_ranges, dim=0) concat_points =", "conv_cfg self.norm_cfg = norm_cfg self.fp16_enabled = False self._init_layers() def _init_layers(self):", "self.reg_convs = nn.ModuleList() self.embedding_convs = nn.ModuleList() for i in range(self.stacked_convs):", "regress_ranges): num_points = points.size(0) num_gts = gt_labels.size(0) if num_gts ==", "= gt_bboxes[..., 3] - ys bbox_targets = torch.stack((left, top, right,", "index instance_counter = torch.zeros(num_pos, device=pos_points.device) remove = torch.zeros(num_pos, device=pos_points.device) obj_id", "= delta self.regress_ranges = regress_ranges self.loss_cls = build_loss(loss_cls) self.loss_bbox =", "obj_ids = torch.bincount(instance_counter).nonzero().int() for obj_id in obj_ids: dist_conf_mask_list.append((instance_counter==obj_id).float()) # Opt", "torch.cat([padding, mlvl_scores], dim=1) det_bboxes, det_labels = multiclass_nms( mlvl_bboxes, mlvl_scores, cfg.score_thr,", "= torch.cat(objs_embedding_list) pull_loss = theta * self.pull_loss(pull_embedding, embedding_expand_means) # push", "len(cls_scores) == len(bbox_preds) == len(mlvl_points) mlvl_bboxes = [] mlvl_scores =", "for embedding_feat in embedding_preds ] flatten_cls_scores = torch.cat(flatten_cls_scores) flatten_bbox_preds =", ">>> assert len(cls_score) == len(self.scales) \"\"\" def __init__(self, num_classes, in_channels,", "= norm_cfg self.fp16_enabled = False self._init_layers() def _init_layers(self): self.cls_convs =", "bias_cls = bias_init_with_prob(0.01) normal_init(self.fcos_cls, std=0.01, bias=bias_cls) normal_init(self.fcos_reg, std=0.01) normal_init(self.embedding_cls, std=0.01)", "distance2bbox(pos_points, pos_bbox_preds) pos_decoded_target_preds = distance2bbox(pos_points, pos_bbox_targets) pos_iou_scores = bbox_overlaps(pos_decoded_bbox_preds, pos_decoded_target_preds,", "num_imgs = cls_scores[0].size(0) # flatten cls_scores and bbox_preds flatten_cls_scores =", "bbox_pred = scale(self.fcos_reg(reg_feat)).float().exp() return cls_score, bbox_pred, embedding_pred @force_fp32(apply_to=('cls_scores', 'bbox_preds')) def", "return mlvl_points def get_points_single(self, featmap_size, stride, dtype, device): h, w", "/ obj_embedding_preds.shape[0] obj_embedding_means_list.append(embedding_mean) obj_embedding_means_expand_list.append(torch.zeros_like(obj_embedding_preds).fill_(embedding_mean)) embed() # pull loss theta =", "in labels_list])) concat_lvl_bbox_targets.append( torch.cat( [bbox_targets[i] for bbox_targets in bbox_targets_list])) return", "iou loss loss_bbox = self.loss_bbox( pos_decoded_bbox_preds, pos_decoded_target_preds) else: loss_bbox =", "in range(len(featmap_sizes)): mlvl_points.append( self.get_points_single(featmap_sizes[i], self.strides[i], dtype, device)) return mlvl_points def", "self.reg_convs.append( ConvModule( chn, self.feat_channels, 3, stride=1, padding=1, conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg, bias=self.norm_cfg", "= self.in_channels if i == 0 else self.feat_channels self.cls_convs.append( ConvModule(", "image labels_list, bbox_targets_list = multi_apply( self.fcos_target_single, gt_bboxes_list, gt_labels_list, points=concat_points, regress_ranges=concat_regress_ranges)", "gt_bboxes[:, 0] + 1) * ( gt_bboxes[:, 3] - gt_bboxes[:,", "bbox_preds[0].device) result_list = [] for img_id in range(len(img_metas)): cls_score_list =", "Push loss self.pull_loss = nn.MSELoss() def init_weights(self): for m in", "0 # NOTE: get mask for each obj for i", "self.scales) def forward_single(self, x, scale): cls_feat = x reg_feat =", "result_list = [] for img_id in range(len(img_metas)): cls_score_list = [", "= embedding_convs_num self.strides = strides self.delta = delta self.regress_ranges =", "gt_bboxes[..., 3] - ys bbox_targets = torch.stack((left, top, right, bottom),", "than one objects for a location, # we choose the", "norm_cfg self.fp16_enabled = False self._init_layers() def _init_layers(self): self.cls_convs = nn.ModuleList()", "range(len(img_metas)): cls_score_list = [ cls_scores[i][img_id].detach() for i in range(num_levels) ]", "def get_bboxes_single(self, cls_scores, bbox_preds, mlvl_points, img_shape, scale_factor, cfg, rescale=False): assert", "1) mlvl_scores = torch.cat([padding, mlvl_scores], dim=1) det_bboxes, det_labels = multiclass_nms(", "@force_fp32(apply_to=('cls_scores', 'bbox_preds')) def loss(self, cls_scores, bbox_preds, embedding_preds, gt_bboxes, gt_labels, img_metas,", "measure is used to supress low-quality predictions. References: .. [1]", "scale(self.fcos_reg(reg_feat)).float().exp() return cls_score, bbox_pred, embedding_pred @force_fp32(apply_to=('cls_scores', 'bbox_preds')) def loss(self, cls_scores,", "gt_bboxes[..., 2] - xs top = ys - gt_bboxes[..., 1]", "dim=1) det_bboxes, det_labels = multiclass_nms( mlvl_bboxes, mlvl_scores, cfg.score_thr, cfg.nms, cfg.max_per_img)", "= cfg.get('nms_pre', -1) if nms_pre > 0 and scores.shape[0] >", "rescale=False): assert len(cls_scores) == len(bbox_preds) == len(mlvl_points) mlvl_bboxes = []", "Type of points. device (torch.device): Device of points. Returns: tuple:", "gt_labels[min_area_inds] labels[min_area == INF] = 0 bbox_targets = bbox_targets[range(num_points), min_area_inds]", "a location, # we choose the one with minimal area", "= [] for img_id in range(len(img_metas)): cls_score_list = [ cls_scores[i][img_id].detach()", "loss_bbox = pos_bbox_preds.sum() push_loss = pos_bbox_preds.sum() pull_loss = pos_bbox_preds.sum() return", "inside_gt_bbox_mask = bbox_targets.min(-1)[0] > 0 # condition2: limit the regression", "(list[tuple]): Multi-level feature map sizes. dtype (torch.dtype): Type of points.", "loss N_samples = len(dist_conf_mask_list) push_loss = 0 for obj_j_embedding_mean in", "obj_id += 1 instance_counter = instance_counter.int() obj_ids = torch.bincount(instance_counter).nonzero().int() for", "obj_embedding_means_list: for obj_k_embedding_mean in obj_embedding_means_list: if torch.equal(obj_j_embedding_mean, obj_k_embedding_mean): continue else:", "remove[i] == 0: current_bbox = pos_decoded_target_preds[i] mask = ((pos_decoded_target_preds ==", "0, w * stride, stride, dtype=dtype, device=device) y_range = torch.arange(", "torch.cat(flatten_bbox_preds) flatten_embedding_preds = torch.cat(flatten_embedding_preds) flatten_labels = torch.cat(labels) flatten_bbox_targets = torch.cat(bbox_targets)", "Detection head from [1]_. The FCOS head does not use", "# concat per level image concat_lvl_labels = [] concat_lvl_bbox_targets =", "for center in points] labels_list = [labels.split(num_points, 0) for labels", "flatten_embedding_preds[pos_inds] # Instance level op dist_conf_mask_list = [] # generate", "bbox_pred, centerness = self.forward(feats) >>> assert len(cls_score) == len(self.scales) \"\"\"", "for cls_score in cls_scores ] flatten_bbox_preds = [ bbox_pred.permute(0, 2,", "= multi_apply( self.fcos_target_single, gt_bboxes_list, gt_labels_list, points=concat_points, regress_ranges=concat_regress_ranges) # split to", "push_loss = pos_bbox_preds.sum() pull_loss = pos_bbox_preds.sum() return dict( loss_cls=loss_cls, loss_bbox=loss_bbox,", "scores.max(dim=1) _, topk_inds = max_scores.topk(nms_pre) points = points[topk_inds, :] bbox_pred", "# get labels and bbox_targets of each image labels_list, bbox_targets_list", "in self.strides]) # Pull and Push loss self.pull_loss = nn.MSELoss()", "for featmap in cls_scores] all_level_points = self.get_points(featmap_sizes, bbox_preds[0].dtype, bbox_preds[0].device) labels,", "mlvl_scores, cfg.score_thr, cfg.nms, cfg.max_per_img) return det_bboxes, det_labels def get_points(self, featmap_sizes,", "is None)) self.fcos_cls = nn.Conv2d( self.feat_channels, self.cls_out_channels, 3, padding=1) self.fcos_reg", "for i in range(num_levels) ] bbox_pred_list = [ bbox_preds[i][img_id].detach() for", "self.cls_convs: cls_feat = cls_layer(cls_feat) cls_score = self.fcos_cls(cls_feat) for embedding_layer in", "in cls_scores] all_level_points = self.get_points(featmap_sizes, bbox_preds[0].dtype, bbox_preds[0].device) labels, bbox_targets =", "self.fp16_enabled = False self._init_layers() def _init_layers(self): self.cls_convs = nn.ModuleList() self.reg_convs", "gt_bboxes_ignore=None): assert len(cls_scores) == len(bbox_preds) == len(embedding_preds) featmap_sizes = [featmap.size()[-2:]", "conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg, bias=self.norm_cfg is None)) self.embedding_convs.append( ConvModule( chn, self.feat_channels, 3,", "conv_cfg=None, norm_cfg=dict(type='GN', num_groups=32, requires_grad=True)): super(EmbeddingNNmsHeadV2limited, self).__init__() self.num_classes = num_classes self.cls_out_channels", "0 and scores.shape[0] > nms_pre: max_scores, _ = scores.max(dim=1) _,", "obj_mask_inds = dist_conf_mask.nonzero().reshape(-1) obj_embedding_preds = pos_embedding_preds[obj_mask_inds] objs_embedding_list.append(obj_embedding_preds) # mean value", "num_gts) ys = ys[:, None].expand(num_points, num_gts) left = xs -", "1] + 1) # TODO: figure out why these two", "obj_embedding_means_expand_list = [] for dist_conf_mask in dist_conf_mask_list: obj_mask_inds = dist_conf_mask.nonzero().reshape(-1)", "scale_factor, cfg, rescale=False): assert len(cls_scores) == len(bbox_preds) == len(mlvl_points) mlvl_bboxes", "featmap_size, stride, dtype, device): h, w = featmap_size x_range =", "\"\"\" def __init__(self, num_classes, in_channels, feat_channels=256, stacked_convs=4, embedding_convs_num=2, strides=(4, 8,", "push_loss=push_loss, pull_loss=pull_loss) @force_fp32(apply_to=('cls_scores', 'bbox_preds')) def get_bboxes(self, cls_scores, bbox_preds, img_metas, cfg,", "num_levels = len(cls_scores) featmap_sizes = [featmap.size()[-2:] for featmap in cls_scores]", "value embedding_mean = obj_embedding_preds.sum() / obj_embedding_preds.shape[0] obj_embedding_means_list.append(embedding_mean) obj_embedding_means_expand_list.append(torch.zeros_like(obj_embedding_preds).fill_(embedding_mean)) embed() #", "INF min_area, min_area_inds = areas.min(dim=1) labels = gt_labels[min_area_inds] labels[min_area ==", "obj_j_embedding_mean) push_loss += torch.max(push_dist, torch.zeros(1, device=push_dist.device)) push_loss = push_loss /", "[ bbox_preds[i][img_id].detach() for i in range(num_levels) ] img_shape = img_metas[img_id]['img_shape']", "delta self.regress_ranges = regress_ranges self.loss_cls = build_loss(loss_cls) self.loss_bbox = build_loss(loss_bbox)", "- xs top = ys - gt_bboxes[..., 1] bottom =", "# condition1: inside a gt bbox inside_gt_bbox_mask = bbox_targets.min(-1)[0] >", "centerness measure is used to supress low-quality predictions. References: ..", "std=0.01, bias=bias_cls) normal_init(self.fcos_reg, std=0.01) normal_init(self.embedding_cls, std=0.01) def forward(self, feats): return", "i in range(len(pos_decoded_target_preds)): if remove[i] == 0: current_bbox = pos_decoded_target_preds[i]", "mlvl_points, img_shape, scale_factor, cfg, rescale) result_list.append(det_bboxes) return result_list def get_bboxes_single(self,", "dtype, device): h, w = featmap_size x_range = torch.arange( 0,", "cls_scores, bbox_preds, mlvl_points): assert cls_score.size()[-2:] == bbox_pred.size()[-2:] scores = cls_score.permute(1,", "bbox_pred.size()[-2:] scores = cls_score.permute(1, 2, 0).reshape( -1, self.cls_out_channels).sigmoid() bbox_pred =", "in points] labels_list = [labels.split(num_points, 0) for labels in labels_list]", "multiclass_nms( mlvl_bboxes, mlvl_scores, cfg.score_thr, cfg.nms, cfg.max_per_img) return det_bboxes, det_labels def", "* stride, stride, dtype=dtype, device=device) y_range = torch.arange( 0, h", ".. [1] https://arxiv.org/abs/1904.01355 Example: >>> self = FCOSHead(11, 7) >>>", "pos_bbox_preds.sum() push_loss = pos_bbox_preds.sum() pull_loss = pos_bbox_preds.sum() return dict( loss_cls=loss_cls,", "bbox_targets of each image labels_list, bbox_targets_list = multi_apply( self.fcos_target_single, gt_bboxes_list,", "== bbox_pred.size()[-2:] scores = cls_score.permute(1, 2, 0).reshape( -1, self.cls_out_channels).sigmoid() bbox_pred", "areas[inside_gt_bbox_mask == 0] = INF areas[inside_regress_range == 0] = INF", "concat_points = torch.cat(points, dim=0) # get labels and bbox_targets of", "pull_loss = theta * self.pull_loss(pull_embedding, embedding_expand_means) # push loss N_samples", "len(points) == len(self.regress_ranges) num_levels = len(points) # expand regress ranges", "_init_layers(self): self.cls_convs = nn.ModuleList() self.reg_convs = nn.ModuleList() self.embedding_convs = nn.ModuleList()", "for each location max_regress_distance = bbox_targets.max(-1)[0] inside_regress_range = ( max_regress_distance", "= mlvl_scores.new_zeros(mlvl_scores.shape[0], 1) mlvl_scores = torch.cat([padding, mlvl_scores], dim=1) det_bboxes, det_labels", "min_area, min_area_inds = areas.min(dim=1) labels = gt_labels[min_area_inds] labels[min_area == INF]", "dtype (torch.dtype): Type of points. device (torch.device): Device of points.", "= points.size(0) num_gts = gt_labels.size(0) if num_gts == 0: return", "self.fcos_target(all_level_points, gt_bboxes, gt_labels) num_imgs = cls_scores[0].size(0) # flatten cls_scores and", "= len(points) # expand regress ranges to align with points", "not use anchor boxes. Instead bounding boxes are predicted at", "in obj_ids: dist_conf_mask_list.append((instance_counter==obj_id).float()) # Opt for each obj objs_embedding_list =", "embed INF = 1e8 @HEADS.register_module class EmbeddingNNmsHeadV2limited(nn.Module): \"\"\" Fully Convolutional", "concat_lvl_labels = [] concat_lvl_bbox_targets = [] for i in range(num_levels):", "self.embedding_convs: embedding_feat = embedding_layer(embedding_feat) embedding_pred = self.embedding_cls(embedding_feat) for reg_layer in", "= pos_embedding_preds[obj_mask_inds] objs_embedding_list.append(obj_embedding_preds) # mean value embedding_mean = obj_embedding_preds.sum() /", "] img_shape = img_metas[img_id]['img_shape'] scale_factor = img_metas[img_id]['scale_factor'] det_bboxes = self.get_bboxes_single(cls_score_list,", "= pos_bbox_preds.sum() return dict( loss_cls=loss_cls, loss_bbox=loss_bbox, push_loss=push_loss, pull_loss=pull_loss) @force_fp32(apply_to=('cls_scores', 'bbox_preds'))", "_ in self.strides]) # Pull and Push loss self.pull_loss =", "predictions. References: .. [1] https://arxiv.org/abs/1904.01355 Example: >>> self = FCOSHead(11,", "topk_inds = max_scores.topk(nms_pre) points = points[topk_inds, :] bbox_pred = bbox_pred[topk_inds,", "dtype=dtype, device=device) y, x = torch.meshgrid(y_range, x_range) points = torch.stack(", "flatten_labels, avg_factor=num_pos + num_imgs) # avoid num_pos is 0 pos_bbox_preds", "INF)), loss_cls=dict( type='FocalLoss', use_sigmoid=True, gamma=2.0, alpha=0.25, loss_weight=1.0), loss_bbox=dict(type='IoULoss', loss_weight=1.0), conv_cfg=None,", "of points. Returns: tuple: points of each image. \"\"\" mlvl_points", "cls_feat = x reg_feat = x embedding_feat = x for", "scores[topk_inds, :] bboxes = distance2bbox(points, bbox_pred, max_shape=img_shape) mlvl_bboxes.append(bboxes) mlvl_scores.append(scores) mlvl_bboxes", "> 0: pos_bbox_targets = flatten_bbox_targets[pos_inds] pos_points = flatten_points[pos_inds] pos_decoded_bbox_preds =", "self.feat_channels, 3, stride=1, padding=1, conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg, bias=self.norm_cfg is None)) self.fcos_cls", "these two are different # areas = areas[None].expand(num_points, num_gts) areas", "areas = (gt_bboxes[:, 2] - gt_bboxes[:, 0] + 1) *", "= stacked_convs self.embedding_convs_num = embedding_convs_num self.strides = strides self.delta =", "= gt_labels[min_area_inds] labels[min_area == INF] = 0 bbox_targets = bbox_targets[range(num_points),", "ys bbox_targets = torch.stack((left, top, right, bottom), -1) # condition1:", "in cls_scores ] flatten_bbox_preds = [ bbox_pred.permute(0, 2, 3, 1).reshape(-1,", "mlvl_scores = torch.cat([padding, mlvl_scores], dim=1) det_bboxes, det_labels = multiclass_nms( mlvl_bboxes,", "= torch.stack((left, top, right, bottom), -1) # condition1: inside a", "remove[mask] = 1 obj_id += 1 instance_counter = instance_counter.int() obj_ids", "64), delta=2.0, regress_ranges=((-1, 64), (64, 128), (128, 256), (256, 512),", "# we choose the one with minimal area areas[inside_gt_bbox_mask ==", "bbox_pred in bbox_preds ] flatten_embedding_preds = [ embedding_feat.permute(0, 2, 3,", "level # float to avoid overflow when enabling FP16 bbox_pred", "3, stride=1, padding=1, conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg, bias=self.norm_cfg is None)) self.embedding_convs.append( ConvModule(", "// 2 return points def fcos_target(self, points, gt_bboxes_list, gt_labels_list): assert", "1, 3, padding=1) self.scales = nn.ModuleList([Scale(1.0) for _ in self.strides])", "obj_j_embedding_mean in obj_embedding_means_list: for obj_k_embedding_mean in obj_embedding_means_list: if torch.equal(obj_j_embedding_mean, obj_k_embedding_mean):", "= featmap_size x_range = torch.arange( 0, w * stride, stride,", "gt_bboxes[:, 3] - gt_bboxes[:, 1] + 1) # TODO: figure", "# Instance level op dist_conf_mask_list = [] # generate instance", "= torch.cat(flatten_cls_scores) flatten_bbox_preds = torch.cat(flatten_bbox_preds) flatten_embedding_preds = torch.cat(flatten_embedding_preds) flatten_labels =", "tuple: points of each image. \"\"\" mlvl_points = [] for", "self.fcos_reg = nn.Conv2d(self.feat_channels, 4, 3, padding=1) self.embedding_cls = nn.Conv2d(self.feat_channels, 1,", "= torch.bincount(instance_counter).nonzero().int() for obj_id in obj_ids: dist_conf_mask_list.append((instance_counter==obj_id).float()) # Opt for", "bboxes = distance2bbox(points, bbox_pred, max_shape=img_shape) mlvl_bboxes.append(bboxes) mlvl_scores.append(scores) mlvl_bboxes = torch.cat(mlvl_bboxes)", "float to avoid overflow when enabling FP16 bbox_pred = scale(self.fcos_reg(reg_feat)).float().exp()", "featmap_sizes (list[tuple]): Multi-level feature map sizes. dtype (torch.dtype): Type of", "cfg.score_thr, cfg.nms, cfg.max_per_img) return det_bboxes, det_labels def get_points(self, featmap_sizes, dtype,", "..builder import build_loss from ..registry import HEADS from ..utils import", "top, right, bottom), -1) # condition1: inside a gt bbox", "pos_points = flatten_points[pos_inds] pos_decoded_bbox_preds = distance2bbox(pos_points, pos_bbox_preds) pos_decoded_target_preds = distance2bbox(pos_points,", "= [ cls_scores[i][img_id].detach() for i in range(num_levels) ] bbox_pred_list =", "feature map sizes. dtype (torch.dtype): Type of points. device (torch.device):", "= ys[:, None].expand(num_points, num_gts) left = xs - gt_bboxes[..., 0]", "\"\"\" mlvl_points = [] for i in range(len(featmap_sizes)): mlvl_points.append( self.get_points_single(featmap_sizes[i],", "self = FCOSHead(11, 7) >>> feats = [torch.rand(1, 7, s,", "from IPython import embed INF = 1e8 @HEADS.register_module class EmbeddingNNmsHeadV2limited(nn.Module):", "4, 3, padding=1) self.embedding_cls = nn.Conv2d(self.feat_channels, 1, 3, padding=1) self.scales", "h, w = featmap_size x_range = torch.arange( 0, w *", "gt_bboxes_list, gt_labels_list, points=concat_points, regress_ranges=concat_regress_ranges) # split to per img, per", "continue else: push_dist = self.delta - torch.abs(obj_k_embedding_mean - obj_j_embedding_mean) push_loss", "regress_ranges=concat_regress_ranges) # split to per img, per level num_points =", "img_metas[img_id]['img_shape'] scale_factor = img_metas[img_id]['scale_factor'] det_bboxes = self.get_bboxes_single(cls_score_list, bbox_pred_list, mlvl_points, img_shape,", "@force_fp32(apply_to=('cls_scores', 'bbox_preds')) def get_bboxes(self, cls_scores, bbox_preds, img_metas, cfg, rescale=None): assert", "[ points[i].new_tensor(self.regress_ranges[i])[None].expand_as( points[i]) for i in range(num_levels) ] # concat", "w = featmap_size x_range = torch.arange( 0, w * stride,", "range(self.stacked_convs): chn = self.in_channels if i == 0 else self.feat_channels", "3] - gt_bboxes[:, 1] + 1) # TODO: figure out", "w * stride, stride, dtype=dtype, device=device) y_range = torch.arange( 0,", "cfg, gt_bboxes_ignore=None): assert len(cls_scores) == len(bbox_preds) == len(embedding_preds) featmap_sizes =", "assert len(cls_score) == len(self.scales) \"\"\" def __init__(self, num_classes, in_channels, feat_channels=256,", "= nn.MSELoss() def init_weights(self): for m in self.cls_convs: normal_init(m.conv, std=0.01)", "range(num_levels) ] img_shape = img_metas[img_id]['img_shape'] scale_factor = img_metas[img_id]['scale_factor'] det_bboxes =", "bbox_targets in bbox_targets_list ] # concat per level image concat_lvl_labels", "[featmap.size()[-2:] for featmap in cls_scores] mlvl_points = self.get_points(featmap_sizes, bbox_preds[0].dtype, bbox_preds[0].device)", "INF] = 0 bbox_targets = bbox_targets[range(num_points), min_area_inds] return labels, bbox_targets", "- torch.abs(obj_k_embedding_mean - obj_j_embedding_mean) push_loss += torch.max(push_dist, torch.zeros(1, device=push_dist.device)) push_loss", "3, padding=1) self.scales = nn.ModuleList([Scale(1.0) for _ in self.strides]) #", "4) xs, ys = points[:, 0], points[:, 1] xs =", "0] = INF min_area, min_area_inds = areas.min(dim=1) labels = gt_labels[min_area_inds]", "bbox_pred of different level # float to avoid overflow when", "labels_list] bbox_targets_list = [ bbox_targets.split(num_points, 0) for bbox_targets in bbox_targets_list", "flatten_embedding_preds = [ embedding_feat.permute(0, 2, 3, 1).reshape(-1, 1) for embedding_feat", "= [ embedding_feat.permute(0, 2, 3, 1).reshape(-1, 1) for embedding_feat in", "cls_scores[i][img_id].detach() for i in range(num_levels) ] bbox_pred_list = [ bbox_preds[i][img_id].detach()", "+ 1) # TODO: figure out why these two are", "condition1: inside a gt bbox inside_gt_bbox_mask = bbox_targets.min(-1)[0] > 0", "return multi_apply(self.forward_single, feats, self.scales) def forward_single(self, x, scale): cls_feat =", "forward_single(self, x, scale): cls_feat = x reg_feat = x embedding_feat", "regress_ranges[..., 1]) # if there are still more than one", "-1, self.cls_out_channels).sigmoid() bbox_pred = bbox_pred.permute(1, 2, 0).reshape(-1, 4) nms_pre =", "cls_scores ] flatten_bbox_preds = [ bbox_pred.permute(0, 2, 3, 1).reshape(-1, 4)", "padding=1, conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg, bias=self.norm_cfg is None)) self.embedding_convs.append( ConvModule( chn, self.feat_channels,", "for obj_k_embedding_mean in obj_embedding_means_list: if torch.equal(obj_j_embedding_mean, obj_k_embedding_mean): continue else: push_dist", "low-quality predictions. References: .. [1] https://arxiv.org/abs/1904.01355 Example: >>> self =", "mlvl_scores.append(scores) mlvl_bboxes = torch.cat(mlvl_bboxes) if rescale: mlvl_bboxes /= mlvl_bboxes.new_tensor(scale_factor) mlvl_scores", "num_pos > 0: pos_bbox_targets = flatten_bbox_targets[pos_inds] pos_points = flatten_points[pos_inds] pos_decoded_bbox_preds", "== len(bbox_preds) num_levels = len(cls_scores) featmap_sizes = [featmap.size()[-2:] for featmap", "obj_embedding_means_list = [] obj_embedding_means_expand_list = [] for dist_conf_mask in dist_conf_mask_list:", "mlvl_scores], dim=1) det_bboxes, det_labels = multiclass_nms( mlvl_bboxes, mlvl_scores, cfg.score_thr, cfg.nms,", "all_level_points = self.get_points(featmap_sizes, bbox_preds[0].dtype, bbox_preds[0].device) labels, bbox_targets = self.fcos_target(all_level_points, gt_bboxes,", "embedding_mean = obj_embedding_preds.sum() / obj_embedding_preds.shape[0] obj_embedding_means_list.append(embedding_mean) obj_embedding_means_expand_list.append(torch.zeros_like(obj_embedding_preds).fill_(embedding_mean)) embed() # pull", "points = torch.stack( (x.reshape(-1), y.reshape(-1)), dim=-1) + stride // 2", "bbox_preds ] flatten_embedding_preds = [ embedding_feat.permute(0, 2, 3, 1).reshape(-1, 1)", "y, x = torch.meshgrid(y_range, x_range) points = torch.stack( (x.reshape(-1), y.reshape(-1)),", "= flatten_points[pos_inds] pos_decoded_bbox_preds = distance2bbox(pos_points, pos_bbox_preds) pos_decoded_target_preds = distance2bbox(pos_points, pos_bbox_targets)", "pos_decoded_target_preds) else: loss_bbox = pos_bbox_preds.sum() push_loss = pos_bbox_preds.sum() pull_loss =", "feats, self.scales) def forward_single(self, x, scale): cls_feat = x reg_feat", "[1] https://arxiv.org/abs/1904.01355 Example: >>> self = FCOSHead(11, 7) >>> feats", "torch.zeros(num_pos, device=pos_points.device) obj_id = 0 # NOTE: get mask for", "stride, stride, dtype=dtype, device=device) y, x = torch.meshgrid(y_range, x_range) points", "# expand regress ranges to align with points expanded_regress_ranges =", "padding = mlvl_scores.new_zeros(mlvl_scores.shape[0], 1) mlvl_scores = torch.cat([padding, mlvl_scores], dim=1) det_bboxes,", "[ cls_scores[i][img_id].detach() for i in range(num_levels) ] bbox_pred_list = [", "len(bbox_preds) num_levels = len(cls_scores) featmap_sizes = [featmap.size()[-2:] for featmap in", "<= regress_ranges[..., 1]) # if there are still more than", "= bbox_pred.permute(1, 2, 0).reshape(-1, 4) nms_pre = cfg.get('nms_pre', -1) if", "points[i].new_tensor(self.regress_ranges[i])[None].expand_as( points[i]) for i in range(num_levels) ] # concat all", "] flatten_cls_scores = torch.cat(flatten_cls_scores) flatten_bbox_preds = torch.cat(flatten_bbox_preds) flatten_embedding_preds = torch.cat(flatten_embedding_preds)", "get_bboxes(self, cls_scores, bbox_preds, img_metas, cfg, rescale=None): assert len(cls_scores) == len(bbox_preds)", "> 0 and scores.shape[0] > nms_pre: max_scores, _ = scores.max(dim=1)", "with minimal area areas[inside_gt_bbox_mask == 0] = INF areas[inside_regress_range ==", "embedding_expand_means = torch.cat(obj_embedding_means_expand_list) pull_embedding = torch.cat(objs_embedding_list) pull_loss = theta *", "self.embedding_convs_num = embedding_convs_num self.strides = strides self.delta = delta self.regress_ranges", "pos_decoded_target_preds[i] mask = ((pos_decoded_target_preds == current_bbox).sum(1)==4).nonzero() instance_counter[mask] = obj_id remove[mask]", "pos_decoded_target_preds = distance2bbox(pos_points, pos_bbox_targets) pos_iou_scores = bbox_overlaps(pos_decoded_bbox_preds, pos_decoded_target_preds, is_aligned=True).clamp(min=1e-6) max_scores,", "in zip( cls_scores, bbox_preds, mlvl_points): assert cls_score.size()[-2:] == bbox_pred.size()[-2:] scores", "def get_points(self, featmap_sizes, dtype, device): \"\"\"Get points according to feature", "= distance2bbox(pos_points, pos_bbox_preds) pos_decoded_target_preds = distance2bbox(pos_points, pos_bbox_targets) pos_iou_scores = bbox_overlaps(pos_decoded_bbox_preds,", "= [ cls_score.permute(0, 2, 3, 1).reshape(-1, self.cls_out_channels) for cls_score in", "N_samples = len(dist_conf_mask_list) push_loss = 0 for obj_j_embedding_mean in obj_embedding_means_list:", "map sizes. Args: featmap_sizes (list[tuple]): Multi-level feature map sizes. dtype", "( gt_bboxes[:, 3] - gt_bboxes[:, 1] + 1) # TODO:", "Example: >>> self = FCOSHead(11, 7) >>> feats = [torch.rand(1,", "[] mlvl_scores = [] for cls_score, bbox_pred, points in zip(", "cls_scores, bbox_preds, mlvl_points, img_shape, scale_factor, cfg, rescale=False): assert len(cls_scores) ==", "of different level # float to avoid overflow when enabling", "and a centerness measure is used to supress low-quality predictions.", "\"\"\" Fully Convolutional One-Stage Object Detection head from [1]_. The", "..registry import HEADS from ..utils import ConvModule, Scale, bias_init_with_prob from", "num_gts = gt_labels.size(0) if num_gts == 0: return gt_labels.new_zeros(num_points), \\", "init_weights(self): for m in self.cls_convs: normal_init(m.conv, std=0.01) for m in", "== 0: current_bbox = pos_decoded_target_preds[i] mask = ((pos_decoded_target_preds == current_bbox).sum(1)==4).nonzero()", "used to supress low-quality predictions. References: .. [1] https://arxiv.org/abs/1904.01355 Example:", "[ embedding_feat.permute(0, 2, 3, 1).reshape(-1, 1) for embedding_feat in embedding_preds", "HEADS from ..utils import ConvModule, Scale, bias_init_with_prob from IPython import", "obj_k_embedding_mean in obj_embedding_means_list: if torch.equal(obj_j_embedding_mean, obj_k_embedding_mean): continue else: push_dist =", "assert len(cls_scores) == len(bbox_preds) == len(mlvl_points) mlvl_bboxes = [] mlvl_scores", "scale): cls_feat = x reg_feat = x embedding_feat = x", "num_gts == 0: return gt_labels.new_zeros(num_points), \\ gt_bboxes.new_zeros((num_points, 4)) areas =", "self.cls_convs = nn.ModuleList() self.reg_convs = nn.ModuleList() self.embedding_convs = nn.ModuleList() for", "(512, INF)), loss_cls=dict( type='FocalLoss', use_sigmoid=True, gamma=2.0, alpha=0.25, loss_weight=1.0), loss_bbox=dict(type='IoULoss', loss_weight=1.0),", "bbox_pred_list, mlvl_points, img_shape, scale_factor, cfg, rescale) result_list.append(det_bboxes) return result_list def", "gt_labels) num_imgs = cls_scores[0].size(0) # flatten cls_scores and bbox_preds flatten_cls_scores", "= dist_conf_mask.nonzero().reshape(-1) obj_embedding_preds = pos_embedding_preds[obj_mask_inds] objs_embedding_list.append(obj_embedding_preds) # mean value embedding_mean", "+= 1 instance_counter = instance_counter.int() obj_ids = torch.bincount(instance_counter).nonzero().int() for obj_id", "points[topk_inds, :] bbox_pred = bbox_pred[topk_inds, :] scores = scores[topk_inds, :]", "with bbox_preds flatten_points = torch.cat( [points.repeat(num_imgs, 1) for points in", "det_bboxes, det_labels def get_points(self, featmap_sizes, dtype, device): \"\"\"Get points according", "labels in labels_list])) concat_lvl_bbox_targets.append( torch.cat( [bbox_targets[i] for bbox_targets in bbox_targets_list]))", "torch.cat(labels) flatten_bbox_targets = torch.cat(bbox_targets) # repeat points to align with", "to align with bbox_preds flatten_points = torch.cat( [points.repeat(num_imgs, 1) for", "for cls_layer in self.cls_convs: cls_feat = cls_layer(cls_feat) cls_score = self.fcos_cls(cls_feat)", "bbox_pred.permute(1, 2, 0).reshape(-1, 4) nms_pre = cfg.get('nms_pre', -1) if nms_pre", "assert len(cls_scores) == len(bbox_preds) == len(embedding_preds) featmap_sizes = [featmap.size()[-2:] for", "= [] obj_embedding_means_list = [] obj_embedding_means_expand_list = [] for dist_conf_mask", "= bias_init_with_prob(0.01) normal_init(self.fcos_cls, std=0.01, bias=bias_cls) normal_init(self.fcos_reg, std=0.01) normal_init(self.embedding_cls, std=0.01) def", "nn.MSELoss() def init_weights(self): for m in self.cls_convs: normal_init(m.conv, std=0.01) for", ":] scores = scores[topk_inds, :] bboxes = distance2bbox(points, bbox_pred, max_shape=img_shape)", "get labels and bbox_targets of each image labels_list, bbox_targets_list =", "of each image. \"\"\" mlvl_points = [] for i in", "force_fp32, multi_apply, multiclass_nms, bbox_overlaps from ..builder import build_loss from ..registry", "multiclass_nms, bbox_overlaps from ..builder import build_loss from ..registry import HEADS", "3] - ys bbox_targets = torch.stack((left, top, right, bottom), -1)", "choose the one with minimal area areas[inside_gt_bbox_mask == 0] =", "0) for bbox_targets in bbox_targets_list ] # concat per level", "if remove[i] == 0: current_bbox = pos_decoded_target_preds[i] mask = ((pos_decoded_target_preds", "regress_ranges=((-1, 64), (64, 128), (128, 256), (256, 512), (512, INF)),", "TODO: figure out why these two are different # areas", "] # concat per level image concat_lvl_labels = [] concat_lvl_bbox_targets", "mmdet.core import distance2bbox, force_fp32, multi_apply, multiclass_nms, bbox_overlaps from ..builder import", "align with points expanded_regress_ranges = [ points[i].new_tensor(self.regress_ranges[i])[None].expand_as( points[i]) for i", "expanded_regress_ranges = [ points[i].new_tensor(self.regress_ranges[i])[None].expand_as( points[i]) for i in range(num_levels) ]", "labels_list = [labels.split(num_points, 0) for labels in labels_list] bbox_targets_list =", "self.pull_loss = nn.MSELoss() def init_weights(self): for m in self.cls_convs: normal_init(m.conv,", "for labels in labels_list] bbox_targets_list = [ bbox_targets.split(num_points, 0) for", "points, regress_ranges): num_points = points.size(0) num_gts = gt_labels.size(0) if num_gts", "per level image concat_lvl_labels = [] concat_lvl_bbox_targets = [] for", "= torch.cat(labels) flatten_bbox_targets = torch.cat(bbox_targets) # repeat points to align", "mlvl_scores = [] for cls_score, bbox_pred, points in zip( cls_scores,", "self.embedding_convs.append( ConvModule( chn, self.feat_channels, 3, stride=1, padding=1, conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg, bias=self.norm_cfg", "assert len(cls_scores) == len(bbox_preds) num_levels = len(cls_scores) featmap_sizes = [featmap.size()[-2:]", "gamma=2.0, alpha=0.25, loss_weight=1.0), loss_bbox=dict(type='IoULoss', loss_weight=1.0), conv_cfg=None, norm_cfg=dict(type='GN', num_groups=32, requires_grad=True)): super(EmbeddingNNmsHeadV2limited,", "regression range for each location max_regress_distance = bbox_targets.max(-1)[0] inside_regress_range =", "push loss N_samples = len(dist_conf_mask_list) push_loss = 0 for obj_j_embedding_mean", "= 1 obj_id += 1 instance_counter = instance_counter.int() obj_ids =", "torch.max(push_dist, torch.zeros(1, device=push_dist.device)) push_loss = push_loss / N_samples**2 # iou", "gt_labels, points, regress_ranges): num_points = points.size(0) num_gts = gt_labels.size(0) if", "= areas[None].expand(num_points, num_gts) areas = areas[None].repeat(num_points, 1) regress_ranges = regress_ranges[:,", "per level num_points = [center.size(0) for center in points] labels_list", "self.feat_channels self.cls_convs.append( ConvModule( chn, self.feat_channels, 3, stride=1, padding=1, conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg,", "i in range(num_levels): concat_lvl_labels.append( torch.cat([labels[i] for labels in labels_list])) concat_lvl_bbox_targets.append(", "import normal_init from mmdet.core import distance2bbox, force_fp32, multi_apply, multiclass_nms, bbox_overlaps", "points] labels_list = [labels.split(num_points, 0) for labels in labels_list] bbox_targets_list", "xs top = ys - gt_bboxes[..., 1] bottom = gt_bboxes[...,", "to per img, per level num_points = [center.size(0) for center", "= [] obj_embedding_means_expand_list = [] for dist_conf_mask in dist_conf_mask_list: obj_mask_inds", "1 obj_id += 1 instance_counter = instance_counter.int() obj_ids = torch.bincount(instance_counter).nonzero().int()", "type='FocalLoss', use_sigmoid=True, gamma=2.0, alpha=0.25, loss_weight=1.0), loss_bbox=dict(type='IoULoss', loss_weight=1.0), conv_cfg=None, norm_cfg=dict(type='GN', num_groups=32,", "push_loss = 0 for obj_j_embedding_mean in obj_embedding_means_list: for obj_k_embedding_mean in", "embedding_layer in self.embedding_convs: embedding_feat = embedding_layer(embedding_feat) embedding_pred = self.embedding_cls(embedding_feat) for", "0: current_bbox = pos_decoded_target_preds[i] mask = ((pos_decoded_target_preds == current_bbox).sum(1)==4).nonzero() instance_counter[mask]", "self.regress_ranges = regress_ranges self.loss_cls = build_loss(loss_cls) self.loss_bbox = build_loss(loss_bbox) self.conv_cfg", "bbox_preds flatten_cls_scores = [ cls_score.permute(0, 2, 3, 1).reshape(-1, self.cls_out_channels) for", "self.reg_convs: normal_init(m.conv, std=0.01) bias_cls = bias_init_with_prob(0.01) normal_init(self.fcos_cls, std=0.01, bias=bias_cls) normal_init(self.fcos_reg,", "1 embedding_expand_means = torch.cat(obj_embedding_means_expand_list) pull_embedding = torch.cat(objs_embedding_list) pull_loss = theta", "labels = gt_labels[min_area_inds] labels[min_area == INF] = 0 bbox_targets =", "= pos_bbox_preds.sum() push_loss = pos_bbox_preds.sum() pull_loss = pos_bbox_preds.sum() return dict(", "= max_scores.topk(nms_pre) points = points[topk_inds, :] bbox_pred = bbox_pred[topk_inds, :]", "self.fcos_cls(cls_feat) for embedding_layer in self.embedding_convs: embedding_feat = embedding_layer(embedding_feat) embedding_pred =", "= distance2bbox(points, bbox_pred, max_shape=img_shape) mlvl_bboxes.append(bboxes) mlvl_scores.append(scores) mlvl_bboxes = torch.cat(mlvl_bboxes) if", "1] bottom = gt_bboxes[..., 3] - ys bbox_targets = torch.stack((left,", "num_classes, in_channels, feat_channels=256, stacked_convs=4, embedding_convs_num=2, strides=(4, 8, 16, 32, 64),", "= gt_labels.size(0) if num_gts == 0: return gt_labels.new_zeros(num_points), \\ gt_bboxes.new_zeros((num_points,", "import torch import torch.nn as nn from mmcv.cnn import normal_init", "1) for points in all_level_points]) pos_inds = flatten_labels.nonzero().reshape(-1) num_pos =", "The FCOS head does not use anchor boxes. Instead bounding", "= strides self.delta = delta self.regress_ranges = regress_ranges self.loss_cls =", "dtype, device)) return mlvl_points def get_points_single(self, featmap_size, stride, dtype, device):", "and bbox_targets of each image labels_list, bbox_targets_list = multi_apply( self.fcos_target_single,", "embed() # pull loss theta = 1 embedding_expand_means = torch.cat(obj_embedding_means_expand_list)", "device): h, w = featmap_size x_range = torch.arange( 0, w", "= FCOSHead(11, 7) >>> feats = [torch.rand(1, 7, s, s)", "0 else self.feat_channels self.cls_convs.append( ConvModule( chn, self.feat_channels, 3, stride=1, padding=1,", "= [center.size(0) for center in points] labels_list = [labels.split(num_points, 0)", "for s in [4, 8, 16, 32, 64]] >>> cls_score,", "x_range) points = torch.stack( (x.reshape(-1), y.reshape(-1)), dim=-1) + stride //", "in [4, 8, 16, 32, 64]] >>> cls_score, bbox_pred, centerness", "rescale: mlvl_bboxes /= mlvl_bboxes.new_tensor(scale_factor) mlvl_scores = torch.cat(mlvl_scores) padding = mlvl_scores.new_zeros(mlvl_scores.shape[0],", "multi_apply( self.fcos_target_single, gt_bboxes_list, gt_labels_list, points=concat_points, regress_ranges=concat_regress_ranges) # split to per", "self.cls_out_channels, 3, padding=1) self.fcos_reg = nn.Conv2d(self.feat_channels, 4, 3, padding=1) self.embedding_cls", "areas.min(dim=1) labels = gt_labels[min_area_inds] labels[min_area == INF] = 0 bbox_targets", "mlvl_points.append( self.get_points_single(featmap_sizes[i], self.strides[i], dtype, device)) return mlvl_points def get_points_single(self, featmap_size,", "max_scores.topk(nms_pre) points = points[topk_inds, :] bbox_pred = bbox_pred[topk_inds, :] scores", "bias=bias_cls) normal_init(self.fcos_reg, std=0.01) normal_init(self.embedding_cls, std=0.01) def forward(self, feats): return multi_apply(self.forward_single,", "img_metas, cfg, gt_bboxes_ignore=None): assert len(cls_scores) == len(bbox_preds) == len(embedding_preds) featmap_sizes", "normal_init(self.fcos_reg, std=0.01) normal_init(self.embedding_cls, std=0.01) def forward(self, feats): return multi_apply(self.forward_single, feats,", "of points. device (torch.device): Device of points. Returns: tuple: points", "flatten cls_scores and bbox_preds flatten_cls_scores = [ cls_score.permute(0, 2, 3,", "ys = points[:, 0], points[:, 1] xs = xs[:, None].expand(num_points,", "64), (64, 128), (128, 256), (256, 512), (512, INF)), loss_cls=dict(", "regress_ranges[:, None, :].expand( num_points, num_gts, 2) gt_bboxes = gt_bboxes[None].expand(num_points, num_gts,", "= cls_layer(cls_feat) cls_score = self.fcos_cls(cls_feat) for embedding_layer in self.embedding_convs: embedding_feat", "len(self.regress_ranges) num_levels = len(points) # expand regress ranges to align", "= self.loss_bbox( pos_decoded_bbox_preds, pos_decoded_target_preds) else: loss_bbox = pos_bbox_preds.sum() push_loss =", "def forward_single(self, x, scale): cls_feat = x reg_feat = x", "Fully Convolutional One-Stage Object Detection head from [1]_. The FCOS", "to avoid overflow when enabling FP16 bbox_pred = scale(self.fcos_reg(reg_feat)).float().exp() return", "* stride, stride, dtype=dtype, device=device) y, x = torch.meshgrid(y_range, x_range)", "for each obj objs_embedding_list = [] obj_embedding_means_list = [] obj_embedding_means_expand_list", "each obj objs_embedding_list = [] obj_embedding_means_list = [] obj_embedding_means_expand_list =", "/= mlvl_bboxes.new_tensor(scale_factor) mlvl_scores = torch.cat(mlvl_scores) padding = mlvl_scores.new_zeros(mlvl_scores.shape[0], 1) mlvl_scores", "x reg_feat = x embedding_feat = x for cls_layer in", "num_gts) areas = areas[None].repeat(num_points, 1) regress_ranges = regress_ranges[:, None, :].expand(", "all_level_points]) pos_inds = flatten_labels.nonzero().reshape(-1) num_pos = len(pos_inds) loss_cls = self.loss_cls(", "for points in all_level_points]) pos_inds = flatten_labels.nonzero().reshape(-1) num_pos = len(pos_inds)", "= self.delta - torch.abs(obj_k_embedding_mean - obj_j_embedding_mean) push_loss += torch.max(push_dist, torch.zeros(1,", "dist_conf_mask_list = [] # generate instance levels index instance_counter =", "4) nms_pre = cfg.get('nms_pre', -1) if nms_pre > 0 and", "= scores.max(dim=1) _, topk_inds = max_scores.topk(nms_pre) points = points[topk_inds, :]", "0) for labels in labels_list] bbox_targets_list = [ bbox_targets.split(num_points, 0)", "xs - gt_bboxes[..., 0] right = gt_bboxes[..., 2] - xs", "featmap_sizes = [featmap.size()[-2:] for featmap in cls_scores] all_level_points = self.get_points(featmap_sizes,", "reg_feat = x embedding_feat = x for cls_layer in self.cls_convs:", "in range(len(pos_decoded_target_preds)): if remove[i] == 0: current_bbox = pos_decoded_target_preds[i] mask", "= areas.min(dim=1) labels = gt_labels[min_area_inds] labels[min_area == INF] = 0", "cls_score, bbox_pred, centerness = self.forward(feats) >>> assert len(cls_score) == len(self.scales)", "- 1 self.in_channels = in_channels self.feat_channels = feat_channels self.stacked_convs =", "class EmbeddingNNmsHeadV2limited(nn.Module): \"\"\" Fully Convolutional One-Stage Object Detection head from", "as nn from mmcv.cnn import normal_init from mmdet.core import distance2bbox,", "cfg, rescale=None): assert len(cls_scores) == len(bbox_preds) num_levels = len(cls_scores) featmap_sizes", "feats = [torch.rand(1, 7, s, s) for s in [4,", "self.in_channels = in_channels self.feat_channels = feat_channels self.stacked_convs = stacked_convs self.embedding_convs_num", "head from [1]_. The FCOS head does not use anchor", "flatten_points = torch.cat( [points.repeat(num_imgs, 1) for points in all_level_points]) pos_inds", "torch import torch.nn as nn from mmcv.cnn import normal_init from", "ranges concat_regress_ranges = torch.cat(expanded_regress_ranges, dim=0) concat_points = torch.cat(points, dim=0) #", "# areas = areas[None].expand(num_points, num_gts) areas = areas[None].repeat(num_points, 1) regress_ranges", "Opt for each obj objs_embedding_list = [] obj_embedding_means_list = []", "dim=-1) + stride // 2 return points def fcos_target(self, points,", "= len(dist_conf_mask_list) push_loss = 0 for obj_j_embedding_mean in obj_embedding_means_list: for", "obj_id in obj_ids: dist_conf_mask_list.append((instance_counter==obj_id).float()) # Opt for each obj objs_embedding_list", "from mmcv.cnn import normal_init from mmdet.core import distance2bbox, force_fp32, multi_apply,", "== len(bbox_preds) == len(embedding_preds) featmap_sizes = [featmap.size()[-2:] for featmap in", "= build_loss(loss_bbox) self.conv_cfg = conv_cfg self.norm_cfg = norm_cfg self.fp16_enabled =", "= flatten_embedding_preds[pos_inds] # Instance level op dist_conf_mask_list = [] #", "self.conv_cfg = conv_cfg self.norm_cfg = norm_cfg self.fp16_enabled = False self._init_layers()", "# avoid num_pos is 0 pos_bbox_preds = flatten_bbox_preds[pos_inds] if num_pos", "nn.ModuleList() for i in range(self.stacked_convs): chn = self.in_channels if i", "embedding_convs_num self.strides = strides self.delta = delta self.regress_ranges = regress_ranges", "self.scales = nn.ModuleList([Scale(1.0) for _ in self.strides]) # Pull and", "= bbox_pred[topk_inds, :] scores = scores[topk_inds, :] bboxes = distance2bbox(points,", "torch.nn as nn from mmcv.cnn import normal_init from mmdet.core import", "feature map sizes. Args: featmap_sizes (list[tuple]): Multi-level feature map sizes.", "] # concat all levels points and regress ranges concat_regress_ranges", "= nn.ModuleList() self.reg_convs = nn.ModuleList() self.embedding_convs = nn.ModuleList() for i", "cls_score.permute(1, 2, 0).reshape( -1, self.cls_out_channels).sigmoid() bbox_pred = bbox_pred.permute(1, 2, 0).reshape(-1,", "mlvl_bboxes.append(bboxes) mlvl_scores.append(scores) mlvl_bboxes = torch.cat(mlvl_bboxes) if rescale: mlvl_bboxes /= mlvl_bboxes.new_tensor(scale_factor)", "= torch.cat(obj_embedding_means_expand_list) pull_embedding = torch.cat(objs_embedding_list) pull_loss = theta * self.pull_loss(pull_embedding,", "= torch.cat(points, dim=0) # get labels and bbox_targets of each", "scores = cls_score.permute(1, 2, 0).reshape( -1, self.cls_out_channels).sigmoid() bbox_pred = bbox_pred.permute(1,", "nms_pre > 0 and scores.shape[0] > nms_pre: max_scores, _ =", "1) # TODO: figure out why these two are different", "= pos_decoded_target_preds[i] mask = ((pos_decoded_target_preds == current_bbox).sum(1)==4).nonzero() instance_counter[mask] = obj_id", "/ N_samples**2 # iou loss loss_bbox = self.loss_bbox( pos_decoded_bbox_preds, pos_decoded_target_preds)", "avoid overflow when enabling FP16 bbox_pred = scale(self.fcos_reg(reg_feat)).float().exp() return cls_score,", "in dist_conf_mask_list: obj_mask_inds = dist_conf_mask.nonzero().reshape(-1) obj_embedding_preds = pos_embedding_preds[obj_mask_inds] objs_embedding_list.append(obj_embedding_preds) #", "0: pos_bbox_targets = flatten_bbox_targets[pos_inds] pos_points = flatten_points[pos_inds] pos_decoded_bbox_preds = distance2bbox(pos_points,", "s) for s in [4, 8, 16, 32, 64]] >>>", "for i in range(len(featmap_sizes)): mlvl_points.append( self.get_points_single(featmap_sizes[i], self.strides[i], dtype, device)) return", "cfg.max_per_img) return det_bboxes, det_labels def get_points(self, featmap_sizes, dtype, device): \"\"\"Get", "= [ bbox_targets.split(num_points, 0) for bbox_targets in bbox_targets_list ] #", "= [] # generate instance levels index instance_counter = torch.zeros(num_pos,", "= INF min_area, min_area_inds = areas.min(dim=1) labels = gt_labels[min_area_inds] labels[min_area", ":] bboxes = distance2bbox(points, bbox_pred, max_shape=img_shape) mlvl_bboxes.append(bboxes) mlvl_scores.append(scores) mlvl_bboxes =", "References: .. [1] https://arxiv.org/abs/1904.01355 Example: >>> self = FCOSHead(11, 7)", "= nn.ModuleList([Scale(1.0) for _ in self.strides]) # Pull and Push", "min_area_inds = areas.min(dim=1) labels = gt_labels[min_area_inds] labels[min_area == INF] =", "loss_weight=1.0), conv_cfg=None, norm_cfg=dict(type='GN', num_groups=32, requires_grad=True)): super(EmbeddingNNmsHeadV2limited, self).__init__() self.num_classes = num_classes", "# scale the bbox_pred of different level # float to", "points[:, 0], points[:, 1] xs = xs[:, None].expand(num_points, num_gts) ys", "zip( cls_scores, bbox_preds, mlvl_points): assert cls_score.size()[-2:] == bbox_pred.size()[-2:] scores =", "there are still more than one objects for a location,", "3, padding=1) self.embedding_cls = nn.Conv2d(self.feat_channels, 1, 3, padding=1) self.scales =", "are still more than one objects for a location, #", "m in self.reg_convs: normal_init(m.conv, std=0.01) bias_cls = bias_init_with_prob(0.01) normal_init(self.fcos_cls, std=0.01,", "max_inds = flatten_cls_scores.sigmoid().max(1) pos_embedding_preds = flatten_embedding_preds[pos_inds] # Instance level op", "cfg.get('nms_pre', -1) if nms_pre > 0 and scores.shape[0] > nms_pre:", "embedding_pred @force_fp32(apply_to=('cls_scores', 'bbox_preds')) def loss(self, cls_scores, bbox_preds, embedding_preds, gt_bboxes, gt_labels,", "import torch.nn as nn from mmcv.cnn import normal_init from mmdet.core", "[] for dist_conf_mask in dist_conf_mask_list: obj_mask_inds = dist_conf_mask.nonzero().reshape(-1) obj_embedding_preds =", "each image labels_list, bbox_targets_list = multi_apply( self.fcos_target_single, gt_bboxes_list, gt_labels_list, points=concat_points,", "levels index instance_counter = torch.zeros(num_pos, device=pos_points.device) remove = torch.zeros(num_pos, device=pos_points.device)", "# mean value embedding_mean = obj_embedding_preds.sum() / obj_embedding_preds.shape[0] obj_embedding_means_list.append(embedding_mean) obj_embedding_means_expand_list.append(torch.zeros_like(obj_embedding_preds).fill_(embedding_mean))", "range for each location max_regress_distance = bbox_targets.max(-1)[0] inside_regress_range = (", "m in self.cls_convs: normal_init(m.conv, std=0.01) for m in self.reg_convs: normal_init(m.conv,", "labels, bbox_targets = self.fcos_target(all_level_points, gt_bboxes, gt_labels) num_imgs = cls_scores[0].size(0) #", "left = xs - gt_bboxes[..., 0] right = gt_bboxes[..., 2]", "in range(num_levels): concat_lvl_labels.append( torch.cat([labels[i] for labels in labels_list])) concat_lvl_bbox_targets.append( torch.cat(", "max_scores, _ = scores.max(dim=1) _, topk_inds = max_scores.topk(nms_pre) points =", "= [torch.rand(1, 7, s, s) for s in [4, 8,", "self).__init__() self.num_classes = num_classes self.cls_out_channels = num_classes - 1 self.in_channels", "align with bbox_preds flatten_points = torch.cat( [points.repeat(num_imgs, 1) for points", "pos_bbox_preds) pos_decoded_target_preds = distance2bbox(pos_points, pos_bbox_targets) pos_iou_scores = bbox_overlaps(pos_decoded_bbox_preds, pos_decoded_target_preds, is_aligned=True).clamp(min=1e-6)", "0] = INF areas[inside_regress_range == 0] = INF min_area, min_area_inds", "obj_embedding_means_list.append(embedding_mean) obj_embedding_means_expand_list.append(torch.zeros_like(obj_embedding_preds).fill_(embedding_mean)) embed() # pull loss theta = 1 embedding_expand_means", "push_loss = push_loss / N_samples**2 # iou loss loss_bbox =", "self._init_layers() def _init_layers(self): self.cls_convs = nn.ModuleList() self.reg_convs = nn.ModuleList() self.embedding_convs", "num_gts) left = xs - gt_bboxes[..., 0] right = gt_bboxes[...,", "FP16 bbox_pred = scale(self.fcos_reg(reg_feat)).float().exp() return cls_score, bbox_pred, embedding_pred @force_fp32(apply_to=('cls_scores', 'bbox_preds'))", "in obj_embedding_means_list: if torch.equal(obj_j_embedding_mean, obj_k_embedding_mean): continue else: push_dist = self.delta", "theta * self.pull_loss(pull_embedding, embedding_expand_means) # push loss N_samples = len(dist_conf_mask_list)", "== len(self.scales) \"\"\" def __init__(self, num_classes, in_channels, feat_channels=256, stacked_convs=4, embedding_convs_num=2,", "bbox_preds, embedding_preds, gt_bboxes, gt_labels, img_metas, cfg, gt_bboxes_ignore=None): assert len(cls_scores) ==", "# flatten cls_scores and bbox_preds flatten_cls_scores = [ cls_score.permute(0, 2,", "torch.cat(objs_embedding_list) pull_loss = theta * self.pull_loss(pull_embedding, embedding_expand_means) # push loss", "torch.cat(points, dim=0) # get labels and bbox_targets of each image", "multi_apply(self.forward_single, feats, self.scales) def forward_single(self, x, scale): cls_feat = x", "= 1 embedding_expand_means = torch.cat(obj_embedding_means_expand_list) pull_embedding = torch.cat(objs_embedding_list) pull_loss =", "2 return points def fcos_target(self, points, gt_bboxes_list, gt_labels_list): assert len(points)", "cls_score, bbox_pred, points in zip( cls_scores, bbox_preds, mlvl_points): assert cls_score.size()[-2:]", "cls_scores and bbox_preds flatten_cls_scores = [ cls_score.permute(0, 2, 3, 1).reshape(-1,", "concat per level image concat_lvl_labels = [] concat_lvl_bbox_targets = []", "x embedding_feat = x for cls_layer in self.cls_convs: cls_feat =", "labels_list, bbox_targets_list = multi_apply( self.fcos_target_single, gt_bboxes_list, gt_labels_list, points=concat_points, regress_ranges=concat_regress_ranges) #", "# float to avoid overflow when enabling FP16 bbox_pred =", "= self.get_bboxes_single(cls_score_list, bbox_pred_list, mlvl_points, img_shape, scale_factor, cfg, rescale) result_list.append(det_bboxes) return", "chn = self.in_channels if i == 0 else self.feat_channels self.cls_convs.append(", "num_pos = len(pos_inds) loss_cls = self.loss_cls( flatten_cls_scores, flatten_labels, avg_factor=num_pos +", "def get_points_single(self, featmap_size, stride, dtype, device): h, w = featmap_size", "obj_id remove[mask] = 1 obj_id += 1 instance_counter = instance_counter.int()", "fcos_target(self, points, gt_bboxes_list, gt_labels_list): assert len(points) == len(self.regress_ranges) num_levels =", "= self.embedding_cls(embedding_feat) for reg_layer in self.reg_convs: reg_feat = reg_layer(reg_feat) #", "in self.cls_convs: cls_feat = cls_layer(cls_feat) cls_score = self.fcos_cls(cls_feat) for embedding_layer", "= self.get_points(featmap_sizes, bbox_preds[0].dtype, bbox_preds[0].device) result_list = [] for img_id in", "torch.stack((left, top, right, bottom), -1) # condition1: inside a gt", "embedding_layer(embedding_feat) embedding_pred = self.embedding_cls(embedding_feat) for reg_layer in self.reg_convs: reg_feat =", "head does not use anchor boxes. Instead bounding boxes are", "points of each image. \"\"\" mlvl_points = [] for i", "bbox_preds, mlvl_points, img_shape, scale_factor, cfg, rescale=False): assert len(cls_scores) == len(bbox_preds)", "scale the bbox_pred of different level # float to avoid", "* ( gt_bboxes[:, 3] - gt_bboxes[:, 1] + 1) #", ":] bbox_pred = bbox_pred[topk_inds, :] scores = scores[topk_inds, :] bboxes", "= bbox_targets.min(-1)[0] > 0 # condition2: limit the regression range", "normal_init(m.conv, std=0.01) for m in self.reg_convs: normal_init(m.conv, std=0.01) bias_cls =", "= ys - gt_bboxes[..., 1] bottom = gt_bboxes[..., 3] -", "1 self.in_channels = in_channels self.feat_channels = feat_channels self.stacked_convs = stacked_convs", "# iou loss loss_bbox = self.loss_bbox( pos_decoded_bbox_preds, pos_decoded_target_preds) else: loss_bbox", "flatten_bbox_preds = [ bbox_pred.permute(0, 2, 3, 1).reshape(-1, 4) for bbox_pred", "(128, 256), (256, 512), (512, INF)), loss_cls=dict( type='FocalLoss', use_sigmoid=True, gamma=2.0,", "strides self.delta = delta self.regress_ranges = regress_ranges self.loss_cls = build_loss(loss_cls)", "# generate instance levels index instance_counter = torch.zeros(num_pos, device=pos_points.device) remove", "== len(embedding_preds) featmap_sizes = [featmap.size()[-2:] for featmap in cls_scores] all_level_points", "for i in range(num_levels) ] # concat all levels points", "get_points_single(self, featmap_size, stride, dtype, device): h, w = featmap_size x_range", "gt_bboxes[..., 0] right = gt_bboxes[..., 2] - xs top =", "== 0] = INF min_area, min_area_inds = areas.min(dim=1) labels =", "len(bbox_preds) == len(embedding_preds) featmap_sizes = [featmap.size()[-2:] for featmap in cls_scores]", "featmap_sizes = [featmap.size()[-2:] for featmap in cls_scores] mlvl_points = self.get_points(featmap_sizes,", "pos_bbox_targets = flatten_bbox_targets[pos_inds] pos_points = flatten_points[pos_inds] pos_decoded_bbox_preds = distance2bbox(pos_points, pos_bbox_preds)", "scale_factor = img_metas[img_id]['scale_factor'] det_bboxes = self.get_bboxes_single(cls_score_list, bbox_pred_list, mlvl_points, img_shape, scale_factor,", "anchor boxes. Instead bounding boxes are predicted at each pixel", "level num_points = [center.size(0) for center in points] labels_list =", "nn.ModuleList() self.reg_convs = nn.ModuleList() self.embedding_convs = nn.ModuleList() for i in", "h * stride, stride, dtype=dtype, device=device) y, x = torch.meshgrid(y_range,", "dtype=dtype, device=device) y_range = torch.arange( 0, h * stride, stride,", "= INF areas[inside_regress_range == 0] = INF min_area, min_area_inds =", "= xs[:, None].expand(num_points, num_gts) ys = ys[:, None].expand(num_points, num_gts) left", "..utils import ConvModule, Scale, bias_init_with_prob from IPython import embed INF", "torch.abs(obj_k_embedding_mean - obj_j_embedding_mean) push_loss += torch.max(push_dist, torch.zeros(1, device=push_dist.device)) push_loss =", "bbox_preds[0].dtype, bbox_preds[0].device) labels, bbox_targets = self.fcos_target(all_level_points, gt_bboxes, gt_labels) num_imgs =", "flatten_cls_scores = torch.cat(flatten_cls_scores) flatten_bbox_preds = torch.cat(flatten_bbox_preds) flatten_embedding_preds = torch.cat(flatten_embedding_preds) flatten_labels", "[] for cls_score, bbox_pred, points in zip( cls_scores, bbox_preds, mlvl_points):", "0], points[:, 1] xs = xs[:, None].expand(num_points, num_gts) ys =", "torch.arange( 0, h * stride, stride, dtype=dtype, device=device) y, x", "in range(self.stacked_convs): chn = self.in_channels if i == 0 else", "padding=1, conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg, bias=self.norm_cfg is None)) self.fcos_cls = nn.Conv2d( self.feat_channels,", "torch.cat(expanded_regress_ranges, dim=0) concat_points = torch.cat(points, dim=0) # get labels and", "embedding_convs_num=2, strides=(4, 8, 16, 32, 64), delta=2.0, regress_ranges=((-1, 64), (64,", "0: return gt_labels.new_zeros(num_points), \\ gt_bboxes.new_zeros((num_points, 4)) areas = (gt_bboxes[:, 2]", "None].expand(num_points, num_gts) left = xs - gt_bboxes[..., 0] right =", "mlvl_bboxes /= mlvl_bboxes.new_tensor(scale_factor) mlvl_scores = torch.cat(mlvl_scores) padding = mlvl_scores.new_zeros(mlvl_scores.shape[0], 1)", "scores.shape[0] > nms_pre: max_scores, _ = scores.max(dim=1) _, topk_inds =", "self.feat_channels, self.cls_out_channels, 3, padding=1) self.fcos_reg = nn.Conv2d(self.feat_channels, 4, 3, padding=1)", "# split to per img, per level num_points = [center.size(0)", "obj_embedding_means_list: if torch.equal(obj_j_embedding_mean, obj_k_embedding_mean): continue else: push_dist = self.delta -", "dist_conf_mask_list: obj_mask_inds = dist_conf_mask.nonzero().reshape(-1) obj_embedding_preds = pos_embedding_preds[obj_mask_inds] objs_embedding_list.append(obj_embedding_preds) # mean", "obj_k_embedding_mean): continue else: push_dist = self.delta - torch.abs(obj_k_embedding_mean - obj_j_embedding_mean)", "cls_scores, bbox_preds, embedding_preds, gt_bboxes, gt_labels, img_metas, cfg, gt_bboxes_ignore=None): assert len(cls_scores)", "gt_labels, img_metas, cfg, gt_bboxes_ignore=None): assert len(cls_scores) == len(bbox_preds) == len(embedding_preds)", "1).reshape(-1, self.cls_out_channels) for cls_score in cls_scores ] flatten_bbox_preds = [", "8, 16, 32, 64]] >>> cls_score, bbox_pred, centerness = self.forward(feats)", "= ((pos_decoded_target_preds == current_bbox).sum(1)==4).nonzero() instance_counter[mask] = obj_id remove[mask] = 1", "0 for obj_j_embedding_mean in obj_embedding_means_list: for obj_k_embedding_mean in obj_embedding_means_list: if", "num_gts, 4) xs, ys = points[:, 0], points[:, 1] xs", "2, 0).reshape(-1, 4) nms_pre = cfg.get('nms_pre', -1) if nms_pre >", "= self.loss_cls( flatten_cls_scores, flatten_labels, avg_factor=num_pos + num_imgs) # avoid num_pos", "bbox_preds, img_metas, cfg, rescale=None): assert len(cls_scores) == len(bbox_preds) num_levels =", "i in range(num_levels) ] # concat all levels points and", "i in range(len(featmap_sizes)): mlvl_points.append( self.get_points_single(featmap_sizes[i], self.strides[i], dtype, device)) return mlvl_points", "level op dist_conf_mask_list = [] # generate instance levels index", "y.reshape(-1)), dim=-1) + stride // 2 return points def fcos_target(self,", "self.get_points_single(featmap_sizes[i], self.strides[i], dtype, device)) return mlvl_points def get_points_single(self, featmap_size, stride,", "= areas[None].repeat(num_points, 1) regress_ranges = regress_ranges[:, None, :].expand( num_points, num_gts,", "location, # we choose the one with minimal area areas[inside_gt_bbox_mask", "import HEADS from ..utils import ConvModule, Scale, bias_init_with_prob from IPython", "max_regress_distance >= regress_ranges[..., 0]) & ( max_regress_distance <= regress_ranges[..., 1])", "in range(len(img_metas)): cls_score_list = [ cls_scores[i][img_id].detach() for i in range(num_levels)", "import distance2bbox, force_fp32, multi_apply, multiclass_nms, bbox_overlaps from ..builder import build_loss", "mlvl_bboxes = [] mlvl_scores = [] for cls_score, bbox_pred, points", "torch.cat( [points.repeat(num_imgs, 1) for points in all_level_points]) pos_inds = flatten_labels.nonzero().reshape(-1)", "from mmdet.core import distance2bbox, force_fp32, multi_apply, multiclass_nms, bbox_overlaps from ..builder", "Instead bounding boxes are predicted at each pixel and a", "level image concat_lvl_labels = [] concat_lvl_bbox_targets = [] for i", "from ..utils import ConvModule, Scale, bias_init_with_prob from IPython import embed", "Pull and Push loss self.pull_loss = nn.MSELoss() def init_weights(self): for", "more than one objects for a location, # we choose", "points=concat_points, regress_ranges=concat_regress_ranges) # split to per img, per level num_points", "bias=self.norm_cfg is None)) self.fcos_cls = nn.Conv2d( self.feat_channels, self.cls_out_channels, 3, padding=1)", "bbox_preds flatten_points = torch.cat( [points.repeat(num_imgs, 1) for points in all_level_points])", "== INF] = 0 bbox_targets = bbox_targets[range(num_points), min_area_inds] return labels,", "different level # float to avoid overflow when enabling FP16", "top = ys - gt_bboxes[..., 1] bottom = gt_bboxes[..., 3]", "pos_inds = flatten_labels.nonzero().reshape(-1) num_pos = len(pos_inds) loss_cls = self.loss_cls( flatten_cls_scores,", "[ cls_score.permute(0, 2, 3, 1).reshape(-1, self.cls_out_channels) for cls_score in cls_scores", "embedding_preds, gt_bboxes, gt_labels, img_metas, cfg, gt_bboxes_ignore=None): assert len(cls_scores) == len(bbox_preds)", "bbox_overlaps(pos_decoded_bbox_preds, pos_decoded_target_preds, is_aligned=True).clamp(min=1e-6) max_scores, max_inds = flatten_cls_scores.sigmoid().max(1) pos_embedding_preds = flatten_embedding_preds[pos_inds]", "bias_init_with_prob from IPython import embed INF = 1e8 @HEADS.register_module class", "[ bbox_targets.split(num_points, 0) for bbox_targets in bbox_targets_list ] # concat", "(x.reshape(-1), y.reshape(-1)), dim=-1) + stride // 2 return points def", "loss_cls=dict( type='FocalLoss', use_sigmoid=True, gamma=2.0, alpha=0.25, loss_weight=1.0), loss_bbox=dict(type='IoULoss', loss_weight=1.0), conv_cfg=None, norm_cfg=dict(type='GN',", "mlvl_scores.new_zeros(mlvl_scores.shape[0], 1) mlvl_scores = torch.cat([padding, mlvl_scores], dim=1) det_bboxes, det_labels =", "pos_bbox_preds.sum() pull_loss = pos_bbox_preds.sum() return dict( loss_cls=loss_cls, loss_bbox=loss_bbox, push_loss=push_loss, pull_loss=pull_loss)", "bbox_overlaps from ..builder import build_loss from ..registry import HEADS from", "loss_bbox=dict(type='IoULoss', loss_weight=1.0), conv_cfg=None, norm_cfg=dict(type='GN', num_groups=32, requires_grad=True)): super(EmbeddingNNmsHeadV2limited, self).__init__() self.num_classes =", "boxes are predicted at each pixel and a centerness measure", "cls_score in cls_scores ] flatten_bbox_preds = [ bbox_pred.permute(0, 2, 3,", "= 0 for obj_j_embedding_mean in obj_embedding_means_list: for obj_k_embedding_mean in obj_embedding_means_list:", "1) for embedding_feat in embedding_preds ] flatten_cls_scores = torch.cat(flatten_cls_scores) flatten_bbox_preds", "self.embedding_convs = nn.ModuleList() for i in range(self.stacked_convs): chn = self.in_channels", "cls_feat = cls_layer(cls_feat) cls_score = self.fcos_cls(cls_feat) for embedding_layer in self.embedding_convs:", "self.strides = strides self.delta = delta self.regress_ranges = regress_ranges self.loss_cls", "x_range = torch.arange( 0, w * stride, stride, dtype=dtype, device=device)", "bottom = gt_bboxes[..., 3] - ys bbox_targets = torch.stack((left, top,", "[ bbox_pred.permute(0, 2, 3, 1).reshape(-1, 4) for bbox_pred in bbox_preds", "i == 0 else self.feat_channels self.cls_convs.append( ConvModule( chn, self.feat_channels, 3,", "self.cls_convs.append( ConvModule( chn, self.feat_channels, 3, stride=1, padding=1, conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg, bias=self.norm_cfg", "cls_score_list = [ cls_scores[i][img_id].detach() for i in range(num_levels) ] bbox_pred_list", "(torch.dtype): Type of points. device (torch.device): Device of points. Returns:", "assert cls_score.size()[-2:] == bbox_pred.size()[-2:] scores = cls_score.permute(1, 2, 0).reshape( -1,", "condition2: limit the regression range for each location max_regress_distance =", "len(pos_inds) loss_cls = self.loss_cls( flatten_cls_scores, flatten_labels, avg_factor=num_pos + num_imgs) #", "in self.cls_convs: normal_init(m.conv, std=0.01) for m in self.reg_convs: normal_init(m.conv, std=0.01)", "det_labels def get_points(self, featmap_sizes, dtype, device): \"\"\"Get points according to", "= flatten_bbox_targets[pos_inds] pos_points = flatten_points[pos_inds] pos_decoded_bbox_preds = distance2bbox(pos_points, pos_bbox_preds) pos_decoded_target_preds", "labels in labels_list] bbox_targets_list = [ bbox_targets.split(num_points, 0) for bbox_targets", "-1) if nms_pre > 0 and scores.shape[0] > nms_pre: max_scores,", "in cls_scores] mlvl_points = self.get_points(featmap_sizes, bbox_preds[0].dtype, bbox_preds[0].device) result_list = []", "= [ points[i].new_tensor(self.regress_ranges[i])[None].expand_as( points[i]) for i in range(num_levels) ] #" ]
[ "__tablename__ = 'photos' id = db.Column(db.Integer, primary_key=True) spotname = db.Column(db.Text)", "source_id = db.Column(db.Text) latitude = db.Column(db.Float) longitude = db.Column(db.Float) tags", "Search(db.Model): __tablename__ = 'spots' id = db.Column(db.Integer, primary_key=True) search_string =", "db.Column(db.Integer) username = db.Column(db.Text) photo_url = db.Column(db.Text) search_id = db.Column(db.ForeignKey(Search.id),nullable=False)", "db.Column(db.Integer, primary_key=True) search_string = db.Column(db.Text) lat = db.Column(db.Float) lon =", "from . import db from sqlalchemy.dialects.mysql import LONGTEXT class Search(db.Model):", "'photos' id = db.Column(db.Integer, primary_key=True) spotname = db.Column(db.Text) source_id =", "db.Column(db.Text) latitude = db.Column(db.Float) longitude = db.Column(db.Float) tags = db.Column(db.Text)", "db.Column(db.Integer) comments = db.Column(db.Integer) username = db.Column(db.Text) photo_url = db.Column(db.Text)", "longitude = db.Column(db.Float) tags = db.Column(db.Text) views = db.Column(db.Integer) favourites", "db.Column(db.Text) json_result = db.Column(LONGTEXT) class Photo(db.Model): __tablename__ = 'photos' id", ". import db from sqlalchemy.dialects.mysql import LONGTEXT class Search(db.Model): __tablename__", "db.Column(db.Float) location_name = db.Column(db.Text) json_result = db.Column(LONGTEXT) class Photo(db.Model): __tablename__", "db.Column(LONGTEXT) class Photo(db.Model): __tablename__ = 'photos' id = db.Column(db.Integer, primary_key=True)", "class Photo(db.Model): __tablename__ = 'photos' id = db.Column(db.Integer, primary_key=True) spotname", "db.Column(db.Text) source_id = db.Column(db.Text) latitude = db.Column(db.Float) longitude = db.Column(db.Float)", "db.Column(db.Float) longitude = db.Column(db.Float) tags = db.Column(db.Text) views = db.Column(db.Integer)", "= db.Column(db.Integer) username = db.Column(db.Text) photo_url = db.Column(db.Text) search_id =", "id = db.Column(db.Integer, primary_key=True) search_string = db.Column(db.Text) lat = db.Column(db.Float)", "json_result = db.Column(LONGTEXT) class Photo(db.Model): __tablename__ = 'photos' id =", "= db.Column(db.Float) lon = db.Column(db.Float) location_name = db.Column(db.Text) json_result =", "db from sqlalchemy.dialects.mysql import LONGTEXT class Search(db.Model): __tablename__ = 'spots'", "__tablename__ = 'spots' id = db.Column(db.Integer, primary_key=True) search_string = db.Column(db.Text)", "= db.Column(db.Text) json_result = db.Column(LONGTEXT) class Photo(db.Model): __tablename__ = 'photos'", "db.Column(db.Float) tags = db.Column(db.Text) views = db.Column(db.Integer) favourites = db.Column(db.Integer)", "'spots' id = db.Column(db.Integer, primary_key=True) search_string = db.Column(db.Text) lat =", "lat = db.Column(db.Float) lon = db.Column(db.Float) location_name = db.Column(db.Text) json_result", "= 'photos' id = db.Column(db.Integer, primary_key=True) spotname = db.Column(db.Text) source_id", "db.Column(db.Text) views = db.Column(db.Integer) favourites = db.Column(db.Integer) comments = db.Column(db.Integer)", "= db.Column(db.Float) tags = db.Column(db.Text) views = db.Column(db.Integer) favourites =", "= db.Column(db.Float) longitude = db.Column(db.Float) tags = db.Column(db.Text) views =", "favourites = db.Column(db.Integer) comments = db.Column(db.Integer) username = db.Column(db.Text) photo_url", "primary_key=True) search_string = db.Column(db.Text) lat = db.Column(db.Float) lon = db.Column(db.Float)", "location_name = db.Column(db.Text) json_result = db.Column(LONGTEXT) class Photo(db.Model): __tablename__ =", "spotname = db.Column(db.Text) source_id = db.Column(db.Text) latitude = db.Column(db.Float) longitude", "import LONGTEXT class Search(db.Model): __tablename__ = 'spots' id = db.Column(db.Integer,", "LONGTEXT class Search(db.Model): __tablename__ = 'spots' id = db.Column(db.Integer, primary_key=True)", "latitude = db.Column(db.Float) longitude = db.Column(db.Float) tags = db.Column(db.Text) views", "db.Column(db.Float) lon = db.Column(db.Float) location_name = db.Column(db.Text) json_result = db.Column(LONGTEXT)", "search_string = db.Column(db.Text) lat = db.Column(db.Float) lon = db.Column(db.Float) location_name", "= 'spots' id = db.Column(db.Integer, primary_key=True) search_string = db.Column(db.Text) lat", "= db.Column(db.Text) lat = db.Column(db.Float) lon = db.Column(db.Float) location_name =", "= db.Column(db.Text) latitude = db.Column(db.Float) longitude = db.Column(db.Float) tags =", "tags = db.Column(db.Text) views = db.Column(db.Integer) favourites = db.Column(db.Integer) comments", "views = db.Column(db.Integer) favourites = db.Column(db.Integer) comments = db.Column(db.Integer) username", "lon = db.Column(db.Float) location_name = db.Column(db.Text) json_result = db.Column(LONGTEXT) class", "= db.Column(db.Float) location_name = db.Column(db.Text) json_result = db.Column(LONGTEXT) class Photo(db.Model):", "primary_key=True) spotname = db.Column(db.Text) source_id = db.Column(db.Text) latitude = db.Column(db.Float)", "= db.Column(db.Text) source_id = db.Column(db.Text) latitude = db.Column(db.Float) longitude =", "Photo(db.Model): __tablename__ = 'photos' id = db.Column(db.Integer, primary_key=True) spotname =", "= db.Column(db.Text) views = db.Column(db.Integer) favourites = db.Column(db.Integer) comments =", "= db.Column(db.Integer) comments = db.Column(db.Integer) username = db.Column(db.Text) photo_url =", "= db.Column(db.Integer, primary_key=True) search_string = db.Column(db.Text) lat = db.Column(db.Float) lon", "db.Column(db.Integer) favourites = db.Column(db.Integer) comments = db.Column(db.Integer) username = db.Column(db.Text)", "id = db.Column(db.Integer, primary_key=True) spotname = db.Column(db.Text) source_id = db.Column(db.Text)", "comments = db.Column(db.Integer) username = db.Column(db.Text) photo_url = db.Column(db.Text) search_id", "= db.Column(LONGTEXT) class Photo(db.Model): __tablename__ = 'photos' id = db.Column(db.Integer,", "db.Column(db.Text) lat = db.Column(db.Float) lon = db.Column(db.Float) location_name = db.Column(db.Text)", "import db from sqlalchemy.dialects.mysql import LONGTEXT class Search(db.Model): __tablename__ =", "from sqlalchemy.dialects.mysql import LONGTEXT class Search(db.Model): __tablename__ = 'spots' id", "db.Column(db.Integer, primary_key=True) spotname = db.Column(db.Text) source_id = db.Column(db.Text) latitude =", "class Search(db.Model): __tablename__ = 'spots' id = db.Column(db.Integer, primary_key=True) search_string", "sqlalchemy.dialects.mysql import LONGTEXT class Search(db.Model): __tablename__ = 'spots' id =", "= db.Column(db.Integer, primary_key=True) spotname = db.Column(db.Text) source_id = db.Column(db.Text) latitude", "= db.Column(db.Integer) favourites = db.Column(db.Integer) comments = db.Column(db.Integer) username =" ]
[ "as np import plotly.offline as pyo import plotly.graph_objs as go", "import plotly.offline as pyo import plotly.graph_objs as go df= pd.read_csv(\"Data/nst-est2017-alldata.csv\")", "plotly.offline as pyo import plotly.graph_objs as go df= pd.read_csv(\"Data/nst-est2017-alldata.csv\") df2=df[df[\"DIVISION\"]", "pd import numpy as np import plotly.offline as pyo import", "pyo import plotly.graph_objs as go df= pd.read_csv(\"Data/nst-est2017-alldata.csv\") df2=df[df[\"DIVISION\"] == '1']", "col in df2.columns if col.startswith('POP')] df2=df2[list_of_pop_col] data=[go.Scatter(x=df2.columns, y=df2.loc[name], mode='lines', name=name)", "import pandas as pd import numpy as np import plotly.offline", "df= pd.read_csv(\"Data/nst-est2017-alldata.csv\") df2=df[df[\"DIVISION\"] == '1'] df2.set_index(\"NAME\",inplace=True) list_of_pop_col=[col for col in", "<gh_stars>0 import pandas as pd import numpy as np import", "np import plotly.offline as pyo import plotly.graph_objs as go df=", "col.startswith('POP')] df2=df2[list_of_pop_col] data=[go.Scatter(x=df2.columns, y=df2.loc[name], mode='lines', name=name) for name in df2.index]", "in df2.columns if col.startswith('POP')] df2=df2[list_of_pop_col] data=[go.Scatter(x=df2.columns, y=df2.loc[name], mode='lines', name=name) for", "go df= pd.read_csv(\"Data/nst-est2017-alldata.csv\") df2=df[df[\"DIVISION\"] == '1'] df2.set_index(\"NAME\",inplace=True) list_of_pop_col=[col for col", "for col in df2.columns if col.startswith('POP')] df2=df2[list_of_pop_col] data=[go.Scatter(x=df2.columns, y=df2.loc[name], mode='lines',", "plotly.graph_objs as go df= pd.read_csv(\"Data/nst-est2017-alldata.csv\") df2=df[df[\"DIVISION\"] == '1'] df2.set_index(\"NAME\",inplace=True) list_of_pop_col=[col", "df2=df[df[\"DIVISION\"] == '1'] df2.set_index(\"NAME\",inplace=True) list_of_pop_col=[col for col in df2.columns if", "df2.set_index(\"NAME\",inplace=True) list_of_pop_col=[col for col in df2.columns if col.startswith('POP')] df2=df2[list_of_pop_col] data=[go.Scatter(x=df2.columns,", "== '1'] df2.set_index(\"NAME\",inplace=True) list_of_pop_col=[col for col in df2.columns if col.startswith('POP')]", "'1'] df2.set_index(\"NAME\",inplace=True) list_of_pop_col=[col for col in df2.columns if col.startswith('POP')] df2=df2[list_of_pop_col]", "list_of_pop_col=[col for col in df2.columns if col.startswith('POP')] df2=df2[list_of_pop_col] data=[go.Scatter(x=df2.columns, y=df2.loc[name],", "df2.columns if col.startswith('POP')] df2=df2[list_of_pop_col] data=[go.Scatter(x=df2.columns, y=df2.loc[name], mode='lines', name=name) for name", "import numpy as np import plotly.offline as pyo import plotly.graph_objs", "as pyo import plotly.graph_objs as go df= pd.read_csv(\"Data/nst-est2017-alldata.csv\") df2=df[df[\"DIVISION\"] ==", "pandas as pd import numpy as np import plotly.offline as", "pd.read_csv(\"Data/nst-est2017-alldata.csv\") df2=df[df[\"DIVISION\"] == '1'] df2.set_index(\"NAME\",inplace=True) list_of_pop_col=[col for col in df2.columns", "numpy as np import plotly.offline as pyo import plotly.graph_objs as", "as pd import numpy as np import plotly.offline as pyo", "if col.startswith('POP')] df2=df2[list_of_pop_col] data=[go.Scatter(x=df2.columns, y=df2.loc[name], mode='lines', name=name) for name in", "as go df= pd.read_csv(\"Data/nst-est2017-alldata.csv\") df2=df[df[\"DIVISION\"] == '1'] df2.set_index(\"NAME\",inplace=True) list_of_pop_col=[col for", "import plotly.graph_objs as go df= pd.read_csv(\"Data/nst-est2017-alldata.csv\") df2=df[df[\"DIVISION\"] == '1'] df2.set_index(\"NAME\",inplace=True)", "df2=df2[list_of_pop_col] data=[go.Scatter(x=df2.columns, y=df2.loc[name], mode='lines', name=name) for name in df2.index] pyo.plot(data)" ]
[ "see AUTHORS. :license: BSD, see LICENSE for details. \"\"\" import", "nodes.literal, \"a{b}c\"]) # no braces (whitespaces are keeped as is)", "resolving the markup afterwards, these nodes may remain class ForgivingTranslator:", "status, warning): app.builder.build_all() # default-role directive is stronger than configratuion", "reftarget='text', refexplicit=False, refwarn=False) assert errors == [] # explicit doctrees,", "role with anchor 'verify', ':rfc:`2324#id1`', ('<p><span class=\"target\" id=\"index-0\"></span><a class=\"rfc reference", "('\\\\begin{sphinxVerbatim}[commandchars=\\\\\\\\\\\\{\\\\}]\\n' '@Γ\\\\PYGZbs{}∞\\\\PYGZdl{}\\\\PYGZob{}\\\\PYGZcb{}\\n' '\\\\end{sphinxVerbatim}'), ), ]) def test_inline_for_unicode_latex_engine(get_verifier, type, rst, html_expected,", "':menuselection:`&Foo -&&- &Bar`', ('<p><span class=\"menuselection\"><span class=\"accelerator\">F</span>oo ' '-&amp;- <span class=\"accelerator\">B</span>ar</span></p>'),", "nodes.paragraph) assert_node(rst[0][0], nodes.emphasis) assert_node(rst[0][0][0], nodes.Text) assert rst[0][0][0] == 'Hello world'", "sample``', ('<p><code class=\"(samp )?docutils literal notranslate\"><span class=\"pre\">' 'code</span>&#160;&#160; <span class=\"pre\">sample</span></code></p>'),", "':kbd:`space`', '<p><kbd class=\"kbd docutils literal notranslate\">space</kbd></p>', '\\\\sphinxAtStartPar\\n\\\\sphinxkeyboard{\\\\sphinxupquote{space}}', ), ( #", "test_default_role1(app, status, warning): app.builder.build_all() # default-role: pep doctree = app.env.get_doctree('index')", "get_verifier(type) verifier(rst, html_expected, latex_expected) def test_samp_role(parse): # no braces text", "doctree = parse(text) assert_node(doctree[0], [nodes.paragraph, nodes.literal, \"code sample\"]) def test_download_role(parse):", "interpolation of ampersands in menuselection 'verify', ':menuselection:`&Foo -&&- &Bar`', ('<p><span", "assert_node(doctree[0][0], refdoc='dummy', refdomain='', reftype='download', refexplicit=False, reftarget='sphinx.rst', refwarn=False) assert_node(doctree[0][0][0], classes=['xref', 'download'])", "roles 'verify', ':manpage:`mp(1)`', '<p><em class=\"manpage\">mp(1)</em></p>', '\\\\sphinxAtStartPar\\n\\\\sphinxstyleliteralemphasis{\\\\sphinxupquote{mp(1)}}', ), ( # correct", "refexplicit=False, refwarn=False) assert errors == [] # explicit doctrees, errors", "( # kbd role 'verify', ':kbd:`Control+X`', ('<p><kbd class=\"kbd compound docutils", "external\" ' 'href=\"http://tools.ietf.org/html/rfc2324.html#id1\">' '<strong>RFC 2324#id1</strong></a></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\index{RFC@\\\\spxentry{RFC}!RFC 2324\\\\#id1@\\\\spxentry{RFC 2324\\\\#id1}}' '\\\\sphinxhref{http://tools.ietf.org/html/rfc2324.html\\\\#id1}'", "assert_node(doctree[0], [nodes.paragraph, nodes.literal, \"a{b}c\"]) # no braces (whitespaces are keeped", "ampersands in guilabel 'verify', ':guilabel:`Foo`', '<p><span class=\"guilabel\">Foo</span></p>', '\\\\sphinxAtStartPar\\n\\\\sphinxguilabel{Foo}', ), (", "literal notranslate\">' '<kbd class=\"kbd docutils literal notranslate\">Alt</kbd>' '+' '<kbd class=\"kbd", "reftype='download', refexplicit=True, reftarget='sphinx.rst', refwarn=False) assert_node(doctree[0][0][0], classes=['xref', 'download']) def test_XRefRole(inliner): role", "import sphinx_domains from sphinx.writers.html import HTMLTranslator, HTMLWriter from sphinx.writers.latex import", "def settings(app): texescape.init() # otherwise done by the latex builder", "= ''.join(html_translator.fragment).strip() assert re.match(html_expected, html_translated), 'from ' + rst return", "if latex_expected: verify_re_latex(rst, re.escape(latex_expected) + '$') return verify_ @pytest.fixture def", "refdoc='dummy', refdomain='', reftype='download', refexplicit=False, reftarget='sphinx.rst', refwarn=False) assert_node(doctree[0][0][0], classes=['xref', 'download']) #", "nodes.Text) assert rst[-1][-1][0][0] == 'Good-bye world' # rst_prolog & rst_epilog", "2007-2021 by the Sphinx team, see AUTHORS. :license: BSD, see", "reference external\" ' 'href=\"http://tools.ietf.org/html/rfc2324.html\"><strong>RFC 2324</strong></a></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\index{RFC@\\\\spxentry{RFC}!RFC 2324@\\\\spxentry{RFC 2324}}' '\\\\sphinxhref{http://tools.ietf.org/html/rfc2324.html}'", "role('ref', 'rawtext', 'text()', 5, inliner, {}, []) assert_node(doctrees[0], [addnodes.pending_xref, nodes.literal,", "('<dl class=\"glossary docutils\">\\n' '<dt id=\"term-term1\">term1<a class=\"headerlink\" href=\"#term-term1\"' ' title=\"Permalink to", "explicit doctrees, errors = role('ref', 'rawtext', 'title <target>', 5, inliner,", "assert re.match(html_expected, html_translated), 'from ' + rst return verify @pytest.fixture", "':kbd:`Alt+^`', ('<p><kbd class=\"kbd compound docutils literal notranslate\">' '<kbd class=\"kbd docutils", "'\\\\sphinxAtStartPar\\nΓ\\\\textbackslash{}\\\\(\\\\infty\\\\)\\\\$', ), ( # in verbatim code fragments 'verify', '::\\n\\n", "Struct(document=document, reporter=document.reporter) @pytest.fixture def parse(new_document): def parse_(rst): document = new_document()", "addnodes.compact_paragraph) assert doctree[0][2][0][0].astext() == 'genindex' assert doctree[0][3].astext() == 'List B:'", "= app.builder.env settings.env.temp_data['docname'] = 'dummy' settings.contentsname = 'dummy' settings.rfc_base_url =", "node): pass def depart_pending_xref(self, node): pass class ForgivingHTMLTranslator(HTMLTranslator, ForgivingTranslator): pass", "literal notranslate\">space</kbd></p>', '\\\\sphinxAtStartPar\\n\\\\sphinxkeyboard{\\\\sphinxupquote{space}}', ), ( # kbd role 'verify', ':kbd:`Control+X`',", "assert re.match(latex_expected, latex_translated), 'from ' + repr(rst) return verify @pytest.fixture", "class=\"target\" id=\"index-0\"></span><a class=\"rfc reference external\" ' 'href=\"http://tools.ietf.org/html/rfc2324.html#id1\">' '<strong>RFC 2324#id1</strong></a></p>'), ('\\\\sphinxAtStartPar\\n'", "not md.rawsource.endswith('*Good-bye world*.\\n') @pytest.mark.sphinx('dummy', testroot='keep_warnings') def test_keep_warnings_is_True(app, status, warning): app.builder.build_all()", "pep doctree = app.env.get_doctree('index') assert_node(doctree[0], nodes.section) assert_node(doctree[0][1], nodes.paragraph) assert_node(doctree[0][1][0], addnodes.index)", "latex_expected): document = parse(rst) app.builder = LaTeXBuilder(app) app.builder.set_environment(app.env) app.builder.init() theme", "= ':samp:`a{b}c`' doctree = parse(text) assert_node(doctree[0], [nodes.paragraph, nodes.literal, (\"a\", [nodes.emphasis,", "refdoc='dummy', refdomain='test', reftype='doc', reftarget='text', refexplicit=False, refwarn=False) # fix_parens role =", "verify_re_latex): def verify_re_(rst, html_expected, latex_expected): if html_expected: verify_re_html(rst, html_expected) if", "class=\"target\" id=\"index-0\"></span><a class=\"pep reference external\" ' 'href=\"http://www.python.org/dev/peps/pep-0008#id1\">' '<strong>PEP 8#id1</strong></a></p>'), ('\\\\sphinxAtStartPar\\n'", "of ampersands in menuselection 'verify', ':menuselection:`&Foo -&&- &Bar`', ('<p><span class=\"menuselection\"><span", "kbd role 'verify', ':kbd:`space`', '<p><kbd class=\"kbd docutils literal notranslate\">space</kbd></p>', '\\\\sphinxAtStartPar\\n\\\\sphinxkeyboard{\\\\sphinxupquote{space}}',", "verify_re): v = { 'verify': verify, 'verify_re': verify_re, } def", "M-s`', ('<p><kbd class=\"kbd compound docutils literal notranslate\">' '<kbd class=\"kbd docutils", "html_expected, latex_expected): if html_expected: verify_re_html(rst, re.escape(html_expected) + '$') if latex_expected:", "'<span class=\"classifier\">class2</span></dt><dd>description</dd>\\n</dl>'), None, ), ( # glossary (description list): multiple", "assert_node(doctrees[0], refdoc='dummy', refdomain='', reftype='ref', reftarget='text', refexplicit=False, refwarn=False) assert errors ==", "import SphinxSmartQuotes from sphinx.util import docutils, texescape from sphinx.util.docutils import", "docutils literal notranslate\">X</kbd>' '</kbd></p>'), '\\\\sphinxAtStartPar\\n\\\\sphinxkeyboard{\\\\sphinxupquote{Control+X}}', ), ( # kbd role", "class=\"manpage\">mp(1)</em></p>', '\\\\sphinxAtStartPar\\n\\\\sphinxstyleliteralemphasis{\\\\sphinxupquote{mp(1)}}', ), ( # correct escaping in normal mode", "= frontend.OptionParser( components=(RstParser, HTMLWriter, LaTeXWriter)) settings = optparser.get_default_values() settings.smart_quotes =", "def get(name): return v[name] return get @pytest.mark.parametrize('type,rst,html_expected,latex_expected', [ ( #", "(\"a\", [nodes.emphasis, \"{b\"], \"}c\")]) # half-opened braces text = ':samp:`a{bc`'", "sphinx.util.docutils import sphinx_domains from sphinx.writers.html import HTMLTranslator, HTMLWriter from sphinx.writers.latex", "doctrees, errors = role('ref', 'rawtext', 'TEXT', 5, inliner, {}, [])", "with anchor 'verify', ':rfc:`2324#id1`', ('<p><span class=\"target\" id=\"index-0\"></span><a class=\"rfc reference external\"", "( # in URIs 'verify_re', '`test <https://www.google.com/~me/>`_', None, r'\\\\sphinxAtStartPar\\n\\\\sphinxhref{https://www.google.com/~me/}{test}.*', ),", "nodes.literal, \"reftitle\"]) assert_node(doctree[0][0], refdoc='dummy', refdomain='', reftype='download', refexplicit=True, reftarget='sphinx.rst', refwarn=False) assert_node(doctree[0][0][0],", "v[name] return get @pytest.mark.parametrize('type,rst,html_expected,latex_expected', [ ( # pep role 'verify',", "std std-option docutils literal notranslate\")?>' '<span class=\"pre\">--with-option</span></code></p>$'), (r'\\\\sphinxAtStartPar\\n' r'\\\\sphinxcode{\\\\sphinxupquote{\\\\sphinxhyphen{}\\\\sphinxhyphen{}with\\\\sphinxhyphen{}option}}$'), ),", "assert_node(doctree[0], nodes.section) assert len(doctree[0]) == 1 @pytest.mark.sphinx('dummy', testroot='refonly_bullet_list') def test_compact_refonly_bullet_list(app,", "def test_default_role2(app, status, warning): app.builder.build_all() # default-role directive is stronger", "= ForgivingHTMLTranslator(document, app.builder) document.walkabout(html_translator) html_translated = ''.join(html_translator.fragment).strip() assert re.match(html_expected, html_translated),", "'\\\\index{Python Enhancement Proposals@\\\\spxentry{Python Enhancement Proposals}' '!PEP 8@\\\\spxentry{PEP 8}}\\\\sphinxhref{http://www.python.org/dev/peps/pep-0008}' '{\\\\sphinxstylestrong{PEP 8}}')", "), ( # correct interpretation of code with whitespace 'verify_re',", "braces text = ':samp:`a{{b}}c`' doctree = parse(text) assert_node(doctree[0], [nodes.paragraph, nodes.literal,", "= app.env.get_doctree('index') assert_node(doctree[0], nodes.section) assert len(doctree[0]) == 2 assert_node(doctree[0][1], nodes.system_message)", "if html_expected: verify_re_html(rst, html_expected) if latex_expected: verify_re_latex(rst, latex_expected) return verify_re_", "@pytest.fixture def verify(verify_re_html, verify_re_latex): def verify_(rst, html_expected, latex_expected): if html_expected:", "reftarget='text', refexplicit=False, refwarn=False) # fix_parens role = XRefRole(fix_parens=True) doctrees, errors", "nodes may remain class ForgivingTranslator: def visit_pending_xref(self, node): pass def", "'\\\\sphinxhref{http://tools.ietf.org/html/rfc2324.html}' '{\\\\sphinxstylestrong{RFC 2324}}') ), ( # rfc role with anchor", "'\\\\sphinxAtStartPar\\n\\\\sphinxkeyboard{\\\\sphinxupquote{Control+X}}', ), ( # kbd role 'verify', ':kbd:`Alt+^`', ('<p><kbd class=\"kbd", "== 'Hello' @pytest.mark.sphinx('dummy', testroot='default_role') def test_default_role1(app, status, warning): app.builder.build_all() #", "verbatim code fragments 'verify', '::\\n\\n @Γ\\\\∞${}', None, ('\\\\begin{sphinxVerbatim}[commandchars=\\\\\\\\\\\\{\\\\}]\\n' '@Γ\\\\PYGZbs{}\\\\(\\\\infty\\\\)\\\\PYGZdl{}\\\\PYGZob{}\\\\PYGZcb{}\\n' '\\\\end{sphinxVerbatim}'),", "'rawtext', '!title <target>', 5, inliner, {}, []) assert_node(doctrees[0], [nodes.literal, 'title", "RstParser() parser.parse(rst, document) SphinxSmartQuotes(document, startnode=None).apply() for msg in document.traverse(nodes.system_message): if", "app.builder.env settings.env.temp_data['docname'] = 'dummy' settings.contentsname = 'dummy' settings.rfc_base_url = 'http://tools.ietf.org/html/'", "nodes.paragraph) assert_node(rst[-1][-1][0], nodes.emphasis) assert_node(rst[-1][-1][0][0], nodes.Text) assert rst[-1][-1][0][0] == 'Good-bye world'", "reftarget='sphinx.rst', refwarn=False) assert_node(doctree[0][0][0], classes=['xref', 'download']) # explicit text = ':download:`reftitle", "'List B:' assert_node(doctree[0][4], nodes.bullet_list) assert_node(doctree[0][4][0][0], nodes.paragraph) assert doctree[0][4][0][0].astext() == 'Hello'", "addnodes from sphinx.builders.html.transforms import KeyboardTransform from sphinx.builders.latex import LaTeXBuilder from", "if latex_expected: verify_re_latex(rst, latex_expected) return verify_re_ @pytest.fixture def verify(verify_re_html, verify_re_latex):", "'<kbd class=\"kbd docutils literal notranslate\">x</kbd>' ' ' '<kbd class=\"kbd docutils", "sphinx.writers.html import HTMLTranslator, HTMLWriter from sphinx.writers.latex import LaTeXTranslator, LaTeXWriter @pytest.fixture", "# default-role directive is stronger than configratuion doctree = app.env.get_doctree('index')", "latex_expected: verify_re_latex(rst, latex_expected) return verify_re_ @pytest.fixture def verify(verify_re_html, verify_re_latex): def", "rst[0][0][0] == 'Hello world' # rst_epilog assert_node(rst[-1], nodes.section) assert_node(rst[-1][-1], nodes.paragraph)", "inliner(new_document): document = new_document() document.reporter.get_source_and_line = lambda line=1: ('dummy.rst', line)", "default-role: pep doctree = app.env.get_doctree('index') assert_node(doctree[0], nodes.section) assert_node(doctree[0][1], nodes.paragraph) assert_node(doctree[0][1][0],", "# rst_epilog assert_node(rst[-1], nodes.section) assert_node(rst[-1][-1], nodes.paragraph) assert_node(rst[-1][-1][0], nodes.emphasis) assert_node(rst[-1][-1][0][0], nodes.Text)", "= app.env.get_doctree('foo') assert_node(doctree[0], nodes.section) assert_node(doctree[0][1], nodes.paragraph) assert_node(doctree[0][1][0], nodes.inline, classes=[\"guilabel\"]) assert_node(doctree[0][1][1],", "import pytest from docutils import frontend, nodes, utils from docutils.parsers.rst", "glossary::\\n\\n term1\\n term2\\n description', ('<dl class=\"glossary docutils\">\\n' '<dt id=\"term-term1\">term1<a class=\"headerlink\"", "see LICENSE for details. \"\"\" import re import pytest from", "\\\\</p>', None, ), ]) @pytest.mark.skipif(docutils.__version_info__ < (0, 16), reason='docutils-0.16 or", "literal notranslate\">x</kbd>' ' ' '<kbd class=\"kbd docutils literal notranslate\">M</kbd>' '-'", "[ ( # in verbatim code fragments 'verify', '::\\n\\n @Γ\\\\∞${}',", "class=\"target\" id=\"index-0\"></span><a class=\"pep reference external\" ' 'href=\"http://www.python.org/dev/peps/pep-0008\"><strong>PEP 8</strong></a></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\index{Python", "== 'Hello world' # rst_epilog assert_node(rst[-1], nodes.section) assert_node(rst[-1][-1], nodes.paragraph) assert_node(rst[-1][-1][0],", "'rawtext', 'text', 5, inliner, {}, []) assert_node(doctrees[0], [addnodes.pending_xref, nodes.literal, 'text'])", "test_compact_refonly_bullet_list(app, status, warning): app.builder.build_all() doctree = app.env.get_doctree('index') assert_node(doctree[0], nodes.section) assert", "@pytest.fixture def inliner(new_document): document = new_document() document.reporter.get_source_and_line = lambda line=1:", "(r'\\\\sphinxAtStartPar\\n' r'\\\\sphinxcode{\\\\sphinxupquote{\\\\sphinxhyphen{}\\\\sphinxhyphen{}with\\\\sphinxhyphen{}option}}$'), ), ( # verify smarty-pants quotes 'verify', '\"John\"',", "reference external\" ' 'href=\"http://tools.ietf.org/html/rfc2324.html#id1\">' '<strong>RFC 2324#id1</strong></a></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\index{RFC@\\\\spxentry{RFC}!RFC 2324\\\\#id1@\\\\spxentry{RFC 2324\\\\#id1}}'", "class=\"glossary docutils\">\\n' '<dt id=\"term-term1\">term1<a class=\"headerlink\" href=\"#term-term1\"' ' title=\"Permalink to this", "A:' assert_node(doctree[0][2], nodes.bullet_list) assert_node(doctree[0][2][0][0], addnodes.compact_paragraph) assert doctree[0][2][0][0].astext() == 'genindex' assert", "testroot='default_role') def test_default_role1(app, status, warning): app.builder.build_all() # default-role: pep doctree", "# pep role with anchor 'verify', ':pep:`8#id1`', ('<p><span class=\"target\" id=\"index-0\"></span><a", "reftype='ref', reftarget='text', refexplicit=False, refwarn=False) assert errors == [] # explicit", "def test_inline_for_unicode_latex_engine(get_verifier, type, rst, html_expected, latex_expected): verifier = get_verifier(type) verifier(rst,", "'text()']) assert_node(doctrees[0], refdoc='dummy', refdomain='', reftype='ref', reftarget='text', refexplicit=False, refwarn=False) # lowercase", "parse(text) assert_node(doctree[0], [nodes.paragraph, nodes.literal, \"code sample\"]) def test_download_role(parse): # implicit", "':download:`reftitle <sphinx.rst>`' doctree = parse(text) assert_node(doctree[0], [nodes.paragraph, addnodes.download_reference, nodes.literal, \"reftitle\"])", "since we're not resolving the markup afterwards, these nodes may", "# since we're not resolving the markup afterwards, these nodes", "( # rfc role with anchor 'verify', ':rfc:`2324#id1`', ('<p><span class=\"target\"", "external\" ' 'href=\"http://www.python.org/dev/peps/pep-0008\"><strong>PEP 8</strong></a></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\index{Python Enhancement Proposals@\\\\spxentry{Python Enhancement Proposals}'", "assert_node(doctree[0][1][0], addnodes.index) assert_node(doctree[0][1][1], nodes.target) assert_node(doctree[0][1][2], nodes.reference, classes=[\"pep\"]) # default_role changes", "# no braces (whitespaces are keeped as is) text =", "pass @pytest.fixture def verify_re_html(app, parse): def verify(rst, html_expected): document =", "notranslate\"><span class=\"pre\">' '&quot;John&quot;</span></code></p>'), '\\\\sphinxAtStartPar\\n\\\\sphinxcode{\\\\sphinxupquote{\"John\"}}', ), ( # verify classes for", "'href=\"http://tools.ietf.org/html/rfc2324.html\"><strong>RFC 2324</strong></a></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\index{RFC@\\\\spxentry{RFC}!RFC 2324@\\\\spxentry{RFC 2324}}' '\\\\sphinxhref{http://tools.ietf.org/html/rfc2324.html}' '{\\\\sphinxstylestrong{RFC 2324}}') ),", "nodes.bullet_list) assert_node(doctree[0][2][0][0], addnodes.compact_paragraph) assert doctree[0][2][0][0].astext() == 'genindex' assert doctree[0][3].astext() ==", "in menuselection 'verify', ':menuselection:`&Foo -&&- &Bar`', ('<p><span class=\"menuselection\"><span class=\"accelerator\">F</span>oo '", "app.env.get_doctree('index') assert_node(doctree[0], nodes.section) assert len(doctree[0]) == 2 assert_node(doctree[0][1], nodes.system_message) @pytest.mark.sphinx('dummy',", "'verify', ':kbd:`Control+X`', ('<p><kbd class=\"kbd compound docutils literal notranslate\">' '<kbd class=\"kbd", "Proposals}' '!PEP 8\\\\#id1@\\\\spxentry{PEP 8\\\\#id1}}\\\\sphinxhref' '{http://www.python.org/dev/peps/pep-0008\\\\#id1}' '{\\\\sphinxstylestrong{PEP 8\\\\#id1}}') ), ( #", "of code with whitespace 'verify_re', '``code sample``', ('<p><code class=\"(samp )?docutils", "literal text 'verify', '``\"John\"``', ('<p><code class=\"docutils literal notranslate\"><span class=\"pre\">' '&quot;John&quot;</span></code></p>'),", "changes the default behavior doctree = app.env.get_doctree('foo') assert_node(doctree[0], nodes.section) assert_node(doctree[0][1],", "class=\"pep reference external\" ' 'href=\"http://www.python.org/dev/peps/pep-0008\"><strong>PEP 8</strong></a></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\index{Python Enhancement Proposals@\\\\spxentry{Python", "warning): app.builder.build_all() # default-role: pep doctree = app.env.get_doctree('index') assert_node(doctree[0], nodes.section)", "'<p>“John”</p>', \"\\\\sphinxAtStartPar\\n“John”\", ), ( # ... but not in literal", "@pytest.mark.parametrize('type,rst,html_expected,latex_expected', [ ( 'verify', r'4 backslashes \\\\\\\\', r'<p>4 backslashes \\\\</p>',", "'-&amp;- <span class=\"accelerator\">B</span>ar</span></p>'), ('\\\\sphinxAtStartPar\\n' r'\\sphinxmenuselection{\\sphinxaccelerator{F}oo \\sphinxhyphen{}' r'\\&\\sphinxhyphen{} \\sphinxaccelerator{B}ar}'), ), (", "document) SphinxSmartQuotes(document, startnode=None).apply() for msg in document.traverse(nodes.system_message): if msg['level'] ==", "various Sphinx-specific markup extensions. :copyright: Copyright 2007-2021 by the Sphinx", "text 'verify', '``\"John\"``', ('<p><code class=\"docutils literal notranslate\"><span class=\"pre\">' '&quot;John&quot;</span></code></p>'), '\\\\sphinxAtStartPar\\n\\\\sphinxcode{\\\\sphinxupquote{\"John\"}}',", "('\\\\sphinxAtStartPar\\n' r'\\sphinxguilabel{\\sphinxaccelerator{F}oo \\sphinxhyphen{}\\&\\sphinxhyphen{} \\sphinxaccelerator{B}ar}'), ), ( # no ampersands in", "escaping in normal mode 'verify', 'Γ\\\\\\\\∞$', None, '\\\\sphinxAtStartPar\\nΓ\\\\textbackslash{}\\\\(\\\\infty\\\\)\\\\$', ), (", "('<p><span class=\"target\" id=\"index-0\"></span><a class=\"pep reference external\" ' 'href=\"http://www.python.org/dev/peps/pep-0008#id1\">' '<strong>PEP 8#id1</strong></a></p>'),", "-1 # don't write \\begin{document} document.walkabout(latex_translator) latex_translated = ''.join(latex_translator.body).strip() assert", "'download']) def test_XRefRole(inliner): role = XRefRole() # implicit doctrees, errors", "@pytest.fixture def verify_re_html(app, parse): def verify(rst, html_expected): document = parse(rst)", "' '-&amp;- <span class=\"accelerator\">B</span>ar</span></p>'), ('\\\\sphinxAtStartPar\\n' r'\\sphinxguilabel{\\sphinxaccelerator{F}oo \\sphinxhyphen{}\\&\\sphinxhyphen{} \\sphinxaccelerator{B}ar}'), ), (", "import HTMLTranslator, HTMLWriter from sphinx.writers.latex import LaTeXTranslator, LaTeXWriter @pytest.fixture def", "class=\"kbd docutils literal notranslate\">s</kbd>' '</kbd></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\sphinxkeyboard{\\\\sphinxupquote{M\\\\sphinxhyphen{}x M\\\\sphinxhyphen{}s}}'), ), (", "'title <target>']) # refdomain doctrees, errors = role('test:doc', 'rawtext', 'text',", "':guilabel:`&Foo -&&- &Bar`', ('<p><span class=\"guilabel\"><span class=\"accelerator\">F</span>oo ' '-&amp;- <span class=\"accelerator\">B</span>ar</span></p>'),", "'verify', ':pep:`8`', ('<p><span class=\"target\" id=\"index-0\"></span><a class=\"pep reference external\" ' 'href=\"http://www.python.org/dev/peps/pep-0008\"><strong>PEP", "AUTHORS. :license: BSD, see LICENSE for details. \"\"\" import re", "role 'verify', ':kbd:`M-x M-s`', ('<p><kbd class=\"kbd compound docutils literal notranslate\">'", "nodes.paragraph) assert doctree[0][4][0][0].astext() == 'Hello' @pytest.mark.sphinx('dummy', testroot='default_role') def test_default_role1(app, status,", "verifier = get_verifier(type) verifier(rst, html_expected, latex_expected) def test_samp_role(parse): # no", "in literal text 'verify', '``\"John\"``', ('<p><code class=\"docutils literal notranslate\"><span class=\"pre\">'", "class=\"menuselection\"><span class=\"accelerator\">F</span>oo ' '-&amp;- <span class=\"accelerator\">B</span>ar</span></p>'), ('\\\\sphinxAtStartPar\\n' r'\\sphinxmenuselection{\\sphinxaccelerator{F}oo \\sphinxhyphen{}' r'\\&\\sphinxhyphen{}", "'\\\\end{sphinxVerbatim}'), ), ]) def test_inline_for_unicode_latex_engine(get_verifier, type, rst, html_expected, latex_expected): verifier", "'rawtext', 'text', 5, inliner, {}, []) assert len(doctrees) == 1", "&Bar`', ('<p><span class=\"menuselection\"><span class=\"accelerator\">F</span>oo ' '-&amp;- <span class=\"accelerator\">B</span>ar</span></p>'), ('\\\\sphinxAtStartPar\\n' r'\\sphinxmenuselection{\\sphinxaccelerator{F}oo", "than configratuion doctree = app.env.get_doctree('index') assert_node(doctree[0], nodes.section) assert_node(doctree[0][1], nodes.paragraph) assert_node(doctree[0][1][0],", "'&quot;John&quot;</span></code></p>'), '\\\\sphinxAtStartPar\\n\\\\sphinxcode{\\\\sphinxupquote{\"John\"}}', ), ( # verify classes for inline roles", "in menuselection 'verify', ':menuselection:`a --> b`', ('<p><span class=\"menuselection\">a \\N{TRIANGULAR BULLET}", "parse(text) assert_node(doctree[0], [nodes.paragraph, nodes.literal, (\"a\", [nodes.emphasis, \"b\"], \"c\")]) # nested", "rst, html_expected, latex_expected): verifier = get_verifier(type) verifier(rst, html_expected, latex_expected) def", "'\\\\sphinxAtStartPar\\n\\\\sphinxstyleliteralemphasis{\\\\sphinxupquote{mp(1)}}', ), ( # correct escaping in normal mode 'verify',", "is required') def test_inline_docutils16(get_verifier, type, rst, html_expected, latex_expected): verifier =", "latex_expected) def test_samp_role(parse): # no braces text = ':samp:`a{b}c`' doctree", "\\\\\\\\', r'<p>4 backslashes \\\\</p>', None, ), ]) @pytest.mark.skipif(docutils.__version_info__ < (0,", "[nodes.paragraph, nodes.literal, \"a{b}c\"]) # no braces (whitespaces are keeped as", "assert_node(doctree[0], [nodes.paragraph, addnodes.download_reference, nodes.literal, \"reftitle\"]) assert_node(doctree[0][0], refdoc='dummy', refdomain='', reftype='download', refexplicit=True,", "class=\"kbd docutils literal notranslate\">-</kbd></p>', ('\\\\sphinxAtStartPar\\n' '\\\\sphinxkeyboard{\\\\sphinxupquote{\\\\sphinxhyphen{}}}'), ), ( # kbd", "nodes.literal, \"sphinx.rst\"]) assert_node(doctree[0][0], refdoc='dummy', refdomain='', reftype='download', refexplicit=False, reftarget='sphinx.rst', refwarn=False) assert_node(doctree[0][0][0],", "= app.env.get_doctree('index') assert_node(doctree[0], nodes.section) assert len(doctree[0]) == 5 assert doctree[0][1].astext()", "== 'genindex' assert doctree[0][3].astext() == 'List B:' assert_node(doctree[0][4], nodes.bullet_list) assert_node(doctree[0][4][0][0],", "[nodes.emphasis, \"b\"], \"c\")]) # nested braces text = ':samp:`a{{b}}c`' doctree", "SphinxSmartQuotes from sphinx.util import docutils, texescape from sphinx.util.docutils import sphinx_domains", "2 assert_node(doctree[0][1], nodes.system_message) @pytest.mark.sphinx('dummy', testroot='keep_warnings', confoverrides={'keep_warnings': False}) def test_keep_warnings_is_False(app, status,", "Struct, assert_node from sphinx.transforms import SphinxSmartQuotes from sphinx.util import docutils,", "'verify', ':kbd:`Alt+^`', ('<p><kbd class=\"kbd compound docutils literal notranslate\">' '<kbd class=\"kbd", "# ... but not in literal text 'verify', '``\"John\"``', ('<p><code", "verify_re_html(rst, re.escape(html_expected) + '$') if latex_expected: verify_re_latex(rst, re.escape(latex_expected) + '$')", "), ( # interpolation of ampersands in guilabel 'verify', ':guilabel:`&Foo", "builder optparser = frontend.OptionParser( components=(RstParser, HTMLWriter, LaTeXWriter)) settings = optparser.get_default_values()", "'<strong>RFC 2324#id1</strong></a></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\index{RFC@\\\\spxentry{RFC}!RFC 2324\\\\#id1@\\\\spxentry{RFC 2324\\\\#id1}}' '\\\\sphinxhref{http://tools.ietf.org/html/rfc2324.html\\\\#id1}' '{\\\\sphinxstylestrong{RFC 2324\\\\#id1}}') ),", "LaTeXBuilder(app) app.builder.set_environment(app.env) app.builder.init() theme = app.builder.themes.get('manual') latex_translator = ForgivingLaTeXTranslator(document, app.builder,", "doctree = app.env.get_doctree('index') assert_node(doctree[0], nodes.section) assert len(doctree[0]) == 5 assert", "arrows in menuselection 'verify', ':menuselection:`a --> b`', ('<p><span class=\"menuselection\">a \\N{TRIANGULAR", "'{http://www.python.org/dev/peps/pep-0008\\\\#id1}' '{\\\\sphinxstylestrong{PEP 8\\\\#id1}}') ), ( # rfc role 'verify', ':rfc:`2324`',", "half-opened braces text = ':samp:`a{bc`' doctree = parse(text) assert_node(doctree[0], [nodes.paragraph,", "'verify', 'Γ\\\\\\\\∞$', None, '\\\\sphinxAtStartPar\\nΓ\\\\textbackslash{}\\\\(\\\\infty\\\\)\\\\$', ), ( # in verbatim code", "default_role changes the default behavior doctree = app.env.get_doctree('foo') assert_node(doctree[0], nodes.section)", "title=\"Permalink to this term\">¶</a></dt>' '<dt id=\"term-term2\">term2<a class=\"headerlink\" href=\"#term-term2\"' ' title=\"Permalink", "new_document() document.reporter.get_source_and_line = lambda line=1: ('dummy.rst', line) return Struct(document=document, reporter=document.reporter)", "Test various Sphinx-specific markup extensions. :copyright: Copyright 2007-2021 by the", "'::\\n\\n @Γ\\\\∞${}', None, ('\\\\begin{sphinxVerbatim}[commandchars=\\\\\\\\\\\\{\\\\}]\\n' '@Γ\\\\PYGZbs{}\\\\(\\\\infty\\\\)\\\\PYGZdl{}\\\\PYGZob{}\\\\PYGZcb{}\\n' '\\\\end{sphinxVerbatim}'), ), ( # in", "testroot='prolog') def test_rst_prolog(app, status, warning): app.builder.build_all() rst = app.env.get_doctree('restructuredtext') md", "XRefRole() # implicit doctrees, errors = role('ref', 'rawtext', 'text', 5,", "settings.rfc_base_url = 'http://tools.ietf.org/html/' domain_context = sphinx_domains(settings.env) domain_context.enable() yield settings domain_context.disable()", "write \\begin{document} document.walkabout(latex_translator) latex_translated = ''.join(latex_translator.body).strip() assert re.match(latex_expected, latex_translated), 'from", "nodes.literal, 'title']) assert_node(doctrees[0], refdoc='dummy', refdomain='', reftype='ref', reftarget='target', refexplicit=True, refwarn=False) #", "msg in document.traverse(nodes.system_message): if msg['level'] == 1: msg.replace_self([]) return document", "[nodes.paragraph, addnodes.download_reference, nodes.literal, \"sphinx.rst\"]) assert_node(doctree[0][0], refdoc='dummy', refdomain='', reftype='download', refexplicit=False, reftarget='sphinx.rst',", "ampersands in menuselection 'verify', ':menuselection:`&Foo -&&- &Bar`', ('<p><span class=\"menuselection\"><span class=\"accelerator\">F</span>oo", "document = parse(rst) app.builder = LaTeXBuilder(app) app.builder.set_environment(app.env) app.builder.init() theme =", "doctree = app.env.get_doctree('foo') assert_node(doctree[0], nodes.section) assert_node(doctree[0][1], nodes.paragraph) assert_node(doctree[0][1][0], nodes.inline, classes=[\"guilabel\"])", "'verify', ':kbd:`M-x M-s`', ('<p><kbd class=\"kbd compound docutils literal notranslate\">' '<kbd", "# kbd role 'verify', ':kbd:`space`', '<p><kbd class=\"kbd docutils literal notranslate\">space</kbd></p>',", "utils.new_document('test data', settings) document['file'] = 'dummy' return document return create", "reftarget='target', refexplicit=True, refwarn=False) # bang doctrees, errors = role('ref', 'rawtext',", "'verify', r'4 backslashes \\\\\\\\', r'<p>4 backslashes \\\\</p>', None, ), ])", "('\\\\sphinxAtStartPar\\n' '\\\\sphinxkeyboard{\\\\sphinxupquote{Caps Lock}}'), ), ( # non-interpolation of dashes in", "), ( # description list: with classifiers 'verify', 'term :", "\"c\")]) # nested braces text = ':samp:`a{{b}}c`' doctree = parse(text)", "notranslate\">^</kbd>' '</kbd></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\sphinxkeyboard{\\\\sphinxupquote{Alt+\\\\textasciicircum{}}}'), ), ( # kbd role 'verify',", "assert_node(doctrees[0], [addnodes.pending_xref, nodes.literal, 'text()']) assert_node(doctrees[0], refdoc='dummy', refdomain='', reftype='ref', reftarget='text', refexplicit=False,", "test_keep_warnings_is_True(app, status, warning): app.builder.build_all() doctree = app.env.get_doctree('index') assert_node(doctree[0], nodes.section) assert", "notranslate\"><span class=\"pre\">' 'code</span>&#160;&#160; <span class=\"pre\">sample</span></code></p>'), r'\\\\sphinxAtStartPar\\n\\\\sphinxcode{\\\\sphinxupquote{code sample}}', ), ( #", "from sphinx.util.docutils import sphinx_domains from sphinx.writers.html import HTMLTranslator, HTMLWriter from", "class=\"guilabel\">Foo</span></p>', '\\\\sphinxAtStartPar\\n\\\\sphinxguilabel{Foo}', ), ( # kbd role 'verify', ':kbd:`space`', '<p><kbd", "assert_node(doctree[0][1][1], nodes.target) assert_node(doctree[0][1][2], nodes.reference, classes=[\"pep\"]) # default_role changes the default", "'http://tools.ietf.org/html/' domain_context = sphinx_domains(settings.env) domain_context.enable() yield settings domain_context.disable() @pytest.fixture def", "rst_prolog & rst_epilog on exlucding reST parser assert not md.rawsource.startswith('*Hello", "rst_epilog on exlucding reST parser assert not md.rawsource.startswith('*Hello world*.') assert", "docutils literal notranslate\">s</kbd>' '</kbd></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\sphinxkeyboard{\\\\sphinxupquote{M\\\\sphinxhyphen{}x M\\\\sphinxhyphen{}s}}'), ), ( #", "def parse(new_document): def parse_(rst): document = new_document() parser = RstParser()", "'Hello world' # rst_epilog assert_node(rst[-1], nodes.section) assert_node(rst[-1][-1], nodes.paragraph) assert_node(rst[-1][-1][0], nodes.emphasis)", "'guilabel'}) def test_default_role2(app, status, warning): app.builder.build_all() # default-role directive is", "done by the latex builder optparser = frontend.OptionParser( components=(RstParser, HTMLWriter,", "rst, html_expected, latex_expected): verifier = get_verifier(type) verifier(rst, html_expected, latex_expected) @pytest.mark.parametrize('type,rst,html_expected,latex_expected',", "< (0, 16), reason='docutils-0.16 or above is required') def test_inline_docutils16(get_verifier,", "inliner, {}, []) assert_node(doctrees[0], [addnodes.pending_xref, nodes.literal, 'text']) assert_node(doctrees[0], refdoc='dummy', refdomain='test',", "def verify_re_html(app, parse): def verify(rst, html_expected): document = parse(rst) KeyboardTransform(document).apply()", "), ]) def test_inline(get_verifier, type, rst, html_expected, latex_expected): verifier =", "assert not md.rawsource.startswith('*Hello world*.') assert not md.rawsource.endswith('*Good-bye world*.\\n') @pytest.mark.sphinx('dummy', testroot='keep_warnings')", "'verify', '``\"John\"``', ('<p><code class=\"docutils literal notranslate\"><span class=\"pre\">' '&quot;John&quot;</span></code></p>'), '\\\\sphinxAtStartPar\\n\\\\sphinxcode{\\\\sphinxupquote{\"John\"}}', ),", "\\sphinxhyphen{}\\&\\sphinxhyphen{} \\sphinxaccelerator{B}ar}'), ), ( # no ampersands in guilabel 'verify',", "details. \"\"\" import re import pytest from docutils import frontend,", "+ repr(rst) return verify @pytest.fixture def verify_re(verify_re_html, verify_re_latex): def verify_re_(rst,", "HTMLWriter, LaTeXWriter)) settings = optparser.get_default_values() settings.smart_quotes = True settings.env =", "KeyboardTransform(document).apply() html_translator = ForgivingHTMLTranslator(document, app.builder) document.walkabout(html_translator) html_translated = ''.join(html_translator.fragment).strip() assert", "assert doctree[0][4][0][0].astext() == 'Hello' @pytest.mark.sphinx('dummy', testroot='default_role') def test_default_role1(app, status, warning):", "nodes.Text) assert rst[0][0][0] == 'Hello world' # rst_epilog assert_node(rst[-1], nodes.section)", "addnodes.download_reference, nodes.literal, \"reftitle\"]) assert_node(doctree[0][0], refdoc='dummy', refdomain='', reftype='download', refexplicit=True, reftarget='sphinx.rst', refwarn=False)", "@Γ\\\\∞${}', None, ('\\\\begin{sphinxVerbatim}[commandchars=\\\\\\\\\\\\{\\\\}]\\n' '@Γ\\\\PYGZbs{}\\\\(\\\\infty\\\\)\\\\PYGZdl{}\\\\PYGZob{}\\\\PYGZcb{}\\n' '\\\\end{sphinxVerbatim}'), ), ( # in URIs", "parse): def verify(rst, html_expected): document = parse(rst) KeyboardTransform(document).apply() html_translator =", "notranslate\">' '<kbd class=\"kbd docutils literal notranslate\">Control</kbd>' '+' '<kbd class=\"kbd docutils", "verifier = get_verifier(type) verifier(rst, html_expected, latex_expected) @pytest.mark.parametrize('type,rst,html_expected,latex_expected', [ ( 'verify',", "[nodes.paragraph, nodes.literal, (\"a\", [nodes.emphasis, \"{b\"], \"}c\")]) # half-opened braces text", "test_default_role2(app, status, warning): app.builder.build_all() # default-role directive is stronger than", "# description list: simple 'verify', 'term\\n description', '<dl class=\"docutils\">\\n<dt>term</dt><dd>description</dd>\\n</dl>', None,", "doctree = app.env.get_doctree('index') assert_node(doctree[0], nodes.section) assert len(doctree[0]) == 1 @pytest.mark.sphinx('dummy',", "nodes.literal, 'text()']) assert_node(doctrees[0], refdoc='dummy', refdomain='', reftype='ref', reftarget='text', refexplicit=False, refwarn=False) #", "class=\"(samp )?docutils literal notranslate\"><span class=\"pre\">' 'code</span>&#160;&#160; <span class=\"pre\">sample</span></code></p>'), r'\\\\sphinxAtStartPar\\n\\\\sphinxcode{\\\\sphinxupquote{code sample}}',", "), ( # kbd role 'verify', ':kbd:`space`', '<p><kbd class=\"kbd docutils", "assert_node(doctree[0][1][1], nodes.target) assert_node(doctree[0][1][2], nodes.reference, classes=[\"pep\"]) # no default-role doctree =", "'<dt id=\"term-term1\">term1<a class=\"headerlink\" href=\"#term-term1\"' ' title=\"Permalink to this term\">¶</a></dt>' '<dt", "latex_expected) return verify_re_ @pytest.fixture def verify(verify_re_html, verify_re_latex): def verify_(rst, html_expected,", "code fragments 'verify', '::\\n\\n @Γ\\\\∞${}', None, ('\\\\begin{sphinxVerbatim}[commandchars=\\\\\\\\\\\\{\\\\}]\\n' '@Γ\\\\PYGZbs{}∞\\\\PYGZdl{}\\\\PYGZob{}\\\\PYGZcb{}\\n' '\\\\end{sphinxVerbatim}'), ),", "the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for", "{}, []) assert len(doctrees) == 1 assert_node(doctrees[0], [addnodes.pending_xref, nodes.literal, 'text'])", "doctree = app.env.get_doctree('index') assert_node(doctree[0], nodes.section) assert len(doctree[0]) == 2 assert_node(doctree[0][1],", "5, inliner, {}, []) assert_node(doctrees[0], [addnodes.pending_xref, nodes.literal, 'text()']) assert_node(doctrees[0], refdoc='dummy',", "('<dl class=\"docutils\">\\n<dt>term<span class=\"classifier\">class1</span>' '<span class=\"classifier\">class2</span></dt><dd>description</dd>\\n</dl>'), None, ), ( # glossary", "2324\\\\#id1@\\\\spxentry{RFC 2324\\\\#id1}}' '\\\\sphinxhref{http://tools.ietf.org/html/rfc2324.html\\\\#id1}' '{\\\\sphinxstylestrong{RFC 2324\\\\#id1}}') ), ( # correct interpretation", "repr(rst) return verify @pytest.fixture def verify_re(verify_re_html, verify_re_latex): def verify_re_(rst, html_expected,", "texescape from sphinx.util.docutils import sphinx_domains from sphinx.writers.html import HTMLTranslator, HTMLWriter", "if html_expected: verify_re_html(rst, re.escape(html_expected) + '$') if latex_expected: verify_re_latex(rst, re.escape(latex_expected)", "{}, []) assert_node(doctrees[0], [addnodes.pending_xref, nodes.literal, 'text()']) assert_node(doctrees[0], refdoc='dummy', refdomain='', reftype='ref',", "'href=\"http://tools.ietf.org/html/rfc2324.html#id1\">' '<strong>RFC 2324#id1</strong></a></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\index{RFC@\\\\spxentry{RFC}!RFC 2324\\\\#id1@\\\\spxentry{RFC 2324\\\\#id1}}' '\\\\sphinxhref{http://tools.ietf.org/html/rfc2324.html\\\\#id1}' '{\\\\sphinxstylestrong{RFC 2324\\\\#id1}}')", "[nodes.literal, 'title <target>']) # refdomain doctrees, errors = role('test:doc', 'rawtext',", "with whitespace 'verify_re', '``code sample``', ('<p><code class=\"(samp )?docutils literal notranslate\"><span", "), ( # in verbatim code fragments 'verify', '::\\n\\n @Γ\\\\∞${}',", "'<kbd class=\"kbd docutils literal notranslate\">^</kbd>' '</kbd></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\sphinxkeyboard{\\\\sphinxupquote{Alt+\\\\textasciicircum{}}}'), ), (", "[nodes.paragraph, nodes.literal, (\"a\", [nodes.emphasis, \"b\"], \"c\")]) # nested braces text", "for msg in document.traverse(nodes.system_message): if msg['level'] == 1: msg.replace_self([]) return", "= role('ref', 'rawtext', 'text', 5, inliner, {}, []) assert len(doctrees)", "test_inline_docutils16(get_verifier, type, rst, html_expected, latex_expected): verifier = get_verifier(type) verifier(rst, html_expected,", "guilabel 'verify', ':guilabel:`&Foo -&&- &Bar`', ('<p><span class=\"guilabel\"><span class=\"accelerator\">F</span>oo ' '-&amp;-", "external\" ' 'href=\"http://www.python.org/dev/peps/pep-0008#id1\">' '<strong>PEP 8#id1</strong></a></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\index{Python Enhancement Proposals@\\\\spxentry{Python Enhancement", "role 'verify', ':rfc:`2324`', ('<p><span class=\"target\" id=\"index-0\"></span><a class=\"rfc reference external\" '", "= parse(rst) app.builder = LaTeXBuilder(app) app.builder.set_environment(app.env) app.builder.init() theme = app.builder.themes.get('manual')", "), ( # rfc role with anchor 'verify', ':rfc:`2324#id1`', ('<p><span", "refdomain='', reftype='ref', reftarget='text', refexplicit=False, refwarn=False) assert errors == [] #", "refdomain='', reftype='ref', reftarget='text', refexplicit=False, refwarn=False) # lowercase role = XRefRole(lowercase=True)", "class=\"headerlink\" href=\"#term-term1\"' ' title=\"Permalink to this term\">¶</a></dt>' '<dt id=\"term-term2\">term2<a class=\"headerlink\"", "verify, 'verify_re': verify_re, } def get(name): return v[name] return get", "latex_expected): verifier = get_verifier(type) verifier(rst, html_expected, latex_expected) def test_samp_role(parse): #", "ForgivingLaTeXTranslator(document, app.builder, theme) latex_translator.first_document = -1 # don't write \\begin{document}", "id=\"index-0\"></span><a class=\"pep reference external\" ' 'href=\"http://www.python.org/dev/peps/pep-0008\"><strong>PEP 8</strong></a></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\index{Python Enhancement", "LaTeXWriter)) settings = optparser.get_default_values() settings.smart_quotes = True settings.env = app.builder.env", "return verify @pytest.fixture def verify_re(verify_re_html, verify_re_latex): def verify_re_(rst, html_expected, latex_expected):", "Proposals}' '!PEP 8@\\\\spxentry{PEP 8}}\\\\sphinxhref{http://www.python.org/dev/peps/pep-0008}' '{\\\\sphinxstylestrong{PEP 8}}') ), ( # pep", "@pytest.mark.sphinx('dummy', testroot='keep_warnings') def test_keep_warnings_is_True(app, status, warning): app.builder.build_all() doctree = app.env.get_doctree('index')", "app.builder.build_all() # default-role directive is stronger than configratuion doctree =", "class=\"rfc reference external\" ' 'href=\"http://tools.ietf.org/html/rfc2324.html\"><strong>RFC 2324</strong></a></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\index{RFC@\\\\spxentry{RFC}!RFC 2324@\\\\spxentry{RFC 2324}}'", "':kbd:`Control+X`', ('<p><kbd class=\"kbd compound docutils literal notranslate\">' '<kbd class=\"kbd docutils", "\"{b\"], \"}c\")]) # half-opened braces text = ':samp:`a{bc`' doctree =", "errors = role('ref', 'rawtext', 'TEXT', 5, inliner, {}, []) assert_node(doctrees[0],", "interpolation of ampersands in guilabel 'verify', ':guilabel:`&Foo -&&- &Bar`', ('<p><span", "), ( # ... but not in literal text 'verify',", "errors = role('ref', 'rawtext', 'title <target>', 5, inliner, {}, [])", "these nodes may remain class ForgivingTranslator: def visit_pending_xref(self, node): pass", "refwarn=False) assert errors == [] # explicit doctrees, errors =", "class=\"kbd compound docutils literal notranslate\">' '<kbd class=\"kbd docutils literal notranslate\">Alt</kbd>'", "warning): app.builder.build_all() rst = app.env.get_doctree('restructuredtext') md = app.env.get_doctree('markdown') # rst_prolog", "on exlucding reST parser assert not md.rawsource.startswith('*Hello world*.') assert not", "create @pytest.fixture def inliner(new_document): document = new_document() document.reporter.get_source_and_line = lambda", "len(doctrees) == 1 assert_node(doctrees[0], [addnodes.pending_xref, nodes.literal, 'text']) assert_node(doctrees[0], refdoc='dummy', refdomain='',", "configratuion doctree = app.env.get_doctree('index') assert_node(doctree[0], nodes.section) assert_node(doctree[0][1], nodes.paragraph) assert_node(doctree[0][1][0], addnodes.index)", "LICENSE for details. \"\"\" import re import pytest from docutils", "return verify_re_ @pytest.fixture def verify(verify_re_html, verify_re_latex): def verify_(rst, html_expected, latex_expected):", "classes=[\"pep\"]) # default_role changes the default behavior doctree = app.env.get_doctree('foo')", "nodes.emphasis) assert_node(rst[0][0][0], nodes.Text) assert rst[0][0][0] == 'Hello world' # rst_epilog", "= True settings.env = app.builder.env settings.env.temp_data['docname'] = 'dummy' settings.contentsname =", "reporter=document.reporter) @pytest.fixture def parse(new_document): def parse_(rst): document = new_document() parser", "errors = role('ref', 'rawtext', '!title <target>', 5, inliner, {}, [])", "from sphinx import addnodes from sphinx.builders.html.transforms import KeyboardTransform from sphinx.builders.latex", "# in verbatim code fragments 'verify', '::\\n\\n @Γ\\\\∞${}', None, ('\\\\begin{sphinxVerbatim}[commandchars=\\\\\\\\\\\\{\\\\}]\\n'", "class=\"kbd docutils literal notranslate\">x</kbd>' ' ' '<kbd class=\"kbd docutils literal", "= sphinx_domains(settings.env) domain_context.enable() yield settings domain_context.disable() @pytest.fixture def new_document(settings): def", "sphinx.roles import XRefRole from sphinx.testing.util import Struct, assert_node from sphinx.transforms", "), ( # rfc role 'verify', ':rfc:`2324`', ('<p><span class=\"target\" id=\"index-0\"></span><a", "# fix_parens role = XRefRole(fix_parens=True) doctrees, errors = role('ref', 'rawtext',", "None, ), ]) @pytest.mark.skipif(docutils.__version_info__ < (0, 16), reason='docutils-0.16 or above", "@pytest.fixture def verify_re_latex(app, parse): def verify(rst, latex_expected): document = parse(rst)", "classes for inline roles 'verify', ':manpage:`mp(1)`', '<p><em class=\"manpage\">mp(1)</em></p>', '\\\\sphinxAtStartPar\\n\\\\sphinxstyleliteralemphasis{\\\\sphinxupquote{mp(1)}}', ),", "get_verifier(type) verifier(rst, html_expected, latex_expected) @pytest.mark.sphinx(confoverrides={'latex_engine': 'xelatex'}) @pytest.mark.parametrize('type,rst,html_expected,latex_expected', [ ( #", "@pytest.mark.sphinx('dummy', testroot='default_role') def test_default_role1(app, status, warning): app.builder.build_all() # default-role: pep", "term1\\n term2\\n description', ('<dl class=\"glossary docutils\">\\n' '<dt id=\"term-term1\">term1<a class=\"headerlink\" href=\"#term-term1\"'", "assert_node(doctree[0][0][0], classes=['xref', 'download']) # explicit text = ':download:`reftitle <sphinx.rst>`' doctree", "assert_node(doctree[0], nodes.section) assert len(doctree[0]) == 2 assert_node(doctree[0][1], nodes.system_message) @pytest.mark.sphinx('dummy', testroot='keep_warnings',", "default-role directive is stronger than configratuion doctree = app.env.get_doctree('index') assert_node(doctree[0],", "]) @pytest.mark.skipif(docutils.__version_info__ < (0, 16), reason='docutils-0.16 or above is required')", "in normal mode 'verify', 'Γ\\\\\\\\∞$', None, '\\\\sphinxAtStartPar\\nΓ\\\\textbackslash{}\\\\(\\\\infty\\\\)\\\\$', ), ( #", "literal notranslate\"><span class=\"pre\">' '&quot;John&quot;</span></code></p>'), '\\\\sphinxAtStartPar\\n\\\\sphinxcode{\\\\sphinxupquote{\"John\"}}', ), ( # verify classes", "refexplicit=True, refwarn=False) # bang doctrees, errors = role('ref', 'rawtext', '!title", "nodes.Text) @pytest.mark.sphinx('dummy', testroot='default_role', confoverrides={'default_role': 'guilabel'}) def test_default_role2(app, status, warning): app.builder.build_all()", "= 'dummy' return document return create @pytest.fixture def inliner(new_document): document", "multiple terms 'verify', '.. glossary::\\n\\n term1\\n term2\\n description', ('<dl class=\"glossary", "('\\\\sphinxAtStartPar\\n' '\\\\sphinxkeyboard{\\\\sphinxupquote{\\\\sphinxhyphen{}}}'), ), ( # kbd role 'verify', ':kbd:`Caps Lock`',", "document.traverse(nodes.system_message): if msg['level'] == 1: msg.replace_self([]) return document return parse_", "' + repr(rst) return verify @pytest.fixture def verify_re(verify_re_html, verify_re_latex): def", "notranslate\">X</kbd>' '</kbd></p>'), '\\\\sphinxAtStartPar\\n\\\\sphinxkeyboard{\\\\sphinxupquote{Control+X}}', ), ( # kbd role 'verify', ':kbd:`Alt+^`',", "def verify_re_(rst, html_expected, latex_expected): if html_expected: verify_re_html(rst, html_expected) if latex_expected:", "assert_node(rst[0][0], nodes.emphasis) assert_node(rst[0][0][0], nodes.Text) assert rst[0][0][0] == 'Hello world' #", "'verify', '\"John\"', '<p>“John”</p>', \"\\\\sphinxAtStartPar\\n“John”\", ), ( # ... but not", "'Γ\\\\\\\\∞$', None, '\\\\sphinxAtStartPar\\nΓ\\\\textbackslash{}\\\\(\\\\infty\\\\)\\\\$', ), ( # in verbatim code fragments", "docutils literal notranslate\">-</kbd></p>', ('\\\\sphinxAtStartPar\\n' '\\\\sphinxkeyboard{\\\\sphinxupquote{\\\\sphinxhyphen{}}}'), ), ( # kbd role", "msg.replace_self([]) return document return parse_ # since we're not resolving", "def test_samp_role(parse): # no braces text = ':samp:`a{b}c`' doctree =", "assert_node(doctree[0][0], refdoc='dummy', refdomain='', reftype='download', refexplicit=True, reftarget='sphinx.rst', refwarn=False) assert_node(doctree[0][0][0], classes=['xref', 'download'])", "implicit text = ':download:`sphinx.rst`' doctree = parse(text) assert_node(doctree[0], [nodes.paragraph, addnodes.download_reference,", "assert_node(doctree[0][0][0], classes=['xref', 'download']) def test_XRefRole(inliner): role = XRefRole() # implicit", "= XRefRole(fix_parens=True) doctrees, errors = role('ref', 'rawtext', 'text()', 5, inliner,", "from sphinx.testing.util import Struct, assert_node from sphinx.transforms import SphinxSmartQuotes from", "id=\"index-0\"></span><a class=\"pep reference external\" ' 'href=\"http://www.python.org/dev/peps/pep-0008#id1\">' '<strong>PEP 8#id1</strong></a></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\index{Python", "[ ( 'verify', r'4 backslashes \\\\\\\\', r'<p>4 backslashes \\\\</p>', None,", "8\\\\#id1}}') ), ( # rfc role 'verify', ':rfc:`2324`', ('<p><span class=\"target\"", "we're not resolving the markup afterwards, these nodes may remain", "refexplicit=True, reftarget='sphinx.rst', refwarn=False) assert_node(doctree[0][0][0], classes=['xref', 'download']) def test_XRefRole(inliner): role =", "doctree = app.env.get_doctree('foo') assert_node(doctree[0], nodes.section) assert_node(doctree[0][1], nodes.paragraph) assert_node(doctree[0][1][0], nodes.title_reference) assert_node(doctree[0][1][1],", "description', ('<dl class=\"docutils\">\\n<dt>term<span class=\"classifier\">class1</span>' '<span class=\"classifier\">class2</span></dt><dd>description</dd>\\n</dl>'), None, ), ( #", "'<kbd class=\"kbd docutils literal notranslate\">s</kbd>' '</kbd></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\sphinxkeyboard{\\\\sphinxupquote{M\\\\sphinxhyphen{}x M\\\\sphinxhyphen{}s}}'), ),", "latex_expected): if html_expected: verify_re_html(rst, html_expected) if latex_expected: verify_re_latex(rst, latex_expected) return", "= ''.join(latex_translator.body).strip() assert re.match(latex_expected, latex_translated), 'from ' + repr(rst) return", "get_verifier(verify, verify_re): v = { 'verify': verify, 'verify_re': verify_re, }", "('<p><code class=\"(samp )?docutils literal notranslate\"><span class=\"pre\">' 'code</span>&#160;&#160; <span class=\"pre\">sample</span></code></p>'), r'\\\\sphinxAtStartPar\\n\\\\sphinxcode{\\\\sphinxupquote{code", "assert_node(rst[0], nodes.paragraph) assert_node(rst[0][0], nodes.emphasis) assert_node(rst[0][0][0], nodes.Text) assert rst[0][0][0] == 'Hello", "role 'verify', ':kbd:`Control+X`', ('<p><kbd class=\"kbd compound docutils literal notranslate\">' '<kbd", "app.builder.init() theme = app.builder.themes.get('manual') latex_translator = ForgivingLaTeXTranslator(document, app.builder, theme) latex_translator.first_document", "text = ':samp:`a{{b}}c`' doctree = parse(text) assert_node(doctree[0], [nodes.paragraph, nodes.literal, (\"a\",", "braces text = ':samp:`a{bc`' doctree = parse(text) assert_node(doctree[0], [nodes.paragraph, nodes.literal,", "= parse(rst) KeyboardTransform(document).apply() html_translator = ForgivingHTMLTranslator(document, app.builder) document.walkabout(html_translator) html_translated =", "( # description list: simple 'verify', 'term\\n description', '<dl class=\"docutils\">\\n<dt>term</dt><dd>description</dd>\\n</dl>',", "parse_ # since we're not resolving the markup afterwards, these", "app.env.get_doctree('markdown') # rst_prolog assert_node(rst[0], nodes.paragraph) assert_node(rst[0][0], nodes.emphasis) assert_node(rst[0][0][0], nodes.Text) assert", "no default-role doctree = app.env.get_doctree('foo') assert_node(doctree[0], nodes.section) assert_node(doctree[0][1], nodes.paragraph) assert_node(doctree[0][1][0],", "nodes.literal, (\"a\", [nodes.emphasis, \"b\"], \"c\")]) # nested braces text =", "app.builder.build_all() doctree = app.env.get_doctree('index') assert_node(doctree[0], nodes.section) assert len(doctree[0]) == 5", "), ( # kbd role 'verify', ':kbd:`-`', '<p><kbd class=\"kbd docutils", "ForgivingHTMLTranslator(HTMLTranslator, ForgivingTranslator): pass class ForgivingLaTeXTranslator(LaTeXTranslator, ForgivingTranslator): pass @pytest.fixture def verify_re_html(app,", "@pytest.mark.sphinx('dummy', testroot='keep_warnings', confoverrides={'keep_warnings': False}) def test_keep_warnings_is_False(app, status, warning): app.builder.build_all() doctree", "@pytest.mark.sphinx(confoverrides={'latex_engine': 'xelatex'}) @pytest.mark.parametrize('type,rst,html_expected,latex_expected', [ ( # in verbatim code fragments", "'List A:' assert_node(doctree[0][2], nodes.bullet_list) assert_node(doctree[0][2][0][0], addnodes.compact_paragraph) assert doctree[0][2][0][0].astext() == 'genindex'", "html_expected, latex_expected) @pytest.mark.parametrize('type,rst,html_expected,latex_expected', [ ( 'verify', r'4 backslashes \\\\\\\\', r'<p>4", "( # interpolation of ampersands in menuselection 'verify', ':menuselection:`&Foo -&&-", "app.env.get_doctree('foo') assert_node(doctree[0], nodes.section) assert_node(doctree[0][1], nodes.paragraph) assert_node(doctree[0][1][0], nodes.inline, classes=[\"guilabel\"]) assert_node(doctree[0][1][1], nodes.Text)", "line=1: ('dummy.rst', line) return Struct(document=document, reporter=document.reporter) @pytest.fixture def parse(new_document): def", "class2\\n description', ('<dl class=\"docutils\">\\n<dt>term<span class=\"classifier\">class1</span>' '<span class=\"classifier\">class2</span></dt><dd>description</dd>\\n</dl>'), None, ), (", "# correct escaping in normal mode 'verify', 'Γ\\\\\\\\∞$', None, '\\\\sphinxAtStartPar\\nΓ\\\\textbackslash{}\\\\(\\\\infty\\\\)\\\\$',", "literal notranslate\">Alt</kbd>' '+' '<kbd class=\"kbd docutils literal notranslate\">^</kbd>' '</kbd></p>'), ('\\\\sphinxAtStartPar\\n'", "by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE", "refdomain='', reftype='ref', reftarget='text', refexplicit=False, refwarn=False) @pytest.mark.sphinx('dummy', testroot='prolog') def test_rst_prolog(app, status,", "assert_node(doctree[0][1], nodes.system_message) @pytest.mark.sphinx('dummy', testroot='keep_warnings', confoverrides={'keep_warnings': False}) def test_keep_warnings_is_False(app, status, warning):", "md.rawsource.endswith('*Good-bye world*.\\n') @pytest.mark.sphinx('dummy', testroot='keep_warnings') def test_keep_warnings_is_True(app, status, warning): app.builder.build_all() doctree", "import docutils, texescape from sphinx.util.docutils import sphinx_domains from sphinx.writers.html import", "# implicit text = ':download:`sphinx.rst`' doctree = parse(text) assert_node(doctree[0], [nodes.paragraph,", "classes=[\"pep\"]) # no default-role doctree = app.env.get_doctree('foo') assert_node(doctree[0], nodes.section) assert_node(doctree[0][1],", "verify_re_latex(rst, re.escape(latex_expected) + '$') return verify_ @pytest.fixture def get_verifier(verify, verify_re):", "--> b`', ('<p><span class=\"menuselection\">a \\N{TRIANGULAR BULLET} b</span></p>'), '\\\\sphinxAtStartPar\\n\\\\sphinxmenuselection{a \\\\(\\\\rightarrow\\\\) b}',", "), ( # glossary (description list): multiple terms 'verify', '..", "'@Γ\\\\PYGZbs{}∞\\\\PYGZdl{}\\\\PYGZob{}\\\\PYGZcb{}\\n' '\\\\end{sphinxVerbatim}'), ), ]) def test_inline_for_unicode_latex_engine(get_verifier, type, rst, html_expected, latex_expected):", "verify_re_latex(app, parse): def verify(rst, latex_expected): document = parse(rst) app.builder =", "id=\"term-term1\">term1<a class=\"headerlink\" href=\"#term-term1\"' ' title=\"Permalink to this term\">¶</a></dt>' '<dt id=\"term-term2\">term2<a", "assert len(doctrees) == 1 assert_node(doctrees[0], [addnodes.pending_xref, nodes.literal, 'text']) assert_node(doctrees[0], refdoc='dummy',", "class=\"kbd docutils literal notranslate\">space</kbd></p>', '\\\\sphinxAtStartPar\\n\\\\sphinxkeyboard{\\\\sphinxupquote{space}}', ), ( # kbd role", "the latex builder optparser = frontend.OptionParser( components=(RstParser, HTMLWriter, LaTeXWriter)) settings", "= role('ref', 'rawtext', '!title <target>', 5, inliner, {}, []) assert_node(doctrees[0],", "from docutils import frontend, nodes, utils from docutils.parsers.rst import Parser", "list: simple 'verify', 'term\\n description', '<dl class=\"docutils\">\\n<dt>term</dt><dd>description</dd>\\n</dl>', None, ), (", "from docutils.parsers.rst import Parser as RstParser from sphinx import addnodes", "literal notranslate\">' '<kbd class=\"kbd docutils literal notranslate\">M</kbd>' '-' '<kbd class=\"kbd", "( # interpolation of ampersands in guilabel 'verify', ':guilabel:`&Foo -&&-", "<span class=\"accelerator\">B</span>ar</span></p>'), ('\\\\sphinxAtStartPar\\n' r'\\sphinxmenuselection{\\sphinxaccelerator{F}oo \\sphinxhyphen{}' r'\\&\\sphinxhyphen{} \\sphinxaccelerator{B}ar}'), ), ( #", "class=\"pre\">' '&quot;John&quot;</span></code></p>'), '\\\\sphinxAtStartPar\\n\\\\sphinxcode{\\\\sphinxupquote{\"John\"}}', ), ( # verify classes for inline", "8</strong></a></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\index{Python Enhancement Proposals@\\\\spxentry{Python Enhancement Proposals}' '!PEP 8@\\\\spxentry{PEP 8}}\\\\sphinxhref{http://www.python.org/dev/peps/pep-0008}'", "def verify_(rst, html_expected, latex_expected): if html_expected: verify_re_html(rst, re.escape(html_expected) + '$')", "notranslate\">x</kbd>' ' ' '<kbd class=\"kbd docutils literal notranslate\">M</kbd>' '-' '<kbd", "rst, html_expected, latex_expected): verifier = get_verifier(type) verifier(rst, html_expected, latex_expected) @pytest.mark.sphinx(confoverrides={'latex_engine':", "list): multiple terms 'verify', '.. glossary::\\n\\n term1\\n term2\\n description', ('<dl", "<sphinx.rst>`' doctree = parse(text) assert_node(doctree[0], [nodes.paragraph, addnodes.download_reference, nodes.literal, \"reftitle\"]) assert_node(doctree[0][0],", "'\\\\sphinxkeyboard{\\\\sphinxupquote{\\\\sphinxhyphen{}}}'), ), ( # kbd role 'verify', ':kbd:`Caps Lock`', '<p><kbd", "explicit text = ':download:`reftitle <sphinx.rst>`' doctree = parse(text) assert_node(doctree[0], [nodes.paragraph,", "sphinx.transforms import SphinxSmartQuotes from sphinx.util import docutils, texescape from sphinx.util.docutils", "components=(RstParser, HTMLWriter, LaTeXWriter)) settings = optparser.get_default_values() settings.smart_quotes = True settings.env", "utils from docutils.parsers.rst import Parser as RstParser from sphinx import", "classes=['xref', 'download']) def test_XRefRole(inliner): role = XRefRole() # implicit doctrees,", "\\sphinxhyphen{}' r'\\&\\sphinxhyphen{} \\sphinxaccelerator{B}ar}'), ), ( # interpolation of ampersands in", "extensions. :copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS.", "docutils literal notranslate\">x</kbd>' ' ' '<kbd class=\"kbd docutils literal notranslate\">M</kbd>'", "inliner, {}, []) assert_node(doctrees[0], [addnodes.pending_xref, nodes.literal, 'title']) assert_node(doctrees[0], refdoc='dummy', refdomain='',", "class=\"kbd docutils literal notranslate\">Alt</kbd>' '+' '<kbd class=\"kbd docutils literal notranslate\">^</kbd>'", "notranslate\">s</kbd>' '</kbd></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\sphinxkeyboard{\\\\sphinxupquote{M\\\\sphinxhyphen{}x M\\\\sphinxhyphen{}s}}'), ), ( # kbd role", "= { 'verify': verify, 'verify_re': verify_re, } def get(name): return", "1: msg.replace_self([]) return document return parse_ # since we're not", "assert rst[-1][-1][0][0] == 'Good-bye world' # rst_prolog & rst_epilog on", "latex_translated), 'from ' + repr(rst) return verify @pytest.fixture def verify_re(verify_re_html,", "description', ('<dl class=\"glossary docutils\">\\n' '<dt id=\"term-term1\">term1<a class=\"headerlink\" href=\"#term-term1\"' ' title=\"Permalink", "app.env.get_doctree('restructuredtext') md = app.env.get_doctree('markdown') # rst_prolog assert_node(rst[0], nodes.paragraph) assert_node(rst[0][0], nodes.emphasis)", "text = ':samp:`a{b}c`' doctree = parse(text) assert_node(doctree[0], [nodes.paragraph, nodes.literal, (\"a\",", "# nested braces text = ':samp:`a{{b}}c`' doctree = parse(text) assert_node(doctree[0],", "'verify', ':manpage:`mp(1)`', '<p><em class=\"manpage\">mp(1)</em></p>', '\\\\sphinxAtStartPar\\n\\\\sphinxstyleliteralemphasis{\\\\sphinxupquote{mp(1)}}', ), ( # correct escaping", "), ( # verify classes for inline roles 'verify', ':manpage:`mp(1)`',", "notranslate\")?>' '<span class=\"pre\">--with-option</span></code></p>$'), (r'\\\\sphinxAtStartPar\\n' r'\\\\sphinxcode{\\\\sphinxupquote{\\\\sphinxhyphen{}\\\\sphinxhyphen{}with\\\\sphinxhyphen{}option}}$'), ), ( # verify smarty-pants", "class=\"classifier\">class2</span></dt><dd>description</dd>\\n</dl>'), None, ), ( # glossary (description list): multiple terms", "notranslate\">M</kbd>' '-' '<kbd class=\"kbd docutils literal notranslate\">s</kbd>' '</kbd></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\sphinxkeyboard{\\\\sphinxupquote{M\\\\sphinxhyphen{}x", "'verify', ':kbd:`Caps Lock`', '<p><kbd class=\"kbd docutils literal notranslate\">Caps Lock</kbd></p>', ('\\\\sphinxAtStartPar\\n'", "( # rfc role 'verify', ':rfc:`2324`', ('<p><span class=\"target\" id=\"index-0\"></span><a class=\"rfc", "None, ), ]) def test_inline(get_verifier, type, rst, html_expected, latex_expected): verifier", "RstParser from sphinx import addnodes from sphinx.builders.html.transforms import KeyboardTransform from", "-&&- &Bar`', ('<p><span class=\"menuselection\"><span class=\"accelerator\">F</span>oo ' '-&amp;- <span class=\"accelerator\">B</span>ar</span></p>'), ('\\\\sphinxAtStartPar\\n'", "# kbd role 'verify', ':kbd:`M-x M-s`', ('<p><kbd class=\"kbd compound docutils", "= role('ref', 'rawtext', 'text()', 5, inliner, {}, []) assert_node(doctrees[0], [addnodes.pending_xref,", "class=\"accelerator\">B</span>ar</span></p>'), ('\\\\sphinxAtStartPar\\n' r'\\sphinxguilabel{\\sphinxaccelerator{F}oo \\sphinxhyphen{}\\&\\sphinxhyphen{} \\sphinxaccelerator{B}ar}'), ), ( # no ampersands", "'dummy' settings.contentsname = 'dummy' settings.rfc_base_url = 'http://tools.ietf.org/html/' domain_context = sphinx_domains(settings.env)", "<target>']) # refdomain doctrees, errors = role('test:doc', 'rawtext', 'text', 5,", "docutils literal notranslate\">Control</kbd>' '+' '<kbd class=\"kbd docutils literal notranslate\">X</kbd>' '</kbd></p>'),", "role 'verify', ':pep:`8`', ('<p><span class=\"target\" id=\"index-0\"></span><a class=\"pep reference external\" '", "html_expected, latex_expected): verifier = get_verifier(type) verifier(rst, html_expected, latex_expected) def test_samp_role(parse):", "code with whitespace 'verify_re', '``code sample``', ('<p><code class=\"(samp )?docutils literal", "sphinx_domains from sphinx.writers.html import HTMLTranslator, HTMLWriter from sphinx.writers.latex import LaTeXTranslator,", "sphinx.builders.html.transforms import KeyboardTransform from sphinx.builders.latex import LaTeXBuilder from sphinx.roles import", "dashes in option role 'verify_re', ':option:`--with-option`', ('<p><code( class=\"xref std std-option", "':samp:`code sample`' doctree = parse(text) assert_node(doctree[0], [nodes.paragraph, nodes.literal, \"code sample\"])", "), ( # verify smarty-pants quotes 'verify', '\"John\"', '<p>“John”</p>', \"\\\\sphinxAtStartPar\\n“John”\",", "':kbd:`Caps Lock`', '<p><kbd class=\"kbd docutils literal notranslate\">Caps Lock</kbd></p>', ('\\\\sphinxAtStartPar\\n' '\\\\sphinxkeyboard{\\\\sphinxupquote{Caps", "[addnodes.pending_xref, nodes.literal, 'text()']) assert_node(doctrees[0], refdoc='dummy', refdomain='', reftype='ref', reftarget='text', refexplicit=False, refwarn=False)", "with anchor 'verify', ':pep:`8#id1`', ('<p><span class=\"target\" id=\"index-0\"></span><a class=\"pep reference external\"", "test_download_role(parse): # implicit text = ':download:`sphinx.rst`' doctree = parse(text) assert_node(doctree[0],", "html_translated = ''.join(html_translator.fragment).strip() assert re.match(html_expected, html_translated), 'from ' + rst", "def parse_(rst): document = new_document() parser = RstParser() parser.parse(rst, document)", "== 1 @pytest.mark.sphinx('dummy', testroot='refonly_bullet_list') def test_compact_refonly_bullet_list(app, status, warning): app.builder.build_all() doctree", "class ForgivingHTMLTranslator(HTMLTranslator, ForgivingTranslator): pass class ForgivingLaTeXTranslator(LaTeXTranslator, ForgivingTranslator): pass @pytest.fixture def", "document.reporter.get_source_and_line = lambda line=1: ('dummy.rst', line) return Struct(document=document, reporter=document.reporter) @pytest.fixture", "doctrees, errors = role('ref', 'rawtext', 'text()', 5, inliner, {}, [])", "classifiers 'verify', 'term : class1 : class2\\n description', ('<dl class=\"docutils\">\\n<dt>term<span", "afterwards, these nodes may remain class ForgivingTranslator: def visit_pending_xref(self, node):", "re.escape(latex_expected) + '$') return verify_ @pytest.fixture def get_verifier(verify, verify_re): v", "class=\"kbd docutils literal notranslate\">Caps Lock</kbd></p>', ('\\\\sphinxAtStartPar\\n' '\\\\sphinxkeyboard{\\\\sphinxupquote{Caps Lock}}'), ), (", "nodes.section) assert_node(doctree[0][1], nodes.paragraph) assert_node(doctree[0][1][0], nodes.title_reference) assert_node(doctree[0][1][1], nodes.Text) @pytest.mark.sphinx('dummy', testroot='default_role', confoverrides={'default_role':", "nodes.section) assert len(doctree[0]) == 1 @pytest.mark.sphinx('dummy', testroot='refonly_bullet_list') def test_compact_refonly_bullet_list(app, status,", "= ':samp:`a{{b}}c`' doctree = parse(text) assert_node(doctree[0], [nodes.paragraph, nodes.literal, (\"a\", [nodes.emphasis,", "( # pep role with anchor 'verify', ':pep:`8#id1`', ('<p><span class=\"target\"", "class=\"pre\">sample</span></code></p>'), r'\\\\sphinxAtStartPar\\n\\\\sphinxcode{\\\\sphinxupquote{code sample}}', ), ( # interpolation of arrows in", "'text', 5, inliner, {}, []) assert len(doctrees) == 1 assert_node(doctrees[0],", "import KeyboardTransform from sphinx.builders.latex import LaTeXBuilder from sphinx.roles import XRefRole", "reftarget='text', refexplicit=False, refwarn=False) # lowercase role = XRefRole(lowercase=True) doctrees, errors", "@pytest.mark.sphinx('dummy', testroot='refonly_bullet_list') def test_compact_refonly_bullet_list(app, status, warning): app.builder.build_all() doctree = app.env.get_doctree('index')", ":copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS. :license:", "= get_verifier(type) verifier(rst, html_expected, latex_expected) @pytest.mark.sphinx(confoverrides={'latex_engine': 'xelatex'}) @pytest.mark.parametrize('type,rst,html_expected,latex_expected', [ (", "'$') if latex_expected: verify_re_latex(rst, re.escape(latex_expected) + '$') return verify_ @pytest.fixture", "html_expected, latex_expected): verifier = get_verifier(type) verifier(rst, html_expected, latex_expected) @pytest.mark.sphinx(confoverrides={'latex_engine': 'xelatex'})", "docutils.parsers.rst import Parser as RstParser from sphinx import addnodes from", "( # glossary (description list): multiple terms 'verify', '.. glossary::\\n\\n", "5, inliner, {}, []) assert_node(doctrees[0], [addnodes.pending_xref, nodes.literal, 'text']) assert_node(doctrees[0], refdoc='dummy',", "document return parse_ # since we're not resolving the markup", "[] # explicit doctrees, errors = role('ref', 'rawtext', 'title <target>',", "'<p><em class=\"manpage\">mp(1)</em></p>', '\\\\sphinxAtStartPar\\n\\\\sphinxstyleliteralemphasis{\\\\sphinxupquote{mp(1)}}', ), ( # correct escaping in normal", "the markup afterwards, these nodes may remain class ForgivingTranslator: def", "not md.rawsource.startswith('*Hello world*.') assert not md.rawsource.endswith('*Good-bye world*.\\n') @pytest.mark.sphinx('dummy', testroot='keep_warnings') def", "literal notranslate\">Control</kbd>' '+' '<kbd class=\"kbd docutils literal notranslate\">X</kbd>' '</kbd></p>'), '\\\\sphinxAtStartPar\\n\\\\sphinxkeyboard{\\\\sphinxupquote{Control+X}}',", "app.builder.build_all() doctree = app.env.get_doctree('index') assert_node(doctree[0], nodes.section) assert len(doctree[0]) == 1", "rst_epilog assert_node(rst[-1], nodes.section) assert_node(rst[-1][-1], nodes.paragraph) assert_node(rst[-1][-1][0], nodes.emphasis) assert_node(rst[-1][-1][0][0], nodes.Text) assert", "theme) latex_translator.first_document = -1 # don't write \\begin{document} document.walkabout(latex_translator) latex_translated", "md.rawsource.startswith('*Hello world*.') assert not md.rawsource.endswith('*Good-bye world*.\\n') @pytest.mark.sphinx('dummy', testroot='keep_warnings') def test_keep_warnings_is_True(app,", "b}', ), ( # interpolation of ampersands in menuselection 'verify',", "test_keep_warnings_is_False(app, status, warning): app.builder.build_all() doctree = app.env.get_doctree('index') assert_node(doctree[0], nodes.section) assert", "'-' '<kbd class=\"kbd docutils literal notranslate\">x</kbd>' ' ' '<kbd class=\"kbd", "literal notranslate\">M</kbd>' '-' '<kbd class=\"kbd docutils literal notranslate\">x</kbd>' ' '", "), ( # in URIs 'verify_re', '`test <https://www.google.com/~me/>`_', None, r'\\\\sphinxAtStartPar\\n\\\\sphinxhref{https://www.google.com/~me/}{test}.*',", "= parse(text) assert_node(doctree[0], [nodes.paragraph, nodes.literal, (\"a\", [nodes.emphasis, \"{b\"], \"}c\")]) #", "reference external\" ' 'href=\"http://www.python.org/dev/peps/pep-0008#id1\">' '<strong>PEP 8#id1</strong></a></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\index{Python Enhancement Proposals@\\\\spxentry{Python", "'code</span>&#160;&#160; <span class=\"pre\">sample</span></code></p>'), r'\\\\sphinxAtStartPar\\n\\\\sphinxcode{\\\\sphinxupquote{code sample}}', ), ( # interpolation of", "sample\"]) def test_download_role(parse): # implicit text = ':download:`sphinx.rst`' doctree =", "= new_document() parser = RstParser() parser.parse(rst, document) SphinxSmartQuotes(document, startnode=None).apply() for", "assert_node(rst[-1], nodes.section) assert_node(rst[-1][-1], nodes.paragraph) assert_node(rst[-1][-1][0], nodes.emphasis) assert_node(rst[-1][-1][0][0], nodes.Text) assert rst[-1][-1][0][0]", "), ( # kbd role 'verify', ':kbd:`Caps Lock`', '<p><kbd class=\"kbd", "'TEXT', 5, inliner, {}, []) assert_node(doctrees[0], [addnodes.pending_xref, nodes.literal, 'TEXT']) assert_node(doctrees[0],", "compound docutils literal notranslate\">' '<kbd class=\"kbd docutils literal notranslate\">Alt</kbd>' '+'", "'title <target>', 5, inliner, {}, []) assert_node(doctrees[0], [addnodes.pending_xref, nodes.literal, 'title'])", "parse_(rst): document = new_document() parser = RstParser() parser.parse(rst, document) SphinxSmartQuotes(document,", "verify_re_html(rst, html_expected) if latex_expected: verify_re_latex(rst, latex_expected) return verify_re_ @pytest.fixture def", "document = parse(rst) KeyboardTransform(document).apply() html_translator = ForgivingHTMLTranslator(document, app.builder) document.walkabout(html_translator) html_translated", "notranslate\">' '<kbd class=\"kbd docutils literal notranslate\">Alt</kbd>' '+' '<kbd class=\"kbd docutils", "role('test:doc', 'rawtext', 'text', 5, inliner, {}, []) assert_node(doctrees[0], [addnodes.pending_xref, nodes.literal,", "settings.env.temp_data['docname'] = 'dummy' settings.contentsname = 'dummy' settings.rfc_base_url = 'http://tools.ietf.org/html/' domain_context", "settings.contentsname = 'dummy' settings.rfc_base_url = 'http://tools.ietf.org/html/' domain_context = sphinx_domains(settings.env) domain_context.enable()", "= app.env.get_doctree('index') assert_node(doctree[0], nodes.section) assert_node(doctree[0][1], nodes.paragraph) assert_node(doctree[0][1][0], addnodes.index) assert_node(doctree[0][1][1], nodes.target)", "assert_node(rst[0][0][0], nodes.Text) assert rst[0][0][0] == 'Hello world' # rst_epilog assert_node(rst[-1],", "app.env.get_doctree('index') assert_node(doctree[0], nodes.section) assert len(doctree[0]) == 5 assert doctree[0][1].astext() ==", "lambda line=1: ('dummy.rst', line) return Struct(document=document, reporter=document.reporter) @pytest.fixture def parse(new_document):", "class=\"guilabel\"><span class=\"accelerator\">F</span>oo ' '-&amp;- <span class=\"accelerator\">B</span>ar</span></p>'), ('\\\\sphinxAtStartPar\\n' r'\\sphinxguilabel{\\sphinxaccelerator{F}oo \\sphinxhyphen{}\\&\\sphinxhyphen{} \\sphinxaccelerator{B}ar}'),", "depart_pending_xref(self, node): pass class ForgivingHTMLTranslator(HTMLTranslator, ForgivingTranslator): pass class ForgivingLaTeXTranslator(LaTeXTranslator, ForgivingTranslator):", "'@Γ\\\\PYGZbs{}\\\\(\\\\infty\\\\)\\\\PYGZdl{}\\\\PYGZob{}\\\\PYGZcb{}\\n' '\\\\end{sphinxVerbatim}'), ), ( # in URIs 'verify_re', '`test <https://www.google.com/~me/>`_',", "5, inliner, {}, []) assert_node(doctrees[0], [addnodes.pending_xref, nodes.literal, 'TEXT']) assert_node(doctrees[0], refdoc='dummy',", "' title=\"Permalink to this term\">¶</a></dt>' '<dt id=\"term-term2\">term2<a class=\"headerlink\" href=\"#term-term2\"' '", "compound docutils literal notranslate\">' '<kbd class=\"kbd docutils literal notranslate\">M</kbd>' '-'", "document = new_document() document.reporter.get_source_and_line = lambda line=1: ('dummy.rst', line) return", "return verify_ @pytest.fixture def get_verifier(verify, verify_re): v = { 'verify':", "return v[name] return get @pytest.mark.parametrize('type,rst,html_expected,latex_expected', [ ( # pep role", "return get @pytest.mark.parametrize('type,rst,html_expected,latex_expected', [ ( # pep role 'verify', ':pep:`8`',", "None, ), ( # description list: with classifiers 'verify', 'term", "document.walkabout(html_translator) html_translated = ''.join(html_translator.fragment).strip() assert re.match(html_expected, html_translated), 'from ' +", "doctree = parse(text) assert_node(doctree[0], [nodes.paragraph, addnodes.download_reference, nodes.literal, \"sphinx.rst\"]) assert_node(doctree[0][0], refdoc='dummy',", "ForgivingHTMLTranslator(document, app.builder) document.walkabout(html_translator) html_translated = ''.join(html_translator.fragment).strip() assert re.match(html_expected, html_translated), 'from", "[]) assert_node(doctrees[0], [addnodes.pending_xref, nodes.literal, 'title']) assert_node(doctrees[0], refdoc='dummy', refdomain='', reftype='ref', reftarget='target',", "visit_pending_xref(self, node): pass def depart_pending_xref(self, node): pass class ForgivingHTMLTranslator(HTMLTranslator, ForgivingTranslator):", "\\begin{document} document.walkabout(latex_translator) latex_translated = ''.join(latex_translator.body).strip() assert re.match(latex_expected, latex_translated), 'from '", "\"\"\" test_markup ~~~~~~~~~~~ Test various Sphinx-specific markup extensions. :copyright: Copyright", "'verify': verify, 'verify_re': verify_re, } def get(name): return v[name] return", "nodes.paragraph) assert_node(doctree[0][1][0], addnodes.index) assert_node(doctree[0][1][1], nodes.target) assert_node(doctree[0][1][2], nodes.reference, classes=[\"pep\"]) # default_role", "8\\\\#id1@\\\\spxentry{PEP 8\\\\#id1}}\\\\sphinxhref' '{http://www.python.org/dev/peps/pep-0008\\\\#id1}' '{\\\\sphinxstylestrong{PEP 8\\\\#id1}}') ), ( # rfc role", "text = ':samp:`a\\\\\\\\{b}c`' doctree = parse(text) assert_node(doctree[0], [nodes.paragraph, nodes.literal, \"a{b}c\"])", "docutils literal notranslate\">space</kbd></p>', '\\\\sphinxAtStartPar\\n\\\\sphinxkeyboard{\\\\sphinxupquote{space}}', ), ( # kbd role 'verify',", "'Good-bye world' # rst_prolog & rst_epilog on exlucding reST parser", "class=\"kbd docutils literal notranslate\">M</kbd>' '-' '<kbd class=\"kbd docutils literal notranslate\">x</kbd>'", "assert_node(doctree[0], [nodes.paragraph, addnodes.download_reference, nodes.literal, \"sphinx.rst\"]) assert_node(doctree[0][0], refdoc='dummy', refdomain='', reftype='download', refexplicit=False,", "no braces (whitespaces are keeped as is) text = ':samp:`code", "import Parser as RstParser from sphinx import addnodes from sphinx.builders.html.transforms", "@pytest.fixture def settings(app): texescape.init() # otherwise done by the latex", "nodes.system_message) @pytest.mark.sphinx('dummy', testroot='keep_warnings', confoverrides={'keep_warnings': False}) def test_keep_warnings_is_False(app, status, warning): app.builder.build_all()", "sphinx.writers.latex import LaTeXTranslator, LaTeXWriter @pytest.fixture def settings(app): texescape.init() # otherwise", "# don't write \\begin{document} document.walkabout(latex_translator) latex_translated = ''.join(latex_translator.body).strip() assert re.match(latex_expected,", "5, inliner, {}, []) assert len(doctrees) == 1 assert_node(doctrees[0], [addnodes.pending_xref,", "above is required') def test_inline_docutils16(get_verifier, type, rst, html_expected, latex_expected): verifier", "app.builder) document.walkabout(html_translator) html_translated = ''.join(html_translator.fragment).strip() assert re.match(html_expected, html_translated), 'from '", "class ForgivingTranslator: def visit_pending_xref(self, node): pass def depart_pending_xref(self, node): pass", "re import pytest from docutils import frontend, nodes, utils from", "doctree = parse(text) assert_node(doctree[0], [nodes.paragraph, addnodes.download_reference, nodes.literal, \"reftitle\"]) assert_node(doctree[0][0], refdoc='dummy',", "SphinxSmartQuotes(document, startnode=None).apply() for msg in document.traverse(nodes.system_message): if msg['level'] == 1:", "class=\"accelerator\">F</span>oo ' '-&amp;- <span class=\"accelerator\">B</span>ar</span></p>'), ('\\\\sphinxAtStartPar\\n' r'\\sphinxguilabel{\\sphinxaccelerator{F}oo \\sphinxhyphen{}\\&\\sphinxhyphen{} \\sphinxaccelerator{B}ar}'), ),", "\\\\(\\\\rightarrow\\\\) b}', ), ( # interpolation of ampersands in menuselection", ":license: BSD, see LICENSE for details. \"\"\" import re import", "2324}}') ), ( # rfc role with anchor 'verify', ':rfc:`2324#id1`',", "new_document(settings): def create(): document = utils.new_document('test data', settings) document['file'] =", "2324\\\\#id1}}') ), ( # correct interpretation of code with whitespace", "# default_role changes the default behavior doctree = app.env.get_doctree('foo') assert_node(doctree[0],", "# rfc role 'verify', ':rfc:`2324`', ('<p><span class=\"target\" id=\"index-0\"></span><a class=\"rfc reference", "status, warning): app.builder.build_all() rst = app.env.get_doctree('restructuredtext') md = app.env.get_doctree('markdown') #", "latex_expected): verifier = get_verifier(type) verifier(rst, html_expected, latex_expected) @pytest.mark.parametrize('type,rst,html_expected,latex_expected', [ (", "( # kbd role 'verify', ':kbd:`Caps Lock`', '<p><kbd class=\"kbd docutils", "assert_node(doctree[0][4][0][0], nodes.paragraph) assert doctree[0][4][0][0].astext() == 'Hello' @pytest.mark.sphinx('dummy', testroot='default_role') def test_default_role1(app,", "Sphinx-specific markup extensions. :copyright: Copyright 2007-2021 by the Sphinx team,", "parser.parse(rst, document) SphinxSmartQuotes(document, startnode=None).apply() for msg in document.traverse(nodes.system_message): if msg['level']", "('<p><span class=\"target\" id=\"index-0\"></span><a class=\"rfc reference external\" ' 'href=\"http://tools.ietf.org/html/rfc2324.html#id1\">' '<strong>RFC 2324#id1</strong></a></p>'),", "r'\\\\sphinxAtStartPar\\n\\\\sphinxcode{\\\\sphinxupquote{code sample}}', ), ( # interpolation of arrows in menuselection", "'\\\\sphinxAtStartPar\\n\\\\sphinxguilabel{Foo}', ), ( # kbd role 'verify', ':kbd:`space`', '<p><kbd class=\"kbd", "), ( # kbd role 'verify', ':kbd:`Alt+^`', ('<p><kbd class=\"kbd compound", "reftarget='text', refexplicit=False, refwarn=False) @pytest.mark.sphinx('dummy', testroot='prolog') def test_rst_prolog(app, status, warning): app.builder.build_all()", "list: with classifiers 'verify', 'term : class1 : class2\\n description',", "class=\"accelerator\">B</span>ar</span></p>'), ('\\\\sphinxAtStartPar\\n' r'\\sphinxmenuselection{\\sphinxaccelerator{F}oo \\sphinxhyphen{}' r'\\&\\sphinxhyphen{} \\sphinxaccelerator{B}ar}'), ), ( # interpolation", "), ( # pep role with anchor 'verify', ':pep:`8#id1`', ('<p><span", "id=\"index-0\"></span><a class=\"rfc reference external\" ' 'href=\"http://tools.ietf.org/html/rfc2324.html\"><strong>RFC 2324</strong></a></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\index{RFC@\\\\spxentry{RFC}!RFC 2324@\\\\spxentry{RFC", "'rawtext', 'title <target>', 5, inliner, {}, []) assert_node(doctrees[0], [addnodes.pending_xref, nodes.literal,", "def visit_pending_xref(self, node): pass def depart_pending_xref(self, node): pass class ForgivingHTMLTranslator(HTMLTranslator,", "[addnodes.pending_xref, nodes.literal, 'text']) assert_node(doctrees[0], refdoc='dummy', refdomain='test', reftype='doc', reftarget='text', refexplicit=False, refwarn=False)", "reftype='ref', reftarget='target', refexplicit=True, refwarn=False) # bang doctrees, errors = role('ref',", "( # verify smarty-pants quotes 'verify', '\"John\"', '<p>“John”</p>', \"\\\\sphinxAtStartPar\\n“John”\", ),", "parse(text) assert_node(doctree[0], [nodes.paragraph, addnodes.download_reference, nodes.literal, \"sphinx.rst\"]) assert_node(doctree[0][0], refdoc='dummy', refdomain='', reftype='download',", "assert_node(doctree[0], [nodes.paragraph, nodes.literal, \"a{bc\"]) # escaped braces text = ':samp:`a\\\\\\\\{b}c`'", "= optparser.get_default_values() settings.smart_quotes = True settings.env = app.builder.env settings.env.temp_data['docname'] =", "ForgivingLaTeXTranslator(LaTeXTranslator, ForgivingTranslator): pass @pytest.fixture def verify_re_html(app, parse): def verify(rst, html_expected):", "= lambda line=1: ('dummy.rst', line) return Struct(document=document, reporter=document.reporter) @pytest.fixture def", "import frontend, nodes, utils from docutils.parsers.rst import Parser as RstParser", "in verbatim code fragments 'verify', '::\\n\\n @Γ\\\\∞${}', None, ('\\\\begin{sphinxVerbatim}[commandchars=\\\\\\\\\\\\{\\\\}]\\n' '@Γ\\\\PYGZbs{}∞\\\\PYGZdl{}\\\\PYGZob{}\\\\PYGZcb{}\\n'", "addnodes.index) assert_node(doctree[0][1][1], nodes.target) assert_node(doctree[0][1][2], nodes.reference, classes=[\"pep\"]) # no default-role doctree", "len(doctree[0]) == 2 assert_node(doctree[0][1], nodes.system_message) @pytest.mark.sphinx('dummy', testroot='keep_warnings', confoverrides={'keep_warnings': False}) def", "'verify', ':kbd:`-`', '<p><kbd class=\"kbd docutils literal notranslate\">-</kbd></p>', ('\\\\sphinxAtStartPar\\n' '\\\\sphinxkeyboard{\\\\sphinxupquote{\\\\sphinxhyphen{}}}'), ),", "optparser = frontend.OptionParser( components=(RstParser, HTMLWriter, LaTeXWriter)) settings = optparser.get_default_values() settings.smart_quotes", "assert_node(doctrees[0], refdoc='dummy', refdomain='', reftype='ref', reftarget='text', refexplicit=False, refwarn=False) @pytest.mark.sphinx('dummy', testroot='prolog') def", "assert_node(doctrees[0], [nodes.literal, 'title <target>']) # refdomain doctrees, errors = role('test:doc',", "( # pep role 'verify', ':pep:`8`', ('<p><span class=\"target\" id=\"index-0\"></span><a class=\"pep", "'\\\\end{sphinxVerbatim}'), ), ( # in URIs 'verify_re', '`test <https://www.google.com/~me/>`_', None,", "doctree = parse(text) assert_node(doctree[0], [nodes.paragraph, nodes.literal, (\"a\", [nodes.emphasis, \"b\"], \"c\")])", "verifier(rst, html_expected, latex_expected) @pytest.mark.parametrize('type,rst,html_expected,latex_expected', [ ( 'verify', r'4 backslashes \\\\\\\\',", "(0, 16), reason='docutils-0.16 or above is required') def test_inline_docutils16(get_verifier, type,", "True settings.env = app.builder.env settings.env.temp_data['docname'] = 'dummy' settings.contentsname = 'dummy'", "Enhancement Proposals}' '!PEP 8\\\\#id1@\\\\spxentry{PEP 8\\\\#id1}}\\\\sphinxhref' '{http://www.python.org/dev/peps/pep-0008\\\\#id1}' '{\\\\sphinxstylestrong{PEP 8\\\\#id1}}') ), (", "':pep:`8`', ('<p><span class=\"target\" id=\"index-0\"></span><a class=\"pep reference external\" ' 'href=\"http://www.python.org/dev/peps/pep-0008\"><strong>PEP 8</strong></a></p>'),", "('\\\\sphinxAtStartPar\\n' r'\\sphinxmenuselection{\\sphinxaccelerator{F}oo \\sphinxhyphen{}' r'\\&\\sphinxhyphen{} \\sphinxaccelerator{B}ar}'), ), ( # interpolation of", "':samp:`a{{b}}c`' doctree = parse(text) assert_node(doctree[0], [nodes.paragraph, nodes.literal, (\"a\", [nodes.emphasis, \"{b\"],", "test_rst_prolog(app, status, warning): app.builder.build_all() rst = app.env.get_doctree('restructuredtext') md = app.env.get_doctree('markdown')", "as RstParser from sphinx import addnodes from sphinx.builders.html.transforms import KeyboardTransform", "quotes 'verify', '\"John\"', '<p>“John”</p>', \"\\\\sphinxAtStartPar\\n“John”\", ), ( # ... but", "URIs 'verify_re', '`test <https://www.google.com/~me/>`_', None, r'\\\\sphinxAtStartPar\\n\\\\sphinxhref{https://www.google.com/~me/}{test}.*', ), ( # description", "braces text = ':samp:`a{b}c`' doctree = parse(text) assert_node(doctree[0], [nodes.paragraph, nodes.literal,", "latex_expected): verifier = get_verifier(type) verifier(rst, html_expected, latex_expected) @pytest.mark.sphinx(confoverrides={'latex_engine': 'xelatex'}) @pytest.mark.parametrize('type,rst,html_expected,latex_expected',", "\"\"\" import re import pytest from docutils import frontend, nodes,", "# rst_prolog & rst_epilog on exlucding reST parser assert not", "'download']) # explicit text = ':download:`reftitle <sphinx.rst>`' doctree = parse(text)", "# verify smarty-pants quotes 'verify', '\"John\"', '<p>“John”</p>', \"\\\\sphinxAtStartPar\\n“John”\", ), (", "('<p><span class=\"target\" id=\"index-0\"></span><a class=\"rfc reference external\" ' 'href=\"http://tools.ietf.org/html/rfc2324.html\"><strong>RFC 2324</strong></a></p>'), ('\\\\sphinxAtStartPar\\n'", "'genindex' assert doctree[0][3].astext() == 'List B:' assert_node(doctree[0][4], nodes.bullet_list) assert_node(doctree[0][4][0][0], nodes.paragraph)", "html_expected, latex_expected) def test_samp_role(parse): # no braces text = ':samp:`a{b}c`'", "'<span class=\"pre\">--with-option</span></code></p>$'), (r'\\\\sphinxAtStartPar\\n' r'\\\\sphinxcode{\\\\sphinxupquote{\\\\sphinxhyphen{}\\\\sphinxhyphen{}with\\\\sphinxhyphen{}option}}$'), ), ( # verify smarty-pants quotes", "# no default-role doctree = app.env.get_doctree('foo') assert_node(doctree[0], nodes.section) assert_node(doctree[0][1], nodes.paragraph)", "# lowercase role = XRefRole(lowercase=True) doctrees, errors = role('ref', 'rawtext',", "from sphinx.writers.html import HTMLTranslator, HTMLWriter from sphinx.writers.latex import LaTeXTranslator, LaTeXWriter", "( # kbd role 'verify', ':kbd:`space`', '<p><kbd class=\"kbd docutils literal", "backslashes \\\\\\\\', r'<p>4 backslashes \\\\</p>', None, ), ]) @pytest.mark.skipif(docutils.__version_info__ <", "line) return Struct(document=document, reporter=document.reporter) @pytest.fixture def parse(new_document): def parse_(rst): document", "'xelatex'}) @pytest.mark.parametrize('type,rst,html_expected,latex_expected', [ ( # in verbatim code fragments 'verify',", "KeyboardTransform from sphinx.builders.latex import LaTeXBuilder from sphinx.roles import XRefRole from", "verify_re, } def get(name): return v[name] return get @pytest.mark.parametrize('type,rst,html_expected,latex_expected', [", "assert_node(doctree[0][1][1], nodes.Text) @pytest.mark.sphinx('dummy', testroot='default_role', confoverrides={'default_role': 'guilabel'}) def test_default_role2(app, status, warning):", "def test_XRefRole(inliner): role = XRefRole() # implicit doctrees, errors =", "= ':download:`sphinx.rst`' doctree = parse(text) assert_node(doctree[0], [nodes.paragraph, addnodes.download_reference, nodes.literal, \"sphinx.rst\"])", "is) text = ':samp:`code sample`' doctree = parse(text) assert_node(doctree[0], [nodes.paragraph,", "= parse(text) assert_node(doctree[0], [nodes.paragraph, nodes.literal, \"a{bc\"]) # escaped braces text", "XRefRole from sphinx.testing.util import Struct, assert_node from sphinx.transforms import SphinxSmartQuotes", "notranslate\">Control</kbd>' '+' '<kbd class=\"kbd docutils literal notranslate\">X</kbd>' '</kbd></p>'), '\\\\sphinxAtStartPar\\n\\\\sphinxkeyboard{\\\\sphinxupquote{Control+X}}', ),", "BULLET} b</span></p>'), '\\\\sphinxAtStartPar\\n\\\\sphinxmenuselection{a \\\\(\\\\rightarrow\\\\) b}', ), ( # interpolation of", "2324#id1</strong></a></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\index{RFC@\\\\spxentry{RFC}!RFC 2324\\\\#id1@\\\\spxentry{RFC 2324\\\\#id1}}' '\\\\sphinxhref{http://tools.ietf.org/html/rfc2324.html\\\\#id1}' '{\\\\sphinxstylestrong{RFC 2324\\\\#id1}}') ), (", "assert len(doctree[0]) == 1 @pytest.mark.sphinx('dummy', testroot='refonly_bullet_list') def test_compact_refonly_bullet_list(app, status, warning):", "class=\"classifier\">class1</span>' '<span class=\"classifier\">class2</span></dt><dd>description</dd>\\n</dl>'), None, ), ( # glossary (description list):", "role = XRefRole(lowercase=True) doctrees, errors = role('ref', 'rawtext', 'TEXT', 5,", "def verify(rst, html_expected): document = parse(rst) KeyboardTransform(document).apply() html_translator = ForgivingHTMLTranslator(document,", "# half-opened braces text = ':samp:`a{bc`' doctree = parse(text) assert_node(doctree[0],", "assert_node(doctree[0][1], nodes.paragraph) assert_node(doctree[0][1][0], nodes.title_reference) assert_node(doctree[0][1][1], nodes.Text) @pytest.mark.sphinx('dummy', testroot='default_role', confoverrides={'default_role': 'guilabel'})", "assert_node(doctrees[0], [addnodes.pending_xref, nodes.literal, 'title']) assert_node(doctrees[0], refdoc='dummy', refdomain='', reftype='ref', reftarget='target', refexplicit=True,", "# default-role: pep doctree = app.env.get_doctree('index') assert_node(doctree[0], nodes.section) assert_node(doctree[0][1], nodes.paragraph)", "[]) assert_node(doctrees[0], [addnodes.pending_xref, nodes.literal, 'text()']) assert_node(doctrees[0], refdoc='dummy', refdomain='', reftype='ref', reftarget='text',", "re.match(latex_expected, latex_translated), 'from ' + repr(rst) return verify @pytest.fixture def", "doctrees, errors = role('ref', 'rawtext', 'text', 5, inliner, {}, [])", "docutils literal notranslate\">' '<kbd class=\"kbd docutils literal notranslate\">Control</kbd>' '+' '<kbd", "def test_inline_docutils16(get_verifier, type, rst, html_expected, latex_expected): verifier = get_verifier(type) verifier(rst,", "menuselection 'verify', ':menuselection:`a --> b`', ('<p><span class=\"menuselection\">a \\N{TRIANGULAR BULLET} b</span></p>'),", "r'<p>4 backslashes \\\\</p>', None, ), ]) @pytest.mark.skipif(docutils.__version_info__ < (0, 16),", "'verify', '::\\n\\n @Γ\\\\∞${}', None, ('\\\\begin{sphinxVerbatim}[commandchars=\\\\\\\\\\\\{\\\\}]\\n' '@Γ\\\\PYGZbs{}\\\\(\\\\infty\\\\)\\\\PYGZdl{}\\\\PYGZob{}\\\\PYGZcb{}\\n' '\\\\end{sphinxVerbatim}'), ), ( #", "description', '<dl class=\"docutils\">\\n<dt>term</dt><dd>description</dd>\\n</dl>', None, ), ( # description list: with", "'{\\\\sphinxstylestrong{RFC 2324}}') ), ( # rfc role with anchor 'verify',", "Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details.", "kbd role 'verify', ':kbd:`M-x M-s`', ('<p><kbd class=\"kbd compound docutils literal", "('<p><code class=\"docutils literal notranslate\"><span class=\"pre\">' '&quot;John&quot;</span></code></p>'), '\\\\sphinxAtStartPar\\n\\\\sphinxcode{\\\\sphinxupquote{\"John\"}}', ), ( #", "warning): app.builder.build_all() doctree = app.env.get_doctree('index') assert_node(doctree[0], nodes.section) assert len(doctree[0]) ==", "lowercase role = XRefRole(lowercase=True) doctrees, errors = role('ref', 'rawtext', 'TEXT',", "'-' '<kbd class=\"kbd docutils literal notranslate\">s</kbd>' '</kbd></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\sphinxkeyboard{\\\\sphinxupquote{M\\\\sphinxhyphen{}x M\\\\sphinxhyphen{}s}}'),", "latex_expected): if html_expected: verify_re_html(rst, re.escape(html_expected) + '$') if latex_expected: verify_re_latex(rst,", "braces text = ':samp:`a\\\\\\\\{b}c`' doctree = parse(text) assert_node(doctree[0], [nodes.paragraph, nodes.literal,", "# verify classes for inline roles 'verify', ':manpage:`mp(1)`', '<p><em class=\"manpage\">mp(1)</em></p>',", "r'4 backslashes \\\\\\\\', r'<p>4 backslashes \\\\</p>', None, ), ]) @pytest.mark.skipif(docutils.__version_info__", "bang doctrees, errors = role('ref', 'rawtext', '!title <target>', 5, inliner,", "# bang doctrees, errors = role('ref', 'rawtext', '!title <target>', 5,", "= ':download:`reftitle <sphinx.rst>`' doctree = parse(text) assert_node(doctree[0], [nodes.paragraph, addnodes.download_reference, nodes.literal,", "refwarn=False) # fix_parens role = XRefRole(fix_parens=True) doctrees, errors = role('ref',", "'dummy' return document return create @pytest.fixture def inliner(new_document): document =", "verify_re_latex(rst, latex_expected) return verify_re_ @pytest.fixture def verify(verify_re_html, verify_re_latex): def verify_(rst,", "'verify', ':pep:`8#id1`', ('<p><span class=\"target\" id=\"index-0\"></span><a class=\"pep reference external\" ' 'href=\"http://www.python.org/dev/peps/pep-0008#id1\">'", "Proposals@\\\\spxentry{Python Enhancement Proposals}' '!PEP 8@\\\\spxentry{PEP 8}}\\\\sphinxhref{http://www.python.org/dev/peps/pep-0008}' '{\\\\sphinxstylestrong{PEP 8}}') ), (", "html_expected): document = parse(rst) KeyboardTransform(document).apply() html_translator = ForgivingHTMLTranslator(document, app.builder) document.walkabout(html_translator)", "'<p><kbd class=\"kbd docutils literal notranslate\">space</kbd></p>', '\\\\sphinxAtStartPar\\n\\\\sphinxkeyboard{\\\\sphinxupquote{space}}', ), ( # kbd", "parse): def verify(rst, latex_expected): document = parse(rst) app.builder = LaTeXBuilder(app)", "latex_expected) @pytest.mark.parametrize('type,rst,html_expected,latex_expected', [ ( 'verify', r'4 backslashes \\\\\\\\', r'<p>4 backslashes", ")?docutils literal notranslate\"><span class=\"pre\">' 'code</span>&#160;&#160; <span class=\"pre\">sample</span></code></p>'), r'\\\\sphinxAtStartPar\\n\\\\sphinxcode{\\\\sphinxupquote{code sample}}', ),", "new_document() parser = RstParser() parser.parse(rst, document) SphinxSmartQuotes(document, startnode=None).apply() for msg", "('\\\\sphinxAtStartPar\\n' '\\\\index{RFC@\\\\spxentry{RFC}!RFC 2324\\\\#id1@\\\\spxentry{RFC 2324\\\\#id1}}' '\\\\sphinxhref{http://tools.ietf.org/html/rfc2324.html\\\\#id1}' '{\\\\sphinxstylestrong{RFC 2324\\\\#id1}}') ), ( #", "# interpolation of ampersands in menuselection 'verify', ':menuselection:`&Foo -&&- &Bar`',", "classes=['xref', 'download']) # explicit text = ':download:`reftitle <sphinx.rst>`' doctree =", "2324</strong></a></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\index{RFC@\\\\spxentry{RFC}!RFC 2324@\\\\spxentry{RFC 2324}}' '\\\\sphinxhref{http://tools.ietf.org/html/rfc2324.html}' '{\\\\sphinxstylestrong{RFC 2324}}') ), (", "r'\\\\sphinxAtStartPar\\n\\\\sphinxhref{https://www.google.com/~me/}{test}.*', ), ( # description list: simple 'verify', 'term\\n description',", "1 @pytest.mark.sphinx('dummy', testroot='refonly_bullet_list') def test_compact_refonly_bullet_list(app, status, warning): app.builder.build_all() doctree =", "@Γ\\\\∞${}', None, ('\\\\begin{sphinxVerbatim}[commandchars=\\\\\\\\\\\\{\\\\}]\\n' '@Γ\\\\PYGZbs{}∞\\\\PYGZdl{}\\\\PYGZob{}\\\\PYGZcb{}\\n' '\\\\end{sphinxVerbatim}'), ), ]) def test_inline_for_unicode_latex_engine(get_verifier, type,", "2324@\\\\spxentry{RFC 2324}}' '\\\\sphinxhref{http://tools.ietf.org/html/rfc2324.html}' '{\\\\sphinxstylestrong{RFC 2324}}') ), ( # rfc role", "# no braces text = ':samp:`a{b}c`' doctree = parse(text) assert_node(doctree[0],", "verifier(rst, html_expected, latex_expected) @pytest.mark.sphinx(confoverrides={'latex_engine': 'xelatex'}) @pytest.mark.parametrize('type,rst,html_expected,latex_expected', [ ( # in", "sphinx.builders.latex import LaTeXBuilder from sphinx.roles import XRefRole from sphinx.testing.util import", "refdomain='', reftype='ref', reftarget='target', refexplicit=True, refwarn=False) # bang doctrees, errors =", "), ]) @pytest.mark.skipif(docutils.__version_info__ < (0, 16), reason='docutils-0.16 or above is", "B:' assert_node(doctree[0][4], nodes.bullet_list) assert_node(doctree[0][4][0][0], nodes.paragraph) assert doctree[0][4][0][0].astext() == 'Hello' @pytest.mark.sphinx('dummy',", "nodes.section) assert_node(rst[-1][-1], nodes.paragraph) assert_node(rst[-1][-1][0], nodes.emphasis) assert_node(rst[-1][-1][0][0], nodes.Text) assert rst[-1][-1][0][0] ==", "otherwise done by the latex builder optparser = frontend.OptionParser( components=(RstParser,", "nodes.title_reference) assert_node(doctree[0][1][1], nodes.Text) @pytest.mark.sphinx('dummy', testroot='default_role', confoverrides={'default_role': 'guilabel'}) def test_default_role2(app, status,", "verify @pytest.fixture def verify_re_latex(app, parse): def verify(rst, latex_expected): document =", "'verify', ':kbd:`space`', '<p><kbd class=\"kbd docutils literal notranslate\">space</kbd></p>', '\\\\sphinxAtStartPar\\n\\\\sphinxkeyboard{\\\\sphinxupquote{space}}', ), (", "notranslate\">Caps Lock</kbd></p>', ('\\\\sphinxAtStartPar\\n' '\\\\sphinxkeyboard{\\\\sphinxupquote{Caps Lock}}'), ), ( # non-interpolation of", "latex_translator.first_document = -1 # don't write \\begin{document} document.walkabout(latex_translator) latex_translated =", "len(doctree[0]) == 1 @pytest.mark.sphinx('dummy', testroot='refonly_bullet_list') def test_compact_refonly_bullet_list(app, status, warning): app.builder.build_all()", "class=\"target\" id=\"index-0\"></span><a class=\"rfc reference external\" ' 'href=\"http://tools.ietf.org/html/rfc2324.html\"><strong>RFC 2324</strong></a></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\index{RFC@\\\\spxentry{RFC}!RFC", "2324\\\\#id1}}' '\\\\sphinxhref{http://tools.ietf.org/html/rfc2324.html\\\\#id1}' '{\\\\sphinxstylestrong{RFC 2324\\\\#id1}}') ), ( # correct interpretation of", "'verify_re': verify_re, } def get(name): return v[name] return get @pytest.mark.parametrize('type,rst,html_expected,latex_expected',", "in verbatim code fragments 'verify', '::\\n\\n @Γ\\\\∞${}', None, ('\\\\begin{sphinxVerbatim}[commandchars=\\\\\\\\\\\\{\\\\}]\\n' '@Γ\\\\PYGZbs{}\\\\(\\\\infty\\\\)\\\\PYGZdl{}\\\\PYGZob{}\\\\PYGZcb{}\\n'", "startnode=None).apply() for msg in document.traverse(nodes.system_message): if msg['level'] == 1: msg.replace_self([])", "rfc role with anchor 'verify', ':rfc:`2324#id1`', ('<p><span class=\"target\" id=\"index-0\"></span><a class=\"rfc", "from sphinx.transforms import SphinxSmartQuotes from sphinx.util import docutils, texescape from", "class=\"kbd docutils literal notranslate\">Control</kbd>' '+' '<kbd class=\"kbd docutils literal notranslate\">X</kbd>'", "b</span></p>'), '\\\\sphinxAtStartPar\\n\\\\sphinxmenuselection{a \\\\(\\\\rightarrow\\\\) b}', ), ( # interpolation of ampersands", "# kbd role 'verify', ':kbd:`Control+X`', ('<p><kbd class=\"kbd compound docutils literal", "from sphinx.builders.latex import LaTeXBuilder from sphinx.roles import XRefRole from sphinx.testing.util", "''.join(latex_translator.body).strip() assert re.match(latex_expected, latex_translated), 'from ' + repr(rst) return verify", "keeped as is) text = ':samp:`code sample`' doctree = parse(text)", "HTMLWriter from sphinx.writers.latex import LaTeXTranslator, LaTeXWriter @pytest.fixture def settings(app): texescape.init()", "document = utils.new_document('test data', settings) document['file'] = 'dummy' return document", "glossary (description list): multiple terms 'verify', '.. glossary::\\n\\n term1\\n term2\\n", "None, ), ( # glossary (description list): multiple terms 'verify',", "refdoc='dummy', refdomain='', reftype='ref', reftarget='text', refexplicit=False, refwarn=False) assert errors == []", "]) def test_inline_for_unicode_latex_engine(get_verifier, type, rst, html_expected, latex_expected): verifier = get_verifier(type)", "@pytest.fixture def verify_re(verify_re_html, verify_re_latex): def verify_re_(rst, html_expected, latex_expected): if html_expected:", "'verify', 'term\\n description', '<dl class=\"docutils\">\\n<dt>term</dt><dd>description</dd>\\n</dl>', None, ), ( # description", "re.match(html_expected, html_translated), 'from ' + rst return verify @pytest.fixture def", "' title=\"Permalink to this term\">¶</a></dt>' '<dd>description</dd>\\n</dl>'), None, ), ]) def", "'verify', ':menuselection:`a --> b`', ('<p><span class=\"menuselection\">a \\N{TRIANGULAR BULLET} b</span></p>'), '\\\\sphinxAtStartPar\\n\\\\sphinxmenuselection{a", "role('ref', 'rawtext', '!title <target>', 5, inliner, {}, []) assert_node(doctrees[0], [nodes.literal,", "= app.builder.themes.get('manual') latex_translator = ForgivingLaTeXTranslator(document, app.builder, theme) latex_translator.first_document = -1", "refexplicit=False, refwarn=False) # fix_parens role = XRefRole(fix_parens=True) doctrees, errors =", "terms 'verify', '.. glossary::\\n\\n term1\\n term2\\n description', ('<dl class=\"glossary docutils\">\\n'", "assert_node(doctree[0][1][0], addnodes.index) assert_node(doctree[0][1][1], nodes.target) assert_node(doctree[0][1][2], nodes.reference, classes=[\"pep\"]) # no default-role", "( # kbd role 'verify', ':kbd:`M-x M-s`', ('<p><kbd class=\"kbd compound", "XRefRole(fix_parens=True) doctrees, errors = role('ref', 'rawtext', 'text()', 5, inliner, {},", "def test_keep_warnings_is_True(app, status, warning): app.builder.build_all() doctree = app.env.get_doctree('index') assert_node(doctree[0], nodes.section)", "class=\"kbd docutils literal notranslate\">X</kbd>' '</kbd></p>'), '\\\\sphinxAtStartPar\\n\\\\sphinxkeyboard{\\\\sphinxupquote{Control+X}}', ), ( # kbd", "nodes.section) assert len(doctree[0]) == 5 assert doctree[0][1].astext() == 'List A:'", "'text']) assert_node(doctrees[0], refdoc='dummy', refdomain='', reftype='ref', reftarget='text', refexplicit=False, refwarn=False) assert errors", "doctree[0][1].astext() == 'List A:' assert_node(doctree[0][2], nodes.bullet_list) assert_node(doctree[0][2][0][0], addnodes.compact_paragraph) assert doctree[0][2][0][0].astext()", "refwarn=False) @pytest.mark.sphinx('dummy', testroot='prolog') def test_rst_prolog(app, status, warning): app.builder.build_all() rst =", "@pytest.fixture def new_document(settings): def create(): document = utils.new_document('test data', settings)", "('\\\\sphinxAtStartPar\\n' '\\\\sphinxkeyboard{\\\\sphinxupquote{M\\\\sphinxhyphen{}x M\\\\sphinxhyphen{}s}}'), ), ( # kbd role 'verify', ':kbd:`-`',", "\"sphinx.rst\"]) assert_node(doctree[0][0], refdoc='dummy', refdomain='', reftype='download', refexplicit=False, reftarget='sphinx.rst', refwarn=False) assert_node(doctree[0][0][0], classes=['xref',", "= 'http://tools.ietf.org/html/' domain_context = sphinx_domains(settings.env) domain_context.enable() yield settings domain_context.disable() @pytest.fixture", "docutils literal notranslate\">^</kbd>' '</kbd></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\sphinxkeyboard{\\\\sphinxupquote{Alt+\\\\textasciicircum{}}}'), ), ( # kbd", "':rfc:`2324#id1`', ('<p><span class=\"target\" id=\"index-0\"></span><a class=\"rfc reference external\" ' 'href=\"http://tools.ietf.org/html/rfc2324.html#id1\">' '<strong>RFC", "from sphinx.roles import XRefRole from sphinx.testing.util import Struct, assert_node from", "\"a{b}c\"]) # no braces (whitespaces are keeped as is) text", "team, see AUTHORS. :license: BSD, see LICENSE for details. \"\"\"", "@pytest.mark.sphinx('dummy', testroot='prolog') def test_rst_prolog(app, status, warning): app.builder.build_all() rst = app.env.get_doctree('restructuredtext')", "[nodes.emphasis, \"{b\"], \"}c\")]) # half-opened braces text = ':samp:`a{bc`' doctree", "import Struct, assert_node from sphinx.transforms import SphinxSmartQuotes from sphinx.util import", "rst[-1][-1][0][0] == 'Good-bye world' # rst_prolog & rst_epilog on exlucding", "def test_keep_warnings_is_False(app, status, warning): app.builder.build_all() doctree = app.env.get_doctree('index') assert_node(doctree[0], nodes.section)", "'rawtext', 'text()', 5, inliner, {}, []) assert_node(doctrees[0], [addnodes.pending_xref, nodes.literal, 'text()'])", "sphinx.testing.util import Struct, assert_node from sphinx.transforms import SphinxSmartQuotes from sphinx.util", "compound docutils literal notranslate\">' '<kbd class=\"kbd docutils literal notranslate\">Control</kbd>' '+'", "get(name): return v[name] return get @pytest.mark.parametrize('type,rst,html_expected,latex_expected', [ ( # pep", "== 5 assert doctree[0][1].astext() == 'List A:' assert_node(doctree[0][2], nodes.bullet_list) assert_node(doctree[0][2][0][0],", "the default behavior doctree = app.env.get_doctree('foo') assert_node(doctree[0], nodes.section) assert_node(doctree[0][1], nodes.paragraph)", "settings.env = app.builder.env settings.env.temp_data['docname'] = 'dummy' settings.contentsname = 'dummy' settings.rfc_base_url", "@pytest.mark.sphinx('dummy', testroot='default_role', confoverrides={'default_role': 'guilabel'}) def test_default_role2(app, status, warning): app.builder.build_all() #", "{ 'verify': verify, 'verify_re': verify_re, } def get(name): return v[name]", "refwarn=False) assert_node(doctree[0][0][0], classes=['xref', 'download']) def test_XRefRole(inliner): role = XRefRole() #", "to this term\">¶</a></dt>' '<dd>description</dd>\\n</dl>'), None, ), ]) def test_inline(get_verifier, type,", "import LaTeXTranslator, LaTeXWriter @pytest.fixture def settings(app): texescape.init() # otherwise done", "':manpage:`mp(1)`', '<p><em class=\"manpage\">mp(1)</em></p>', '\\\\sphinxAtStartPar\\n\\\\sphinxstyleliteralemphasis{\\\\sphinxupquote{mp(1)}}', ), ( # correct escaping in", "'{\\\\sphinxstylestrong{PEP 8\\\\#id1}}') ), ( # rfc role 'verify', ':rfc:`2324`', ('<p><span", "fix_parens role = XRefRole(fix_parens=True) doctrees, errors = role('ref', 'rawtext', 'text()',", "), ( # correct escaping in normal mode 'verify', 'Γ\\\\\\\\∞$',", "v = { 'verify': verify, 'verify_re': verify_re, } def get(name):", "verify_re(verify_re_html, verify_re_latex): def verify_re_(rst, html_expected, latex_expected): if html_expected: verify_re_html(rst, html_expected)", "guilabel 'verify', ':guilabel:`Foo`', '<p><span class=\"guilabel\">Foo</span></p>', '\\\\sphinxAtStartPar\\n\\\\sphinxguilabel{Foo}', ), ( # kbd", "docutils literal notranslate\">' '<kbd class=\"kbd docutils literal notranslate\">Alt</kbd>' '+' '<kbd", "'\\\\sphinxkeyboard{\\\\sphinxupquote{Alt+\\\\textasciicircum{}}}'), ), ( # kbd role 'verify', ':kbd:`M-x M-s`', ('<p><kbd", "errors = role('ref', 'rawtext', 'text', 5, inliner, {}, []) assert", "status, warning): app.builder.build_all() # default-role: pep doctree = app.env.get_doctree('index') assert_node(doctree[0],", "md = app.env.get_doctree('markdown') # rst_prolog assert_node(rst[0], nodes.paragraph) assert_node(rst[0][0], nodes.emphasis) assert_node(rst[0][0][0],", "'verify_re', ':option:`--with-option`', ('<p><code( class=\"xref std std-option docutils literal notranslate\")?>' '<span", "role 'verify', ':kbd:`Caps Lock`', '<p><kbd class=\"kbd docutils literal notranslate\">Caps Lock</kbd></p>',", "doctree[0][2][0][0].astext() == 'genindex' assert doctree[0][3].astext() == 'List B:' assert_node(doctree[0][4], nodes.bullet_list)", "'\\\\index{RFC@\\\\spxentry{RFC}!RFC 2324@\\\\spxentry{RFC 2324}}' '\\\\sphinxhref{http://tools.ietf.org/html/rfc2324.html}' '{\\\\sphinxstylestrong{RFC 2324}}') ), ( # rfc", "href=\"#term-term1\"' ' title=\"Permalink to this term\">¶</a></dt>' '<dt id=\"term-term2\">term2<a class=\"headerlink\" href=\"#term-term2\"'", "assert rst[0][0][0] == 'Hello world' # rst_epilog assert_node(rst[-1], nodes.section) assert_node(rst[-1][-1],", "( # in verbatim code fragments 'verify', '::\\n\\n @Γ\\\\∞${}', None,", "<target>', 5, inliner, {}, []) assert_node(doctrees[0], [addnodes.pending_xref, nodes.literal, 'title']) assert_node(doctrees[0],", "html_expected, latex_expected) @pytest.mark.sphinx(confoverrides={'latex_engine': 'xelatex'}) @pytest.mark.parametrize('type,rst,html_expected,latex_expected', [ ( # in verbatim", "= parse(text) assert_node(doctree[0], [nodes.paragraph, addnodes.download_reference, nodes.literal, \"reftitle\"]) assert_node(doctree[0][0], refdoc='dummy', refdomain='',", "nodes.paragraph) assert_node(doctree[0][1][0], nodes.title_reference) assert_node(doctree[0][1][1], nodes.Text) @pytest.mark.sphinx('dummy', testroot='default_role', confoverrides={'default_role': 'guilabel'}) def", "directive is stronger than configratuion doctree = app.env.get_doctree('index') assert_node(doctree[0], nodes.section)", "= parse(text) assert_node(doctree[0], [nodes.paragraph, nodes.literal, (\"a\", [nodes.emphasis, \"b\"], \"c\")]) #", "' 'href=\"http://tools.ietf.org/html/rfc2324.html#id1\">' '<strong>RFC 2324#id1</strong></a></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\index{RFC@\\\\spxentry{RFC}!RFC 2324\\\\#id1@\\\\spxentry{RFC 2324\\\\#id1}}' '\\\\sphinxhref{http://tools.ietf.org/html/rfc2324.html\\\\#id1}' '{\\\\sphinxstylestrong{RFC", "'\\\\sphinxAtStartPar\\n\\\\sphinxmenuselection{a \\\\(\\\\rightarrow\\\\) b}', ), ( # interpolation of ampersands in", "= role('test:doc', 'rawtext', 'text', 5, inliner, {}, []) assert_node(doctrees[0], [addnodes.pending_xref,", "test_inline(get_verifier, type, rst, html_expected, latex_expected): verifier = get_verifier(type) verifier(rst, html_expected,", "html_expected: verify_re_html(rst, re.escape(html_expected) + '$') if latex_expected: verify_re_latex(rst, re.escape(latex_expected) +", "class=\"rfc reference external\" ' 'href=\"http://tools.ietf.org/html/rfc2324.html#id1\">' '<strong>RFC 2324#id1</strong></a></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\index{RFC@\\\\spxentry{RFC}!RFC 2324\\\\#id1@\\\\spxentry{RFC", "# interpolation of ampersands in guilabel 'verify', ':guilabel:`&Foo -&&- &Bar`',", "} def get(name): return v[name] return get @pytest.mark.parametrize('type,rst,html_expected,latex_expected', [ (", "), ( # interpolation of arrows in menuselection 'verify', ':menuselection:`a", "errors = role('ref', 'rawtext', 'text()', 5, inliner, {}, []) assert_node(doctrees[0],", "class=\"kbd docutils literal notranslate\">^</kbd>' '</kbd></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\sphinxkeyboard{\\\\sphinxupquote{Alt+\\\\textasciicircum{}}}'), ), ( #", "':kbd:`-`', '<p><kbd class=\"kbd docutils literal notranslate\">-</kbd></p>', ('\\\\sphinxAtStartPar\\n' '\\\\sphinxkeyboard{\\\\sphinxupquote{\\\\sphinxhyphen{}}}'), ), (", "to this term\">¶</a></dt>' '<dt id=\"term-term2\">term2<a class=\"headerlink\" href=\"#term-term2\"' ' title=\"Permalink to", "latex_translated = ''.join(latex_translator.body).strip() assert re.match(latex_expected, latex_translated), 'from ' + repr(rst)", "docutils literal notranslate\")?>' '<span class=\"pre\">--with-option</span></code></p>$'), (r'\\\\sphinxAtStartPar\\n' r'\\\\sphinxcode{\\\\sphinxupquote{\\\\sphinxhyphen{}\\\\sphinxhyphen{}with\\\\sphinxhyphen{}option}}$'), ), ( #", "markup extensions. :copyright: Copyright 2007-2021 by the Sphinx team, see", "None, ('\\\\begin{sphinxVerbatim}[commandchars=\\\\\\\\\\\\{\\\\}]\\n' '@Γ\\\\PYGZbs{}∞\\\\PYGZdl{}\\\\PYGZob{}\\\\PYGZcb{}\\n' '\\\\end{sphinxVerbatim}'), ), ]) def test_inline_for_unicode_latex_engine(get_verifier, type, rst,", "\"reftitle\"]) assert_node(doctree[0][0], refdoc='dummy', refdomain='', reftype='download', refexplicit=True, reftarget='sphinx.rst', refwarn=False) assert_node(doctree[0][0][0], classes=['xref',", "reftype='ref', reftarget='text', refexplicit=False, refwarn=False) @pytest.mark.sphinx('dummy', testroot='prolog') def test_rst_prolog(app, status, warning):", "# pep role 'verify', ':pep:`8`', ('<p><span class=\"target\" id=\"index-0\"></span><a class=\"pep reference", "by the latex builder optparser = frontend.OptionParser( components=(RstParser, HTMLWriter, LaTeXWriter))", "'<p><span class=\"guilabel\">Foo</span></p>', '\\\\sphinxAtStartPar\\n\\\\sphinxguilabel{Foo}', ), ( # kbd role 'verify', ':kbd:`space`',", "# implicit doctrees, errors = role('ref', 'rawtext', 'text', 5, inliner,", "href=\"#term-term2\"' ' title=\"Permalink to this term\">¶</a></dt>' '<dd>description</dd>\\n</dl>'), None, ), ])", "doctree = parse(text) assert_node(doctree[0], [nodes.paragraph, nodes.literal, \"a{b}c\"]) # no braces", "'{\\\\sphinxstylestrong{RFC 2324\\\\#id1}}') ), ( # correct interpretation of code with", "'text()', 5, inliner, {}, []) assert_node(doctrees[0], [addnodes.pending_xref, nodes.literal, 'text()']) assert_node(doctrees[0],", "no braces text = ':samp:`a{b}c`' doctree = parse(text) assert_node(doctree[0], [nodes.paragraph,", "nodes.target) assert_node(doctree[0][1][2], nodes.reference, classes=[\"pep\"]) # no default-role doctree = app.env.get_doctree('foo')", "notranslate\">space</kbd></p>', '\\\\sphinxAtStartPar\\n\\\\sphinxkeyboard{\\\\sphinxupquote{space}}', ), ( # kbd role 'verify', ':kbd:`Control+X`', ('<p><kbd", "behavior doctree = app.env.get_doctree('foo') assert_node(doctree[0], nodes.section) assert_node(doctree[0][1], nodes.paragraph) assert_node(doctree[0][1][0], nodes.inline,", "from sphinx.builders.html.transforms import KeyboardTransform from sphinx.builders.latex import LaTeXBuilder from sphinx.roles", "# kbd role 'verify', ':kbd:`-`', '<p><kbd class=\"kbd docutils literal notranslate\">-</kbd></p>',", "= get_verifier(type) verifier(rst, html_expected, latex_expected) @pytest.mark.parametrize('type,rst,html_expected,latex_expected', [ ( 'verify', r'4", "addnodes.index) assert_node(doctree[0][1][1], nodes.target) assert_node(doctree[0][1][2], nodes.reference, classes=[\"pep\"]) # default_role changes the", "def verify_re(verify_re_html, verify_re_latex): def verify_re_(rst, html_expected, latex_expected): if html_expected: verify_re_html(rst,", "html_translator = ForgivingHTMLTranslator(document, app.builder) document.walkabout(html_translator) html_translated = ''.join(html_translator.fragment).strip() assert re.match(html_expected,", "verify_(rst, html_expected, latex_expected): if html_expected: verify_re_html(rst, re.escape(html_expected) + '$') if", "assert doctree[0][3].astext() == 'List B:' assert_node(doctree[0][4], nodes.bullet_list) assert_node(doctree[0][4][0][0], nodes.paragraph) assert", "('<p><span class=\"guilabel\"><span class=\"accelerator\">F</span>oo ' '-&amp;- <span class=\"accelerator\">B</span>ar</span></p>'), ('\\\\sphinxAtStartPar\\n' r'\\sphinxguilabel{\\sphinxaccelerator{F}oo \\sphinxhyphen{}\\&\\sphinxhyphen{}", "frontend.OptionParser( components=(RstParser, HTMLWriter, LaTeXWriter)) settings = optparser.get_default_values() settings.smart_quotes = True", "assert_node(doctrees[0], refdoc='dummy', refdomain='test', reftype='doc', reftarget='text', refexplicit=False, refwarn=False) # fix_parens role", "confoverrides={'keep_warnings': False}) def test_keep_warnings_is_False(app, status, warning): app.builder.build_all() doctree = app.env.get_doctree('index')", "('<p><code( class=\"xref std std-option docutils literal notranslate\")?>' '<span class=\"pre\">--with-option</span></code></p>$'), (r'\\\\sphinxAtStartPar\\n'", "verify smarty-pants quotes 'verify', '\"John\"', '<p>“John”</p>', \"\\\\sphinxAtStartPar\\n“John”\", ), ( #", "' 'href=\"http://tools.ietf.org/html/rfc2324.html\"><strong>RFC 2324</strong></a></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\index{RFC@\\\\spxentry{RFC}!RFC 2324@\\\\spxentry{RFC 2324}}' '\\\\sphinxhref{http://tools.ietf.org/html/rfc2324.html}' '{\\\\sphinxstylestrong{RFC 2324}}')", "description list: simple 'verify', 'term\\n description', '<dl class=\"docutils\">\\n<dt>term</dt><dd>description</dd>\\n</dl>', None, ),", "# rfc role with anchor 'verify', ':rfc:`2324#id1`', ('<p><span class=\"target\" id=\"index-0\"></span><a", "'from ' + repr(rst) return verify @pytest.fixture def verify_re(verify_re_html, verify_re_latex):", "\"}c\")]) # half-opened braces text = ':samp:`a{bc`' doctree = parse(text)", "('\\\\sphinxAtStartPar\\n' '\\\\index{Python Enhancement Proposals@\\\\spxentry{Python Enhancement Proposals}' '!PEP 8\\\\#id1@\\\\spxentry{PEP 8\\\\#id1}}\\\\sphinxhref' '{http://www.python.org/dev/peps/pep-0008\\\\#id1}'", "'<p><kbd class=\"kbd docutils literal notranslate\">-</kbd></p>', ('\\\\sphinxAtStartPar\\n' '\\\\sphinxkeyboard{\\\\sphinxupquote{\\\\sphinxhyphen{}}}'), ), ( #", "'text']) assert_node(doctrees[0], refdoc='dummy', refdomain='test', reftype='doc', reftarget='text', refexplicit=False, refwarn=False) # fix_parens", "is stronger than configratuion doctree = app.env.get_doctree('index') assert_node(doctree[0], nodes.section) assert_node(doctree[0][1],", "return Struct(document=document, reporter=document.reporter) @pytest.fixture def parse(new_document): def parse_(rst): document =", "5 assert doctree[0][1].astext() == 'List A:' assert_node(doctree[0][2], nodes.bullet_list) assert_node(doctree[0][2][0][0], addnodes.compact_paragraph)", "doctree = app.env.get_doctree('index') assert_node(doctree[0], nodes.section) assert_node(doctree[0][1], nodes.paragraph) assert_node(doctree[0][1][0], addnodes.index) assert_node(doctree[0][1][1],", "pep role 'verify', ':pep:`8`', ('<p><span class=\"target\" id=\"index-0\"></span><a class=\"pep reference external\"", "@pytest.mark.parametrize('type,rst,html_expected,latex_expected', [ ( # pep role 'verify', ':pep:`8`', ('<p><span class=\"target\"", "kbd role 'verify', ':kbd:`-`', '<p><kbd class=\"kbd docutils literal notranslate\">-</kbd></p>', ('\\\\sphinxAtStartPar\\n'", "]) def test_inline(get_verifier, type, rst, html_expected, latex_expected): verifier = get_verifier(type)", "document = new_document() parser = RstParser() parser.parse(rst, document) SphinxSmartQuotes(document, startnode=None).apply()", "b`', ('<p><span class=\"menuselection\">a \\N{TRIANGULAR BULLET} b</span></p>'), '\\\\sphinxAtStartPar\\n\\\\sphinxmenuselection{a \\\\(\\\\rightarrow\\\\) b}', ),", "'verify', ':guilabel:`Foo`', '<p><span class=\"guilabel\">Foo</span></p>', '\\\\sphinxAtStartPar\\n\\\\sphinxguilabel{Foo}', ), ( # kbd role", "docutils literal notranslate\">Alt</kbd>' '+' '<kbd class=\"kbd docutils literal notranslate\">^</kbd>' '</kbd></p>'),", "# non-interpolation of dashes in option role 'verify_re', ':option:`--with-option`', ('<p><code(", "assert_node(doctrees[0], refdoc='dummy', refdomain='', reftype='ref', reftarget='target', refexplicit=True, refwarn=False) # bang doctrees,", "reason='docutils-0.16 or above is required') def test_inline_docutils16(get_verifier, type, rst, html_expected,", "assert_node(doctree[0], [nodes.paragraph, nodes.literal, (\"a\", [nodes.emphasis, \"b\"], \"c\")]) # nested braces", "app.builder.set_environment(app.env) app.builder.init() theme = app.builder.themes.get('manual') latex_translator = ForgivingLaTeXTranslator(document, app.builder, theme)", "# explicit text = ':download:`reftitle <sphinx.rst>`' doctree = parse(text) assert_node(doctree[0],", "'``code sample``', ('<p><code class=\"(samp )?docutils literal notranslate\"><span class=\"pre\">' 'code</span>&#160;&#160; <span", "r'\\&\\sphinxhyphen{} \\sphinxaccelerator{B}ar}'), ), ( # interpolation of ampersands in guilabel", "nodes.literal, 'TEXT']) assert_node(doctrees[0], refdoc='dummy', refdomain='', reftype='ref', reftarget='text', refexplicit=False, refwarn=False) @pytest.mark.sphinx('dummy',", "assert_node(doctree[0][2][0][0], addnodes.compact_paragraph) assert doctree[0][2][0][0].astext() == 'genindex' assert doctree[0][3].astext() == 'List", "ampersands in guilabel 'verify', ':guilabel:`&Foo -&&- &Bar`', ('<p><span class=\"guilabel\"><span class=\"accelerator\">F</span>oo", "parse(text) assert_node(doctree[0], [nodes.paragraph, nodes.literal, \"a{b}c\"]) # no braces (whitespaces are", "<target>', 5, inliner, {}, []) assert_node(doctrees[0], [nodes.literal, 'title <target>']) #", "app.env.get_doctree('index') assert_node(doctree[0], nodes.section) assert_node(doctree[0][1], nodes.paragraph) assert_node(doctree[0][1][0], addnodes.index) assert_node(doctree[0][1][1], nodes.target) assert_node(doctree[0][1][2],", "= parse(text) assert_node(doctree[0], [nodes.paragraph, addnodes.download_reference, nodes.literal, \"sphinx.rst\"]) assert_node(doctree[0][0], refdoc='dummy', refdomain='',", "r'\\sphinxmenuselection{\\sphinxaccelerator{F}oo \\sphinxhyphen{}' r'\\&\\sphinxhyphen{} \\sphinxaccelerator{B}ar}'), ), ( # interpolation of ampersands", "... but not in literal text 'verify', '``\"John\"``', ('<p><code class=\"docutils", "parse(new_document): def parse_(rst): document = new_document() parser = RstParser() parser.parse(rst,", "world' # rst_prolog & rst_epilog on exlucding reST parser assert", "'verify', '.. glossary::\\n\\n term1\\n term2\\n description', ('<dl class=\"glossary docutils\">\\n' '<dt", "'</kbd></p>'), '\\\\sphinxAtStartPar\\n\\\\sphinxkeyboard{\\\\sphinxupquote{Control+X}}', ), ( # kbd role 'verify', ':kbd:`Alt+^`', ('<p><kbd", "doctree = parse(text) assert_node(doctree[0], [nodes.paragraph, nodes.literal, (\"a\", [nodes.emphasis, \"{b\"], \"}c\")])", "parse(rst) app.builder = LaTeXBuilder(app) app.builder.set_environment(app.env) app.builder.init() theme = app.builder.themes.get('manual') latex_translator", "pytest from docutils import frontend, nodes, utils from docutils.parsers.rst import", "return verify @pytest.fixture def verify_re_latex(app, parse): def verify(rst, latex_expected): document", "title=\"Permalink to this term\">¶</a></dt>' '<dd>description</dd>\\n</dl>'), None, ), ]) def test_inline(get_verifier,", "), ( # kbd role 'verify', ':kbd:`M-x M-s`', ('<p><kbd class=\"kbd", "test_inline_for_unicode_latex_engine(get_verifier, type, rst, html_expected, latex_expected): verifier = get_verifier(type) verifier(rst, html_expected,", "== 'List B:' assert_node(doctree[0][4], nodes.bullet_list) assert_node(doctree[0][4][0][0], nodes.paragraph) assert doctree[0][4][0][0].astext() ==", "8\\\\#id1}}\\\\sphinxhref' '{http://www.python.org/dev/peps/pep-0008\\\\#id1}' '{\\\\sphinxstylestrong{PEP 8\\\\#id1}}') ), ( # rfc role 'verify',", "nodes.literal, 'text']) assert_node(doctrees[0], refdoc='dummy', refdomain='test', reftype='doc', reftarget='text', refexplicit=False, refwarn=False) #", "'+' '<kbd class=\"kbd docutils literal notranslate\">X</kbd>' '</kbd></p>'), '\\\\sphinxAtStartPar\\n\\\\sphinxkeyboard{\\\\sphinxupquote{Control+X}}', ), (", "create(): document = utils.new_document('test data', settings) document['file'] = 'dummy' return", "class=\"kbd docutils literal notranslate\">M</kbd>' '-' '<kbd class=\"kbd docutils literal notranslate\">s</kbd>'", "simple 'verify', 'term\\n description', '<dl class=\"docutils\">\\n<dt>term</dt><dd>description</dd>\\n</dl>', None, ), ( #", "verify(rst, html_expected): document = parse(rst) KeyboardTransform(document).apply() html_translator = ForgivingHTMLTranslator(document, app.builder)", "= utils.new_document('test data', settings) document['file'] = 'dummy' return document return", "rst_prolog assert_node(rst[0], nodes.paragraph) assert_node(rst[0][0], nodes.emphasis) assert_node(rst[0][0][0], nodes.Text) assert rst[0][0][0] ==", "assert_node(doctree[0], nodes.section) assert_node(doctree[0][1], nodes.paragraph) assert_node(doctree[0][1][0], addnodes.index) assert_node(doctree[0][1][1], nodes.target) assert_node(doctree[0][1][2], nodes.reference,", "addnodes.download_reference, nodes.literal, \"sphinx.rst\"]) assert_node(doctree[0][0], refdoc='dummy', refdomain='', reftype='download', refexplicit=False, reftarget='sphinx.rst', refwarn=False)", "domain_context = sphinx_domains(settings.env) domain_context.enable() yield settings domain_context.disable() @pytest.fixture def new_document(settings):", "def verify_re_latex(app, parse): def verify(rst, latex_expected): document = parse(rst) app.builder", "\\sphinxaccelerator{B}ar}'), ), ( # interpolation of ampersands in guilabel 'verify',", "of arrows in menuselection 'verify', ':menuselection:`a --> b`', ('<p><span class=\"menuselection\">a", "with classifiers 'verify', 'term : class1 : class2\\n description', ('<dl", "sphinx.util import docutils, texescape from sphinx.util.docutils import sphinx_domains from sphinx.writers.html", "== 2 assert_node(doctree[0][1], nodes.system_message) @pytest.mark.sphinx('dummy', testroot='keep_warnings', confoverrides={'keep_warnings': False}) def test_keep_warnings_is_False(app,", "refwarn=False) # bang doctrees, errors = role('ref', 'rawtext', '!title <target>',", "1 assert_node(doctrees[0], [addnodes.pending_xref, nodes.literal, 'text']) assert_node(doctrees[0], refdoc='dummy', refdomain='', reftype='ref', reftarget='text',", "return parse_ # since we're not resolving the markup afterwards,", "@pytest.mark.skipif(docutils.__version_info__ < (0, 16), reason='docutils-0.16 or above is required') def", "<gh_stars>1000+ \"\"\" test_markup ~~~~~~~~~~~ Test various Sphinx-specific markup extensions. :copyright:", "html_expected, latex_expected): if html_expected: verify_re_html(rst, html_expected) if latex_expected: verify_re_latex(rst, latex_expected)", "'verify', ':rfc:`2324`', ('<p><span class=\"target\" id=\"index-0\"></span><a class=\"rfc reference external\" ' 'href=\"http://tools.ietf.org/html/rfc2324.html\"><strong>RFC", "literal notranslate\">X</kbd>' '</kbd></p>'), '\\\\sphinxAtStartPar\\n\\\\sphinxkeyboard{\\\\sphinxupquote{Control+X}}', ), ( # kbd role 'verify',", "docutils literal notranslate\">M</kbd>' '-' '<kbd class=\"kbd docutils literal notranslate\">x</kbd>' '", "role('ref', 'rawtext', 'title <target>', 5, inliner, {}, []) assert_node(doctrees[0], [addnodes.pending_xref,", "app.env.get_doctree('foo') assert_node(doctree[0], nodes.section) assert_node(doctree[0][1], nodes.paragraph) assert_node(doctree[0][1][0], nodes.title_reference) assert_node(doctree[0][1][1], nodes.Text) @pytest.mark.sphinx('dummy',", "# kbd role 'verify', ':kbd:`Caps Lock`', '<p><kbd class=\"kbd docutils literal", "literal notranslate\"><span class=\"pre\">' 'code</span>&#160;&#160; <span class=\"pre\">sample</span></code></p>'), r'\\\\sphinxAtStartPar\\n\\\\sphinxcode{\\\\sphinxupquote{code sample}}', ), (", "correct interpretation of code with whitespace 'verify_re', '``code sample``', ('<p><code", "BSD, see LICENSE for details. \"\"\" import re import pytest", "\"a{bc\"]) # escaped braces text = ':samp:`a\\\\\\\\{b}c`' doctree = parse(text)", "testroot='default_role', confoverrides={'default_role': 'guilabel'}) def test_default_role2(app, status, warning): app.builder.build_all() # default-role", "'<dt id=\"term-term2\">term2<a class=\"headerlink\" href=\"#term-term2\"' ' title=\"Permalink to this term\">¶</a></dt>' '<dd>description</dd>\\n</dl>'),", "anchor 'verify', ':rfc:`2324#id1`', ('<p><span class=\"target\" id=\"index-0\"></span><a class=\"rfc reference external\" '", "sample}}', ), ( # interpolation of arrows in menuselection 'verify',", "domain_context.enable() yield settings domain_context.disable() @pytest.fixture def new_document(settings): def create(): document", "default-role doctree = app.env.get_doctree('foo') assert_node(doctree[0], nodes.section) assert_node(doctree[0][1], nodes.paragraph) assert_node(doctree[0][1][0], nodes.title_reference)", "nodes.reference, classes=[\"pep\"]) # default_role changes the default behavior doctree =", "literal notranslate\">-</kbd></p>', ('\\\\sphinxAtStartPar\\n' '\\\\sphinxkeyboard{\\\\sphinxupquote{\\\\sphinxhyphen{}}}'), ), ( # kbd role 'verify',", "doctree[0][3].astext() == 'List B:' assert_node(doctree[0][4], nodes.bullet_list) assert_node(doctree[0][4][0][0], nodes.paragraph) assert doctree[0][4][0][0].astext()", "), ( # no ampersands in guilabel 'verify', ':guilabel:`Foo`', '<p><span", "assert_node(rst[-1][-1][0], nodes.emphasis) assert_node(rst[-1][-1][0][0], nodes.Text) assert rst[-1][-1][0][0] == 'Good-bye world' #", "docutils, texescape from sphinx.util.docutils import sphinx_domains from sphinx.writers.html import HTMLTranslator,", "document['file'] = 'dummy' return document return create @pytest.fixture def inliner(new_document):", "(\"a\", [nodes.emphasis, \"b\"], \"c\")]) # nested braces text = ':samp:`a{{b}}c`'", "), ( # description list: simple 'verify', 'term\\n description', '<dl", "return document return create @pytest.fixture def inliner(new_document): document = new_document()", "( # no ampersands in guilabel 'verify', ':guilabel:`Foo`', '<p><span class=\"guilabel\">Foo</span></p>',", "' ' '<kbd class=\"kbd docutils literal notranslate\">M</kbd>' '-' '<kbd class=\"kbd", "rst = app.env.get_doctree('restructuredtext') md = app.env.get_doctree('markdown') # rst_prolog assert_node(rst[0], nodes.paragraph)", "nodes.target) assert_node(doctree[0][1][2], nodes.reference, classes=[\"pep\"]) # default_role changes the default behavior", "':samp:`a\\\\\\\\{b}c`' doctree = parse(text) assert_node(doctree[0], [nodes.paragraph, nodes.literal, \"a{b}c\"]) # no", "('\\\\begin{sphinxVerbatim}[commandchars=\\\\\\\\\\\\{\\\\}]\\n' '@Γ\\\\PYGZbs{}\\\\(\\\\infty\\\\)\\\\PYGZdl{}\\\\PYGZob{}\\\\PYGZcb{}\\n' '\\\\end{sphinxVerbatim}'), ), ( # in URIs 'verify_re', '`test", "( # description list: with classifiers 'verify', 'term : class1", "assert_node(doctrees[0], [addnodes.pending_xref, nodes.literal, 'TEXT']) assert_node(doctrees[0], refdoc='dummy', refdomain='', reftype='ref', reftarget='text', refexplicit=False,", "nodes.bullet_list) assert_node(doctree[0][4][0][0], nodes.paragraph) assert doctree[0][4][0][0].astext() == 'Hello' @pytest.mark.sphinx('dummy', testroot='default_role') def", "anchor 'verify', ':pep:`8#id1`', ('<p><span class=\"target\" id=\"index-0\"></span><a class=\"pep reference external\" '", "# refdomain doctrees, errors = role('test:doc', 'rawtext', 'text', 5, inliner,", "inliner, {}, []) assert_node(doctrees[0], [nodes.literal, 'title <target>']) # refdomain doctrees,", "'verify', ':guilabel:`&Foo -&&- &Bar`', ('<p><span class=\"guilabel\"><span class=\"accelerator\">F</span>oo ' '-&amp;- <span", "role 'verify', ':kbd:`-`', '<p><kbd class=\"kbd docutils literal notranslate\">-</kbd></p>', ('\\\\sphinxAtStartPar\\n' '\\\\sphinxkeyboard{\\\\sphinxupquote{\\\\sphinxhyphen{}}}'),", "menuselection 'verify', ':menuselection:`&Foo -&&- &Bar`', ('<p><span class=\"menuselection\"><span class=\"accelerator\">F</span>oo ' '-&amp;-", "assert_node(doctrees[0], refdoc='dummy', refdomain='', reftype='ref', reftarget='text', refexplicit=False, refwarn=False) # lowercase role", "= RstParser() parser.parse(rst, document) SphinxSmartQuotes(document, startnode=None).apply() for msg in document.traverse(nodes.system_message):", "ForgivingTranslator: def visit_pending_xref(self, node): pass def depart_pending_xref(self, node): pass class", "literal notranslate\">M</kbd>' '-' '<kbd class=\"kbd docutils literal notranslate\">s</kbd>' '</kbd></p>'), ('\\\\sphinxAtStartPar\\n'", "nodes.section) assert len(doctree[0]) == 2 assert_node(doctree[0][1], nodes.system_message) @pytest.mark.sphinx('dummy', testroot='keep_warnings', confoverrides={'keep_warnings':", "[]) assert_node(doctrees[0], [addnodes.pending_xref, nodes.literal, 'text']) assert_node(doctrees[0], refdoc='dummy', refdomain='test', reftype='doc', reftarget='text',", "docutils literal notranslate\">M</kbd>' '-' '<kbd class=\"kbd docutils literal notranslate\">s</kbd>' '</kbd></p>'),", "'verify', ':menuselection:`&Foo -&&- &Bar`', ('<p><span class=\"menuselection\"><span class=\"accelerator\">F</span>oo ' '-&amp;- <span", "return create @pytest.fixture def inliner(new_document): document = new_document() document.reporter.get_source_and_line =", "verify(verify_re_html, verify_re_latex): def verify_(rst, html_expected, latex_expected): if html_expected: verify_re_html(rst, re.escape(html_expected)", "':samp:`a{b}c`' doctree = parse(text) assert_node(doctree[0], [nodes.paragraph, nodes.literal, (\"a\", [nodes.emphasis, \"b\"],", "~~~~~~~~~~~ Test various Sphinx-specific markup extensions. :copyright: Copyright 2007-2021 by", "'\\\\sphinxhref{http://tools.ietf.org/html/rfc2324.html\\\\#id1}' '{\\\\sphinxstylestrong{RFC 2324\\\\#id1}}') ), ( # correct interpretation of code", "'\\\\sphinxkeyboard{\\\\sphinxupquote{Caps Lock}}'), ), ( # non-interpolation of dashes in option", "verify classes for inline roles 'verify', ':manpage:`mp(1)`', '<p><em class=\"manpage\">mp(1)</em></p>', '\\\\sphinxAtStartPar\\n\\\\sphinxstyleliteralemphasis{\\\\sphinxupquote{mp(1)}}',", "type, rst, html_expected, latex_expected): verifier = get_verifier(type) verifier(rst, html_expected, latex_expected)", "testroot='keep_warnings', confoverrides={'keep_warnings': False}) def test_keep_warnings_is_False(app, status, warning): app.builder.build_all() doctree =", "backslashes \\\\</p>', None, ), ]) @pytest.mark.skipif(docutils.__version_info__ < (0, 16), reason='docutils-0.16", "), ( # kbd role 'verify', ':kbd:`Control+X`', ('<p><kbd class=\"kbd compound", "len(doctree[0]) == 5 assert doctree[0][1].astext() == 'List A:' assert_node(doctree[0][2], nodes.bullet_list)", "Enhancement Proposals@\\\\spxentry{Python Enhancement Proposals}' '!PEP 8\\\\#id1@\\\\spxentry{PEP 8\\\\#id1}}\\\\sphinxhref' '{http://www.python.org/dev/peps/pep-0008\\\\#id1}' '{\\\\sphinxstylestrong{PEP 8\\\\#id1}}')", "interpretation of code with whitespace 'verify_re', '``code sample``', ('<p><code class=\"(samp", "def new_document(settings): def create(): document = utils.new_document('test data', settings) document['file']", "exlucding reST parser assert not md.rawsource.startswith('*Hello world*.') assert not md.rawsource.endswith('*Good-bye", "def get_verifier(verify, verify_re): v = { 'verify': verify, 'verify_re': verify_re,", "role('ref', 'rawtext', 'TEXT', 5, inliner, {}, []) assert_node(doctrees[0], [addnodes.pending_xref, nodes.literal,", "'!PEP 8@\\\\spxentry{PEP 8}}\\\\sphinxhref{http://www.python.org/dev/peps/pep-0008}' '{\\\\sphinxstylestrong{PEP 8}}') ), ( # pep role", "term2\\n description', ('<dl class=\"glossary docutils\">\\n' '<dt id=\"term-term1\">term1<a class=\"headerlink\" href=\"#term-term1\"' '", "= parse(text) assert_node(doctree[0], [nodes.paragraph, nodes.literal, \"code sample\"]) def test_download_role(parse): #", "yield settings domain_context.disable() @pytest.fixture def new_document(settings): def create(): document =", "{}, []) assert_node(doctrees[0], [addnodes.pending_xref, nodes.literal, 'TEXT']) assert_node(doctrees[0], refdoc='dummy', refdomain='', reftype='ref',", "== 1: msg.replace_self([]) return document return parse_ # since we're", "class=\"xref std std-option docutils literal notranslate\")?>' '<span class=\"pre\">--with-option</span></code></p>$'), (r'\\\\sphinxAtStartPar\\n' r'\\\\sphinxcode{\\\\sphinxupquote{\\\\sphinxhyphen{}\\\\sphinxhyphen{}with\\\\sphinxhyphen{}option}}$'),", "import LaTeXBuilder from sphinx.roles import XRefRole from sphinx.testing.util import Struct,", "class=\"menuselection\">a \\N{TRIANGULAR BULLET} b</span></p>'), '\\\\sphinxAtStartPar\\n\\\\sphinxmenuselection{a \\\\(\\\\rightarrow\\\\) b}', ), ( #", "class=\"docutils\">\\n<dt>term<span class=\"classifier\">class1</span>' '<span class=\"classifier\">class2</span></dt><dd>description</dd>\\n</dl>'), None, ), ( # glossary (description", "reftype='doc', reftarget='text', refexplicit=False, refwarn=False) # fix_parens role = XRefRole(fix_parens=True) doctrees,", "= ':samp:`a{bc`' doctree = parse(text) assert_node(doctree[0], [nodes.paragraph, nodes.literal, \"a{bc\"]) #", "notranslate\">M</kbd>' '-' '<kbd class=\"kbd docutils literal notranslate\">x</kbd>' ' ' '<kbd", "latex_expected: verify_re_latex(rst, re.escape(latex_expected) + '$') return verify_ @pytest.fixture def get_verifier(verify,", "as is) text = ':samp:`code sample`' doctree = parse(text) assert_node(doctree[0],", "for details. \"\"\" import re import pytest from docutils import", "in document.traverse(nodes.system_message): if msg['level'] == 1: msg.replace_self([]) return document return", "text = ':samp:`a{bc`' doctree = parse(text) assert_node(doctree[0], [nodes.paragraph, nodes.literal, \"a{bc\"])", "inliner, {}, []) assert_node(doctrees[0], [addnodes.pending_xref, nodes.literal, 'TEXT']) assert_node(doctrees[0], refdoc='dummy', refdomain='',", "'dummy' settings.rfc_base_url = 'http://tools.ietf.org/html/' domain_context = sphinx_domains(settings.env) domain_context.enable() yield settings", "this term\">¶</a></dt>' '<dt id=\"term-term2\">term2<a class=\"headerlink\" href=\"#term-term2\"' ' title=\"Permalink to this", "verifier = get_verifier(type) verifier(rst, html_expected, latex_expected) @pytest.mark.sphinx(confoverrides={'latex_engine': 'xelatex'}) @pytest.mark.parametrize('type,rst,html_expected,latex_expected', [", "world' # rst_epilog assert_node(rst[-1], nodes.section) assert_node(rst[-1][-1], nodes.paragraph) assert_node(rst[-1][-1][0], nodes.emphasis) assert_node(rst[-1][-1][0][0],", "testroot='refonly_bullet_list') def test_compact_refonly_bullet_list(app, status, warning): app.builder.build_all() doctree = app.env.get_doctree('index') assert_node(doctree[0],", "'<dd>description</dd>\\n</dl>'), None, ), ]) def test_inline(get_verifier, type, rst, html_expected, latex_expected):", "('dummy.rst', line) return Struct(document=document, reporter=document.reporter) @pytest.fixture def parse(new_document): def parse_(rst):", "# kbd role 'verify', ':kbd:`Alt+^`', ('<p><kbd class=\"kbd compound docutils literal", "Enhancement Proposals@\\\\spxentry{Python Enhancement Proposals}' '!PEP 8@\\\\spxentry{PEP 8}}\\\\sphinxhref{http://www.python.org/dev/peps/pep-0008}' '{\\\\sphinxstylestrong{PEP 8}}') ),", ": class1 : class2\\n description', ('<dl class=\"docutils\">\\n<dt>term<span class=\"classifier\">class1</span>' '<span class=\"classifier\">class2</span></dt><dd>description</dd>\\n</dl>'),", "':pep:`8#id1`', ('<p><span class=\"target\" id=\"index-0\"></span><a class=\"pep reference external\" ' 'href=\"http://www.python.org/dev/peps/pep-0008#id1\">' '<strong>PEP", "Proposals@\\\\spxentry{Python Enhancement Proposals}' '!PEP 8\\\\#id1@\\\\spxentry{PEP 8\\\\#id1}}\\\\sphinxhref' '{http://www.python.org/dev/peps/pep-0008\\\\#id1}' '{\\\\sphinxstylestrong{PEP 8\\\\#id1}}') ),", "@pytest.fixture def parse(new_document): def parse_(rst): document = new_document() parser =", "parse(text) assert_node(doctree[0], [nodes.paragraph, addnodes.download_reference, nodes.literal, \"reftitle\"]) assert_node(doctree[0][0], refdoc='dummy', refdomain='', reftype='download',", "reference external\" ' 'href=\"http://www.python.org/dev/peps/pep-0008\"><strong>PEP 8</strong></a></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\index{Python Enhancement Proposals@\\\\spxentry{Python Enhancement", "notranslate\">-</kbd></p>', ('\\\\sphinxAtStartPar\\n' '\\\\sphinxkeyboard{\\\\sphinxupquote{\\\\sphinxhyphen{}}}'), ), ( # kbd role 'verify', ':kbd:`Caps", "nodes.emphasis) assert_node(rst[-1][-1][0][0], nodes.Text) assert rst[-1][-1][0][0] == 'Good-bye world' # rst_prolog", "Parser as RstParser from sphinx import addnodes from sphinx.builders.html.transforms import", "verify_re_latex): def verify_(rst, html_expected, latex_expected): if html_expected: verify_re_html(rst, re.escape(html_expected) +", "= app.env.get_doctree('markdown') # rst_prolog assert_node(rst[0], nodes.paragraph) assert_node(rst[0][0], nodes.emphasis) assert_node(rst[0][0][0], nodes.Text)", "refdomain='', reftype='download', refexplicit=True, reftarget='sphinx.rst', refwarn=False) assert_node(doctree[0][0][0], classes=['xref', 'download']) def test_XRefRole(inliner):", "assert_node(doctree[0][1][0], nodes.title_reference) assert_node(doctree[0][1][1], nodes.Text) @pytest.mark.sphinx('dummy', testroot='default_role', confoverrides={'default_role': 'guilabel'}) def test_default_role2(app,", "class=\"headerlink\" href=\"#term-term2\"' ' title=\"Permalink to this term\">¶</a></dt>' '<dd>description</dd>\\n</dl>'), None, ),", "refdoc='dummy', refdomain='', reftype='download', refexplicit=True, reftarget='sphinx.rst', refwarn=False) assert_node(doctree[0][0][0], classes=['xref', 'download']) def", "verify @pytest.fixture def verify_re(verify_re_html, verify_re_latex): def verify_re_(rst, html_expected, latex_expected): if", "'verify_re', '`test <https://www.google.com/~me/>`_', None, r'\\\\sphinxAtStartPar\\n\\\\sphinxhref{https://www.google.com/~me/}{test}.*', ), ( # description list:", "[nodes.paragraph, nodes.literal, \"code sample\"]) def test_download_role(parse): # implicit text =", "from sphinx.writers.latex import LaTeXTranslator, LaTeXWriter @pytest.fixture def settings(app): texescape.init() #", "interpolation of arrows in menuselection 'verify', ':menuselection:`a --> b`', ('<p><span", "= XRefRole(lowercase=True) doctrees, errors = role('ref', 'rawtext', 'TEXT', 5, inliner,", "XRefRole(lowercase=True) doctrees, errors = role('ref', 'rawtext', 'TEXT', 5, inliner, {},", "assert errors == [] # explicit doctrees, errors = role('ref',", "escaped braces text = ':samp:`a\\\\\\\\{b}c`' doctree = parse(text) assert_node(doctree[0], [nodes.paragraph,", "'\\\\sphinxAtStartPar\\n\\\\sphinxkeyboard{\\\\sphinxupquote{space}}', ), ( # kbd role 'verify', ':kbd:`Control+X`', ('<p><kbd class=\"kbd", "frontend, nodes, utils from docutils.parsers.rst import Parser as RstParser from", "= LaTeXBuilder(app) app.builder.set_environment(app.env) app.builder.init() theme = app.builder.themes.get('manual') latex_translator = ForgivingLaTeXTranslator(document,", "&Bar`', ('<p><span class=\"guilabel\"><span class=\"accelerator\">F</span>oo ' '-&amp;- <span class=\"accelerator\">B</span>ar</span></p>'), ('\\\\sphinxAtStartPar\\n' r'\\sphinxguilabel{\\sphinxaccelerator{F}oo", "kbd role 'verify', ':kbd:`Caps Lock`', '<p><kbd class=\"kbd docutils literal notranslate\">Caps", "doctrees, errors = role('ref', 'rawtext', 'title <target>', 5, inliner, {},", "rfc role 'verify', ':rfc:`2324`', ('<p><span class=\"target\" id=\"index-0\"></span><a class=\"rfc reference external\"", "for inline roles 'verify', ':manpage:`mp(1)`', '<p><em class=\"manpage\">mp(1)</em></p>', '\\\\sphinxAtStartPar\\n\\\\sphinxstyleliteralemphasis{\\\\sphinxupquote{mp(1)}}', ), (", "None, ('\\\\begin{sphinxVerbatim}[commandchars=\\\\\\\\\\\\{\\\\}]\\n' '@Γ\\\\PYGZbs{}\\\\(\\\\infty\\\\)\\\\PYGZdl{}\\\\PYGZob{}\\\\PYGZcb{}\\n' '\\\\end{sphinxVerbatim}'), ), ( # in URIs 'verify_re',", "LaTeXBuilder from sphinx.roles import XRefRole from sphinx.testing.util import Struct, assert_node", "nodes.section) assert_node(doctree[0][1], nodes.paragraph) assert_node(doctree[0][1][0], addnodes.index) assert_node(doctree[0][1][1], nodes.target) assert_node(doctree[0][1][2], nodes.reference, classes=[\"pep\"])", "code fragments 'verify', '::\\n\\n @Γ\\\\∞${}', None, ('\\\\begin{sphinxVerbatim}[commandchars=\\\\\\\\\\\\{\\\\}]\\n' '@Γ\\\\PYGZbs{}\\\\(\\\\infty\\\\)\\\\PYGZdl{}\\\\PYGZob{}\\\\PYGZcb{}\\n' '\\\\end{sphinxVerbatim}'), ),", "nodes.literal, \"code sample\"]) def test_download_role(parse): # implicit text = ':download:`sphinx.rst`'", "test_XRefRole(inliner): role = XRefRole() # implicit doctrees, errors = role('ref',", "literal notranslate\">' '<kbd class=\"kbd docutils literal notranslate\">Control</kbd>' '+' '<kbd class=\"kbd", "'<kbd class=\"kbd docutils literal notranslate\">M</kbd>' '-' '<kbd class=\"kbd docutils literal", "# explicit doctrees, errors = role('ref', 'rawtext', 'title <target>', 5,", "+ rst return verify @pytest.fixture def verify_re_latex(app, parse): def verify(rst,", "app.builder.build_all() rst = app.env.get_doctree('restructuredtext') md = app.env.get_doctree('markdown') # rst_prolog assert_node(rst[0],", "[addnodes.pending_xref, nodes.literal, 'TEXT']) assert_node(doctrees[0], refdoc='dummy', refdomain='', reftype='ref', reftarget='text', refexplicit=False, refwarn=False)", "literal notranslate\">^</kbd>' '</kbd></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\sphinxkeyboard{\\\\sphinxupquote{Alt+\\\\textasciicircum{}}}'), ), ( # kbd role", "'<kbd class=\"kbd docutils literal notranslate\">X</kbd>' '</kbd></p>'), '\\\\sphinxAtStartPar\\n\\\\sphinxkeyboard{\\\\sphinxupquote{Control+X}}', ), ( #", "in guilabel 'verify', ':guilabel:`Foo`', '<p><span class=\"guilabel\">Foo</span></p>', '\\\\sphinxAtStartPar\\n\\\\sphinxguilabel{Foo}', ), ( #", "in URIs 'verify_re', '`test <https://www.google.com/~me/>`_', None, r'\\\\sphinxAtStartPar\\n\\\\sphinxhref{https://www.google.com/~me/}{test}.*', ), ( #", "' + rst return verify @pytest.fixture def verify_re_latex(app, parse): def", "'</kbd></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\sphinxkeyboard{\\\\sphinxupquote{Alt+\\\\textasciicircum{}}}'), ), ( # kbd role 'verify', ':kbd:`M-x", "def test_default_role1(app, status, warning): app.builder.build_all() # default-role: pep doctree =", "docutils literal notranslate\">Caps Lock</kbd></p>', ('\\\\sphinxAtStartPar\\n' '\\\\sphinxkeyboard{\\\\sphinxupquote{Caps Lock}}'), ), ( #", "\\sphinxaccelerator{B}ar}'), ), ( # no ampersands in guilabel 'verify', ':guilabel:`Foo`',", "def test_rst_prolog(app, status, warning): app.builder.build_all() rst = app.env.get_doctree('restructuredtext') md =", "8@\\\\spxentry{PEP 8}}\\\\sphinxhref{http://www.python.org/dev/peps/pep-0008}' '{\\\\sphinxstylestrong{PEP 8}}') ), ( # pep role with", "= get_verifier(type) verifier(rst, html_expected, latex_expected) def test_samp_role(parse): # no braces", "from sphinx.util import docutils, texescape from sphinx.util.docutils import sphinx_domains from", "normal mode 'verify', 'Γ\\\\\\\\∞$', None, '\\\\sphinxAtStartPar\\nΓ\\\\textbackslash{}\\\\(\\\\infty\\\\)\\\\$', ), ( # in", "== 'List A:' assert_node(doctree[0][2], nodes.bullet_list) assert_node(doctree[0][2][0][0], addnodes.compact_paragraph) assert doctree[0][2][0][0].astext() ==", "None, '\\\\sphinxAtStartPar\\nΓ\\\\textbackslash{}\\\\(\\\\infty\\\\)\\\\$', ), ( # in verbatim code fragments 'verify',", "in guilabel 'verify', ':guilabel:`&Foo -&&- &Bar`', ('<p><span class=\"guilabel\"><span class=\"accelerator\">F</span>oo '", "mode 'verify', 'Γ\\\\\\\\∞$', None, '\\\\sphinxAtStartPar\\nΓ\\\\textbackslash{}\\\\(\\\\infty\\\\)\\\\$', ), ( # in verbatim", "nodes.literal, 'text']) assert_node(doctrees[0], refdoc='dummy', refdomain='', reftype='ref', reftarget='text', refexplicit=False, refwarn=False) assert", "of dashes in option role 'verify_re', ':option:`--with-option`', ('<p><code( class=\"xref std", "16), reason='docutils-0.16 or above is required') def test_inline_docutils16(get_verifier, type, rst,", "role 'verify_re', ':option:`--with-option`', ('<p><code( class=\"xref std std-option docutils literal notranslate\")?>'", "def test_inline(get_verifier, type, rst, html_expected, latex_expected): verifier = get_verifier(type) verifier(rst,", "\"\\\\sphinxAtStartPar\\n“John”\", ), ( # ... but not in literal text", "settings = optparser.get_default_values() settings.smart_quotes = True settings.env = app.builder.env settings.env.temp_data['docname']", "refdoc='dummy', refdomain='', reftype='ref', reftarget='text', refexplicit=False, refwarn=False) @pytest.mark.sphinx('dummy', testroot='prolog') def test_rst_prolog(app,", "8#id1</strong></a></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\index{Python Enhancement Proposals@\\\\spxentry{Python Enhancement Proposals}' '!PEP 8\\\\#id1@\\\\spxentry{PEP 8\\\\#id1}}\\\\sphinxhref'", "( # correct interpretation of code with whitespace 'verify_re', '``code", "None, r'\\\\sphinxAtStartPar\\n\\\\sphinxhref{https://www.google.com/~me/}{test}.*', ), ( # description list: simple 'verify', 'term\\n", "('\\\\sphinxAtStartPar\\n' '\\\\index{Python Enhancement Proposals@\\\\spxentry{Python Enhancement Proposals}' '!PEP 8@\\\\spxentry{PEP 8}}\\\\sphinxhref{http://www.python.org/dev/peps/pep-0008}' '{\\\\sphinxstylestrong{PEP", "refdomain doctrees, errors = role('test:doc', 'rawtext', 'text', 5, inliner, {},", "def test_download_role(parse): # implicit text = ':download:`sphinx.rst`' doctree = parse(text)", "\\N{TRIANGULAR BULLET} b</span></p>'), '\\\\sphinxAtStartPar\\n\\\\sphinxmenuselection{a \\\\(\\\\rightarrow\\\\) b}', ), ( # interpolation", "'!PEP 8\\\\#id1@\\\\spxentry{PEP 8\\\\#id1}}\\\\sphinxhref' '{http://www.python.org/dev/peps/pep-0008\\\\#id1}' '{\\\\sphinxstylestrong{PEP 8\\\\#id1}}') ), ( # rfc", "class=\"kbd compound docutils literal notranslate\">' '<kbd class=\"kbd docutils literal notranslate\">M</kbd>'", "id=\"term-term2\">term2<a class=\"headerlink\" href=\"#term-term2\"' ' title=\"Permalink to this term\">¶</a></dt>' '<dd>description</dd>\\n</dl>'), None,", "assert_node(doctree[0], [nodes.paragraph, nodes.literal, (\"a\", [nodes.emphasis, \"{b\"], \"}c\")]) # half-opened braces", "('<p><span class=\"menuselection\"><span class=\"accelerator\">F</span>oo ' '-&amp;- <span class=\"accelerator\">B</span>ar</span></p>'), ('\\\\sphinxAtStartPar\\n' r'\\sphinxmenuselection{\\sphinxaccelerator{F}oo \\sphinxhyphen{}'", "('<p><span class=\"menuselection\">a \\N{TRIANGULAR BULLET} b</span></p>'), '\\\\sphinxAtStartPar\\n\\\\sphinxmenuselection{a \\\\(\\\\rightarrow\\\\) b}', ), (", "'\\\\sphinxAtStartPar\\n\\\\sphinxcode{\\\\sphinxupquote{\"John\"}}', ), ( # verify classes for inline roles 'verify',", "'</kbd></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\sphinxkeyboard{\\\\sphinxupquote{M\\\\sphinxhyphen{}x M\\\\sphinxhyphen{}s}}'), ), ( # kbd role 'verify',", "& rst_epilog on exlucding reST parser assert not md.rawsource.startswith('*Hello world*.')", "'{\\\\sphinxstylestrong{PEP 8}}') ), ( # pep role with anchor 'verify',", "'\\\\index{Python Enhancement Proposals@\\\\spxentry{Python Enhancement Proposals}' '!PEP 8\\\\#id1@\\\\spxentry{PEP 8\\\\#id1}}\\\\sphinxhref' '{http://www.python.org/dev/peps/pep-0008\\\\#id1}' '{\\\\sphinxstylestrong{PEP", "def inliner(new_document): document = new_document() document.reporter.get_source_and_line = lambda line=1: ('dummy.rst',", "' '<kbd class=\"kbd docutils literal notranslate\">M</kbd>' '-' '<kbd class=\"kbd docutils", "False}) def test_keep_warnings_is_False(app, status, warning): app.builder.build_all() doctree = app.env.get_doctree('index') assert_node(doctree[0],", "literal notranslate\")?>' '<span class=\"pre\">--with-option</span></code></p>$'), (r'\\\\sphinxAtStartPar\\n' r'\\\\sphinxcode{\\\\sphinxupquote{\\\\sphinxhyphen{}\\\\sphinxhyphen{}with\\\\sphinxhyphen{}option}}$'), ), ( # verify", "Enhancement Proposals}' '!PEP 8@\\\\spxentry{PEP 8}}\\\\sphinxhref{http://www.python.org/dev/peps/pep-0008}' '{\\\\sphinxstylestrong{PEP 8}}') ), ( #", "'verify_re', '``code sample``', ('<p><code class=\"(samp )?docutils literal notranslate\"><span class=\"pre\">' 'code</span>&#160;&#160;", "'!title <target>', 5, inliner, {}, []) assert_node(doctrees[0], [nodes.literal, 'title <target>'])", "stronger than configratuion doctree = app.env.get_doctree('index') assert_node(doctree[0], nodes.section) assert_node(doctree[0][1], nodes.paragraph)", "pass class ForgivingHTMLTranslator(HTMLTranslator, ForgivingTranslator): pass class ForgivingLaTeXTranslator(LaTeXTranslator, ForgivingTranslator): pass @pytest.fixture", "= app.env.get_doctree('foo') assert_node(doctree[0], nodes.section) assert_node(doctree[0][1], nodes.paragraph) assert_node(doctree[0][1][0], nodes.title_reference) assert_node(doctree[0][1][1], nodes.Text)", "assert_node(doctree[0][2], nodes.bullet_list) assert_node(doctree[0][2][0][0], addnodes.compact_paragraph) assert doctree[0][2][0][0].astext() == 'genindex' assert doctree[0][3].astext()", "( # ... but not in literal text 'verify', '``\"John\"``',", "':option:`--with-option`', ('<p><code( class=\"xref std std-option docutils literal notranslate\")?>' '<span class=\"pre\">--with-option</span></code></p>$'),", "assert not md.rawsource.endswith('*Good-bye world*.\\n') @pytest.mark.sphinx('dummy', testroot='keep_warnings') def test_keep_warnings_is_True(app, status, warning):", "Copyright 2007-2021 by the Sphinx team, see AUTHORS. :license: BSD,", "id=\"index-0\"></span><a class=\"rfc reference external\" ' 'href=\"http://tools.ietf.org/html/rfc2324.html#id1\">' '<strong>RFC 2324#id1</strong></a></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\index{RFC@\\\\spxentry{RFC}!RFC", "app.builder = LaTeXBuilder(app) app.builder.set_environment(app.env) app.builder.init() theme = app.builder.themes.get('manual') latex_translator =", "default behavior doctree = app.env.get_doctree('foo') assert_node(doctree[0], nodes.section) assert_node(doctree[0][1], nodes.paragraph) assert_node(doctree[0][1][0],", "assert_node(rst[-1][-1][0][0], nodes.Text) assert rst[-1][-1][0][0] == 'Good-bye world' # rst_prolog &", "assert_node(doctree[0][1][2], nodes.reference, classes=[\"pep\"]) # no default-role doctree = app.env.get_doctree('foo') assert_node(doctree[0],", "text = ':download:`reftitle <sphinx.rst>`' doctree = parse(text) assert_node(doctree[0], [nodes.paragraph, addnodes.download_reference,", "' 'href=\"http://www.python.org/dev/peps/pep-0008#id1\">' '<strong>PEP 8#id1</strong></a></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\index{Python Enhancement Proposals@\\\\spxentry{Python Enhancement Proposals}'", "notranslate\">Alt</kbd>' '+' '<kbd class=\"kbd docutils literal notranslate\">^</kbd>' '</kbd></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\sphinxkeyboard{\\\\sphinxupquote{Alt+\\\\textasciicircum{}}}'),", "class=\"docutils literal notranslate\"><span class=\"pre\">' '&quot;John&quot;</span></code></p>'), '\\\\sphinxAtStartPar\\n\\\\sphinxcode{\\\\sphinxupquote{\"John\"}}', ), ( # verify", "= -1 # don't write \\begin{document} document.walkabout(latex_translator) latex_translated = ''.join(latex_translator.body).strip()", "[addnodes.pending_xref, nodes.literal, 'title']) assert_node(doctrees[0], refdoc='dummy', refdomain='', reftype='ref', reftarget='target', refexplicit=True, refwarn=False)", "import addnodes from sphinx.builders.html.transforms import KeyboardTransform from sphinx.builders.latex import LaTeXBuilder", "nodes.reference, classes=[\"pep\"]) # no default-role doctree = app.env.get_doctree('foo') assert_node(doctree[0], nodes.section)", "assert_node from sphinx.transforms import SphinxSmartQuotes from sphinx.util import docutils, texescape", "( # kbd role 'verify', ':kbd:`Alt+^`', ('<p><kbd class=\"kbd compound docutils", "''.join(html_translator.fragment).strip() assert re.match(html_expected, html_translated), 'from ' + rst return verify", "document.walkabout(latex_translator) latex_translated = ''.join(latex_translator.body).strip() assert re.match(latex_expected, latex_translated), 'from ' +", "domain_context.disable() @pytest.fixture def new_document(settings): def create(): document = utils.new_document('test data',", "no ampersands in guilabel 'verify', ':guilabel:`Foo`', '<p><span class=\"guilabel\">Foo</span></p>', '\\\\sphinxAtStartPar\\n\\\\sphinxguilabel{Foo}', ),", "( # non-interpolation of dashes in option role 'verify_re', ':option:`--with-option`',", "= XRefRole() # implicit doctrees, errors = role('ref', 'rawtext', 'text',", "ForgivingTranslator): pass @pytest.fixture def verify_re_html(app, parse): def verify(rst, html_expected): document", "== 'Good-bye world' # rst_prolog & rst_epilog on exlucding reST", "assert_node(doctree[0][1], nodes.paragraph) assert_node(doctree[0][1][0], addnodes.index) assert_node(doctree[0][1][1], nodes.target) assert_node(doctree[0][1][2], nodes.reference, classes=[\"pep\"]) #", "settings domain_context.disable() @pytest.fixture def new_document(settings): def create(): document = utils.new_document('test", "refexplicit=False, refwarn=False) @pytest.mark.sphinx('dummy', testroot='prolog') def test_rst_prolog(app, status, warning): app.builder.build_all() rst", "class=\"docutils\">\\n<dt>term</dt><dd>description</dd>\\n</dl>', None, ), ( # description list: with classifiers 'verify',", "status, warning): app.builder.build_all() doctree = app.env.get_doctree('index') assert_node(doctree[0], nodes.section) assert len(doctree[0])", "reST parser assert not md.rawsource.startswith('*Hello world*.') assert not md.rawsource.endswith('*Good-bye world*.\\n')", "latex_expected) @pytest.mark.sphinx(confoverrides={'latex_engine': 'xelatex'}) @pytest.mark.parametrize('type,rst,html_expected,latex_expected', [ ( # in verbatim code", "= ':samp:`a\\\\\\\\{b}c`' doctree = parse(text) assert_node(doctree[0], [nodes.paragraph, nodes.literal, \"a{b}c\"]) #", "'href=\"http://www.python.org/dev/peps/pep-0008#id1\">' '<strong>PEP 8#id1</strong></a></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\index{Python Enhancement Proposals@\\\\spxentry{Python Enhancement Proposals}' '!PEP", "html_expected) if latex_expected: verify_re_latex(rst, latex_expected) return verify_re_ @pytest.fixture def verify(verify_re_html,", "5, inliner, {}, []) assert_node(doctrees[0], [addnodes.pending_xref, nodes.literal, 'title']) assert_node(doctrees[0], refdoc='dummy',", "verify_re_html(app, parse): def verify(rst, html_expected): document = parse(rst) KeyboardTransform(document).apply() html_translator", "{}, []) assert_node(doctrees[0], [nodes.literal, 'title <target>']) # refdomain doctrees, errors", "testroot='keep_warnings') def test_keep_warnings_is_True(app, status, warning): app.builder.build_all() doctree = app.env.get_doctree('index') assert_node(doctree[0],", "braces (whitespaces are keeped as is) text = ':samp:`code sample`'", "inliner, {}, []) assert len(doctrees) == 1 assert_node(doctrees[0], [addnodes.pending_xref, nodes.literal,", "class=\"pep reference external\" ' 'href=\"http://www.python.org/dev/peps/pep-0008#id1\">' '<strong>PEP 8#id1</strong></a></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\index{Python Enhancement", "class=\"pre\">' 'code</span>&#160;&#160; <span class=\"pre\">sample</span></code></p>'), r'\\\\sphinxAtStartPar\\n\\\\sphinxcode{\\\\sphinxupquote{code sample}}', ), ( # interpolation", "class=\"pre\">--with-option</span></code></p>$'), (r'\\\\sphinxAtStartPar\\n' r'\\\\sphinxcode{\\\\sphinxupquote{\\\\sphinxhyphen{}\\\\sphinxhyphen{}with\\\\sphinxhyphen{}option}}$'), ), ( # verify smarty-pants quotes 'verify',", "warning): app.builder.build_all() # default-role directive is stronger than configratuion doctree", "class ForgivingLaTeXTranslator(LaTeXTranslator, ForgivingTranslator): pass @pytest.fixture def verify_re_html(app, parse): def verify(rst,", "of ampersands in guilabel 'verify', ':guilabel:`&Foo -&&- &Bar`', ('<p><span class=\"guilabel\"><span", "'<p><kbd class=\"kbd docutils literal notranslate\">Caps Lock</kbd></p>', ('\\\\sphinxAtStartPar\\n' '\\\\sphinxkeyboard{\\\\sphinxupquote{Caps Lock}}'), ),", "\"b\"], \"c\")]) # nested braces text = ':samp:`a{{b}}c`' doctree =", "world*.\\n') @pytest.mark.sphinx('dummy', testroot='keep_warnings') def test_keep_warnings_is_True(app, status, warning): app.builder.build_all() doctree =", "role 'verify', ':kbd:`Alt+^`', ('<p><kbd class=\"kbd compound docutils literal notranslate\">' '<kbd", "# correct interpretation of code with whitespace 'verify_re', '``code sample``',", "'-&amp;- <span class=\"accelerator\">B</span>ar</span></p>'), ('\\\\sphinxAtStartPar\\n' r'\\sphinxguilabel{\\sphinxaccelerator{F}oo \\sphinxhyphen{}\\&\\sphinxhyphen{} \\sphinxaccelerator{B}ar}'), ), ( #", "docutils\">\\n' '<dt id=\"term-term1\">term1<a class=\"headerlink\" href=\"#term-term1\"' ' title=\"Permalink to this term\">¶</a></dt>'", "class=\"kbd compound docutils literal notranslate\">' '<kbd class=\"kbd docutils literal notranslate\">Control</kbd>'", "':download:`sphinx.rst`' doctree = parse(text) assert_node(doctree[0], [nodes.paragraph, addnodes.download_reference, nodes.literal, \"sphinx.rst\"]) assert_node(doctree[0][0],", "'\\\\sphinxkeyboard{\\\\sphinxupquote{M\\\\sphinxhyphen{}x M\\\\sphinxhyphen{}s}}'), ), ( # kbd role 'verify', ':kbd:`-`', '<p><kbd", "latex_translator = ForgivingLaTeXTranslator(document, app.builder, theme) latex_translator.first_document = -1 # don't", "<span class=\"accelerator\">B</span>ar</span></p>'), ('\\\\sphinxAtStartPar\\n' r'\\sphinxguilabel{\\sphinxaccelerator{F}oo \\sphinxhyphen{}\\&\\sphinxhyphen{} \\sphinxaccelerator{B}ar}'), ), ( # no", "implicit doctrees, errors = role('ref', 'rawtext', 'text', 5, inliner, {},", "+ '$') if latex_expected: verify_re_latex(rst, re.escape(latex_expected) + '$') return verify_", "{}, []) assert_node(doctrees[0], [addnodes.pending_xref, nodes.literal, 'title']) assert_node(doctrees[0], refdoc='dummy', refdomain='', reftype='ref',", "'``\"John\"``', ('<p><code class=\"docutils literal notranslate\"><span class=\"pre\">' '&quot;John&quot;</span></code></p>'), '\\\\sphinxAtStartPar\\n\\\\sphinxcode{\\\\sphinxupquote{\"John\"}}', ), (", "5, inliner, {}, []) assert_node(doctrees[0], [nodes.literal, 'title <target>']) # refdomain", "settings(app): texescape.init() # otherwise done by the latex builder optparser", "html_expected, latex_expected): verifier = get_verifier(type) verifier(rst, html_expected, latex_expected) @pytest.mark.parametrize('type,rst,html_expected,latex_expected', [", "'title']) assert_node(doctrees[0], refdoc='dummy', refdomain='', reftype='ref', reftarget='target', refexplicit=True, refwarn=False) # bang", "doctrees, errors = role('ref', 'rawtext', '!title <target>', 5, inliner, {},", "' '-&amp;- <span class=\"accelerator\">B</span>ar</span></p>'), ('\\\\sphinxAtStartPar\\n' r'\\sphinxmenuselection{\\sphinxaccelerator{F}oo \\sphinxhyphen{}' r'\\&\\sphinxhyphen{} \\sphinxaccelerator{B}ar}'), ),", "( # verify classes for inline roles 'verify', ':manpage:`mp(1)`', '<p><em", "'::\\n\\n @Γ\\\\∞${}', None, ('\\\\begin{sphinxVerbatim}[commandchars=\\\\\\\\\\\\{\\\\}]\\n' '@Γ\\\\PYGZbs{}∞\\\\PYGZdl{}\\\\PYGZob{}\\\\PYGZcb{}\\n' '\\\\end{sphinxVerbatim}'), ), ]) def test_inline_for_unicode_latex_engine(get_verifier,", "markup afterwards, these nodes may remain class ForgivingTranslator: def visit_pending_xref(self,", "remain class ForgivingTranslator: def visit_pending_xref(self, node): pass def depart_pending_xref(self, node):", "data', settings) document['file'] = 'dummy' return document return create @pytest.fixture", "world*.') assert not md.rawsource.endswith('*Good-bye world*.\\n') @pytest.mark.sphinx('dummy', testroot='keep_warnings') def test_keep_warnings_is_True(app, status,", "'TEXT']) assert_node(doctrees[0], refdoc='dummy', refdomain='', reftype='ref', reftarget='text', refexplicit=False, refwarn=False) @pytest.mark.sphinx('dummy', testroot='prolog')", "== 1 assert_node(doctrees[0], [addnodes.pending_xref, nodes.literal, 'text']) assert_node(doctrees[0], refdoc='dummy', refdomain='', reftype='ref',", "theme = app.builder.themes.get('manual') latex_translator = ForgivingLaTeXTranslator(document, app.builder, theme) latex_translator.first_document =", "re.escape(html_expected) + '$') if latex_expected: verify_re_latex(rst, re.escape(latex_expected) + '$') return", "notranslate\">' '<kbd class=\"kbd docutils literal notranslate\">M</kbd>' '-' '<kbd class=\"kbd docutils", "doctree = parse(text) assert_node(doctree[0], [nodes.paragraph, nodes.literal, \"a{bc\"]) # escaped braces", "import XRefRole from sphinx.testing.util import Struct, assert_node from sphinx.transforms import", "reftype='download', refexplicit=False, reftarget='sphinx.rst', refwarn=False) assert_node(doctree[0][0][0], classes=['xref', 'download']) # explicit text", "kbd role 'verify', ':kbd:`Alt+^`', ('<p><kbd class=\"kbd compound docutils literal notranslate\">'", "refdoc='dummy', refdomain='', reftype='ref', reftarget='target', refexplicit=True, refwarn=False) # bang doctrees, errors", "'\\\\index{RFC@\\\\spxentry{RFC}!RFC 2324\\\\#id1@\\\\spxentry{RFC 2324\\\\#id1}}' '\\\\sphinxhref{http://tools.ietf.org/html/rfc2324.html\\\\#id1}' '{\\\\sphinxstylestrong{RFC 2324\\\\#id1}}') ), ( # correct", "= ForgivingLaTeXTranslator(document, app.builder, theme) latex_translator.first_document = -1 # don't write", "'term\\n description', '<dl class=\"docutils\">\\n<dt>term</dt><dd>description</dd>\\n</dl>', None, ), ( # description list:", "parse(rst) KeyboardTransform(document).apply() html_translator = ForgivingHTMLTranslator(document, app.builder) document.walkabout(html_translator) html_translated = ''.join(html_translator.fragment).strip()", "doctree[0][4][0][0].astext() == 'Hello' @pytest.mark.sphinx('dummy', testroot='default_role') def test_default_role1(app, status, warning): app.builder.build_all()", "nodes.literal, \"a{bc\"]) # escaped braces text = ':samp:`a\\\\\\\\{b}c`' doctree =", "'+' '<kbd class=\"kbd docutils literal notranslate\">^</kbd>' '</kbd></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\sphinxkeyboard{\\\\sphinxupquote{Alt+\\\\textasciicircum{}}}'), ),", "rst return verify @pytest.fixture def verify_re_latex(app, parse): def verify(rst, latex_expected):", "text = ':download:`sphinx.rst`' doctree = parse(text) assert_node(doctree[0], [nodes.paragraph, addnodes.download_reference, nodes.literal,", "description list: with classifiers 'verify', 'term : class1 : class2\\n", "non-interpolation of dashes in option role 'verify_re', ':option:`--with-option`', ('<p><code( class=\"xref", "errors == [] # explicit doctrees, errors = role('ref', 'rawtext',", "[addnodes.pending_xref, nodes.literal, 'text']) assert_node(doctrees[0], refdoc='dummy', refdomain='', reftype='ref', reftarget='text', refexplicit=False, refwarn=False)", "sample`' doctree = parse(text) assert_node(doctree[0], [nodes.paragraph, nodes.literal, \"code sample\"]) def", "assert doctree[0][2][0][0].astext() == 'genindex' assert doctree[0][3].astext() == 'List B:' assert_node(doctree[0][4],", "role with anchor 'verify', ':pep:`8#id1`', ('<p><span class=\"target\" id=\"index-0\"></span><a class=\"pep reference", "# no ampersands in guilabel 'verify', ':guilabel:`Foo`', '<p><span class=\"guilabel\">Foo</span></p>', '\\\\sphinxAtStartPar\\n\\\\sphinxguilabel{Foo}',", "ForgivingTranslator): pass class ForgivingLaTeXTranslator(LaTeXTranslator, ForgivingTranslator): pass @pytest.fixture def verify_re_html(app, parse):", "msg['level'] == 1: msg.replace_self([]) return document return parse_ # since", "verbatim code fragments 'verify', '::\\n\\n @Γ\\\\∞${}', None, ('\\\\begin{sphinxVerbatim}[commandchars=\\\\\\\\\\\\{\\\\}]\\n' '@Γ\\\\PYGZbs{}∞\\\\PYGZdl{}\\\\PYGZob{}\\\\PYGZcb{}\\n' '\\\\end{sphinxVerbatim}'),", "+ '$') return verify_ @pytest.fixture def get_verifier(verify, verify_re): v =", "':menuselection:`a --> b`', ('<p><span class=\"menuselection\">a \\N{TRIANGULAR BULLET} b</span></p>'), '\\\\sphinxAtStartPar\\n\\\\sphinxmenuselection{a \\\\(\\\\rightarrow\\\\)", "[]) assert_node(doctrees[0], [nodes.literal, 'title <target>']) # refdomain doctrees, errors =", "<span class=\"pre\">sample</span></code></p>'), r'\\\\sphinxAtStartPar\\n\\\\sphinxcode{\\\\sphinxupquote{code sample}}', ), ( # interpolation of arrows", "( 'verify', r'4 backslashes \\\\\\\\', r'<p>4 backslashes \\\\</p>', None, ),", "@pytest.mark.parametrize('type,rst,html_expected,latex_expected', [ ( # in verbatim code fragments 'verify', '::\\n\\n", "nested braces text = ':samp:`a{{b}}c`' doctree = parse(text) assert_node(doctree[0], [nodes.paragraph,", "= role('ref', 'rawtext', 'title <target>', 5, inliner, {}, []) assert_node(doctrees[0],", "<https://www.google.com/~me/>`_', None, r'\\\\sphinxAtStartPar\\n\\\\sphinxhref{https://www.google.com/~me/}{test}.*', ), ( # description list: simple 'verify',", "node): pass class ForgivingHTMLTranslator(HTMLTranslator, ForgivingTranslator): pass class ForgivingLaTeXTranslator(LaTeXTranslator, ForgivingTranslator): pass", "confoverrides={'default_role': 'guilabel'}) def test_default_role2(app, status, warning): app.builder.build_all() # default-role directive", "= parse(text) assert_node(doctree[0], [nodes.paragraph, nodes.literal, \"a{b}c\"]) # no braces (whitespaces", "8}}') ), ( # pep role with anchor 'verify', ':pep:`8#id1`',", "'Hello' @pytest.mark.sphinx('dummy', testroot='default_role') def test_default_role1(app, status, warning): app.builder.build_all() # default-role:", "settings.smart_quotes = True settings.env = app.builder.env settings.env.temp_data['docname'] = 'dummy' settings.contentsname", "Lock`', '<p><kbd class=\"kbd docutils literal notranslate\">Caps Lock</kbd></p>', ('\\\\sphinxAtStartPar\\n' '\\\\sphinxkeyboard{\\\\sphinxupquote{Caps Lock}}'),", "8}}\\\\sphinxhref{http://www.python.org/dev/peps/pep-0008}' '{\\\\sphinxstylestrong{PEP 8}}') ), ( # pep role with anchor", "fragments 'verify', '::\\n\\n @Γ\\\\∞${}', None, ('\\\\begin{sphinxVerbatim}[commandchars=\\\\\\\\\\\\{\\\\}]\\n' '@Γ\\\\PYGZbs{}∞\\\\PYGZdl{}\\\\PYGZob{}\\\\PYGZcb{}\\n' '\\\\end{sphinxVerbatim}'), ), ])", "{}, []) assert_node(doctrees[0], [addnodes.pending_xref, nodes.literal, 'text']) assert_node(doctrees[0], refdoc='dummy', refdomain='test', reftype='doc',", "refexplicit=False, reftarget='sphinx.rst', refwarn=False) assert_node(doctree[0][0][0], classes=['xref', 'download']) # explicit text =", "refwarn=False) # lowercase role = XRefRole(lowercase=True) doctrees, errors = role('ref',", "( # kbd role 'verify', ':kbd:`-`', '<p><kbd class=\"kbd docutils literal", "verify_re_ @pytest.fixture def verify(verify_re_html, verify_re_latex): def verify_(rst, html_expected, latex_expected): if", "'<strong>PEP 8#id1</strong></a></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\index{Python Enhancement Proposals@\\\\spxentry{Python Enhancement Proposals}' '!PEP 8\\\\#id1@\\\\spxentry{PEP", "assert_node(doctree[0][4], nodes.bullet_list) assert_node(doctree[0][4][0][0], nodes.paragraph) assert doctree[0][4][0][0].astext() == 'Hello' @pytest.mark.sphinx('dummy', testroot='default_role')", "pass def depart_pending_xref(self, node): pass class ForgivingHTMLTranslator(HTMLTranslator, ForgivingTranslator): pass class", "@pytest.fixture def get_verifier(verify, verify_re): v = { 'verify': verify, 'verify_re':", "= 'dummy' settings.rfc_base_url = 'http://tools.ietf.org/html/' domain_context = sphinx_domains(settings.env) domain_context.enable() yield", "(description list): multiple terms 'verify', '.. glossary::\\n\\n term1\\n term2\\n description',", "pass class ForgivingLaTeXTranslator(LaTeXTranslator, ForgivingTranslator): pass @pytest.fixture def verify_re_html(app, parse): def", "in option role 'verify_re', ':option:`--with-option`', ('<p><code( class=\"xref std std-option docutils", "assert_node(doctree[0], nodes.section) assert len(doctree[0]) == 5 assert doctree[0][1].astext() == 'List", "( # correct escaping in normal mode 'verify', 'Γ\\\\\\\\∞$', None,", "fragments 'verify', '::\\n\\n @Γ\\\\∞${}', None, ('\\\\begin{sphinxVerbatim}[commandchars=\\\\\\\\\\\\{\\\\}]\\n' '@Γ\\\\PYGZbs{}\\\\(\\\\infty\\\\)\\\\PYGZdl{}\\\\PYGZob{}\\\\PYGZcb{}\\n' '\\\\end{sphinxVerbatim}'), ), (", "'<kbd class=\"kbd docutils literal notranslate\">Alt</kbd>' '+' '<kbd class=\"kbd docutils literal", "r'\\\\sphinxcode{\\\\sphinxupquote{\\\\sphinxhyphen{}\\\\sphinxhyphen{}with\\\\sphinxhyphen{}option}}$'), ), ( # verify smarty-pants quotes 'verify', '\"John\"', '<p>“John”</p>',", "[nodes.paragraph, nodes.literal, \"a{bc\"]) # escaped braces text = ':samp:`a\\\\\\\\{b}c`' doctree", "[ ( # pep role 'verify', ':pep:`8`', ('<p><span class=\"target\" id=\"index-0\"></span><a", "class1 : class2\\n description', ('<dl class=\"docutils\">\\n<dt>term<span class=\"classifier\">class1</span>' '<span class=\"classifier\">class2</span></dt><dd>description</dd>\\n</dl>'), None,", "reftype='ref', reftarget='text', refexplicit=False, refwarn=False) # lowercase role = XRefRole(lowercase=True) doctrees,", "LaTeXWriter @pytest.fixture def settings(app): texescape.init() # otherwise done by the", "or above is required') def test_inline_docutils16(get_verifier, type, rst, html_expected, latex_expected):", "app.builder.build_all() doctree = app.env.get_doctree('index') assert_node(doctree[0], nodes.section) assert len(doctree[0]) == 2", "-&&- &Bar`', ('<p><span class=\"guilabel\"><span class=\"accelerator\">F</span>oo ' '-&amp;- <span class=\"accelerator\">B</span>ar</span></p>'), ('\\\\sphinxAtStartPar\\n'", "[]) assert len(doctrees) == 1 assert_node(doctrees[0], [addnodes.pending_xref, nodes.literal, 'text']) assert_node(doctrees[0],", "term\">¶</a></dt>' '<dt id=\"term-term2\">term2<a class=\"headerlink\" href=\"#term-term2\"' ' title=\"Permalink to this term\">¶</a></dt>'", "'term : class1 : class2\\n description', ('<dl class=\"docutils\">\\n<dt>term<span class=\"classifier\">class1</span>' '<span", "':samp:`a{bc`' doctree = parse(text) assert_node(doctree[0], [nodes.paragraph, nodes.literal, \"a{bc\"]) # escaped", "verify_re_(rst, html_expected, latex_expected): if html_expected: verify_re_html(rst, html_expected) if latex_expected: verify_re_latex(rst,", "= role('ref', 'rawtext', 'TEXT', 5, inliner, {}, []) assert_node(doctrees[0], [addnodes.pending_xref,", "= new_document() document.reporter.get_source_and_line = lambda line=1: ('dummy.rst', line) return Struct(document=document,", "r'\\sphinxguilabel{\\sphinxaccelerator{F}oo \\sphinxhyphen{}\\&\\sphinxhyphen{} \\sphinxaccelerator{B}ar}'), ), ( # no ampersands in guilabel", "), ]) def test_inline_for_unicode_latex_engine(get_verifier, type, rst, html_expected, latex_expected): verifier =", "'.. glossary::\\n\\n term1\\n term2\\n description', ('<dl class=\"glossary docutils\">\\n' '<dt id=\"term-term1\">term1<a", "M\\\\sphinxhyphen{}s}}'), ), ( # kbd role 'verify', ':kbd:`-`', '<p><kbd class=\"kbd", "[nodes.paragraph, addnodes.download_reference, nodes.literal, \"reftitle\"]) assert_node(doctree[0][0], refdoc='dummy', refdomain='', reftype='download', refexplicit=True, reftarget='sphinx.rst',", "literal notranslate\">s</kbd>' '</kbd></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\sphinxkeyboard{\\\\sphinxupquote{M\\\\sphinxhyphen{}x M\\\\sphinxhyphen{}s}}'), ), ( # kbd", "= app.env.get_doctree('restructuredtext') md = app.env.get_doctree('markdown') # rst_prolog assert_node(rst[0], nodes.paragraph) assert_node(rst[0][0],", "optparser.get_default_values() settings.smart_quotes = True settings.env = app.builder.env settings.env.temp_data['docname'] = 'dummy'", "= 'dummy' settings.contentsname = 'dummy' settings.rfc_base_url = 'http://tools.ietf.org/html/' domain_context =", "smarty-pants quotes 'verify', '\"John\"', '<p>“John”</p>', \"\\\\sphinxAtStartPar\\n“John”\", ), ( # ...", "), ( # non-interpolation of dashes in option role 'verify_re',", "document return create @pytest.fixture def inliner(new_document): document = new_document() document.reporter.get_source_and_line", "app.builder.themes.get('manual') latex_translator = ForgivingLaTeXTranslator(document, app.builder, theme) latex_translator.first_document = -1 #", "html_translated), 'from ' + rst return verify @pytest.fixture def verify_re_latex(app,", "parse(text) assert_node(doctree[0], [nodes.paragraph, nodes.literal, \"a{bc\"]) # escaped braces text =", "HTMLTranslator, HTMLWriter from sphinx.writers.latex import LaTeXTranslator, LaTeXWriter @pytest.fixture def settings(app):", "not in literal text 'verify', '``\"John\"``', ('<p><code class=\"docutils literal notranslate\"><span", "assert_node(doctree[0], nodes.section) assert_node(doctree[0][1], nodes.paragraph) assert_node(doctree[0][1][0], nodes.title_reference) assert_node(doctree[0][1][1], nodes.Text) @pytest.mark.sphinx('dummy', testroot='default_role',", "'verify', ':rfc:`2324#id1`', ('<p><span class=\"target\" id=\"index-0\"></span><a class=\"rfc reference external\" ' 'href=\"http://tools.ietf.org/html/rfc2324.html#id1\">'", "def create(): document = utils.new_document('test data', settings) document['file'] = 'dummy'", "Lock}}'), ), ( # non-interpolation of dashes in option role", "docutils import frontend, nodes, utils from docutils.parsers.rst import Parser as", "sphinx import addnodes from sphinx.builders.html.transforms import KeyboardTransform from sphinx.builders.latex import", "def verify(verify_re_html, verify_re_latex): def verify_(rst, html_expected, latex_expected): if html_expected: verify_re_html(rst,", "sphinx_domains(settings.env) domain_context.enable() yield settings domain_context.disable() @pytest.fixture def new_document(settings): def create():", "test_samp_role(parse): # no braces text = ':samp:`a{b}c`' doctree = parse(text)", "'rawtext', 'TEXT', 5, inliner, {}, []) assert_node(doctrees[0], [addnodes.pending_xref, nodes.literal, 'TEXT'])", "role('ref', 'rawtext', 'text', 5, inliner, {}, []) assert len(doctrees) ==", "pep role with anchor 'verify', ':pep:`8#id1`', ('<p><span class=\"target\" id=\"index-0\"></span><a class=\"pep", "not resolving the markup afterwards, these nodes may remain class", "texescape.init() # otherwise done by the latex builder optparser =", "'<dl class=\"docutils\">\\n<dt>term</dt><dd>description</dd>\\n</dl>', None, ), ( # description list: with classifiers", "\"code sample\"]) def test_download_role(parse): # implicit text = ':download:`sphinx.rst`' doctree", "def test_compact_refonly_bullet_list(app, status, warning): app.builder.build_all() doctree = app.env.get_doctree('index') assert_node(doctree[0], nodes.section)", "# in URIs 'verify_re', '`test <https://www.google.com/~me/>`_', None, r'\\\\sphinxAtStartPar\\n\\\\sphinxhref{https://www.google.com/~me/}{test}.*', ), (", "refexplicit=False, refwarn=False) # lowercase role = XRefRole(lowercase=True) doctrees, errors =", "refwarn=False) assert_node(doctree[0][0][0], classes=['xref', 'download']) # explicit text = ':download:`reftitle <sphinx.rst>`'", "verify_ @pytest.fixture def get_verifier(verify, verify_re): v = { 'verify': verify,", "# description list: with classifiers 'verify', 'term : class1 :", "docutils literal notranslate\">' '<kbd class=\"kbd docutils literal notranslate\">M</kbd>' '-' '<kbd", "verifier(rst, html_expected, latex_expected) def test_samp_role(parse): # no braces text =", "role = XRefRole() # implicit doctrees, errors = role('ref', 'rawtext',", "doctrees, errors = role('test:doc', 'rawtext', 'text', 5, inliner, {}, [])", "errors = role('test:doc', 'rawtext', 'text', 5, inliner, {}, []) assert_node(doctrees[0],", "'verify', '::\\n\\n @Γ\\\\∞${}', None, ('\\\\begin{sphinxVerbatim}[commandchars=\\\\\\\\\\\\{\\\\}]\\n' '@Γ\\\\PYGZbs{}∞\\\\PYGZdl{}\\\\PYGZob{}\\\\PYGZcb{}\\n' '\\\\end{sphinxVerbatim}'), ), ]) def", "assert_node(doctrees[0], [addnodes.pending_xref, nodes.literal, 'text']) assert_node(doctrees[0], refdoc='dummy', refdomain='test', reftype='doc', reftarget='text', refexplicit=False,", "('<p><kbd class=\"kbd compound docutils literal notranslate\">' '<kbd class=\"kbd docutils literal", "if msg['level'] == 1: msg.replace_self([]) return document return parse_ #", "' 'href=\"http://www.python.org/dev/peps/pep-0008\"><strong>PEP 8</strong></a></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\index{Python Enhancement Proposals@\\\\spxentry{Python Enhancement Proposals}' '!PEP", "[]) assert_node(doctrees[0], [addnodes.pending_xref, nodes.literal, 'TEXT']) assert_node(doctrees[0], refdoc='dummy', refdomain='', reftype='ref', reftarget='text',", "= app.env.get_doctree('index') assert_node(doctree[0], nodes.section) assert len(doctree[0]) == 1 @pytest.mark.sphinx('dummy', testroot='refonly_bullet_list')", "':guilabel:`Foo`', '<p><span class=\"guilabel\">Foo</span></p>', '\\\\sphinxAtStartPar\\n\\\\sphinxguilabel{Foo}', ), ( # kbd role 'verify',", "parser assert not md.rawsource.startswith('*Hello world*.') assert not md.rawsource.endswith('*Good-bye world*.\\n') @pytest.mark.sphinx('dummy',", "assert len(doctree[0]) == 2 assert_node(doctree[0][1], nodes.system_message) @pytest.mark.sphinx('dummy', testroot='keep_warnings', confoverrides={'keep_warnings': False})", "# escaped braces text = ':samp:`a\\\\\\\\{b}c`' doctree = parse(text) assert_node(doctree[0],", "('\\\\sphinxAtStartPar\\n' '\\\\sphinxkeyboard{\\\\sphinxupquote{Alt+\\\\textasciicircum{}}}'), ), ( # kbd role 'verify', ':kbd:`M-x M-s`',", "nodes.paragraph) assert_node(doctree[0][1][0], addnodes.index) assert_node(doctree[0][1][1], nodes.target) assert_node(doctree[0][1][2], nodes.reference, classes=[\"pep\"]) # no", "get_verifier(type) verifier(rst, html_expected, latex_expected) @pytest.mark.parametrize('type,rst,html_expected,latex_expected', [ ( 'verify', r'4 backslashes", "external\" ' 'href=\"http://tools.ietf.org/html/rfc2324.html\"><strong>RFC 2324</strong></a></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\index{RFC@\\\\spxentry{RFC}!RFC 2324@\\\\spxentry{RFC 2324}}' '\\\\sphinxhref{http://tools.ietf.org/html/rfc2324.html}' '{\\\\sphinxstylestrong{RFC", "kbd role 'verify', ':kbd:`Control+X`', ('<p><kbd class=\"kbd compound docutils literal notranslate\">'", "get @pytest.mark.parametrize('type,rst,html_expected,latex_expected', [ ( # pep role 'verify', ':pep:`8`', ('<p><span", "'text', 5, inliner, {}, []) assert_node(doctrees[0], [addnodes.pending_xref, nodes.literal, 'text']) assert_node(doctrees[0],", "def depart_pending_xref(self, node): pass class ForgivingHTMLTranslator(HTMLTranslator, ForgivingTranslator): pass class ForgivingLaTeXTranslator(LaTeXTranslator,", "refdomain='', reftype='download', refexplicit=False, reftarget='sphinx.rst', refwarn=False) assert_node(doctree[0][0][0], classes=['xref', 'download']) # explicit", "required') def test_inline_docutils16(get_verifier, type, rst, html_expected, latex_expected): verifier = get_verifier(type)", "app.builder, theme) latex_translator.first_document = -1 # don't write \\begin{document} document.walkabout(latex_translator)", "may remain class ForgivingTranslator: def visit_pending_xref(self, node): pass def depart_pending_xref(self,", "= ':samp:`code sample`' doctree = parse(text) assert_node(doctree[0], [nodes.paragraph, nodes.literal, \"code", "'\"John\"', '<p>“John”</p>', \"\\\\sphinxAtStartPar\\n“John”\", ), ( # ... but not in", "2324}}' '\\\\sphinxhref{http://tools.ietf.org/html/rfc2324.html}' '{\\\\sphinxstylestrong{RFC 2324}}') ), ( # rfc role with", "assert_node(rst[-1][-1], nodes.paragraph) assert_node(rst[-1][-1][0], nodes.emphasis) assert_node(rst[-1][-1][0][0], nodes.Text) assert rst[-1][-1][0][0] == 'Good-bye", "class=\"accelerator\">F</span>oo ' '-&amp;- <span class=\"accelerator\">B</span>ar</span></p>'), ('\\\\sphinxAtStartPar\\n' r'\\sphinxmenuselection{\\sphinxaccelerator{F}oo \\sphinxhyphen{}' r'\\&\\sphinxhyphen{} \\sphinxaccelerator{B}ar}'),", "':kbd:`M-x M-s`', ('<p><kbd class=\"kbd compound docutils literal notranslate\">' '<kbd class=\"kbd", "whitespace 'verify_re', '``code sample``', ('<p><code class=\"(samp )?docutils literal notranslate\"><span class=\"pre\">'", "('<p><span class=\"target\" id=\"index-0\"></span><a class=\"pep reference external\" ' 'href=\"http://www.python.org/dev/peps/pep-0008\"><strong>PEP 8</strong></a></p>'), ('\\\\sphinxAtStartPar\\n'", "# glossary (description list): multiple terms 'verify', '.. glossary::\\n\\n term1\\n", "but not in literal text 'verify', '``\"John\"``', ('<p><code class=\"docutils literal", "test_markup ~~~~~~~~~~~ Test various Sphinx-specific markup extensions. :copyright: Copyright 2007-2021", "parser = RstParser() parser.parse(rst, document) SphinxSmartQuotes(document, startnode=None).apply() for msg in", "assert doctree[0][1].astext() == 'List A:' assert_node(doctree[0][2], nodes.bullet_list) assert_node(doctree[0][2][0][0], addnodes.compact_paragraph) assert", "latex builder optparser = frontend.OptionParser( components=(RstParser, HTMLWriter, LaTeXWriter)) settings =", "text = ':samp:`code sample`' doctree = parse(text) assert_node(doctree[0], [nodes.paragraph, nodes.literal,", "option role 'verify_re', ':option:`--with-option`', ('<p><code( class=\"xref std std-option docutils literal", "# interpolation of arrows in menuselection 'verify', ':menuselection:`a --> b`',", "(whitespaces are keeped as is) text = ':samp:`code sample`' doctree", "Lock</kbd></p>', ('\\\\sphinxAtStartPar\\n' '\\\\sphinxkeyboard{\\\\sphinxupquote{Caps Lock}}'), ), ( # non-interpolation of dashes", "assert_node(doctree[0][1][2], nodes.reference, classes=[\"pep\"]) # default_role changes the default behavior doctree", "inline roles 'verify', ':manpage:`mp(1)`', '<p><em class=\"manpage\">mp(1)</em></p>', '\\\\sphinxAtStartPar\\n\\\\sphinxstyleliteralemphasis{\\\\sphinxupquote{mp(1)}}', ), ( #", "LaTeXTranslator, LaTeXWriter @pytest.fixture def settings(app): texescape.init() # otherwise done by", "app.env.get_doctree('index') assert_node(doctree[0], nodes.section) assert len(doctree[0]) == 1 @pytest.mark.sphinx('dummy', testroot='refonly_bullet_list') def", "reftarget='sphinx.rst', refwarn=False) assert_node(doctree[0][0][0], classes=['xref', 'download']) def test_XRefRole(inliner): role = XRefRole()", "), ( # interpolation of ampersands in menuselection 'verify', ':menuselection:`&Foo", "('\\\\sphinxAtStartPar\\n' '\\\\index{RFC@\\\\spxentry{RFC}!RFC 2324@\\\\spxentry{RFC 2324}}' '\\\\sphinxhref{http://tools.ietf.org/html/rfc2324.html}' '{\\\\sphinxstylestrong{RFC 2324}}') ), ( #", "'verify', 'term : class1 : class2\\n description', ('<dl class=\"docutils\">\\n<dt>term<span class=\"classifier\">class1</span>'", ": class2\\n description', ('<dl class=\"docutils\">\\n<dt>term<span class=\"classifier\">class1</span>' '<span class=\"classifier\">class2</span></dt><dd>description</dd>\\n</dl>'), None, ),", "'<kbd class=\"kbd docutils literal notranslate\">Control</kbd>' '+' '<kbd class=\"kbd docutils literal", "nodes, utils from docutils.parsers.rst import Parser as RstParser from sphinx", "settings) document['file'] = 'dummy' return document return create @pytest.fixture def", "# otherwise done by the latex builder optparser = frontend.OptionParser(", "( # interpolation of arrows in menuselection 'verify', ':menuselection:`a -->", "'$') return verify_ @pytest.fixture def get_verifier(verify, verify_re): v = {", "term\">¶</a></dt>' '<dd>description</dd>\\n</dl>'), None, ), ]) def test_inline(get_verifier, type, rst, html_expected,", "app.builder.build_all() # default-role: pep doctree = app.env.get_doctree('index') assert_node(doctree[0], nodes.section) assert_node(doctree[0][1],", "inliner, {}, []) assert_node(doctrees[0], [addnodes.pending_xref, nodes.literal, 'text()']) assert_node(doctrees[0], refdoc='dummy', refdomain='',", "verify(rst, latex_expected): document = parse(rst) app.builder = LaTeXBuilder(app) app.builder.set_environment(app.env) app.builder.init()", "refdomain='test', reftype='doc', reftarget='text', refexplicit=False, refwarn=False) # fix_parens role = XRefRole(fix_parens=True)", "role 'verify', ':kbd:`space`', '<p><kbd class=\"kbd docutils literal notranslate\">space</kbd></p>', '\\\\sphinxAtStartPar\\n\\\\sphinxkeyboard{\\\\sphinxupquote{space}}', ),", "'from ' + rst return verify @pytest.fixture def verify_re_latex(app, parse):", "literal notranslate\">Caps Lock</kbd></p>', ('\\\\sphinxAtStartPar\\n' '\\\\sphinxkeyboard{\\\\sphinxupquote{Caps Lock}}'), ), ( # non-interpolation", "':rfc:`2324`', ('<p><span class=\"target\" id=\"index-0\"></span><a class=\"rfc reference external\" ' 'href=\"http://tools.ietf.org/html/rfc2324.html\"><strong>RFC 2324</strong></a></p>'),", "are keeped as is) text = ':samp:`code sample`' doctree =", "== [] # explicit doctrees, errors = role('ref', 'rawtext', 'title", "# rst_prolog assert_node(rst[0], nodes.paragraph) assert_node(rst[0][0], nodes.emphasis) assert_node(rst[0][0][0], nodes.Text) assert rst[0][0][0]", "assert_node(doctrees[0], [addnodes.pending_xref, nodes.literal, 'text']) assert_node(doctrees[0], refdoc='dummy', refdomain='', reftype='ref', reftarget='text', refexplicit=False,", "html_expected: verify_re_html(rst, html_expected) if latex_expected: verify_re_latex(rst, latex_expected) return verify_re_ @pytest.fixture", "correct escaping in normal mode 'verify', 'Γ\\\\\\\\∞$', None, '\\\\sphinxAtStartPar\\nΓ\\\\textbackslash{}\\\\(\\\\infty\\\\)\\\\$', ),", "don't write \\begin{document} document.walkabout(latex_translator) latex_translated = ''.join(latex_translator.body).strip() assert re.match(latex_expected, latex_translated),", "parse(text) assert_node(doctree[0], [nodes.paragraph, nodes.literal, (\"a\", [nodes.emphasis, \"{b\"], \"}c\")]) # half-opened", "'`test <https://www.google.com/~me/>`_', None, r'\\\\sphinxAtStartPar\\n\\\\sphinxhref{https://www.google.com/~me/}{test}.*', ), ( # description list: simple", "assert_node(doctree[0], [nodes.paragraph, nodes.literal, \"code sample\"]) def test_download_role(parse): # implicit text", "role = XRefRole(fix_parens=True) doctrees, errors = role('ref', 'rawtext', 'text()', 5,", "return document return parse_ # since we're not resolving the", "assert len(doctree[0]) == 5 assert doctree[0][1].astext() == 'List A:' assert_node(doctree[0][2],", "'href=\"http://www.python.org/dev/peps/pep-0008\"><strong>PEP 8</strong></a></p>'), ('\\\\sphinxAtStartPar\\n' '\\\\index{Python Enhancement Proposals@\\\\spxentry{Python Enhancement Proposals}' '!PEP 8@\\\\spxentry{PEP", "refdoc='dummy', refdomain='', reftype='ref', reftarget='text', refexplicit=False, refwarn=False) # lowercase role =", "import re import pytest from docutils import frontend, nodes, utils", "std-option docutils literal notranslate\")?>' '<span class=\"pre\">--with-option</span></code></p>$'), (r'\\\\sphinxAtStartPar\\n' r'\\\\sphinxcode{\\\\sphinxupquote{\\\\sphinxhyphen{}\\\\sphinxhyphen{}with\\\\sphinxhyphen{}option}}$'), ), (", "def verify(rst, latex_expected): document = parse(rst) app.builder = LaTeXBuilder(app) app.builder.set_environment(app.env)", "nodes.literal, (\"a\", [nodes.emphasis, \"{b\"], \"}c\")]) # half-opened braces text =", "this term\">¶</a></dt>' '<dd>description</dd>\\n</dl>'), None, ), ]) def test_inline(get_verifier, type, rst," ]
[ "string components that are duplicates of strings in the actual", "# that container is gone, try again curObjRef = None", "hold objects that we should start traversals from often and", "continue try: cLen = len(container) except Exception, e: # this", "%s)' % ( name, itype(container), percent, minutes, idx2id2len[self._index][objId], fastRepr(container, maxLen=CheckContainers.ReprItems)))", "for container in self._leakDetector.getContainerByIdGen(id): yield None except: # reference is", "leakContainer(task=None): base = getBase() if not hasattr(base, 'leakContainer'): base.leakContainer =", "True: # yield up here instead of at the end,", "None return container def getContainerGen(self, getInstance=False): # try to get", "self._ldde = self._leakDetector._getDestroyEvent() self.accept(self._ldde, self._handleLDDestroy) ContainerLeakDetector.addPrivateObj(self.__dict__) def destroy(self): self.ignore(self._ldde) self._leakDetector", "indirection # if getInstance is True, will return instance instead", "name, leakDetector): Job.__init__(self, name) self._leakDetector = leakDetector self._id2ref = self._leakDetector._id2ref", "* 1.5: 1 1.5 2.3 3.4 5.1 7.6 11.4 17.1", "try: for curObj in curObjRef.getContainerGen(): yield None except: self.notify.debug('lost current", "self._id2discoveredStartRef: existingRef = self._id2discoveredStartRef[objId] if type(existingRef) not in (types.IntType, types.LongType):", "leakDetector): Job.__init__(self, name) self._leakDetector = leakDetector self.notify = self._leakDetector.notify ContainerLeakDetector.addPrivateObj(self.__dict__)", "indirection in indirections: yield None if not indirection.isDictKey(): # build", "indirection.getString() else: curObj = self._getContainerByEval(evalStr, curObj=curObj) if curObj is None:", "= evalStr self.dictKey = NoDictKey # is the dictKey a", "of the larger set by 2/3 minLen *= 3. workingListSelector", "except: pass else: try: index = -1 attrs = []", "finished(self): if self._doneCallback: self._doneCallback(self) class PruneObjectRefs(Job): \"\"\" Job to destroy", "in idx2id2len[self._index-4] and objId in idx2id2len[self._index-5]): # if size has", "in self._leakDetector.getContainerNameByIdGen( id, getInstance=getInstance): yield None except: pass else: print", "NoDictKey def _getNonWeakDictKey(self): if not self._isWeakRef: return self.dictKey else: key", "e: # this is OK because we are yielding during", "no longer a container, it is now %s (%s)' %", "prevent cycles in the references (i.e. base.loader.base) for goesThrough in", "False # if we haven't picked the next ref, check", "else: # prevent infinite recursion in built-in containers related to", "container in _id2baseStartRef[id].getContainerGen(): yield None except: # reference is invalid,", "# yield up here instead of at the end, since", "are storing a reference to this object, don't store a", "current container, ref.getContainerGen() failed') # that container is gone, try", "we're not storing a reference to the actual object, #", "when leak detector is about to be destroyed return 'cldDestroy-%s'", "% self._serialNum @classmethod def addPrivateObj(cls, obj): cls.PrivateIds.add(id(obj)) @classmethod def removePrivateObj(cls,", "(existingRef.getNumIndirections() >= ref.getNumIndirections()): # the ref that we already have", "'leakContainer-%s' % serialNum()) if task: return task.done leakContainer() def _createTaskLeak():", "set up the base containers, the ones that hold most", "1 3 7 15 31 63 127 255 511 1023", "of the current traversal curObjRef = None while True: #", "times but eventually it will discover every object. Checks container", "# main dict of id(container)->containerRef self._id2ref = {} # storage", "= None attr = None keys = curObj.keys() # we", "ObjectRef(Indirection(evalStr='base.__dict__'), id(base.__dict__)) self._id2baseStartRef[id(base.__dict__)] = ref for i in self._addContainerGen(base.__dict__, ref):", "in self.goesThroughGen(obj=obj, objId=objId): pass return goesThrough def _getContainerByEval(self, evalStr, curObj=None):", "None: # choose an object to start a traversal from", "set of start refs every time we start a new", "element pass if not goesThrough: objRef = ObjectRef(Indirection(evalStr='.__dict__'), id(child), parentObjRef)", "a candidate if curObjRef is None: notDeadEnd = not self._isDeadEnd(attr,", "validity by asking for each container \"\"\" def __init__(self, name,", "'[key]', etc.) \"\"\" notify = directNotify.newCategory(\"ObjectRef\") class FailedEval(Exception): pass def", "self._leakDetector = leakDetector self.notify = self._leakDetector.notify ContainerLeakDetector.addPrivateObj(self.__dict__) def destroy(self): ContainerLeakDetector.removePrivateObj(self.__dict__)", "a # of times that is # proportional to their", "return Job.Priorities.High def run(self): ids = self._leakDetector.getContainerIds() try: for id", "FPTObjsOfType(Job): def __init__(self, name, leakDetector, otn, doneCallback=None): Job.__init__(self, name) self._leakDetector", "self._leakDetector.getContainerNameById(objId) if idx2id2len[self._index-1][objId] != 0: percent = 100. * (float(diff)", "ind in other._indirections: self._indirections.append(ind) # make sure we're not storing", "on each set based on how many refs it contains", "the iteration self.notify.debug('could not index into %s with key %s'", "the indirections don't go away on us indirections = self._indirections", "indirections don't get destroyed while we're using them for ind", "= safeRepr(dictKey) useEval = False try: keyEval = eval(keyRepr) useEval", "base containers, the ones that hold most objects ref =", "Exception, e: print 'CheckContainers job caught exception: %s' % e", "instance dict, change our syntax from ['key'] to .key if", "object exploration algorithm, including objects that exist # just to", "\"\"\" ReprItems = 5 def __init__(self, name, leakDetector, index): Job.__init__(self,", "self._leakDetector.removeContainerById(objId) continue self._leakDetector._index2containerId2len[self._index][objId] = cLen # compare the current len", "usage, scene graph size, # framerate, etc. See LeakDetectors.py if", "a weak reference? self._isWeakRef = False self._refCount = 0 if", "curObj dictionary curObj = indirection.dereferenceDictKey(curObj) evalStr = '' yield None", "def getContainerByIdGen(self, id, **kwArgs): # return a generator to look", "tuples as keys since they can't be weakref'd, and use", "sure our indirections don't get destroyed while we're using them", "a string to be eval'd evalStr += indirection.getString() else: curObj", "88 143 232 # * 2.: 1 3 7 15", "in this reference, # this isn't perfect, for example if", "on how many refs it contains baseLen = len(self._baseStartRefWorkingList.source) discLen", "in indirections: yield None indirection.release() yield str def getFinalIndirectionStr(self): prevIndirection", "already have is more concise than the new ref return", "while True: yield Job.Sleep def getPathsToContainers(self, name, ot, doneCallback=None): j", "self._indirections[-1].getString(prevIndirection=prevIndirection) def __repr__(self): for result in self.getEvalStrGen(): pass return result", "self._id2ref: storedItem = objId self._id2discoveredStartRef[objId] = storedItem def run(self): try:", "is None: notDeadEnd = not self._isDeadEnd(attr, key) if hasLength or", "= ObjectRef(Indirection(evalStr='[%s]' % index), id(curObj[index]), parentObjRef) yield None if hasLength:", "this eval is not based off of curObj, use the", "the next ref, check if this one is a candidate", "if __dev__: raise yield Job.Done class ContainerLeakDetector(Job): \"\"\" Low-priority Python", "\"\"\" notify = directNotify.newCategory(\"ContainerLeakDetector\") # set of containers that should", "yield None except: # ref is invalid self.notify.debug('invalid startRef, stored", "to the # definitive ref sets self._baseStartRefWorkingList = ScratchPad(refGen=nullGen(), source=self._id2baseStartRef)", "notDeadEnd: self._addDiscoveredStartRef(child, objRef) curObjRef = objRef continue if type(curObj) is", "self._refCount -= 1 if self._refCount == 0: self.destroy() def isDictKey(self):", "1 for key in keys: yield None numKeysLeft -= 1", "destroy any container refs that are no longer valid. Checks", "ids involved in this reference, # this isn't perfect, for", "involved in this reference, # this isn't perfect, for example", "= None): Job.__init__(self, name) self._serialNum = serialNum() self._findContainersJob = None", "ContainerLeakDetector.PrivateIds: return True # prevent crashes in objects that define", "crashes in objects that define __cmp__ and don't handle strings", "yield None try: for container in self._leakDetector.getContainerByIdGen(id): yield None except:", "goesThrough: objRef = ObjectRef(Indirection(evalStr='[%s]' % index), id(curObj[index]), parentObjRef) yield None", "self._leakDetector.notify self._index = index ContainerLeakDetector.addPrivateObj(self.__dict__) def destroy(self): ContainerLeakDetector.removePrivateObj(self.__dict__) Job.destroy(self) def", "# are we building off of an existing ref? if", "in self._addContainerGen(attr, objRef): yield None if notDeadEnd: self._addDiscoveredStartRef(attr, objRef) if", "getContainerGen(self, getInstance=False): # try to get a handle on the", "if len(startRefWorkingList.source) == 0: # ref set is empty, choose", "indirection.release() yield str def getFinalIndirectionStr(self): prevIndirection = None if len(self._indirections)", "eventually it will discover every object. Checks container sizes at", "if prevIndirection is not None and prevIndirection.evalStr is not None:", "traversal from try: startRefWorkingList = workingListSelector.next() except StopIteration: # do", "this is a dictionary lookup, pass dictKey instead of evalStr", "for goesThrough in parentObjRef.goesThroughGen(child): # don't yield, container might lose", "def getPathsToContainersNamed(self, name, on, doneCallback=None): j = FPTObjsNamed(name, self, on,", "task=None): self._index2delay[len(self._index2containerId2len)] = self._nextCheckDelay self._checkContainersJob = CheckContainers( '%s-checkForLeaks' % self.getJobName(),", "self._id2ref: for existingRepr in self._id2ref[contId].getEvalStrGen(): yield None for newRepr in", "# this eval is not based off of curObj, use", "yield None except: # TODO self.notify.debug('caught exception in getContainerByIdGen (1)')", "None if hasLength: for i in self._addContainerGen(attr, objRef): yield None", "container>' def removeContainerById(self, id): if id in self._id2ref: self._id2ref[id].destroy() del", "types.IntType, types.LongType, types.NoneType, types.NotImplementedType, types.TypeType, types.CodeType, types.FunctionType, types.StringType, types.UnicodeType, types.TupleType):", "including objects that exist # just to measure things such", "dictKey a weak reference? self._isWeakRef = False self._refCount = 0", "# storage for results of check-container job self._index2containerId2len = {}", "by eval'ing and looking things # up in dictionaries, depending", "except: pass else: print 'GPTC(' + self._otn + '):' +", "for each container \"\"\" def __init__(self, name, leakDetector): Job.__init__(self, name)", "run(self): try: ids = self._leakDetector.getContainerIds() for id in ids: yield", "return hasattr(obj, '__len__') def _addContainerGen(self, cont, objRef): contId = id(cont)", "Checks validity by asking for each container \"\"\" def __init__(self,", "pass except Exception, e: print 'CheckContainers job caught exception: %s'", "shorter than what we already have, # put it in", "we already have is more concise than the new ref", "components that are duplicates of strings in the actual system", "workingListSelector = flywheel([self._baseStartRefWorkingList, self._discoveredStartRefWorkingList], [baseLen/minLen, discLen/minLen]) yield None continue #", "yield None if objId in idx2id2len[self._index-1]: diff = idx2id2len[self._index][objId] -", "None: # eval('curObj.foo.bar.someDict') evalStr = 'curObj%s' % evalStr else: #", "the object in _id2ref? sometimes we do that # to", "def __repr__(self): return self.getString() class ObjectRef: \"\"\" stores a reference", "self._nextCheckDelay = self._nextCheckDelay * self._checkDelayScale def _checkForLeaks(self, task=None): self._index2delay[len(self._index2containerId2len)] =", "== '.__dict__': str = str[:-lenDict] for indirection in indirections: yield", "the ones that hold most objects ref = ObjectRef(Indirection(evalStr='__builtin__.__dict__'), id(__builtin__.__dict__))", "# just to measure things such as C++ memory usage,", "hit a dead end, start over from another container curObjRef", "asking for each container \"\"\" def __init__(self, name, leakDetector): Job.__init__(self,", "of evalStr self.evalStr = evalStr self.dictKey = NoDictKey # is", "'FPTObjsOfType job caught exception: %s' % e if __dev__: raise", "types.TypeType, types.CodeType, types.FunctionType, types.StringType, types.UnicodeType, types.TupleType): return True # if", "def getContainerNameById(self, id): if id in self._id2ref: return repr(self._id2ref[id]) return", "self._addContainerGen(attr, objRef): yield None if notDeadEnd: self._addDiscoveredStartRef(attr, objRef) if curObjRef", "idx2id2len[self._index-5][objId] if diff > 0 and diff2 > 0 and", "remove it self._leakDetector.removeContainerById(id) _id2baseStartRef = self._leakDetector._findContainersJob._id2baseStartRef ids = _id2baseStartRef.keys() for", "dict key>' return key def dereferenceDictKey(self, parentDict): # look ourselves", "key = random.choice(base.leakContainer.keys()) ContainerLeakDetector.notify.debug( 'removing reference to leakContainer key %s", "empty (__builtin__ etc.) continue # do we need to go", "yield None except: pass else: if hasattr(container, '__class__'): cName =", "pass dictKey instead of evalStr self.evalStr = evalStr self.dictKey =", "= weakref.ref(dictKey) self._isWeakRef = True except TypeError, e: ContainerLeakDetector.notify.debug('could not", "dead end, start over from another container curObjRef = None", "# make sure our indirections don't get destroyed while we're", "def getPriority(self): return Job.Priorities.High def run(self): ids = self._leakDetector.getContainerIds() try:", "self._leakDetector = None self._doneCallback = None ContainerLeakDetector.removePrivateObj(self.__dict__) Job.destroy(self) def _handleLDDestroy(self):", "will cut down the traversals of the larger set by", "= '' for indirection in indirections: yield None indirection.release() if", "0 and diff3 > 0 and diff4 > 0 and", "set is empty, choose another break # make a generator", "an existing ref? if other is not None: for ind", "TODO self.notify.debug('caught exception in getContainerByIdGen (1)') else: self.notify.warning( '%s (%s)", "# use tuples as keys since they can't be weakref'd,", "self, on, doneCallback) jobMgr.add(j) return j def _scheduleNextLeakCheck(self): taskMgr.doMethodLater(self._nextCheckDelay, self._checkForLeaks,", "objId in idx2id2len[self._index-3]): diff2 = idx2id2len[self._index-1][objId] - idx2id2len[self._index-2][objId] diff3 =", "ref sets self._baseStartRefWorkingList = ScratchPad(refGen=nullGen(), source=self._id2baseStartRef) self._discoveredStartRefWorkingList = ScratchPad(refGen=nullGen(), source=self._id2discoveredStartRef)", "indirection through a dictionary? return self.dictKey is not NoDictKey def", "the key, store it as an evalStr keyRepr = safeRepr(dictKey)", "that this is still the object we originally pointed to", "Job.__init__(self, name) self._leakDetector = leakDetector self.notify = self._leakDetector.notify self._on =", "def getContainerById(self, id): for result in self._id2ref[id].getContainerGen(): pass return result", "key = None attr = None keys = curObj.keys() #", "'FindContainers job caught exception: %s' % e if __dev__: raise", "# this will cut down the traversals of the larger", "notDeadEnd: # prevent cycles in the references (i.e. base.loader.base) for", "we will continue traversing the object graph via one attr,", "a memory leak assert type(objId) in (types.IntType, types.LongType) # prevent", "types.StringType and objName in ('im_self', 'im_class'): return True try: className", "getInstance=False): str = '' prevIndirection = None curIndirection = None", "objects that define __cmp__ and don't handle strings if type(objName)", "of at the end, since we skip back to the", "refs it contains baseLen = len(self._baseStartRefWorkingList.source) discLen = len(self._discoveredStartRefWorkingList.source) minLen", "'__class__'): cName = container.__class__.__name__ else: cName = container.__name__ if (self._otn.lower()", "def _checkForLeaks(self, task=None): self._index2delay[len(self._index2containerId2len)] = self._nextCheckDelay self._checkContainersJob = CheckContainers( '%s-checkForLeaks'", "= None break attrs.append(attr) # we will continue traversing the", "# choose it at random without taking a big chunk", "%s)' % (name, itype(container), idx2id2len[self._index][objId], fastRepr(container, maxLen=CheckContainers.ReprItems))) self.notify.warning(msg) yield None", "iteration self.notify.debug('could not index into %s with key %s' %", "ContainerLeakDetector(Job): \"\"\" Low-priority Python object-graph walker that looks for leaking", "be used as part of an eval, or as a", "an element of the container. Stored as a string to", "return 1 def _isDeadEnd(self, obj, objName=None): if type(obj) in (types.BooleanType,", "that we already have is more concise than the new", "self._leakDetector.getContainerByIdGen(startId): yield None except: # ref is invalid self.notify.debug('invalid startRef,", "the base containers, the ones that hold most objects ref", "if className == 'method-wrapper': return True return False def _hasLength(self,", "* 15. # divide by two, since the first check", "sure they are found by # the object exploration algorithm,", "will continue traversing the object graph via one key of", "break for indirection in indirections: yield None indirection.release() yield id(o)", "def removeContainerById(self, id): if id in self._id2ref: self._id2ref[id].destroy() del self._id2ref[id]", "for i in self._addContainerGen(simbase.__dict__, ref): pass def destroy(self): ContainerLeakDetector.removePrivateObj(self.__dict__) Job.destroy(self)", "don't go away on us indirections = self._indirections for indirection", "storedItem = ref # if we already are storing a", "_id2baseStartRef = self._leakDetector._findContainersJob._id2baseStartRef ids = _id2baseStartRef.keys() for id in ids:", "set of all visited objects; it may visit the same", "for i in self._addContainerGen(__builtin__.__dict__, ref): pass try: base except: pass", "= (self._otn.lower() not in 'dict') yield None try: for container", "%s' % keyRepr) self.dictKey = dictKey self._isWeakRef = False def", "in parentObjRef.goesThrough(curObj[index]): # don't yield, container might lose this element", "self._serialNum def getContainerIds(self): return self._id2ref.keys() def getContainerByIdGen(self, id, **kwArgs): #", "'.foo', dict[key] -> '[key]', etc.) \"\"\" notify = directNotify.newCategory(\"ObjectRef\") class", "in ids: getInstance = (self._otn.lower() not in 'dict') yield None", "None if len(self._indirections) > 1: prevIndirection = self._indirections[-2] return self._indirections[-1].getString(prevIndirection=prevIndirection)", "None' % contName) self._leakDetector.removeContainerById(objId) continue try: cLen = len(container) except", "to discover containers rather than keep a set of all", "it contains baseLen = len(self._baseStartRefWorkingList.source) discLen = len(self._discoveredStartRefWorkingList.source) minLen =", "# make a generator that yields containers a # of", "2 and objId in idx2id2len[self._index-2] and objId in idx2id2len[self._index-3]): diff2", "index into %s with key %s' % ( parentObjRef, safeRepr(key)))", "this an indirection through a dictionary? return self.dictKey is not", "the container if possible stored as a series of 'indirections'", "key, store it as an evalStr keyRepr = safeRepr(dictKey) useEval", "to a container in a way that does not prevent", "types.LongType, types.NoneType, types.NotImplementedType, types.TypeType, types.CodeType, types.FunctionType, types.StringType, types.UnicodeType, types.TupleType): return", "of the dict, # choose it at random without taking", "an instance # since it can't be repr/eval'd # that", "if this is a dictionary lookup, pass dictKey instead of", "# false, allowing a ref to base.myObject.otherObject.myObject for goesThrough in", "def getContainerGen(self, getInstance=False): # try to get a handle on", "hasLength = self._hasLength(attr) notDeadEnd = False if curObjRef is None:", "repr/eval the key, store it as an evalStr keyRepr =", "self._checkDelayScale def _checkForLeaks(self, task=None): self._index2delay[len(self._index2containerId2len)] = self._nextCheckDelay self._checkContainersJob = CheckContainers(", "def _getContainerByEval(self, evalStr, curObj=None): if curObj is not None: #", "with key %s' % ( parentObjRef, safeRepr(key))) continue hasLength =", "a starting object is this object for traversing the object", "yield None indirection.release() yield id(o) == objId def goesThrough(self, obj=None,", "this yields a different set of start refs every time", "based on how many refs it contains baseLen = len(self._baseStartRefWorkingList.source)", "if notDeadEnd: self._addDiscoveredStartRef(attr, objRef) if curObjRef is None and random.randrange(numAttrsLeft)", "for indirection in indirections: yield None indirection.release() yield id(o) ==", "for goesThrough in parentObjRef.goesThrough(curObj[index]): # don't yield, container might lose", "True return False def _hasLength(self, obj): return hasattr(obj, '__len__') def", "self.dictKey = NoDictKey def acquire(self): self._refCount += 1 def release(self):", "self.notify.getDebug(): for contName in self._leakDetector.getContainerNameByIdGen(objId): yield None self.notify.debug( '%s no", "except: pass if useEval: # check to make sure the", "a container in a way that does not prevent garbage", "self.acceptOnce(self._checkContainersJob.getFinishedEvent(), self._scheduleNextLeakCheck) jobMgr.add(self._checkContainersJob) return task.done def _scheduleNextPruning(self): taskMgr.doMethodLater(self._pruneTaskPeriod, self._pruneObjectRefs, self._getPruneTaskName())", "have been garbage-collected TODO: store string components that are duplicates", "up in dictionaries, depending on the type of each indirection", "len(existingRepr): if contId in self._id2ref: self._leakDetector.removeContainerById(contId) self._id2ref[contId] = objRef def", "= False # if we haven't picked the next ref,", "= {} # use tuples as keys since they can't", "= False try: keyEval = eval(keyRepr) useEval = True except:", "discover containers rather than keep a set of all visited", "self.evalStr = '[%s]' % keyRepr else: try: # store a", "make a generator that yields containers a # of times", "# definitive ref sets self._baseStartRefWorkingList = ScratchPad(refGen=nullGen(), source=self._id2baseStartRef) self._discoveredStartRefWorkingList =", "None: # this ref set is empty, choose another #", "1.5: 1 1.5 2.3 3.4 5.1 7.6 11.4 17.1 25.6", "string to be used as part of an eval, or", "%s' % curObjRef) #import pdb;pdb.set_trace() # store a copy of", "hasLength = self._hasLength(child) notDeadEnd = not self._isDeadEnd(child) if hasLength or", "= index ContainerLeakDetector.addPrivateObj(self.__dict__) def destroy(self): ContainerLeakDetector.removePrivateObj(self.__dict__) Job.destroy(self) def getPriority(self): return", "str += curIndirection.getString(prevIndirection=prevIndirection, nextIndirection=nextIndirection) if getInstance: lenDict = len('.__dict__') if", "keys = curObj.keys() # we will continue traversing the object", "None and random.randrange(numAttrsLeft) == 0: curObjRef = objRef del attr", "if self._index <= 4: if diff > 0 and diff2", "className == 'method-wrapper': return True return False def _hasLength(self, obj):", "leakDetector self.notify = self._leakDetector.notify self._on = on self._doneCallback = doneCallback", "< len(indirections)-1: nextIndirection = indirections[i+1] else: nextIndirection = None str", "self._leakDetector._index2delay[self._index-1]) / 60. name = self._leakDetector.getContainerNameById(objId) if idx2id2len[self._index-1][objId] != 0:", "None attr = None keys = curObj.keys() # we will", "1 numAttrsLeft -= 1 hasLength = self._hasLength(attr) notDeadEnd = False", "childNames = dir(curObj) except: pass else: try: index = -1", "= 100. * (float(diff) / float(idx2id2len[self._index-1][objId])) try: for container in", "invalid, remove it self._leakDetector.removeContainerById(id) _id2baseStartRef = self._leakDetector._findContainersJob._id2baseStartRef ids = _id2baseStartRef.keys()", "container is None: # this container no longer exists if", "% startId) self._leakDetector.removeContainerById(startId) continue curObjRef = containerRef try: for curObj", "this object, don't store a second reference if objId in", "each container for objId in ids: yield None try: for", "eval'd evalStr += indirection.getString() else: curObj = self._getContainerByEval(evalStr, curObj=curObj) if", "None: return key return parentDict[key] def getString(self, prevIndirection=None, nextIndirection=None): #", "two, since the first check just takes length measurements and", "not goesThrough: objRef = ObjectRef(Indirection(evalStr='.__dict__'), id(child), parentObjRef) yield None if", "self._index = index ContainerLeakDetector.addPrivateObj(self.__dict__) def destroy(self): ContainerLeakDetector.removePrivateObj(self.__dict__) Job.destroy(self) def getPriority(self):", "0: percent = 100. * (float(diff) / float(idx2id2len[self._index-1][objId])) try: for", "yield id(o) == objId def goesThrough(self, obj=None, objId=None): # since", "indirections = self._indirections for indirection in indirections: yield None indirection.acquire()", "we already are storing a reference to this object, don't", "= ObjectRef(Indirection(evalStr='leakDetectors'), id(leakDetectors)) self._id2baseStartRef[id(leakDetectors)] = ref for i in self._addContainerGen(__builtin__.__dict__,", "raise yield Job.Done class ContainerLeakDetector(Job): \"\"\" Low-priority Python object-graph walker", "15 31 63 127 255 511 1023 2047 # *", "that # to avoid storing multiple redundant refs to a", "PStatCollector from direct.directnotify.DirectNotifyGlobal import directNotify from direct.showbase.PythonUtil import Queue, invertDictLossless,", "return 'cldDestroy-%s' % self._serialNum def getLeakEvent(self): # sent when a", "at random without taking a big chunk of CPU time", "set() def __init__(self, name, firstCheckDelay = None): Job.__init__(self, name) self._serialNum", "_getDestroyEvent(self): # sent when leak detector is about to be", "not hasattr(base, 'leakContainer'): base.leakContainer = {} # use tuples as", "from a container to an element of the container. Stored", "# prevent cycles (i.e. base.loader.base.loader) assert not self.goesThrough(objId=objId) self._indirections.append(indirection) #", "the Python objects to discover containers rather than keep a", "getInstance: lenDict = len('.__dict__') if evalStr[-lenDict:] == '.__dict__': evalStr =", "to this object, don't store a second reference if objId", "removePrivateObj(cls, obj): cls.PrivateIds.remove(id(obj)) def _getCheckTaskName(self): return 'checkForLeakingContainers-%s' % self._serialNum def", "self._addDiscoveredStartRef(attr, objRef) if curObjRef is None and random.randrange(numKeysLeft) == 0:", "start # fib: 1 2 4 7 12 20 33", "curObjRef) #import pdb;pdb.set_trace() # store a copy of the current", "yield None container = result except Exception, e: # this", "CheckContainers( '%s-checkForLeaks' % self.getJobName(), self, len(self._index2containerId2len)) self.acceptOnce(self._checkContainersJob.getFinishedEvent(), self._scheduleNextLeakCheck) jobMgr.add(self._checkContainersJob) return", "would return # false, allowing a ref to base.myObject.otherObject.myObject for", "is None: raise FailedEval(evalStr) # try to look up this", "to an element of the container. Stored as a string", "in self._leakDetector.getContainerByIdGen(objId): yield None except: # TODO self.notify.debug('caught exception in", "ref = ObjectRef(Indirection(evalStr='leakDetectors'), id(leakDetectors)) self._id2baseStartRef[id(leakDetectors)] = ref for i in", "self._index2delay[len(self._index2containerId2len)] = self._nextCheckDelay self._checkContainersJob = CheckContainers( '%s-checkForLeaks' % self.getJobName(), self,", "else: ref = ObjectRef(Indirection(evalStr='simbase.__dict__'), id(simbase.__dict__)) self._id2baseStartRef[id(simbase.__dict__)] = ref for i", "name, leakDetector): Job.__init__(self, name) self._leakDetector = leakDetector self.notify = self._leakDetector.notify", "the object exploration algorithm, including objects that exist # just", "yield None self.notify.debug('%s no longer exists; getContainerById returned None' %", "otn, doneCallback=None): Job.__init__(self, name) self._leakDetector = leakDetector self.notify = self._leakDetector.notify", "74.9 113.3 171 self._nextCheckDelay = self._nextCheckDelay * self._checkDelayScale def _checkForLeaks(self,", "it's an internal object, ignore it if id(obj) in ContainerLeakDetector.PrivateIds:", "if objId in idx2id2len[self._index-1]: diff = idx2id2len[self._index][objId] - idx2id2len[self._index-1][objId] \"\"\"", "__init__(self, evalStr=None, dictKey=NoDictKey): # if this is a dictionary lookup,", "getContainerByIdGen (3)') else: msg = ('leak detected: %s (%s) consistently", "= serialNum() self._findContainersJob = None self._checkContainersJob = None self._pruneContainersJob =", "to past lens if self._index > 0: idx2id2len = self._leakDetector._index2containerId2len", "objRef): yield None if notDeadEnd: self._addDiscoveredStartRef(child, objRef) curObjRef = objRef", "= self._indirections[-2] return self._indirections[-1].getString(prevIndirection=prevIndirection) def __repr__(self): for result in self.getEvalStrGen():", "Indirection: \"\"\" Represents the indirection that brings you from a", "self._getNonWeakDictKey() # objects in __builtin__ will have parentDict==None if parentDict", "off of an existing ref? if other is not None:", "minLen *= 3. workingListSelector = flywheel([self._baseStartRefWorkingList, self._discoveredStartRefWorkingList], [baseLen/minLen, discLen/minLen]) yield", "the previous indirection was an instance dict, change our syntax", "getPriority(self): return Job.Priorities.Normal def run(self): try: self._leakDetector._index2containerId2len[self._index] = {} ids", "else: objId = id(obj) o = None evalStr = ''", "objRef) if curObjRef is None and random.randrange(numKeysLeft) == 0: curObjRef", "[container, name]) if config.GetBool('pdb-on-leak-detect', 0): import pdb;pdb.set_trace() pass except Exception,", "container is gone, try again curObjRef = None continue self.notify.debug('-->", "\"\"\" Job to destroy any container refs that are no", "[baseLen/minLen, discLen/minLen]) yield None continue # grab the next start", "ref): pass def destroy(self): ContainerLeakDetector.removePrivateObj(self.__dict__) Job.destroy(self) def getPriority(self): return Job.Priorities.Low", "= NoDictKey def acquire(self): self._refCount += 1 def release(self): self._refCount", "= indirections[i] if i < len(indirections)-1: nextIndirection = indirections[i+1] else:", "('leak detected: %s (%s) consistently increased in size over the", "usage \"\"\" def __init__(self, evalStr=None, dictKey=NoDictKey): # if this is", "Exception, e: print 'FindContainers job caught exception: %s' % e", "> 0: idx2id2len = self._leakDetector._index2containerId2len for objId in idx2id2len[self._index]: yield", "if id in self._id2ref: return repr(self._id2ref[id]) return '<unknown container>' def", "sizes at ever-increasing intervals. \"\"\" notify = directNotify.newCategory(\"ContainerLeakDetector\") # set", "as id %s' % startId) self._leakDetector.removeContainerById(startId) continue curObjRef = containerRef", "None: notDeadEnd = not self._isDeadEnd(attr, key) if hasLength or notDeadEnd:", "34 55 89 # * 2.: 1 2 4 8", "key self.dictKey = weakref.ref(dictKey) self._isWeakRef = True except TypeError, e:", "ContainerLeakDetector.notify.debug('could not weakref dict key %s' % keyRepr) self.dictKey =", "% serialNum()) if task: return task.done leakContainer() def _createTaskLeak(): leakTaskName", "and prevIndirection.evalStr is not None: if prevIndirection.evalStr[-len(instanceDictStr):] == instanceDictStr: return", "if diff > 0 and diff2 > 0 and diff3", "if hash(keyEval) != hash(dictKey): useEval = False if useEval: #", "id): for result in self._id2ref[id].getContainerGen(): pass return result def getContainerNameByIdGen(self,", "%.2f%% in %.2f minutes (%s items at last measurement, current", "getInstance is True, will return instance instead of instance dict", "safeRepr, fastRepr from direct.showbase.Job import Job import types, weakref, random,", "check just takes length measurements and # doesn't check for", "1: prevIndirection = self._indirections[-2] return self._indirections[-1].getString(prevIndirection=prevIndirection) def __repr__(self): for result", "self._findContainersJob = None self._checkContainersJob = None self._pruneContainersJob = None if", "8 13 21 34 55 89 # * 2.: 1", "evalStr, curObj=None): if curObj is not None: # eval('curObj.foo.bar.someDict') evalStr", "as an evalStr self.evalStr = '[%s]' % keyRepr else: try:", "is a candidate if curObjRef is None: notDeadEnd = not", "def getPriority(self): return Job.Priorities.Normal def run(self): try: self._leakDetector._index2containerId2len[self._index] = {}", "by 2/3 minLen *= 3. workingListSelector = flywheel([self._baseStartRefWorkingList, self._discoveredStartRefWorkingList], [baseLen/minLen,", "= self._hasLength(child) notDeadEnd = not self._isDeadEnd(child) if hasLength or notDeadEnd:", "e: print 'PruneObjectRefs job caught exception: %s' % e if", "except Exception, e: print 'PruneObjectRefs job caught exception: %s' %", "self._nextCheckDelay self._checkContainersJob = CheckContainers( '%s-checkForLeaks' % self.getJobName(), self, len(self._index2containerId2len)) self.acceptOnce(self._checkContainersJob.getFinishedEvent(),", "True, will return instance instead of instance dict #import pdb;pdb.set_trace()", "- idx2id2len[self._index-4][objId] diff5 = idx2id2len[self._index-4][objId] - idx2id2len[self._index-5][objId] if diff >", "% self.getJobName(), self) jobMgr.add(self._findContainersJob) self._scheduleNextLeakCheck() self._scheduleNextPruning() while True: yield Job.Sleep", "graph traversal objId = id(obj) if objId in self._id2discoveredStartRef: existingRef", "None if notDeadEnd: self._addDiscoveredStartRef(attr, objRef) if curObjRef is None and", "raise yield Job.Done def finished(self): if self._doneCallback: self._doneCallback(self) class FPTObjsNamed(Job):", "reference is invalid, remove it del _id2baseStartRef[id] _id2discoveredStartRef = self._leakDetector._findContainersJob._id2discoveredStartRef", "attrs = [] while 1: yield None try: attr =", "ObjectRef(Indirection(evalStr='.__dict__'), id(child), parentObjRef) yield None if hasLength: for i in", "have is more concise than the new ref return storedItem", "in (types.IntType, types.LongType): if (existingRef.getNumIndirections() >= ref.getNumIndirections()): # the ref", "keys since they can't be weakref'd, and use an instance", "ids: yield None try: for container in _id2discoveredStartRef[id].getContainerGen(): yield None", "None except KeyError, ke: return None return container def getContainerGen(self,", "self._serialNum = serialNum() self._findContainersJob = None self._checkContainersJob = None self._pruneContainersJob", "# delay from job start # fib: 1 2 4", "big chunk of CPU time numAttrsLeft = len(attrs) + 1", "_createTaskLeak(): leakTaskName = uniqueName('leakedTask') leakDoLaterName = uniqueName('leakedDoLater') def nullTask(task=None): return", "/ float(idx2id2len[self._index-1][objId])) try: for container in self._leakDetector.getContainerByIdGen(objId): yield None except:", "ptc in self._leakDetector.getContainerNameByIdGen(id): yield None except: pass else: print 'GPTCN('", "self._refCount == 0: self.destroy() def isDictKey(self): # is this an", "4: if diff > 0 and diff2 > 0 and", "already have, # put it in the table if contId", "= config.GetFloat('leak-detector-prune-period', 60. * 30.) # main dict of id(container)->containerRef", "# look ourselves up in parentDict key = self._getNonWeakDictKey() #", "indirections: yield None indirection.acquire() for indirection in indirections: yield None", "5 8 13 21 34 55 89 # * 2.:", "= len('.__dict__') if str[-lenDict:] == '.__dict__': str = str[:-lenDict] for", "used as part of an eval, or as a key", "taking a big chunk of CPU time numKeysLeft = len(keys)", "curObj = indirection.dereferenceDictKey(curObj) evalStr = '' yield None o =", "types.LongType) else: objId = id(obj) o = None evalStr =", "references (i.e. base.loader.base) for goesThrough in parentObjRef.goesThroughGen(child): # don't yield,", "by asking for each container \"\"\" def __init__(self, name, leakDetector):", "= NoDictKey # is the dictKey a weak reference? self._isWeakRef", "= fw if curObjRef is None: # this ref set", "in self._id2ref: if (self._id2ref[objId].getNumIndirections() >= ref.getNumIndirections()): # the ref that", "the global__builtin__ namespace # put __builtin__ at the start if", "not None: if prevIndirection.evalStr[-len(instanceDictStr):] == instanceDictStr: return '.%s' % keyRepr", "# we've discovered an object that can be used to", "objId in self._id2ref: storedItem = objId self._id2discoveredStartRef[objId] = storedItem def", "and objId in idx2id2len[self._index-3]): diff2 = idx2id2len[self._index-1][objId] - idx2id2len[self._index-2][objId] diff3", "new ref return storedItem = ref # if we already", "cLen # compare the current len of each container to", "4.75 8.1 13.2 20.8 32.2 49.3 74.9 113.3 171 self._nextCheckDelay", "def _getPruneTaskName(self): return 'pruneLeakingContainerRefs-%s' % self._serialNum def getContainerIds(self): return self._id2ref.keys()", "container in self._leakDetector.getContainerByIdGen(id): yield None except: # reference is invalid,", "at the end, since we skip back to the #", "True except: pass if useEval: # check to make sure", "ref that we already have is more concise than the", "-= 1 try: attr = curObj[key] except KeyError, e: #", "return self._indirections[-1].getString(prevIndirection=prevIndirection) def __repr__(self): for result in self.getEvalStrGen(): pass return", "if this container is new, or the objRef repr is", "None try: for container in self._leakDetector.getContainerByIdGen(id): yield None except: pass", "parentDict is None: return key return parentDict[key] def getString(self, prevIndirection=None,", "self._indirections for indirection in indirections: indirection.acquire() for i in xrange(len(indirections)):", "prevIndirection = None if len(self._indirections) > 1: prevIndirection = self._indirections[-2]", "e: print 'FindContainers job caught exception: %s' % e if", "Job.Done def finished(self): if self._doneCallback: self._doneCallback(self) class PruneObjectRefs(Job): \"\"\" Job", "notify = directNotify.newCategory(\"ObjectRef\") class FailedEval(Exception): pass def __init__(self, indirection, objId,", "indirection.dereferenceDictKey(curObj) evalStr = '' yield None o = self._getContainerByEval(evalStr, curObj=curObj)", "result class FindContainers(Job): \"\"\" Explore the Python graph, looking for", "self.notify.debug('%s no longer exists; getContainerById returned None' % contName) self._leakDetector.removeContainerById(objId)", "own tables for leaks ContainerLeakDetector.addPrivateObj(ContainerLeakDetector.PrivateIds) ContainerLeakDetector.addPrivateObj(self.__dict__) self.setPriority(Job.Priorities.Min) jobMgr.add(self) def destroy(self):", "getBase() taskMgr.add(nullTask, uniqueName(leakTaskName)) taskMgr.doMethodLater(1 << 31, nullDoLater, uniqueName(leakDoLaterName)) taskMgr.doMethodLater(10, leakTask,", "# store a copy of the current objRef parentObjRef =", "except: # reference is invalid, remove it del _id2baseStartRef[id] _id2discoveredStartRef", "via one attr, # choose it at random without taking", "__builtin__.__dict__: objRef = ObjectRef(Indirection(evalStr='%s' % key), id(curObj[key])) else: objRef =", "def __repr__(self): for result in self.getEvalStrGen(): pass return result class", "None continue # grab the next start ref from this", "store as an evalStr self.evalStr = '[%s]' % keyRepr else:", "cont, objRef): contId = id(cont) # if this container is", "self._isDeadEnd(child) if hasLength or notDeadEnd: # prevent cycles in the", "for i in self._addContainerGen(base.__dict__, ref): pass try: simbase except: pass", "== 'method-wrapper': return True return False def _hasLength(self, obj): return", "leak is detected # passes description string as argument return", "main dict of id(container)->containerRef self._id2ref = {} # storage for", "self.notify = self._leakDetector.notify self._on = on self._doneCallback = doneCallback self._ldde", "100. * (float(diff) / float(idx2id2len[self._index-1][objId])) try: for container in self._leakDetector.getContainerByIdGen(objId):", "143 232 # * 2.: 1 3 7 15 31", "= container.__name__ if (self._otn.lower() in cName.lower()): try: for ptc in", "else: try: # store a weakref to the key self.dictKey", "33 54 88 143 232 # * 2.: 1 3", "5.1 7.6 11.4 17.1 25.6 38.4 57.7 # # delay", "at last measurement, current contents: %s)' % ( name, itype(container),", "= {} ref = ObjectRef(Indirection(evalStr='leakDetectors'), id(leakDetectors)) self._id2baseStartRef[id(leakDetectors)] = ref for", "% contName) self._leakDetector.removeContainerById(objId) continue try: cLen = len(container) except Exception,", "try: for container in self._leakDetector.getContainerByIdGen(id): yield None except: # reference", "other._indirections: self._indirections.append(ind) # make sure we're not storing a reference", "base = getBase() if not hasattr(base, 'leakContainer'): base.leakContainer = {}", "self._leakDetector.getContainerByIdGen(id): yield None except: pass else: name = self._leakDetector._id2ref[id].getFinalIndirectionStr() if", "measurement, current contents: %s)' % (name, itype(container), idx2id2len[self._index][objId], fastRepr(container, maxLen=CheckContainers.ReprItems)))", "the actual system so that Python will keep one copy", "that we should start traversals from often and not-as-often, #", "e: pass del itr continue except Exception, e: print 'FindContainers", "look ourselves up in parentDict key = self._getNonWeakDictKey() # objects", "diff3 > 0 and diff4 > 0 and diff5 >", "%s' % e if __dev__: raise yield Job.Done class ContainerLeakDetector(Job):", "direct.directnotify.DirectNotifyGlobal import directNotify from direct.showbase.PythonUtil import Queue, invertDictLossless, makeFlywheelGen from", "None while True: # yield up here instead of at", "_getCheckTaskName(self): return 'checkForLeakingContainers-%s' % self._serialNum def _getPruneTaskName(self): return 'pruneLeakingContainerRefs-%s' %", "'[%s]' % keyRepr else: try: # store a weakref to", "element pass if not goesThrough: if curObj is __builtin__.__dict__: objRef", "an instance dict, skip over this one (obj.__dict__[keyName] == obj.keyName)", "goesThrough in self.goesThroughGen(obj=obj, objId=objId): pass return goesThrough def _getContainerByEval(self, evalStr,", "repr is shorter than what we already have, # put", "<< 31, nullDoLater, uniqueName(leakDoLaterName)) taskMgr.doMethodLater(10, leakTask, 'doLeakTask-%s' % serialNum()) if", "since we cache the ids involved in this reference, #", "notDeadEnd: self._addDiscoveredStartRef(attr, objRef) if curObjRef is None and random.randrange(numKeysLeft) ==", "e: ContainerLeakDetector.notify.debug('could not weakref dict key %s' % keyRepr) self.dictKey", "try: container = eval(evalStr) except NameError, ne: return None except", "_id2discoveredStartRef.keys() for id in ids: yield None try: for container", "not weakref dict key %s' % keyRepr) self.dictKey = dictKey", "not indirection.isDictKey(): # build up a string to be eval'd", "container to past lens if self._index > 0: idx2id2len =", "self._doneCallback(self) class FPTObjsNamed(Job): def __init__(self, name, leakDetector, on, doneCallback=None): Job.__init__(self,", "for indirection in indirections: indirection.acquire() for indirection in indirections: yield", "'doLeakTask-%s' % serialNum()) if task: return task.done leakTask() class NoDictKey:", "print 'CheckContainers job caught exception: %s' % e if __dev__:", "return self.evalStr # we're stored as a dict key keyRepr", "is invalid, remove it self._leakDetector.removeContainerById(id) _id2baseStartRef = self._leakDetector._findContainersJob._id2baseStartRef ids =", "if config.GetBool('pdb-on-leak-detect', 0): import pdb;pdb.set_trace() pass except Exception, e: print", "self._id2discoveredStartRef[objId] if type(existingRef) not in (types.IntType, types.LongType): if (existingRef.getNumIndirections() >=", "is None and random.randrange(numAttrsLeft) == 0: curObjRef = objRef del", "this container no longer exists if self.notify.getDebug(): for contName in", "startRefWorkingList.refGen.next() break except StopIteration: # we've run out of refs,", "leakDetector self.notify = self._leakDetector.notify self._index = index ContainerLeakDetector.addPrivateObj(self.__dict__) def destroy(self):", "a reference to this object, don't store a second reference", "= ref for i in self._addContainerGen(__builtin__.__dict__, ref): pass try: base", "# since it can't be repr/eval'd # that will force", "reduce memory usage \"\"\" def __init__(self, evalStr=None, dictKey=NoDictKey): # if", "ref to base.myObject.otherObject.myObject for goesThrough in self.goesThroughGen(obj=obj, objId=objId): pass return", "our own tables for leaks ContainerLeakDetector.addPrivateObj(ContainerLeakDetector.PrivateIds) ContainerLeakDetector.addPrivateObj(self.__dict__) self.setPriority(Job.Priorities.Min) jobMgr.add(self) def", "remove it del _id2baseStartRef[id] _id2discoveredStartRef = self._leakDetector._findContainersJob._id2discoveredStartRef ids = _id2discoveredStartRef.keys()", "since we skip back to the # top of the", "the dict, # choose it at random without taking a", "elif (objId in idx2id2len[self._index-4] and objId in idx2id2len[self._index-5]): # if", "we hit a dead end, start over from another container", "notDeadEnd = not self._isDeadEnd(attr, key) if hasLength or notDeadEnd: #", "the objRef repr is shorter than what we already have,", "if type(obj) in (types.BooleanType, types.BuiltinFunctionType, types.BuiltinMethodType, types.ComplexType, types.FloatType, types.IntType, types.LongType,", "is more concise than the new ref return if objId", "{} # test the non-weakref object reference handling if random.random()", "objId = id(obj) o = None evalStr = '' curObj", "/ 60. name = self._leakDetector.getContainerNameById(objId) if idx2id2len[self._index-1][objId] != 0: percent", "self._leakDetector.notify ContainerLeakDetector.addPrivateObj(self.__dict__) def destroy(self): ContainerLeakDetector.removePrivateObj(self.__dict__) Job.destroy(self) def getPriority(self): return Job.Priorities.Normal", "container return self._id2ref[id].getContainerGen(**kwArgs) def getContainerById(self, id): for result in self._id2ref[id].getContainerGen():", "discLen))) # this will cut down the traversals of the", "to be looked up in a dict. Each dictionary dereference", "objId=None): # since we cache the ids involved in this", "self.notify.getDebug(): for contName in self._leakDetector.getContainerNameByIdGen(objId): yield None self.notify.debug('%s no longer", "if objId in self._id2ref: storedItem = objId self._id2discoveredStartRef[objId] = storedItem", "the container. Stored as a string to be used as", "def finished(self): if self._doneCallback: self._doneCallback(self) class PruneObjectRefs(Job): \"\"\" Job to", "= self._leakDetector.notify self._index = index ContainerLeakDetector.addPrivateObj(self.__dict__) def destroy(self): ContainerLeakDetector.removePrivateObj(self.__dict__) Job.destroy(self)", "on, doneCallback=None): Job.__init__(self, name) self._leakDetector = leakDetector self.notify = self._leakDetector.notify", "except: pass else: # prevent infinite recursion in built-in containers", "make sure the indirections don't go away on us indirections", "(i.e. base.loader.base) for goesThrough in parentObjRef.goesThroughGen(child): # don't yield, container", "reduce memory usage, this does a random walk of the", "def getLeakEvent(self): # sent when a leak is detected #", "again curObjRef = None continue self.notify.debug('--> %s' % curObjRef) #import", "- idx2id2len[self._index-2][objId] diff3 = idx2id2len[self._index-2][objId] - idx2id2len[self._index-3][objId] if self._index <=", "if curObjRef is None: notDeadEnd = not self._isDeadEnd(attr, key) if", "container in a way that does not prevent garbage collection", "# * 2.: 1 2 4 8 16 32 64", "of each indirection # if getInstance is True, will return", "be examined PrivateIds = set() def __init__(self, name, firstCheckDelay =", "getContainerNameByIdGen(self, id, **kwArgs): return self._id2ref[id].getEvalStrGen(**kwArgs) def getContainerNameById(self, id): if id", "# framerate, etc. See LeakDetectors.py if not hasattr(__builtin__, \"leakDetectors\"): __builtin__.leakDetectors", "if type(objName) == types.StringType and objName in ('im_self', 'im_class'): return", "__dev__: raise yield Job.Done class FPTObjsOfType(Job): def __init__(self, name, leakDetector,", "in indirections: indirection.acquire() for indirection in indirections: yield None if", "indirections don't go away on us indirections = self._indirections for", "indirection, objId, other=None): self._indirections = [] # are we building", "128 256 512 1024 # * 1.5: 1 1.5 2.3", "for indirection in indirections: yield None if not indirection.isDictKey(): #", "for key in keys: yield None numKeysLeft -= 1 try:", "2047 # * 1.5: 1 2.5 4.75 8.1 13.2 20.8", "= not self._isDeadEnd(child) if hasLength or notDeadEnd: # prevent cycles", "walk of the Python objects to discover containers rather than", "yield self._getContainerByEval(evalStr, curObj=curObj) def getEvalStrGen(self, getInstance=False): str = '' prevIndirection", "self._nextCheckDelay * self._checkDelayScale def _checkForLeaks(self, task=None): self._index2delay[len(self._index2containerId2len)] = self._nextCheckDelay self._checkContainersJob", "= None continue self.notify.debug('--> %s' % curObjRef) #import pdb;pdb.set_trace() #", "and objId in idx2id2len[self._index-5]): # if size has consistently increased", "we start a new traversal # force creation of a", "way that does not prevent garbage collection of the container", "after this Ref was created this would return # false,", "def _scheduleNextPruning(self): taskMgr.doMethodLater(self._pruneTaskPeriod, self._pruneObjectRefs, self._getPruneTaskName()) def _pruneObjectRefs(self, task=None): self._pruneContainersJob =", "def __init__(self, evalStr=None, dictKey=NoDictKey): # if this is a dictionary", "(types.BooleanType, types.BuiltinFunctionType, types.BuiltinMethodType, types.ComplexType, types.FloatType, types.IntType, types.LongType, types.NoneType, types.NotImplementedType, types.TypeType,", "indirection in indirections: yield None indirection.release() yield str def getFinalIndirectionStr(self):", "without taking a big chunk of CPU time numKeysLeft =", "in self._indirections: ind.acquire() self.notify.debug(repr(self)) def destroy(self): for indirection in self._indirections:", "name]) if config.GetBool('pdb-on-leak-detect', 0): import pdb;pdb.set_trace() pass except Exception, e:", "if (existingRef.getNumIndirections() >= ref.getNumIndirections()): # the ref that we already", "evalStr[-lenDict:] == '.__dict__': evalStr = evalStr[:-lenDict] # TODO: check that", "= str[:-lenDict] for indirection in indirections: yield None indirection.release() yield", "weakref'd, and use an instance # since it can't be", "obj is None: assert type(objId) in (types.IntType, types.LongType) else: objId", "evalStr = 'curObj%s' % evalStr else: # this eval is", "= idx2id2len[self._index-1][objId] - idx2id2len[self._index-2][objId] diff3 = idx2id2len[self._index-2][objId] - idx2id2len[self._index-3][objId] if", "def isDictKey(self): # is this an indirection through a dictionary?", "a dictionary? return self.dictKey is not NoDictKey def _getNonWeakDictKey(self): if", "lose this element pass if not goesThrough: if curObj is", "name) self._leakDetector = leakDetector self.notify = self._leakDetector.notify self._otn = otn", "class Indirection: \"\"\" Represents the indirection that brings you from", "contName in self._leakDetector.getContainerNameByIdGen(objId): yield None self.notify.debug('%s no longer exists; getContainerById", "this will cut down the traversals of the larger set", "consistently increased in size over the last ' '5 periods", "object for traversing the object graph? try: return len(startObj) except:", "to avoid storing multiple redundant refs to a single item", "already there bis = '__builtin__' if evalStr[:len(bis)] != bis: evalStr", "objRef = ObjectRef(Indirection(dictKey=key), id(curObj[key]), parentObjRef) yield None if hasLength: for", "is OK because we are yielding during the iteration self.notify.debug('could", "storage for results of check-container job self._index2containerId2len = {} self._index2delay", "continue # do we need to go look up the", "self._id2ref[id].destroy() del self._id2ref[id] def run(self): # start looking for containers", "an object instanceDictStr = '.__dict__' if self.evalStr is not None:", "sure we're not storing a reference to the actual object,", "ptc except Exception, e: print 'FPTObjsNamed job caught exception: %s'", "not based off of curObj, use the global__builtin__ namespace #", "is not None: # eval('curObj.foo.bar.someDict') evalStr = 'curObj%s' % evalStr", "in attrs: yield None index += 1 numAttrsLeft -= 1", "or as a key to be looked up in a", "self._leakDetector._index2containerId2len[self._index][objId] = cLen # compare the current len of each", "objects ref = ObjectRef(Indirection(evalStr='__builtin__.__dict__'), id(__builtin__.__dict__)) self._id2baseStartRef[id(__builtin__.__dict__)] = ref # container", "some custom classes don't do well when iterated attr =", "id, **kwArgs): # return a generator to look up a", "Job.__init__(self, name) self._leakDetector = leakDetector self.notify = self._leakDetector.notify ContainerLeakDetector.addPrivateObj(self.__dict__) def", "curObj=curObj) def getEvalStrGen(self, getInstance=False): str = '' prevIndirection = None", "return None return container def getContainerGen(self, getInstance=False): # try to", "failed') # that container is gone, try again curObjRef =", "self.goesThroughGen(obj=obj, objId=objId): pass return goesThrough def _getContainerByEval(self, evalStr, curObj=None): if", "ref): # we've discovered an object that can be used", "= self._leakDetector.getContainerIds() try: for id in ids: yield None try:", "this reference, # this isn't perfect, for example if base.myObject", "types.NotImplementedType, types.TypeType, types.CodeType, types.FunctionType, types.StringType, types.UnicodeType, types.TupleType): return True #", "len(startRefWorkingList.source) == 0: # ref set is empty, choose another", "single item if type(curObjRef) in (types.IntType, types.LongType): startId = curObjRef", "built-in containers related to methods if className == 'method-wrapper': return", "multiple redundant refs to a single item if type(curObjRef) in", "return key return parentDict[key] def getString(self, prevIndirection=None, nextIndirection=None): # return", "self._id2ref = {} # storage for results of check-container job", "in indirections: yield None indirection.release() yield id(o) == objId def", "a new set if len(startRefWorkingList.source) == 0: # ref set", "our syntax from ['key'] to .key if prevIndirection is not", "key), id(curObj[key])) else: objRef = ObjectRef(Indirection(dictKey=key), id(curObj[key]), parentObjRef) yield None", "object to start a traversal from try: startRefWorkingList = workingListSelector.next()", "'cldDestroy-%s' % self._serialNum def getLeakEvent(self): # sent when a leak", "self._leakDetector.getContainerNameByIdGen(objId): yield None self.notify.debug( '%s is no longer a container,", "171 self._nextCheckDelay = self._nextCheckDelay * self._checkDelayScale def _checkForLeaks(self, task=None): self._index2delay[len(self._index2containerId2len)]", "(i.e. base.loader.base) for goesThrough in parentObjRef.goesThrough(curObj[index]): # don't yield, container", "ref = ObjectRef(Indirection(evalStr='base.__dict__'), id(base.__dict__)) self._id2baseStartRef[id(base.__dict__)] = ref for i in", "we do that # to avoid storing multiple redundant refs", "over the last ' '3 periods (%s items at last", "1 2 4 7 12 20 33 54 88 143", "pass else: print 'GPTCN(' + self._on + '):' + self.getJobName()", "FailedEval(evalStr) # try to look up this key in the", "of CPU time numKeysLeft = len(keys) + 1 for key", "% evalStr else: # this eval is not based off", "if not goesThrough: if curObj is __builtin__.__dict__: objRef = ObjectRef(Indirection(evalStr='%s'", "Python objects to discover containers rather than keep a set", "container sizes at ever-increasing intervals. \"\"\" notify = directNotify.newCategory(\"ContainerLeakDetector\") #", "def goesThroughGen(self, obj=None, objId=None): if obj is None: assert type(objId)", "= self._indirections for indirection in indirections: yield None indirection.acquire() for", "KeyError, e: # this is OK because we are yielding", "yield None o = self._getContainerByEval(evalStr, curObj=curObj) if id(o) == objId:", "id(curObj[key])) else: objRef = ObjectRef(Indirection(dictKey=key), id(curObj[key]), parentObjRef) yield None if", "reassigned # to a different object after this Ref was", "taking a big chunk of CPU time numAttrsLeft = len(attrs)", "index += 1 numAttrsLeft -= 1 hasLength = self._hasLength(attr) notDeadEnd", "be eval'd evalStr += indirection.getString() else: curObj = self._getContainerByEval(evalStr, curObj=curObj)", "0): import pdb;pdb.set_trace() pass except Exception, e: print 'CheckContainers job", "containers that should not be examined PrivateIds = set() def", "up in parentDict key = self._getNonWeakDictKey() # objects in __builtin__", "ot, doneCallback=None): j = FPTObjsOfType(name, self, ot, doneCallback) jobMgr.add(j) return", "allowing a ref to base.myObject.otherObject.myObject for goesThrough in self.goesThroughGen(obj=obj, objId=objId):", "self._leakDetector.notify self._on = on self._doneCallback = doneCallback self._ldde = self._leakDetector._getDestroyEvent()", "evalStr = evalStr[:-lenDict] # TODO: check that this is still", "while loop right off the bat workingListSelector = nullGen() #", "def __init__(self, indirection, objId, other=None): self._indirections = [] # are", "= id(obj) if objId in self._id2discoveredStartRef: existingRef = self._id2discoveredStartRef[objId] if", "traversal objId = id(obj) if objId in self._id2discoveredStartRef: existingRef =", "direct.showbase.PythonUtil import Queue, invertDictLossless, makeFlywheelGen from direct.showbase.PythonUtil import itype, serialNum,", "Ref was created this would return # false, allowing a", "PrivateIds = set() def __init__(self, name, firstCheckDelay = None): Job.__init__(self,", "storing a reference to this object, don't store a second", "self._id2ref[id].getEvalStrGen(**kwArgs) def getContainerNameById(self, id): if id in self._id2ref: return repr(self._id2ref[id])", "to methods if className == 'method-wrapper': return True return False", "def destroy(self): ContainerLeakDetector.removePrivateObj(self.__dict__) Job.destroy(self) def getPriority(self): return Job.Priorities.Normal def run(self):", "True: yield Job.Sleep def getPathsToContainers(self, name, ot, doneCallback=None): j =", "# top of the while loop from various points yield", "storing multiple redundant refs to a single item if type(curObjRef)", "name = self._leakDetector._id2ref[id].getFinalIndirectionStr() if self._on.lower() in name.lower(): try: for ptc", "object many times but eventually it will discover every object.", "not be examined PrivateIds = set() def __init__(self, name, firstCheckDelay", "relative # of traversals on each set based on how", "ContainerLeakDetector.addPrivateObj(self.__dict__) def destroy(self): ContainerLeakDetector.removePrivateObj(self.__dict__) Job.destroy(self) def getPriority(self): return Job.Priorities.Normal def", "o = None evalStr = '' curObj = None #", "if type(existingRef) not in (types.IntType, types.LongType): if (existingRef.getNumIndirections() >= ref.getNumIndirections()):", "check is too spammy if diff > 20: if diff", "last 5 checks, # send out a warning diff4 =", "for indirection in indirections: yield None indirection.release() if getInstance: lenDict", "return self.evalStr[:-len(instanceDictStr)] # if the previous indirection was an instance", "else: curObj = self._getContainerByEval(evalStr, curObj=curObj) if curObj is None: raise", "too spammy if diff > 20: if diff > idx2id2len[self._index-1][objId]:", "that yields containers a # of times that is #", "without taking a big chunk of CPU time numAttrsLeft =", "leakTask, 'doLeakTask-%s' % serialNum()) if task: return task.done leakTask() class", "= self._leakDetector.getContainerIds() # record the current len of each container", "the full name of an object instanceDictStr = '.__dict__' if", "name, on, doneCallback=None): j = FPTObjsNamed(name, self, on, doneCallback) jobMgr.add(j)", "= [] # are we building off of an existing", "objRef continue if type(curObj) is types.DictType: key = None attr", "you from a container to an element of the container.", "diff5 = idx2id2len[self._index-4][objId] - idx2id2len[self._index-5][objId] if diff > 0 and", "since the dict key might have been garbage-collected TODO: store", "objId def goesThrough(self, obj=None, objId=None): # since we cache the", "is not None: jobMgr.remove(self._pruneContainersJob) self._pruneContainersJob = None if self._checkContainersJob is", "in self._leakDetector.getContainerByIdGen(id): yield None except: pass else: name = self._leakDetector._id2ref[id].getFinalIndirectionStr()", "hold most objects ref = ObjectRef(Indirection(evalStr='__builtin__.__dict__'), id(__builtin__.__dict__)) self._id2baseStartRef[id(__builtin__.__dict__)] = ref", "container, it is now %s (%s)' % (contName, safeRepr(container), e))", "indirection was an instance dict, change our syntax from ['key']", "each indirection # if getInstance is True, will return instance", "the current len of each container to past lens if", "Job import types, weakref, random, __builtin__ def _createContainerLeak(): def leakContainer(task=None):", "in ids: yield None try: for result in self._leakDetector.getContainerByIdGen(objId): yield", "change our syntax from ['key'] to .key if prevIndirection is", "picked the next ref, check if this one is a", "continue # grab the next start ref from this sequence", "handling if random.random() < .01: key = random.choice(base.leakContainer.keys()) ContainerLeakDetector.notify.debug( 'removing", "weakref dict key %s' % keyRepr) self.dictKey = dictKey self._isWeakRef", "= not self._isDeadEnd(attr) if hasLength or notDeadEnd: # prevent cycles", "doneCallback=None): j = FPTObjsNamed(name, self, on, doneCallback) jobMgr.add(j) return j", "how many refs it contains baseLen = len(self._baseStartRefWorkingList.source) discLen =", "in parentDict key = self._getNonWeakDictKey() # objects in __builtin__ will", "raise FailedEval(evalStr) # try to look up this key in", "self._leakDetector.removeContainerById(contId) self._id2ref[contId] = objRef def _addDiscoveredStartRef(self, obj, ref): # we've", "don't handle strings if type(objName) == types.StringType and objName in", "= CheckContainers( '%s-checkForLeaks' % self.getJobName(), self, len(self._index2containerId2len)) self.acceptOnce(self._checkContainersJob.getFinishedEvent(), self._scheduleNextLeakCheck) jobMgr.add(self._checkContainersJob)", "LeakKey: pass base.leakContainer[(LeakKey(),)] = {} # test the non-weakref object", "yielding during the iteration self.notify.debug('could not index into %s with", "_handleLDDestroy(self): self.destroy() def getPriority(self): return Job.Priorities.High def run(self): ids =", "the current objRef parentObjRef = curObjRef # if we hit", "have is more concise than the new ref return if", "from direct.showbase.PythonUtil import Queue, invertDictLossless, makeFlywheelGen from direct.showbase.PythonUtil import itype,", "[] while 1: yield None try: attr = itr.next() except:", "for goesThrough in self.goesThroughGen(obj=obj, objId=objId): pass return goesThrough def _getContainerByEval(self,", "task.done leakContainer() def _createTaskLeak(): leakTaskName = uniqueName('leakedTask') leakDoLaterName = uniqueName('leakedDoLater')", "we should start traversals from often and not-as-often, # respectively", "ObjectRef(Indirection(evalStr='[%s]' % index), id(curObj[index]), parentObjRef) yield None if hasLength: for", "ref is invalid self.notify.debug('invalid startRef, stored as id %s' %", "fastRepr(container, maxLen=CheckContainers.ReprItems))) self.notify.warning(msg) yield None messenger.send(self._leakDetector.getLeakEvent(), [container, name]) if config.GetBool('pdb-on-leak-detect',", "container.__name__ if (self._otn.lower() in cName.lower()): try: for ptc in self._leakDetector.getContainerNameByIdGen(", "return '.%s' % self.evalStr[2:-2] return self.evalStr # we're stored as", "self._baseStartRefWorkingList = ScratchPad(refGen=nullGen(), source=self._id2baseStartRef) self._discoveredStartRefWorkingList = ScratchPad(refGen=nullGen(), source=self._id2discoveredStartRef) self.notify =", "loop right off the bat workingListSelector = nullGen() # this", "= self._indirections for indirection in indirections: indirection.acquire() for indirection in", "key to be looked up in a dict. Each dictionary", "prevIndirection = self._indirections[-2] return self._indirections[-1].getString(prevIndirection=prevIndirection) def __repr__(self): for result in", "ref from this sequence and see if it's still valid", "detector is about to be destroyed return 'cldDestroy-%s' % self._serialNum", "def finished(self): if self._doneCallback: self._doneCallback(self) class FPTObjsNamed(Job): def __init__(self, name,", "0 and diff2 > 0 and diff3 > 0: name", "# if we're an instance dict, skip over this one", "evalStr = '' yield None o = self._getContainerByEval(evalStr, curObj=curObj) if", "the curObj dictionary curObj = indirection.dereferenceDictKey(curObj) evalStr = '' yield", "are found by # the object exploration algorithm, including objects", "self._on.lower() in name.lower(): try: for ptc in self._leakDetector.getContainerNameByIdGen(id): yield None", "= None self._pruneContainersJob = None if firstCheckDelay is None: firstCheckDelay", "is invalid, remove it del _id2baseStartRef[id] _id2discoveredStartRef = self._leakDetector._findContainersJob._id2discoveredStartRef ids", "make sure our indirections don't get destroyed while we're using", "1.5) self._pruneTaskPeriod = config.GetFloat('leak-detector-prune-period', 60. * 30.) # main dict", "we're stored as a dict key keyRepr = safeRepr(self._getNonWeakDictKey()) #", "else: # this eval is not based off of curObj,", "self.notify = self._leakDetector.notify self._index = index ContainerLeakDetector.addPrivateObj(self.__dict__) def destroy(self): ContainerLeakDetector.removePrivateObj(self.__dict__)", "handle on the container by eval'ing and looking things #", "= curObj.__dict__ hasLength = self._hasLength(child) notDeadEnd = not self._isDeadEnd(child) if", "container might lose this element pass if not goesThrough: if", "Python object-graph walker that looks for leaking containers. To reduce", "= None del self._id2ref del self._index2containerId2len del self._index2delay def _getDestroyEvent(self):", "if objId in self._id2ref: if (self._id2ref[objId].getNumIndirections() >= ref.getNumIndirections()): # the", "this holds the current step of the current traversal curObjRef", "= ObjectRef(Indirection(evalStr='simbase.__dict__'), id(simbase.__dict__)) self._id2baseStartRef[id(simbase.__dict__)] = ref for i in self._addContainerGen(simbase.__dict__,", "OK because we are yielding during the iteration self.notify.debug('could not", "fastRepr from direct.showbase.Job import Job import types, weakref, random, __builtin__", "ref return if objId in self._id2ref: if (self._id2ref[objId].getNumIndirections() >= ref.getNumIndirections()):", "chunk of CPU time numKeysLeft = len(keys) + 1 for", "(%s)' % ( contName, e)) self._leakDetector.removeContainerById(objId) continue if container is", "the while loop right off the bat workingListSelector = nullGen()", "( name, itype(container), percent, minutes, idx2id2len[self._index][objId], fastRepr(container, maxLen=CheckContainers.ReprItems))) yield None", "'):' + self.getJobName() + ': ' + ptc except Exception,", "index = -1 attrs = [] while 1: yield None", "yield None indirection.release() if getInstance: lenDict = len('.__dict__') if evalStr[-lenDict:]", "in the references (i.e. base.loader.base) for goesThrough in parentObjRef.goesThrough(curObj[index]): #", "base.leakContainer[(LeakKey(),)] = {} # test the non-weakref object reference handling", "want to make sure they are found by # the", "= '.__dict__' if self.evalStr is not None: # if we're", "a big chunk of CPU time numKeysLeft = len(keys) +", "up in a dict. Each dictionary dereference is individually eval'd", "often and not-as-often, # respectively self._id2baseStartRef = {} self._id2discoveredStartRef =", "not self.goesThrough(objId=objId) self._indirections.append(indirection) # make sure our indirections don't get", "prevent infinite recursion in built-in containers related to methods if", "in ids: yield None try: for container in _id2baseStartRef[id].getContainerGen(): yield", "= curObj.keys() # we will continue traversing the object graph", "memory leak assert type(objId) in (types.IntType, types.LongType) # prevent cycles", "= FindContainers( '%s-findContainers' % self.getJobName(), self) jobMgr.add(self._findContainersJob) self._scheduleNextLeakCheck() self._scheduleNextPruning() while", "skip back to the # top of the while loop", "else: msg = ('leak detected: %s (%s) consistently increased in", "self._indirections.append(ind) # make sure we're not storing a reference to", "example if base.myObject is reassigned # to a different object", "ind.acquire() self.notify.debug(repr(self)) def destroy(self): for indirection in self._indirections: indirection.release() del", "classes don't do well when iterated attr = None break", "PruneObjectRefs( '%s-pruneObjectRefs' % self.getJobName(), self) self.acceptOnce(self._pruneContainersJob.getFinishedEvent(), self._scheduleNextPruning) jobMgr.add(self._pruneContainersJob) return task.done", "self._id2ref[id] def run(self): # start looking for containers self._findContainersJob =", "if we can repr/eval the key, store it as an", "None indirection.acquire() for indirection in indirections: yield None if not", "fw in makeFlywheelGen( startRefWorkingList.source.values(), countFunc=lambda x: self.getStartObjAffinity(x), scale=.05): yield None", "3 5 8 13 21 34 55 89 # *", "\"\"\" Low-priority Python object-graph walker that looks for leaking containers.", "leak detector is about to be destroyed return 'cldDestroy-%s' %", "None and random.randrange(numKeysLeft) == 0: curObjRef = objRef del key", "an instance dict, change our syntax from ['key'] to .key", "self.notify.getDebug(): for contName in self._leakDetector.getContainerNameByIdGen(objId): yield None self.notify.debug( '%s is", "= len(container) except Exception, e: # this container no longer", "set of containers that should not be examined PrivateIds =", "repr/eval'd # that will force the leak detector to hold", "contId not in self._id2ref or len(newRepr) < len(existingRepr): if contId", "= None jobMgr.remove(self._findContainersJob) self._findContainersJob = None del self._id2ref del self._index2containerId2len", "look up a container return self._id2ref[id].getContainerGen(**kwArgs) def getContainerById(self, id): for", "else: msg = ('%s (%s) consistently increased in size over", "attr = None keys = curObj.keys() # we will continue", "idx2id2len[self._index-1][objId] != 0: percent = 100. * (float(diff) / float(idx2id2len[self._index-1][objId]))", "addPrivateObj(cls, obj): cls.PrivateIds.add(id(obj)) @classmethod def removePrivateObj(cls, obj): cls.PrivateIds.remove(id(obj)) def _getCheckTaskName(self):", "= len(self._baseStartRefWorkingList.source) discLen = len(self._discoveredStartRefWorkingList.source) minLen = float(max(1, min(baseLen, discLen)))", "nextIndirection is not None and self.evalStr[-len(instanceDictStr):] == instanceDictStr: return self.evalStr[:-len(instanceDictStr)]", "up here instead of at the end, since we skip", "except: pass else: if hasattr(container, '__class__'): cName = container.__class__.__name__ else:", "goesThrough in parentObjRef.goesThroughGen(child): # don't yield, container might lose this", "self._index2containerId2len del self._index2delay def _getDestroyEvent(self): # sent when leak detector", "off the bat workingListSelector = nullGen() # this holds the", "types.LongType) # prevent cycles (i.e. base.loader.base.loader) assert not self.goesThrough(objId=objId) self._indirections.append(indirection)", "self._leakDetector._id2ref # these hold objects that we should start traversals", "objRef) if curObjRef is None and random.randrange(numAttrsLeft) == 0: curObjRef", "Job.Priorities.Normal def run(self): try: self._leakDetector._index2containerId2len[self._index] = {} ids = self._leakDetector.getContainerIds()", "destroy(self): for indirection in self._indirections: indirection.release() del self._indirections def getNumIndirections(self):", "if getInstance: lenDict = len('.__dict__') if str[-lenDict:] == '.__dict__': str", "etc. See LeakDetectors.py if not hasattr(__builtin__, \"leakDetectors\"): __builtin__.leakDetectors = {}", "0: name = self._leakDetector.getContainerNameById(objId) try: for container in self._leakDetector.getContainerByIdGen(objId): yield", "'' for indirection in indirections: yield None indirection.release() if getInstance:", "ourselves up in parentDict key = self._getNonWeakDictKey() # objects in", "is # proportional to their length for fw in makeFlywheelGen(", "7.6 11.4 17.1 25.6 38.4 57.7 # # delay from", "parentDict): # look ourselves up in parentDict key = self._getNonWeakDictKey()", "in objRef.getEvalStrGen(): yield None if contId not in self._id2ref or", "except TypeError, e: ContainerLeakDetector.notify.debug('could not weakref dict key %s' %", "1 def release(self): self._refCount -= 1 if self._refCount == 0:", "raise yield Job.Done def finished(self): if self._doneCallback: self._doneCallback(self) class PruneObjectRefs(Job):", "current objRef parentObjRef = curObjRef # if we hit a", "leak detector to hold a normal 'non-weak' reference class LeakKey:", "# to a different object after this Ref was created", "no longer valid. Checks validity by asking for each container", "it if id(obj) in ContainerLeakDetector.PrivateIds: return True # prevent crashes", "traversing the object graph via one attr, # choose it", "different object after this Ref was created this would return", "return len(self._indirections) def goesThroughGen(self, obj=None, objId=None): if obj is None:", "store string components that are duplicates of strings in the", "= uniqueName('leakedTask') leakDoLaterName = uniqueName('leakedDoLater') def nullTask(task=None): return task.cont def", "for curObj in curObjRef.getContainerGen(): yield None except: self.notify.debug('lost current container,", "None except: pass else: name = self._leakDetector._id2ref[id].getFinalIndirectionStr() if self._on.lower() in", "not in (types.IntType, types.LongType): if (existingRef.getNumIndirections() >= ref.getNumIndirections()): # the", "types.NoneType, types.NotImplementedType, types.TypeType, types.CodeType, types.FunctionType, types.StringType, types.UnicodeType, types.TupleType): return True", "object we originally pointed to yield self._getContainerByEval(evalStr, curObj=curObj) def getEvalStrGen(self,", "id, getInstance=getInstance): yield None except: pass else: print 'GPTC(' +", "generator that yields containers a # of times that is", "self._index2delay = {} if config.GetBool('leak-container', 0): _createContainerLeak() if config.GetBool('leak-tasks', 0):", "# don't check our own tables for leaks ContainerLeakDetector.addPrivateObj(ContainerLeakDetector.PrivateIds) ContainerLeakDetector.addPrivateObj(self.__dict__)", "leakContainer, 'leakContainer-%s' % serialNum()) if task: return task.done leakContainer() def", "another break # make a generator that yields containers a", "existing ref? if other is not None: for ind in", "yield None continue # grab the next start ref from", "'[%s]' % keyRepr def __repr__(self): return self.getString() class ObjectRef: \"\"\"", "113.3 171 self._nextCheckDelay = self._nextCheckDelay * self._checkDelayScale def _checkForLeaks(self, task=None):", "ref # if we already are storing a reference to", "weakref.ref(dictKey) self._isWeakRef = True except TypeError, e: ContainerLeakDetector.notify.debug('could not weakref", "0: # ref set is empty, choose another break #", "id(o) == objId def goesThrough(self, obj=None, objId=None): # since we", "exception: %s' % e if __dev__: raise yield Job.Done def", "del self._indirections def getNumIndirections(self): return len(self._indirections) def goesThroughGen(self, obj=None, objId=None):", "def destroy(self): ContainerLeakDetector.removePrivateObj(self.__dict__) Job.destroy(self) def getPriority(self): return Job.Priorities.Low @staticmethod def", "self._findContainersJob = None del self._id2ref del self._index2containerId2len del self._index2delay def", "idx2id2len[self._index-1][objId] \"\"\" # this check is too spammy if diff", "during the iteration self.notify.debug('could not index into %s with key", "from various points yield None #import pdb;pdb.set_trace() if curObjRef is", "internal object, ignore it if id(obj) in ContainerLeakDetector.PrivateIds: return True", "pdb;pdb.set_trace() pass except Exception, e: print 'CheckContainers job caught exception:", "= container.__class__.__name__ else: cName = container.__name__ if (self._otn.lower() in cName.lower()):", "random walk of the Python objects to discover containers rather", "if len(self._indirections) > 1: prevIndirection = self._indirections[-2] return self._indirections[-1].getString(prevIndirection=prevIndirection) def", "raise yield Job.Done class FPTObjsOfType(Job): def __init__(self, name, leakDetector, otn,", "ptc except Exception, e: print 'FPTObjsOfType job caught exception: %s'", "self._leakDetector.removeContainerById(objId) continue if container is None: # this container no", "# if getInstance is True, will return instance instead of", "= doneCallback self._ldde = self._leakDetector._getDestroyEvent() self.accept(self._ldde, self._handleLDDestroy) ContainerLeakDetector.addPrivateObj(self.__dict__) def destroy(self):", "curObjRef is None: notDeadEnd = not self._isDeadEnd(attr) if hasLength or", "%s' % e if __dev__: raise yield Job.Done class FPTObjsOfType(Job):", "on the container by eval'ing and looking things # up", "indirections: yield None indirection.release() yield str def getFinalIndirectionStr(self): prevIndirection =", "proportional to their length for fw in makeFlywheelGen( startRefWorkingList.source.values(), countFunc=lambda", "as a dict key keyRepr = safeRepr(self._getNonWeakDictKey()) # if the", "use an instance # since it can't be repr/eval'd #", "__repr__(self): return self.getString() class ObjectRef: \"\"\" stores a reference to", "new, or the objRef repr is shorter than what we", "None try: attr = itr.next() except: # some custom classes", "= workingListSelector.next() except StopIteration: # do relative # of traversals", "FPTObjsNamed(name, self, on, doneCallback) jobMgr.add(j) return j def _scheduleNextLeakCheck(self): taskMgr.doMethodLater(self._nextCheckDelay,", "instance dict, skip over this one (obj.__dict__[keyName] == obj.keyName) if", "if other is not None: for ind in other._indirections: self._indirections.append(ind)", "curObjRef = objRef del key del attr continue try: childNames", "> 0: name = self._leakDetector.getContainerNameById(objId) try: for container in self._leakDetector.getContainerByIdGen(objId):", "self.getString() class ObjectRef: \"\"\" stores a reference to a container", "goesThrough(self, obj=None, objId=None): # since we cache the ids involved", "self.destroy() def getPriority(self): return Job.Priorities.High def run(self): ids = self._leakDetector.getContainerIds()", "self._getContainerByEval(evalStr, curObj=curObj) if id(o) == objId: break for indirection in", "pdb;pdb.set_trace() evalStr = '' curObj = None # make sure", "and diff4 > 0 and diff5 > 0: name =", "namespace # put __builtin__ at the start if it's not", "else: nextIndirection = None str += curIndirection.getString(prevIndirection=prevIndirection, nextIndirection=nextIndirection) if getInstance:", "def _createContainerLeak(): def leakContainer(task=None): base = getBase() if not hasattr(base,", "ids = self._leakDetector.getContainerIds() # record the current len of each", "ids: yield None try: for container in _id2baseStartRef[id].getContainerGen(): yield None", "valid while True: yield None try: curObjRef = startRefWorkingList.refGen.next() break", "various points yield None #import pdb;pdb.set_trace() if curObjRef is None:", "base.loader.base.loader) assert not self.goesThrough(objId=objId) self._indirections.append(indirection) # make sure our indirections", "= self._leakDetector._id2ref # these hold objects that we should start", "store a copy of the current objRef parentObjRef = curObjRef", "so that our iterations aren't disturbed by changes to the", "x: self.getStartObjAffinity(x), scale=.05): yield None startRefWorkingList.refGen = fw if curObjRef", "not None: # if we're an instance dict, skip over", "return result def getContainerNameByIdGen(self, id, **kwArgs): return self._id2ref[id].getEvalStrGen(**kwArgs) def getContainerNameById(self,", "prevIndirection is not None and prevIndirection.evalStr is not None: if", "== objId: break for indirection in indirections: yield None indirection.release()", "obj.keyName) if nextIndirection is not None and self.evalStr[-len(instanceDictStr):] == instanceDictStr:", "None: raise FailedEval(evalStr) # try to look up this key", "if idx2id2len[self._index-1][objId] != 0: percent = 100. * (float(diff) /", "str = str[:-lenDict] for indirection in indirections: yield None indirection.release()", "cycles in the references (i.e. base.loader.base) for goesThrough in parentObjRef.goesThroughGen(curObj[key]):", "try: # this yields a different set of start refs", "in parentObjRef.goesThroughGen(curObj[key]): # don't yield, container might lose this element", "find potential leaks; sub-job of ContainerLeakDetector \"\"\" ReprItems = 5", "# we will continue traversing the object graph via one", "hasattr(__builtin__, \"leakDetectors\"): __builtin__.leakDetectors = {} ref = ObjectRef(Indirection(evalStr='leakDetectors'), id(leakDetectors)) self._id2baseStartRef[id(leakDetectors)]", "= self._hasLength(attr) notDeadEnd = False # if we haven't picked", "of the container if possible stored as a series of", "break attrs.append(attr) # we will continue traversing the object graph", "StopIteration, e: pass del itr continue except Exception, e: print", "ids = _id2baseStartRef.keys() for id in ids: yield None try:", "to go look up the object in _id2ref? sometimes we", "- idx2id2len[self._index-3][objId] if self._index <= 4: if diff > 0", "on, doneCallback) jobMgr.add(j) return j def _scheduleNextLeakCheck(self): taskMgr.doMethodLater(self._nextCheckDelay, self._checkForLeaks, self._getCheckTaskName())", "self._findContainersJob = FindContainers( '%s-findContainers' % self.getJobName(), self) jobMgr.add(self._findContainersJob) self._scheduleNextLeakCheck() self._scheduleNextPruning()", "len(newRepr) < len(existingRepr): if contId in self._id2ref: self._leakDetector.removeContainerById(contId) self._id2ref[contId] =", "-= 1 hasLength = self._hasLength(attr) notDeadEnd = False if curObjRef", "leakDetector self._id2ref = self._leakDetector._id2ref # these hold objects that we", "if obj is None: assert type(objId) in (types.IntType, types.LongType) else:", "safeRepr(self._getNonWeakDictKey()) # if the previous indirection was an instance dict,", "indirections[i+1] else: nextIndirection = None str += curIndirection.getString(prevIndirection=prevIndirection, nextIndirection=nextIndirection) if", "id %s' % startId) self._leakDetector.removeContainerById(startId) continue curObjRef = containerRef try:", "maxLen=CheckContainers.ReprItems))) self.notify.warning(msg) yield None messenger.send(self._leakDetector.getLeakEvent(), [container, name]) if config.GetBool('pdb-on-leak-detect', 0):", "one is a candidate if curObjRef is None: notDeadEnd =", "objRef.getEvalStrGen(): yield None if contId not in self._id2ref or len(newRepr)", "types.LongType): startId = curObjRef curObjRef = None try: for containerRef", "def _pruneObjectRefs(self, task=None): self._pruneContainersJob = PruneObjectRefs( '%s-pruneObjectRefs' % self.getJobName(), self)", "since they can't be weakref'd, and use an instance #", "full name of an object instanceDictStr = '.__dict__' if self.evalStr", "if contId in self._id2ref: self._leakDetector.removeContainerById(contId) self._id2ref[contId] = objRef def _addDiscoveredStartRef(self,", "if it's not already there bis = '__builtin__' if evalStr[:len(bis)]", "to the key self.dictKey = weakref.ref(dictKey) self._isWeakRef = True except", "up the base containers, the ones that hold most objects", "TODO self.notify.debug('caught exception in getContainerByIdGen (2)') else: msg = ('%s", "= ('leak detected: %s (%s) consistently increased in size over", "# respectively self._id2baseStartRef = {} self._id2discoveredStartRef = {} # these", "# choose an object to start a traversal from try:", "0: idx2id2len = self._leakDetector._index2containerId2len for objId in idx2id2len[self._index]: yield None", "the current len of each container for objId in ids:", "curObj, use the global__builtin__ namespace # put __builtin__ at the", "TODO: check that this is still the object we originally", "id in ids: getInstance = (self._otn.lower() not in 'dict') yield", "the # top of the while loop from various points", "hasattr(base, 'leakContainer'): base.leakContainer = {} # use tuples as keys", "we've discovered an object that can be used to start", "try: simbase except: pass else: ref = ObjectRef(Indirection(evalStr='simbase.__dict__'), id(simbase.__dict__)) self._id2baseStartRef[id(simbase.__dict__)]", "# sent when leak detector is about to be destroyed", "className = obj.__class__.__name__ except: pass else: # prevent infinite recursion", "if __dev__: raise yield Job.Done class FPTObjsOfType(Job): def __init__(self, name,", "return repr(self._id2ref[id]) return '<unknown container>' def removeContainerById(self, id): if id", "the new ref return if objId in self._id2ref: if (self._id2ref[objId].getNumIndirections()", "to start a traversal from try: startRefWorkingList = workingListSelector.next() except", "else: ref = ObjectRef(Indirection(evalStr='base.__dict__'), id(base.__dict__)) self._id2baseStartRef[id(base.__dict__)] = ref for i", "if random.random() < .01: key = random.choice(base.leakContainer.keys()) ContainerLeakDetector.notify.debug( 'removing reference", "in self._id2ref: self._leakDetector.removeContainerById(contId) self._id2ref[contId] = objRef def _addDiscoveredStartRef(self, obj, ref):", "getContainerById(self, id): for result in self._id2ref[id].getContainerGen(): pass return result def", "element of the container. Stored as a string to be", "diff3 = idx2id2len[self._index-2][objId] - idx2id2len[self._index-3][objId] if self._index <= 4: if", "del self._index2containerId2len del self._index2delay def _getDestroyEvent(self): # sent when leak", "def __init__(self, name, leakDetector, index): Job.__init__(self, name) self._leakDetector = leakDetector", "if hasattr(container, '__class__'): cName = container.__class__.__name__ else: cName = container.__name__", "that can be used to start an object graph traversal", "% ( parentObjRef, safeRepr(key))) continue hasLength = self._hasLength(attr) notDeadEnd =", "that hold most objects ref = ObjectRef(Indirection(evalStr='__builtin__.__dict__'), id(__builtin__.__dict__)) self._id2baseStartRef[id(__builtin__.__dict__)] =", "# reference is invalid, remove it del _id2discoveredStartRef[id] except Exception,", "self._checkContainersJob = None jobMgr.remove(self._findContainersJob) self._findContainersJob = None del self._id2ref del", "for container in self._leakDetector.getContainerByIdGen( id, getInstance=getInstance): yield None except: pass", "self._id2ref: self._leakDetector.removeContainerById(contId) self._id2ref[contId] = objRef def _addDiscoveredStartRef(self, obj, ref): #", "container in self._leakDetector.getContainerByIdGen( id, getInstance=getInstance): yield None except: pass else:", "ContainerLeakDetector.removePrivateObj(self.__dict__) Job.destroy(self) def getPriority(self): return Job.Priorities.Low @staticmethod def getStartObjAffinity(startObj): #", "be repr/eval'd # that will force the leak detector to", "def _addContainerGen(self, cont, objRef): contId = id(cont) # if this", "in %.2f minutes (%s items at last measurement, current contents:", "_addDiscoveredStartRef(self, obj, ref): # we've discovered an object that can", "exception in getContainerById (%s)' % ( contName, e)) self._leakDetector.removeContainerById(objId) continue", "0: prevIndirection = indirections[i-1] else: prevIndirection = None curIndirection =", "leakDetector, index): Job.__init__(self, name) self._leakDetector = leakDetector self.notify = self._leakDetector.notify", "if i > 0: prevIndirection = indirections[i-1] else: prevIndirection =", "ContainerLeakDetector.removePrivateObj(self.__dict__) Job.destroy(self) def getPriority(self): return Job.Priorities.Normal def run(self): try: self._leakDetector._index2containerId2len[self._index]", "items at last measurement, current contents: %s)' % (name, itype(container),", "grab the next start ref from this sequence and see", "NoDictKey # is the dictKey a weak reference? self._isWeakRef =", "good of a starting object is this object for traversing", "self._doneCallback = None ContainerLeakDetector.removePrivateObj(self.__dict__) Job.destroy(self) def _handleLDDestroy(self): self.destroy() def getPriority(self):", "self.dictKey = dictKey self._isWeakRef = False def destroy(self): # re-entrant", "destroy(self): # re-entrant self.dictKey = NoDictKey def acquire(self): self._refCount +=", "57.7 # # delay from job start # fib: 1", "# this ref set is empty, choose another # the", "print 'GPTC(' + self._otn + '):' + self.getJobName() + ':", "objRef): yield None if notDeadEnd: self._addDiscoveredStartRef(attr, objRef) if curObjRef is", "over this one (obj.__dict__[keyName] == obj.keyName) if nextIndirection is not", "eval is not based off of curObj, use the global__builtin__", "leakTaskName=leakTaskName): base = getBase() taskMgr.add(nullTask, uniqueName(leakTaskName)) taskMgr.doMethodLater(1 << 31, nullDoLater,", "idx2id2len[self._index][objId], fastRepr(container, maxLen=CheckContainers.ReprItems))) self.notify.warning(msg) yield None elif (objId in idx2id2len[self._index-4]", "size over the last ' '3 periods (%s items at", "None self.notify.debug( '%s no longer exists; caught exception in getContainerById", "curIndirection.getString(prevIndirection=prevIndirection, nextIndirection=nextIndirection) if getInstance: lenDict = len('.__dict__') if str[-lenDict:] ==", "% keyRepr) self.dictKey = dictKey self._isWeakRef = False def destroy(self):", "Job.destroy(self) def _handleLDDestroy(self): self.destroy() def getPriority(self): return Job.Priorities.High def run(self):", "run(self): ids = self._leakDetector.getContainerIds() try: for id in ids: getInstance", "attrs.append(attr) # we will continue traversing the object graph via", "None: assert type(objId) in (types.IntType, types.LongType) else: objId = id(obj)", "ref = ObjectRef(Indirection(evalStr='simbase.__dict__'), id(simbase.__dict__)) self._id2baseStartRef[id(simbase.__dict__)] = ref for i in", "random without taking a big chunk of CPU time numKeysLeft", "= (self._leakDetector._index2delay[self._index] - self._leakDetector._index2delay[self._index-1]) / 60. name = self._leakDetector.getContainerNameById(objId) if", "result def getContainerNameByIdGen(self, id, **kwArgs): return self._id2ref[id].getEvalStrGen(**kwArgs) def getContainerNameById(self, id):", "an evalStr self.evalStr = '[%s]' % keyRepr else: try: #", "'__builtin__' if evalStr[:len(bis)] != bis: evalStr = '%s.%s' % (bis,", "return None except AttributeError, ae: return None except KeyError, ke:", "self.notify.debug('--> %s' % curObjRef) #import pdb;pdb.set_trace() # store a copy", "if evalStr[:len(bis)] != bis: evalStr = '%s.%s' % (bis, evalStr)", "because we are yielding during the iteration self.notify.debug('could not index", "getInstance = (self._otn.lower() not in 'dict') yield None try: for", "objName in ('im_self', 'im_class'): return True try: className = obj.__class__.__name__", "None if hasattr(curObj, '__dict__'): child = curObj.__dict__ hasLength = self._hasLength(child)", "print 'FindContainers job caught exception: %s' % e if __dev__:", "run(self): ids = self._leakDetector.getContainerIds() try: for id in ids: yield", "idx2id2len[self._index-3]): diff2 = idx2id2len[self._index-1][objId] - idx2id2len[self._index-2][objId] diff3 = idx2id2len[self._index-2][objId] -", "we building off of an existing ref? if other is", "attr = None break attrs.append(attr) # we will continue traversing", "leakDetector, on, doneCallback=None): Job.__init__(self, name) self._leakDetector = leakDetector self.notify =", "not NoDictKey: # if we can repr/eval the key, store", "= not self._isDeadEnd(attr, key) if hasLength or notDeadEnd: # prevent", "except AttributeError, ae: return None except KeyError, ke: return None", "len(self._indirections) > 1: prevIndirection = self._indirections[-2] return self._indirections[-1].getString(prevIndirection=prevIndirection) def __repr__(self):", "the first check just takes length measurements and # doesn't", "**kwArgs): # return a generator to look up a container", "name = self._leakDetector.getContainerNameById(objId) if idx2id2len[self._index-1][objId] != 0: percent = 100.", "this ref set is empty, choose another # the base", "\"\"\" stores a reference to a container in a way", "it del _id2discoveredStartRef[id] except Exception, e: print 'PruneObjectRefs job caught", "str = '' prevIndirection = None curIndirection = None nextIndirection", "_scheduleNextLeakCheck(self): taskMgr.doMethodLater(self._nextCheckDelay, self._checkForLeaks, self._getCheckTaskName()) # delay between checks # fib:", "indirection in indirections: yield None indirection.release() yield id(o) == objId", "collection of the container if possible stored as a series", "'containerLeakDetected-%s' % self._serialNum @classmethod def addPrivateObj(cls, obj): cls.PrivateIds.add(id(obj)) @classmethod def", "job self._index2containerId2len = {} self._index2delay = {} if config.GetBool('leak-container', 0):", "to check container sizes and find potential leaks; sub-job of", "they can't be weakref'd, and use an instance # since", "big chunk of CPU time numKeysLeft = len(keys) + 1", "* 1.5: 1 2.5 4.75 8.1 13.2 20.8 32.2 49.3", "# TODO self.notify.debug('caught exception in getContainerByIdGen (3)') else: msg =", "startRefWorkingList.source.values(), countFunc=lambda x: self.getStartObjAffinity(x), scale=.05): yield None startRefWorkingList.refGen = fw", "_pruneObjectRefs(self, task=None): self._pruneContainersJob = PruneObjectRefs( '%s-pruneObjectRefs' % self.getJobName(), self) self.acceptOnce(self._pruneContainersJob.getFinishedEvent(),", "(obj.foo -> '.foo', dict[key] -> '[key]', etc.) \"\"\" notify =", "memory usage, scene graph size, # framerate, etc. See LeakDetectors.py", "class CheckContainers(Job): \"\"\" Job to check container sizes and find", "name, ot, doneCallback=None): j = FPTObjsOfType(name, self, ot, doneCallback) jobMgr.add(j)", "is about to be destroyed return 'cldDestroy-%s' % self._serialNum def", "yield None try: for container in self._leakDetector.getContainerByIdGen( id, getInstance=getInstance): yield", "To reduce memory usage, this does a random walk of", "> 0 and diff3 > 0: name = self._leakDetector.getContainerNameById(objId) try:", "getContainerById returned None' % contName) self._leakDetector.removeContainerById(objId) continue try: cLen =", "self._getCheckTaskName()) # delay between checks # fib: 1 1 2", "it in the table if contId in self._id2ref: for existingRepr", "= getBase() if not hasattr(base, 'leakContainer'): base.leakContainer = {} #", "if parentDict is None: return key return parentDict[key] def getString(self,", "# prevent cycles in the references (i.e. base.loader.base) for goesThrough", "1.5: 1 2.5 4.75 8.1 13.2 20.8 32.2 49.3 74.9", "copy and reduce memory usage \"\"\" def __init__(self, evalStr=None, dictKey=NoDictKey):", "curObj is None: raise FailedEval(evalStr) # try to look up", "see if it's still valid while True: yield None try:", "2.5 4.75 8.1 13.2 20.8 32.2 49.3 74.9 113.3 171", "objRef def _addDiscoveredStartRef(self, obj, ref): # we've discovered an object", "= len(self._discoveredStartRefWorkingList.source) minLen = float(max(1, min(baseLen, discLen))) # this will", "e if __dev__: raise yield Job.Done class CheckContainers(Job): \"\"\" Job", "element pass if not goesThrough: objRef = ObjectRef(Indirection(evalStr='[%s]' % index),", "go look up the object in _id2ref? sometimes we do", "% ( name, itype(container), percent, minutes, idx2id2len[self._index][objId], fastRepr(container, maxLen=CheckContainers.ReprItems))) yield", "' + ptc except Exception, e: print 'FPTObjsOfType job caught", "(2)') else: msg = ('%s (%s) consistently increased in size", "Job.__init__(self, name) self._serialNum = serialNum() self._findContainersJob = None self._checkContainersJob =", "= ObjectRef(Indirection(dictKey=key), id(curObj[key]), parentObjRef) yield None if hasLength: for i", "Exception, e: print 'FPTObjsOfType job caught exception: %s' % e", "= _id2baseStartRef.keys() for id in ids: yield None try: for", "indirection in self._indirections: indirection.release() del self._indirections def getNumIndirections(self): return len(self._indirections)", "e if __dev__: raise yield Job.Done class ContainerLeakDetector(Job): \"\"\" Low-priority", "eval(keyRepr) useEval = True except: pass if useEval: # check", "= indirections[i+1] else: nextIndirection = None str += curIndirection.getString(prevIndirection=prevIndirection, nextIndirection=nextIndirection)", "else: objRef = ObjectRef(Indirection(dictKey=key), id(curObj[key]), parentObjRef) yield None if hasLength:", "the base set should never be empty (__builtin__ etc.) continue", "many refs it contains baseLen = len(self._baseStartRefWorkingList.source) discLen = len(self._discoveredStartRefWorkingList.source)", "don't check our own tables for leaks ContainerLeakDetector.addPrivateObj(ContainerLeakDetector.PrivateIds) ContainerLeakDetector.addPrivateObj(self.__dict__) self.setPriority(Job.Priorities.Min)", "time numKeysLeft = len(keys) + 1 for key in keys:", "# record the current len of each container for objId", "* 30.) # main dict of id(container)->containerRef self._id2ref = {}", "for results of check-container job self._index2containerId2len = {} self._index2delay =", "keyRepr = safeRepr(dictKey) useEval = False try: keyEval = eval(keyRepr)", "cycles (i.e. base.loader.base.loader) assert not self.goesThrough(objId=objId) self._indirections.append(indirection) # make sure", "goesThroughGen(self, obj=None, objId=None): if obj is None: assert type(objId) in", "longer exists if self.notify.getDebug(): for contName in self._leakDetector.getContainerNameByIdGen(objId): yield None", "generator to look up a container return self._id2ref[id].getContainerGen(**kwArgs) def getContainerById(self,", "not None: jobMgr.remove(self._checkContainersJob) self._checkContainersJob = None jobMgr.remove(self._findContainersJob) self._findContainersJob = None", "was an instance dict, change our syntax from ['key'] to", "yield None self.notify.debug( '%s is no longer a container, it", "except: pass else: ref = ObjectRef(Indirection(evalStr='simbase.__dict__'), id(simbase.__dict__)) self._id2baseStartRef[id(simbase.__dict__)] = ref", "(bis, evalStr) try: container = eval(evalStr) except NameError, ne: return", "'<unknown container>' def removeContainerById(self, id): if id in self._id2ref: self._id2ref[id].destroy()", "# proportional to their length for fw in makeFlywheelGen( startRefWorkingList.source.values(),", "leakTaskName = uniqueName('leakedTask') leakDoLaterName = uniqueName('leakedDoLater') def nullTask(task=None): return task.cont", "%s with key %s' % ( parentObjRef, safeRepr(key))) continue hasLength", "fastRepr(container, maxLen=CheckContainers.ReprItems))) self.notify.warning(msg) yield None elif (objId in idx2id2len[self._index-4] and", "that Python will keep one copy and reduce memory usage", "class FindContainers(Job): \"\"\" Explore the Python graph, looking for objects", "' '3 periods (%s items at last measurement, current contents:", "# store a weakref to the key self.dictKey = weakref.ref(dictKey)", "(self._otn.lower() in cName.lower()): try: for ptc in self._leakDetector.getContainerNameByIdGen( id, getInstance=getInstance):", "None: # if we're an instance dict, skip over this", "import directNotify from direct.showbase.PythonUtil import Queue, invertDictLossless, makeFlywheelGen from direct.showbase.PythonUtil", "check container sizes and find potential leaks; sub-job of ContainerLeakDetector", "looking for objects that support __len__() \"\"\" def __init__(self, name,", "reference to this object, don't store a second reference if", "None indirection.release() yield id(o) == objId def goesThrough(self, obj=None, objId=None):", "pass return goesThrough def _getContainerByEval(self, evalStr, curObj=None): if curObj is", "the dict key might have been garbage-collected TODO: store string", "_id2baseStartRef.keys() for id in ids: yield None try: for container", "destroy(self): messenger.send(self._getDestroyEvent()) self.ignoreAll() if self._pruneContainersJob is not None: jobMgr.remove(self._pruneContainersJob) self._pruneContainersJob", "for result in self._leakDetector.getContainerByIdGen(objId): yield None container = result except", "name, itype(container), percent, minutes, idx2id2len[self._index][objId], fastRepr(container, maxLen=CheckContainers.ReprItems))) yield None \"\"\"", "= getBase() taskMgr.add(nullTask, uniqueName(leakTaskName)) taskMgr.doMethodLater(1 << 31, nullDoLater, uniqueName(leakDoLaterName)) taskMgr.doMethodLater(10,", "memory usage, this does a random walk of the Python", "except StopIteration: # we've run out of refs, grab a", "to hold a normal 'non-weak' reference class LeakKey: pass base.leakContainer[(LeakKey(),)]", "+ self._otn + '):' + self.getJobName() + ': ' +", "= self._leakDetector.getContainerIds() try: for id in ids: getInstance = (self._otn.lower()", "pass return result def getContainerNameByIdGen(self, id, **kwArgs): return self._id2ref[id].getEvalStrGen(**kwArgs) def", "if self.notify.getDebug(): for contName in self._leakDetector.getContainerNameByIdGen(objId): yield None self.notify.debug('%s no", "self.getJobName(), self, len(self._index2containerId2len)) self.acceptOnce(self._checkContainersJob.getFinishedEvent(), self._scheduleNextLeakCheck) jobMgr.add(self._checkContainersJob) return task.done def _scheduleNextPruning(self):", "a traversal from try: startRefWorkingList = workingListSelector.next() except StopIteration: #", "self.notify.debug('could not index into %s with key %s' % (", "False def destroy(self): # re-entrant self.dictKey = NoDictKey def acquire(self):", "hasLength: for i in self._addContainerGen(attr, objRef): yield None if notDeadEnd:", "prevIndirection=None, nextIndirection=None): # return our contribution to the full name", "# sent when a leak is detected # passes description", "stored as id %s' % startId) self._leakDetector.removeContainerById(startId) continue curObjRef =", "takes length measurements and # doesn't check for leaks self._nextCheckDelay", "cName.lower()): try: for ptc in self._leakDetector.getContainerNameByIdGen( id, getInstance=getInstance): yield None", "0: self.destroy() def isDictKey(self): # is this an indirection through", "exception in getContainerByIdGen (3)') else: msg = ('leak detected: %s", "for leaking containers. To reduce memory usage, this does a", "'' yield None o = self._getContainerByEval(evalStr, curObj=curObj) if id(o) ==", "obj=None, objId=None): if obj is None: assert type(objId) in (types.IntType,", "# we've run out of refs, grab a new set", "goesThrough: objRef = ObjectRef(Indirection(evalStr='.__dict__'), id(child), parentObjRef) yield None if hasLength:", "try: for container in self._leakDetector.getContainerByIdGen(objId): yield None except: # TODO", "in other._indirections: self._indirections.append(ind) # make sure we're not storing a", "else: name = self._leakDetector._id2ref[id].getFinalIndirectionStr() if self._on.lower() in name.lower(): try: for", "is new, or the objRef repr is shorter than what", "if we haven't picked the next ref, check if this", "obj): cls.PrivateIds.remove(id(obj)) def _getCheckTaskName(self): return 'checkForLeakingContainers-%s' % self._serialNum def _getPruneTaskName(self):", "None if notDeadEnd: self._addDiscoveredStartRef(child, objRef) curObjRef = objRef continue if", "from this sequence and see if it's still valid while", "indirection that brings you from a container to an element", "container. Stored as a string to be used as part", "= len(keys) + 1 for key in keys: yield None", "last measurement, current contents: %s)' % ( name, itype(container), percent,", "= random.choice(base.leakContainer.keys()) ContainerLeakDetector.notify.debug( 'removing reference to leakContainer key %s so", "self._indirections: ind.acquire() self.notify.debug(repr(self)) def destroy(self): for indirection in self._indirections: indirection.release()", "check-container job self._index2containerId2len = {} self._index2delay = {} if config.GetBool('leak-container',", "# up in dictionaries, depending on the type of each", "percent = 100. * (float(diff) / float(idx2id2len[self._index-1][objId])) try: for container", "curObj dictionary curObj = indirection.dereferenceDictKey(curObj) evalStr = '' for indirection", "self.notify = self._leakDetector.notify ContainerLeakDetector.addPrivateObj(self.__dict__) def destroy(self): ContainerLeakDetector.removePrivateObj(self.__dict__) Job.destroy(self) def getPriority(self):", "and objName in ('im_self', 'im_class'): return True try: className =", "safeRepr(key))) continue hasLength = self._hasLength(attr) notDeadEnd = False # if", "idx2id2len[self._index]: yield None if objId in idx2id2len[self._index-1]: diff = idx2id2len[self._index][objId]", "127 255 511 1023 2047 # * 1.5: 1 2.5", "reference to a container in a way that does not", "stored as a series of 'indirections' (obj.foo -> '.foo', dict[key]", "direct.showbase.Job import Job import types, weakref, random, __builtin__ def _createContainerLeak():", "object after this Ref was created this would return #", "id(obj) if objId in self._id2discoveredStartRef: existingRef = self._id2discoveredStartRef[objId] if type(existingRef)", "yields containers a # of times that is # proportional", "to the full name of an object instanceDictStr = '.__dict__'", "is __builtin__.__dict__: objRef = ObjectRef(Indirection(evalStr='%s' % key), id(curObj[key])) else: objRef", "notify = directNotify.newCategory(\"ContainerLeakDetector\") # set of containers that should not", "except: # TODO self.notify.debug('caught exception in getContainerByIdGen (1)') else: self.notify.warning(", "sequence and see if it's still valid while True: yield", "\"\"\" def __init__(self, evalStr=None, dictKey=NoDictKey): # if this is a", "ref # container for objects that want to make sure", "(float(diff) / float(idx2id2len[self._index-1][objId])) try: for container in self._leakDetector.getContainerByIdGen(objId): yield None", "past lens if self._index > 0: idx2id2len = self._leakDetector._index2containerId2len for", "def _hasLength(self, obj): return hasattr(obj, '__len__') def _addContainerGen(self, cont, objRef):", "parentObjRef, safeRepr(key))) continue hasLength = self._hasLength(attr) notDeadEnd = False #", "self._isDeadEnd(attr) if hasLength or notDeadEnd: # prevent cycles in the", "exploration algorithm, including objects that exist # just to measure", "in objects that define __cmp__ and don't handle strings if", "container for objId in ids: yield None try: for result", "indirections = self._indirections for indirection in indirections: indirection.acquire() for i", "indirections[i-1] else: prevIndirection = None curIndirection = indirections[i] if i", "away on us indirections = self._indirections for indirection in indirections:", "choose another # the base set should never be empty", "self._id2ref: self._id2ref[id].destroy() del self._id2ref[id] def run(self): # start looking for", "return '<garbage-collected dict key>' return key def dereferenceDictKey(self, parentDict): #", "be looked up in a dict. Each dictionary dereference is", "print 'FPTObjsNamed job caught exception: %s' % e if __dev__:", "21 34 55 89 # * 2.: 1 2 4", "to the actual object, # that could cause a memory", "existingRef = self._id2discoveredStartRef[objId] if type(existingRef) not in (types.IntType, types.LongType): if", "(name, itype(container), idx2id2len[self._index][objId], fastRepr(container, maxLen=CheckContainers.ReprItems))) self.notify.warning(msg) yield None elif (objId", "measure things such as C++ memory usage, scene graph size,", "an object graph traversal objId = id(obj) if objId in", "dictionary curObj = indirection.dereferenceDictKey(curObj) evalStr = '' yield None o", "None if self._checkContainersJob is not None: jobMgr.remove(self._checkContainersJob) self._checkContainersJob = None", "None jobMgr.remove(self._findContainersJob) self._findContainersJob = None del self._id2ref del self._index2containerId2len del", "self._id2baseStartRef[id(__builtin__.__dict__)] = ref # container for objects that want to", "getInstance=False): # try to get a handle on the container", "over from another container curObjRef = None if hasattr(curObj, '__dict__'):", "ne: return None except AttributeError, ae: return None except KeyError,", "cause a memory leak assert type(objId) in (types.IntType, types.LongType) #", "down the traversals of the larger set by 2/3 minLen", "minutes, idx2id2len[self._index][objId], fastRepr(container, maxLen=CheckContainers.ReprItems))) yield None \"\"\" if (self._index >", "in ids: yield None try: for container in _id2discoveredStartRef[id].getContainerGen(): yield", "self.ignoreAll() if self._pruneContainersJob is not None: jobMgr.remove(self._pruneContainersJob) self._pruneContainersJob = None", "to look up a container return self._id2ref[id].getContainerGen(**kwArgs) def getContainerById(self, id):", "= self._leakDetector._index2containerId2len for objId in idx2id2len[self._index]: yield None if objId", "None continue self.notify.debug('--> %s' % curObjRef) #import pdb;pdb.set_trace() # store", "them for ind in self._indirections: ind.acquire() self.notify.debug(repr(self)) def destroy(self): for", "from job start # fib: 1 2 4 7 12", "to start an object graph traversal objId = id(obj) if", "our contribution to the full name of an object instanceDictStr", "detector to hold a normal 'non-weak' reference class LeakKey: pass", "this one is a candidate if curObjRef is None: notDeadEnd", "this key in the curObj dictionary curObj = indirection.dereferenceDictKey(curObj) evalStr", "_getContainerByEval(self, evalStr, curObj=None): if curObj is not None: # eval('curObj.foo.bar.someDict')", "in self._id2ref or len(newRepr) < len(existingRepr): if contId in self._id2ref:", "self._addContainerGen(child, objRef): yield None if notDeadEnd: self._addDiscoveredStartRef(child, objRef) curObjRef =", "def run(self): try: self._leakDetector._index2containerId2len[self._index] = {} ids = self._leakDetector.getContainerIds() #", "leakTask(task=None, leakTaskName=leakTaskName): base = getBase() taskMgr.add(nullTask, uniqueName(leakTaskName)) taskMgr.doMethodLater(1 << 31,", "us indirections = self._indirections for indirection in indirections: indirection.acquire() for", "key del attr continue try: childNames = dir(curObj) except: pass", "obj): return hasattr(obj, '__len__') def _addContainerGen(self, cont, objRef): contId =", "and objId in idx2id2len[self._index-2] and objId in idx2id2len[self._index-3]): diff2 =", "def destroy(self): self.ignore(self._ldde) self._leakDetector = None self._doneCallback = None ContainerLeakDetector.removePrivateObj(self.__dict__)", "a leak is detected # passes description string as argument", "return None except KeyError, ke: return None return container def", "if notDeadEnd: self._addDiscoveredStartRef(child, objRef) curObjRef = objRef continue if type(curObj)", "# objects in __builtin__ will have parentDict==None if parentDict is", "Job.Priorities.High def run(self): ids = self._leakDetector.getContainerIds() try: for id in", "object graph via one key of the dict, # choose", "= leakDetector self.notify = self._leakDetector.notify ContainerLeakDetector.addPrivateObj(self.__dict__) def destroy(self): ContainerLeakDetector.removePrivateObj(self.__dict__) Job.destroy(self)", "store a second reference if objId in self._id2ref: storedItem =", "at ever-increasing intervals. \"\"\" notify = directNotify.newCategory(\"ContainerLeakDetector\") # set of", "top of the while loop from various points yield None", "except: # ref is invalid self.notify.debug('invalid startRef, stored as id", "pass def __init__(self, indirection, objId, other=None): self._indirections = [] #", "= 0 if dictKey is not NoDictKey: # if we", "key keyRepr = safeRepr(self._getNonWeakDictKey()) # if the previous indirection was", "dictionary? return self.dictKey is not NoDictKey def _getNonWeakDictKey(self): if not", "for traversing the object graph? try: return len(startObj) except: return", "a second reference if objId in self._id2ref: storedItem = objId", "the object graph via one attr, # choose it at", "assert type(objId) in (types.IntType, types.LongType) else: objId = id(obj) o", "in (types.IntType, types.LongType) else: objId = id(obj) o = None", "% self.evalStr[2:-2] return self.evalStr # we're stored as a dict", "e)) self._leakDetector.removeContainerById(objId) continue if container is None: # this container", "refs, grab a new set if len(startRefWorkingList.source) == 0: #", "contents: %s)' % ( name, itype(container), percent, minutes, idx2id2len[self._index][objId], fastRepr(container,", "def _getCheckTaskName(self): return 'checkForLeakingContainers-%s' % self._serialNum def _getPruneTaskName(self): return 'pruneLeakingContainerRefs-%s'", "511 1023 2047 # * 1.5: 1 2.5 4.75 8.1", "for objId in ids: yield None try: for result in", "self._indirections = [] # are we building off of an", "container.__class__.__name__ else: cName = container.__name__ if (self._otn.lower() in cName.lower()): try:", "id in ids: yield None try: for container in self._leakDetector.getContainerByIdGen(id):", "sizes and find potential leaks; sub-job of ContainerLeakDetector \"\"\" ReprItems", "to a single item if type(curObjRef) in (types.IntType, types.LongType): startId", "container in self._leakDetector.getContainerByIdGen(objId): yield None except: # TODO self.notify.debug('caught exception", "most objects ref = ObjectRef(Indirection(evalStr='__builtin__.__dict__'), id(__builtin__.__dict__)) self._id2baseStartRef[id(__builtin__.__dict__)] = ref #", "objects in __builtin__ will have parentDict==None if parentDict is None:", "that does not prevent garbage collection of the container if", "this object for traversing the object graph? try: return len(startObj)", "1.5 2.3 3.4 5.1 7.6 11.4 17.1 25.6 38.4 57.7", "yields a different set of start refs every time we", "def destroy(self): messenger.send(self._getDestroyEvent()) self.ignoreAll() if self._pruneContainersJob is not None: jobMgr.remove(self._pruneContainersJob)", "= len(attrs) + 1 for attr in attrs: yield None", "yield None try: attr = itr.next() except: # some custom", "nextIndirection=None): # return our contribution to the full name of", "that should not be examined PrivateIds = set() def __init__(self,", "None if objId in idx2id2len[self._index-1]: diff = idx2id2len[self._index][objId] - idx2id2len[self._index-1][objId]", "yield None except: # reference is invalid, remove it self._leakDetector.removeContainerById(id)", "# send out a warning diff4 = idx2id2len[self._index-3][objId] - idx2id2len[self._index-4][objId]", "e: print 'FPTObjsOfType job caught exception: %s' % e if", "# container for objects that want to make sure they", "objects to discover containers rather than keep a set of", "we skip back to the # top of the while", "objId in self._id2ref: if (self._id2ref[objId].getNumIndirections() >= ref.getNumIndirections()): # the ref", "return True try: className = obj.__class__.__name__ except: pass else: #", "time numAttrsLeft = len(attrs) + 1 for attr in attrs:", "start a traversal from try: startRefWorkingList = workingListSelector.next() except StopIteration:", "= {} # storage for results of check-container job self._index2containerId2len", "checks # fib: 1 1 2 3 5 8 13", "id in self._id2ref: return repr(self._id2ref[id]) return '<unknown container>' def removeContainerById(self,", "curObjRef is None and random.randrange(numKeysLeft) == 0: curObjRef = objRef", "eval succeeded if hash(keyEval) != hash(dictKey): useEval = False if", "release(self): self._refCount -= 1 if self._refCount == 0: self.destroy() def", "return goesThrough def _getContainerByEval(self, evalStr, curObj=None): if curObj is not", "# the base set should never be empty (__builtin__ etc.)", "diff = idx2id2len[self._index][objId] - idx2id2len[self._index-1][objId] \"\"\" # this check is", "for example if base.myObject is reassigned # to a different", "a different object after this Ref was created this would", "yield None except: self.notify.debug('lost current container, ref.getContainerGen() failed') # that", "is None: notDeadEnd = not self._isDeadEnd(attr) if hasLength or notDeadEnd:", "% e if __dev__: raise yield Job.Done class ContainerLeakDetector(Job): \"\"\"", "Python graph, looking for objects that support __len__() \"\"\" def", "invalid, remove it del _id2baseStartRef[id] _id2discoveredStartRef = self._leakDetector._findContainersJob._id2discoveredStartRef ids =", "return task.done leakContainer() def _createTaskLeak(): leakTaskName = uniqueName('leakedTask') leakDoLaterName =", "for container in self._leakDetector.getContainerByIdGen(id): yield None except: pass else: name", "is not NoDictKey def _getNonWeakDictKey(self): if not self._isWeakRef: return self.dictKey", "if we're an instance dict, skip over this one (obj.__dict__[keyName]", "+ self._on + '):' + self.getJobName() + ': ' +", "None except: pass else: print 'GPTCN(' + self._on + '):'", "get a handle on the container by eval'ing and looking", "hasLength: for i in self._addContainerGen(child, objRef): yield None if notDeadEnd:", "class NoDictKey: pass class Indirection: \"\"\" Represents the indirection that", "cache the ids involved in this reference, # this isn't", "not already there bis = '__builtin__' if evalStr[:len(bis)] != bis:", "# grab the next start ref from this sequence and", "random.randrange(numKeysLeft) == 0: curObjRef = objRef del key del attr", "do relative # of traversals on each set based on", "# of traversals on each set based on how many", "curObjRef is None: # this ref set is empty, choose", "= None ContainerLeakDetector.removePrivateObj(self.__dict__) Job.destroy(self) def _handleLDDestroy(self): self.destroy() def getPriority(self): return", "can't be repr/eval'd # that will force the leak detector", "= nullGen() # this holds the current step of the", "dict, skip over this one (obj.__dict__[keyName] == obj.keyName) if nextIndirection", "self._getContainerByEval(evalStr, curObj=curObj) if curObj is None: raise FailedEval(evalStr) # try", "index ContainerLeakDetector.addPrivateObj(self.__dict__) def destroy(self): ContainerLeakDetector.removePrivateObj(self.__dict__) Job.destroy(self) def getPriority(self): return Job.Priorities.Normal", "self._index > 0: idx2id2len = self._leakDetector._index2containerId2len for objId in idx2id2len[self._index]:", "that are no longer valid. Checks validity by asking for", "isn't perfect, for example if base.myObject is reassigned # to", "def getContainerIds(self): return self._id2ref.keys() def getContainerByIdGen(self, id, **kwArgs): # return", "yield str def getFinalIndirectionStr(self): prevIndirection = None if len(self._indirections) >", "<= 4: if diff > 0 and diff2 > 0", "_id2baseStartRef[id] _id2discoveredStartRef = self._leakDetector._findContainersJob._id2discoveredStartRef ids = _id2discoveredStartRef.keys() for id in", "try: for container in self._leakDetector.getContainerByIdGen(id): yield None except: pass else:", "curObjRef is None: # choose an object to start a", "= self._leakDetector._findContainersJob._id2discoveredStartRef ids = _id2discoveredStartRef.keys() for id in ids: yield", "= firstCheckDelay/2. self._checkDelayScale = config.GetFloat('leak-detector-check-delay-scale', 1.5) self._pruneTaskPeriod = config.GetFloat('leak-detector-prune-period', 60.", "never be empty (__builtin__ etc.) continue # do we need", "ids: yield None try: for result in self._leakDetector.getContainerByIdGen(objId): yield None", "= self._leakDetector._id2ref[id].getFinalIndirectionStr() if self._on.lower() in name.lower(): try: for ptc in", "refs every time we start a new traversal # force", "self._leakDetector.removeContainerById(objId) continue try: cLen = len(container) except Exception, e: #", "pass class Indirection: \"\"\" Represents the indirection that brings you", "keyEval = eval(keyRepr) useEval = True except: pass if useEval:", "curObj=curObj) if id(o) == objId: break for indirection in indirections:", "38.4 57.7 # # delay from job start # fib:", "indirections = self._indirections for indirection in indirections: indirection.acquire() for indirection", "None except: # TODO self.notify.debug('caught exception in getContainerByIdGen (2)') else:", "== obj.keyName) if nextIndirection is not None and self.evalStr[-len(instanceDictStr):] ==", "set if len(startRefWorkingList.source) == 0: # ref set is empty,", "we need to go look up the object in _id2ref?", "(types.IntType, types.LongType) # prevent cycles (i.e. base.loader.base.loader) assert not self.goesThrough(objId=objId)", "__builtin__ def _createContainerLeak(): def leakContainer(task=None): base = getBase() if not", "name, leakDetector, on, doneCallback=None): Job.__init__(self, name) self._leakDetector = leakDetector self.notify", "container = result except Exception, e: # this container no", "leakDoLaterName = uniqueName('leakedDoLater') def nullTask(task=None): return task.cont def nullDoLater(task=None): return", "if size has consistently increased over the last 5 checks,", "infinite recursion in built-in containers related to methods if className", "sets self._baseStartRefWorkingList = ScratchPad(refGen=nullGen(), source=self._id2baseStartRef) self._discoveredStartRefWorkingList = ScratchPad(refGen=nullGen(), source=self._id2discoveredStartRef) self.notify", "return if objId in self._id2ref: if (self._id2ref[objId].getNumIndirections() >= ref.getNumIndirections()): #", "in cName.lower()): try: for ptc in self._leakDetector.getContainerNameByIdGen( id, getInstance=getInstance): yield", "are no longer valid. Checks validity by asking for each", "curObj=None): if curObj is not None: # eval('curObj.foo.bar.someDict') evalStr =", "makeFlywheelGen from direct.showbase.PythonUtil import itype, serialNum, safeRepr, fastRepr from direct.showbase.Job", "leaks self._nextCheckDelay = firstCheckDelay/2. self._checkDelayScale = config.GetFloat('leak-detector-check-delay-scale', 1.5) self._pruneTaskPeriod =", "containers rather than keep a set of all visited objects;", "# if this is a dictionary lookup, pass dictKey instead", "keyRepr = safeRepr(self._getNonWeakDictKey()) # if the previous indirection was an", "self._getContainerByEval(evalStr, curObj=curObj) def getEvalStrGen(self, getInstance=False): str = '' prevIndirection =", "if container is None: # this container no longer exists", "fw if curObjRef is None: # this ref set is", "jobMgr.add(j) return j def _scheduleNextLeakCheck(self): taskMgr.doMethodLater(self._nextCheckDelay, self._checkForLeaks, self._getCheckTaskName()) # delay", "reference is invalid, remove it self._leakDetector.removeContainerById(id) _id2baseStartRef = self._leakDetector._findContainersJob._id2baseStartRef ids", "the last ' '3 periods (%s items at last measurement,", "self, len(self._index2containerId2len)) self.acceptOnce(self._checkContainersJob.getFinishedEvent(), self._scheduleNextLeakCheck) jobMgr.add(self._checkContainersJob) return task.done def _scheduleNextPruning(self): taskMgr.doMethodLater(self._pruneTaskPeriod,", "longer exists; getContainerById returned None' % contName) self._leakDetector.removeContainerById(objId) continue try:", "# set of containers that should not be examined PrivateIds", "start over from another container curObjRef = None if hasattr(curObj,", "ids = self._leakDetector.getContainerIds() try: for id in ids: getInstance =", "except Exception, e: print 'FPTObjsNamed job caught exception: %s' %", "duplicates of strings in the actual system so that Python", "random, __builtin__ def _createContainerLeak(): def leakContainer(task=None): base = getBase() if", "' + ptc except Exception, e: print 'FPTObjsNamed job caught", "-> '[key]', etc.) \"\"\" notify = directNotify.newCategory(\"ObjectRef\") class FailedEval(Exception): pass", "type(existingRef) not in (types.IntType, types.LongType): if (existingRef.getNumIndirections() >= ref.getNumIndirections()): #", "i in xrange(len(indirections)): yield None if i > 0: prevIndirection", "numAttrsLeft -= 1 hasLength = self._hasLength(attr) notDeadEnd = False if", "= ScratchPad(refGen=nullGen(), source=self._id2discoveredStartRef) self.notify = self._leakDetector.notify ContainerLeakDetector.addPrivateObj(self.__dict__) # set up", "self._leakDetector.getContainerByIdGen(id): yield None except: # reference is invalid, remove it", "self._checkContainersJob = CheckContainers( '%s-checkForLeaks' % self.getJobName(), self, len(self._index2containerId2len)) self.acceptOnce(self._checkContainersJob.getFinishedEvent(), self._scheduleNextLeakCheck)", "= cLen # compare the current len of each container", "useEval = True except: pass if useEval: # check to", "self.notify.debug(repr(self)) def destroy(self): for indirection in self._indirections: indirection.release() del self._indirections", "start a new traversal # force creation of a new", "the same object many times but eventually it will discover", "the end, since we skip back to the # top", "in self._addContainerGen(__builtin__.__dict__, ref): pass try: base except: pass else: ref", "a ref to base.myObject.otherObject.myObject for goesThrough in self.goesThroughGen(obj=obj, objId=objId): pass", "Stored as a string to be used as part of", "not None and self.evalStr[-len(instanceDictStr):] == instanceDictStr: return self.evalStr[:-len(instanceDictStr)] # if", "{} if config.GetBool('leak-container', 0): _createContainerLeak() if config.GetBool('leak-tasks', 0): _createTaskLeak() #", "try: for result in self._leakDetector.getContainerByIdGen(objId): yield None container = result", "= self._leakDetector.getContainerNameById(objId) try: for container in self._leakDetector.getContainerByIdGen(objId): yield None except:", "> 0 and diff2 > 0 and diff3 > 0", "> 0 and diff5 > 0: name = self._leakDetector.getContainerNameById(objId) try:", ".01: key = random.choice(base.leakContainer.keys()) ContainerLeakDetector.notify.debug( 'removing reference to leakContainer key", "curObjRef = None try: for containerRef in self._leakDetector.getContainerByIdGen(startId): yield None", "self._scheduleNextPruning() while True: yield Job.Sleep def getPathsToContainers(self, name, ot, doneCallback=None):", "curObj = self._getContainerByEval(evalStr, curObj=curObj) if curObj is None: raise FailedEval(evalStr)", "dict #import pdb;pdb.set_trace() evalStr = '' curObj = None #", "getInstance: lenDict = len('.__dict__') if str[-lenDict:] == '.__dict__': str =", "not-as-often, # respectively self._id2baseStartRef = {} self._id2discoveredStartRef = {} #", "traversal # force creation of a new workingListSelector inside the", "17.1 25.6 38.4 57.7 # # delay from job start", "= dir(curObj) except: pass else: try: index = -1 attrs", "self.notify.debug('caught exception in getContainerByIdGen (2)') else: msg = ('%s (%s)", "keyRepr else: try: # store a weakref to the key", "self._indirections def getNumIndirections(self): return len(self._indirections) def goesThroughGen(self, obj=None, objId=None): if", "objRef del key del attr continue try: childNames = dir(curObj)", "__init__(self, name, leakDetector, on, doneCallback=None): Job.__init__(self, name) self._leakDetector = leakDetector", "containers, the ones that hold most objects ref = ObjectRef(Indirection(evalStr='__builtin__.__dict__'),", "is the dictKey a weak reference? self._isWeakRef = False self._refCount", "self._leakDetector.notify self._otn = otn self._doneCallback = doneCallback self._ldde = self._leakDetector._getDestroyEvent()", "= dictKey self._isWeakRef = False def destroy(self): # re-entrant self.dictKey", "pass def destroy(self): ContainerLeakDetector.removePrivateObj(self.__dict__) Job.destroy(self) def getPriority(self): return Job.Priorities.Low @staticmethod", "it may visit the same object many times but eventually", "jobMgr.remove(self._findContainersJob) self._findContainersJob = None del self._id2ref del self._index2containerId2len del self._index2delay", "self._leakDetector = leakDetector self.notify = self._leakDetector.notify self._on = on self._doneCallback", "last ' '5 periods (%s items at last measurement, current", "directNotify.newCategory(\"ObjectRef\") class FailedEval(Exception): pass def __init__(self, indirection, objId, other=None): self._indirections", "objRef) curObjRef = objRef continue if type(curObj) is types.DictType: key", "is not None: # if we're an instance dict, skip", "lenDict = len('.__dict__') if evalStr[-lenDict:] == '.__dict__': evalStr = evalStr[:-lenDict]", "of traversals on each set based on how many refs", "is None: # choose an object to start a traversal", "None: return '<garbage-collected dict key>' return key def dereferenceDictKey(self, parentDict):", "getString(self, prevIndirection=None, nextIndirection=None): # return our contribution to the full", "= self.dictKey() if key is None: return '<garbage-collected dict key>'", "nextIndirection = None str += curIndirection.getString(prevIndirection=prevIndirection, nextIndirection=nextIndirection) if getInstance: lenDict", "types.StringType, types.UnicodeType, types.TupleType): return True # if it's an internal", "= {} # test the non-weakref object reference handling if", "eval'ing and looking things # up in dictionaries, depending on", "= startRefWorkingList.refGen.next() break except StopIteration: # we've run out of", "exists if self.notify.getDebug(): for contName in self._leakDetector.getContainerNameByIdGen(objId): yield None self.notify.debug(", "None evalStr = '' curObj = None # make sure", "ObjectRef(Indirection(evalStr='%s' % key), id(curObj[key])) else: objRef = ObjectRef(Indirection(dictKey=key), id(curObj[key]), parentObjRef)", "is None: # this ref set is empty, choose another", "doesn't check for leaks self._nextCheckDelay = firstCheckDelay/2. self._checkDelayScale = config.GetFloat('leak-detector-check-delay-scale',", "taskMgr.doMethodLater(self._pruneTaskPeriod, self._pruneObjectRefs, self._getPruneTaskName()) def _pruneObjectRefs(self, task=None): self._pruneContainersJob = PruneObjectRefs( '%s-pruneObjectRefs'", "ids: getInstance = (self._otn.lower() not in 'dict') yield None try:", "key %s so it will be garbage-collected' % safeRepr(key)) del", "not self._isWeakRef: return self.dictKey else: key = self.dictKey() if key", "the current step of the current traversal curObjRef = None", "to make sure the eval succeeded if hash(keyEval) != hash(dictKey):", "o = self._getContainerByEval(evalStr, curObj=curObj) if id(o) == objId: break for", "types.UnicodeType, types.TupleType): return True # if it's an internal object,", "of times that is # proportional to their length for", "not goesThrough: if curObj is __builtin__.__dict__: objRef = ObjectRef(Indirection(evalStr='%s' %", "a set of all visited objects; it may visit the", "instanceDictStr: return self.evalStr[:-len(instanceDictStr)] # if the previous indirection was an", "of a starting object is this object for traversing the", "safeRepr(container), e)) self._leakDetector.removeContainerById(objId) continue self._leakDetector._index2containerId2len[self._index][objId] = cLen # compare the", "and diff2 > 0 and diff3 > 0 and diff4", "except: # reference is invalid, remove it self._leakDetector.removeContainerById(id) _id2baseStartRef =", "if dictKey is not NoDictKey: # if we can repr/eval", "creation of a new workingListSelector inside the while loop right", "return True return False def _hasLength(self, obj): return hasattr(obj, '__len__')", "self._discoveredStartRefWorkingList], [baseLen/minLen, discLen/minLen]) yield None continue # grab the next", "containers self._findContainersJob = FindContainers( '%s-findContainers' % self.getJobName(), self) jobMgr.add(self._findContainersJob) self._scheduleNextLeakCheck()", "* 2.: 1 2 4 8 16 32 64 128", "== 0: self.destroy() def isDictKey(self): # is this an indirection", "in idx2id2len[self._index]: yield None if objId in idx2id2len[self._index-1]: diff =", "!= hash(dictKey): useEval = False if useEval: # eval/repr succeeded,", "notDeadEnd: self._addDiscoveredStartRef(attr, objRef) if curObjRef is None and random.randrange(numAttrsLeft) ==", "= None if firstCheckDelay is None: firstCheckDelay = 60. *", "it can't be repr/eval'd # that will force the leak", "for indirection in self._indirections: indirection.release() del self._indirections def getNumIndirections(self): return", "self.evalStr # we're stored as a dict key keyRepr =", "to make sure they are found by # the object", "('%s (%s) consistently increased in size over the last '", "current len of each container for objId in ids: yield", "curObj.keys() # we will continue traversing the object graph via", "# TODO self.notify.debug('caught exception in getContainerByIdGen (1)') else: self.notify.warning( '%s", "def run(self): # start looking for containers self._findContainersJob = FindContainers(", "self, ot, doneCallback) jobMgr.add(j) return j def getPathsToContainersNamed(self, name, on,", "except StopIteration, e: pass del itr continue except Exception, e:", "len(self._baseStartRefWorkingList.source) discLen = len(self._discoveredStartRefWorkingList.source) minLen = float(max(1, min(baseLen, discLen))) #", "base.loader.base) for goesThrough in parentObjRef.goesThroughGen(child): # don't yield, container might", "current contents: %s)' % (name, itype(container), idx2id2len[self._index][objId], fastRepr(container, maxLen=CheckContainers.ReprItems))) self.notify.warning(msg)", "4 7 12 20 33 54 88 143 232 #", "id in ids: yield None try: for container in _id2baseStartRef[id].getContainerGen():", "Job.destroy(self) def getPriority(self): return Job.Priorities.Normal def run(self): try: ids =", "will have parentDict==None if parentDict is None: return key return", "Explore the Python graph, looking for objects that support __len__()", "None try: for result in self._leakDetector.getContainerByIdGen(objId): yield None container =", "for i in xrange(len(indirections)): yield None if i > 0:", "and use an instance # since it can't be repr/eval'd", "in (types.BooleanType, types.BuiltinFunctionType, types.BuiltinMethodType, types.ComplexType, types.FloatType, types.IntType, types.LongType, types.NoneType, types.NotImplementedType,", "container refs that are no longer valid. Checks validity by", "+ 1 for attr in attrs: yield None index +=", "j def getPathsToContainersNamed(self, name, on, doneCallback=None): j = FPTObjsNamed(name, self,", "1 2 3 5 8 13 21 34 55 89", "depending on the type of each indirection # if getInstance", "bis = '__builtin__' if evalStr[:len(bis)] != bis: evalStr = '%s.%s'", "1 try: attr = curObj[key] except KeyError, e: # this", "# force creation of a new workingListSelector inside the while", "this check is too spammy if diff > 20: if", "'GPTCN(' + self._on + '):' + self.getJobName() + ': '", "= None try: for containerRef in self._leakDetector.getContainerByIdGen(startId): yield None except:", "fib: 1 1 2 3 5 8 13 21 34", "**kwArgs): return self._id2ref[id].getEvalStrGen(**kwArgs) def getContainerNameById(self, id): if id in self._id2ref:", "= '' yield None o = self._getContainerByEval(evalStr, curObj=curObj) if id(o)", "= idx2id2len[self._index-3][objId] - idx2id2len[self._index-4][objId] diff5 = idx2id2len[self._index-4][objId] - idx2id2len[self._index-5][objId] if", "+ 1 for key in keys: yield None numKeysLeft -=", "id, getInstance=getInstance): yield None except: pass else: if hasattr(container, '__class__'):", "does a random walk of the Python objects to discover", "if diff > 20: if diff > idx2id2len[self._index-1][objId]: minutes =", "import types, weakref, random, __builtin__ def _createContainerLeak(): def leakContainer(task=None): base", "return '[%s]' % keyRepr def __repr__(self): return self.getString() class ObjectRef:", "of the container. Stored as a string to be used", "self._isWeakRef: return self.dictKey else: key = self.dictKey() if key is", "objects that exist # just to measure things such as", "NoDictKey: # if we can repr/eval the key, store it", "{} # use tuples as keys since they can't be", "idx2id2len[self._index-1][objId]: minutes = (self._leakDetector._index2delay[self._index] - self._leakDetector._index2delay[self._index-1]) / 60. name =", "don't yield, container might lose this element pass if not", "periods (%s items at last measurement, current contents: %s)' %", "just takes length measurements and # doesn't check for leaks", "might have been garbage-collected TODO: store string components that are", "it del _id2baseStartRef[id] _id2discoveredStartRef = self._leakDetector._findContainersJob._id2discoveredStartRef ids = _id2discoveredStartRef.keys() for", "class ContainerLeakDetector(Job): \"\"\" Low-priority Python object-graph walker that looks for", "id(base.__dict__)) self._id2baseStartRef[id(base.__dict__)] = ref for i in self._addContainerGen(base.__dict__, ref): pass", "= True except: pass if useEval: # check to make", "idx2id2len[self._index-2] and objId in idx2id2len[self._index-3]): diff2 = idx2id2len[self._index-1][objId] - idx2id2len[self._index-2][objId]", "useEval = False try: keyEval = eval(keyRepr) useEval = True", "_getPruneTaskName(self): return 'pruneLeakingContainerRefs-%s' % self._serialNum def getContainerIds(self): return self._id2ref.keys() def", "if not hasattr(base, 'leakContainer'): base.leakContainer = {} # use tuples", "child = curObj.__dict__ hasLength = self._hasLength(child) notDeadEnd = not self._isDeadEnd(child)", "of strings in the actual system so that Python will", "this element pass if not goesThrough: objRef = ObjectRef(Indirection(evalStr='.__dict__'), id(child),", "yield None self.notify.debug( '%s no longer exists; caught exception in", "20.8 32.2 49.3 74.9 113.3 171 self._nextCheckDelay = self._nextCheckDelay *", "= flywheel([self._baseStartRefWorkingList, self._discoveredStartRefWorkingList], [baseLen/minLen, discLen/minLen]) yield None continue # grab", "# try to look up this key in the curObj", "(types.IntType, types.LongType): startId = curObjRef curObjRef = None try: for", "id(container)->containerRef self._id2ref = {} # storage for results of check-container", "'dict') yield None try: for container in self._leakDetector.getContainerByIdGen( id, getInstance=getInstance):", "need to go look up the object in _id2ref? sometimes", "# delay between checks # fib: 1 1 2 3", "self._id2ref: return repr(self._id2ref[id]) return '<unknown container>' def removeContainerById(self, id): if", "8 16 32 64 128 256 512 1024 # *", "getPriority(self): return Job.Priorities.Normal def run(self): try: ids = self._leakDetector.getContainerIds() for", "random.choice(base.leakContainer.keys()) ContainerLeakDetector.notify.debug( 'removing reference to leakContainer key %s so it", "def goesThrough(self, obj=None, objId=None): # since we cache the ids", "attr except StopIteration, e: pass del itr continue except Exception,", "self._nextCheckDelay = firstCheckDelay/2. self._checkDelayScale = config.GetFloat('leak-detector-check-delay-scale', 1.5) self._pruneTaskPeriod = config.GetFloat('leak-detector-prune-period',", "self.dictKey is not NoDictKey def _getNonWeakDictKey(self): if not self._isWeakRef: return", "evalStr = '' for indirection in indirections: yield None indirection.release()", "garbage-collected TODO: store string components that are duplicates of strings", "curObjRef # if we hit a dead end, start over", "0 and diff4 > 0 and diff5 > 0: name", "normal 'non-weak' reference class LeakKey: pass base.leakContainer[(LeakKey(),)] = {} #", "the table if contId in self._id2ref: for existingRepr in self._id2ref[contId].getEvalStrGen():", "step of the current traversal curObjRef = None while True:", "ObjectRef(Indirection(evalStr='simbase.__dict__'), id(simbase.__dict__)) self._id2baseStartRef[id(simbase.__dict__)] = ref for i in self._addContainerGen(simbase.__dict__, ref):", "2 4 7 12 20 33 54 88 143 232", "container in _id2discoveredStartRef[id].getContainerGen(): yield None except: # reference is invalid,", "serialNum() self._findContainersJob = None self._checkContainersJob = None self._pruneContainersJob = None", "in indirections: indirection.acquire() for i in xrange(len(indirections)): yield None if", "we're using them for ind in self._indirections: ind.acquire() self.notify.debug(repr(self)) def", "'5 periods (%s items at last measurement, current contents: %s)'", "type(curObjRef) in (types.IntType, types.LongType): startId = curObjRef curObjRef = None", "self) jobMgr.add(self._findContainersJob) self._scheduleNextLeakCheck() self._scheduleNextPruning() while True: yield Job.Sleep def getPathsToContainers(self,", "curObjRef curObjRef = None try: for containerRef in self._leakDetector.getContainerByIdGen(startId): yield", "= False if curObjRef is None: notDeadEnd = not self._isDeadEnd(attr)", "1 if self._refCount == 0: self.destroy() def isDictKey(self): # is", "0 and diff2 > 0 and diff3 > 0 and", "traversing the object graph via one key of the dict,", "caught exception in getContainerById (%s)' % ( contName, e)) self._leakDetector.removeContainerById(objId)", "self._id2baseStartRef[id(simbase.__dict__)] = ref for i in self._addContainerGen(simbase.__dict__, ref): pass def", "diff5 > 0: name = self._leakDetector.getContainerNameById(objId) try: for container in", "1: yield None try: attr = itr.next() except: # some", "task: return task.done leakTask() class NoDictKey: pass class Indirection: \"\"\"", "self._leakDetector._id2ref[id].getFinalIndirectionStr() if self._on.lower() in name.lower(): try: for ptc in self._leakDetector.getContainerNameByIdGen(id):", "# re-entrant self.dictKey = NoDictKey def acquire(self): self._refCount += 1", "base.leakContainer = {} # use tuples as keys since they", "container curObjRef = None if hasattr(curObj, '__dict__'): child = curObj.__dict__", "curObjRef = None while True: # yield up here instead", "#import pdb;pdb.set_trace() # store a copy of the current objRef", "if self._checkContainersJob is not None: jobMgr.remove(self._checkContainersJob) self._checkContainersJob = None jobMgr.remove(self._findContainersJob)", "so that Python will keep one copy and reduce memory", "else: prevIndirection = None curIndirection = indirections[i] if i <", "curObjRef.getContainerGen(): yield None except: self.notify.debug('lost current container, ref.getContainerGen() failed') #", "yield None if hasLength: for i in self._addContainerGen(child, objRef): yield", "is this object for traversing the object graph? try: return", "< len(existingRepr): if contId in self._id2ref: self._leakDetector.removeContainerById(contId) self._id2ref[contId] = objRef", "ref? if other is not None: for ind in other._indirections:", "curObjRef = startRefWorkingList.refGen.next() break except StopIteration: # we've run out", "caught exception: %s' % e if __dev__: raise yield Job.Done", "del itr continue except Exception, e: print 'FindContainers job caught", "self.evalStr = evalStr self.dictKey = NoDictKey # is the dictKey", "of ContainerLeakDetector \"\"\" ReprItems = 5 def __init__(self, name, leakDetector,", "print 'GPTCN(' + self._on + '):' + self.getJobName() + ':", "increased in size over the last ' '3 periods (%s", "self._refCount += 1 def release(self): self._refCount -= 1 if self._refCount", "= itr.next() except: # some custom classes don't do well", "current step of the current traversal curObjRef = None while", "None: firstCheckDelay = 60. * 15. # divide by two,", "types.BuiltinMethodType, types.ComplexType, types.FloatType, types.IntType, types.LongType, types.NoneType, types.NotImplementedType, types.TypeType, types.CodeType, types.FunctionType,", "size has consistently increased over the last 5 checks, #", "base.myObject.otherObject.myObject for goesThrough in self.goesThroughGen(obj=obj, objId=objId): pass return goesThrough def", "and reduce memory usage \"\"\" def __init__(self, evalStr=None, dictKey=NoDictKey): #", "# * 1.5: 1 1.5 2.3 3.4 5.1 7.6 11.4", "= ref for i in self._addContainerGen(simbase.__dict__, ref): pass def destroy(self):", "if not self._isWeakRef: return self.dictKey else: key = self.dictKey() if", "sometimes we do that # to avoid storing multiple redundant", "# make sure the indirections don't go away on us", "container \"\"\" def __init__(self, name, leakDetector): Job.__init__(self, name) self._leakDetector =", "% e if __dev__: raise yield Job.Done def finished(self): if", "object graph traversal objId = id(obj) if objId in self._id2discoveredStartRef:", "# TODO: check that this is still the object we", "+= curIndirection.getString(prevIndirection=prevIndirection, nextIndirection=nextIndirection) if getInstance: lenDict = len('.__dict__') if str[-lenDict:]", "# the ref that we already have is more concise", "is reassigned # to a different object after this Ref", "one copy and reduce memory usage \"\"\" def __init__(self, evalStr=None,", "dict[key] -> '[key]', etc.) \"\"\" notify = directNotify.newCategory(\"ObjectRef\") class FailedEval(Exception):", "idx2id2len[self._index][objId], fastRepr(container, maxLen=CheckContainers.ReprItems))) yield None \"\"\" if (self._index > 2", "try: className = obj.__class__.__name__ except: pass else: # prevent infinite", "instance # since it can't be repr/eval'd # that will", "a new workingListSelector inside the while loop right off the", "5 def __init__(self, name, leakDetector, index): Job.__init__(self, name) self._leakDetector =", "as argument return 'containerLeakDetected-%s' % self._serialNum @classmethod def addPrivateObj(cls, obj):", "of each container to past lens if self._index > 0:", "except: # TODO self.notify.debug('caught exception in getContainerByIdGen (3)') else: msg", "useEval: # eval/repr succeeded, store as an evalStr self.evalStr =", "workingListSelector inside the while loop right off the bat workingListSelector", "str def getFinalIndirectionStr(self): prevIndirection = None if len(self._indirections) > 1:", "not in self._id2ref or len(newRepr) < len(existingRepr): if contId in", "id(cont) # if this container is new, or the objRef", "just to measure things such as C++ memory usage, scene", "containerRef try: for curObj in curObjRef.getContainerGen(): yield None except: self.notify.debug('lost", "visit the same object many times but eventually it will", "True: yield None try: curObjRef = startRefWorkingList.refGen.next() break except StopIteration:", "ContainerLeakDetector \"\"\" ReprItems = 5 def __init__(self, name, leakDetector, index):", "except KeyError, e: # this is OK because we are", "exist # just to measure things such as C++ memory", "weakref to the key self.dictKey = weakref.ref(dictKey) self._isWeakRef = True", "returned None' % contName) self._leakDetector.removeContainerById(objId) continue try: cLen = len(container)", "if curObjRef is None and random.randrange(numAttrsLeft) == 0: curObjRef =", "what we already have, # put it in the table", "succeeded, store as an evalStr self.evalStr = '[%s]' % keyRepr", "container no longer exists if self.notify.getDebug(): for contName in self._leakDetector.getContainerNameByIdGen(objId):", "# that will force the leak detector to hold a", "new ref return if objId in self._id2ref: if (self._id2ref[objId].getNumIndirections() >=", "pass base.leakContainer[(LeakKey(),)] = {} # test the non-weakref object reference", "longer a container, it is now %s (%s)' % (contName,", "the references (i.e. base.loader.base) for goesThrough in parentObjRef.goesThrough(curObj[index]): # don't", "strings in the actual system so that Python will keep", "grew %.2f%% in %.2f minutes (%s items at last measurement,", "% self._serialNum def getContainerIds(self): return self._id2ref.keys() def getContainerByIdGen(self, id, **kwArgs):", "the object graph? try: return len(startObj) except: return 1 def", "startId) self._leakDetector.removeContainerById(startId) continue curObjRef = containerRef try: for curObj in", "for existingRepr in self._id2ref[contId].getEvalStrGen(): yield None for newRepr in objRef.getEvalStrGen():", "self.notify = self._leakDetector.notify self._otn = otn self._doneCallback = doneCallback self._ldde", "attr continue try: childNames = dir(curObj) except: pass else: try:", "self._id2ref.keys() def getContainerByIdGen(self, id, **kwArgs): # return a generator to", "del self._index2delay def _getDestroyEvent(self): # sent when leak detector is", "= None evalStr = '' curObj = None # make", "framerate, etc. See LeakDetectors.py if not hasattr(__builtin__, \"leakDetectors\"): __builtin__.leakDetectors =", "pass try: simbase except: pass else: ref = ObjectRef(Indirection(evalStr='simbase.__dict__'), id(simbase.__dict__))", "keyRepr return '[%s]' % keyRepr def __repr__(self): return self.getString() class", "other is not None: for ind in other._indirections: self._indirections.append(ind) #", "\"\"\" def __init__(self, name, leakDetector): Job.__init__(self, name) self._leakDetector = leakDetector", "workingListSelector = nullGen() # this holds the current step of", "the traversals of the larger set by 2/3 minLen *=", "'PruneObjectRefs job caught exception: %s' % e if __dev__: raise", "a dictionary lookup, pass dictKey instead of evalStr self.evalStr =", "a reference to a container in a way that does", "for indirection in indirections: yield None indirection.acquire() for indirection in", "in indirections: yield None if not indirection.isDictKey(): # build up", "start refs every time we start a new traversal #", "curObj[key] except KeyError, e: # this is OK because we", "description string as argument return 'containerLeakDetected-%s' % self._serialNum @classmethod def", "a string to be used as part of an eval,", "the ids involved in this reference, # this isn't perfect,", "instead of instance dict #import pdb;pdb.set_trace() evalStr = '' curObj", "more concise than the new ref return if objId in", "def nullTask(task=None): return task.cont def nullDoLater(task=None): return task.done def leakTask(task=None,", "instead of at the end, since we skip back to", "+ ptc except Exception, e: print 'FPTObjsNamed job caught exception:", "different set of start refs every time we start a", "None if contId not in self._id2ref or len(newRepr) < len(existingRepr):", "eval(evalStr) except NameError, ne: return None except AttributeError, ae: return", "pass else: ref = ObjectRef(Indirection(evalStr='simbase.__dict__'), id(simbase.__dict__)) self._id2baseStartRef[id(simbase.__dict__)] = ref for", "direct.showbase.PythonUtil import itype, serialNum, safeRepr, fastRepr from direct.showbase.Job import Job", "ignore it if id(obj) in ContainerLeakDetector.PrivateIds: return True # prevent", "getStartObjAffinity(startObj): # how good of a starting object is this", "min(baseLen, discLen))) # this will cut down the traversals of", "self.dictKey else: key = self.dictKey() if key is None: return", "ContainerLeakDetector.notify.debug( 'removing reference to leakContainer key %s so it will", "not in 'dict') yield None try: for container in self._leakDetector.getContainerByIdGen(", "of CPU time numAttrsLeft = len(attrs) + 1 for attr", "to .key if prevIndirection is not None and prevIndirection.evalStr is", "in size over the last ' '3 periods (%s items", "recursion in built-in containers related to methods if className ==", "= '%s.%s' % (bis, evalStr) try: container = eval(evalStr) except", "not prevent garbage collection of the container if possible stored", "using them for ind in self._indirections: ind.acquire() self.notify.debug(repr(self)) def destroy(self):", "pass else: ref = ObjectRef(Indirection(evalStr='base.__dict__'), id(base.__dict__)) self._id2baseStartRef[id(base.__dict__)] = ref for", "= leakDetector self.notify = self._leakDetector.notify self._index = index ContainerLeakDetector.addPrivateObj(self.__dict__) def", "an object to start a traversal from try: startRefWorkingList =", "and random.randrange(numAttrsLeft) == 0: curObjRef = objRef del attr except", "ContainerLeakDetector.removePrivateObj(self.__dict__) Job.destroy(self) def _handleLDDestroy(self): self.destroy() def getPriority(self): return Job.Priorities.High def", "maxLen=CheckContainers.ReprItems))) self.notify.warning(msg) yield None elif (objId in idx2id2len[self._index-4] and objId", "key>' return key def dereferenceDictKey(self, parentDict): # look ourselves up", "def dereferenceDictKey(self, parentDict): # look ourselves up in parentDict key", "between checks # fib: 1 1 2 3 5 8", "in self._id2ref[contId].getEvalStrGen(): yield None for newRepr in objRef.getEvalStrGen(): yield None", "13.2 20.8 32.2 49.3 74.9 113.3 171 self._nextCheckDelay = self._nextCheckDelay", "send out a warning diff4 = idx2id2len[self._index-3][objId] - idx2id2len[self._index-4][objId] diff5", "None str += curIndirection.getString(prevIndirection=prevIndirection, nextIndirection=nextIndirection) if getInstance: lenDict = len('.__dict__')", "dereference is individually eval'd since the dict key might have", "object, # that could cause a memory leak assert type(objId)", "# ref is invalid self.notify.debug('invalid startRef, stored as id %s'", "false, allowing a ref to base.myObject.otherObject.myObject for goesThrough in self.goesThroughGen(obj=obj,", "def getContainerNameByIdGen(self, id, **kwArgs): return self._id2ref[id].getEvalStrGen(**kwArgs) def getContainerNameById(self, id): if", "__init__(self, name, leakDetector, otn, doneCallback=None): Job.__init__(self, name) self._leakDetector = leakDetector", "instanceDictStr: return '.%s' % self.evalStr[2:-2] return self.evalStr # we're stored", "is invalid self.notify.debug('invalid startRef, stored as id %s' % startId)", "pointed to yield self._getContainerByEval(evalStr, curObj=curObj) def getEvalStrGen(self, getInstance=False): str =", "id(curObj[index]), parentObjRef) yield None if hasLength: for i in self._addContainerGen(attr,", "return 'containerLeakDetected-%s' % self._serialNum @classmethod def addPrivateObj(cls, obj): cls.PrivateIds.add(id(obj)) @classmethod", "def __init__(self, name, leakDetector): Job.__init__(self, name) self._leakDetector = leakDetector self._id2ref", "was created this would return # false, allowing a ref", "in 'dict') yield None try: for container in self._leakDetector.getContainerByIdGen( id,", "# to avoid storing multiple redundant refs to a single", "diff2 > 0 and diff3 > 0: name = self._leakDetector.getContainerNameById(objId)", "13 21 34 55 89 # * 2.: 1 2", "key) if hasLength or notDeadEnd: # prevent cycles in the", "choose another break # make a generator that yields containers", "fib: 1 2 4 7 12 20 33 54 88", "destroy(self): self.ignore(self._ldde) self._leakDetector = None self._doneCallback = None ContainerLeakDetector.removePrivateObj(self.__dict__) Job.destroy(self)", "> 0 and diff4 > 0 and diff5 > 0:", "if not goesThrough: objRef = ObjectRef(Indirection(evalStr='.__dict__'), id(child), parentObjRef) yield None", "# * 1.5: 1 2.5 4.75 8.1 13.2 20.8 32.2", "# ref set is empty, choose another break # make", "TypeError, e: ContainerLeakDetector.notify.debug('could not weakref dict key %s' % keyRepr)", "7 15 31 63 127 255 511 1023 2047 #", "existingRepr in self._id2ref[contId].getEvalStrGen(): yield None for newRepr in objRef.getEvalStrGen(): yield", "if it's an internal object, ignore it if id(obj) in", "in self._leakDetector.getContainerNameByIdGen(objId): yield None self.notify.debug('%s no longer exists; getContainerById returned", "return self._id2ref.keys() def getContainerByIdGen(self, id, **kwArgs): # return a generator", "is not None and prevIndirection.evalStr is not None: if prevIndirection.evalStr[-len(instanceDictStr):]", "maxLen=CheckContainers.ReprItems))) yield None \"\"\" if (self._index > 2 and objId", "try: return len(startObj) except: return 1 def _isDeadEnd(self, obj, objName=None):", "object is this object for traversing the object graph? try:", "and diff3 > 0 and diff4 > 0 and diff5", "we already have, # put it in the table if", "% (name, itype(container), idx2id2len[self._index][objId], fastRepr(container, maxLen=CheckContainers.ReprItems))) self.notify.warning(msg) yield None messenger.send(self._leakDetector.getLeakEvent(),", "indirection.release() del self._indirections def getNumIndirections(self): return len(self._indirections) def goesThroughGen(self, obj=None,", "startRefWorkingList = workingListSelector.next() except StopIteration: # do relative # of", "None container = result except Exception, e: # this container", "Job.destroy(self) def getPriority(self): return Job.Priorities.Normal def run(self): try: self._leakDetector._index2containerId2len[self._index] =", "'curObj%s' % evalStr else: # this eval is not based", "raise yield Job.Done class CheckContainers(Job): \"\"\" Job to check container", "key def dereferenceDictKey(self, parentDict): # look ourselves up in parentDict", "reference class LeakKey: pass base.leakContainer[(LeakKey(),)] = {} # test the", "is None: # this container no longer exists if self.notify.getDebug():", "ids = self._leakDetector.getContainerIds() try: for id in ids: yield None", "# reference is invalid, remove it del _id2baseStartRef[id] _id2discoveredStartRef =", "cLen = len(container) except Exception, e: # this container no", "doneCallback) jobMgr.add(j) return j def _scheduleNextLeakCheck(self): taskMgr.doMethodLater(self._nextCheckDelay, self._checkForLeaks, self._getCheckTaskName()) #", "jobMgr.add(self._findContainersJob) self._scheduleNextLeakCheck() self._scheduleNextPruning() while True: yield Job.Sleep def getPathsToContainers(self, name,", "iterated attr = None break attrs.append(attr) # we will continue", "e if __dev__: raise yield Job.Done class FPTObjsOfType(Job): def __init__(self,", "__dev__: raise yield Job.Done def finished(self): if self._doneCallback: self._doneCallback(self) class", "Job.Done class ContainerLeakDetector(Job): \"\"\" Low-priority Python object-graph walker that looks", "= self._leakDetector.notify self._on = on self._doneCallback = doneCallback self._ldde =", "objId in self._id2discoveredStartRef: existingRef = self._id2discoveredStartRef[objId] if type(existingRef) not in", "else: cName = container.__name__ if (self._otn.lower() in cName.lower()): try: for", "the eval succeeded if hash(keyEval) != hash(dictKey): useEval = False", "lose this element pass if not goesThrough: objRef = ObjectRef(Indirection(evalStr='.__dict__'),", "# if we hit a dead end, start over from", "concise than the new ref return storedItem = ref #", "LeakDetectors.py if not hasattr(__builtin__, \"leakDetectors\"): __builtin__.leakDetectors = {} ref =", "type(curObj) is types.DictType: key = None attr = None keys", "def getPriority(self): return Job.Priorities.Normal def run(self): try: ids = self._leakDetector.getContainerIds()", "start looking for containers self._findContainersJob = FindContainers( '%s-findContainers' % self.getJobName(),", "yield Job.Sleep def getPathsToContainers(self, name, ot, doneCallback=None): j = FPTObjsOfType(name,", "a big chunk of CPU time numAttrsLeft = len(attrs) +", "self.accept(self._ldde, self._handleLDDestroy) ContainerLeakDetector.addPrivateObj(self.__dict__) def destroy(self): self.ignore(self._ldde) self._leakDetector = None self._doneCallback", "_addContainerGen(self, cont, objRef): contId = id(cont) # if this container", "indirection in indirections: indirection.acquire() for i in xrange(len(indirections)): yield None", "prevIndirection = None curIndirection = indirections[i] if i < len(indirections)-1:", "= {} self._id2discoveredStartRef = {} # these are working copies", "_checkForLeaks(self, task=None): self._index2delay[len(self._index2containerId2len)] = self._nextCheckDelay self._checkContainersJob = CheckContainers( '%s-checkForLeaks' %", "many times but eventually it will discover every object. Checks", "except: return 1 def _isDeadEnd(self, obj, objName=None): if type(obj) in", "not goesThrough: objRef = ObjectRef(Indirection(evalStr='[%s]' % index), id(curObj[index]), parentObjRef) yield", "in the curObj dictionary curObj = indirection.dereferenceDictKey(curObj) evalStr = ''", "self._leakDetector.getContainerIds() try: for id in ids: yield None try: for", "= {} ids = self._leakDetector.getContainerIds() # record the current len", "self._handleLDDestroy) ContainerLeakDetector.addPrivateObj(self.__dict__) def destroy(self): self.ignore(self._ldde) self._leakDetector = None self._doneCallback =", "related to methods if className == 'method-wrapper': return True return", "for fw in makeFlywheelGen( startRefWorkingList.source.values(), countFunc=lambda x: self.getStartObjAffinity(x), scale=.05): yield", "if self._index > 0: idx2id2len = self._leakDetector._index2containerId2len for objId in", "is too spammy if diff > 20: if diff >", "except: # TODO self.notify.debug('caught exception in getContainerByIdGen (2)') else: msg", "of all visited objects; it may visit the same object", "if possible stored as a series of 'indirections' (obj.foo ->", "2 4 8 16 32 64 128 256 512 1024", "diff2 = idx2id2len[self._index-1][objId] - idx2id2len[self._index-2][objId] diff3 = idx2id2len[self._index-2][objId] - idx2id2len[self._index-3][objId]", "and self.evalStr[-len(instanceDictStr):] == instanceDictStr: return self.evalStr[:-len(instanceDictStr)] # if the previous", "if task: return task.done leakContainer() def _createTaskLeak(): leakTaskName = uniqueName('leakedTask')", "to be eval'd evalStr += indirection.getString() else: curObj = self._getContainerByEval(evalStr,", "it's still valid while True: yield None try: curObjRef =", "contents: %s)' % (name, itype(container), idx2id2len[self._index][objId], fastRepr(container, maxLen=CheckContainers.ReprItems))) self.notify.warning(msg) yield", "def acquire(self): self._refCount += 1 def release(self): self._refCount -= 1", "that is # proportional to their length for fw in", "yield None except: pass else: print 'GPTC(' + self._otn +", "firstCheckDelay/2. self._checkDelayScale = config.GetFloat('leak-detector-check-delay-scale', 1.5) self._pruneTaskPeriod = config.GetFloat('leak-detector-prune-period', 60. *", "yield None \"\"\" if (self._index > 2 and objId in", "7 12 20 33 54 88 143 232 # *", "should not be examined PrivateIds = set() def __init__(self, name,", "# these hold objects that we should start traversals from", "or len(newRepr) < len(existingRepr): if contId in self._id2ref: self._leakDetector.removeContainerById(contId) self._id2ref[contId]", "percent, minutes, idx2id2len[self._index][objId], fastRepr(container, maxLen=CheckContainers.ReprItems))) yield None \"\"\" if (self._index", "ot, doneCallback) jobMgr.add(j) return j def getPathsToContainersNamed(self, name, on, doneCallback=None):", "should never be empty (__builtin__ etc.) continue # do we", "object graph via one attr, # choose it at random", "yield None except: pass else: print 'GPTCN(' + self._on +", "55 89 # * 2.: 1 2 4 8 16", "the last 5 checks, # send out a warning diff4", "1 def _isDeadEnd(self, obj, objName=None): if type(obj) in (types.BooleanType, types.BuiltinFunctionType,", "self.evalStr[-len(instanceDictStr):] == instanceDictStr: return self.evalStr[:-len(instanceDictStr)] # if the previous indirection", "32 64 128 256 512 1024 # * 1.5: 1", "self.notify.debug('caught exception in getContainerByIdGen (3)') else: msg = ('leak detected:", "Exception, e: print 'FPTObjsNamed job caught exception: %s' % e", "if id(o) == objId: break for indirection in indirections: yield", "self._isWeakRef = False def destroy(self): # re-entrant self.dictKey = NoDictKey", "# eval/repr succeeded, store as an evalStr self.evalStr = '[%s]'", "i < len(indirections)-1: nextIndirection = indirections[i+1] else: nextIndirection = None", "str[:-lenDict] for indirection in indirections: yield None indirection.release() yield str", "discLen/minLen]) yield None continue # grab the next start ref", "in self._leakDetector.getContainerNameByIdGen(id): yield None except: pass else: print 'GPTCN(' +", "key is None: return '<garbage-collected dict key>' return key def", "re-entrant self.dictKey = NoDictKey def acquire(self): self._refCount += 1 def", "a handle on the container by eval'ing and looking things", "None if not indirection.isDictKey(): # build up a string to", "def run(self): ids = self._leakDetector.getContainerIds() try: for id in ids:", "if (self._otn.lower() in cName.lower()): try: for ptc in self._leakDetector.getContainerNameByIdGen( id,", "so it will be garbage-collected' % safeRepr(key)) del base.leakContainer[key] taskMgr.doMethodLater(10,", "not storing a reference to the actual object, # that", "= ref # container for objects that want to make", "and random.randrange(numKeysLeft) == 0: curObjRef = objRef del key del", "exists; caught exception in getContainerById (%s)' % ( contName, e))", "object reference handling if random.random() < .01: key = random.choice(base.leakContainer.keys())", "CheckContainers(Job): \"\"\" Job to check container sizes and find potential", "self._leakDetector.getContainerByIdGen(objId): yield None container = result except Exception, e: #", "= self._leakDetector.getContainerIds() for id in ids: yield None try: for", "evalStr keyRepr = safeRepr(dictKey) useEval = False try: keyEval =", "hold a normal 'non-weak' reference class LeakKey: pass base.leakContainer[(LeakKey(),)] =", "taskMgr.doMethodLater(10, leakContainer, 'leakContainer-%s' % serialNum()) if task: return task.done leakContainer()", "increased in size over the last ' '5 periods (%s", "= ('%s (%s) consistently increased in size over the last", "# we're stored as a dict key keyRepr = safeRepr(self._getNonWeakDictKey())", "base.loader.base) for goesThrough in parentObjRef.goesThrough(curObj[index]): # don't yield, container might", "destroy(self): ContainerLeakDetector.removePrivateObj(self.__dict__) Job.destroy(self) def getPriority(self): return Job.Priorities.Low @staticmethod def getStartObjAffinity(startObj):", "for container in _id2discoveredStartRef[id].getContainerGen(): yield None except: # reference is", "StopIteration: # we've run out of refs, grab a new", "'3 periods (%s items at last measurement, current contents: %s)'", "return storedItem = ref # if we already are storing", "i > 0: prevIndirection = indirections[i-1] else: prevIndirection = None", "yield None try: for result in self._leakDetector.getContainerByIdGen(objId): yield None container", "None: # this container no longer exists if self.notify.getDebug(): for", "for result in self._id2ref[id].getContainerGen(): pass return result def getContainerNameByIdGen(self, id,", "on the type of each indirection # if getInstance is", "types.CodeType, types.FunctionType, types.StringType, types.UnicodeType, types.TupleType): return True # if it's", "= result except Exception, e: # this container no longer", "None except AttributeError, ae: return None except KeyError, ke: return", "refs to a single item if type(curObjRef) in (types.IntType, types.LongType):", "return False def _hasLength(self, obj): return hasattr(obj, '__len__') def _addContainerGen(self,", "originally pointed to yield self._getContainerByEval(evalStr, curObj=curObj) def getEvalStrGen(self, getInstance=False): str", "< .01: key = random.choice(base.leakContainer.keys()) ContainerLeakDetector.notify.debug( 'removing reference to leakContainer", "new workingListSelector inside the while loop right off the bat", "key return parentDict[key] def getString(self, prevIndirection=None, nextIndirection=None): # return our", "of the current objRef parentObjRef = curObjRef # if we", "ref.getNumIndirections()): # the ref that we already have is more", "'im_class'): return True try: className = obj.__class__.__name__ except: pass else:", "None break attrs.append(attr) # we will continue traversing the object", "Represents the indirection that brings you from a container to", "getContainerById (%s)' % ( contName, e)) self._leakDetector.removeContainerById(objId) continue if container", "looking things # up in dictionaries, depending on the type", "the start if it's not already there bis = '__builtin__'", "'%s no longer exists; caught exception in getContainerById (%s)' %", "None o = self._getContainerByEval(evalStr, curObj=curObj) if id(o) == objId: break", "when iterated attr = None break attrs.append(attr) # we will", "if self._doneCallback: self._doneCallback(self) class PruneObjectRefs(Job): \"\"\" Job to destroy any", "of containers that should not be examined PrivateIds = set()", "= None if hasattr(curObj, '__dict__'): child = curObj.__dict__ hasLength =", "= idx2id2len[self._index-4][objId] - idx2id2len[self._index-5][objId] if diff > 0 and diff2", "in the actual system so that Python will keep one", "put __builtin__ at the start if it's not already there", "# this yields a different set of start refs every", "us indirections = self._indirections for indirection in indirections: yield None", "jobMgr.add(self) def destroy(self): messenger.send(self._getDestroyEvent()) self.ignoreAll() if self._pruneContainersJob is not None:", "the dictKey a weak reference? self._isWeakRef = False self._refCount =", "try: self._leakDetector._index2containerId2len[self._index] = {} ids = self._leakDetector.getContainerIds() # record the", "self._id2discoveredStartRef = {} # these are working copies so that", "self._id2ref[contId].getEvalStrGen(): yield None for newRepr in objRef.getEvalStrGen(): yield None if", "print 'PruneObjectRefs job caught exception: %s' % e if __dev__:", "in getContainerByIdGen (2)') else: msg = ('%s (%s) consistently increased", "None except: pass else: print 'GPTC(' + self._otn + '):'", "cName = container.__class__.__name__ else: cName = container.__name__ if (self._otn.lower() in", "indirection.release() if getInstance: lenDict = len('.__dict__') if evalStr[-lenDict:] == '.__dict__':", "divide by two, since the first check just takes length", "used to start an object graph traversal objId = id(obj)", "run out of refs, grab a new set if len(startRefWorkingList.source)", "self._leakDetector.removeContainerById(id) _id2baseStartRef = self._leakDetector._findContainersJob._id2baseStartRef ids = _id2baseStartRef.keys() for id in", "results of check-container job self._index2containerId2len = {} self._index2delay = {}", "key = self.dictKey() if key is None: return '<garbage-collected dict", "yield None indirection.release() yield str def getFinalIndirectionStr(self): prevIndirection = None", "for contName in self._leakDetector.getContainerNameByIdGen(objId): yield None self.notify.debug( '%s no longer", "if useEval: # eval/repr succeeded, store as an evalStr self.evalStr", "Job to check container sizes and find potential leaks; sub-job", "back to the # top of the while loop from", "in a way that does not prevent garbage collection of", "__dev__: raise yield Job.Done class ContainerLeakDetector(Job): \"\"\" Low-priority Python object-graph", "self._index2containerId2len = {} self._index2delay = {} if config.GetBool('leak-container', 0): _createContainerLeak()", "task=None): self._pruneContainersJob = PruneObjectRefs( '%s-pruneObjectRefs' % self.getJobName(), self) self.acceptOnce(self._pruneContainersJob.getFinishedEvent(), self._scheduleNextPruning)", "eval, or as a key to be looked up in", "notDeadEnd = not self._isDeadEnd(attr) if hasLength or notDeadEnd: # prevent", "config.GetBool('leak-tasks', 0): _createTaskLeak() # don't check our own tables for", "same object many times but eventually it will discover every", "this would return # false, allowing a ref to base.myObject.otherObject.myObject", "for ind in self._indirections: ind.acquire() self.notify.debug(repr(self)) def destroy(self): for indirection", "from pandac.PandaModules import PStatCollector from direct.directnotify.DirectNotifyGlobal import directNotify from direct.showbase.PythonUtil", "ScratchPad(refGen=nullGen(), source=self._id2baseStartRef) self._discoveredStartRefWorkingList = ScratchPad(refGen=nullGen(), source=self._id2discoveredStartRef) self.notify = self._leakDetector.notify ContainerLeakDetector.addPrivateObj(self.__dict__)", "in self._addContainerGen(simbase.__dict__, ref): pass def destroy(self): ContainerLeakDetector.removePrivateObj(self.__dict__) Job.destroy(self) def getPriority(self):", "return True # if it's an internal object, ignore it", "startRef, stored as id %s' % startId) self._leakDetector.removeContainerById(startId) continue curObjRef", "indirection.isDictKey(): # build up a string to be eval'd evalStr", "ObjectRef: \"\"\" stores a reference to a container in a", "None try: for container in self._leakDetector.getContainerByIdGen( id, getInstance=getInstance): yield None", "prevIndirection.evalStr[-len(instanceDictStr):] == instanceDictStr: return '.%s' % self.evalStr[2:-2] return self.evalStr #", "uniqueName('leakedTask') leakDoLaterName = uniqueName('leakedDoLater') def nullTask(task=None): return task.cont def nullDoLater(task=None):", "self._otn + '):' + self.getJobName() + ': ' + ptc", "other=None): self._indirections = [] # are we building off of", "is still the object we originally pointed to yield self._getContainerByEval(evalStr,", "\"\"\" # this check is too spammy if diff >", "now %s (%s)' % (contName, safeRepr(container), e)) self._leakDetector.removeContainerById(objId) continue self._leakDetector._index2containerId2len[self._index][objId]", "idx2id2len[self._index-4] and objId in idx2id2len[self._index-5]): # if size has consistently", "ref = ObjectRef(Indirection(evalStr='__builtin__.__dict__'), id(__builtin__.__dict__)) self._id2baseStartRef[id(__builtin__.__dict__)] = ref # container for", "indirections: yield None indirection.release() yield id(o) == objId def goesThrough(self,", "self.notify.warning(msg) yield None elif (objId in idx2id2len[self._index-4] and objId in", "in self._id2ref: self._id2ref[id].destroy() del self._id2ref[id] def run(self): # start looking", "self.dictKey = weakref.ref(dictKey) self._isWeakRef = True except TypeError, e: ContainerLeakDetector.notify.debug('could", "ReprItems = 5 def __init__(self, name, leakDetector, index): Job.__init__(self, name)", "self._doneCallback: self._doneCallback(self) class PruneObjectRefs(Job): \"\"\" Job to destroy any container", "leakContainer key %s so it will be garbage-collected' % safeRepr(key))", "try: for id in ids: yield None try: for container", "use tuples as keys since they can't be weakref'd, and", "None index += 1 numAttrsLeft -= 1 hasLength = self._hasLength(attr)", "algorithm, including objects that exist # just to measure things", "getContainerByIdGen(self, id, **kwArgs): # return a generator to look up", "id, **kwArgs): return self._id2ref[id].getEvalStrGen(**kwArgs) def getContainerNameById(self, id): if id in", "of refs, grab a new set if len(startRefWorkingList.source) == 0:", "j def _scheduleNextLeakCheck(self): taskMgr.doMethodLater(self._nextCheckDelay, self._checkForLeaks, self._getCheckTaskName()) # delay between checks", "to a different object after this Ref was created this", "def nullDoLater(task=None): return task.done def leakTask(task=None, leakTaskName=leakTaskName): base = getBase()", "for objects that want to make sure they are found", "in self._indirections: indirection.release() del self._indirections def getNumIndirections(self): return len(self._indirections) def", "or the objRef repr is shorter than what we already", "for newRepr in objRef.getEvalStrGen(): yield None if contId not in", "yield None if notDeadEnd: self._addDiscoveredStartRef(attr, objRef) if curObjRef is None", "objRef = ObjectRef(Indirection(evalStr='%s' % key), id(curObj[key])) else: objRef = ObjectRef(Indirection(dictKey=key),", "run(self): try: # this yields a different set of start", "we will continue traversing the object graph via one key", "exception: %s' % e if __dev__: raise yield Job.Done class", "leak assert type(objId) in (types.IntType, types.LongType) # prevent cycles (i.e.", "pass else: # prevent infinite recursion in built-in containers related", "False def _hasLength(self, obj): return hasattr(obj, '__len__') def _addContainerGen(self, cont,", "in (types.IntType, types.LongType): startId = curObjRef curObjRef = None try:", "is a dictionary lookup, pass dictKey instead of evalStr self.evalStr", "goesThrough in parentObjRef.goesThrough(curObj[index]): # don't yield, container might lose this", "= storedItem def run(self): try: # this yields a different", "% curObjRef) #import pdb;pdb.set_trace() # store a copy of the", "contName in self._leakDetector.getContainerNameByIdGen(objId): yield None self.notify.debug( '%s is no longer", "obj, ref): # we've discovered an object that can be", "= 5 def __init__(self, name, leakDetector, index): Job.__init__(self, name) self._leakDetector", "0 and diff5 > 0: name = self._leakDetector.getContainerNameById(objId) try: for", "usage, this does a random walk of the Python objects", "self._scheduleNextLeakCheck) jobMgr.add(self._checkContainersJob) return task.done def _scheduleNextPruning(self): taskMgr.doMethodLater(self._pruneTaskPeriod, self._pruneObjectRefs, self._getPruneTaskName()) def", "return Job.Priorities.Low @staticmethod def getStartObjAffinity(startObj): # how good of a", "self.evalStr[2:-2] return self.evalStr # we're stored as a dict key", "to yield self._getContainerByEval(evalStr, curObj=curObj) def getEvalStrGen(self, getInstance=False): str = ''", "# build up a string to be eval'd evalStr +=", "up a container return self._id2ref[id].getContainerGen(**kwArgs) def getContainerById(self, id): for result", "have parentDict==None if parentDict is None: return key return parentDict[key]", "hasattr(obj, '__len__') def _addContainerGen(self, cont, objRef): contId = id(cont) #", "Python will keep one copy and reduce memory usage \"\"\"", "or notDeadEnd: # prevent cycles in the references (i.e. base.loader.base)", "for i in self._addContainerGen(child, objRef): yield None if notDeadEnd: self._addDiscoveredStartRef(child,", "except: pass else: print 'GPTCN(' + self._on + '):' +", "= {} if config.GetBool('leak-container', 0): _createContainerLeak() if config.GetBool('leak-tasks', 0): _createTaskLeak()", "return task.done def _scheduleNextPruning(self): taskMgr.doMethodLater(self._pruneTaskPeriod, self._pruneObjectRefs, self._getPruneTaskName()) def _pruneObjectRefs(self, task=None):", "None try: for containerRef in self._leakDetector.getContainerByIdGen(startId): yield None except: #", "FindContainers( '%s-findContainers' % self.getJobName(), self) jobMgr.add(self._findContainersJob) self._scheduleNextLeakCheck() self._scheduleNextPruning() while True:", "larger set by 2/3 minLen *= 3. workingListSelector = flywheel([self._baseStartRefWorkingList,", "0 if dictKey is not NoDictKey: # if we can", "# set up the base containers, the ones that hold", "= None self._checkContainersJob = None self._pruneContainersJob = None if firstCheckDelay", "config.GetFloat('leak-detector-check-delay-scale', 1.5) self._pruneTaskPeriod = config.GetFloat('leak-detector-prune-period', 60. * 30.) # main", "yield None if not indirection.isDictKey(): # build up a string", "if (self._index > 2 and objId in idx2id2len[self._index-2] and objId", "time we start a new traversal # force creation of", "= '[%s]' % keyRepr else: try: # store a weakref", "container if possible stored as a series of 'indirections' (obj.foo", "class ObjectRef: \"\"\" stores a reference to a container in", "notDeadEnd = False # if we haven't picked the next", "objId=None): if obj is None: assert type(objId) in (types.IntType, types.LongType)", "is more concise than the new ref return storedItem =", "self._doneCallback = doneCallback self._ldde = self._leakDetector._getDestroyEvent() self.accept(self._ldde, self._handleLDDestroy) ContainerLeakDetector.addPrivateObj(self.__dict__) def", "it self._leakDetector.removeContainerById(id) _id2baseStartRef = self._leakDetector._findContainersJob._id2baseStartRef ids = _id2baseStartRef.keys() for id", "notDeadEnd = not self._isDeadEnd(child) if hasLength or notDeadEnd: # prevent", "= directNotify.newCategory(\"ContainerLeakDetector\") # set of containers that should not be", "self._leakDetector.getContainerNameByIdGen(objId): yield None self.notify.debug('%s no longer exists; getContainerById returned None'", "self._getPruneTaskName()) def _pruneObjectRefs(self, task=None): self._pruneContainersJob = PruneObjectRefs( '%s-pruneObjectRefs' % self.getJobName(),", "= ObjectRef(Indirection(evalStr='base.__dict__'), id(base.__dict__)) self._id2baseStartRef[id(base.__dict__)] = ref for i in self._addContainerGen(base.__dict__,", "in __builtin__ will have parentDict==None if parentDict is None: return", "if prevIndirection.evalStr[-len(instanceDictStr):] == instanceDictStr: return '.%s' % keyRepr return '[%s]'", "def getStartObjAffinity(startObj): # how good of a starting object is", "yield, container might lose this element pass if not goesThrough:", "ContainerLeakDetector.addPrivateObj(ContainerLeakDetector.PrivateIds) ContainerLeakDetector.addPrivateObj(self.__dict__) self.setPriority(Job.Priorities.Min) jobMgr.add(self) def destroy(self): messenger.send(self._getDestroyEvent()) self.ignoreAll() if self._pruneContainersJob", "dict, change our syntax from ['key'] to .key if prevIndirection", "the Python graph, looking for objects that support __len__() \"\"\"", "yield Job.Done def finished(self): if self._doneCallback: self._doneCallback(self) class FPTObjsNamed(Job): def", "object. Checks container sizes at ever-increasing intervals. \"\"\" notify =", "weakref, random, __builtin__ def _createContainerLeak(): def leakContainer(task=None): base = getBase()", "times that is # proportional to their length for fw", "# start looking for containers self._findContainersJob = FindContainers( '%s-findContainers' %", "individually eval'd since the dict key might have been garbage-collected", "if we already are storing a reference to this object,", "None messenger.send(self._leakDetector.getLeakEvent(), [container, name]) if config.GetBool('pdb-on-leak-detect', 0): import pdb;pdb.set_trace() pass", "self._doneCallback(self) class PruneObjectRefs(Job): \"\"\" Job to destroy any container refs", "reference? self._isWeakRef = False self._refCount = 0 if dictKey is", "self.destroy() def isDictKey(self): # is this an indirection through a", "_id2ref? sometimes we do that # to avoid storing multiple", "remove it del _id2discoveredStartRef[id] except Exception, e: print 'PruneObjectRefs job", "this sequence and see if it's still valid while True:", "_createTaskLeak() # don't check our own tables for leaks ContainerLeakDetector.addPrivateObj(ContainerLeakDetector.PrivateIds)", "name) self._leakDetector = leakDetector self.notify = self._leakDetector.notify self._index = index", "and not-as-often, # respectively self._id2baseStartRef = {} self._id2discoveredStartRef = {}", "delay from job start # fib: 1 2 4 7", "lens if self._index > 0: idx2id2len = self._leakDetector._index2containerId2len for objId", "if hasLength: for i in self._addContainerGen(attr, objRef): yield None if", "(__builtin__ etc.) continue # do we need to go look", "% serialNum()) if task: return task.done leakTask() class NoDictKey: pass", "e: # this container no longer exists if self.notify.getDebug(): for", "as an evalStr keyRepr = safeRepr(dictKey) useEval = False try:", "nullDoLater(task=None): return task.done def leakTask(task=None, leakTaskName=leakTaskName): base = getBase() taskMgr.add(nullTask,", "try: for ptc in self._leakDetector.getContainerNameByIdGen( id, getInstance=getInstance): yield None except:", "ObjectRef(Indirection(evalStr='leakDetectors'), id(leakDetectors)) self._id2baseStartRef[id(leakDetectors)] = ref for i in self._addContainerGen(__builtin__.__dict__, ref):", "that container is gone, try again curObjRef = None continue", "been garbage-collected TODO: store string components that are duplicates of", "redundant refs to a single item if type(curObjRef) in (types.IntType,", "isDictKey(self): # is this an indirection through a dictionary? return", "name, leakDetector, otn, doneCallback=None): Job.__init__(self, name) self._leakDetector = leakDetector self.notify", "how good of a starting object is this object for", "the key self.dictKey = weakref.ref(dictKey) self._isWeakRef = True except TypeError,", "dict. Each dictionary dereference is individually eval'd since the dict", "else: print 'GPTCN(' + self._on + '):' + self.getJobName() +", "to look up this key in the curObj dictionary curObj", "yield None startRefWorkingList.refGen = fw if curObjRef is None: #", "as C++ memory usage, scene graph size, # framerate, etc.", "# is the dictKey a weak reference? self._isWeakRef = False", "check for leaks self._nextCheckDelay = firstCheckDelay/2. self._checkDelayScale = config.GetFloat('leak-detector-check-delay-scale', 1.5)", "doneCallback=None): j = FPTObjsOfType(name, self, ot, doneCallback) jobMgr.add(j) return j", "False try: keyEval = eval(keyRepr) useEval = True except: pass", "goesThrough in parentObjRef.goesThroughGen(curObj[key]): # don't yield, container might lose this", "can be used to start an object graph traversal objId", "= ref # if we already are storing a reference", "len(self._discoveredStartRefWorkingList.source) minLen = float(max(1, min(baseLen, discLen))) # this will cut", "task.done def leakTask(task=None, leakTaskName=leakTaskName): base = getBase() taskMgr.add(nullTask, uniqueName(leakTaskName)) taskMgr.doMethodLater(1", "self.notify.debug('invalid startRef, stored as id %s' % startId) self._leakDetector.removeContainerById(startId) continue", "{} self._index2delay = {} if config.GetBool('leak-container', 0): _createContainerLeak() if config.GetBool('leak-tasks',", "dictKey is not NoDictKey: # if we can repr/eval the", "# this isn't perfect, for example if base.myObject is reassigned", "( parentObjRef, safeRepr(key))) continue hasLength = self._hasLength(attr) notDeadEnd = False", "False self._refCount = 0 if dictKey is not NoDictKey: #", "attr, # choose it at random without taking a big", "{} ids = self._leakDetector.getContainerIds() # record the current len of", "getInstance=getInstance): yield None except: pass else: print 'GPTC(' + self._otn", "return a generator to look up a container return self._id2ref[id].getContainerGen(**kwArgs)", "yield None if hasLength: for i in self._addContainerGen(attr, objRef): yield", "yield None #import pdb;pdb.set_trace() if curObjRef is None: # choose", "# some custom classes don't do well when iterated attr", "= id(cont) # if this container is new, or the", "from another container curObjRef = None if hasattr(curObj, '__dict__'): child", "doneCallback self._ldde = self._leakDetector._getDestroyEvent() self.accept(self._ldde, self._handleLDDestroy) ContainerLeakDetector.addPrivateObj(self.__dict__) def destroy(self): self.ignore(self._ldde)", "containers related to methods if className == 'method-wrapper': return True", "object instanceDictStr = '.__dict__' if self.evalStr is not None: #", "in makeFlywheelGen( startRefWorkingList.source.values(), countFunc=lambda x: self.getStartObjAffinity(x), scale=.05): yield None startRefWorkingList.refGen", "except KeyError, ke: return None return container def getContainerGen(self, getInstance=False):", "'.__dict__' if self.evalStr is not None: # if we're an", "if diff > idx2id2len[self._index-1][objId]: minutes = (self._leakDetector._index2delay[self._index] - self._leakDetector._index2delay[self._index-1]) /", "it will be garbage-collected' % safeRepr(key)) del base.leakContainer[key] taskMgr.doMethodLater(10, leakContainer,", "make sure they are found by # the object exploration", "See LeakDetectors.py if not hasattr(__builtin__, \"leakDetectors\"): __builtin__.leakDetectors = {} ref", "since the first check just takes length measurements and #", "contName in self._leakDetector.getContainerNameByIdGen(objId): yield None self.notify.debug( '%s no longer exists;", "next ref, check if this one is a candidate if", "# compare the current len of each container to past", "garbage-collected' % safeRepr(key)) del base.leakContainer[key] taskMgr.doMethodLater(10, leakContainer, 'leakContainer-%s' % serialNum())", "= objRef del attr except StopIteration, e: pass del itr", "current contents: %s)' % ( name, itype(container), percent, minutes, idx2id2len[self._index][objId],", "base.myObject is reassigned # to a different object after this", "'__dict__'): child = curObj.__dict__ hasLength = self._hasLength(child) notDeadEnd = not", "in idx2id2len[self._index-1]: diff = idx2id2len[self._index][objId] - idx2id2len[self._index-1][objId] \"\"\" # this", "Job.Done def finished(self): if self._doneCallback: self._doneCallback(self) class FPTObjsNamed(Job): def __init__(self,", "cls.PrivateIds.remove(id(obj)) def _getCheckTaskName(self): return 'checkForLeakingContainers-%s' % self._serialNum def _getPruneTaskName(self): return", "non-weakref object reference handling if random.random() < .01: key =", "grab a new set if len(startRefWorkingList.source) == 0: # ref", "an object that can be used to start an object", "(i.e. base.loader.base) for goesThrough in parentObjRef.goesThroughGen(curObj[key]): # don't yield, container", "break except StopIteration: # we've run out of refs, grab", "indirection.acquire() for indirection in indirections: yield None if not indirection.isDictKey():", "self._addContainerGen(simbase.__dict__, ref): pass def destroy(self): ContainerLeakDetector.removePrivateObj(self.__dict__) Job.destroy(self) def getPriority(self): return", "0: curObjRef = objRef del key del attr continue try:", "= False self._refCount = 0 if dictKey is not NoDictKey:", "numKeysLeft -= 1 try: attr = curObj[key] except KeyError, e:", "for id in ids: yield None try: for container in", "if curObj is __builtin__.__dict__: objRef = ObjectRef(Indirection(evalStr='%s' % key), id(curObj[key]))", ">= ref.getNumIndirections()): # the ref that we already have is", "None except: # reference is invalid, remove it self._leakDetector.removeContainerById(id) _id2baseStartRef", "parentObjRef) yield None if hasLength: for i in self._addContainerGen(child, objRef):", "yield None messenger.send(self._leakDetector.getLeakEvent(), [container, name]) if config.GetBool('pdb-on-leak-detect', 0): import pdb;pdb.set_trace()", "parentDict==None if parentDict is None: return key return parentDict[key] def", "might lose this element pass if not goesThrough: if curObj", "references (i.e. base.loader.base) for goesThrough in parentObjRef.goesThroughGen(curObj[key]): # don't yield,", "'%s-checkForLeaks' % self.getJobName(), self, len(self._index2containerId2len)) self.acceptOnce(self._checkContainersJob.getFinishedEvent(), self._scheduleNextLeakCheck) jobMgr.add(self._checkContainersJob) return task.done", "are duplicates of strings in the actual system so that", "already are storing a reference to this object, don't store", "if type(curObjRef) in (types.IntType, types.LongType): startId = curObjRef curObjRef =", "getPriority(self): return Job.Priorities.Low @staticmethod def getStartObjAffinity(startObj): # how good of", "indirections[i] if i < len(indirections)-1: nextIndirection = indirections[i+1] else: nextIndirection", "dictKey=NoDictKey): # if this is a dictionary lookup, pass dictKey", "(i.e. base.loader.base.loader) assert not self.goesThrough(objId=objId) self._indirections.append(indirection) # make sure our", "of a new workingListSelector inside the while loop right off", "if useEval: # check to make sure the eval succeeded", "\"\"\" if (self._index > 2 and objId in idx2id2len[self._index-2] and", "are we building off of an existing ref? if other", "a different set of start refs every time we start", "argument return 'containerLeakDetected-%s' % self._serialNum @classmethod def addPrivateObj(cls, obj): cls.PrivateIds.add(id(obj))", "pdb;pdb.set_trace() # store a copy of the current objRef parentObjRef", "looks for leaking containers. To reduce memory usage, this does", "jobMgr.remove(self._pruneContainersJob) self._pruneContainersJob = None if self._checkContainersJob is not None: jobMgr.remove(self._checkContainersJob)", "= {} self._index2delay = {} if config.GetBool('leak-container', 0): _createContainerLeak() if", "# if the previous indirection was an instance dict, change", "indirection.acquire() for i in xrange(len(indirections)): yield None if i >", "leaking containers. To reduce memory usage, this does a random", "consistently increased over the last 5 checks, # send out", "- idx2id2len[self._index-1][objId] \"\"\" # this check is too spammy if", "keyRepr) self.dictKey = dictKey self._isWeakRef = False def destroy(self): #", "in ('im_self', 'im_class'): return True try: className = obj.__class__.__name__ except:", "AttributeError, ae: return None except KeyError, ke: return None return", "try: attr = curObj[key] except KeyError, e: # this is", "memory usage \"\"\" def __init__(self, evalStr=None, dictKey=NoDictKey): # if this", "# eval('curObj.foo.bar.someDict') evalStr = 'curObj%s' % evalStr else: # this", "= FPTObjsNamed(name, self, on, doneCallback) jobMgr.add(j) return j def _scheduleNextLeakCheck(self):", "choose it at random without taking a big chunk of", "leakContainer() def _createTaskLeak(): leakTaskName = uniqueName('leakedTask') leakDoLaterName = uniqueName('leakedDoLater') def", "self.evalStr[:-len(instanceDictStr)] # if the previous indirection was an instance dict,", "containers. To reduce memory usage, this does a random walk", "% e if __dev__: raise yield Job.Done class FPTObjsOfType(Job): def", "will continue traversing the object graph via one attr, #", "reference to leakContainer key %s so it will be garbage-collected'", "i in self._addContainerGen(simbase.__dict__, ref): pass def destroy(self): ContainerLeakDetector.removePrivateObj(self.__dict__) Job.destroy(self) def", "do that # to avoid storing multiple redundant refs to", "+ ': ' + ptc except Exception, e: print 'FPTObjsNamed", "self.dictKey() if key is None: return '<garbage-collected dict key>' return", "89 # * 2.: 1 2 4 8 16 32", "in dictionaries, depending on the type of each indirection #", "try: cLen = len(container) except Exception, e: # this container", "Low-priority Python object-graph walker that looks for leaking containers. To", "we're an instance dict, skip over this one (obj.__dict__[keyName] ==", "ObjectRef(Indirection(dictKey=key), id(curObj[key]), parentObjRef) yield None if hasLength: for i in", "holds the current step of the current traversal curObjRef =", "= indirections[i-1] else: prevIndirection = None curIndirection = indirections[i] if", "% (name, itype(container), idx2id2len[self._index][objId], fastRepr(container, maxLen=CheckContainers.ReprItems))) self.notify.warning(msg) yield None elif", "serialNum()) if task: return task.done leakTask() class NoDictKey: pass class", "this does a random walk of the Python objects to", "definitive ref sets self._baseStartRefWorkingList = ScratchPad(refGen=nullGen(), source=self._id2baseStartRef) self._discoveredStartRefWorkingList = ScratchPad(refGen=nullGen(),", "obj.__class__.__name__ except: pass else: # prevent infinite recursion in built-in", "in self._leakDetector.getContainerNameByIdGen(objId): yield None self.notify.debug( '%s is no longer a", "ind in self._indirections: ind.acquire() self.notify.debug(repr(self)) def destroy(self): for indirection in", "indirection.release() yield id(o) == objId def goesThrough(self, obj=None, objId=None): #", "msg = ('leak detected: %s (%s) consistently increased in size", "yield None try: for container in _id2baseStartRef[id].getContainerGen(): yield None except:", "'FPTObjsNamed job caught exception: %s' % e if __dev__: raise", "config.GetFloat('leak-detector-prune-period', 60. * 30.) # main dict of id(container)->containerRef self._id2ref", "16 32 64 128 256 512 1024 # * 1.5:", "dictionary dereference is individually eval'd since the dict key might", "make sure the eval succeeded if hash(keyEval) != hash(dictKey): useEval", "force creation of a new workingListSelector inside the while loop", "brings you from a container to an element of the", "None # make sure the indirections don't go away on", "key %s' % keyRepr) self.dictKey = dictKey self._isWeakRef = False", "evalStr self.evalStr = evalStr self.dictKey = NoDictKey # is the", "diff > 20: if diff > idx2id2len[self._index-1][objId]: minutes = (self._leakDetector._index2delay[self._index]", "self._leakDetector.getContainerByIdGen( id, getInstance=getInstance): yield None except: pass else: if hasattr(container,", "check that this is still the object we originally pointed", "- self._leakDetector._index2delay[self._index-1]) / 60. name = self._leakDetector.getContainerNameById(objId) if idx2id2len[self._index-1][objId] !=", "try: # store a weakref to the key self.dictKey =", "float(idx2id2len[self._index-1][objId])) try: for container in self._leakDetector.getContainerByIdGen(objId): yield None except: #", "run(self): # start looking for containers self._findContainersJob = FindContainers( '%s-findContainers'", "and don't handle strings if type(objName) == types.StringType and objName", "len of each container to past lens if self._index >", "self._indirections[-2] return self._indirections[-1].getString(prevIndirection=prevIndirection) def __repr__(self): for result in self.getEvalStrGen(): pass", "up the object in _id2ref? sometimes we do that #", "NoDictKey: pass class Indirection: \"\"\" Represents the indirection that brings", "= objId self._id2discoveredStartRef[objId] = storedItem def run(self): try: # this", "self._leakDetector.getContainerNameById(objId) try: for container in self._leakDetector.getContainerByIdGen(objId): yield None except: #", "cycles in the references (i.e. base.loader.base) for goesThrough in parentObjRef.goesThrough(curObj[index]):", "attr = itr.next() except: # some custom classes don't do", "name) self._leakDetector = leakDetector self._id2ref = self._leakDetector._id2ref # these hold", "self.notify.debug( '%s no longer exists; caught exception in getContainerById (%s)'", "not None: for ind in other._indirections: self._indirections.append(ind) # make sure", "(%s) grew %.2f%% in %.2f minutes (%s items at last", "don't store a second reference if objId in self._id2ref: storedItem", "def _addDiscoveredStartRef(self, obj, ref): # we've discovered an object that", "consistently increased in size over the last ' '3 periods", "not None: if prevIndirection.evalStr[-len(instanceDictStr):] == instanceDictStr: return '.%s' % self.evalStr[2:-2]", "about to be destroyed return 'cldDestroy-%s' % self._serialNum def getLeakEvent(self):", "notDeadEnd = False if curObjRef is None: notDeadEnd = not", "'CheckContainers job caught exception: %s' % e if __dev__: raise", "container for objects that want to make sure they are", "Job.__init__(self, name) self._leakDetector = leakDetector self._id2ref = self._leakDetector._id2ref # these", "import pdb;pdb.set_trace() pass except Exception, e: print 'CheckContainers job caught", "diff4 > 0 and diff5 > 0: name = self._leakDetector.getContainerNameById(objId)", "pass if not goesThrough: objRef = ObjectRef(Indirection(evalStr='.__dict__'), id(child), parentObjRef) yield", "set based on how many refs it contains baseLen =", "self._id2baseStartRef = {} self._id2discoveredStartRef = {} # these are working", "self.notify.debug('lost current container, ref.getContainerGen() failed') # that container is gone,", "% index), id(curObj[index]), parentObjRef) yield None if hasLength: for i", "possible stored as a series of 'indirections' (obj.foo -> '.foo',", "types.ComplexType, types.FloatType, types.IntType, types.LongType, types.NoneType, types.NotImplementedType, types.TypeType, types.CodeType, types.FunctionType, types.StringType,", "import Queue, invertDictLossless, makeFlywheelGen from direct.showbase.PythonUtil import itype, serialNum, safeRepr,", "an eval, or as a key to be looked up", "# the object exploration algorithm, including objects that exist #", "@staticmethod def getStartObjAffinity(startObj): # how good of a starting object", "# this check is too spammy if diff > 20:", "destroyed while we're using them for ind in self._indirections: ind.acquire()", "None: jobMgr.remove(self._checkContainersJob) self._checkContainersJob = None jobMgr.remove(self._findContainersJob) self._findContainersJob = None del", "length for fw in makeFlywheelGen( startRefWorkingList.source.values(), countFunc=lambda x: self.getStartObjAffinity(x), scale=.05):", "ptc in self._leakDetector.getContainerNameByIdGen( id, getInstance=getInstance): yield None except: pass else:", "make sure we're not storing a reference to the actual", "yield None if notDeadEnd: self._addDiscoveredStartRef(child, objRef) curObjRef = objRef continue", "each container \"\"\" def __init__(self, name, leakDetector): Job.__init__(self, name) self._leakDetector", "self._indirections for indirection in indirections: indirection.acquire() for indirection in indirections:", "self._leakDetector.getContainerNameByIdGen( id, getInstance=getInstance): yield None except: pass else: print 'GPTC('", "self._checkContainersJob is not None: jobMgr.remove(self._checkContainersJob) self._checkContainersJob = None jobMgr.remove(self._findContainersJob) self._findContainersJob", "== 0: curObjRef = objRef del key del attr continue", "destroyed return 'cldDestroy-%s' % self._serialNum def getLeakEvent(self): # sent when", "is None and random.randrange(numKeysLeft) == 0: curObjRef = objRef del", "def release(self): self._refCount -= 1 if self._refCount == 0: self.destroy()", "in (types.IntType, types.LongType) # prevent cycles (i.e. base.loader.base.loader) assert not", "getNumIndirections(self): return len(self._indirections) def goesThroughGen(self, obj=None, objId=None): if obj is", "id(o) == objId: break for indirection in indirections: yield None", "it at random without taking a big chunk of CPU", "messenger.send(self._leakDetector.getLeakEvent(), [container, name]) if config.GetBool('pdb-on-leak-detect', 0): import pdb;pdb.set_trace() pass except", "objName=None): if type(obj) in (types.BooleanType, types.BuiltinFunctionType, types.BuiltinMethodType, types.ComplexType, types.FloatType, types.IntType,", "return j def getPathsToContainersNamed(self, name, on, doneCallback=None): j = FPTObjsNamed(name,", "self._id2discoveredStartRef[objId] = storedItem def run(self): try: # this yields a", "string to be eval'd evalStr += indirection.getString() else: curObj =", "not self._isDeadEnd(child) if hasLength or notDeadEnd: # prevent cycles in", "hasLength or notDeadEnd: # prevent cycles in the references (i.e.", "= None curIndirection = indirections[i] if i < len(indirections)-1: nextIndirection", "= id(obj) o = None evalStr = '' curObj =", "len(startObj) except: return 1 def _isDeadEnd(self, obj, objName=None): if type(obj)", "does not prevent garbage collection of the container if possible", "this is still the object we originally pointed to yield", "= None self._doneCallback = None ContainerLeakDetector.removePrivateObj(self.__dict__) Job.destroy(self) def _handleLDDestroy(self): self.destroy()", "while we're using them for ind in self._indirections: ind.acquire() self.notify.debug(repr(self))", "they are found by # the object exploration algorithm, including", "self._on = on self._doneCallback = doneCallback self._ldde = self._leakDetector._getDestroyEvent() self.accept(self._ldde,", "= self._nextCheckDelay self._checkContainersJob = CheckContainers( '%s-checkForLeaks' % self.getJobName(), self, len(self._index2containerId2len))", "try: childNames = dir(curObj) except: pass else: try: index =", "is not None: if prevIndirection.evalStr[-len(instanceDictStr):] == instanceDictStr: return '.%s' %", "diff3 > 0: name = self._leakDetector.getContainerNameById(objId) try: for container in", "record the current len of each container for objId in", "None self.notify.debug('%s no longer exists; getContainerById returned None' % contName)", "of an object instanceDictStr = '.__dict__' if self.evalStr is not", "# this container no longer exists if self.notify.getDebug(): for contName", "this is OK because we are yielding during the iteration", "can't be weakref'd, and use an instance # since it", "intervals. \"\"\" notify = directNotify.newCategory(\"ContainerLeakDetector\") # set of containers that", "to be destroyed return 'cldDestroy-%s' % self._serialNum def getLeakEvent(self): #", "itype, serialNum, safeRepr, fastRepr from direct.showbase.Job import Job import types,", "scene graph size, # framerate, etc. See LeakDetectors.py if not", "config.GetBool('pdb-on-leak-detect', 0): import pdb;pdb.set_trace() pass except Exception, e: print 'CheckContainers", "reference is invalid, remove it del _id2discoveredStartRef[id] except Exception, e:", "prevent crashes in objects that define __cmp__ and don't handle", "of 'indirections' (obj.foo -> '.foo', dict[key] -> '[key]', etc.) \"\"\"", "walker that looks for leaking containers. To reduce memory usage,", "== instanceDictStr: return '.%s' % keyRepr return '[%s]' % keyRepr", "True # prevent crashes in objects that define __cmp__ and", "and see if it's still valid while True: yield None", "% key), id(curObj[key])) else: objRef = ObjectRef(Indirection(dictKey=key), id(curObj[key]), parentObjRef) yield", "__init__(self, name, leakDetector, index): Job.__init__(self, name) self._leakDetector = leakDetector self.notify", "idx2id2len[self._index-2][objId] - idx2id2len[self._index-3][objId] if self._index <= 4: if diff >", "'checkForLeakingContainers-%s' % self._serialNum def _getPruneTaskName(self): return 'pruneLeakingContainerRefs-%s' % self._serialNum def", "'pruneLeakingContainerRefs-%s' % self._serialNum def getContainerIds(self): return self._id2ref.keys() def getContainerByIdGen(self, id,", "xrange(len(indirections)): yield None if i > 0: prevIndirection = indirections[i-1]", "still the object we originally pointed to yield self._getContainerByEval(evalStr, curObj=curObj)", "yield Job.Done def finished(self): if self._doneCallback: self._doneCallback(self) class PruneObjectRefs(Job): \"\"\"", "Exception, e: print 'PruneObjectRefs job caught exception: %s' % e", "config.GetBool('leak-container', 0): _createContainerLeak() if config.GetBool('leak-tasks', 0): _createTaskLeak() # don't check", "def leakContainer(task=None): base = getBase() if not hasattr(base, 'leakContainer'): base.leakContainer", "flywheel([self._baseStartRefWorkingList, self._discoveredStartRefWorkingList], [baseLen/minLen, discLen/minLen]) yield None continue # grab the", "ContainerLeakDetector.addPrivateObj(self.__dict__) def destroy(self): self.ignore(self._ldde) self._leakDetector = None self._doneCallback = None", "'%s (%s) grew %.2f%% in %.2f minutes (%s items at", "job caught exception: %s' % e if __dev__: raise yield", "a way that does not prevent garbage collection of the", "dereferenceDictKey(self, parentDict): # look ourselves up in parentDict key =", "passes description string as argument return 'containerLeakDetected-%s' % self._serialNum @classmethod", "# do we need to go look up the object", "instanceDictStr = '.__dict__' if self.evalStr is not None: # if", "it is now %s (%s)' % (contName, safeRepr(container), e)) self._leakDetector.removeContainerById(objId)", "leakTask() class NoDictKey: pass class Indirection: \"\"\" Represents the indirection", "cName = container.__name__ if (self._otn.lower() in cName.lower()): try: for ptc", "yield up here instead of at the end, since we", "obj, objName=None): if type(obj) in (types.BooleanType, types.BuiltinFunctionType, types.BuiltinMethodType, types.ComplexType, types.FloatType,", "set should never be empty (__builtin__ etc.) continue # do", "numKeysLeft = len(keys) + 1 for key in keys: yield", "% keyRepr def __repr__(self): return self.getString() class ObjectRef: \"\"\" stores", "'.__dict__': str = str[:-lenDict] for indirection in indirections: yield None", "Job.Done class FPTObjsOfType(Job): def __init__(self, name, leakDetector, otn, doneCallback=None): Job.__init__(self,", "class FPTObjsOfType(Job): def __init__(self, name, leakDetector, otn, doneCallback=None): Job.__init__(self, name)", "%s (%s)' % (contName, safeRepr(container), e)) self._leakDetector.removeContainerById(objId) continue self._leakDetector._index2containerId2len[self._index][objId] =", "look up this key in the curObj dictionary curObj =", "instance instead of instance dict #import pdb;pdb.set_trace() evalStr = ''", "starting object is this object for traversing the object graph?", "weak reference? self._isWeakRef = False self._refCount = 0 if dictKey", "leakDetector, otn, doneCallback=None): Job.__init__(self, name) self._leakDetector = leakDetector self.notify =", "the indirection that brings you from a container to an", "should start traversals from often and not-as-often, # respectively self._id2baseStartRef", "': ' + ptc except Exception, e: print 'FPTObjsNamed job", "_createContainerLeak() if config.GetBool('leak-tasks', 0): _createTaskLeak() # don't check our own", "objId self._id2discoveredStartRef[objId] = storedItem def run(self): try: # this yields", "uniqueName('leakedDoLater') def nullTask(task=None): return task.cont def nullDoLater(task=None): return task.done def", "contId = id(cont) # if this container is new, or", "__len__() \"\"\" def __init__(self, name, leakDetector): Job.__init__(self, name) self._leakDetector =", "invalid self.notify.debug('invalid startRef, stored as id %s' % startId) self._leakDetector.removeContainerById(startId)", "Job.Sleep def getPathsToContainers(self, name, ot, doneCallback=None): j = FPTObjsOfType(name, self,", "TODO self.notify.debug('caught exception in getContainerByIdGen (3)') else: msg = ('leak", "is not NoDictKey: # if we can repr/eval the key,", "pass if not goesThrough: if curObj is __builtin__.__dict__: objRef =", "simbase except: pass else: ref = ObjectRef(Indirection(evalStr='simbase.__dict__'), id(simbase.__dict__)) self._id2baseStartRef[id(simbase.__dict__)] =", "= self._leakDetector.notify ContainerLeakDetector.addPrivateObj(self.__dict__) # set up the base containers, the", "attr = curObj[key] except KeyError, e: # this is OK", "in _id2baseStartRef[id].getContainerGen(): yield None except: # reference is invalid, remove", "= ScratchPad(refGen=nullGen(), source=self._id2baseStartRef) self._discoveredStartRefWorkingList = ScratchPad(refGen=nullGen(), source=self._id2discoveredStartRef) self.notify = self._leakDetector.notify", "random without taking a big chunk of CPU time numAttrsLeft", "pass else: print 'GPTC(' + self._otn + '):' + self.getJobName()", "= self._id2discoveredStartRef[objId] if type(existingRef) not in (types.IntType, types.LongType): if (existingRef.getNumIndirections()", "objId in idx2id2len[self._index-5]): # if size has consistently increased over", "_getNonWeakDictKey(self): if not self._isWeakRef: return self.dictKey else: key = self.dictKey()", "curObjRef is None: notDeadEnd = not self._isDeadEnd(attr, key) if hasLength", "# return a generator to look up a container return", "series of 'indirections' (obj.foo -> '.foo', dict[key] -> '[key]', etc.)", "yield None index += 1 numAttrsLeft -= 1 hasLength =", "4 8 16 32 64 128 256 512 1024 #", "= directNotify.newCategory(\"ObjectRef\") class FailedEval(Exception): pass def __init__(self, indirection, objId, other=None):", "length measurements and # doesn't check for leaks self._nextCheckDelay =", "from direct.directnotify.DirectNotifyGlobal import directNotify from direct.showbase.PythonUtil import Queue, invertDictLossless, makeFlywheelGen", "be empty (__builtin__ etc.) continue # do we need to", "for containerRef in self._leakDetector.getContainerByIdGen(startId): yield None except: # ref is", "else: try: index = -1 attrs = [] while 1:", "if self._pruneContainersJob is not None: jobMgr.remove(self._pruneContainersJob) self._pruneContainersJob = None if", "continue if container is None: # this container no longer", "taskMgr.doMethodLater(self._nextCheckDelay, self._checkForLeaks, self._getCheckTaskName()) # delay between checks # fib: 1", "keys: yield None numKeysLeft -= 1 try: attr = curObj[key]", "# make sure we're not storing a reference to the", "self._serialNum @classmethod def addPrivateObj(cls, obj): cls.PrivateIds.add(id(obj)) @classmethod def removePrivateObj(cls, obj):", "= {} # these are working copies so that our", "if self._on.lower() in name.lower(): try: for ptc in self._leakDetector.getContainerNameByIdGen(id): yield", "del self._id2ref[id] def run(self): # start looking for containers self._findContainersJob", "def removePrivateObj(cls, obj): cls.PrivateIds.remove(id(obj)) def _getCheckTaskName(self): return 'checkForLeakingContainers-%s' % self._serialNum", "if not indirection.isDictKey(): # build up a string to be", "a generator that yields containers a # of times that", "current len of each container to past lens if self._index", "= config.GetFloat('leak-detector-check-delay-scale', 1.5) self._pruneTaskPeriod = config.GetFloat('leak-detector-prune-period', 60. * 30.) #", "evalStr += indirection.getString() else: curObj = self._getContainerByEval(evalStr, curObj=curObj) if curObj", "parentObjRef = curObjRef # if we hit a dead end,", "try: attr = itr.next() except: # some custom classes don't", "continue curObjRef = containerRef try: for curObj in curObjRef.getContainerGen(): yield", "__repr__(self): for result in self.getEvalStrGen(): pass return result class FindContainers(Job):", "off of curObj, use the global__builtin__ namespace # put __builtin__", "exists; getContainerById returned None' % contName) self._leakDetector.removeContainerById(objId) continue try: cLen", "'non-weak' reference class LeakKey: pass base.leakContainer[(LeakKey(),)] = {} # test", "don't do well when iterated attr = None break attrs.append(attr)", "getInstance=getInstance): yield None except: pass else: if hasattr(container, '__class__'): cName", "None indirection.release() yield str def getFinalIndirectionStr(self): prevIndirection = None if", "len(self._index2containerId2len)) self.acceptOnce(self._checkContainersJob.getFinishedEvent(), self._scheduleNextLeakCheck) jobMgr.add(self._checkContainersJob) return task.done def _scheduleNextPruning(self): taskMgr.doMethodLater(self._pruneTaskPeriod, self._pruneObjectRefs,", "# return our contribution to the full name of an", "None: if prevIndirection.evalStr[-len(instanceDictStr):] == instanceDictStr: return '.%s' % keyRepr return", "curObjRef = None continue self.notify.debug('--> %s' % curObjRef) #import pdb;pdb.set_trace()", "since it can't be repr/eval'd # that will force the", "invertDictLossless, makeFlywheelGen from direct.showbase.PythonUtil import itype, serialNum, safeRepr, fastRepr from", "False if curObjRef is None: notDeadEnd = not self._isDeadEnd(attr) if", "newRepr in objRef.getEvalStrGen(): yield None if contId not in self._id2ref", "yield None except: pass else: name = self._leakDetector._id2ref[id].getFinalIndirectionStr() if self._on.lower()", "indirection in indirections: indirection.acquire() for indirection in indirections: yield None", "we've run out of refs, grab a new set if", "well when iterated attr = None break attrs.append(attr) # we", "if (self._id2ref[objId].getNumIndirections() >= ref.getNumIndirections()): # the ref that we already", "= self._leakDetector.notify ContainerLeakDetector.addPrivateObj(self.__dict__) def destroy(self): ContainerLeakDetector.removePrivateObj(self.__dict__) Job.destroy(self) def getPriority(self): return", "the ref that we already have is more concise than", "hasattr(curObj, '__dict__'): child = curObj.__dict__ hasLength = self._hasLength(child) notDeadEnd =", "via one key of the dict, # choose it at", "def __init__(self, name, leakDetector, otn, doneCallback=None): Job.__init__(self, name) self._leakDetector =", "discovered an object that can be used to start an", "for contName in self._leakDetector.getContainerNameByIdGen(objId): yield None self.notify.debug('%s no longer exists;", "is None: return '<garbage-collected dict key>' return key def dereferenceDictKey(self,", "12 20 33 54 88 143 232 # * 2.:", "True # if it's an internal object, ignore it if", "is None: firstCheckDelay = 60. * 15. # divide by", "2 3 5 8 13 21 34 55 89 #", "= None nextIndirection = None # make sure the indirections", "in the table if contId in self._id2ref: for existingRepr in", "on us indirections = self._indirections for indirection in indirections: indirection.acquire()", "curIndirection = indirections[i] if i < len(indirections)-1: nextIndirection = indirections[i+1]", "out of refs, grab a new set if len(startRefWorkingList.source) ==", "self._pruneContainersJob = PruneObjectRefs( '%s-pruneObjectRefs' % self.getJobName(), self) self.acceptOnce(self._pruneContainersJob.getFinishedEvent(), self._scheduleNextPruning) jobMgr.add(self._pruneContainersJob)", "ref, check if this one is a candidate if curObjRef", "build up a string to be eval'd evalStr += indirection.getString()", "'leakContainer'): base.leakContainer = {} # use tuples as keys since", "taskMgr.add(nullTask, uniqueName(leakTaskName)) taskMgr.doMethodLater(1 << 31, nullDoLater, uniqueName(leakDoLaterName)) taskMgr.doMethodLater(10, leakTask, 'doLeakTask-%s'", "name of an object instanceDictStr = '.__dict__' if self.evalStr is", "objRef repr is shorter than what we already have, #", "'indirections' (obj.foo -> '.foo', dict[key] -> '[key]', etc.) \"\"\" notify", "id(obj) o = None evalStr = '' curObj = None", "%.2f minutes (%s items at last measurement, current contents: %s)'", "= curObj[key] except KeyError, e: # this is OK because", "if it's still valid while True: yield None try: curObjRef", "for container in self._leakDetector.getContainerByIdGen(objId): yield None except: # TODO self.notify.debug('caught", "11.4 17.1 25.6 38.4 57.7 # # delay from job", "class PruneObjectRefs(Job): \"\"\" Job to destroy any container refs that", "1 hasLength = self._hasLength(attr) notDeadEnd = False if curObjRef is", "getContainerNameById(self, id): if id in self._id2ref: return repr(self._id2ref[id]) return '<unknown", "= '' prevIndirection = None curIndirection = None nextIndirection =", "for id in ids: getInstance = (self._otn.lower() not in 'dict')", "ScratchPad(refGen=nullGen(), source=self._id2discoveredStartRef) self.notify = self._leakDetector.notify ContainerLeakDetector.addPrivateObj(self.__dict__) # set up the", "idx2id2len[self._index-3][objId] if self._index <= 4: if diff > 0 and", "idx2id2len[self._index-2][objId] diff3 = idx2id2len[self._index-2][objId] - idx2id2len[self._index-3][objId] if self._index <= 4:", "self._id2ref del self._index2containerId2len del self._index2delay def _getDestroyEvent(self): # sent when", "itr.next() except: # some custom classes don't do well when", "keep one copy and reduce memory usage \"\"\" def __init__(self,", "not NoDictKey def _getNonWeakDictKey(self): if not self._isWeakRef: return self.dictKey else:", "bis: evalStr = '%s.%s' % (bis, evalStr) try: container =", "\"\"\" Job to check container sizes and find potential leaks;", "measurements and # doesn't check for leaks self._nextCheckDelay = firstCheckDelay/2.", "self._pruneTaskPeriod = config.GetFloat('leak-detector-prune-period', 60. * 30.) # main dict of", "getLeakEvent(self): # sent when a leak is detected # passes", "def _scheduleNextLeakCheck(self): taskMgr.doMethodLater(self._nextCheckDelay, self._checkForLeaks, self._getCheckTaskName()) # delay between checks #", "= PruneObjectRefs( '%s-pruneObjectRefs' % self.getJobName(), self) self.acceptOnce(self._pruneContainersJob.getFinishedEvent(), self._scheduleNextPruning) jobMgr.add(self._pruneContainersJob) return", "= -1 attrs = [] while 1: yield None try:", "taskMgr.doMethodLater(10, leakTask, 'doLeakTask-%s' % serialNum()) if task: return task.done leakTask()", "\"\"\" Explore the Python graph, looking for objects that support", "indirection in indirections: yield None indirection.acquire() for indirection in indirections:", "%s (%s) consistently increased in size over the last '", "idx2id2len[self._index-1][objId] - idx2id2len[self._index-2][objId] diff3 = idx2id2len[self._index-2][objId] - idx2id2len[self._index-3][objId] if self._index", "self.getJobName(), self) jobMgr.add(self._findContainersJob) self._scheduleNextLeakCheck() self._scheduleNextPruning() while True: yield Job.Sleep def", "we can repr/eval the key, store it as an evalStr", "the next start ref from this sequence and see if", "str[-lenDict:] == '.__dict__': str = str[:-lenDict] for indirection in indirections:", "potential leaks; sub-job of ContainerLeakDetector \"\"\" ReprItems = 5 def", "= ObjectRef(Indirection(evalStr='.__dict__'), id(child), parentObjRef) yield None if hasLength: for i", "contains baseLen = len(self._baseStartRefWorkingList.source) discLen = len(self._discoveredStartRefWorkingList.source) minLen = float(max(1,", "could cause a memory leak assert type(objId) in (types.IntType, types.LongType)", "*= 3. workingListSelector = flywheel([self._baseStartRefWorkingList, self._discoveredStartRefWorkingList], [baseLen/minLen, discLen/minLen]) yield None", "if str[-lenDict:] == '.__dict__': str = str[:-lenDict] for indirection in", "contName, e)) self._leakDetector.removeContainerById(objId) continue if container is None: # this", "60. name = self._leakDetector.getContainerNameById(objId) if idx2id2len[self._index-1][objId] != 0: percent =", "[] # are we building off of an existing ref?", "self._leakDetector = leakDetector self.notify = self._leakDetector.notify self._otn = otn self._doneCallback", "type of each indirection # if getInstance is True, will", "try: ids = self._leakDetector.getContainerIds() for id in ids: yield None", "self._refCount = 0 if dictKey is not NoDictKey: # if", "self._addContainerGen(base.__dict__, ref): pass try: simbase except: pass else: ref =", "cycles in the references (i.e. base.loader.base) for goesThrough in parentObjRef.goesThroughGen(child):", "id(__builtin__.__dict__)) self._id2baseStartRef[id(__builtin__.__dict__)] = ref # container for objects that want", "len(self._indirections) def goesThroughGen(self, obj=None, objId=None): if obj is None: assert", "in parentObjRef.goesThroughGen(child): # don't yield, container might lose this element", "return container def getContainerGen(self, getInstance=False): # try to get a", "continue traversing the object graph via one attr, # choose", "__builtin__ will have parentDict==None if parentDict is None: return key", "it will discover every object. Checks container sizes at ever-increasing", "in size over the last ' '5 periods (%s items", "name) self._leakDetector = leakDetector self.notify = self._leakDetector.notify self._on = on", "Job to destroy any container refs that are no longer", "size over the last ' '5 periods (%s items at", "evalStr[:len(bis)] != bis: evalStr = '%s.%s' % (bis, evalStr) try:", "'%s.%s' % (bis, evalStr) try: container = eval(evalStr) except NameError,", "traversal curObjRef = None while True: # yield up here", "self._leakDetector._findContainersJob._id2discoveredStartRef ids = _id2discoveredStartRef.keys() for id in ids: yield None", "if curObjRef is None: # this ref set is empty,", "base.leakContainer[key] taskMgr.doMethodLater(10, leakContainer, 'leakContainer-%s' % serialNum()) if task: return task.done", "# try to get a handle on the container by", "= leakDetector self.notify = self._leakDetector.notify self._otn = otn self._doneCallback =", "firstCheckDelay = 60. * 15. # divide by two, since", "return result class FindContainers(Job): \"\"\" Explore the Python graph, looking", "types, weakref, random, __builtin__ def _createContainerLeak(): def leakContainer(task=None): base =", "(1)') else: self.notify.warning( '%s (%s) grew %.2f%% in %.2f minutes", "= _id2discoveredStartRef.keys() for id in ids: yield None try: for", "%s' % ( parentObjRef, safeRepr(key))) continue hasLength = self._hasLength(attr) notDeadEnd", "in the references (i.e. base.loader.base) for goesThrough in parentObjRef.goesThroughGen(curObj[key]): #", "doneCallback) jobMgr.add(j) return j def getPathsToContainersNamed(self, name, on, doneCallback=None): j", "idx2id2len[self._index-5]): # if size has consistently increased over the last", "objId in idx2id2len[self._index-2] and objId in idx2id2len[self._index-3]): diff2 = idx2id2len[self._index-1][objId]", "(objId in idx2id2len[self._index-4] and objId in idx2id2len[self._index-5]): # if size", "30.) # main dict of id(container)->containerRef self._id2ref = {} #", "nextIndirection=nextIndirection) if getInstance: lenDict = len('.__dict__') if str[-lenDict:] == '.__dict__':", "destroy(self): ContainerLeakDetector.removePrivateObj(self.__dict__) Job.destroy(self) def getPriority(self): return Job.Priorities.Normal def run(self): try:", "__dev__: raise yield Job.Done class CheckContainers(Job): \"\"\" Job to check", "Job.__init__(self, name) self._leakDetector = leakDetector self.notify = self._leakDetector.notify self._otn =", "ref): pass try: base except: pass else: ref = ObjectRef(Indirection(evalStr='base.__dict__'),", "types.FloatType, types.IntType, types.LongType, types.NoneType, types.NotImplementedType, types.TypeType, types.CodeType, types.FunctionType, types.StringType, types.UnicodeType,", "on us indirections = self._indirections for indirection in indirections: yield", "= obj.__class__.__name__ except: pass else: # prevent infinite recursion in", "is not based off of curObj, use the global__builtin__ namespace", "from ['key'] to .key if prevIndirection is not None and", "self._id2baseStartRef[id(base.__dict__)] = ref for i in self._addContainerGen(base.__dict__, ref): pass try:", "yield None except: # TODO self.notify.debug('caught exception in getContainerByIdGen (2)')", "in self._addContainerGen(child, objRef): yield None if notDeadEnd: self._addDiscoveredStartRef(child, objRef) curObjRef", "2.: 1 2 4 8 16 32 64 128 256", "storedItem def run(self): try: # this yields a different set", "continue self._leakDetector._index2containerId2len[self._index][objId] = cLen # compare the current len of", "getContainerByIdGen (2)') else: msg = ('%s (%s) consistently increased in", "yield None if i > 0: prevIndirection = indirections[i-1] else:", "otn self._doneCallback = doneCallback self._ldde = self._leakDetector._getDestroyEvent() self.accept(self._ldde, self._handleLDDestroy) ContainerLeakDetector.addPrivateObj(self.__dict__)", "* 2.: 1 3 7 15 31 63 127 255", "= curObjRef # if we hit a dead end, start", "try: startRefWorkingList = workingListSelector.next() except StopIteration: # do relative #", "source=self._id2discoveredStartRef) self.notify = self._leakDetector.notify ContainerLeakDetector.addPrivateObj(self.__dict__) # set up the base", "if config.GetBool('leak-tasks', 0): _createTaskLeak() # don't check our own tables", "return self.getString() class ObjectRef: \"\"\" stores a reference to a", "len(attrs) + 1 for attr in attrs: yield None index", "len(indirections)-1: nextIndirection = indirections[i+1] else: nextIndirection = None str +=", "the non-weakref object reference handling if random.random() < .01: key", "None: notDeadEnd = not self._isDeadEnd(attr) if hasLength or notDeadEnd: #", "is empty, choose another break # make a generator that", "__builtin__.leakDetectors = {} ref = ObjectRef(Indirection(evalStr='leakDetectors'), id(leakDetectors)) self._id2baseStartRef[id(leakDetectors)] = ref", "parentObjRef) yield None if hasLength: for i in self._addContainerGen(attr, objRef):", "dict of id(container)->containerRef self._id2ref = {} # storage for results", "__builtin__ at the start if it's not already there bis", "while loop from various points yield None #import pdb;pdb.set_trace() if", "set by 2/3 minLen *= 3. workingListSelector = flywheel([self._baseStartRefWorkingList, self._discoveredStartRefWorkingList],", "self.setPriority(Job.Priorities.Min) jobMgr.add(self) def destroy(self): messenger.send(self._getDestroyEvent()) self.ignoreAll() if self._pruneContainersJob is not", "in built-in containers related to methods if className == 'method-wrapper':", "attrs: yield None index += 1 numAttrsLeft -= 1 hasLength", "msg = ('%s (%s) consistently increased in size over the", "spammy if diff > 20: if diff > idx2id2len[self._index-1][objId]: minutes", "types.LongType): if (existingRef.getNumIndirections() >= ref.getNumIndirections()): # the ref that we", "None numKeysLeft -= 1 try: attr = curObj[key] except KeyError,", "as a key to be looked up in a dict.", "objRef = ObjectRef(Indirection(evalStr='[%s]' % index), id(curObj[index]), parentObjRef) yield None if", "the last ' '5 periods (%s items at last measurement,", "of an eval, or as a key to be looked", "if hasLength or notDeadEnd: # prevent cycles in the references", "= leakDetector self.notify = self._leakDetector.notify self._on = on self._doneCallback =", "objId = id(obj) if objId in self._id2discoveredStartRef: existingRef = self._id2discoveredStartRef[objId]", "be weakref'd, and use an instance # since it can't", "it's not already there bis = '__builtin__' if evalStr[:len(bis)] !=", "may visit the same object many times but eventually it", "StopIteration: # do relative # of traversals on each set", "TODO: store string components that are duplicates of strings in", "ContainerLeakDetector.addPrivateObj(self.__dict__) # set up the base containers, the ones that", "try to look up this key in the curObj dictionary", "in self._leakDetector.getContainerNameByIdGen(objId): yield None self.notify.debug( '%s no longer exists; caught", "sent when a leak is detected # passes description string", "in getContainerByIdGen (3)') else: msg = ('leak detected: %s (%s)", "= self._getContainerByEval(evalStr, curObj=curObj) if id(o) == objId: break for indirection", "yield None except: # reference is invalid, remove it del", "the actual object, # that could cause a memory leak", "class FailedEval(Exception): pass def __init__(self, indirection, objId, other=None): self._indirections =", "self.notify.debug('caught exception in getContainerByIdGen (1)') else: self.notify.warning( '%s (%s) grew", "key in the curObj dictionary curObj = indirection.dereferenceDictKey(curObj) evalStr =", "is now %s (%s)' % (contName, safeRepr(container), e)) self._leakDetector.removeContainerById(objId) continue", "'' curObj = None # make sure the indirections don't", "# if we already are storing a reference to this", "self.goesThrough(objId=objId) self._indirections.append(indirection) # make sure our indirections don't get destroyed", "traversals on each set based on how many refs it", "contId in self._id2ref: for existingRepr in self._id2ref[contId].getEvalStrGen(): yield None for", "if not goesThrough: objRef = ObjectRef(Indirection(evalStr='[%s]' % index), id(curObj[index]), parentObjRef)", "that looks for leaking containers. To reduce memory usage, this", "self._serialNum def getLeakEvent(self): # sent when a leak is detected", "try again curObjRef = None continue self.notify.debug('--> %s' % curObjRef)", "lose this element pass if not goesThrough: objRef = ObjectRef(Indirection(evalStr='[%s]'", "== 0: # ref set is empty, choose another break", "detected # passes description string as argument return 'containerLeakDetected-%s' %", "\"\"\" notify = directNotify.newCategory(\"ObjectRef\") class FailedEval(Exception): pass def __init__(self, indirection,", "every time we start a new traversal # force creation", "as part of an eval, or as a key to", "None except: # ref is invalid self.notify.debug('invalid startRef, stored as", "this element pass if not goesThrough: objRef = ObjectRef(Indirection(evalStr='[%s]' %", "instance dict #import pdb;pdb.set_trace() evalStr = '' curObj = None", "None startRefWorkingList.refGen = fw if curObjRef is None: # this", "to measure things such as C++ memory usage, scene graph", "not index into %s with key %s' % ( parentObjRef,", "_createContainerLeak(): def leakContainer(task=None): base = getBase() if not hasattr(base, 'leakContainer'):", "the new ref return storedItem = ref # if we", "1 1.5 2.3 3.4 5.1 7.6 11.4 17.1 25.6 38.4", "is individually eval'd since the dict key might have been", "eval'd since the dict key might have been garbage-collected TODO:", "return self.dictKey is not NoDictKey def _getNonWeakDictKey(self): if not self._isWeakRef:", "return self._id2ref[id].getContainerGen(**kwArgs) def getContainerById(self, id): for result in self._id2ref[id].getContainerGen(): pass", "longer exists; caught exception in getContainerById (%s)' % ( contName,", "'__len__') def _addContainerGen(self, cont, objRef): contId = id(cont) # if", "= None while True: # yield up here instead of", "except: # some custom classes don't do well when iterated", "the object graph via one key of the dict, #", "= otn self._doneCallback = doneCallback self._ldde = self._leakDetector._getDestroyEvent() self.accept(self._ldde, self._handleLDDestroy)", "self._id2ref = self._leakDetector._id2ref # these hold objects that we should", "self.dictKey = NoDictKey # is the dictKey a weak reference?", "in self._id2ref[id].getContainerGen(): pass return result def getContainerNameByIdGen(self, id, **kwArgs): return", "of an existing ref? if other is not None: for", "self._indirections for indirection in indirections: yield None indirection.acquire() for indirection", "= False if useEval: # eval/repr succeeded, store as an", "None nextIndirection = None # make sure the indirections don't", "def __init__(self, name, leakDetector, on, doneCallback=None): Job.__init__(self, name) self._leakDetector =", "e: print 'FPTObjsNamed job caught exception: %s' % e if", "self._hasLength(attr) notDeadEnd = False if curObjRef is None: notDeadEnd =", "= self._leakDetector.notify self._otn = otn self._doneCallback = doneCallback self._ldde =", "yield None indirection.acquire() for indirection in indirections: yield None if", "types.TupleType): return True # if it's an internal object, ignore", "> 0 and diff3 > 0 and diff4 > 0", "reference, # this isn't perfect, for example if base.myObject is", "jobMgr.add(self._checkContainersJob) return task.done def _scheduleNextPruning(self): taskMgr.doMethodLater(self._pruneTaskPeriod, self._pruneObjectRefs, self._getPruneTaskName()) def _pruneObjectRefs(self,", "1023 2047 # * 1.5: 1 2.5 4.75 8.1 13.2", "in a dict. Each dictionary dereference is individually eval'd since", "is not None: jobMgr.remove(self._checkContainersJob) self._checkContainersJob = None jobMgr.remove(self._findContainersJob) self._findContainersJob =", "return len(startObj) except: return 1 def _isDeadEnd(self, obj, objName=None): if", "not None and prevIndirection.evalStr is not None: if prevIndirection.evalStr[-len(instanceDictStr):] ==", "still valid while True: yield None try: curObjRef = startRefWorkingList.refGen.next()", "= curObjRef curObjRef = None try: for containerRef in self._leakDetector.getContainerByIdGen(startId):", ".key if prevIndirection is not None and prevIndirection.evalStr is not", "True try: className = obj.__class__.__name__ except: pass else: # prevent", "go away on us indirections = self._indirections for indirection in", "* self._checkDelayScale def _checkForLeaks(self, task=None): self._index2delay[len(self._index2containerId2len)] = self._nextCheckDelay self._checkContainersJob =", "new set if len(startRefWorkingList.source) == 0: # ref set is", "= leakDetector self._id2ref = self._leakDetector._id2ref # these hold objects that", "FPTObjsOfType(name, self, ot, doneCallback) jobMgr.add(j) return j def getPathsToContainersNamed(self, name,", "safeRepr(key)) del base.leakContainer[key] taskMgr.doMethodLater(10, leakContainer, 'leakContainer-%s' % serialNum()) if task:", "item if type(curObjRef) in (types.IntType, types.LongType): startId = curObjRef curObjRef", "63 127 255 511 1023 2047 # * 1.5: 1", "type(obj) in (types.BooleanType, types.BuiltinFunctionType, types.BuiltinMethodType, types.ComplexType, types.FloatType, types.IntType, types.LongType, types.NoneType,", "if nextIndirection is not None and self.evalStr[-len(instanceDictStr):] == instanceDictStr: return", "for indirection in indirections: yield None indirection.release() yield str def", "might lose this element pass if not goesThrough: objRef =", "= False def destroy(self): # re-entrant self.dictKey = NoDictKey def", "None self._pruneContainersJob = None if firstCheckDelay is None: firstCheckDelay =", "a container return self._id2ref[id].getContainerGen(**kwArgs) def getContainerById(self, id): for result in", "dir(curObj) except: pass else: try: index = -1 attrs =", "each container to past lens if self._index > 0: idx2id2len", "working copies so that our iterations aren't disturbed by changes", "== '.__dict__': evalStr = evalStr[:-lenDict] # TODO: check that this", "- idx2id2len[self._index-5][objId] if diff > 0 and diff2 > 0", "self._leakDetector.getContainerNameByIdGen(id): yield None except: pass else: print 'GPTCN(' + self._on", "firstCheckDelay = None): Job.__init__(self, name) self._serialNum = serialNum() self._findContainersJob =", "getContainerIds(self): return self._id2ref.keys() def getContainerByIdGen(self, id, **kwArgs): # return a", "diff > idx2id2len[self._index-1][objId]: minutes = (self._leakDetector._index2delay[self._index] - self._leakDetector._index2delay[self._index-1]) / 60.", "(self._leakDetector._index2delay[self._index] - self._leakDetector._index2delay[self._index-1]) / 60. name = self._leakDetector.getContainerNameById(objId) if idx2id2len[self._index-1][objId]", "'' prevIndirection = None curIndirection = None nextIndirection = None", "in self._id2ref: for existingRepr in self._id2ref[contId].getEvalStrGen(): yield None for newRepr", "idx2id2len[self._index-4][objId] - idx2id2len[self._index-5][objId] if diff > 0 and diff2 >", "than the new ref return storedItem = ref # if", "else: key = self.dictKey() if key is None: return '<garbage-collected", "# that could cause a memory leak assert type(objId) in", "pandac.PandaModules import PStatCollector from direct.directnotify.DirectNotifyGlobal import directNotify from direct.showbase.PythonUtil import", "id in self._id2ref: self._id2ref[id].destroy() del self._id2ref[id] def run(self): # start", "graph? try: return len(startObj) except: return 1 def _isDeadEnd(self, obj,", "messenger.send(self._getDestroyEvent()) self.ignoreAll() if self._pruneContainersJob is not None: jobMgr.remove(self._pruneContainersJob) self._pruneContainersJob =", "('im_self', 'im_class'): return True try: className = obj.__class__.__name__ except: pass", "(%s) consistently increased in size over the last ' '3", "FPTObjsNamed(Job): def __init__(self, name, leakDetector, on, doneCallback=None): Job.__init__(self, name) self._leakDetector", "is invalid, remove it del _id2discoveredStartRef[id] except Exception, e: print", "dictKey instead of evalStr self.evalStr = evalStr self.dictKey = NoDictKey", "return task.done leakTask() class NoDictKey: pass class Indirection: \"\"\" Represents", "> idx2id2len[self._index-1][objId]: minutes = (self._leakDetector._index2delay[self._index] - self._leakDetector._index2delay[self._index-1]) / 60. name", "self._leakDetector.getContainerByIdGen(objId): yield None except: # TODO self.notify.debug('caught exception in getContainerByIdGen", "points yield None #import pdb;pdb.set_trace() if curObjRef is None: #", "lookup, pass dictKey instead of evalStr self.evalStr = evalStr self.dictKey", "2/3 minLen *= 3. workingListSelector = flywheel([self._baseStartRefWorkingList, self._discoveredStartRefWorkingList], [baseLen/minLen, discLen/minLen])", "except NameError, ne: return None except AttributeError, ae: return None", "objRef): contId = id(cont) # if this container is new,", "assert not self.goesThrough(objId=objId) self._indirections.append(indirection) # make sure our indirections don't", "3. workingListSelector = flywheel([self._baseStartRefWorkingList, self._discoveredStartRefWorkingList], [baseLen/minLen, discLen/minLen]) yield None continue", "except Exception, e: print 'FPTObjsOfType job caught exception: %s' %", "discover every object. Checks container sizes at ever-increasing intervals. \"\"\"", "ref for i in self._addContainerGen(__builtin__.__dict__, ref): pass try: base except:", "try: for containerRef in self._leakDetector.getContainerByIdGen(startId): yield None except: # ref", "ids = _id2discoveredStartRef.keys() for id in ids: yield None try:", "dictionary curObj = indirection.dereferenceDictKey(curObj) evalStr = '' for indirection in", "etc.) \"\"\" notify = directNotify.newCategory(\"ObjectRef\") class FailedEval(Exception): pass def __init__(self,", "name) self._serialNum = serialNum() self._findContainersJob = None self._checkContainersJob = None", "a key to be looked up in a dict. Each", "# check to make sure the eval succeeded if hash(keyEval)", "% safeRepr(key)) del base.leakContainer[key] taskMgr.doMethodLater(10, leakContainer, 'leakContainer-%s' % serialNum()) if", "def _createTaskLeak(): leakTaskName = uniqueName('leakedTask') leakDoLaterName = uniqueName('leakedDoLater') def nullTask(task=None):", "id(simbase.__dict__)) self._id2baseStartRef[id(simbase.__dict__)] = ref for i in self._addContainerGen(simbase.__dict__, ref): pass", "'.%s' % self.evalStr[2:-2] return self.evalStr # we're stored as a", "for leaks ContainerLeakDetector.addPrivateObj(ContainerLeakDetector.PrivateIds) ContainerLeakDetector.addPrivateObj(self.__dict__) self.setPriority(Job.Priorities.Min) jobMgr.add(self) def destroy(self): messenger.send(self._getDestroyEvent()) self.ignoreAll()", "= FPTObjsOfType(name, self, ot, doneCallback) jobMgr.add(j) return j def getPathsToContainersNamed(self,", "keep a set of all visited objects; it may visit", "if curObjRef is None: notDeadEnd = not self._isDeadEnd(attr) if hasLength", "that exist # just to measure things such as C++", "instead of evalStr self.evalStr = evalStr self.dictKey = NoDictKey #", "cut down the traversals of the larger set by 2/3", "containerRef in self._leakDetector.getContainerByIdGen(startId): yield None except: # ref is invalid", "hasattr(container, '__class__'): cName = container.__class__.__name__ else: cName = container.__name__ if", "to the # top of the while loop from various", "index): Job.__init__(self, name) self._leakDetector = leakDetector self.notify = self._leakDetector.notify self._index", "'%s is no longer a container, it is now %s", "and diff5 > 0: name = self._leakDetector.getContainerNameById(objId) try: for container", "def getPathsToContainers(self, name, ot, doneCallback=None): j = FPTObjsOfType(name, self, ot,", "20: if diff > idx2id2len[self._index-1][objId]: minutes = (self._leakDetector._index2delay[self._index] - self._leakDetector._index2delay[self._index-1])", "= set() def __init__(self, name, firstCheckDelay = None): Job.__init__(self, name)", "container sizes and find potential leaks; sub-job of ContainerLeakDetector \"\"\"", "leaks; sub-job of ContainerLeakDetector \"\"\" ReprItems = 5 def __init__(self,", "print 'FPTObjsOfType job caught exception: %s' % e if __dev__:", "Job.Priorities.Low @staticmethod def getStartObjAffinity(startObj): # how good of a starting", "pdb;pdb.set_trace() if curObjRef is None: # choose an object to", "empty, choose another # the base set should never be", "in self.getEvalStrGen(): pass return result class FindContainers(Job): \"\"\" Explore the", "getPathsToContainers(self, name, ot, doneCallback=None): j = FPTObjsOfType(name, self, ot, doneCallback)", "FailedEval(Exception): pass def __init__(self, indirection, objId, other=None): self._indirections = []", "# # delay from job start # fib: 1 2", "_scheduleNextPruning(self): taskMgr.doMethodLater(self._pruneTaskPeriod, self._pruneObjectRefs, self._getPruneTaskName()) def _pruneObjectRefs(self, task=None): self._pruneContainersJob = PruneObjectRefs(", "handle strings if type(objName) == types.StringType and objName in ('im_self',", "class LeakKey: pass base.leakContainer[(LeakKey(),)] = {} # test the non-weakref", "del self._id2ref del self._index2containerId2len del self._index2delay def _getDestroyEvent(self): # sent", "next start ref from this sequence and see if it's", "container to an element of the container. Stored as a", "test the non-weakref object reference handling if random.random() < .01:", "None curIndirection = indirections[i] if i < len(indirections)-1: nextIndirection =", "increased over the last 5 checks, # send out a", "else: if hasattr(container, '__class__'): cName = container.__class__.__name__ else: cName =", "None except: # TODO self.notify.debug('caught exception in getContainerByIdGen (1)') else:", "prevent cycles (i.e. base.loader.base.loader) assert not self.goesThrough(objId=objId) self._indirections.append(indirection) # make", "don't get destroyed while we're using them for ind in", "for containers self._findContainersJob = FindContainers( '%s-findContainers' % self.getJobName(), self) jobMgr.add(self._findContainersJob)", "= indirection.dereferenceDictKey(curObj) evalStr = '' yield None o = self._getContainerByEval(evalStr,", "bat workingListSelector = nullGen() # this holds the current step", "diff2 > 0 and diff3 > 0 and diff4 >", "except StopIteration: # do relative # of traversals on each", "ids: yield None try: for container in self._leakDetector.getContainerByIdGen(id): yield None", "def _getDestroyEvent(self): # sent when leak detector is about to", "(%s)' % (contName, safeRepr(container), e)) self._leakDetector.removeContainerById(objId) continue self._leakDetector._index2containerId2len[self._index][objId] = cLen", "are yielding during the iteration self.notify.debug('could not index into %s", "if id(obj) in ContainerLeakDetector.PrivateIds: return True # prevent crashes in", "result in self._id2ref[id].getContainerGen(): pass return result def getContainerNameByIdGen(self, id, **kwArgs):", "objRef = ObjectRef(Indirection(evalStr='.__dict__'), id(child), parentObjRef) yield None if hasLength: for", "indirection in indirections: yield None indirection.release() if getInstance: lenDict =", "task: return task.done leakContainer() def _createTaskLeak(): leakTaskName = uniqueName('leakedTask') leakDoLaterName", "def getFinalIndirectionStr(self): prevIndirection = None if len(self._indirections) > 1: prevIndirection", "'<garbage-collected dict key>' return key def dereferenceDictKey(self, parentDict): # look", "+ '):' + self.getJobName() + ': ' + ptc except", "255 511 1023 2047 # * 1.5: 1 2.5 4.75", "self._leakDetector.getContainerIds() for id in ids: yield None try: for container", "nextIndirection = None # make sure the indirections don't go", "{} ref = ObjectRef(Indirection(evalStr='leakDetectors'), id(leakDetectors)) self._id2baseStartRef[id(leakDetectors)] = ref for i", "self._leakDetector.getContainerIds() # record the current len of each container for", "return self._id2ref[id].getEvalStrGen(**kwArgs) def getContainerNameById(self, id): if id in self._id2ref: return", "getEvalStrGen(self, getInstance=False): str = '' prevIndirection = None curIndirection =", "(contName, safeRepr(container), e)) self._leakDetector.removeContainerById(objId) continue self._leakDetector._index2containerId2len[self._index][objId] = cLen # compare", "loop from various points yield None #import pdb;pdb.set_trace() if curObjRef", "container might lose this element pass if not goesThrough: objRef", "curObjRef = objRef continue if type(curObj) is types.DictType: key =", "diff4 = idx2id2len[self._index-3][objId] - idx2id2len[self._index-4][objId] diff5 = idx2id2len[self._index-4][objId] - idx2id2len[self._index-5][objId]", "for result in self.getEvalStrGen(): pass return result class FindContainers(Job): \"\"\"", "created this would return # false, allowing a ref to", "be garbage-collected' % safeRepr(key)) del base.leakContainer[key] taskMgr.doMethodLater(10, leakContainer, 'leakContainer-%s' %", "doneCallback=None): Job.__init__(self, name) self._leakDetector = leakDetector self.notify = self._leakDetector.notify self._on", "methods if className == 'method-wrapper': return True return False def", "yield None for newRepr in objRef.getEvalStrGen(): yield None if contId", "container = eval(evalStr) except NameError, ne: return None except AttributeError,", "%s' % e if __dev__: raise yield Job.Done class CheckContainers(Job):", "if prevIndirection.evalStr[-len(instanceDictStr):] == instanceDictStr: return '.%s' % self.evalStr[2:-2] return self.evalStr", "> 0 and diff2 > 0 and diff3 > 0:", "a random walk of the Python objects to discover containers", "curObjRef = objRef del attr except StopIteration, e: pass del", "if config.GetBool('leak-container', 0): _createContainerLeak() if config.GetBool('leak-tasks', 0): _createTaskLeak() # don't", "self._id2ref[id].getContainerGen(**kwArgs) def getContainerById(self, id): for result in self._id2ref[id].getContainerGen(): pass return", "concise than the new ref return if objId in self._id2ref:", "for objects that support __len__() \"\"\" def __init__(self, name, leakDetector):", "curObjRef is None and random.randrange(numAttrsLeft) == 0: curObjRef = objRef", "copy of the current objRef parentObjRef = curObjRef # if", "pass else: if hasattr(container, '__class__'): cName = container.__class__.__name__ else: cName", "hash(dictKey): useEval = False if useEval: # eval/repr succeeded, store", "in ContainerLeakDetector.PrivateIds: return True # prevent crashes in objects that", "def __init__(self, name, firstCheckDelay = None): Job.__init__(self, name) self._serialNum =", "= '' curObj = None # make sure the indirections", "perfect, for example if base.myObject is reassigned # to a", "# fib: 1 2 4 7 12 20 33 54", "from often and not-as-often, # respectively self._id2baseStartRef = {} self._id2discoveredStartRef", "_isDeadEnd(self, obj, objName=None): if type(obj) in (types.BooleanType, types.BuiltinFunctionType, types.BuiltinMethodType, types.ComplexType,", "such as C++ memory usage, scene graph size, # framerate,", "a warning diff4 = idx2id2len[self._index-3][objId] - idx2id2len[self._index-4][objId] diff5 = idx2id2len[self._index-4][objId]", "+= 1 def release(self): self._refCount -= 1 if self._refCount ==", "continue self.notify.debug('--> %s' % curObjRef) #import pdb;pdb.set_trace() # store a", "return 'checkForLeakingContainers-%s' % self._serialNum def _getPruneTaskName(self): return 'pruneLeakingContainerRefs-%s' % self._serialNum", "(self._otn.lower() not in 'dict') yield None try: for container in", "garbage collection of the container if possible stored as a", "ref set is empty, choose another # the base set", "# test the non-weakref object reference handling if random.random() <", "not None: # eval('curObj.foo.bar.someDict') evalStr = 'curObj%s' % evalStr else:", "_hasLength(self, obj): return hasattr(obj, '__len__') def _addContainerGen(self, cont, objRef): contId", "= objRef del key del attr continue try: childNames =", "an indirection through a dictionary? return self.dictKey is not NoDictKey", "# if it's an internal object, ignore it if id(obj)", "CPU time numKeysLeft = len(keys) + 1 for key in", "\"leakDetectors\"): __builtin__.leakDetectors = {} ref = ObjectRef(Indirection(evalStr='leakDetectors'), id(leakDetectors)) self._id2baseStartRef[id(leakDetectors)] =", "self._leakDetector = leakDetector self._id2ref = self._leakDetector._id2ref # these hold objects", "idx2id2len[self._index-3][objId] - idx2id2len[self._index-4][objId] diff5 = idx2id2len[self._index-4][objId] - idx2id2len[self._index-5][objId] if diff", "dict key might have been garbage-collected TODO: store string components", "self._isDeadEnd(attr, key) if hasLength or notDeadEnd: # prevent cycles in", "31 63 127 255 511 1023 2047 # * 1.5:", "except Exception, e: print 'FindContainers job caught exception: %s' %", "will force the leak detector to hold a normal 'non-weak'", "None \"\"\" if (self._index > 2 and objId in idx2id2len[self._index-2]", "copies so that our iterations aren't disturbed by changes to", "ref for i in self._addContainerGen(base.__dict__, ref): pass try: simbase except:", "removeContainerById(self, id): if id in self._id2ref: self._id2ref[id].destroy() del self._id2ref[id] def", "if self._refCount == 0: self.destroy() def isDictKey(self): # is this", "self._discoveredStartRefWorkingList = ScratchPad(refGen=nullGen(), source=self._id2discoveredStartRef) self.notify = self._leakDetector.notify ContainerLeakDetector.addPrivateObj(self.__dict__) # set", "size, # framerate, etc. See LeakDetectors.py if not hasattr(__builtin__, \"leakDetectors\"):", "curObjRef = containerRef try: for curObj in curObjRef.getContainerGen(): yield None", "% self.getJobName(), self, len(self._index2containerId2len)) self.acceptOnce(self._checkContainersJob.getFinishedEvent(), self._scheduleNextLeakCheck) jobMgr.add(self._checkContainersJob) return task.done def", "for attr in attrs: yield None index += 1 numAttrsLeft", "self._pruneContainersJob is not None: jobMgr.remove(self._pruneContainersJob) self._pruneContainersJob = None if self._checkContainersJob", "== 0: curObjRef = objRef del attr except StopIteration, e:", "and diff2 > 0 and diff3 > 0: name =", "getContainerByIdGen (1)') else: self.notify.warning( '%s (%s) grew %.2f%% in %.2f", "self.notify.warning(msg) yield None messenger.send(self._leakDetector.getLeakEvent(), [container, name]) if config.GetBool('pdb-on-leak-detect', 0): import", "= eval(evalStr) except NameError, ne: return None except AttributeError, ae:", "pass try: base except: pass else: ref = ObjectRef(Indirection(evalStr='base.__dict__'), id(base.__dict__))", "i in self._addContainerGen(child, objRef): yield None if notDeadEnd: self._addDiscoveredStartRef(child, objRef)", "this one (obj.__dict__[keyName] == obj.keyName) if nextIndirection is not None", "except Exception, e: # this container no longer exists if", "and diff3 > 0: name = self._leakDetector.getContainerNameById(objId) try: for container", "self.notify = self._leakDetector.notify ContainerLeakDetector.addPrivateObj(self.__dict__) # set up the base containers,", "assert type(objId) in (types.IntType, types.LongType) # prevent cycles (i.e. base.loader.base.loader)", "not None: jobMgr.remove(self._pruneContainersJob) self._pruneContainersJob = None if self._checkContainersJob is not", "parentObjRef.goesThroughGen(curObj[key]): # don't yield, container might lose this element pass", "force the leak detector to hold a normal 'non-weak' reference", "1 2 4 8 16 32 64 128 256 512", "= None curIndirection = None nextIndirection = None # make", "at last measurement, current contents: %s)' % (name, itype(container), idx2id2len[self._index][objId],", "except: pass else: ref = ObjectRef(Indirection(evalStr='base.__dict__'), id(base.__dict__)) self._id2baseStartRef[id(base.__dict__)] = ref", "self._isWeakRef = True except TypeError, e: ContainerLeakDetector.notify.debug('could not weakref dict", "while True: yield None try: curObjRef = startRefWorkingList.refGen.next() break except", "name, leakDetector, index): Job.__init__(self, name) self._leakDetector = leakDetector self.notify =", "self._leakDetector._index2containerId2len for objId in idx2id2len[self._index]: yield None if objId in", "is not None and self.evalStr[-len(instanceDictStr):] == instanceDictStr: return self.evalStr[:-len(instanceDictStr)] #", "def destroy(self): for indirection in self._indirections: indirection.release() del self._indirections def", "itr continue except Exception, e: print 'FindContainers job caught exception:", "self._leakDetector._index2containerId2len[self._index] = {} ids = self._leakDetector.getContainerIds() # record the current", "longer valid. Checks validity by asking for each container \"\"\"", "{} # storage for results of check-container job self._index2containerId2len =", "nullDoLater, uniqueName(leakDoLaterName)) taskMgr.doMethodLater(10, leakTask, 'doLeakTask-%s' % serialNum()) if task: return", "is types.DictType: key = None attr = None keys =", "it as an evalStr keyRepr = safeRepr(dictKey) useEval = False", "can repr/eval the key, store it as an evalStr keyRepr", "is None: return key return parentDict[key] def getString(self, prevIndirection=None, nextIndirection=None):", "if i < len(indirections)-1: nextIndirection = indirections[i+1] else: nextIndirection =", "= [] while 1: yield None try: attr = itr.next()", "task.cont def nullDoLater(task=None): return task.done def leakTask(task=None, leakTaskName=leakTaskName): base =", "check to make sure the eval succeeded if hash(keyEval) !=", "leakDetector self.notify = self._leakDetector.notify ContainerLeakDetector.addPrivateObj(self.__dict__) def destroy(self): ContainerLeakDetector.removePrivateObj(self.__dict__) Job.destroy(self) def", "> 0: prevIndirection = indirections[i-1] else: prevIndirection = None curIndirection", "for ind in other._indirections: self._indirections.append(ind) # make sure we're not", "len(container) except Exception, e: # this container no longer exists", "a container, it is now %s (%s)' % (contName, safeRepr(container),", "# prevent crashes in objects that define __cmp__ and don't", "traversals of the larger set by 2/3 minLen *= 3.", "from direct.showbase.PythonUtil import itype, serialNum, safeRepr, fastRepr from direct.showbase.Job import", "on, doneCallback=None): j = FPTObjsNamed(name, self, on, doneCallback) jobMgr.add(j) return", "= idx2id2len[self._index-2][objId] - idx2id2len[self._index-3][objId] if self._index <= 4: if diff", "that could cause a memory leak assert type(objId) in (types.IntType,", "(self._id2ref[objId].getNumIndirections() >= ref.getNumIndirections()): # the ref that we already have", "an evalStr keyRepr = safeRepr(dictKey) useEval = False try: keyEval", "result in self.getEvalStrGen(): pass return result class FindContainers(Job): \"\"\" Explore", "of check-container job self._index2containerId2len = {} self._index2delay = {} if", "self._leakDetector = leakDetector self.notify = self._leakDetector.notify self._index = index ContainerLeakDetector.addPrivateObj(self.__dict__)", "syntax from ['key'] to .key if prevIndirection is not None", "# how good of a starting object is this object", "id(obj) in ContainerLeakDetector.PrivateIds: return True # prevent crashes in objects", "curObjRef = None if hasattr(curObj, '__dict__'): child = curObj.__dict__ hasLength", "# don't yield, container might lose this element pass if", "= len('.__dict__') if evalStr[-lenDict:] == '.__dict__': evalStr = evalStr[:-lenDict] #", "directNotify.newCategory(\"ContainerLeakDetector\") # set of containers that should not be examined", "1 for attr in attrs: yield None index += 1", "i in self._addContainerGen(__builtin__.__dict__, ref): pass try: base except: pass else:", "to be used as part of an eval, or as", "lenDict = len('.__dict__') if str[-lenDict:] == '.__dict__': str = str[:-lenDict]", "object-graph walker that looks for leaking containers. To reduce memory", "use the global__builtin__ namespace # put __builtin__ at the start", "be used to start an object graph traversal objId =", "self._id2ref or len(newRepr) < len(existingRepr): if contId in self._id2ref: self._leakDetector.removeContainerById(contId)", "a dead end, start over from another container curObjRef =", "idx2id2len[self._index][objId] - idx2id2len[self._index-1][objId] \"\"\" # this check is too spammy", "type(objName) == types.StringType and objName in ('im_self', 'im_class'): return True", "ae: return None except KeyError, ke: return None return container", "refs that are no longer valid. Checks validity by asking", "None self._checkContainersJob = None self._pruneContainersJob = None if firstCheckDelay is", "3.4 5.1 7.6 11.4 17.1 25.6 38.4 57.7 # #", "makeFlywheelGen( startRefWorkingList.source.values(), countFunc=lambda x: self.getStartObjAffinity(x), scale=.05): yield None startRefWorkingList.refGen =", "= 'curObj%s' % evalStr else: # this eval is not", "has consistently increased over the last 5 checks, # send", "ref.getContainerGen() failed') # that container is gone, try again curObjRef", "try: for ptc in self._leakDetector.getContainerNameByIdGen(id): yield None except: pass else:", "def getString(self, prevIndirection=None, nextIndirection=None): # return our contribution to the", "None if firstCheckDelay is None: firstCheckDelay = 60. * 15.", "if contId not in self._id2ref or len(newRepr) < len(existingRepr): if", "0): _createContainerLeak() if config.GetBool('leak-tasks', 0): _createTaskLeak() # don't check our", "id(child), parentObjRef) yield None if hasLength: for i in self._addContainerGen(child,", "compare the current len of each container to past lens", "% keyRepr return '[%s]' % keyRepr def __repr__(self): return self.getString()", "import itype, serialNum, safeRepr, fastRepr from direct.showbase.Job import Job import", "workingListSelector.next() except StopIteration: # do relative # of traversals on", "name, firstCheckDelay = None): Job.__init__(self, name) self._serialNum = serialNum() self._findContainersJob", "['key'] to .key if prevIndirection is not None and prevIndirection.evalStr", "valid. Checks validity by asking for each container \"\"\" def", "than the new ref return if objId in self._id2ref: if", "ref return storedItem = ref # if we already are", "of start refs every time we start a new traversal", "= True except TypeError, e: ContainerLeakDetector.notify.debug('could not weakref dict key", "previous indirection was an instance dict, change our syntax from", "object, don't store a second reference if objId in self._id2ref:", "self._id2ref[contId] = objRef def _addDiscoveredStartRef(self, obj, ref): # we've discovered", "= objRef def _addDiscoveredStartRef(self, obj, ref): # we've discovered an", "= uniqueName('leakedDoLater') def nullTask(task=None): return task.cont def nullDoLater(task=None): return task.done", "pass if useEval: # check to make sure the eval", "(%s items at last measurement, current contents: %s)' % (name,", "as a series of 'indirections' (obj.foo -> '.foo', dict[key] ->", "containers a # of times that is # proportional to", "def leakTask(task=None, leakTaskName=leakTaskName): base = getBase() taskMgr.add(nullTask, uniqueName(leakTaskName)) taskMgr.doMethodLater(1 <<", "== instanceDictStr: return '.%s' % self.evalStr[2:-2] return self.evalStr # we're", "by changes to the # definitive ref sets self._baseStartRefWorkingList =", "return our contribution to the full name of an object", "# put __builtin__ at the start if it's not already", "nullGen() # this holds the current step of the current", "base.loader.base) for goesThrough in parentObjRef.goesThroughGen(curObj[key]): # don't yield, container might", "if curObjRef is None and random.randrange(numKeysLeft) == 0: curObjRef =", "j = FPTObjsOfType(name, self, ot, doneCallback) jobMgr.add(j) return j def", "sure the indirections don't go away on us indirections =", "by # the object exploration algorithm, including objects that exist", "#import pdb;pdb.set_trace() if curObjRef is None: # choose an object", "at the start if it's not already there bis =", "jobMgr.remove(self._checkContainersJob) self._checkContainersJob = None jobMgr.remove(self._findContainersJob) self._findContainersJob = None del self._id2ref", "== instanceDictStr: return self.evalStr[:-len(instanceDictStr)] # if the previous indirection was", "our indirections don't get destroyed while we're using them for", "= eval(keyRepr) useEval = True except: pass if useEval: #", "KeyError, ke: return None return container def getContainerGen(self, getInstance=False): #", "None curIndirection = None nextIndirection = None # make sure", "if the previous indirection was an instance dict, change our", "candidate if curObjRef is None: notDeadEnd = not self._isDeadEnd(attr, key)", "fastRepr(container, maxLen=CheckContainers.ReprItems))) yield None \"\"\" if (self._index > 2 and", "5 checks, # send out a warning diff4 = idx2id2len[self._index-3][objId]", "any container refs that are no longer valid. Checks validity", "ContainerLeakDetector.addPrivateObj(self.__dict__) self.setPriority(Job.Priorities.Min) jobMgr.add(self) def destroy(self): messenger.send(self._getDestroyEvent()) self.ignoreAll() if self._pruneContainersJob is", "self.getStartObjAffinity(x), scale=.05): yield None startRefWorkingList.refGen = fw if curObjRef is", "a series of 'indirections' (obj.foo -> '.foo', dict[key] -> '[key]',", "uniqueName(leakTaskName)) taskMgr.doMethodLater(1 << 31, nullDoLater, uniqueName(leakDoLaterName)) taskMgr.doMethodLater(10, leakTask, 'doLeakTask-%s' %", "of instance dict #import pdb;pdb.set_trace() evalStr = '' curObj =", "support __len__() \"\"\" def __init__(self, name, leakDetector): Job.__init__(self, name) self._leakDetector", "objects that want to make sure they are found by", "continue traversing the object graph via one key of the", "@classmethod def removePrivateObj(cls, obj): cls.PrivateIds.remove(id(obj)) def _getCheckTaskName(self): return 'checkForLeakingContainers-%s' %", "None: jobMgr.remove(self._pruneContainersJob) self._pruneContainersJob = None if self._checkContainersJob is not None:", "hash(keyEval) != hash(dictKey): useEval = False if useEval: # eval/repr", "return True # prevent crashes in objects that define __cmp__", "# if this container is new, or the objRef repr", "index), id(curObj[index]), parentObjRef) yield None if hasLength: for i in", "= None # make sure the indirections don't go away", "> 2 and objId in idx2id2len[self._index-2] and objId in idx2id2len[self._index-3]):", "obj): cls.PrivateIds.add(id(obj)) @classmethod def removePrivateObj(cls, obj): cls.PrivateIds.remove(id(obj)) def _getCheckTaskName(self): return", "from direct.showbase.Job import Job import types, weakref, random, __builtin__ def", "0: curObjRef = objRef del attr except StopIteration, e: pass", "self._checkForLeaks, self._getCheckTaskName()) # delay between checks # fib: 1 1", "name) self._leakDetector = leakDetector self.notify = self._leakDetector.notify ContainerLeakDetector.addPrivateObj(self.__dict__) def destroy(self):", "> 20: if diff > idx2id2len[self._index-1][objId]: minutes = (self._leakDetector._index2delay[self._index] -", "will be garbage-collected' % safeRepr(key)) del base.leakContainer[key] taskMgr.doMethodLater(10, leakContainer, 'leakContainer-%s'", "2.3 3.4 5.1 7.6 11.4 17.1 25.6 38.4 57.7 #", "container is new, or the objRef repr is shorter than", "curObj is not None: # eval('curObj.foo.bar.someDict') evalStr = 'curObj%s' %", "49.3 74.9 113.3 171 self._nextCheckDelay = self._nextCheckDelay * self._checkDelayScale def", "an internal object, ignore it if id(obj) in ContainerLeakDetector.PrivateIds: return", "self._doneCallback: self._doneCallback(self) class FPTObjsNamed(Job): def __init__(self, name, leakDetector, on, doneCallback=None):", "firstCheckDelay is None: firstCheckDelay = 60. * 15. # divide", "return Job.Priorities.Normal def run(self): try: ids = self._leakDetector.getContainerIds() for id", "= None if len(self._indirections) > 1: prevIndirection = self._indirections[-2] return", "# since we cache the ids involved in this reference,", "None keys = curObj.keys() # we will continue traversing the", "checks, # send out a warning diff4 = idx2id2len[self._index-3][objId] -", "base except: pass else: ref = ObjectRef(Indirection(evalStr='base.__dict__'), id(base.__dict__)) self._id2baseStartRef[id(base.__dict__)] =", "if self.notify.getDebug(): for contName in self._leakDetector.getContainerNameByIdGen(objId): yield None self.notify.debug( '%s", "last ' '3 periods (%s items at last measurement, current", "e if __dev__: raise yield Job.Done def finished(self): if self._doneCallback:", "NameError, ne: return None except AttributeError, ae: return None except", "objId: break for indirection in indirections: yield None indirection.release() yield", "dictKey self._isWeakRef = False def destroy(self): # re-entrant self.dictKey =", "we originally pointed to yield self._getContainerByEval(evalStr, curObj=curObj) def getEvalStrGen(self, getInstance=False):", "= on self._doneCallback = doneCallback self._ldde = self._leakDetector._getDestroyEvent() self.accept(self._ldde, self._handleLDDestroy)", "else: print 'GPTC(' + self._otn + '):' + self.getJobName() +", "for container in _id2baseStartRef[id].getContainerGen(): yield None except: # reference is", "None indirection.release() if getInstance: lenDict = len('.__dict__') if evalStr[-lenDict:] ==", "are working copies so that our iterations aren't disturbed by", "rather than keep a set of all visited objects; it", "dict key keyRepr = safeRepr(self._getNonWeakDictKey()) # if the previous indirection", "len(keys) + 1 for key in keys: yield None numKeysLeft", "self._isWeakRef = False self._refCount = 0 if dictKey is not", "None #import pdb;pdb.set_trace() if curObjRef is None: # choose an", "objId=objId): pass return goesThrough def _getContainerByEval(self, evalStr, curObj=None): if curObj", "key %s' % ( parentObjRef, safeRepr(key))) continue hasLength = self._hasLength(attr)", "= ObjectRef(Indirection(evalStr='%s' % key), id(curObj[key])) else: objRef = ObjectRef(Indirection(dictKey=key), id(curObj[key]),", "in idx2id2len[self._index-5]): # if size has consistently increased over the", "# if we can repr/eval the key, store it as", "actual system so that Python will keep one copy and", "to base.myObject.otherObject.myObject for goesThrough in self.goesThroughGen(obj=obj, objId=objId): pass return goesThrough", "yield None numKeysLeft -= 1 try: attr = curObj[key] except", "if firstCheckDelay is None: firstCheckDelay = 60. * 15. #", "objects that support __len__() \"\"\" def __init__(self, name, leakDetector): Job.__init__(self,", "getPathsToContainersNamed(self, name, on, doneCallback=None): j = FPTObjsNamed(name, self, on, doneCallback)", "task.done leakTask() class NoDictKey: pass class Indirection: \"\"\" Represents the", "try: index = -1 attrs = [] while 1: yield", "True except TypeError, e: ContainerLeakDetector.notify.debug('could not weakref dict key %s'", "string as argument return 'containerLeakDetected-%s' % self._serialNum @classmethod def addPrivateObj(cls,", "container in self._leakDetector.getContainerByIdGen(id): yield None except: pass else: name =", "disturbed by changes to the # definitive ref sets self._baseStartRefWorkingList", "# divide by two, since the first check just takes", "None del self._id2ref del self._index2containerId2len del self._index2delay def _getDestroyEvent(self): #", "types.BuiltinFunctionType, types.BuiltinMethodType, types.ComplexType, types.FloatType, types.IntType, types.LongType, types.NoneType, types.NotImplementedType, types.TypeType, types.CodeType,", "parentObjRef.goesThrough(curObj[index]): # don't yield, container might lose this element pass", "class FPTObjsNamed(Job): def __init__(self, name, leakDetector, on, doneCallback=None): Job.__init__(self, name)", "the # definitive ref sets self._baseStartRefWorkingList = ScratchPad(refGen=nullGen(), source=self._id2baseStartRef) self._discoveredStartRefWorkingList", "is gone, try again curObjRef = None continue self.notify.debug('--> %s'", "self._addContainerGen(__builtin__.__dict__, ref): pass try: base except: pass else: ref =", "def _getNonWeakDictKey(self): if not self._isWeakRef: return self.dictKey else: key =", "one key of the dict, # choose it at random", "we are yielding during the iteration self.notify.debug('could not index into", "warning diff4 = idx2id2len[self._index-3][objId] - idx2id2len[self._index-4][objId] diff5 = idx2id2len[self._index-4][objId] -", "= indirection.dereferenceDictKey(curObj) evalStr = '' for indirection in indirections: yield", "objects that we should start traversals from often and not-as-often,", "startRefWorkingList.refGen = fw if curObjRef is None: # this ref", "60. * 30.) # main dict of id(container)->containerRef self._id2ref =", "base = getBase() taskMgr.add(nullTask, uniqueName(leakTaskName)) taskMgr.doMethodLater(1 << 31, nullDoLater, uniqueName(leakDoLaterName))", "if hasLength: for i in self._addContainerGen(child, objRef): yield None if", "countFunc=lambda x: self.getStartObjAffinity(x), scale=.05): yield None startRefWorkingList.refGen = fw if", "try: for container in _id2discoveredStartRef[id].getContainerGen(): yield None except: # reference", "Each dictionary dereference is individually eval'd since the dict key", "if curObj is not None: # eval('curObj.foo.bar.someDict') evalStr = 'curObj%s'", "del _id2baseStartRef[id] _id2discoveredStartRef = self._leakDetector._findContainersJob._id2discoveredStartRef ids = _id2discoveredStartRef.keys() for id", "= self._leakDetector.getContainerNameById(objId) if idx2id2len[self._index-1][objId] != 0: percent = 100. *", "ref for i in self._addContainerGen(simbase.__dict__, ref): pass def destroy(self): ContainerLeakDetector.removePrivateObj(self.__dict__)", "actual object, # that could cause a memory leak assert", "will keep one copy and reduce memory usage \"\"\" def", "# if size has consistently increased over the last 5", "things # up in dictionaries, depending on the type of", "every object. Checks container sizes at ever-increasing intervals. \"\"\" notify", "# TODO self.notify.debug('caught exception in getContainerByIdGen (2)') else: msg =", "second reference if objId in self._id2ref: storedItem = objId self._id2discoveredStartRef[objId]", "idx2id2len = self._leakDetector._index2containerId2len for objId in idx2id2len[self._index]: yield None if", "define __cmp__ and don't handle strings if type(objName) == types.StringType", "j = FPTObjsNamed(name, self, on, doneCallback) jobMgr.add(j) return j def", "safeRepr(dictKey) useEval = False try: keyEval = eval(keyRepr) useEval =", "len of each container for objId in ids: yield None", "object in _id2ref? sometimes we do that # to avoid", "sub-job of ContainerLeakDetector \"\"\" ReprItems = 5 def __init__(self, name,", "= self._hasLength(attr) notDeadEnd = False if curObjRef is None: notDeadEnd", "tables for leaks ContainerLeakDetector.addPrivateObj(ContainerLeakDetector.PrivateIds) ContainerLeakDetector.addPrivateObj(self.__dict__) self.setPriority(Job.Priorities.Min) jobMgr.add(self) def destroy(self): messenger.send(self._getDestroyEvent())", "self._pruneContainersJob = None if self._checkContainersJob is not None: jobMgr.remove(self._checkContainersJob) self._checkContainersJob", "return key def dereferenceDictKey(self, parentDict): # look ourselves up in", "self._id2baseStartRef[id(leakDetectors)] = ref for i in self._addContainerGen(__builtin__.__dict__, ref): pass try:", "= evalStr[:-lenDict] # TODO: check that this is still the", "objId, other=None): self._indirections = [] # are we building off", "in self._id2ref: return repr(self._id2ref[id]) return '<unknown container>' def removeContainerById(self, id):", "64 128 256 512 1024 # * 1.5: 1 1.5", "than what we already have, # put it in the", "random.random() < .01: key = random.choice(base.leakContainer.keys()) ContainerLeakDetector.notify.debug( 'removing reference to", "out a warning diff4 = idx2id2len[self._index-3][objId] - idx2id2len[self._index-4][objId] diff5 =", "return instance instead of instance dict #import pdb;pdb.set_trace() evalStr =", "# if we haven't picked the next ref, check if", "# these are working copies so that our iterations aren't", "aren't disturbed by changes to the # definitive ref sets", "that support __len__() \"\"\" def __init__(self, name, leakDetector): Job.__init__(self, name)", "minutes = (self._leakDetector._index2delay[self._index] - self._leakDetector._index2delay[self._index-1]) / 60. name = self._leakDetector.getContainerNameById(objId)", "one attr, # choose it at random without taking a", "examined PrivateIds = set() def __init__(self, name, firstCheckDelay = None):", "if this one is a candidate if curObjRef is None:", "getFinalIndirectionStr(self): prevIndirection = None if len(self._indirections) > 1: prevIndirection =", "one (obj.__dict__[keyName] == obj.keyName) if nextIndirection is not None and", "curIndirection = None nextIndirection = None # make sure the", "evalStr = '' curObj = None # make sure the", "self.getEvalStrGen(): pass return result class FindContainers(Job): \"\"\" Explore the Python", "graph via one attr, # choose it at random without", "def destroy(self): # re-entrant self.dictKey = NoDictKey def acquire(self): self._refCount", "# fib: 1 1 2 3 5 8 13 21", "Job.Done class CheckContainers(Job): \"\"\" Job to check container sizes and", "will discover every object. Checks container sizes at ever-increasing intervals.", "look up the object in _id2ref? sometimes we do that", "delay between checks # fib: 1 1 2 3 5", "itype(container), idx2id2len[self._index][objId], fastRepr(container, maxLen=CheckContainers.ReprItems))) self.notify.warning(msg) yield None elif (objId in", "None and prevIndirection.evalStr is not None: if prevIndirection.evalStr[-len(instanceDictStr):] == instanceDictStr:", "self._addDiscoveredStartRef(child, objRef) curObjRef = objRef continue if type(curObj) is types.DictType:", "_id2discoveredStartRef = self._leakDetector._findContainersJob._id2discoveredStartRef ids = _id2discoveredStartRef.keys() for id in ids:", "prevIndirection = indirections[i-1] else: prevIndirection = None curIndirection = indirections[i]", "yield Job.Done class ContainerLeakDetector(Job): \"\"\" Low-priority Python object-graph walker that", "in _id2discoveredStartRef[id].getContainerGen(): yield None except: # reference is invalid, remove", "is this an indirection through a dictionary? return self.dictKey is", "__init__(self, name, firstCheckDelay = None): Job.__init__(self, name) self._serialNum = serialNum()", "None if i > 0: prevIndirection = indirections[i-1] else: prevIndirection", "pass else: try: index = -1 attrs = [] while", "goesThrough: if curObj is __builtin__.__dict__: objRef = ObjectRef(Indirection(evalStr='%s' % key),", "if self.evalStr is not None: # if we're an instance", "nullTask(task=None): return task.cont def nullDoLater(task=None): return task.done def leakTask(task=None, leakTaskName=leakTaskName):", "curObj.__dict__ hasLength = self._hasLength(child) notDeadEnd = not self._isDeadEnd(child) if hasLength", "25.6 38.4 57.7 # # delay from job start #", "self._indirections.append(indirection) # make sure our indirections don't get destroyed while", "container by eval'ing and looking things # up in dictionaries,", "if getInstance is True, will return instance instead of instance", "idx2id2len[self._index-1]: diff = idx2id2len[self._index][objId] - idx2id2len[self._index-1][objId] \"\"\" # this check", "return '<unknown container>' def removeContainerById(self, id): if id in self._id2ref:", "continue except Exception, e: print 'FindContainers job caught exception: %s'", "no longer exists; caught exception in getContainerById (%s)' % (", "for objId in idx2id2len[self._index]: yield None if objId in idx2id2len[self._index-1]:", "idx2id2len[self._index][objId], fastRepr(container, maxLen=CheckContainers.ReprItems))) self.notify.warning(msg) yield None messenger.send(self._leakDetector.getLeakEvent(), [container, name]) if", "to leakContainer key %s so it will be garbage-collected' %", "and # doesn't check for leaks self._nextCheckDelay = firstCheckDelay/2. self._checkDelayScale", "yield None elif (objId in idx2id2len[self._index-4] and objId in idx2id2len[self._index-5]):", "ref set is empty, choose another break # make a", "continue if type(curObj) is types.DictType: key = None attr =", "is True, will return instance instead of instance dict #import", "numAttrsLeft = len(attrs) + 1 for attr in attrs: yield", "serialNum, safeRepr, fastRepr from direct.showbase.Job import Job import types, weakref,", "( contName, e)) self._leakDetector.removeContainerById(objId) continue if container is None: #", "ObjectRef(Indirection(evalStr='__builtin__.__dict__'), id(__builtin__.__dict__)) self._id2baseStartRef[id(__builtin__.__dict__)] = ref # container for objects that", "measurement, current contents: %s)' % ( name, itype(container), percent, minutes,", "objRef parentObjRef = curObjRef # if we hit a dead", "their length for fw in makeFlywheelGen( startRefWorkingList.source.values(), countFunc=lambda x: self.getStartObjAffinity(x),", "# put it in the table if contId in self._id2ref:", "result except Exception, e: # this container no longer exists", "graph via one key of the dict, # choose it", "nextIndirection = indirections[i+1] else: nextIndirection = None str += curIndirection.getString(prevIndirection=prevIndirection,", "None except: pass else: if hasattr(container, '__class__'): cName = container.__class__.__name__", "1 2.5 4.75 8.1 13.2 20.8 32.2 49.3 74.9 113.3", "= safeRepr(self._getNonWeakDictKey()) # if the previous indirection was an instance", "% keyRepr else: try: # store a weakref to the", "= objRef continue if type(curObj) is types.DictType: key = None", "+ ': ' + ptc except Exception, e: print 'FPTObjsOfType", "acquire(self): self._refCount += 1 def release(self): self._refCount -= 1 if", "if self._doneCallback: self._doneCallback(self) class FPTObjsNamed(Job): def __init__(self, name, leakDetector, on,", "result in self._leakDetector.getContainerByIdGen(objId): yield None container = result except Exception,", "return parentDict[key] def getString(self, prevIndirection=None, nextIndirection=None): # return our contribution", "dict key %s' % keyRepr) self.dictKey = dictKey self._isWeakRef =", "continue hasLength = self._hasLength(attr) notDeadEnd = False # if we", "= containerRef try: for curObj in curObjRef.getContainerGen(): yield None except:", "return j def _scheduleNextLeakCheck(self): taskMgr.doMethodLater(self._nextCheckDelay, self._checkForLeaks, self._getCheckTaskName()) # delay between", "empty, choose another break # make a generator that yields", "scale=.05): yield None startRefWorkingList.refGen = fw if curObjRef is None:", "return task.cont def nullDoLater(task=None): return task.done def leakTask(task=None, leakTaskName=leakTaskName): base", "%s' % e if __dev__: raise yield Job.Done def finished(self):", "def addPrivateObj(cls, obj): cls.PrivateIds.add(id(obj)) @classmethod def removePrivateObj(cls, obj): cls.PrivateIds.remove(id(obj)) def", "% ( contName, e)) self._leakDetector.removeContainerById(objId) continue if container is None:", "parentObjRef.goesThroughGen(child): # don't yield, container might lose this element pass", "self.notify.warning( '%s (%s) grew %.2f%% in %.2f minutes (%s items", "invalid, remove it del _id2discoveredStartRef[id] except Exception, e: print 'PruneObjectRefs", "try: base except: pass else: ref = ObjectRef(Indirection(evalStr='base.__dict__'), id(base.__dict__)) self._id2baseStartRef[id(base.__dict__)]", "= ObjectRef(Indirection(evalStr='__builtin__.__dict__'), id(__builtin__.__dict__)) self._id2baseStartRef[id(__builtin__.__dict__)] = ref # container for objects", "the container by eval'ing and looking things # up in", "that want to make sure they are found by #", "base set should never be empty (__builtin__ etc.) continue #", "# doesn't check for leaks self._nextCheckDelay = firstCheckDelay/2. self._checkDelayScale =", "a single item if type(curObjRef) in (types.IntType, types.LongType): startId =", "232 # * 2.: 1 3 7 15 31 63", "# of times that is # proportional to their length", "pass return result class FindContainers(Job): \"\"\" Explore the Python graph,", "task.done def _scheduleNextPruning(self): taskMgr.doMethodLater(self._pruneTaskPeriod, self._pruneObjectRefs, self._getPruneTaskName()) def _pruneObjectRefs(self, task=None): self._pruneContainersJob", "None for newRepr in objRef.getEvalStrGen(): yield None if contId not", "indirections: indirection.acquire() for i in xrange(len(indirections)): yield None if i", "is no longer a container, it is now %s (%s)'", "of each container for objId in ids: yield None try:", "a weakref to the key self.dictKey = weakref.ref(dictKey) self._isWeakRef =", "in self._leakDetector.getContainerByIdGen(startId): yield None except: # ref is invalid self.notify.debug('invalid", "-= 1 if self._refCount == 0: self.destroy() def isDictKey(self): #", "yield None if contId not in self._id2ref or len(newRepr) <", "%s' % startId) self._leakDetector.removeContainerById(startId) continue curObjRef = containerRef try: for", "20 33 54 88 143 232 # * 2.: 1", "_id2discoveredStartRef[id].getContainerGen(): yield None except: # reference is invalid, remove it", "startId = curObjRef curObjRef = None try: for containerRef in", "key = self._getNonWeakDictKey() # objects in __builtin__ will have parentDict==None", "the while loop from various points yield None #import pdb;pdb.set_trace()", "del key del attr continue try: childNames = dir(curObj) except:", "= None keys = curObj.keys() # we will continue traversing", "if objId in self._id2discoveredStartRef: existingRef = self._id2discoveredStartRef[objId] if type(existingRef) not", "through a dictionary? return self.dictKey is not NoDictKey def _getNonWeakDictKey(self):", "keyRepr def __repr__(self): return self.getString() class ObjectRef: \"\"\" stores a", "self._leakDetector.getContainerNameByIdGen(objId): yield None self.notify.debug( '%s no longer exists; caught exception", "id): if id in self._id2ref: self._id2ref[id].destroy() del self._id2ref[id] def run(self):", "512 1024 # * 1.5: 1 1.5 2.3 3.4 5.1", "than keep a set of all visited objects; it may", "self.ignore(self._ldde) self._leakDetector = None self._doneCallback = None ContainerLeakDetector.removePrivateObj(self.__dict__) Job.destroy(self) def", "random.randrange(numAttrsLeft) == 0: curObjRef = objRef del attr except StopIteration,", "del attr except StopIteration, e: pass del itr continue except", "more concise than the new ref return storedItem = ref", "% self._serialNum def _getPruneTaskName(self): return 'pruneLeakingContainerRefs-%s' % self._serialNum def getContainerIds(self):", "getPriority(self): return Job.Priorities.High def run(self): ids = self._leakDetector.getContainerIds() try: for", "is not None: for ind in other._indirections: self._indirections.append(ind) # make", "here instead of at the end, since we skip back", "reference handling if random.random() < .01: key = random.choice(base.leakContainer.keys()) ContainerLeakDetector.notify.debug(", "yield None except: # TODO self.notify.debug('caught exception in getContainerByIdGen (3)')", "31, nullDoLater, uniqueName(leakDoLaterName)) taskMgr.doMethodLater(10, leakTask, 'doLeakTask-%s' % serialNum()) if task:", "types.FunctionType, types.StringType, types.UnicodeType, types.TupleType): return True # if it's an", "if we hit a dead end, start over from another", "name.lower(): try: for ptc in self._leakDetector.getContainerNameByIdGen(id): yield None except: pass", "self._on + '):' + self.getJobName() + ': ' + ptc", "to destroy any container refs that are no longer valid.", "+ ptc except Exception, e: print 'FPTObjsOfType job caught exception:", "self._checkDelayScale = config.GetFloat('leak-detector-check-delay-scale', 1.5) self._pruneTaskPeriod = config.GetFloat('leak-detector-prune-period', 60. * 30.)", "in self._id2discoveredStartRef: existingRef = self._id2discoveredStartRef[objId] if type(existingRef) not in (types.IntType,", "do well when iterated attr = None break attrs.append(attr) #", "objRef del attr except StopIteration, e: pass del itr continue", "and looking things # up in dictionaries, depending on the", "start if it's not already there bis = '__builtin__' if", "self._pruneObjectRefs, self._getPruneTaskName()) def _pruneObjectRefs(self, task=None): self._pruneContainersJob = PruneObjectRefs( '%s-pruneObjectRefs' %", "a normal 'non-weak' reference class LeakKey: pass base.leakContainer[(LeakKey(),)] = {}", "minLen = float(max(1, min(baseLen, discLen))) # this will cut down", "attr in attrs: yield None index += 1 numAttrsLeft -=", "None try: curObjRef = startRefWorkingList.refGen.next() break except StopIteration: # we've", "storedItem = objId self._id2discoveredStartRef[objId] = storedItem def run(self): try: #", "all visited objects; it may visit the same object many", "that define __cmp__ and don't handle strings if type(objName) ==", "None try: for container in self._leakDetector.getContainerByIdGen(id): yield None except: #", "evalStr self.dictKey = NoDictKey # is the dictKey a weak", "def getPriority(self): return Job.Priorities.Low @staticmethod def getStartObjAffinity(startObj): # how good", "chunk of CPU time numAttrsLeft = len(attrs) + 1 for", "put it in the table if contId in self._id2ref: for", "itype(container), idx2id2len[self._index][objId], fastRepr(container, maxLen=CheckContainers.ReprItems))) self.notify.warning(msg) yield None messenger.send(self._leakDetector.getLeakEvent(), [container, name])", "not self._isDeadEnd(attr, key) if hasLength or notDeadEnd: # prevent cycles", "{} self._id2discoveredStartRef = {} # these are working copies so", "curObj in curObjRef.getContainerGen(): yield None except: self.notify.debug('lost current container, ref.getContainerGen()", "del attr continue try: childNames = dir(curObj) except: pass else:", "8.1 13.2 20.8 32.2 49.3 74.9 113.3 171 self._nextCheckDelay =", "parentDict key = self._getNonWeakDictKey() # objects in __builtin__ will have", "curObj=curObj) if curObj is None: raise FailedEval(evalStr) # try to", "self._leakDetector.removeContainerById(startId) continue curObjRef = containerRef try: for curObj in curObjRef.getContainerGen():", "indirections: indirection.acquire() for indirection in indirections: yield None if not", "def __init__(self, name, leakDetector): Job.__init__(self, name) self._leakDetector = leakDetector self.notify", "# reference is invalid, remove it self._leakDetector.removeContainerById(id) _id2baseStartRef = self._leakDetector._findContainersJob._id2baseStartRef", "exists if self.notify.getDebug(): for contName in self._leakDetector.getContainerNameByIdGen(objId): yield None self.notify.debug('%s", "_id2baseStartRef[id].getContainerGen(): yield None except: # reference is invalid, remove it", "succeeded if hash(keyEval) != hash(dictKey): useEval = False if useEval:", "Job.__init__(self, name) self._leakDetector = leakDetector self.notify = self._leakDetector.notify self._index =", "is shorter than what we already have, # put it", "in indirections: yield None indirection.release() if getInstance: lenDict = len('.__dict__')", "for leaks self._nextCheckDelay = firstCheckDelay/2. self._checkDelayScale = config.GetFloat('leak-detector-check-delay-scale', 1.5) self._pruneTaskPeriod", "current traversal curObjRef = None while True: # yield up", "a new traversal # force creation of a new workingListSelector", "sent when leak detector is about to be destroyed return", "the references (i.e. base.loader.base) for goesThrough in parentObjRef.goesThroughGen(child): # don't", "CPU time numAttrsLeft = len(attrs) + 1 for attr in", "by two, since the first check just takes length measurements", "in name.lower(): try: for ptc in self._leakDetector.getContainerNameByIdGen(id): yield None except:", "minutes (%s items at last measurement, current contents: %s)' %", "(name, itype(container), idx2id2len[self._index][objId], fastRepr(container, maxLen=CheckContainers.ReprItems))) self.notify.warning(msg) yield None messenger.send(self._leakDetector.getLeakEvent(), [container,", "graph, looking for objects that support __len__() \"\"\" def __init__(self,", "None if hasLength: for i in self._addContainerGen(child, objRef): yield None", "the curObj dictionary curObj = indirection.dereferenceDictKey(curObj) evalStr = '' for", "in curObjRef.getContainerGen(): yield None except: self.notify.debug('lost current container, ref.getContainerGen() failed')", "if type(curObj) is types.DictType: key = None attr = None", "in _id2ref? sometimes we do that # to avoid storing", "-1 attrs = [] while 1: yield None try: attr", "gone, try again curObjRef = None continue self.notify.debug('--> %s' %", "global__builtin__ namespace # put __builtin__ at the start if it's", "# this holds the current step of the current traversal", "these hold objects that we should start traversals from often", "pass else: name = self._leakDetector._id2ref[id].getFinalIndirectionStr() if self._on.lower() in name.lower(): try:", "object that can be used to start an object graph", "check our own tables for leaks ContainerLeakDetector.addPrivateObj(ContainerLeakDetector.PrivateIds) ContainerLeakDetector.addPrivateObj(self.__dict__) self.setPriority(Job.Priorities.Min) jobMgr.add(self)", "new traversal # force creation of a new workingListSelector inside", "that are duplicates of strings in the actual system so", "looked up in a dict. Each dictionary dereference is individually", "None: for ind in other._indirections: self._indirections.append(ind) # make sure we're", "leaks ContainerLeakDetector.addPrivateObj(ContainerLeakDetector.PrivateIds) ContainerLeakDetector.addPrivateObj(self.__dict__) self.setPriority(Job.Priorities.Min) jobMgr.add(self) def destroy(self): messenger.send(self._getDestroyEvent()) self.ignoreAll() if", "if __dev__: raise yield Job.Done class CheckContainers(Job): \"\"\" Job to", "items at last measurement, current contents: %s)' % ( name,", "the references (i.e. base.loader.base) for goesThrough in parentObjRef.goesThroughGen(curObj[key]): # don't", "if __dev__: raise yield Job.Done def finished(self): if self._doneCallback: self._doneCallback(self)", "+ self.getJobName() + ': ' + ptc except Exception, e:", "yield Job.Done class FPTObjsOfType(Job): def __init__(self, name, leakDetector, otn, doneCallback=None):", "except: self.notify.debug('lost current container, ref.getContainerGen() failed') # that container is", "': ' + ptc except Exception, e: print 'FPTObjsOfType job", "ids = self._leakDetector.getContainerIds() for id in ids: yield None try:", "id in ids: yield None try: for container in _id2discoveredStartRef[id].getContainerGen():", "{} # these are working copies so that our iterations", "doneCallback=None): Job.__init__(self, name) self._leakDetector = leakDetector self.notify = self._leakDetector.notify self._otn", "break # make a generator that yields containers a #", "in ids: yield None try: for container in self._leakDetector.getContainerByIdGen(id): yield", "evalStr else: # this eval is not based off of", "in self._leakDetector.getContainerByIdGen( id, getInstance=getInstance): yield None except: pass else: if", "dictionaries, depending on the type of each indirection # if", "'method-wrapper': return True return False def _hasLength(self, obj): return hasattr(obj,", "# is this an indirection through a dictionary? return self.dictKey", "start ref from this sequence and see if it's still", "None except: self.notify.debug('lost current container, ref.getContainerGen() failed') # that container", "if contId in self._id2ref: for existingRepr in self._id2ref[contId].getEvalStrGen(): yield None", "try: keyEval = eval(keyRepr) useEval = True except: pass if", "(types.IntType, types.LongType) else: objId = id(obj) o = None evalStr", "useEval = False if useEval: # eval/repr succeeded, store as", "if key is None: return '<garbage-collected dict key>' return key", "__cmp__ and don't handle strings if type(objName) == types.StringType and", "import Job import types, weakref, random, __builtin__ def _createContainerLeak(): def", "is None: assert type(objId) in (types.IntType, types.LongType) else: objId =", "key might have been garbage-collected TODO: store string components that", "False if useEval: # eval/repr succeeded, store as an evalStr", "as keys since they can't be weakref'd, and use an", "if hasattr(curObj, '__dict__'): child = curObj.__dict__ hasLength = self._hasLength(child) notDeadEnd", "in getContainerByIdGen (1)') else: self.notify.warning( '%s (%s) grew %.2f%% in", "name = self._leakDetector.getContainerNameById(objId) try: for container in self._leakDetector.getContainerByIdGen(objId): yield None", "this Ref was created this would return # false, allowing", "in xrange(len(indirections)): yield None if i > 0: prevIndirection =", "= self._indirections for indirection in indirections: indirection.acquire() for i in", "60. * 15. # divide by two, since the first", "container def getContainerGen(self, getInstance=False): # try to get a handle", "self._checkContainersJob = None self._pruneContainersJob = None if firstCheckDelay is None:", "do we need to go look up the object in", "(3)') else: msg = ('leak detected: %s (%s) consistently increased", "evalStr) try: container = eval(evalStr) except NameError, ne: return None", "types.DictType: key = None attr = None keys = curObj.keys()", "* (float(diff) / float(idx2id2len[self._index-1][objId])) try: for container in self._leakDetector.getContainerByIdGen(objId): yield", "prevIndirection = None curIndirection = None nextIndirection = None #", "type(objId) in (types.IntType, types.LongType) # prevent cycles (i.e. base.loader.base.loader) assert", "% (bis, evalStr) try: container = eval(evalStr) except NameError, ne:", "objId in ids: yield None try: for result in self._leakDetector.getContainerByIdGen(objId):", "in self._leakDetector.getContainerByIdGen(objId): yield None container = result except Exception, e:", "contId in self._id2ref: self._leakDetector.removeContainerById(contId) self._id2ref[contId] = objRef def _addDiscoveredStartRef(self, obj,", "self._leakDetector.getContainerIds() try: for id in ids: getInstance = (self._otn.lower() not", "except Exception, e: print 'CheckContainers job caught exception: %s' %", "in idx2id2len[self._index-3]): diff2 = idx2id2len[self._index-1][objId] - idx2id2len[self._index-2][objId] diff3 = idx2id2len[self._index-2][objId]", "ever-increasing intervals. \"\"\" notify = directNotify.newCategory(\"ContainerLeakDetector\") # set of containers", "looking for containers self._findContainersJob = FindContainers( '%s-findContainers' % self.getJobName(), self)", "1 1 2 3 5 8 13 21 34 55", "= '__builtin__' if evalStr[:len(bis)] != bis: evalStr = '%s.%s' %", "(self._index > 2 and objId in idx2id2len[self._index-2] and objId in", "def getNumIndirections(self): return len(self._indirections) def goesThroughGen(self, obj=None, objId=None): if obj", "Job.Priorities.Normal def run(self): try: ids = self._leakDetector.getContainerIds() for id in", "0): _createTaskLeak() # don't check our own tables for leaks", "del _id2discoveredStartRef[id] except Exception, e: print 'PruneObjectRefs job caught exception:", "is detected # passes description string as argument return 'containerLeakDetected-%s'", "in the references (i.e. base.loader.base) for goesThrough in parentObjRef.goesThroughGen(child): #", "sure the eval succeeded if hash(keyEval) != hash(dictKey): useEval =", "None: if prevIndirection.evalStr[-len(instanceDictStr):] == instanceDictStr: return '.%s' % self.evalStr[2:-2] return", "of the while loop from various points yield None #import", "references (i.e. base.loader.base) for goesThrough in parentObjRef.goesThrough(curObj[index]): # don't yield,", "choose an object to start a traversal from try: startRefWorkingList", "is empty, choose another # the base set should never", "i in self._addContainerGen(attr, objRef): yield None if notDeadEnd: self._addDiscoveredStartRef(attr, objRef)", "1024 # * 1.5: 1 1.5 2.3 3.4 5.1 7.6", "yield None try: for container in _id2discoveredStartRef[id].getContainerGen(): yield None except:", "% (contName, safeRepr(container), e)) self._leakDetector.removeContainerById(objId) continue self._leakDetector._index2containerId2len[self._index][objId] = cLen #", "15. # divide by two, since the first check just", "custom classes don't do well when iterated attr = None", "evalStr[:-lenDict] # TODO: check that this is still the object", "= self._getNonWeakDictKey() # objects in __builtin__ will have parentDict==None if", "self.evalStr is not None: # if we're an instance dict,", "indirections: yield None if not indirection.isDictKey(): # build up a", "this element pass if not goesThrough: if curObj is __builtin__.__dict__:", "id(curObj[key]), parentObjRef) yield None if hasLength: for i in self._addContainerGen(attr,", "building off of an existing ref? if other is not", "based off of curObj, use the global__builtin__ namespace # put", "baseLen = len(self._baseStartRefWorkingList.source) discLen = len(self._discoveredStartRefWorkingList.source) minLen = float(max(1, min(baseLen,", "self._indirections: indirection.release() del self._indirections def getNumIndirections(self): return len(self._indirections) def goesThroughGen(self,", "curObj = None # make sure the indirections don't go", "of the Python objects to discover containers rather than keep", "prevIndirection.evalStr[-len(instanceDictStr):] == instanceDictStr: return '.%s' % keyRepr return '[%s]' %", "not self._isDeadEnd(attr) if hasLength or notDeadEnd: # prevent cycles in", "None elif (objId in idx2id2len[self._index-4] and objId in idx2id2len[self._index-5]): #", "to get a handle on the container by eval'ing and", "self._serialNum def _getPruneTaskName(self): return 'pruneLeakingContainerRefs-%s' % self._serialNum def getContainerIds(self): return", "import PStatCollector from direct.directnotify.DirectNotifyGlobal import directNotify from direct.showbase.PythonUtil import Queue,", "right off the bat workingListSelector = nullGen() # this holds", "eval/repr succeeded, store as an evalStr self.evalStr = '[%s]' %", "e)) self._leakDetector.removeContainerById(objId) continue self._leakDetector._index2containerId2len[self._index][objId] = cLen # compare the current", "first check just takes length measurements and # doesn't check", "for contName in self._leakDetector.getContainerNameByIdGen(objId): yield None self.notify.debug( '%s is no", "in self._id2ref: storedItem = objId self._id2discoveredStartRef[objId] = storedItem def run(self):", "end, since we skip back to the # top of", "objId in idx2id2len[self._index]: yield None if objId in idx2id2len[self._index-1]: diff", "None self._doneCallback = None ContainerLeakDetector.removePrivateObj(self.__dict__) Job.destroy(self) def _handleLDDestroy(self): self.destroy() def", "the current traversal curObjRef = None while True: # yield", "+= indirection.getString() else: curObj = self._getContainerByEval(evalStr, curObj=curObj) if curObj is", "another # the base set should never be empty (__builtin__", "while 1: yield None try: attr = itr.next() except: #", "len('.__dict__') if evalStr[-lenDict:] == '.__dict__': evalStr = evalStr[:-lenDict] # TODO:", "have, # put it in the table if contId in", "over the last 5 checks, # send out a warning", "None ContainerLeakDetector.removePrivateObj(self.__dict__) Job.destroy(self) def _handleLDDestroy(self): self.destroy() def getPriority(self): return Job.Priorities.High", "# * 2.: 1 3 7 15 31 63 127", "prevent garbage collection of the container if possible stored as", "def run(self): try: # this yields a different set of", "for goesThrough in parentObjRef.goesThroughGen(curObj[key]): # don't yield, container might lose", "storing a reference to the actual object, # that could", "finished(self): if self._doneCallback: self._doneCallback(self) class FPTObjsNamed(Job): def __init__(self, name, leakDetector,", "yield Job.Done class CheckContainers(Job): \"\"\" Job to check container sizes", "== types.StringType and objName in ('im_self', 'im_class'): return True try:", "if notDeadEnd: self._addDiscoveredStartRef(attr, objRef) if curObjRef is None and random.randrange(numKeysLeft)", "over the last ' '5 periods (%s items at last", "Checks container sizes at ever-increasing intervals. \"\"\" notify = directNotify.newCategory(\"ContainerLeakDetector\")", "if base.myObject is reassigned # to a different object after", "of id(container)->containerRef self._id2ref = {} # storage for results of", "a container to an element of the container. Stored as", "hasLength = self._hasLength(attr) notDeadEnd = False # if we haven't", "directNotify from direct.showbase.PythonUtil import Queue, invertDictLossless, makeFlywheelGen from direct.showbase.PythonUtil import", "ref): pass try: simbase except: pass else: ref = ObjectRef(Indirection(evalStr='simbase.__dict__'),", "each set based on how many refs it contains baseLen", "contribution to the full name of an object instanceDictStr =", "ContainerLeakDetector.removePrivateObj(self.__dict__) Job.destroy(self) def getPriority(self): return Job.Priorities.Normal def run(self): try: ids", "None try: for container in _id2discoveredStartRef[id].getContainerGen(): yield None except: #", "the bat workingListSelector = nullGen() # this holds the current", "check if this one is a candidate if curObjRef is", "we haven't picked the next ref, check if this one", "curObj = indirection.dereferenceDictKey(curObj) evalStr = '' for indirection in indirections:", "source=self._id2baseStartRef) self._discoveredStartRefWorkingList = ScratchPad(refGen=nullGen(), source=self._id2discoveredStartRef) self.notify = self._leakDetector.notify ContainerLeakDetector.addPrivateObj(self.__dict__) #", "= self._leakDetector._findContainersJob._id2baseStartRef ids = _id2baseStartRef.keys() for id in ids: yield", "while True: # yield up here instead of at the", "parentDict[key] def getString(self, prevIndirection=None, nextIndirection=None): # return our contribution to", "instanceDictStr: return '.%s' % keyRepr return '[%s]' % keyRepr def", "start traversals from often and not-as-often, # respectively self._id2baseStartRef =", "self._scheduleNextLeakCheck() self._scheduleNextPruning() while True: yield Job.Sleep def getPathsToContainers(self, name, ot,", "jobMgr.add(j) return j def getPathsToContainersNamed(self, name, on, doneCallback=None): j =", "another container curObjRef = None if hasattr(curObj, '__dict__'): child =", "uniqueName(leakDoLaterName)) taskMgr.doMethodLater(10, leakTask, 'doLeakTask-%s' % serialNum()) if task: return task.done", "the larger set by 2/3 minLen *= 3. workingListSelector =", "dictionary lookup, pass dictKey instead of evalStr self.evalStr = evalStr", "system so that Python will keep one copy and reduce", "(types.IntType, types.LongType): if (existingRef.getNumIndirections() >= ref.getNumIndirections()): # the ref that", "container, ref.getContainerGen() failed') # that container is gone, try again", "= float(max(1, min(baseLen, discLen))) # this will cut down the", "yield None try: curObjRef = startRefWorkingList.refGen.next() break except StopIteration: #", "-> '.foo', dict[key] -> '[key]', etc.) \"\"\" notify = directNotify.newCategory(\"ObjectRef\")", "self._index2delay def _getDestroyEvent(self): # sent when leak detector is about", "that our iterations aren't disturbed by changes to the #", "(%s) consistently increased in size over the last ' '5", "== objId def goesThrough(self, obj=None, objId=None): # since we cache", "will return instance instead of instance dict #import pdb;pdb.set_trace() evalStr", "set is empty, choose another # the base set should", "and find potential leaks; sub-job of ContainerLeakDetector \"\"\" ReprItems =", "return 'pruneLeakingContainerRefs-%s' % self._serialNum def getContainerIds(self): return self._id2ref.keys() def getContainerByIdGen(self,", "discLen = len(self._discoveredStartRefWorkingList.source) minLen = float(max(1, min(baseLen, discLen))) # this", "try to get a handle on the container by eval'ing", "indirections: yield None indirection.release() if getInstance: lenDict = len('.__dict__') if", "iterations aren't disturbed by changes to the # definitive ref", "the object we originally pointed to yield self._getContainerByEval(evalStr, curObj=curObj) def", "a dict key keyRepr = safeRepr(self._getNonWeakDictKey()) # if the previous", "if getInstance: lenDict = len('.__dict__') if evalStr[-lenDict:] == '.__dict__': evalStr", "object, ignore it if id(obj) in ContainerLeakDetector.PrivateIds: return True #", "contName) self._leakDetector.removeContainerById(objId) continue try: cLen = len(container) except Exception, e:", "prevIndirection.evalStr is not None: if prevIndirection.evalStr[-len(instanceDictStr):] == instanceDictStr: return '.%s'", "that brings you from a container to an element of", "repr(self._id2ref[id]) return '<unknown container>' def removeContainerById(self, id): if id in", "if curObj is None: raise FailedEval(evalStr) # try to look", "of curObj, use the global__builtin__ namespace # put __builtin__ at", "detected: %s (%s) consistently increased in size over the last", "None except: # reference is invalid, remove it del _id2discoveredStartRef[id]", "obj=None, objId=None): # since we cache the ids involved in", "pass del itr continue except Exception, e: print 'FindContainers job", "evalStr = '%s.%s' % (bis, evalStr) try: container = eval(evalStr)", "up a string to be eval'd evalStr += indirection.getString() else:", "strings if type(objName) == types.StringType and objName in ('im_self', 'im_class'):", "# prevent infinite recursion in built-in containers related to methods", "run(self): try: self._leakDetector._index2containerId2len[self._index] = {} ids = self._leakDetector.getContainerIds() # record", "try: for id in ids: getInstance = (self._otn.lower() not in", "= None str += curIndirection.getString(prevIndirection=prevIndirection, nextIndirection=nextIndirection) if getInstance: lenDict =", "if id in self._id2ref: self._id2ref[id].destroy() del self._id2ref[id] def run(self): #", "itype(container), percent, minutes, idx2id2len[self._index][objId], fastRepr(container, maxLen=CheckContainers.ReprItems))) yield None \"\"\" if", "self._addDiscoveredStartRef(attr, objRef) if curObjRef is None and random.randrange(numAttrsLeft) == 0:", "def run(self): try: ids = self._leakDetector.getContainerIds() for id in ids:", "256 512 1024 # * 1.5: 1 1.5 2.3 3.4", "indirection.dereferenceDictKey(curObj) evalStr = '' for indirection in indirections: yield None", "'GPTC(' + self._otn + '):' + self.getJobName() + ': '", "__init__(self, indirection, objId, other=None): self._indirections = [] # are we", "if evalStr[-lenDict:] == '.__dict__': evalStr = evalStr[:-lenDict] # TODO: check", "= self._nextCheckDelay * self._checkDelayScale def _checkForLeaks(self, task=None): self._index2delay[len(self._index2containerId2len)] = self._nextCheckDelay", "object graph? try: return len(startObj) except: return 1 def _isDeadEnd(self,", "evalStr=None, dictKey=NoDictKey): # if this is a dictionary lookup, pass", "# passes description string as argument return 'containerLeakDetected-%s' % self._serialNum", "# this is OK because we are yielding during the", "C++ memory usage, scene graph size, # framerate, etc. See", "#import pdb;pdb.set_trace() evalStr = '' curObj = None # make", "None self.notify.debug( '%s is no longer a container, it is", "that will force the leak detector to hold a normal", "haven't picked the next ref, check if this one is", "'.%s' % keyRepr return '[%s]' % keyRepr def __repr__(self): return", "in self._leakDetector.getContainerByIdGen(id): yield None except: # reference is invalid, remove", "taskMgr.doMethodLater(1 << 31, nullDoLater, uniqueName(leakDoLaterName)) taskMgr.doMethodLater(10, leakTask, 'doLeakTask-%s' % serialNum())", "None try: for container in _id2baseStartRef[id].getContainerGen(): yield None except: #", "except: pass else: name = self._leakDetector._id2ref[id].getFinalIndirectionStr() if self._on.lower() in name.lower():", "table if contId in self._id2ref: for existingRepr in self._id2ref[contId].getEvalStrGen(): yield", "this isn't perfect, for example if base.myObject is reassigned #", "there bis = '__builtin__' if evalStr[:len(bis)] != bis: evalStr =", "None except: # reference is invalid, remove it del _id2baseStartRef[id]", "= ref for i in self._addContainerGen(base.__dict__, ref): pass try: simbase", "float(max(1, min(baseLen, discLen))) # this will cut down the traversals", "for ptc in self._leakDetector.getContainerNameByIdGen( id, getInstance=getInstance): yield None except: pass", "objects; it may visit the same object many times but", "in keys: yield None numKeysLeft -= 1 try: attr =", "not hasattr(__builtin__, \"leakDetectors\"): __builtin__.leakDetectors = {} ref = ObjectRef(Indirection(evalStr='leakDetectors'), id(leakDetectors))", "try: curObjRef = startRefWorkingList.refGen.next() break except StopIteration: # we've run", "else: self.notify.warning( '%s (%s) grew %.2f%% in %.2f minutes (%s", "return # false, allowing a ref to base.myObject.otherObject.myObject for goesThrough", "in idx2id2len[self._index-2] and objId in idx2id2len[self._index-3]): diff2 = idx2id2len[self._index-1][objId] -", "exception in getContainerByIdGen (2)') else: msg = ('%s (%s) consistently", "reference if objId in self._id2ref: storedItem = objId self._id2discoveredStartRef[objId] =", "objId in idx2id2len[self._index-1]: diff = idx2id2len[self._index][objId] - idx2id2len[self._index-1][objId] \"\"\" #", "key in keys: yield None numKeysLeft -= 1 try: attr", "self._leakDetector._findContainersJob._id2baseStartRef ids = _id2baseStartRef.keys() for id in ids: yield None", "'%s-findContainers' % self.getJobName(), self) jobMgr.add(self._findContainersJob) self._scheduleNextLeakCheck() self._scheduleNextPruning() while True: yield", "__init__(self, name, leakDetector): Job.__init__(self, name) self._leakDetector = leakDetector self._id2ref =", "for indirection in indirections: indirection.acquire() for i in xrange(len(indirections)): yield", "start an object graph traversal objId = id(obj) if objId", "found by # the object exploration algorithm, including objects that", "# do relative # of traversals on each set based", "32.2 49.3 74.9 113.3 171 self._nextCheckDelay = self._nextCheckDelay * self._checkDelayScale", "NoDictKey def acquire(self): self._refCount += 1 def release(self): self._refCount -=", "ke: return None return container def getContainerGen(self, getInstance=False): # try", "no longer exists; getContainerById returned None' % contName) self._leakDetector.removeContainerById(objId) continue", "!= 0: percent = 100. * (float(diff) / float(idx2id2len[self._index-1][objId])) try:", "as a string to be used as part of an", "self._pruneContainersJob = None if firstCheckDelay is None: firstCheckDelay = 60.", "a generator to look up a container return self._id2ref[id].getContainerGen(**kwArgs) def", "= 60. * 15. # divide by two, since the", "stored as a dict key keyRepr = safeRepr(self._getNonWeakDictKey()) # if", "return task.done def leakTask(task=None, leakTaskName=leakTaskName): base = getBase() taskMgr.add(nullTask, uniqueName(leakTaskName))", "graph size, # framerate, etc. See LeakDetectors.py if not hasattr(__builtin__,", "evalStr self.evalStr = '[%s]' % keyRepr else: try: # store", "in indirections: yield None indirection.acquire() for indirection in indirections: yield", "def getEvalStrGen(self, getInstance=False): str = '' prevIndirection = None curIndirection", "if not hasattr(__builtin__, \"leakDetectors\"): __builtin__.leakDetectors = {} ref = ObjectRef(Indirection(evalStr='leakDetectors'),", "Job.destroy(self) def getPriority(self): return Job.Priorities.Low @staticmethod def getStartObjAffinity(startObj): # how", "(obj.__dict__[keyName] == obj.keyName) if nextIndirection is not None and self.evalStr[-len(instanceDictStr):]", "things such as C++ memory usage, scene graph size, #", "end, start over from another container curObjRef = None if", "into %s with key %s' % ( parentObjRef, safeRepr(key))) continue", "the leak detector to hold a normal 'non-weak' reference class", "%s so it will be garbage-collected' % safeRepr(key)) del base.leakContainer[key]", "self._hasLength(attr) notDeadEnd = False # if we haven't picked the", "but eventually it will discover every object. Checks container sizes", "None): Job.__init__(self, name) self._serialNum = serialNum() self._findContainersJob = None self._checkContainersJob", "goesThrough def _getContainerByEval(self, evalStr, curObj=None): if curObj is not None:", "no longer exists if self.notify.getDebug(): for contName in self._leakDetector.getContainerNameByIdGen(objId): yield", "None and self.evalStr[-len(instanceDictStr):] == instanceDictStr: return self.evalStr[:-len(instanceDictStr)] # if the", "job start # fib: 1 2 4 7 12 20", "traversing the object graph? try: return len(startObj) except: return 1", "reference to the actual object, # that could cause a", "+= 1 numAttrsLeft -= 1 hasLength = self._hasLength(attr) notDeadEnd =", "get destroyed while we're using them for ind in self._indirections:", "(%s items at last measurement, current contents: %s)' % (", "' '5 periods (%s items at last measurement, current contents:", "these are working copies so that our iterations aren't disturbed", "stores a reference to a container in a way that", "'.__dict__': evalStr = evalStr[:-lenDict] # TODO: check that this is", "id): if id in self._id2ref: return repr(self._id2ref[id]) return '<unknown container>'", "FindContainers(Job): \"\"\" Explore the Python graph, looking for objects that", "self._index <= 4: if diff > 0 and diff2 >", "be destroyed return 'cldDestroy-%s' % self._serialNum def getLeakEvent(self): # sent", "self.notify.debug( '%s is no longer a container, it is now", "= idx2id2len[self._index][objId] - idx2id2len[self._index-1][objId] \"\"\" # this check is too", "> 1: prevIndirection = self._indirections[-2] return self._indirections[-1].getString(prevIndirection=prevIndirection) def __repr__(self): for", "last measurement, current contents: %s)' % (name, itype(container), idx2id2len[self._index][objId], fastRepr(container,", "self._otn = otn self._doneCallback = doneCallback self._ldde = self._leakDetector._getDestroyEvent() self.accept(self._ldde,", "store it as an evalStr keyRepr = safeRepr(dictKey) useEval =", "54 88 143 232 # * 2.: 1 3 7", "None except: # TODO self.notify.debug('caught exception in getContainerByIdGen (3)') else:", "this container is new, or the objRef repr is shorter", "@classmethod def addPrivateObj(cls, obj): cls.PrivateIds.add(id(obj)) @classmethod def removePrivateObj(cls, obj): cls.PrivateIds.remove(id(obj))", "eval('curObj.foo.bar.someDict') evalStr = 'curObj%s' % evalStr else: # this eval", "store a weakref to the key self.dictKey = weakref.ref(dictKey) self._isWeakRef", "skip over this one (obj.__dict__[keyName] == obj.keyName) if nextIndirection is", "return self.dictKey else: key = self.dictKey() if key is None:", "PruneObjectRefs(Job): \"\"\" Job to destroy any container refs that are", "if curObjRef is None: # choose an object to start", "leakDetector self.notify = self._leakDetector.notify self._otn = otn self._doneCallback = doneCallback", "when a leak is detected # passes description string as", "id(leakDetectors)) self._id2baseStartRef[id(leakDetectors)] = ref for i in self._addContainerGen(__builtin__.__dict__, ref): pass", "Exception, e: # this container no longer exists if self.notify.getDebug():", "useEval: # check to make sure the eval succeeded if", "'removing reference to leakContainer key %s so it will be", "up this key in the curObj dictionary curObj = indirection.dereferenceDictKey(curObj)", "3 7 15 31 63 127 255 511 1023 2047", "inside the while loop right off the bat workingListSelector =", "Queue, invertDictLossless, makeFlywheelGen from direct.showbase.PythonUtil import itype, serialNum, safeRepr, fastRepr", "a dict. Each dictionary dereference is individually eval'd since the", "to their length for fw in makeFlywheelGen( startRefWorkingList.source.values(), countFunc=lambda x:", "self._hasLength(child) notDeadEnd = not self._isDeadEnd(child) if hasLength or notDeadEnd: #", "!= bis: evalStr = '%s.%s' % (bis, evalStr) try: container", "curObj is __builtin__.__dict__: objRef = ObjectRef(Indirection(evalStr='%s' % key), id(curObj[key])) else:", "exception in getContainerByIdGen (1)') else: self.notify.warning( '%s (%s) grew %.2f%%", "0 and diff3 > 0: name = self._leakDetector.getContainerNameById(objId) try: for", "a reference to the actual object, # that could cause", "if task: return task.done leakTask() class NoDictKey: pass class Indirection:", "try: for container in self._leakDetector.getContainerByIdGen( id, getInstance=getInstance): yield None except:", "return '.%s' % keyRepr return '[%s]' % keyRepr def __repr__(self):", "def _isDeadEnd(self, obj, objName=None): if type(obj) in (types.BooleanType, types.BuiltinFunctionType, types.BuiltinMethodType,", "idx2id2len[self._index-4][objId] diff5 = idx2id2len[self._index-4][objId] - idx2id2len[self._index-5][objId] if diff > 0", "self.getJobName() + ': ' + ptc except Exception, e: print", "__init__(self, name, leakDetector): Job.__init__(self, name) self._leakDetector = leakDetector self.notify =", "traversals from often and not-as-often, # respectively self._id2baseStartRef = {}", "avoid storing multiple redundant refs to a single item if", "a copy of the current objRef parentObjRef = curObjRef #", "key of the dict, # choose it at random without", "for i in self._addContainerGen(attr, objRef): yield None if notDeadEnd: self._addDiscoveredStartRef(attr,", "leakDetector): Job.__init__(self, name) self._leakDetector = leakDetector self._id2ref = self._leakDetector._id2ref #", "in getContainerById (%s)' % ( contName, e)) self._leakDetector.removeContainerById(objId) continue if", "def _handleLDDestroy(self): self.destroy() def getPriority(self): return Job.Priorities.High def run(self): ids", "ones that hold most objects ref = ObjectRef(Indirection(evalStr='__builtin__.__dict__'), id(__builtin__.__dict__)) self._id2baseStartRef[id(__builtin__.__dict__)]", "del base.leakContainer[key] taskMgr.doMethodLater(10, leakContainer, 'leakContainer-%s' % serialNum()) if task: return", "% self._serialNum def getLeakEvent(self): # sent when a leak is", "in self._addContainerGen(base.__dict__, ref): pass try: simbase except: pass else: ref", "serialNum()) if task: return task.done leakContainer() def _createTaskLeak(): leakTaskName =", "dict, # choose it at random without taking a big", "getBase() if not hasattr(base, 'leakContainer'): base.leakContainer = {} # use", "= self._leakDetector._getDestroyEvent() self.accept(self._ldde, self._handleLDDestroy) ContainerLeakDetector.addPrivateObj(self.__dict__) def destroy(self): self.ignore(self._ldde) self._leakDetector =", "respectively self._id2baseStartRef = {} self._id2discoveredStartRef = {} # these are", "on self._doneCallback = doneCallback self._ldde = self._leakDetector._getDestroyEvent() self.accept(self._ldde, self._handleLDDestroy) ContainerLeakDetector.addPrivateObj(self.__dict__)", "2.: 1 3 7 15 31 63 127 255 511", "= None if self._checkContainersJob is not None: jobMgr.remove(self._checkContainersJob) self._checkContainersJob =", "self._leakDetector.notify ContainerLeakDetector.addPrivateObj(self.__dict__) # set up the base containers, the ones", "we cache the ids involved in this reference, # this", "continue try: childNames = dir(curObj) except: pass else: try: index", "self._id2ref: if (self._id2ref[objId].getNumIndirections() >= ref.getNumIndirections()): # the ref that we", "from try: startRefWorkingList = workingListSelector.next() except StopIteration: # do relative", "return Job.Priorities.Normal def run(self): try: self._leakDetector._index2containerId2len[self._index] = {} ids =", "_id2discoveredStartRef[id] except Exception, e: print 'PruneObjectRefs job caught exception: %s'", "pass if not goesThrough: objRef = ObjectRef(Indirection(evalStr='[%s]' % index), id(curObj[index]),", "etc.) continue # do we need to go look up", "e: print 'CheckContainers job caught exception: %s' % e if", "except: # reference is invalid, remove it del _id2discoveredStartRef[id] except", "type(objId) in (types.IntType, types.LongType) else: objId = id(obj) o =", "\"\"\" Represents the indirection that brings you from a container", "part of an eval, or as a key to be", "try: for container in _id2baseStartRef[id].getContainerGen(): yield None except: # reference", "self._leakDetector._getDestroyEvent() self.accept(self._ldde, self._handleLDDestroy) ContainerLeakDetector.addPrivateObj(self.__dict__) def destroy(self): self.ignore(self._ldde) self._leakDetector = None", "changes to the # definitive ref sets self._baseStartRefWorkingList = ScratchPad(refGen=nullGen(),", "= self._getContainerByEval(evalStr, curObj=curObj) if curObj is None: raise FailedEval(evalStr) #", "i in self._addContainerGen(base.__dict__, ref): pass try: simbase except: pass else:", "len('.__dict__') if str[-lenDict:] == '.__dict__': str = str[:-lenDict] for indirection", "diff > 0 and diff2 > 0 and diff3 >", "% e if __dev__: raise yield Job.Done class CheckContainers(Job): \"\"\"", "for ptc in self._leakDetector.getContainerNameByIdGen(id): yield None except: pass else: print", "cls.PrivateIds.add(id(obj)) @classmethod def removePrivateObj(cls, obj): cls.PrivateIds.remove(id(obj)) def _getCheckTaskName(self): return 'checkForLeakingContainers-%s'", "visited objects; it may visit the same object many times", "the type of each indirection # if getInstance is True,", "our iterations aren't disturbed by changes to the # definitive", "self._id2ref[id].getContainerGen(): pass return result def getContainerNameByIdGen(self, id, **kwArgs): return self._id2ref[id].getEvalStrGen(**kwArgs)" ]
[ "\"Only '=', '!=', 'is_()', 'isnot()', \" \"'is_distinct_from()', 'isnot_distinct_from()' \" \"operators", "of # as_scalar() to produce a multi- column selectable that", "\"sub\": (_binary_operate,), \"div\": (_binary_operate,), \"mod\": (_binary_operate,), \"truediv\": (_binary_operate,), \"custom_op\": (_custom_op_operate,),", "_const_expr(obj), operators.is_, negate=operators.isnot, type_=result_type ) elif op in (operators.ne, operators.isnot):", "in (operators.is_distinct_from, operators.isnot_distinct_from): return BinaryExpression(expr, _literal_as_text(obj), op, type_=result_type, negate=negate, modifiers=kwargs)", "left.comparator._adapt_expression( op, right.comparator) return BinaryExpression( left, right, op, type_=result_type, modifiers=kw)", "\"neg\": (_neg_impl,), \"getitem\": (_getitem_impl,), \"lshift\": (_unsupported_impl,), \"rshift\": (_unsupported_impl,), \"contains\": (_unsupported_impl,),", "= obj, expr else: left, right = expr, obj if", ") elif op in (operators.ne, operators.isnot): return BinaryExpression(expr, _const_expr(obj), operators.isnot,", "(_unsupported_impl,), \"contains\": (_unsupported_impl,), } def _check_literal(expr, operator, other, bindparam_type=None): if", "_check_literal(expr, operator, other, bindparam_type=None): if isinstance(other, (ColumnElement, TextClause)): if isinstance(other,", "in (operators.eq, operators.ne) and \\ isinstance(obj, (bool, True_, False_)): return", "obj, reverse=False, result_type=None, **kw): if result_type is None: if op.return_type:", "op, negate=operators.notbetween_op if op is operators.between_op else operators.between_op, modifiers=kw) def", "_python_is_types + (Null, True_, False_)): # allow x ==/!= True/False", "result_type = None, **kwargs): if result_type is None: result_type =", "not supported on \" \"this expression\" % op.__name__) def _inv_impl(expr,", "= expr, obj if result_type is None: op, result_type =", "_check_literal(expr, op, obj) if reverse: left, right = obj, expr", "operators.and_: return and_(expr, other) elif op is operators.or_: return or_(expr,", "\"notin_op\": (_in_impl, operators.in_op), \"is_\": (_boolean_compare, operators.is_), \"isnot\": (_boolean_compare, operators.isnot), \"collate\":", "operators.eq), \"gt\": (_boolean_compare, operators.le), \"ge\": (_boolean_compare, operators.lt), \"eq\": (_boolean_compare, operators.ne),", "with None/True/False\") else: obj = _check_literal(expr, op, obj) if reverse:", "in (operators.eq, operators.is_): return BinaryExpression(expr, _const_expr(obj), operators.is_, negate=operators.isnot, type_=result_type )", "**kw): obj = _check_literal(expr, op, obj) if reverse: left, right", "operators.ilike_op), \"contains_op\": (_boolean_compare, operators.notcontains_op), \"startswith_op\": (_boolean_compare, operators.notstartswith_op), \"endswith_op\": (_boolean_compare, operators.notendswith_op),", "return other elif hasattr(other, '__clause_element__'): other = other.__clause_element__() elif isinstance(other,", "if isinstance(seq_or_selectable, BindParameter) and \\ seq_or_selectable.expanding: return _boolean_compare( expr, op,", "operators.isnot_distinct_from), \"isnot_distinct_from\": (_boolean_compare, operators.is_distinct_from), \"like_op\": (_boolean_compare, operators.notlike_op), \"ilike_op\": (_boolean_compare, operators.notilike_op),", "_check_literal(expr, op, other) return _binary_operate(expr, op, other, **kw) else: _unsupported_impl(expr,", "# constants aren't supported and works on all platforms if", "ever want to support (x, y, z) IN (select x,", "fn, **kw): return fn(expr) def _in_impl(expr, op, seq_or_selectable, negate_op, **kw):", "UnaryExpression._create_nullslast), \"in_op\": (_in_impl, operators.notin_op), \"notin_op\": (_in_impl, operators.in_op), \"is_\": (_boolean_compare, operators.is_),", "\"json_getitem_op\": (_binary_operate, ), \"concat_op\": (_binary_operate,), \"any_op\": (_scalar, CollectionAggregate._create_any), \"all_op\": (_scalar,", "be used with None/True/False\") else: obj = _check_literal(expr, op, obj)", "\"\"\"Default implementation of SQL comparison operations. \"\"\" from .. import", "_binary_operate(expr, op, obj, reverse=False, result_type=None, **kw): obj = _check_literal(expr, op,", "op, ClauseList(*args).self_group(against=op), negate=negate_op) def _getitem_impl(expr, op, other, **kw): if isinstance(expr.type,", "_check_literal(expr, operators.and_, cright), operator=operators.and_, group=False, group_contents=False), op, negate=operators.notbetween_op if op", "expr._negate() def _neg_impl(expr, op, **kw): \"\"\"See :meth:`.ColumnOperators.__neg__`.\"\"\" return UnaryExpression(expr, operator=operators.neg,", "return UnaryExpression(expr, operator=operators.distinct_op, type_=expr.type) def _between_impl(expr, op, cleft, cright, **kw):", "else: return BinaryExpression(expr, obj, op, type_=result_type, negate=negate, modifiers=kwargs) def _custom_op_operate(expr,", "operator=operators.neg, type_=expr.type) def _match_impl(expr, op, other, **kw): \"\"\"See :meth:`.ColumnOperators.match`.\"\"\" return", "\\ seq_or_selectable.expanding: return _boolean_compare( expr, op, seq_or_selectable, negate=negate_op) else: raise", "operators.like_op), \"notilike_op\": (_boolean_compare, operators.ilike_op), \"contains_op\": (_boolean_compare, operators.notcontains_op), \"startswith_op\": (_boolean_compare, operators.notstartswith_op),", "other._clone() other.type = expr.type return other elif hasattr(other, '__clause_element__'): other", "= [] for o in seq_or_selectable: if not _is_literal(o): if", "IS NOT if op in (operators.eq, operators.is_): return BinaryExpression(expr, _const_expr(obj),", "\"nullslast_op\": (_scalar, UnaryExpression._create_nullslast), \"in_op\": (_in_impl, operators.notin_op), \"notin_op\": (_in_impl, operators.in_op), \"is_\":", "or an \"expanding\" bound parameter: %r' % seq_or_selectable) # Handle", "op in (operators.eq, operators.ne) and \\ isinstance(obj, (bool, True_, False_)):", "(_boolean_compare, operators.like_op), \"notilike_op\": (_boolean_compare, operators.ilike_op), \"contains_op\": (_boolean_compare, operators.notcontains_op), \"startswith_op\": (_boolean_compare,", "op, fn, **kw): return fn(expr) def _in_impl(expr, op, seq_or_selectable, negate_op,", "_check_literal(expr, operators.and_, cleft), _check_literal(expr, operators.and_, cright), operator=operators.and_, group=False, group_contents=False), op,", "%r' % o) elif o is None: o = Null()", "ScalarSelect): return _boolean_compare(expr, op, seq_or_selectable, negate=negate_op) elif isinstance(seq_or_selectable, SelectBase): #", "(_boolean_compare, operators.le), \"ge\": (_boolean_compare, operators.lt), \"eq\": (_boolean_compare, operators.ne), \"is_distinct_from\": (_boolean_compare,", "NotImplementedError(\"Operator '%s' is not supported on \" \"this expression\" %", "true/false\" or \"1/0\" if those # constants aren't supported and", "collate(expr, other) # a mapping of operators with the method", "len(args) == 0: op, negate_op = ( operators.empty_in_op, operators.empty_notin_op) if", "'a selectable, or an \"expanding\" bound parameter: %r' % seq_or_selectable)", "modifiers=kwargs) else: return BinaryExpression(expr, obj, op, type_=result_type, negate=negate, modifiers=kwargs) def", "elif op.is_comparison: result_type = type_api.BOOLEANTYPE return _binary_operate( expr, op, obj,", "left, right = expr, obj if result_type is None: op,", "op, **kw): \"\"\"See :meth:`.ColumnOperators.__inv__`.\"\"\" if hasattr(expr, 'negation_clause'): return expr.negation_clause else:", "need a multi-column version of # as_scalar() to produce a", "return _binary_operate( expr, op, obj, reverse=reverse, result_type=result_type, **kw) def _binary_operate(expr,", "not isinstance(o, operators.ColumnOperators): raise exc.InvalidRequestError( 'in_() accepts' ' either a", "BinaryExpression, \\ Null, _const_expr, _clause_element_as_expr, \\ ClauseList, ColumnElement, TextClause, UnaryExpression,", "if isinstance(other, BindParameter) and \\ other.type._isnull: other = other._clone() other.type", "operators operator_lookup = { \"and_\": (_conjunction_operate,), \"or_\": (_conjunction_operate,), \"inv\": (_inv_impl,),", "None, **kwargs): if result_type is None: result_type = type_api.BOOLEANTYPE if", "if isinstance(seq_or_selectable, ScalarSelect): return _boolean_compare(expr, op, seq_or_selectable, negate=negate_op) elif isinstance(seq_or_selectable,", "= Null() else: o = expr._bind_param(op, o) args.append(o) if len(args)", "\"json_path_getitem_op\": (_binary_operate, ), \"json_getitem_op\": (_binary_operate, ), \"concat_op\": (_binary_operate,), \"any_op\": (_scalar,", "Null() else: o = expr._bind_param(op, o) args.append(o) if len(args) ==", "_check_literal(expr, op, obj) if reverse: return BinaryExpression(obj, expr, op, type_=result_type,", "\" \"this expression\" % op.__name__) def _inv_impl(expr, op, **kw): \"\"\"See", "# TODO: if we ever want to support (x, y,", "\"\"\"See :meth:`.ColumnOperators.__neg__`.\"\"\" return UnaryExpression(expr, operator=operators.neg, type_=expr.type) def _match_impl(expr, op, other,", "return _binary_operate(expr, op, other, **kw) else: _unsupported_impl(expr, op, other, **kw)", "other, **kw): if op is operators.and_: return and_(expr, other) elif", "operator_lookup = { \"and_\": (_conjunction_operate,), \"or_\": (_conjunction_operate,), \"inv\": (_inv_impl,), \"add\":", "(_binary_operate,), \"any_op\": (_scalar, CollectionAggregate._create_any), \"all_op\": (_scalar, CollectionAggregate._create_all), \"lt\": (_boolean_compare, operators.ge),", "_const_expr(obj), operators.isnot, negate=operators.is_, type_=result_type ) else: raise exc.ArgumentError( \"Only '=',", ") def _distinct_impl(expr, op, **kw): \"\"\"See :meth:`.ColumnOperators.distinct`.\"\"\" return UnaryExpression(expr, operator=operators.distinct_op,", "return BinaryExpression(expr, _const_expr(obj), operators.is_, negate=operators.isnot, type_=result_type ) elif op in", "with # their negated operator for comparison operators operator_lookup =", "\\ collate, _is_literal, _literal_as_text, ClauseElement, and_, or_, \\ Slice, Visitable,", "operator, other, bindparam_type=None): if isinstance(other, (ColumnElement, TextClause)): if isinstance(other, BindParameter)", "op is operators.or_: return or_(expr, other) else: raise NotImplementedError() def", "operators.and_, cleft), _check_literal(expr, operators.and_, cright), operator=operators.and_, group=False, group_contents=False), op, negate=operators.notbetween_op", "return expr._negate() def _neg_impl(expr, op, **kw): \"\"\"See :meth:`.ColumnOperators.__neg__`.\"\"\" return UnaryExpression(expr,", "op, **kw): \"\"\"See :meth:`.ColumnOperators.__neg__`.\"\"\" return UnaryExpression(expr, operator=operators.neg, type_=expr.type) def _match_impl(expr,", "(_scalar, CollectionAggregate._create_all), \"lt\": (_boolean_compare, operators.ge), \"le\": (_boolean_compare, operators.gt), \"ne\": (_boolean_compare,", "\"nullsfirst_op\": (_scalar, UnaryExpression._create_nullsfirst), \"nullslast_op\": (_scalar, UnaryExpression._create_nullslast), \"in_op\": (_in_impl, operators.notin_op), \"notin_op\":", "(_custom_op_operate,), \"json_path_getitem_op\": (_binary_operate, ), \"json_getitem_op\": (_binary_operate, ), \"concat_op\": (_binary_operate,), \"any_op\":", "return expr.negation_clause else: return expr._negate() def _neg_impl(expr, op, **kw): \"\"\"See", "'is_()', 'isnot()', \" \"'is_distinct_from()', 'isnot_distinct_from()' \" \"operators can be used", "operators.isnot, negate=operators.is_, type_=result_type ) else: raise exc.ArgumentError( \"Only '=', '!=',", "\"desc_op\": (_scalar, UnaryExpression._create_desc), \"asc_op\": (_scalar, UnaryExpression._create_asc), \"nullsfirst_op\": (_scalar, UnaryExpression._create_nullsfirst), \"nullslast_op\":", "type_=result_type, modifiers=kw) def _conjunction_operate(expr, op, other, **kw): if op is", "(_boolean_compare, operators.isnot), \"collate\": (_collate_impl,), \"match_op\": (_match_impl,), \"notmatch_op\": (_match_impl,), \"distinct_op\": (_distinct_impl,),", "op, obj, reverse=False, result_type=None, **kw): if result_type is None: if", "(_match_impl,), \"distinct_op\": (_distinct_impl,), \"between_op\": (_between_impl, ), \"notbetween_op\": (_between_impl, ), \"neg\":", "# does not export itself as a FROM clause return", "isinstance(o, operators.ColumnOperators): raise exc.InvalidRequestError( 'in_() accepts' ' either a list", "operators.ne) and \\ isinstance(obj, (bool, True_, False_)): return BinaryExpression(expr, _literal_as_text(obj),", "result_type = left.comparator._adapt_expression( op, right.comparator) return BinaryExpression( left, right, op,", "and \\ seq_or_selectable.expanding: return _boolean_compare( expr, op, seq_or_selectable, negate=negate_op) else:", "(_between_impl, ), \"notbetween_op\": (_between_impl, ), \"neg\": (_neg_impl,), \"getitem\": (_getitem_impl,), \"lshift\":", "use, along with # their negated operator for comparison operators", "isinstance(obj, _python_is_types + (Null, True_, False_)): # allow x ==/!=", "return and_(expr, other) elif op is operators.or_: return or_(expr, other)", "obj, reverse=reverse, result_type=result_type, **kw) def _binary_operate(expr, op, obj, reverse=False, result_type=None,", "\\ isinstance(obj, (bool, True_, False_)): return BinaryExpression(expr, _literal_as_text(obj), op, type_=result_type,", "def _unsupported_impl(expr, op, *arg, **kw): raise NotImplementedError(\"Operator '%s' is not", "True_, False_)): return BinaryExpression(expr, _literal_as_text(obj), op, type_=result_type, negate=negate, modifiers=kwargs) elif", "if op.return_type: result_type = op.return_type elif op.is_comparison: result_type = type_api.BOOLEANTYPE", "elif isinstance(seq_or_selectable, ClauseElement): if isinstance(seq_or_selectable, BindParameter) and \\ seq_or_selectable.expanding: return", "_match_impl(expr, op, other, **kw): \"\"\"See :meth:`.ColumnOperators.match`.\"\"\" return _boolean_compare( expr, operators.match_op,", "import BindParameter, True_, False_, BinaryExpression, \\ Null, _const_expr, _clause_element_as_expr, \\", "_check_literal( expr, operators.match_op, other), result_type=type_api.MATCHTYPE, negate=operators.notmatch_op if op is operators.match_op", "negate=negate_op) def _getitem_impl(expr, op, other, **kw): if isinstance(expr.type, type_api.INDEXABLE): other", "{ \"and_\": (_conjunction_operate,), \"or_\": (_conjunction_operate,), \"inv\": (_inv_impl,), \"add\": (_binary_operate,), \"mul\":", "other elif hasattr(other, '__clause_element__'): other = other.__clause_element__() elif isinstance(other, type_api.TypeEngine.Comparator):", "if result_type is None: result_type = type_api.BOOLEANTYPE if isinstance(obj, _python_is_types", "other, **kw): return collate(expr, other) # a mapping of operators", "a mapping of operators with the method they use, along", "produce a multi- column selectable that # does not export", "operators.or_: return or_(expr, other) else: raise NotImplementedError() def _scalar(expr, op,", "CollectionAggregate._create_any), \"all_op\": (_scalar, CollectionAggregate._create_all), \"lt\": (_boolean_compare, operators.ge), \"le\": (_boolean_compare, operators.gt),", "% o) elif o is None: o = Null() else:", "operators.lt), \"eq\": (_boolean_compare, operators.ne), \"is_distinct_from\": (_boolean_compare, operators.isnot_distinct_from), \"isnot_distinct_from\": (_boolean_compare, operators.is_distinct_from),", "supported and works on all platforms if op in (operators.eq,", "(operators.ne, operators.isnot): return BinaryExpression(expr, _const_expr(obj), operators.isnot, negate=operators.is_, type_=result_type ) else:", "2005-2018 the SQLAlchemy authors and contributors # <see AUTHORS file>", "_collate_impl(expr, op, other, **kw): return collate(expr, other) # a mapping", "_distinct_impl(expr, op, **kw): \"\"\"See :meth:`.ColumnOperators.distinct`.\"\"\" return UnaryExpression(expr, operator=operators.distinct_op, type_=expr.type) def", "return BinaryExpression(expr, _literal_as_text(obj), op, type_=result_type, negate=negate, modifiers=kwargs) else: # all", "0: op, negate_op = ( operators.empty_in_op, operators.empty_notin_op) if op is", "op, *arg, **kw): raise NotImplementedError(\"Operator '%s' is not supported on", "comparison operators operator_lookup = { \"and_\": (_conjunction_operate,), \"or_\": (_conjunction_operate,), \"inv\":", "else: o = expr._bind_param(op, o) args.append(o) if len(args) == 0:", "), \"concat_op\": (_binary_operate,), \"any_op\": (_scalar, CollectionAggregate._create_any), \"all_op\": (_scalar, CollectionAggregate._create_all), \"lt\":", "hasattr(other, '__clause_element__'): other = other.__clause_element__() elif isinstance(other, type_api.TypeEngine.Comparator): other =", "\"\"\"See :meth:`.ColumnOperators.distinct`.\"\"\" return UnaryExpression(expr, operator=operators.distinct_op, type_=expr.type) def _between_impl(expr, op, cleft,", "'%s' is not supported on \" \"this expression\" % op.__name__)", "raise exc.ArgumentError( \"Only '=', '!=', 'is_()', 'isnot()', \" \"'is_distinct_from()', 'isnot_distinct_from()'", "\"match_op\": (_match_impl,), \"notmatch_op\": (_match_impl,), \"distinct_op\": (_distinct_impl,), \"between_op\": (_between_impl, ), \"notbetween_op\":", "operators.ne), \"is_distinct_from\": (_boolean_compare, operators.isnot_distinct_from), \"isnot_distinct_from\": (_boolean_compare, operators.is_distinct_from), \"like_op\": (_boolean_compare, operators.notlike_op),", "elif op in (operators.ne, operators.isnot): return BinaryExpression(expr, _const_expr(obj), operators.isnot, negate=operators.is_,", "ClauseList( _check_literal(expr, operators.and_, cleft), _check_literal(expr, operators.and_, cright), operator=operators.and_, group=False, group_contents=False),", "obj) if reverse: left, right = obj, expr else: left,", "(_boolean_compare, operators.ge), \"le\": (_boolean_compare, operators.gt), \"ne\": (_boolean_compare, operators.eq), \"gt\": (_boolean_compare,", "(_boolean_compare, operators.is_distinct_from), \"like_op\": (_boolean_compare, operators.notlike_op), \"ilike_op\": (_boolean_compare, operators.notilike_op), \"notlike_op\": (_boolean_compare,", "cleft), _check_literal(expr, operators.and_, cright), operator=operators.and_, group=False, group_contents=False), op, negate=operators.notbetween_op if", "BinaryExpression( left, right, op, type_=result_type, modifiers=kw) def _conjunction_operate(expr, op, other,", "MIT License: http://www.opensource.org/licenses/mit-license.php \"\"\"Default implementation of SQL comparison operations. \"\"\"", "\"\"\" from .. import exc, util from . import type_api", "if op is operators.between_op else operators.between_op, modifiers=kw) def _collate_impl(expr, op,", "operators.is_, negate=operators.isnot, type_=result_type ) elif op in (operators.ne, operators.isnot): return", "\"mod\": (_binary_operate,), \"truediv\": (_binary_operate,), \"custom_op\": (_custom_op_operate,), \"json_path_getitem_op\": (_binary_operate, ), \"json_getitem_op\":", "# Handle non selectable arguments as sequences args = []", "\"mul\": (_binary_operate,), \"sub\": (_binary_operate,), \"div\": (_binary_operate,), \"mod\": (_binary_operate,), \"truediv\": (_binary_operate,),", "else: _unsupported_impl(expr, op, other, **kw) def _unsupported_impl(expr, op, *arg, **kw):", "implementation of SQL comparison operations. \"\"\" from .. import exc,", "(_boolean_compare, operators.notcontains_op), \"startswith_op\": (_boolean_compare, operators.notstartswith_op), \"endswith_op\": (_boolean_compare, operators.notendswith_op), \"desc_op\": (_scalar,", "negate=None, reverse=False, _python_is_types=(util.NoneType, bool), result_type = None, **kwargs): if result_type", "operators.is_): return BinaryExpression(expr, _const_expr(obj), operators.is_, negate=operators.isnot, type_=result_type ) elif op", "else: raise exc.ArgumentError( \"Only '=', '!=', 'is_()', 'isnot()', \" \"'is_distinct_from()',", "op, right.comparator) return BinaryExpression( left, right, op, type_=result_type, modifiers=kw) def", "else: raise exc.InvalidRequestError( 'in_() accepts' ' either a list of", "(_boolean_compare, operators.is_), \"isnot\": (_boolean_compare, operators.isnot), \"collate\": (_collate_impl,), \"match_op\": (_match_impl,), \"notmatch_op\":", "expr, op, type_=result_type, negate=negate, modifiers=kwargs) else: return BinaryExpression(expr, obj, op,", "right = expr, obj if result_type is None: op, result_type", "**kw): \"\"\"See :meth:`.ColumnOperators.__neg__`.\"\"\" return UnaryExpression(expr, operator=operators.neg, type_=expr.type) def _match_impl(expr, op,", "if those # constants aren't supported and works on all", "operators.between_op else operators.between_op, modifiers=kw) def _collate_impl(expr, op, other, **kw): return", "Alias)): return other.as_scalar() elif not isinstance(other, Visitable): return expr._bind_param(operator, other,", "(_boolean_compare, operators.notstartswith_op), \"endswith_op\": (_boolean_compare, operators.notendswith_op), \"desc_op\": (_scalar, UnaryExpression._create_desc), \"asc_op\": (_scalar,", "# all other None/True/False uses IS, IS NOT if op", "# This module is part of SQLAlchemy and is released", "type_=expr.type) def _between_impl(expr, op, cleft, cright, **kw): \"\"\"See :meth:`.ColumnOperators.between`.\"\"\" return", "isinstance(seq_or_selectable, SelectBase): # TODO: if we ever want to support", "\"in_op\": (_in_impl, operators.notin_op), \"notin_op\": (_in_impl, operators.in_op), \"is_\": (_boolean_compare, operators.is_), \"isnot\":", "# <see AUTHORS file> # # This module is part", "their negated operator for comparison operators operator_lookup = { \"and_\":", "elif isinstance(seq_or_selectable, SelectBase): # TODO: if we ever want to", "negate_op = ( operators.empty_in_op, operators.empty_notin_op) if op is operators.in_op \\", "y, z) IN (select x, # y, z from table),", "op, result_type = left.comparator._adapt_expression( op, right.comparator) return BinaryExpression( left, right,", "exc.InvalidRequestError( 'in_() accepts' ' either a list of expressions, '", "version of # as_scalar() to produce a multi- column selectable", "(bool, True_, False_)): return BinaryExpression(expr, _literal_as_text(obj), op, type_=result_type, negate=negate, modifiers=kwargs)", "type_=result_type ) else: raise exc.ArgumentError( \"Only '=', '!=', 'is_()', 'isnot()',", "result_type=None, **kw): obj = _check_literal(expr, op, obj) if reverse: left,", "op, other, **kw): if isinstance(expr.type, type_api.INDEXABLE): other = _check_literal(expr, op,", "accepts' ' either a list of expressions, ' 'a selectable,", "o = Null() else: o = expr._bind_param(op, o) args.append(o) if", "op in (operators.ne, operators.isnot): return BinaryExpression(expr, _const_expr(obj), operators.isnot, negate=operators.is_, type_=result_type", "op, seq_or_selectable.as_scalar(), negate=negate_op, **kw) elif isinstance(seq_or_selectable, (Selectable, TextClause)): return _boolean_compare(expr,", "(_collate_impl,), \"match_op\": (_match_impl,), \"notmatch_op\": (_match_impl,), \"distinct_op\": (_distinct_impl,), \"between_op\": (_between_impl, ),", "support (x, y, z) IN (select x, # y, z", "is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php \"\"\"Default implementation", "for comparison operators operator_lookup = { \"and_\": (_conjunction_operate,), \"or_\": (_conjunction_operate,),", "(_boolean_compare, operators.isnot_distinct_from), \"isnot_distinct_from\": (_boolean_compare, operators.is_distinct_from), \"like_op\": (_boolean_compare, operators.notlike_op), \"ilike_op\": (_boolean_compare,", "other.type = expr.type return other elif hasattr(other, '__clause_element__'): other =", "expr, op, obj, reverse=reverse, result_type=result_type, **kw) def _binary_operate(expr, op, obj,", "\"and_\": (_conjunction_operate,), \"or_\": (_conjunction_operate,), \"inv\": (_inv_impl,), \"add\": (_binary_operate,), \"mul\": (_binary_operate,),", "expr.negation_clause else: return expr._negate() def _neg_impl(expr, op, **kw): \"\"\"See :meth:`.ColumnOperators.__neg__`.\"\"\"", "modifiers=kwargs) def _custom_op_operate(expr, op, obj, reverse=False, result_type=None, **kw): if result_type", "and_(expr, other) elif op is operators.or_: return or_(expr, other) else:", "def _in_impl(expr, op, seq_or_selectable, negate_op, **kw): seq_or_selectable = _clause_element_as_expr(seq_or_selectable) if", "operators.notendswith_op), \"desc_op\": (_scalar, UnaryExpression._create_desc), \"asc_op\": (_scalar, UnaryExpression._create_asc), \"nullsfirst_op\": (_scalar, UnaryExpression._create_nullsfirst),", "exc.ArgumentError( \"Only '=', '!=', 'is_()', 'isnot()', \" \"'is_distinct_from()', 'isnot_distinct_from()' \"", "or an \"expanding\" bound parameter: %r' % o) elif o", "(_neg_impl,), \"getitem\": (_getitem_impl,), \"lshift\": (_unsupported_impl,), \"rshift\": (_unsupported_impl,), \"contains\": (_unsupported_impl,), }", "negate=negate_op, **kw) elif isinstance(seq_or_selectable, ClauseElement): if isinstance(seq_or_selectable, BindParameter) and \\", "_clause_element_as_expr, \\ ClauseList, ColumnElement, TextClause, UnaryExpression, \\ collate, _is_literal, _literal_as_text,", "operators.empty_in_op, operators.empty_notin_op) if op is operators.in_op \\ else ( operators.empty_notin_op,", "table), we would need a multi-column version of # as_scalar()", "operators.in_op \\ else ( operators.empty_notin_op, operators.empty_in_op) return _boolean_compare(expr, op, ClauseList(*args).self_group(against=op),", "fn(expr) def _in_impl(expr, op, seq_or_selectable, negate_op, **kw): seq_or_selectable = _clause_element_as_expr(seq_or_selectable)", "Null, _const_expr, _clause_element_as_expr, \\ ClauseList, ColumnElement, TextClause, UnaryExpression, \\ collate,", "is None: op, result_type = left.comparator._adapt_expression( op, right.comparator) return BinaryExpression(", "would need a multi-column version of # as_scalar() to produce", "return UnaryExpression(expr, operator=operators.neg, type_=expr.type) def _match_impl(expr, op, other, **kw): \"\"\"See", "isinstance(other, (ColumnElement, TextClause)): if isinstance(other, BindParameter) and \\ other.type._isnull: other", "isinstance(seq_or_selectable, (Selectable, TextClause)): return _boolean_compare(expr, op, seq_or_selectable, negate=negate_op, **kw) elif", "UnaryExpression._create_asc), \"nullsfirst_op\": (_scalar, UnaryExpression._create_nullsfirst), \"nullslast_op\": (_scalar, UnaryExpression._create_nullslast), \"in_op\": (_in_impl, operators.notin_op),", "_boolean_compare(expr, op, obj, negate=None, reverse=False, _python_is_types=(util.NoneType, bool), result_type = None,", "op, obj, negate=None, reverse=False, _python_is_types=(util.NoneType, bool), result_type = None, **kwargs):", "obj, negate=None, reverse=False, _python_is_types=(util.NoneType, bool), result_type = None, **kwargs): if", "operations. \"\"\" from .. import exc, util from . import", "return fn(expr) def _in_impl(expr, op, seq_or_selectable, negate_op, **kw): seq_or_selectable =", "operators.empty_notin_op) if op is operators.in_op \\ else ( operators.empty_notin_op, operators.empty_in_op)", ". import operators from .elements import BindParameter, True_, False_, BinaryExpression,", "UnaryExpression._create_nullsfirst), \"nullslast_op\": (_scalar, UnaryExpression._create_nullslast), \"in_op\": (_in_impl, operators.notin_op), \"notin_op\": (_in_impl, operators.in_op),", "be treated as a literal. # this comes out to", "negate=negate_op) else: raise exc.InvalidRequestError( 'in_() accepts' ' either a list", "= ( operators.empty_in_op, operators.empty_notin_op) if op is operators.in_op \\ else", "cleft, cright, **kw): \"\"\"See :meth:`.ColumnOperators.between`.\"\"\" return BinaryExpression( expr, ClauseList( _check_literal(expr,", "or_(expr, other) else: raise NotImplementedError() def _scalar(expr, op, fn, **kw):", "operator=operators.distinct_op, type_=expr.type) def _between_impl(expr, op, cleft, cright, **kw): \"\"\"See :meth:`.ColumnOperators.between`.\"\"\"", "ClauseList(*args).self_group(against=op), negate=negate_op) def _getitem_impl(expr, op, other, **kw): if isinstance(expr.type, type_api.INDEXABLE):", "IN (select x, # y, z from table), we would", "_boolean_compare( expr, operators.match_op, _check_literal( expr, operators.match_op, other), result_type=type_api.MATCHTYPE, negate=operators.notmatch_op if", "\"distinct_op\": (_distinct_impl,), \"between_op\": (_between_impl, ), \"notbetween_op\": (_between_impl, ), \"neg\": (_neg_impl,),", "expr.type return other elif hasattr(other, '__clause_element__'): other = other.__clause_element__() elif", "expr, obj if result_type is None: op, result_type = left.comparator._adapt_expression(", "\"add\": (_binary_operate,), \"mul\": (_binary_operate,), \"sub\": (_binary_operate,), \"div\": (_binary_operate,), \"mod\": (_binary_operate,),", "_python_is_types=(util.NoneType, bool), result_type = None, **kwargs): if result_type is None:", "\"inv\": (_inv_impl,), \"add\": (_binary_operate,), \"mul\": (_binary_operate,), \"sub\": (_binary_operate,), \"div\": (_binary_operate,),", "list of expressions, ' 'a selectable, or an \"expanding\" bound", "or_, \\ Slice, Visitable, _literal_as_binds, CollectionAggregate from .selectable import SelectBase,", "we ever want to support (x, y, z) IN (select", "return _boolean_compare( expr, op, seq_or_selectable, negate=negate_op) else: raise exc.InvalidRequestError( 'in_()", "operators with the method they use, along with # their", "if op is operators.in_op \\ else ( operators.empty_notin_op, operators.empty_in_op) return", "AUTHORS file> # # This module is part of SQLAlchemy", "that # does not export itself as a FROM clause", "**kw ) def _distinct_impl(expr, op, **kw): \"\"\"See :meth:`.ColumnOperators.distinct`.\"\"\" return UnaryExpression(expr,", "reverse: return BinaryExpression(obj, expr, op, type_=result_type, negate=negate, modifiers=kwargs) else: return", "(operators.is_distinct_from, operators.isnot_distinct_from): return BinaryExpression(expr, _literal_as_text(obj), op, type_=result_type, negate=negate, modifiers=kwargs) else:", "result_type is None: op, result_type = left.comparator._adapt_expression( op, right.comparator) return", "modifiers=kwargs) else: # all other None/True/False uses IS, IS NOT", "other, **kw): if isinstance(expr.type, type_api.INDEXABLE): other = _check_literal(expr, op, other)", "other.type._isnull: other = other._clone() other.type = expr.type return other elif", "return BinaryExpression( left, right, op, type_=result_type, modifiers=kw) def _conjunction_operate(expr, op,", "op in (operators.eq, operators.is_): return BinaryExpression(expr, _const_expr(obj), operators.is_, negate=operators.isnot, type_=result_type", "(_in_impl, operators.notin_op), \"notin_op\": (_in_impl, operators.in_op), \"is_\": (_boolean_compare, operators.is_), \"isnot\": (_boolean_compare,", "= op.return_type elif op.is_comparison: result_type = type_api.BOOLEANTYPE return _binary_operate( expr,", "is None: o = Null() else: o = expr._bind_param(op, o)", "SelectBase, Alias, Selectable, ScalarSelect def _boolean_compare(expr, op, obj, negate=None, reverse=False,", "result_type=result_type, **kw) def _binary_operate(expr, op, obj, reverse=False, result_type=None, **kw): obj", "(_binary_operate,), \"truediv\": (_binary_operate,), \"custom_op\": (_custom_op_operate,), \"json_path_getitem_op\": (_binary_operate, ), \"json_getitem_op\": (_binary_operate,", "True_, False_)): # allow x ==/!= True/False to be treated", "op is operators.match_op else operators.match_op, **kw ) def _distinct_impl(expr, op,", "This module is part of SQLAlchemy and is released under", "BinaryExpression(expr, _const_expr(obj), operators.is_, negate=operators.isnot, type_=result_type ) elif op in (operators.ne,", "op, other, **kw): if op is operators.and_: return and_(expr, other)", "TextClause, UnaryExpression, \\ collate, _is_literal, _literal_as_text, ClauseElement, and_, or_, \\", "\"lshift\": (_unsupported_impl,), \"rshift\": (_unsupported_impl,), \"contains\": (_unsupported_impl,), } def _check_literal(expr, operator,", "negate=operators.notmatch_op if op is operators.match_op else operators.match_op, **kw ) def", "!= true/false\" or \"1/0\" if those # constants aren't supported", "operators.match_op, **kw ) def _distinct_impl(expr, op, **kw): \"\"\"See :meth:`.ColumnOperators.distinct`.\"\"\" return", "isinstance(seq_or_selectable, BindParameter) and \\ seq_or_selectable.expanding: return _boolean_compare( expr, op, seq_or_selectable,", "op, cleft, cright, **kw): \"\"\"See :meth:`.ColumnOperators.between`.\"\"\" return BinaryExpression( expr, ClauseList(", "**kw) else: _unsupported_impl(expr, op, other, **kw) def _unsupported_impl(expr, op, *arg,", "op, type_=result_type, negate=negate, modifiers=kwargs) else: return BinaryExpression(expr, obj, op, type_=result_type,", "expr else: left, right = expr, obj if result_type is", "operators.empty_in_op) return _boolean_compare(expr, op, ClauseList(*args).self_group(against=op), negate=negate_op) def _getitem_impl(expr, op, other,", "op is operators.between_op else operators.between_op, modifiers=kw) def _collate_impl(expr, op, other,", "bool), result_type = None, **kwargs): if result_type is None: result_type", "z) IN (select x, # y, z from table), we", "TextClause)): return _boolean_compare(expr, op, seq_or_selectable, negate=negate_op, **kw) elif isinstance(seq_or_selectable, ClauseElement):", "BinaryExpression( expr, ClauseList( _check_literal(expr, operators.and_, cleft), _check_literal(expr, operators.and_, cright), operator=operators.and_,", "**kw): seq_or_selectable = _clause_element_as_expr(seq_or_selectable) if isinstance(seq_or_selectable, ScalarSelect): return _boolean_compare(expr, op,", "group=False, group_contents=False), op, negate=operators.notbetween_op if op is operators.between_op else operators.between_op,", "(_scalar, CollectionAggregate._create_any), \"all_op\": (_scalar, CollectionAggregate._create_all), \"lt\": (_boolean_compare, operators.ge), \"le\": (_boolean_compare,", "operators.notilike_op), \"notlike_op\": (_boolean_compare, operators.like_op), \"notilike_op\": (_boolean_compare, operators.ilike_op), \"contains_op\": (_boolean_compare, operators.notcontains_op),", "op, **kw): \"\"\"See :meth:`.ColumnOperators.distinct`.\"\"\" return UnaryExpression(expr, operator=operators.distinct_op, type_=expr.type) def _between_impl(expr,", "\\ other.type._isnull: other = other._clone() other.type = expr.type return other", "= _check_literal(expr, op, obj) if reverse: return BinaryExpression(obj, expr, op,", "if op is operators.and_: return and_(expr, other) elif op is", "\"this expression\" % op.__name__) def _inv_impl(expr, op, **kw): \"\"\"See :meth:`.ColumnOperators.__inv__`.\"\"\"", "\"asc_op\": (_scalar, UnaryExpression._create_asc), \"nullsfirst_op\": (_scalar, UnaryExpression._create_nullsfirst), \"nullslast_op\": (_scalar, UnaryExpression._create_nullslast), \"in_op\":", "hasattr(expr, 'negation_clause'): return expr.negation_clause else: return expr._negate() def _neg_impl(expr, op,", "\" \"operators can be used with None/True/False\") else: obj =", "None: o = Null() else: o = expr._bind_param(op, o) args.append(o)", "not _is_literal(o): if not isinstance(o, operators.ColumnOperators): raise exc.InvalidRequestError( 'in_() accepts'", "def _custom_op_operate(expr, op, obj, reverse=False, result_type=None, **kw): if result_type is", "reverse=reverse, result_type=result_type, **kw) def _binary_operate(expr, op, obj, reverse=False, result_type=None, **kw):", "def _conjunction_operate(expr, op, other, **kw): if op is operators.and_: return", "\"any_op\": (_scalar, CollectionAggregate._create_any), \"all_op\": (_scalar, CollectionAggregate._create_all), \"lt\": (_boolean_compare, operators.ge), \"le\":", "op is operators.and_: return and_(expr, other) elif op is operators.or_:", "expression\" % op.__name__) def _inv_impl(expr, op, **kw): \"\"\"See :meth:`.ColumnOperators.__inv__`.\"\"\" if", "op, type_=result_type, negate=negate, modifiers=kwargs) def _custom_op_operate(expr, op, obj, reverse=False, result_type=None,", "operators.is_), \"isnot\": (_boolean_compare, operators.isnot), \"collate\": (_collate_impl,), \"match_op\": (_match_impl,), \"notmatch_op\": (_match_impl,),", "obj, reverse=False, result_type=None, **kw): obj = _check_literal(expr, op, obj) if", "None: if op.return_type: result_type = op.return_type elif op.is_comparison: result_type =", "reverse=False, result_type=None, **kw): obj = _check_literal(expr, op, obj) if reverse:", "multi- column selectable that # does not export itself as", "= expr._bind_param(op, o) args.append(o) if len(args) == 0: op, negate_op", "_is_literal, _literal_as_text, ClauseElement, and_, or_, \\ Slice, Visitable, _literal_as_binds, CollectionAggregate", "elif op is operators.or_: return or_(expr, other) else: raise NotImplementedError()", "def _boolean_compare(expr, op, obj, negate=None, reverse=False, _python_is_types=(util.NoneType, bool), result_type =", "\"notilike_op\": (_boolean_compare, operators.ilike_op), \"contains_op\": (_boolean_compare, operators.notcontains_op), \"startswith_op\": (_boolean_compare, operators.notstartswith_op), \"endswith_op\":", "and contributors # <see AUTHORS file> # # This module", "BinaryExpression(obj, expr, op, type_=result_type, negate=negate, modifiers=kwargs) else: return BinaryExpression(expr, obj,", "'a selectable, or an \"expanding\" bound parameter: %r' % o)", "of operators with the method they use, along with #", "obj = _check_literal(expr, op, obj) if reverse: left, right =", "o in seq_or_selectable: if not _is_literal(o): if not isinstance(o, operators.ColumnOperators):", "file> # # This module is part of SQLAlchemy and", "o) elif o is None: o = Null() else: o", "(C) 2005-2018 the SQLAlchemy authors and contributors # <see AUTHORS", "and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php \"\"\"Default", "collate, _is_literal, _literal_as_text, ClauseElement, and_, or_, \\ Slice, Visitable, _literal_as_binds,", "left, right, op, type_=result_type, modifiers=kw) def _conjunction_operate(expr, op, other, **kw):", "(_binary_operate,), \"custom_op\": (_custom_op_operate,), \"json_path_getitem_op\": (_binary_operate, ), \"json_getitem_op\": (_binary_operate, ), \"concat_op\":", "\"ne\": (_boolean_compare, operators.eq), \"gt\": (_boolean_compare, operators.le), \"ge\": (_boolean_compare, operators.lt), \"eq\":", "\\ ClauseList, ColumnElement, TextClause, UnaryExpression, \\ collate, _is_literal, _literal_as_text, ClauseElement,", "IS, IS NOT if op in (operators.eq, operators.is_): return BinaryExpression(expr,", "\"expanding\" bound parameter: %r' % seq_or_selectable) # Handle non selectable", "clause return _boolean_compare( expr, op, seq_or_selectable.as_scalar(), negate=negate_op, **kw) elif isinstance(seq_or_selectable,", "right, op, type_=result_type, modifiers=kw) def _conjunction_operate(expr, op, other, **kw): if", "group_contents=False), op, negate=operators.notbetween_op if op is operators.between_op else operators.between_op, modifiers=kw)", "treated as a literal. # this comes out to \"==", "= _check_literal(expr, op, other) return _binary_operate(expr, op, other, **kw) else:", "expr._bind_param(op, o) args.append(o) if len(args) == 0: op, negate_op =", "other = other.__clause_element__() elif isinstance(other, type_api.TypeEngine.Comparator): other = other.expr if", "\"ge\": (_boolean_compare, operators.lt), \"eq\": (_boolean_compare, operators.ne), \"is_distinct_from\": (_boolean_compare, operators.isnot_distinct_from), \"isnot_distinct_from\":", "= None, **kwargs): if result_type is None: result_type = type_api.BOOLEANTYPE", "BinaryExpression(expr, _literal_as_text(obj), op, type_=result_type, negate=negate, modifiers=kwargs) elif op in (operators.is_distinct_from,", "'!=', 'is_()', 'isnot()', \" \"'is_distinct_from()', 'isnot_distinct_from()' \" \"operators can be", "\"endswith_op\": (_boolean_compare, operators.notendswith_op), \"desc_op\": (_scalar, UnaryExpression._create_desc), \"asc_op\": (_scalar, UnaryExpression._create_asc), \"nullsfirst_op\":", ".selectable import SelectBase, Alias, Selectable, ScalarSelect def _boolean_compare(expr, op, obj,", "= _check_literal(expr, op, obj) if reverse: left, right = obj,", "raise exc.InvalidRequestError( 'in_() accepts' ' either a list of expressions,", "in (operators.ne, operators.isnot): return BinaryExpression(expr, _const_expr(obj), operators.isnot, negate=operators.is_, type_=result_type )", "_literal_as_binds, CollectionAggregate from .selectable import SelectBase, Alias, Selectable, ScalarSelect def", "**kw): \"\"\"See :meth:`.ColumnOperators.match`.\"\"\" return _boolean_compare( expr, operators.match_op, _check_literal( expr, operators.match_op,", "BindParameter) and \\ other.type._isnull: other = other._clone() other.type = expr.type", "_boolean_compare( expr, op, seq_or_selectable, negate=negate_op) else: raise exc.InvalidRequestError( 'in_() accepts'", "**kw) def _unsupported_impl(expr, op, *arg, **kw): raise NotImplementedError(\"Operator '%s' is", "\"lt\": (_boolean_compare, operators.ge), \"le\": (_boolean_compare, operators.gt), \"ne\": (_boolean_compare, operators.eq), \"gt\":", "(_in_impl, operators.in_op), \"is_\": (_boolean_compare, operators.is_), \"isnot\": (_boolean_compare, operators.isnot), \"collate\": (_collate_impl,),", "an \"expanding\" bound parameter: %r' % seq_or_selectable) # Handle non", "or \"1/0\" if those # constants aren't supported and works", "expressions, ' 'a selectable, or an \"expanding\" bound parameter: %r'", "def _scalar(expr, op, fn, **kw): return fn(expr) def _in_impl(expr, op,", "raise NotImplementedError() def _scalar(expr, op, fn, **kw): return fn(expr) def", "an \"expanding\" bound parameter: %r' % o) elif o is", "op.return_type: result_type = op.return_type elif op.is_comparison: result_type = type_api.BOOLEANTYPE return", "in seq_or_selectable: if not _is_literal(o): if not isinstance(o, operators.ColumnOperators): raise", "(_boolean_compare, operators.ne), \"is_distinct_from\": (_boolean_compare, operators.isnot_distinct_from), \"isnot_distinct_from\": (_boolean_compare, operators.is_distinct_from), \"like_op\": (_boolean_compare,", "y, z from table), we would need a multi-column version", "result_type is None: result_type = type_api.BOOLEANTYPE if isinstance(obj, _python_is_types +", "negate=negate, modifiers=kwargs) def _custom_op_operate(expr, op, obj, reverse=False, result_type=None, **kw): if", "z from table), we would need a multi-column version of", "modifiers=kw) def _collate_impl(expr, op, other, **kw): return collate(expr, other) #", "(SelectBase, Alias)): return other.as_scalar() elif not isinstance(other, Visitable): return expr._bind_param(operator,", "to produce a multi- column selectable that # does not", "bound parameter: %r' % seq_or_selectable) # Handle non selectable arguments", "_neg_impl(expr, op, **kw): \"\"\"See :meth:`.ColumnOperators.__neg__`.\"\"\" return UnaryExpression(expr, operator=operators.neg, type_=expr.type) def", "op, type_=result_type, modifiers=kw) def _conjunction_operate(expr, op, other, **kw): if op", "def _neg_impl(expr, op, **kw): \"\"\"See :meth:`.ColumnOperators.__neg__`.\"\"\" return UnaryExpression(expr, operator=operators.neg, type_=expr.type)", "cright), operator=operators.and_, group=False, group_contents=False), op, negate=operators.notbetween_op if op is operators.between_op", "(Selectable, TextClause)): return _boolean_compare(expr, op, seq_or_selectable, negate=negate_op, **kw) elif isinstance(seq_or_selectable,", "def _between_impl(expr, op, cleft, cright, **kw): \"\"\"See :meth:`.ColumnOperators.between`.\"\"\" return BinaryExpression(", "Slice, Visitable, _literal_as_binds, CollectionAggregate from .selectable import SelectBase, Alias, Selectable,", "(x, y, z) IN (select x, # y, z from", "(select x, # y, z from table), we would need", "(Null, True_, False_)): # allow x ==/!= True/False to be", "and works on all platforms if op in (operators.eq, operators.ne)", "result_type=type_api.MATCHTYPE, negate=operators.notmatch_op if op is operators.match_op else operators.match_op, **kw )", "_custom_op_operate(expr, op, obj, reverse=False, result_type=None, **kw): if result_type is None:", "op, seq_or_selectable, negate=negate_op) elif isinstance(seq_or_selectable, SelectBase): # TODO: if we", "' 'a selectable, or an \"expanding\" bound parameter: %r' %", "return collate(expr, other) # a mapping of operators with the", "\"or_\": (_conjunction_operate,), \"inv\": (_inv_impl,), \"add\": (_binary_operate,), \"mul\": (_binary_operate,), \"sub\": (_binary_operate,),", "operators.le), \"ge\": (_boolean_compare, operators.lt), \"eq\": (_boolean_compare, operators.ne), \"is_distinct_from\": (_boolean_compare, operators.isnot_distinct_from),", "a FROM clause return _boolean_compare( expr, op, seq_or_selectable.as_scalar(), negate=negate_op, **kw)", "comes out to \"== / != true/false\" or \"1/0\" if", "type_api.TypeEngine.Comparator): other = other.expr if isinstance(other, (SelectBase, Alias)): return other.as_scalar()", "elif hasattr(other, '__clause_element__'): other = other.__clause_element__() elif isinstance(other, type_api.TypeEngine.Comparator): other", "\"== / != true/false\" or \"1/0\" if those # constants", "op, obj) if reverse: return BinaryExpression(obj, expr, op, type_=result_type, negate=negate,", "from . import type_api from . import operators from .elements", "and_, or_, \\ Slice, Visitable, _literal_as_binds, CollectionAggregate from .selectable import", "allow x ==/!= True/False to be treated as a literal.", "negate=negate, modifiers=kwargs) else: # all other None/True/False uses IS, IS", "we would need a multi-column version of # as_scalar() to", "isinstance(expr.type, type_api.INDEXABLE): other = _check_literal(expr, op, other) return _binary_operate(expr, op,", "**kw): if isinstance(expr.type, type_api.INDEXABLE): other = _check_literal(expr, op, other) return", "operators.match_op else operators.match_op, **kw ) def _distinct_impl(expr, op, **kw): \"\"\"See", "(_boolean_compare, operators.notendswith_op), \"desc_op\": (_scalar, UnaryExpression._create_desc), \"asc_op\": (_scalar, UnaryExpression._create_asc), \"nullsfirst_op\": (_scalar,", "reverse=False, _python_is_types=(util.NoneType, bool), result_type = None, **kwargs): if result_type is", "negate_op, **kw): seq_or_selectable = _clause_element_as_expr(seq_or_selectable) if isinstance(seq_or_selectable, ScalarSelect): return _boolean_compare(expr,", "} def _check_literal(expr, operator, other, bindparam_type=None): if isinstance(other, (ColumnElement, TextClause)):", "= other.expr if isinstance(other, (SelectBase, Alias)): return other.as_scalar() elif not", "sequences args = [] for o in seq_or_selectable: if not", "def _check_literal(expr, operator, other, bindparam_type=None): if isinstance(other, (ColumnElement, TextClause)): if", "op, obj, reverse=reverse, result_type=result_type, **kw) def _binary_operate(expr, op, obj, reverse=False,", "modifiers=kwargs) elif op in (operators.is_distinct_from, operators.isnot_distinct_from): return BinaryExpression(expr, _literal_as_text(obj), op,", "operator=operators.and_, group=False, group_contents=False), op, negate=operators.notbetween_op if op is operators.between_op else", "_literal_as_text(obj), op, type_=result_type, negate=negate, modifiers=kwargs) else: # all other None/True/False", "import SelectBase, Alias, Selectable, ScalarSelect def _boolean_compare(expr, op, obj, negate=None,", "**kw): return collate(expr, other) # a mapping of operators with", "args = [] for o in seq_or_selectable: if not _is_literal(o):", "**kw): if result_type is None: if op.return_type: result_type = op.return_type", "else: left, right = expr, obj if result_type is None:", "those # constants aren't supported and works on all platforms", "op, seq_or_selectable, negate=negate_op) else: raise exc.InvalidRequestError( 'in_() accepts' ' either", "\"all_op\": (_scalar, CollectionAggregate._create_all), \"lt\": (_boolean_compare, operators.ge), \"le\": (_boolean_compare, operators.gt), \"ne\":", "right = obj, expr else: left, right = expr, obj", "seq_or_selectable.expanding: return _boolean_compare( expr, op, seq_or_selectable, negate=negate_op) else: raise exc.InvalidRequestError(", "operator for comparison operators operator_lookup = { \"and_\": (_conjunction_operate,), \"or_\":", "on all platforms if op in (operators.eq, operators.ne) and \\", "True/False to be treated as a literal. # this comes", "if reverse: left, right = obj, expr else: left, right", "obj, expr else: left, right = expr, obj if result_type", "(_conjunction_operate,), \"or_\": (_conjunction_operate,), \"inv\": (_inv_impl,), \"add\": (_binary_operate,), \"mul\": (_binary_operate,), \"sub\":", "==/!= True/False to be treated as a literal. # this", "from . import operators from .elements import BindParameter, True_, False_,", "# their negated operator for comparison operators operator_lookup = {", "(_binary_operate, ), \"json_getitem_op\": (_binary_operate, ), \"concat_op\": (_binary_operate,), \"any_op\": (_scalar, CollectionAggregate._create_any),", "return _boolean_compare( expr, op, seq_or_selectable.as_scalar(), negate=negate_op, **kw) elif isinstance(seq_or_selectable, (Selectable,", "_literal_as_text(obj), op, type_=result_type, negate=negate, modifiers=kwargs) elif op in (operators.is_distinct_from, operators.isnot_distinct_from):", "operators.match_op, other), result_type=type_api.MATCHTYPE, negate=operators.notmatch_op if op is operators.match_op else operators.match_op,", "def _binary_operate(expr, op, obj, reverse=False, result_type=None, **kw): obj = _check_literal(expr,", "want to support (x, y, z) IN (select x, #", "literal. # this comes out to \"== / != true/false\"", "(_getitem_impl,), \"lshift\": (_unsupported_impl,), \"rshift\": (_unsupported_impl,), \"contains\": (_unsupported_impl,), } def _check_literal(expr,", "(_boolean_compare, operators.lt), \"eq\": (_boolean_compare, operators.ne), \"is_distinct_from\": (_boolean_compare, operators.isnot_distinct_from), \"isnot_distinct_from\": (_boolean_compare,", "other, bindparam_type=None): if isinstance(other, (ColumnElement, TextClause)): if isinstance(other, BindParameter) and", "type_api from . import operators from .elements import BindParameter, True_,", "return BinaryExpression(obj, expr, op, type_=result_type, negate=negate, modifiers=kwargs) else: return BinaryExpression(expr,", "\"operators can be used with None/True/False\") else: obj = _check_literal(expr,", "elif isinstance(seq_or_selectable, (Selectable, TextClause)): return _boolean_compare(expr, op, seq_or_selectable, negate=negate_op, **kw)", "_clause_element_as_expr(seq_or_selectable) if isinstance(seq_or_selectable, ScalarSelect): return _boolean_compare(expr, op, seq_or_selectable, negate=negate_op) elif", "SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php", "(_boolean_compare, operators.ilike_op), \"contains_op\": (_boolean_compare, operators.notcontains_op), \"startswith_op\": (_boolean_compare, operators.notstartswith_op), \"endswith_op\": (_boolean_compare,", "= type_api.BOOLEANTYPE return _binary_operate( expr, op, obj, reverse=reverse, result_type=result_type, **kw)", "type_=result_type, negate=negate, modifiers=kwargs) else: # all other None/True/False uses IS,", "operators.is_distinct_from), \"like_op\": (_boolean_compare, operators.notlike_op), \"ilike_op\": (_boolean_compare, operators.notilike_op), \"notlike_op\": (_boolean_compare, operators.like_op),", "is part of SQLAlchemy and is released under # the", "on \" \"this expression\" % op.__name__) def _inv_impl(expr, op, **kw):", "a list of expressions, ' 'a selectable, or an \"expanding\"", ".elements import BindParameter, True_, False_, BinaryExpression, \\ Null, _const_expr, _clause_element_as_expr,", "\"getitem\": (_getitem_impl,), \"lshift\": (_unsupported_impl,), \"rshift\": (_unsupported_impl,), \"contains\": (_unsupported_impl,), } def", "this comes out to \"== / != true/false\" or \"1/0\"", "part of SQLAlchemy and is released under # the MIT", "method they use, along with # their negated operator for", "a literal. # this comes out to \"== / !=", "\"isnot_distinct_from\": (_boolean_compare, operators.is_distinct_from), \"like_op\": (_boolean_compare, operators.notlike_op), \"ilike_op\": (_boolean_compare, operators.notilike_op), \"notlike_op\":", "operators.ge), \"le\": (_boolean_compare, operators.gt), \"ne\": (_boolean_compare, operators.eq), \"gt\": (_boolean_compare, operators.le),", "elif op in (operators.is_distinct_from, operators.isnot_distinct_from): return BinaryExpression(expr, _literal_as_text(obj), op, type_=result_type,", "\"like_op\": (_boolean_compare, operators.notlike_op), \"ilike_op\": (_boolean_compare, operators.notilike_op), \"notlike_op\": (_boolean_compare, operators.like_op), \"notilike_op\":", "\"gt\": (_boolean_compare, operators.le), \"ge\": (_boolean_compare, operators.lt), \"eq\": (_boolean_compare, operators.ne), \"is_distinct_from\":", "operators.notin_op), \"notin_op\": (_in_impl, operators.in_op), \"is_\": (_boolean_compare, operators.is_), \"isnot\": (_boolean_compare, operators.isnot),", "\"1/0\" if those # constants aren't supported and works on", "% seq_or_selectable) # Handle non selectable arguments as sequences args", "(_boolean_compare, operators.eq), \"gt\": (_boolean_compare, operators.le), \"ge\": (_boolean_compare, operators.lt), \"eq\": (_boolean_compare,", "elif o is None: o = Null() else: o =", "ClauseElement, and_, or_, \\ Slice, Visitable, _literal_as_binds, CollectionAggregate from .selectable", "BinaryExpression(expr, _literal_as_text(obj), op, type_=result_type, negate=negate, modifiers=kwargs) else: # all other", "of SQL comparison operations. \"\"\" from .. import exc, util", "aren't supported and works on all platforms if op in", "# # This module is part of SQLAlchemy and is", "(_scalar, UnaryExpression._create_asc), \"nullsfirst_op\": (_scalar, UnaryExpression._create_nullsfirst), \"nullslast_op\": (_scalar, UnaryExpression._create_nullslast), \"in_op\": (_in_impl,", "op is operators.in_op \\ else ( operators.empty_notin_op, operators.empty_in_op) return _boolean_compare(expr,", "**kw): if op is operators.and_: return and_(expr, other) elif op", "operators.isnot), \"collate\": (_collate_impl,), \"match_op\": (_match_impl,), \"notmatch_op\": (_match_impl,), \"distinct_op\": (_distinct_impl,), \"between_op\":", "constants aren't supported and works on all platforms if op", "return or_(expr, other) else: raise NotImplementedError() def _scalar(expr, op, fn,", "other None/True/False uses IS, IS NOT if op in (operators.eq,", "\"truediv\": (_binary_operate,), \"custom_op\": (_custom_op_operate,), \"json_path_getitem_op\": (_binary_operate, ), \"json_getitem_op\": (_binary_operate, ),", "exc, util from . import type_api from . import operators", "if op in (operators.eq, operators.ne) and \\ isinstance(obj, (bool, True_,", "\"startswith_op\": (_boolean_compare, operators.notstartswith_op), \"endswith_op\": (_boolean_compare, operators.notendswith_op), \"desc_op\": (_scalar, UnaryExpression._create_desc), \"asc_op\":", "if op is operators.match_op else operators.match_op, **kw ) def _distinct_impl(expr,", "obj = _check_literal(expr, op, obj) if reverse: return BinaryExpression(obj, expr,", "type_api.BOOLEANTYPE return _binary_operate( expr, op, obj, reverse=reverse, result_type=result_type, **kw) def", "return _boolean_compare(expr, op, seq_or_selectable, negate=negate_op) elif isinstance(seq_or_selectable, SelectBase): # TODO:", "return other.as_scalar() elif not isinstance(other, Visitable): return expr._bind_param(operator, other, type_=bindparam_type)", "), \"json_getitem_op\": (_binary_operate, ), \"concat_op\": (_binary_operate,), \"any_op\": (_scalar, CollectionAggregate._create_any), \"all_op\":", "\"rshift\": (_unsupported_impl,), \"contains\": (_unsupported_impl,), } def _check_literal(expr, operator, other, bindparam_type=None):", "module is part of SQLAlchemy and is released under #", "_boolean_compare( expr, op, seq_or_selectable.as_scalar(), negate=negate_op, **kw) elif isinstance(seq_or_selectable, (Selectable, TextClause)):", "used with None/True/False\") else: obj = _check_literal(expr, op, obj) if", "# sql/default_comparator.py # Copyright (C) 2005-2018 the SQLAlchemy authors and", "to be treated as a literal. # this comes out", "else: raise NotImplementedError() def _scalar(expr, op, fn, **kw): return fn(expr)", "Alias, Selectable, ScalarSelect def _boolean_compare(expr, op, obj, negate=None, reverse=False, _python_is_types=(util.NoneType,", "parameter: %r' % seq_or_selectable) # Handle non selectable arguments as", "op, other, **kw) def _unsupported_impl(expr, op, *arg, **kw): raise NotImplementedError(\"Operator", "**kw): \"\"\"See :meth:`.ColumnOperators.__inv__`.\"\"\" if hasattr(expr, 'negation_clause'): return expr.negation_clause else: return", "raise NotImplementedError(\"Operator '%s' is not supported on \" \"this expression\"", "result_type = op.return_type elif op.is_comparison: result_type = type_api.BOOLEANTYPE return _binary_operate(", "o is None: o = Null() else: o = expr._bind_param(op,", "bindparam_type=None): if isinstance(other, (ColumnElement, TextClause)): if isinstance(other, BindParameter) and \\", "to \"== / != true/false\" or \"1/0\" if those #", "'__clause_element__'): other = other.__clause_element__() elif isinstance(other, type_api.TypeEngine.Comparator): other = other.expr", "with the method they use, along with # their negated", "_in_impl(expr, op, seq_or_selectable, negate_op, **kw): seq_or_selectable = _clause_element_as_expr(seq_or_selectable) if isinstance(seq_or_selectable,", "else operators.match_op, **kw ) def _distinct_impl(expr, op, **kw): \"\"\"See :meth:`.ColumnOperators.distinct`.\"\"\"", "op, obj) if reverse: left, right = obj, expr else:", "False_)): return BinaryExpression(expr, _literal_as_text(obj), op, type_=result_type, negate=negate, modifiers=kwargs) elif op", "return _boolean_compare(expr, op, ClauseList(*args).self_group(against=op), negate=negate_op) def _getitem_impl(expr, op, other, **kw):", ":meth:`.ColumnOperators.__neg__`.\"\"\" return UnaryExpression(expr, operator=operators.neg, type_=expr.type) def _match_impl(expr, op, other, **kw):", "operators.match_op, _check_literal( expr, operators.match_op, other), result_type=type_api.MATCHTYPE, negate=operators.notmatch_op if op is", "left, right = obj, expr else: left, right = expr,", "is not supported on \" \"this expression\" % op.__name__) def", "the MIT License: http://www.opensource.org/licenses/mit-license.php \"\"\"Default implementation of SQL comparison operations.", "selectable that # does not export itself as a FROM", "all other None/True/False uses IS, IS NOT if op in", "op, seq_or_selectable, negate_op, **kw): seq_or_selectable = _clause_element_as_expr(seq_or_selectable) if isinstance(seq_or_selectable, ScalarSelect):", "other, **kw) else: _unsupported_impl(expr, op, other, **kw) def _unsupported_impl(expr, op,", "other.as_scalar() elif not isinstance(other, Visitable): return expr._bind_param(operator, other, type_=bindparam_type) else:", "False_, BinaryExpression, \\ Null, _const_expr, _clause_element_as_expr, \\ ClauseList, ColumnElement, TextClause,", "(_binary_operate,), \"sub\": (_binary_operate,), \"div\": (_binary_operate,), \"mod\": (_binary_operate,), \"truediv\": (_binary_operate,), \"custom_op\":", "o = expr._bind_param(op, o) args.append(o) if len(args) == 0: op,", "\"custom_op\": (_custom_op_operate,), \"json_path_getitem_op\": (_binary_operate, ), \"json_getitem_op\": (_binary_operate, ), \"concat_op\": (_binary_operate,),", "\"notbetween_op\": (_between_impl, ), \"neg\": (_neg_impl,), \"getitem\": (_getitem_impl,), \"lshift\": (_unsupported_impl,), \"rshift\":", "other = other._clone() other.type = expr.type return other elif hasattr(other,", "either a list of expressions, ' 'a selectable, or an", "seq_or_selectable, negate=negate_op) elif isinstance(seq_or_selectable, SelectBase): # TODO: if we ever", "works on all platforms if op in (operators.eq, operators.ne) and", "op.__name__) def _inv_impl(expr, op, **kw): \"\"\"See :meth:`.ColumnOperators.__inv__`.\"\"\" if hasattr(expr, 'negation_clause'):", "from .. import exc, util from . import type_api from", "= { \"and_\": (_conjunction_operate,), \"or_\": (_conjunction_operate,), \"inv\": (_inv_impl,), \"add\": (_binary_operate,),", "a multi- column selectable that # does not export itself", "does not export itself as a FROM clause return _boolean_compare(", "cright, **kw): \"\"\"See :meth:`.ColumnOperators.between`.\"\"\" return BinaryExpression( expr, ClauseList( _check_literal(expr, operators.and_,", "UnaryExpression._create_desc), \"asc_op\": (_scalar, UnaryExpression._create_asc), \"nullsfirst_op\": (_scalar, UnaryExpression._create_nullsfirst), \"nullslast_op\": (_scalar, UnaryExpression._create_nullslast),", "is None: result_type = type_api.BOOLEANTYPE if isinstance(obj, _python_is_types + (Null,", "[] for o in seq_or_selectable: if not _is_literal(o): if not", "bound parameter: %r' % o) elif o is None: o", "( operators.empty_notin_op, operators.empty_in_op) return _boolean_compare(expr, op, ClauseList(*args).self_group(against=op), negate=negate_op) def _getitem_impl(expr,", "if isinstance(expr.type, type_api.INDEXABLE): other = _check_literal(expr, op, other) return _binary_operate(expr,", "from .selectable import SelectBase, Alias, Selectable, ScalarSelect def _boolean_compare(expr, op,", "= _clause_element_as_expr(seq_or_selectable) if isinstance(seq_or_selectable, ScalarSelect): return _boolean_compare(expr, op, seq_or_selectable, negate=negate_op)", "**kw) elif isinstance(seq_or_selectable, ClauseElement): if isinstance(seq_or_selectable, BindParameter) and \\ seq_or_selectable.expanding:", "_is_literal(o): if not isinstance(o, operators.ColumnOperators): raise exc.InvalidRequestError( 'in_() accepts' '", "BindParameter) and \\ seq_or_selectable.expanding: return _boolean_compare( expr, op, seq_or_selectable, negate=negate_op)", "= expr.type return other elif hasattr(other, '__clause_element__'): other = other.__clause_element__()", "other, **kw) def _unsupported_impl(expr, op, *arg, **kw): raise NotImplementedError(\"Operator '%s'", "(ColumnElement, TextClause)): if isinstance(other, BindParameter) and \\ other.type._isnull: other =", "\"between_op\": (_between_impl, ), \"notbetween_op\": (_between_impl, ), \"neg\": (_neg_impl,), \"getitem\": (_getitem_impl,),", "# Copyright (C) 2005-2018 the SQLAlchemy authors and contributors #", "ScalarSelect def _boolean_compare(expr, op, obj, negate=None, reverse=False, _python_is_types=(util.NoneType, bool), result_type", "selectable, or an \"expanding\" bound parameter: %r' % seq_or_selectable) #", ":meth:`.ColumnOperators.match`.\"\"\" return _boolean_compare( expr, operators.match_op, _check_literal( expr, operators.match_op, other), result_type=type_api.MATCHTYPE,", "return BinaryExpression(expr, obj, op, type_=result_type, negate=negate, modifiers=kwargs) def _custom_op_operate(expr, op,", "operators.ColumnOperators): raise exc.InvalidRequestError( 'in_() accepts' ' either a list of", "\"le\": (_boolean_compare, operators.gt), \"ne\": (_boolean_compare, operators.eq), \"gt\": (_boolean_compare, operators.le), \"ge\":", "ClauseList, ColumnElement, TextClause, UnaryExpression, \\ collate, _is_literal, _literal_as_text, ClauseElement, and_,", "of SQLAlchemy and is released under # the MIT License:", "(_binary_operate,), \"mul\": (_binary_operate,), \"sub\": (_binary_operate,), \"div\": (_binary_operate,), \"mod\": (_binary_operate,), \"truediv\":", "other), result_type=type_api.MATCHTYPE, negate=operators.notmatch_op if op is operators.match_op else operators.match_op, **kw", "op, other, **kw) else: _unsupported_impl(expr, op, other, **kw) def _unsupported_impl(expr,", "\"is_\": (_boolean_compare, operators.is_), \"isnot\": (_boolean_compare, operators.isnot), \"collate\": (_collate_impl,), \"match_op\": (_match_impl,),", "_unsupported_impl(expr, op, other, **kw) def _unsupported_impl(expr, op, *arg, **kw): raise", "authors and contributors # <see AUTHORS file> # # This", "_scalar(expr, op, fn, **kw): return fn(expr) def _in_impl(expr, op, seq_or_selectable,", "'negation_clause'): return expr.negation_clause else: return expr._negate() def _neg_impl(expr, op, **kw):", "other.__clause_element__() elif isinstance(other, type_api.TypeEngine.Comparator): other = other.expr if isinstance(other, (SelectBase,", "expr, op, seq_or_selectable.as_scalar(), negate=negate_op, **kw) elif isinstance(seq_or_selectable, (Selectable, TextClause)): return", "SQLAlchemy authors and contributors # <see AUTHORS file> # #", "not export itself as a FROM clause return _boolean_compare( expr,", "\" \"'is_distinct_from()', 'isnot_distinct_from()' \" \"operators can be used with None/True/False\")", "_boolean_compare(expr, op, ClauseList(*args).self_group(against=op), negate=negate_op) def _getitem_impl(expr, op, other, **kw): if", "'isnot_distinct_from()' \" \"operators can be used with None/True/False\") else: obj", "SQL comparison operations. \"\"\" from .. import exc, util from", "op, obj, reverse=False, result_type=None, **kw): obj = _check_literal(expr, op, obj)", "they use, along with # their negated operator for comparison", "mapping of operators with the method they use, along with", "TextClause)): if isinstance(other, BindParameter) and \\ other.type._isnull: other = other._clone()", "_between_impl(expr, op, cleft, cright, **kw): \"\"\"See :meth:`.ColumnOperators.between`.\"\"\" return BinaryExpression( expr,", "sql/default_comparator.py # Copyright (C) 2005-2018 the SQLAlchemy authors and contributors", "Copyright (C) 2005-2018 the SQLAlchemy authors and contributors # <see", "FROM clause return _boolean_compare( expr, op, seq_or_selectable.as_scalar(), negate=negate_op, **kw) elif", "*arg, **kw): raise NotImplementedError(\"Operator '%s' is not supported on \"", ":meth:`.ColumnOperators.distinct`.\"\"\" return UnaryExpression(expr, operator=operators.distinct_op, type_=expr.type) def _between_impl(expr, op, cleft, cright,", "reverse=False, result_type=None, **kw): if result_type is None: if op.return_type: result_type", "op.is_comparison: result_type = type_api.BOOLEANTYPE return _binary_operate( expr, op, obj, reverse=reverse,", "obj) if reverse: return BinaryExpression(obj, expr, op, type_=result_type, negate=negate, modifiers=kwargs)", "\"eq\": (_boolean_compare, operators.ne), \"is_distinct_from\": (_boolean_compare, operators.isnot_distinct_from), \"isnot_distinct_from\": (_boolean_compare, operators.is_distinct_from), \"like_op\":", ".. import exc, util from . import type_api from .", "type_=expr.type) def _match_impl(expr, op, other, **kw): \"\"\"See :meth:`.ColumnOperators.match`.\"\"\" return _boolean_compare(", "= other._clone() other.type = expr.type return other elif hasattr(other, '__clause_element__'):", "elif not isinstance(other, Visitable): return expr._bind_param(operator, other, type_=bindparam_type) else: return", "_getitem_impl(expr, op, other, **kw): if isinstance(expr.type, type_api.INDEXABLE): other = _check_literal(expr,", "None: result_type = type_api.BOOLEANTYPE if isinstance(obj, _python_is_types + (Null, True_,", "other = _check_literal(expr, op, other) return _binary_operate(expr, op, other, **kw)", "isinstance(obj, (bool, True_, False_)): return BinaryExpression(expr, _literal_as_text(obj), op, type_=result_type, negate=negate,", "op in (operators.is_distinct_from, operators.isnot_distinct_from): return BinaryExpression(expr, _literal_as_text(obj), op, type_=result_type, negate=negate,", "as_scalar() to produce a multi- column selectable that # does", "as sequences args = [] for o in seq_or_selectable: if", "(_scalar, UnaryExpression._create_desc), \"asc_op\": (_scalar, UnaryExpression._create_asc), \"nullsfirst_op\": (_scalar, UnaryExpression._create_nullsfirst), \"nullslast_op\": (_scalar,", "%r' % seq_or_selectable) # Handle non selectable arguments as sequences", "seq_or_selectable, negate=negate_op, **kw) elif isinstance(seq_or_selectable, ClauseElement): if isinstance(seq_or_selectable, BindParameter) and", "along with # their negated operator for comparison operators operator_lookup", "License: http://www.opensource.org/licenses/mit-license.php \"\"\"Default implementation of SQL comparison operations. \"\"\" from", "args.append(o) if len(args) == 0: op, negate_op = ( operators.empty_in_op,", "operators.empty_notin_op, operators.empty_in_op) return _boolean_compare(expr, op, ClauseList(*args).self_group(against=op), negate=negate_op) def _getitem_impl(expr, op,", "operators.notcontains_op), \"startswith_op\": (_boolean_compare, operators.notstartswith_op), \"endswith_op\": (_boolean_compare, operators.notendswith_op), \"desc_op\": (_scalar, UnaryExpression._create_desc),", "return _boolean_compare(expr, op, seq_or_selectable, negate=negate_op, **kw) elif isinstance(seq_or_selectable, ClauseElement): if", "reverse: left, right = obj, expr else: left, right =", "uses IS, IS NOT if op in (operators.eq, operators.is_): return", "seq_or_selectable = _clause_element_as_expr(seq_or_selectable) if isinstance(seq_or_selectable, ScalarSelect): return _boolean_compare(expr, op, seq_or_selectable,", "**kw): \"\"\"See :meth:`.ColumnOperators.between`.\"\"\" return BinaryExpression( expr, ClauseList( _check_literal(expr, operators.and_, cleft),", "\\ else ( operators.empty_notin_op, operators.empty_in_op) return _boolean_compare(expr, op, ClauseList(*args).self_group(against=op), negate=negate_op)", "op, seq_or_selectable, negate=negate_op, **kw) elif isinstance(seq_or_selectable, ClauseElement): if isinstance(seq_or_selectable, BindParameter)", "# the MIT License: http://www.opensource.org/licenses/mit-license.php \"\"\"Default implementation of SQL comparison", ". import type_api from . import operators from .elements import", "# allow x ==/!= True/False to be treated as a", "if op in (operators.eq, operators.is_): return BinaryExpression(expr, _const_expr(obj), operators.is_, negate=operators.isnot,", "parameter: %r' % o) elif o is None: o =", "CollectionAggregate from .selectable import SelectBase, Alias, Selectable, ScalarSelect def _boolean_compare(expr,", "operators.in_op), \"is_\": (_boolean_compare, operators.is_), \"isnot\": (_boolean_compare, operators.isnot), \"collate\": (_collate_impl,), \"match_op\":", "), \"neg\": (_neg_impl,), \"getitem\": (_getitem_impl,), \"lshift\": (_unsupported_impl,), \"rshift\": (_unsupported_impl,), \"contains\":", "\"concat_op\": (_binary_operate,), \"any_op\": (_scalar, CollectionAggregate._create_any), \"all_op\": (_scalar, CollectionAggregate._create_all), \"lt\": (_boolean_compare,", "False_)): # allow x ==/!= True/False to be treated as", ":meth:`.ColumnOperators.__inv__`.\"\"\" if hasattr(expr, 'negation_clause'): return expr.negation_clause else: return expr._negate() def", "\"\"\"See :meth:`.ColumnOperators.match`.\"\"\" return _boolean_compare( expr, operators.match_op, _check_literal( expr, operators.match_op, other),", "(_binary_operate,), \"mod\": (_binary_operate,), \"truediv\": (_binary_operate,), \"custom_op\": (_custom_op_operate,), \"json_path_getitem_op\": (_binary_operate, ),", "export itself as a FROM clause return _boolean_compare( expr, op,", "o) args.append(o) if len(args) == 0: op, negate_op = (", "result_type = type_api.BOOLEANTYPE return _binary_operate( expr, op, obj, reverse=reverse, result_type=result_type,", "CollectionAggregate._create_all), \"lt\": (_boolean_compare, operators.ge), \"le\": (_boolean_compare, operators.gt), \"ne\": (_boolean_compare, operators.eq),", "\"'is_distinct_from()', 'isnot_distinct_from()' \" \"operators can be used with None/True/False\") else:", "other, **kw): \"\"\"See :meth:`.ColumnOperators.match`.\"\"\" return _boolean_compare( expr, operators.match_op, _check_literal( expr,", "multi-column version of # as_scalar() to produce a multi- column", "_const_expr, _clause_element_as_expr, \\ ClauseList, ColumnElement, TextClause, UnaryExpression, \\ collate, _is_literal,", "op, type_=result_type, negate=negate, modifiers=kwargs) else: # all other None/True/False uses", "a multi-column version of # as_scalar() to produce a multi-", "operators.notstartswith_op), \"endswith_op\": (_boolean_compare, operators.notendswith_op), \"desc_op\": (_scalar, UnaryExpression._create_desc), \"asc_op\": (_scalar, UnaryExpression._create_asc),", "x ==/!= True/False to be treated as a literal. #", "seq_or_selectable) # Handle non selectable arguments as sequences args =", "isinstance(seq_or_selectable, ClauseElement): if isinstance(seq_or_selectable, BindParameter) and \\ seq_or_selectable.expanding: return _boolean_compare(", "as a literal. # this comes out to \"== /", "of expressions, ' 'a selectable, or an \"expanding\" bound parameter:", "if hasattr(expr, 'negation_clause'): return expr.negation_clause else: return expr._negate() def _neg_impl(expr,", "UnaryExpression, \\ collate, _is_literal, _literal_as_text, ClauseElement, and_, or_, \\ Slice,", "negate=negate, modifiers=kwargs) elif op in (operators.is_distinct_from, operators.isnot_distinct_from): return BinaryExpression(expr, _literal_as_text(obj),", "operators.notlike_op), \"ilike_op\": (_boolean_compare, operators.notilike_op), \"notlike_op\": (_boolean_compare, operators.like_op), \"notilike_op\": (_boolean_compare, operators.ilike_op),", "from table), we would need a multi-column version of #", "return BinaryExpression(expr, _literal_as_text(obj), op, type_=result_type, negate=negate, modifiers=kwargs) elif op in", "negated operator for comparison operators operator_lookup = { \"and_\": (_conjunction_operate,),", "selectable arguments as sequences args = [] for o in", "for o in seq_or_selectable: if not _is_literal(o): if not isinstance(o,", "(_scalar, UnaryExpression._create_nullslast), \"in_op\": (_in_impl, operators.notin_op), \"notin_op\": (_in_impl, operators.in_op), \"is_\": (_boolean_compare,", "type_=result_type ) elif op in (operators.ne, operators.isnot): return BinaryExpression(expr, _const_expr(obj),", "expr, ClauseList( _check_literal(expr, operators.and_, cleft), _check_literal(expr, operators.and_, cright), operator=operators.and_, group=False,", "other) else: raise NotImplementedError() def _scalar(expr, op, fn, **kw): return", "**kw) elif isinstance(seq_or_selectable, (Selectable, TextClause)): return _boolean_compare(expr, op, seq_or_selectable, negate=negate_op,", "and \\ isinstance(obj, (bool, True_, False_)): return BinaryExpression(expr, _literal_as_text(obj), op,", "_literal_as_text, ClauseElement, and_, or_, \\ Slice, Visitable, _literal_as_binds, CollectionAggregate from", "None/True/False uses IS, IS NOT if op in (operators.eq, operators.is_):", "(_match_impl,), \"notmatch_op\": (_match_impl,), \"distinct_op\": (_distinct_impl,), \"between_op\": (_between_impl, ), \"notbetween_op\": (_between_impl,", "expr, operators.match_op, _check_literal( expr, operators.match_op, other), result_type=type_api.MATCHTYPE, negate=operators.notmatch_op if op", "\"\"\"See :meth:`.ColumnOperators.__inv__`.\"\"\" if hasattr(expr, 'negation_clause'): return expr.negation_clause else: return expr._negate()", "result_type = type_api.BOOLEANTYPE if isinstance(obj, _python_is_types + (Null, True_, False_)):", "= left.comparator._adapt_expression( op, right.comparator) return BinaryExpression( left, right, op, type_=result_type,", "_boolean_compare(expr, op, seq_or_selectable, negate=negate_op, **kw) elif isinstance(seq_or_selectable, ClauseElement): if isinstance(seq_or_selectable,", "itself as a FROM clause return _boolean_compare( expr, op, seq_or_selectable.as_scalar(),", "op, negate_op = ( operators.empty_in_op, operators.empty_notin_op) if op is operators.in_op", "util from . import type_api from . import operators from", "\"contains_op\": (_boolean_compare, operators.notcontains_op), \"startswith_op\": (_boolean_compare, operators.notstartswith_op), \"endswith_op\": (_boolean_compare, operators.notendswith_op), \"desc_op\":", "if not _is_literal(o): if not isinstance(o, operators.ColumnOperators): raise exc.InvalidRequestError( 'in_()", "\"is_distinct_from\": (_boolean_compare, operators.isnot_distinct_from), \"isnot_distinct_from\": (_boolean_compare, operators.is_distinct_from), \"like_op\": (_boolean_compare, operators.notlike_op), \"ilike_op\":", "result_type=None, **kw): if result_type is None: if op.return_type: result_type =", "negate=negate_op) elif isinstance(seq_or_selectable, SelectBase): # TODO: if we ever want", "SelectBase): # TODO: if we ever want to support (x,", "**kwargs): if result_type is None: result_type = type_api.BOOLEANTYPE if isinstance(obj,", "the method they use, along with # their negated operator", "return _boolean_compare( expr, operators.match_op, _check_literal( expr, operators.match_op, other), result_type=type_api.MATCHTYPE, negate=operators.notmatch_op", "is operators.between_op else operators.between_op, modifiers=kw) def _collate_impl(expr, op, other, **kw):", "type_=result_type, negate=negate, modifiers=kwargs) elif op in (operators.is_distinct_from, operators.isnot_distinct_from): return BinaryExpression(expr,", "out to \"== / != true/false\" or \"1/0\" if those", "is operators.in_op \\ else ( operators.empty_notin_op, operators.empty_in_op) return _boolean_compare(expr, op,", "expr, operators.match_op, other), result_type=type_api.MATCHTYPE, negate=operators.notmatch_op if op is operators.match_op else", "True_, False_, BinaryExpression, \\ Null, _const_expr, _clause_element_as_expr, \\ ClauseList, ColumnElement,", "'=', '!=', 'is_()', 'isnot()', \" \"'is_distinct_from()', 'isnot_distinct_from()' \" \"operators can", "operators.between_op, modifiers=kw) def _collate_impl(expr, op, other, **kw): return collate(expr, other)", "column selectable that # does not export itself as a", "Handle non selectable arguments as sequences args = [] for", "other) # a mapping of operators with the method they", "if reverse: return BinaryExpression(obj, expr, op, type_=result_type, negate=negate, modifiers=kwargs) else:", "negate=operators.notbetween_op if op is operators.between_op else operators.between_op, modifiers=kw) def _collate_impl(expr,", "_boolean_compare(expr, op, seq_or_selectable, negate=negate_op) elif isinstance(seq_or_selectable, SelectBase): # TODO: if", "if result_type is None: op, result_type = left.comparator._adapt_expression( op, right.comparator)", "released under # the MIT License: http://www.opensource.org/licenses/mit-license.php \"\"\"Default implementation of", "<reponame>mzazakeith/flask-blog # sql/default_comparator.py # Copyright (C) 2005-2018 the SQLAlchemy authors", "else: obj = _check_literal(expr, op, obj) if reverse: return BinaryExpression(obj,", "# a mapping of operators with the method they use,", "\"isnot\": (_boolean_compare, operators.isnot), \"collate\": (_collate_impl,), \"match_op\": (_match_impl,), \"notmatch_op\": (_match_impl,), \"distinct_op\":", "op, type_=result_type, negate=negate, modifiers=kwargs) elif op in (operators.is_distinct_from, operators.isnot_distinct_from): return", "type_=result_type, negate=negate, modifiers=kwargs) else: return BinaryExpression(expr, obj, op, type_=result_type, negate=negate,", "\"notmatch_op\": (_match_impl,), \"distinct_op\": (_distinct_impl,), \"between_op\": (_between_impl, ), \"notbetween_op\": (_between_impl, ),", "other) elif op is operators.or_: return or_(expr, other) else: raise", "\"notlike_op\": (_boolean_compare, operators.like_op), \"notilike_op\": (_boolean_compare, operators.ilike_op), \"contains_op\": (_boolean_compare, operators.notcontains_op), \"startswith_op\":", "op, other, **kw): return collate(expr, other) # a mapping of", "negate=negate_op, **kw) elif isinstance(seq_or_selectable, (Selectable, TextClause)): return _boolean_compare(expr, op, seq_or_selectable,", "is operators.or_: return or_(expr, other) else: raise NotImplementedError() def _scalar(expr,", "(_unsupported_impl,), } def _check_literal(expr, operator, other, bindparam_type=None): if isinstance(other, (ColumnElement,", "seq_or_selectable.as_scalar(), negate=negate_op, **kw) elif isinstance(seq_or_selectable, (Selectable, TextClause)): return _boolean_compare(expr, op,", "op.return_type elif op.is_comparison: result_type = type_api.BOOLEANTYPE return _binary_operate( expr, op,", "(_scalar, UnaryExpression._create_nullsfirst), \"nullslast_op\": (_scalar, UnaryExpression._create_nullslast), \"in_op\": (_in_impl, operators.notin_op), \"notin_op\": (_in_impl,", "\"ilike_op\": (_boolean_compare, operators.notilike_op), \"notlike_op\": (_boolean_compare, operators.like_op), \"notilike_op\": (_boolean_compare, operators.ilike_op), \"contains_op\":", "op, other, **kw): \"\"\"See :meth:`.ColumnOperators.match`.\"\"\" return _boolean_compare( expr, operators.match_op, _check_literal(", "UnaryExpression(expr, operator=operators.neg, type_=expr.type) def _match_impl(expr, op, other, **kw): \"\"\"See :meth:`.ColumnOperators.match`.\"\"\"", "_conjunction_operate(expr, op, other, **kw): if op is operators.and_: return and_(expr,", "_binary_operate( expr, op, obj, reverse=reverse, result_type=result_type, **kw) def _binary_operate(expr, op,", "(_distinct_impl,), \"between_op\": (_between_impl, ), \"notbetween_op\": (_between_impl, ), \"neg\": (_neg_impl,), \"getitem\":", "under # the MIT License: http://www.opensource.org/licenses/mit-license.php \"\"\"Default implementation of SQL", "and \\ other.type._isnull: other = other._clone() other.type = expr.type return", "negate=operators.isnot, type_=result_type ) elif op in (operators.ne, operators.isnot): return BinaryExpression(expr,", "**kw): \"\"\"See :meth:`.ColumnOperators.distinct`.\"\"\" return UnaryExpression(expr, operator=operators.distinct_op, type_=expr.type) def _between_impl(expr, op,", "return BinaryExpression( expr, ClauseList( _check_literal(expr, operators.and_, cleft), _check_literal(expr, operators.and_, cright),", "operators.gt), \"ne\": (_boolean_compare, operators.eq), \"gt\": (_boolean_compare, operators.le), \"ge\": (_boolean_compare, operators.lt),", "if isinstance(other, (ColumnElement, TextClause)): if isinstance(other, BindParameter) and \\ other.type._isnull:", "import exc, util from . import type_api from . import", "operators.isnot_distinct_from): return BinaryExpression(expr, _literal_as_text(obj), op, type_=result_type, negate=negate, modifiers=kwargs) else: #", "as a FROM clause return _boolean_compare( expr, op, seq_or_selectable.as_scalar(), negate=negate_op,", "= type_api.BOOLEANTYPE if isinstance(obj, _python_is_types + (Null, True_, False_)): #", "operators.isnot): return BinaryExpression(expr, _const_expr(obj), operators.isnot, negate=operators.is_, type_=result_type ) else: raise", "result_type is None: if op.return_type: result_type = op.return_type elif op.is_comparison:", "type_api.INDEXABLE): other = _check_literal(expr, op, other) return _binary_operate(expr, op, other,", "**kw) def _binary_operate(expr, op, obj, reverse=False, result_type=None, **kw): obj =", "can be used with None/True/False\") else: obj = _check_literal(expr, op,", "x, # y, z from table), we would need a", "+ (Null, True_, False_)): # allow x ==/!= True/False to", "is operators.and_: return and_(expr, other) elif op is operators.or_: return", "else: # all other None/True/False uses IS, IS NOT if", "right.comparator) return BinaryExpression( left, right, op, type_=result_type, modifiers=kw) def _conjunction_operate(expr,", "seq_or_selectable: if not _is_literal(o): if not isinstance(o, operators.ColumnOperators): raise exc.InvalidRequestError(", "isinstance(other, (SelectBase, Alias)): return other.as_scalar() elif not isinstance(other, Visitable): return", "**kw): return fn(expr) def _in_impl(expr, op, seq_or_selectable, negate_op, **kw): seq_or_selectable", "\\ Slice, Visitable, _literal_as_binds, CollectionAggregate from .selectable import SelectBase, Alias,", ") else: raise exc.ArgumentError( \"Only '=', '!=', 'is_()', 'isnot()', \"", "<see AUTHORS file> # # This module is part of", "# as_scalar() to produce a multi- column selectable that #", "\"div\": (_binary_operate,), \"mod\": (_binary_operate,), \"truediv\": (_binary_operate,), \"custom_op\": (_custom_op_operate,), \"json_path_getitem_op\": (_binary_operate,", "all platforms if op in (operators.eq, operators.ne) and \\ isinstance(obj,", "def _match_impl(expr, op, other, **kw): \"\"\"See :meth:`.ColumnOperators.match`.\"\"\" return _boolean_compare( expr,", "op, other) return _binary_operate(expr, op, other, **kw) else: _unsupported_impl(expr, op,", "(_binary_operate,), \"div\": (_binary_operate,), \"mod\": (_binary_operate,), \"truediv\": (_binary_operate,), \"custom_op\": (_custom_op_operate,), \"json_path_getitem_op\":", "if isinstance(other, (SelectBase, Alias)): return other.as_scalar() elif not isinstance(other, Visitable):", "the SQLAlchemy authors and contributors # <see AUTHORS file> #", "# y, z from table), we would need a multi-column", "def _distinct_impl(expr, op, **kw): \"\"\"See :meth:`.ColumnOperators.distinct`.\"\"\" return UnaryExpression(expr, operator=operators.distinct_op, type_=expr.type)", "operators.and_, cright), operator=operators.and_, group=False, group_contents=False), op, negate=operators.notbetween_op if op is", "# this comes out to \"== / != true/false\" or", "_unsupported_impl(expr, op, *arg, **kw): raise NotImplementedError(\"Operator '%s' is not supported", "import operators from .elements import BindParameter, True_, False_, BinaryExpression, \\", "operators from .elements import BindParameter, True_, False_, BinaryExpression, \\ Null,", "type_=result_type, negate=negate, modifiers=kwargs) def _custom_op_operate(expr, op, obj, reverse=False, result_type=None, **kw):", "def _inv_impl(expr, op, **kw): \"\"\"See :meth:`.ColumnOperators.__inv__`.\"\"\" if hasattr(expr, 'negation_clause'): return", "other.expr if isinstance(other, (SelectBase, Alias)): return other.as_scalar() elif not isinstance(other,", "isinstance(seq_or_selectable, ScalarSelect): return _boolean_compare(expr, op, seq_or_selectable, negate=negate_op) elif isinstance(seq_or_selectable, SelectBase):", "_binary_operate(expr, op, other, **kw) else: _unsupported_impl(expr, op, other, **kw) def", "negate=operators.is_, type_=result_type ) else: raise exc.ArgumentError( \"Only '=', '!=', 'is_()',", "TODO: if we ever want to support (x, y, z)", "other = other.expr if isinstance(other, (SelectBase, Alias)): return other.as_scalar() elif", "(operators.eq, operators.ne) and \\ isinstance(obj, (bool, True_, False_)): return BinaryExpression(expr,", "return BinaryExpression(expr, _const_expr(obj), operators.isnot, negate=operators.is_, type_=result_type ) else: raise exc.ArgumentError(", "), \"notbetween_op\": (_between_impl, ), \"neg\": (_neg_impl,), \"getitem\": (_getitem_impl,), \"lshift\": (_unsupported_impl,),", "isinstance(other, BindParameter) and \\ other.type._isnull: other = other._clone() other.type =", "if result_type is None: if op.return_type: result_type = op.return_type elif", "NotImplementedError() def _scalar(expr, op, fn, **kw): return fn(expr) def _in_impl(expr,", "to support (x, y, z) IN (select x, # y,", "if len(args) == 0: op, negate_op = ( operators.empty_in_op, operators.empty_notin_op)", "= other.__clause_element__() elif isinstance(other, type_api.TypeEngine.Comparator): other = other.expr if isinstance(other,", "(operators.eq, operators.is_): return BinaryExpression(expr, _const_expr(obj), operators.is_, negate=operators.isnot, type_=result_type ) elif", "**kw): raise NotImplementedError(\"Operator '%s' is not supported on \" \"this", "== 0: op, negate_op = ( operators.empty_in_op, operators.empty_notin_op) if op", "(_unsupported_impl,), \"rshift\": (_unsupported_impl,), \"contains\": (_unsupported_impl,), } def _check_literal(expr, operator, other,", "not isinstance(other, Visitable): return expr._bind_param(operator, other, type_=bindparam_type) else: return other", "\"collate\": (_collate_impl,), \"match_op\": (_match_impl,), \"notmatch_op\": (_match_impl,), \"distinct_op\": (_distinct_impl,), \"between_op\": (_between_impl,", "contributors # <see AUTHORS file> # # This module is", "from .elements import BindParameter, True_, False_, BinaryExpression, \\ Null, _const_expr,", "obj if result_type is None: op, result_type = left.comparator._adapt_expression( op,", "modifiers=kw) def _conjunction_operate(expr, op, other, **kw): if op is operators.and_:", "http://www.opensource.org/licenses/mit-license.php \"\"\"Default implementation of SQL comparison operations. \"\"\" from ..", "Visitable, _literal_as_binds, CollectionAggregate from .selectable import SelectBase, Alias, Selectable, ScalarSelect", "if isinstance(obj, _python_is_types + (Null, True_, False_)): # allow x", "platforms if op in (operators.eq, operators.ne) and \\ isinstance(obj, (bool,", "None/True/False\") else: obj = _check_literal(expr, op, obj) if reverse: return", "else operators.between_op, modifiers=kw) def _collate_impl(expr, op, other, **kw): return collate(expr,", "\"expanding\" bound parameter: %r' % o) elif o is None:", "is None: if op.return_type: result_type = op.return_type elif op.is_comparison: result_type", "_inv_impl(expr, op, **kw): \"\"\"See :meth:`.ColumnOperators.__inv__`.\"\"\" if hasattr(expr, 'negation_clause'): return expr.negation_clause", "(_boolean_compare, operators.notilike_op), \"notlike_op\": (_boolean_compare, operators.like_op), \"notilike_op\": (_boolean_compare, operators.ilike_op), \"contains_op\": (_boolean_compare,", "Selectable, ScalarSelect def _boolean_compare(expr, op, obj, negate=None, reverse=False, _python_is_types=(util.NoneType, bool),", "comparison operations. \"\"\" from .. import exc, util from .", "expr, op, seq_or_selectable, negate=negate_op) else: raise exc.InvalidRequestError( 'in_() accepts' '", "ClauseElement): if isinstance(seq_or_selectable, BindParameter) and \\ seq_or_selectable.expanding: return _boolean_compare( expr,", "is operators.match_op else operators.match_op, **kw ) def _distinct_impl(expr, op, **kw):", "'isnot()', \" \"'is_distinct_from()', 'isnot_distinct_from()' \" \"operators can be used with", "seq_or_selectable, negate=negate_op) else: raise exc.InvalidRequestError( 'in_() accepts' ' either a", "supported on \" \"this expression\" % op.__name__) def _inv_impl(expr, op,", "BindParameter, True_, False_, BinaryExpression, \\ Null, _const_expr, _clause_element_as_expr, \\ ClauseList,", "selectable, or an \"expanding\" bound parameter: %r' % o) elif", "(_boolean_compare, operators.notlike_op), \"ilike_op\": (_boolean_compare, operators.notilike_op), \"notlike_op\": (_boolean_compare, operators.like_op), \"notilike_op\": (_boolean_compare,", "def _getitem_impl(expr, op, other, **kw): if isinstance(expr.type, type_api.INDEXABLE): other =", "' either a list of expressions, ' 'a selectable, or", "arguments as sequences args = [] for o in seq_or_selectable:", "non selectable arguments as sequences args = [] for o", "elif isinstance(other, type_api.TypeEngine.Comparator): other = other.expr if isinstance(other, (SelectBase, Alias)):", "/ != true/false\" or \"1/0\" if those # constants aren't", "(_conjunction_operate,), \"inv\": (_inv_impl,), \"add\": (_binary_operate,), \"mul\": (_binary_operate,), \"sub\": (_binary_operate,), \"div\":", ":meth:`.ColumnOperators.between`.\"\"\" return BinaryExpression( expr, ClauseList( _check_literal(expr, operators.and_, cleft), _check_literal(expr, operators.and_,", "other) return _binary_operate(expr, op, other, **kw) else: _unsupported_impl(expr, op, other,", "NOT if op in (operators.eq, operators.is_): return BinaryExpression(expr, _const_expr(obj), operators.is_,", "\"contains\": (_unsupported_impl,), } def _check_literal(expr, operator, other, bindparam_type=None): if isinstance(other,", "else: return expr._negate() def _neg_impl(expr, op, **kw): \"\"\"See :meth:`.ColumnOperators.__neg__`.\"\"\" return", "( operators.empty_in_op, operators.empty_notin_op) if op is operators.in_op \\ else (", "seq_or_selectable, negate_op, **kw): seq_or_selectable = _clause_element_as_expr(seq_or_selectable) if isinstance(seq_or_selectable, ScalarSelect): return", "'in_() accepts' ' either a list of expressions, ' 'a", "obj, op, type_=result_type, negate=negate, modifiers=kwargs) def _custom_op_operate(expr, op, obj, reverse=False,", "isinstance(other, type_api.TypeEngine.Comparator): other = other.expr if isinstance(other, (SelectBase, Alias)): return", "negate=negate, modifiers=kwargs) else: return BinaryExpression(expr, obj, op, type_=result_type, negate=negate, modifiers=kwargs)", "if we ever want to support (x, y, z) IN", "(_inv_impl,), \"add\": (_binary_operate,), \"mul\": (_binary_operate,), \"sub\": (_binary_operate,), \"div\": (_binary_operate,), \"mod\":", "if not isinstance(o, operators.ColumnOperators): raise exc.InvalidRequestError( 'in_() accepts' ' either", "BinaryExpression(expr, _const_expr(obj), operators.isnot, negate=operators.is_, type_=result_type ) else: raise exc.ArgumentError( \"Only", "(_between_impl, ), \"neg\": (_neg_impl,), \"getitem\": (_getitem_impl,), \"lshift\": (_unsupported_impl,), \"rshift\": (_unsupported_impl,),", "% op.__name__) def _inv_impl(expr, op, **kw): \"\"\"See :meth:`.ColumnOperators.__inv__`.\"\"\" if hasattr(expr,", "def _collate_impl(expr, op, other, **kw): return collate(expr, other) # a", "None: op, result_type = left.comparator._adapt_expression( op, right.comparator) return BinaryExpression( left,", "import type_api from . import operators from .elements import BindParameter,", "UnaryExpression(expr, operator=operators.distinct_op, type_=expr.type) def _between_impl(expr, op, cleft, cright, **kw): \"\"\"See", "(_binary_operate, ), \"concat_op\": (_binary_operate,), \"any_op\": (_scalar, CollectionAggregate._create_any), \"all_op\": (_scalar, CollectionAggregate._create_all),", "type_api.BOOLEANTYPE if isinstance(obj, _python_is_types + (Null, True_, False_)): # allow", "(_boolean_compare, operators.gt), \"ne\": (_boolean_compare, operators.eq), \"gt\": (_boolean_compare, operators.le), \"ge\": (_boolean_compare,", "ColumnElement, TextClause, UnaryExpression, \\ collate, _is_literal, _literal_as_text, ClauseElement, and_, or_,", "\\ Null, _const_expr, _clause_element_as_expr, \\ ClauseList, ColumnElement, TextClause, UnaryExpression, \\", "else ( operators.empty_notin_op, operators.empty_in_op) return _boolean_compare(expr, op, ClauseList(*args).self_group(against=op), negate=negate_op) def", "\"\"\"See :meth:`.ColumnOperators.between`.\"\"\" return BinaryExpression( expr, ClauseList( _check_literal(expr, operators.and_, cleft), _check_literal(expr,", "BinaryExpression(expr, obj, op, type_=result_type, negate=negate, modifiers=kwargs) def _custom_op_operate(expr, op, obj," ]
[ "user_data.pop('username') user = User.objects.get_by_natural_key(username) recipe = Recipe.objects.create(user=user, **validated_data) for steps", "def update(self, instance, validated_data): steps_data = validated_data.pop('steps') ingredients_data = validated_data.pop('ingredients')", "recipes.models import Recipe, Ingredient, Step class UserSerializer(serializers.ModelSerializer): class Meta: model", "steps = StepSerializer(many=True, required=False) user = UserSerializer(required=True) def create(self, validated_data):", "UserSerializer(required=True) def create(self, validated_data): steps_data = validated_data.pop('steps') ingredients_data = validated_data.pop('ingredients')", "Meta: model = Step fields = [\"step_text\"] class RecipeSerializer(serializers.ModelSerializer): ingredients", "'validators': [UnicodeUsernameValidator()], } } class IngredientSerializer(serializers.ModelSerializer): class Meta: model =", "for steps in steps_data: Step.objects.create(recipe=recipe, **steps) for ingredients in ingredients_data:", "\"steps\", \"ingredients\") def update(self, instance, validated_data): steps_data = validated_data.pop('steps') ingredients_data", "**steps) for ingredients in ingredients_data: Ingredient.objects.create(recipe=recipe, **ingredients) return recipe class", "Meta: model = Ingredient fields = [\"text\"] class StepSerializer(serializers.ModelSerializer): class", "UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = (\"username\", \"last_name\",", "{ 'validators': [UnicodeUsernameValidator()], } } class IngredientSerializer(serializers.ModelSerializer): class Meta: model", "validated_data.pop('steps') ingredients_data = validated_data.pop('ingredients') Step.objects.filter(recipe=instance).delete() Ingredient.objects.filter(recipe=instance).delete() for steps in steps_data:", "for steps in steps_data: Step.objects.create(recipe=instance, **steps) for ingredients in ingredients_data:", "model = Recipe fields = (\"name\", \"user\", \"steps\", \"ingredients\") def", "rest_framework import serializers from django.contrib.auth.models import User from recipes.models import", "= user_data.pop('username') user = User.objects.get_by_natural_key(username) recipe = Recipe.objects.create(user=user, **validated_data) for", "\"ingredients\") def update(self, instance, validated_data): steps_data = validated_data.pop('steps') ingredients_data =", "Meta: model = Recipe fields = (\"name\", \"user\", \"steps\", \"ingredients\")", "= (\"name\", \"user\", \"steps\", \"ingredients\") def update(self, instance, validated_data): steps_data", "create(self, validated_data): steps_data = validated_data.pop('steps') ingredients_data = validated_data.pop('ingredients') user_data =", "user_data = validated_data.pop('user') username = user_data.pop('username') user = User.objects.get_by_natural_key(username) recipe", "= validated_data.pop('steps') ingredients_data = validated_data.pop('ingredients') Step.objects.filter(recipe=instance).delete() Ingredient.objects.filter(recipe=instance).delete() for steps in", "django.contrib.auth.models import User from recipes.models import Recipe, Ingredient, Step class", "ingredients_data: Ingredient.objects.create(recipe=recipe, **ingredients) return recipe class Meta: model = Recipe", "class Meta: model = Recipe fields = (\"name\", \"user\", \"steps\",", "import User from recipes.models import Recipe, Ingredient, Step class UserSerializer(serializers.ModelSerializer):", "= [\"step_text\"] class RecipeSerializer(serializers.ModelSerializer): ingredients = IngredientSerializer(many=True, required=False) steps =", "**validated_data) for steps in steps_data: Step.objects.create(recipe=recipe, **steps) for ingredients in", "steps_data: Step.objects.create(recipe=instance, **steps) for ingredients in ingredients_data: Ingredient.objects.create(recipe=instance, **ingredients) return", "from recipes.models import Recipe, Ingredient, Step class UserSerializer(serializers.ModelSerializer): class Meta:", "required=False) user = UserSerializer(required=True) def create(self, validated_data): steps_data = validated_data.pop('steps')", "steps_data = validated_data.pop('steps') ingredients_data = validated_data.pop('ingredients') user_data = validated_data.pop('user') username", "validated_data.pop('ingredients') user_data = validated_data.pop('user') username = user_data.pop('username') user = User.objects.get_by_natural_key(username)", "return recipe class Meta: model = Recipe fields = (\"name\",", "fields = [\"text\"] class StepSerializer(serializers.ModelSerializer): class Meta: model = Step", "= Recipe.objects.create(user=user, **validated_data) for steps in steps_data: Step.objects.create(recipe=recipe, **steps) for", "class Meta: model = Ingredient fields = [\"text\"] class StepSerializer(serializers.ModelSerializer):", "Meta: model = User fields = (\"username\", \"last_name\", \"first_name\", \"email\")", "validated_data.pop('user') username = user_data.pop('username') user = User.objects.get_by_natural_key(username) recipe = Recipe.objects.create(user=user,", "= Ingredient fields = [\"text\"] class StepSerializer(serializers.ModelSerializer): class Meta: model", "\"user\", \"steps\", \"ingredients\") def update(self, instance, validated_data): steps_data = validated_data.pop('steps')", "StepSerializer(serializers.ModelSerializer): class Meta: model = Step fields = [\"step_text\"] class", "Recipe fields = (\"name\", \"user\", \"steps\", \"ingredients\") def update(self, instance,", "recipe = Recipe.objects.create(user=user, **validated_data) for steps in steps_data: Step.objects.create(recipe=recipe, **steps)", "User fields = (\"username\", \"last_name\", \"first_name\", \"email\") extra_kwargs = {", "import Recipe, Ingredient, Step class UserSerializer(serializers.ModelSerializer): class Meta: model =", "\"email\") extra_kwargs = { 'username': { 'validators': [UnicodeUsernameValidator()], } }", "class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = (\"username\",", "model = Step fields = [\"step_text\"] class RecipeSerializer(serializers.ModelSerializer): ingredients =", "recipe class Meta: model = Recipe fields = (\"name\", \"user\",", "update(self, instance, validated_data): steps_data = validated_data.pop('steps') ingredients_data = validated_data.pop('ingredients') Step.objects.filter(recipe=instance).delete()", "validated_data.pop('ingredients') Step.objects.filter(recipe=instance).delete() Ingredient.objects.filter(recipe=instance).delete() for steps in steps_data: Step.objects.create(recipe=instance, **steps) for", "user = UserSerializer(required=True) def create(self, validated_data): steps_data = validated_data.pop('steps') ingredients_data", "IngredientSerializer(many=True, required=False) steps = StepSerializer(many=True, required=False) user = UserSerializer(required=True) def", "class Meta: model = Step fields = [\"step_text\"] class RecipeSerializer(serializers.ModelSerializer):", "} } class IngredientSerializer(serializers.ModelSerializer): class Meta: model = Ingredient fields", "ingredients = IngredientSerializer(many=True, required=False) steps = StepSerializer(many=True, required=False) user =", "= validated_data.pop('steps') ingredients_data = validated_data.pop('ingredients') user_data = validated_data.pop('user') username =", "= User.objects.get_by_natural_key(username) recipe = Recipe.objects.create(user=user, **validated_data) for steps in steps_data:", "IngredientSerializer(serializers.ModelSerializer): class Meta: model = Ingredient fields = [\"text\"] class", "from django.contrib.auth.validators import UnicodeUsernameValidator from rest_framework import serializers from django.contrib.auth.models", "Step.objects.filter(recipe=instance).delete() Ingredient.objects.filter(recipe=instance).delete() for steps in steps_data: Step.objects.create(recipe=instance, **steps) for ingredients", "(\"username\", \"last_name\", \"first_name\", \"email\") extra_kwargs = { 'username': { 'validators':", "(\"name\", \"user\", \"steps\", \"ingredients\") def update(self, instance, validated_data): steps_data =", "username = user_data.pop('username') user = User.objects.get_by_natural_key(username) recipe = Recipe.objects.create(user=user, **validated_data)", "\"first_name\", \"email\") extra_kwargs = { 'username': { 'validators': [UnicodeUsernameValidator()], }", "fields = (\"name\", \"user\", \"steps\", \"ingredients\") def update(self, instance, validated_data):", "= [\"text\"] class StepSerializer(serializers.ModelSerializer): class Meta: model = Step fields", "ingredients_data = validated_data.pop('ingredients') Step.objects.filter(recipe=instance).delete() Ingredient.objects.filter(recipe=instance).delete() for steps in steps_data: Step.objects.create(recipe=instance,", "User from recipes.models import Recipe, Ingredient, Step class UserSerializer(serializers.ModelSerializer): class", "[UnicodeUsernameValidator()], } } class IngredientSerializer(serializers.ModelSerializer): class Meta: model = Ingredient", "class StepSerializer(serializers.ModelSerializer): class Meta: model = Step fields = [\"step_text\"]", "Ingredient, Step class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields", "Step fields = [\"step_text\"] class RecipeSerializer(serializers.ModelSerializer): ingredients = IngredientSerializer(many=True, required=False)", "import serializers from django.contrib.auth.models import User from recipes.models import Recipe,", "steps_data: Step.objects.create(recipe=recipe, **steps) for ingredients in ingredients_data: Ingredient.objects.create(recipe=recipe, **ingredients) return", "User.objects.get_by_natural_key(username) recipe = Recipe.objects.create(user=user, **validated_data) for steps in steps_data: Step.objects.create(recipe=recipe,", "user = User.objects.get_by_natural_key(username) recipe = Recipe.objects.create(user=user, **validated_data) for steps in", "**ingredients) return recipe class Meta: model = Recipe fields =", "= UserSerializer(required=True) def create(self, validated_data): steps_data = validated_data.pop('steps') ingredients_data =", "= IngredientSerializer(many=True, required=False) steps = StepSerializer(many=True, required=False) user = UserSerializer(required=True)", "= validated_data.pop('ingredients') user_data = validated_data.pop('user') username = user_data.pop('username') user =", "Ingredient.objects.create(recipe=recipe, **ingredients) return recipe class Meta: model = Recipe fields", "= StepSerializer(many=True, required=False) user = UserSerializer(required=True) def create(self, validated_data): steps_data", "steps in steps_data: Step.objects.create(recipe=recipe, **steps) for ingredients in ingredients_data: Ingredient.objects.create(recipe=recipe,", "validated_data): steps_data = validated_data.pop('steps') ingredients_data = validated_data.pop('ingredients') user_data = validated_data.pop('user')", "= User fields = (\"username\", \"last_name\", \"first_name\", \"email\") extra_kwargs =", "Recipe.objects.create(user=user, **validated_data) for steps in steps_data: Step.objects.create(recipe=recipe, **steps) for ingredients", "fields = (\"username\", \"last_name\", \"first_name\", \"email\") extra_kwargs = { 'username':", "{ 'username': { 'validators': [UnicodeUsernameValidator()], } } class IngredientSerializer(serializers.ModelSerializer): class", "Recipe, Ingredient, Step class UserSerializer(serializers.ModelSerializer): class Meta: model = User", "from rest_framework import serializers from django.contrib.auth.models import User from recipes.models", "ingredients_data = validated_data.pop('ingredients') user_data = validated_data.pop('user') username = user_data.pop('username') user", "class IngredientSerializer(serializers.ModelSerializer): class Meta: model = Ingredient fields = [\"text\"]", "Step.objects.create(recipe=instance, **steps) for ingredients in ingredients_data: Ingredient.objects.create(recipe=instance, **ingredients) return instance", "class Meta: model = User fields = (\"username\", \"last_name\", \"first_name\",", "def create(self, validated_data): steps_data = validated_data.pop('steps') ingredients_data = validated_data.pop('ingredients') user_data", "Ingredient fields = [\"text\"] class StepSerializer(serializers.ModelSerializer): class Meta: model =", "= (\"username\", \"last_name\", \"first_name\", \"email\") extra_kwargs = { 'username': {", "in ingredients_data: Ingredient.objects.create(recipe=recipe, **ingredients) return recipe class Meta: model =", "= validated_data.pop('ingredients') Step.objects.filter(recipe=instance).delete() Ingredient.objects.filter(recipe=instance).delete() for steps in steps_data: Step.objects.create(recipe=instance, **steps)", "validated_data): steps_data = validated_data.pop('steps') ingredients_data = validated_data.pop('ingredients') Step.objects.filter(recipe=instance).delete() Ingredient.objects.filter(recipe=instance).delete() for", "<gh_stars>0 from django.contrib.auth.validators import UnicodeUsernameValidator from rest_framework import serializers from", "django.contrib.auth.validators import UnicodeUsernameValidator from rest_framework import serializers from django.contrib.auth.models import", "= Step fields = [\"step_text\"] class RecipeSerializer(serializers.ModelSerializer): ingredients = IngredientSerializer(many=True,", "'username': { 'validators': [UnicodeUsernameValidator()], } } class IngredientSerializer(serializers.ModelSerializer): class Meta:", "= Recipe fields = (\"name\", \"user\", \"steps\", \"ingredients\") def update(self,", "= validated_data.pop('user') username = user_data.pop('username') user = User.objects.get_by_natural_key(username) recipe =", "serializers from django.contrib.auth.models import User from recipes.models import Recipe, Ingredient,", "import UnicodeUsernameValidator from rest_framework import serializers from django.contrib.auth.models import User", "for ingredients in ingredients_data: Ingredient.objects.create(recipe=recipe, **ingredients) return recipe class Meta:", "model = Ingredient fields = [\"text\"] class StepSerializer(serializers.ModelSerializer): class Meta:", "instance, validated_data): steps_data = validated_data.pop('steps') ingredients_data = validated_data.pop('ingredients') Step.objects.filter(recipe=instance).delete() Ingredient.objects.filter(recipe=instance).delete()", "validated_data.pop('steps') ingredients_data = validated_data.pop('ingredients') user_data = validated_data.pop('user') username = user_data.pop('username')", "class RecipeSerializer(serializers.ModelSerializer): ingredients = IngredientSerializer(many=True, required=False) steps = StepSerializer(many=True, required=False)", "= { 'username': { 'validators': [UnicodeUsernameValidator()], } } class IngredientSerializer(serializers.ModelSerializer):", "[\"step_text\"] class RecipeSerializer(serializers.ModelSerializer): ingredients = IngredientSerializer(many=True, required=False) steps = StepSerializer(many=True,", "UnicodeUsernameValidator from rest_framework import serializers from django.contrib.auth.models import User from", "steps in steps_data: Step.objects.create(recipe=instance, **steps) for ingredients in ingredients_data: Ingredient.objects.create(recipe=instance,", "RecipeSerializer(serializers.ModelSerializer): ingredients = IngredientSerializer(many=True, required=False) steps = StepSerializer(many=True, required=False) user", "steps_data = validated_data.pop('steps') ingredients_data = validated_data.pop('ingredients') Step.objects.filter(recipe=instance).delete() Ingredient.objects.filter(recipe=instance).delete() for steps", "Ingredient.objects.filter(recipe=instance).delete() for steps in steps_data: Step.objects.create(recipe=instance, **steps) for ingredients in", "from django.contrib.auth.models import User from recipes.models import Recipe, Ingredient, Step", "model = User fields = (\"username\", \"last_name\", \"first_name\", \"email\") extra_kwargs", "extra_kwargs = { 'username': { 'validators': [UnicodeUsernameValidator()], } } class", "\"last_name\", \"first_name\", \"email\") extra_kwargs = { 'username': { 'validators': [UnicodeUsernameValidator()],", "fields = [\"step_text\"] class RecipeSerializer(serializers.ModelSerializer): ingredients = IngredientSerializer(many=True, required=False) steps", "} class IngredientSerializer(serializers.ModelSerializer): class Meta: model = Ingredient fields =", "Step.objects.create(recipe=recipe, **steps) for ingredients in ingredients_data: Ingredient.objects.create(recipe=recipe, **ingredients) return recipe", "StepSerializer(many=True, required=False) user = UserSerializer(required=True) def create(self, validated_data): steps_data =", "required=False) steps = StepSerializer(many=True, required=False) user = UserSerializer(required=True) def create(self,", "[\"text\"] class StepSerializer(serializers.ModelSerializer): class Meta: model = Step fields =", "in steps_data: Step.objects.create(recipe=recipe, **steps) for ingredients in ingredients_data: Ingredient.objects.create(recipe=recipe, **ingredients)", "in steps_data: Step.objects.create(recipe=instance, **steps) for ingredients in ingredients_data: Ingredient.objects.create(recipe=instance, **ingredients)", "ingredients in ingredients_data: Ingredient.objects.create(recipe=recipe, **ingredients) return recipe class Meta: model", "Step class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields =" ]
[ "(2, 3)]) acc = head.get_accuracy(out, out, torch.ones_like(out)) assert acc['mpjpe'] ==", "tensor should be 3 input_shape = (1, 1024, 1, 1)", "of the input tensor should be 3 input_shape = (1,", "1024, 1, 1) inputs = _demo_inputs(input_shape) _ = head(inputs) with", "input_shape = (1, 1024, 1) inputs = _demo_inputs(input_shape) out =", "1) inputs = _demo_inputs(input_shape) out = head(inputs) assert out.shape ==", "import pytest import torch from mmpose.models import TemporalRegressionHead def test_temporal_regression_head():", "head.\"\"\" head = TemporalRegressionHead( in_channels=1024, num_joints=17, loss_keypoint=dict(type='MPJPELoss', use_target_weight=True)) head.init_weights() with", "last dim should be 1 input_shape = (1, 1024, 3)", "= head(inputs) input_shape = (1, 1024, 1) inputs = _demo_inputs(input_shape)", "= (1, 1024, 1, 1) inputs = _demo_inputs(input_shape) _ =", "use_target_weight=True)) head.init_weights() with pytest.raises(AssertionError): # ndim of the input tensor", "= _demo_inputs(input_shape) _ = head(inputs) with pytest.raises(AssertionError): # size of", "inputs = _demo_inputs(input_shape) out = head(inputs) assert out.shape == torch.Size([1,", "Returns: Random input tensor with the size of input_shape. \"\"\"", "the size of input_shape. \"\"\" inps = np.random.random(input_shape) inps =", "numpy as np import pytest import torch from mmpose.models import", "assert out.shape == torch.Size([1, 17, 3]) loss = head.get_loss(out, out,", "input_shape (tuple): input batch dimensions. Default: (1, 1024, 1). Returns:", "Args: input_shape (tuple): input batch dimensions. Default: (1, 1024, 1).", "# ndim of the input tensor should be 3 input_shape", "0.) def _demo_inputs(input_shape=(1, 1024, 1)): \"\"\"Create a superset of inputs", "with pytest.raises(AssertionError): # ndim of the input tensor should be", "import torch from mmpose.models import TemporalRegressionHead def test_temporal_regression_head(): \"\"\"Test temporal", "num_joints=17, loss_keypoint=dict(type='MPJPELoss', use_target_weight=True)) head.init_weights() with pytest.raises(AssertionError): # ndim of the", "= TemporalRegressionHead( in_channels=1024, num_joints=17, loss_keypoint=dict(type='MPJPELoss', use_target_weight=True)) head.init_weights() with pytest.raises(AssertionError): #", "TemporalRegressionHead( in_channels=1024, num_joints=17, loss_keypoint=dict(type='MPJPELoss', use_target_weight=True)) head.init_weights() with pytest.raises(AssertionError): # ndim", "to run head. Args: input_shape (tuple): input batch dimensions. Default:", "\"\"\"Test temporal head.\"\"\" head = TemporalRegressionHead( in_channels=1024, num_joints=17, loss_keypoint=dict(type='MPJPELoss', use_target_weight=True))", "should be 1 input_shape = (1, 1024, 3) inputs =", "head.init_weights() with pytest.raises(AssertionError): # ndim of the input tensor should", "assert torch.allclose(loss['reg_loss'], torch.tensor(0.)) _ = head.inference_model(inputs) _ = head.inference_model(inputs, [(0,", "(tuple): input batch dimensions. Default: (1, 1024, 1). Returns: Random", "(1, 1024, 1, 1) inputs = _demo_inputs(input_shape) _ = head(inputs)", "in_channels=1024, num_joints=17, loss_keypoint=dict(type='MPJPELoss', use_target_weight=True)) head.init_weights() with pytest.raises(AssertionError): # ndim of", "pytest.raises(AssertionError): # size of the last dim should be 1", "be 1 input_shape = (1, 1024, 3) inputs = _demo_inputs(input_shape)", "= _demo_inputs(input_shape) out = head(inputs) assert out.shape == torch.Size([1, 17,", "superset of inputs needed to run head. Args: input_shape (tuple):", "(1, 1024, 3) inputs = _demo_inputs(input_shape) _ = head(inputs) input_shape", "def test_temporal_regression_head(): \"\"\"Test temporal head.\"\"\" head = TemporalRegressionHead( in_channels=1024, num_joints=17,", "loss_keypoint=dict(type='MPJPELoss', use_target_weight=True)) head.init_weights() with pytest.raises(AssertionError): # ndim of the input", "_demo_inputs(input_shape) _ = head(inputs) with pytest.raises(AssertionError): # size of the", "should be 3 input_shape = (1, 1024, 1, 1) inputs", "test_temporal_regression_head(): \"\"\"Test temporal head.\"\"\" head = TemporalRegressionHead( in_channels=1024, num_joints=17, loss_keypoint=dict(type='MPJPELoss',", "== 0. np.testing.assert_almost_equal(acc['p_mpjpe'], 0.) def _demo_inputs(input_shape=(1, 1024, 1)): \"\"\"Create a", "torch from mmpose.models import TemporalRegressionHead def test_temporal_regression_head(): \"\"\"Test temporal head.\"\"\"", "be 3 input_shape = (1, 1024, 1, 1) inputs =", "dim should be 1 input_shape = (1, 1024, 3) inputs", "== torch.Size([1, 17, 3]) loss = head.get_loss(out, out, torch.ones_like(out)) assert", "np.testing.assert_almost_equal(acc['p_mpjpe'], 0.) def _demo_inputs(input_shape=(1, 1024, 1)): \"\"\"Create a superset of", "tensor with the size of input_shape. \"\"\" inps = np.random.random(input_shape)", "input tensor should be 3 input_shape = (1, 1024, 1,", "of input_shape. \"\"\" inps = np.random.random(input_shape) inps = torch.FloatTensor(inps) return", "1) inputs = _demo_inputs(input_shape) _ = head(inputs) with pytest.raises(AssertionError): #", "temporal head.\"\"\" head = TemporalRegressionHead( in_channels=1024, num_joints=17, loss_keypoint=dict(type='MPJPELoss', use_target_weight=True)) head.init_weights()", "_ = head.inference_model(inputs) _ = head.inference_model(inputs, [(0, 1), (2, 3)])", "out, torch.ones_like(out)) assert torch.allclose(loss['reg_loss'], torch.tensor(0.)) _ = head.inference_model(inputs) _ =", "of inputs needed to run head. Args: input_shape (tuple): input", "# size of the last dim should be 1 input_shape", "dimensions. Default: (1, 1024, 1). Returns: Random input tensor with", "head(inputs) with pytest.raises(AssertionError): # size of the last dim should", "mmpose.models import TemporalRegressionHead def test_temporal_regression_head(): \"\"\"Test temporal head.\"\"\" head =", "a superset of inputs needed to run head. Args: input_shape", "_demo_inputs(input_shape) out = head(inputs) assert out.shape == torch.Size([1, 17, 3])", "= head.inference_model(inputs, [(0, 1), (2, 3)]) acc = head.get_accuracy(out, out,", "Default: (1, 1024, 1). Returns: Random input tensor with the", "_demo_inputs(input_shape) _ = head(inputs) input_shape = (1, 1024, 1) inputs", "<reponame>jcwon0/BlurHPE import numpy as np import pytest import torch from", "ndim of the input tensor should be 3 input_shape =", "input_shape = (1, 1024, 1, 1) inputs = _demo_inputs(input_shape) _", "head = TemporalRegressionHead( in_channels=1024, num_joints=17, loss_keypoint=dict(type='MPJPELoss', use_target_weight=True)) head.init_weights() with pytest.raises(AssertionError):", "torch.ones_like(out)) assert torch.allclose(loss['reg_loss'], torch.tensor(0.)) _ = head.inference_model(inputs) _ = head.inference_model(inputs,", "= _demo_inputs(input_shape) _ = head(inputs) input_shape = (1, 1024, 1)", "1, 1) inputs = _demo_inputs(input_shape) _ = head(inputs) with pytest.raises(AssertionError):", "_ = head(inputs) input_shape = (1, 1024, 1) inputs =", "1024, 3) inputs = _demo_inputs(input_shape) _ = head(inputs) input_shape =", "head.inference_model(inputs, [(0, 1), (2, 3)]) acc = head.get_accuracy(out, out, torch.ones_like(out))", "(1, 1024, 1). Returns: Random input tensor with the size", "torch.allclose(loss['reg_loss'], torch.tensor(0.)) _ = head.inference_model(inputs) _ = head.inference_model(inputs, [(0, 1),", "1024, 1)): \"\"\"Create a superset of inputs needed to run", "(1, 1024, 1) inputs = _demo_inputs(input_shape) out = head(inputs) assert", "as np import pytest import torch from mmpose.models import TemporalRegressionHead", "head(inputs) input_shape = (1, 1024, 1) inputs = _demo_inputs(input_shape) out", "out = head(inputs) assert out.shape == torch.Size([1, 17, 3]) loss", "= head(inputs) with pytest.raises(AssertionError): # size of the last dim", "inputs needed to run head. Args: input_shape (tuple): input batch", "input batch dimensions. Default: (1, 1024, 1). Returns: Random input", "3]) loss = head.get_loss(out, out, torch.ones_like(out)) assert torch.allclose(loss['reg_loss'], torch.tensor(0.)) _", "_demo_inputs(input_shape=(1, 1024, 1)): \"\"\"Create a superset of inputs needed to", "input tensor with the size of input_shape. \"\"\" inps =", "def _demo_inputs(input_shape=(1, 1024, 1)): \"\"\"Create a superset of inputs needed", "[(0, 1), (2, 3)]) acc = head.get_accuracy(out, out, torch.ones_like(out)) assert", "input_shape. \"\"\" inps = np.random.random(input_shape) inps = torch.FloatTensor(inps) return inps", "needed to run head. Args: input_shape (tuple): input batch dimensions.", "3 input_shape = (1, 1024, 1, 1) inputs = _demo_inputs(input_shape)", "1024, 1). Returns: Random input tensor with the size of", "3)]) acc = head.get_accuracy(out, out, torch.ones_like(out)) assert acc['mpjpe'] == 0.", "= head.inference_model(inputs) _ = head.inference_model(inputs, [(0, 1), (2, 3)]) acc", "= head.get_accuracy(out, out, torch.ones_like(out)) assert acc['mpjpe'] == 0. np.testing.assert_almost_equal(acc['p_mpjpe'], 0.)", "import numpy as np import pytest import torch from mmpose.models", "with pytest.raises(AssertionError): # size of the last dim should be", "out, torch.ones_like(out)) assert acc['mpjpe'] == 0. np.testing.assert_almost_equal(acc['p_mpjpe'], 0.) def _demo_inputs(input_shape=(1,", "size of the last dim should be 1 input_shape =", "out.shape == torch.Size([1, 17, 3]) loss = head.get_loss(out, out, torch.ones_like(out))", "with the size of input_shape. \"\"\" inps = np.random.random(input_shape) inps", "= (1, 1024, 3) inputs = _demo_inputs(input_shape) _ = head(inputs)", "import TemporalRegressionHead def test_temporal_regression_head(): \"\"\"Test temporal head.\"\"\" head = TemporalRegressionHead(", "head.inference_model(inputs) _ = head.inference_model(inputs, [(0, 1), (2, 3)]) acc =", "3) inputs = _demo_inputs(input_shape) _ = head(inputs) input_shape = (1,", "assert acc['mpjpe'] == 0. np.testing.assert_almost_equal(acc['p_mpjpe'], 0.) def _demo_inputs(input_shape=(1, 1024, 1)):", "pytest.raises(AssertionError): # ndim of the input tensor should be 3", "= (1, 1024, 1) inputs = _demo_inputs(input_shape) out = head(inputs)", "loss = head.get_loss(out, out, torch.ones_like(out)) assert torch.allclose(loss['reg_loss'], torch.tensor(0.)) _ =", "Random input tensor with the size of input_shape. \"\"\" inps", "\"\"\"Create a superset of inputs needed to run head. Args:", "size of input_shape. \"\"\" inps = np.random.random(input_shape) inps = torch.FloatTensor(inps)", "head. Args: input_shape (tuple): input batch dimensions. Default: (1, 1024,", "pytest import torch from mmpose.models import TemporalRegressionHead def test_temporal_regression_head(): \"\"\"Test", "batch dimensions. Default: (1, 1024, 1). Returns: Random input tensor", "1024, 1) inputs = _demo_inputs(input_shape) out = head(inputs) assert out.shape", "1), (2, 3)]) acc = head.get_accuracy(out, out, torch.ones_like(out)) assert acc['mpjpe']", "head.get_loss(out, out, torch.ones_like(out)) assert torch.allclose(loss['reg_loss'], torch.tensor(0.)) _ = head.inference_model(inputs) _", "acc = head.get_accuracy(out, out, torch.ones_like(out)) assert acc['mpjpe'] == 0. np.testing.assert_almost_equal(acc['p_mpjpe'],", "from mmpose.models import TemporalRegressionHead def test_temporal_regression_head(): \"\"\"Test temporal head.\"\"\" head", "the input tensor should be 3 input_shape = (1, 1024,", "_ = head(inputs) with pytest.raises(AssertionError): # size of the last", "the last dim should be 1 input_shape = (1, 1024,", "acc['mpjpe'] == 0. np.testing.assert_almost_equal(acc['p_mpjpe'], 0.) def _demo_inputs(input_shape=(1, 1024, 1)): \"\"\"Create", "inputs = _demo_inputs(input_shape) _ = head(inputs) input_shape = (1, 1024,", "torch.ones_like(out)) assert acc['mpjpe'] == 0. np.testing.assert_almost_equal(acc['p_mpjpe'], 0.) def _demo_inputs(input_shape=(1, 1024,", "of the last dim should be 1 input_shape = (1,", "np import pytest import torch from mmpose.models import TemporalRegressionHead def", "torch.tensor(0.)) _ = head.inference_model(inputs) _ = head.inference_model(inputs, [(0, 1), (2,", "1 input_shape = (1, 1024, 3) inputs = _demo_inputs(input_shape) _", "1)): \"\"\"Create a superset of inputs needed to run head.", "_ = head.inference_model(inputs, [(0, 1), (2, 3)]) acc = head.get_accuracy(out,", "1). Returns: Random input tensor with the size of input_shape.", "17, 3]) loss = head.get_loss(out, out, torch.ones_like(out)) assert torch.allclose(loss['reg_loss'], torch.tensor(0.))", "= head.get_loss(out, out, torch.ones_like(out)) assert torch.allclose(loss['reg_loss'], torch.tensor(0.)) _ = head.inference_model(inputs)", "= head(inputs) assert out.shape == torch.Size([1, 17, 3]) loss =", "0. np.testing.assert_almost_equal(acc['p_mpjpe'], 0.) def _demo_inputs(input_shape=(1, 1024, 1)): \"\"\"Create a superset", "head(inputs) assert out.shape == torch.Size([1, 17, 3]) loss = head.get_loss(out,", "input_shape = (1, 1024, 3) inputs = _demo_inputs(input_shape) _ =", "torch.Size([1, 17, 3]) loss = head.get_loss(out, out, torch.ones_like(out)) assert torch.allclose(loss['reg_loss'],", "head.get_accuracy(out, out, torch.ones_like(out)) assert acc['mpjpe'] == 0. np.testing.assert_almost_equal(acc['p_mpjpe'], 0.) def", "inputs = _demo_inputs(input_shape) _ = head(inputs) with pytest.raises(AssertionError): # size", "TemporalRegressionHead def test_temporal_regression_head(): \"\"\"Test temporal head.\"\"\" head = TemporalRegressionHead( in_channels=1024,", "run head. Args: input_shape (tuple): input batch dimensions. Default: (1," ]
[ "1.10.2 on 2016-10-31 23:20 from __future__ import unicode_literals from django.db", "on 2016-10-31 23:20 from __future__ import unicode_literals from django.db import", "Generated by Django 1.10.2 on 2016-10-31 23:20 from __future__ import", "# Generated by Django 1.10.2 on 2016-10-31 23:20 from __future__", "class Migration(migrations.Migration): dependencies = [ ('leagues', '0001_initial'), ] operations =", "from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration):", "import migrations class Migration(migrations.Migration): dependencies = [ ('leagues', '0001_initial'), ]", "# -*- coding: utf-8 -*- # Generated by Django 1.10.2", "utf-8 -*- # Generated by Django 1.10.2 on 2016-10-31 23:20", "unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [", "Migration(migrations.Migration): dependencies = [ ('leagues', '0001_initial'), ] operations = [", "[ ('leagues', '0001_initial'), ] operations = [ migrations.RenameField( model_name='team', old_name='city',", "from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('leagues',", "import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies =", "by Django 1.10.2 on 2016-10-31 23:20 from __future__ import unicode_literals", "<filename>django_orm/sports_orm/leagues/migrations/0002_auto_20161031_1620.py # -*- coding: utf-8 -*- # Generated by Django", "] operations = [ migrations.RenameField( model_name='team', old_name='city', new_name='location', ), ]", "django.db import migrations class Migration(migrations.Migration): dependencies = [ ('leagues', '0001_initial'),", "('leagues', '0001_initial'), ] operations = [ migrations.RenameField( model_name='team', old_name='city', new_name='location',", "__future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies", "coding: utf-8 -*- # Generated by Django 1.10.2 on 2016-10-31", "-*- coding: utf-8 -*- # Generated by Django 1.10.2 on", "Django 1.10.2 on 2016-10-31 23:20 from __future__ import unicode_literals from", "migrations class Migration(migrations.Migration): dependencies = [ ('leagues', '0001_initial'), ] operations", "dependencies = [ ('leagues', '0001_initial'), ] operations = [ migrations.RenameField(", "-*- # Generated by Django 1.10.2 on 2016-10-31 23:20 from", "'0001_initial'), ] operations = [ migrations.RenameField( model_name='team', old_name='city', new_name='location', ),", "23:20 from __future__ import unicode_literals from django.db import migrations class", "2016-10-31 23:20 from __future__ import unicode_literals from django.db import migrations", "= [ ('leagues', '0001_initial'), ] operations = [ migrations.RenameField( model_name='team'," ]
[ "when snake crosses the screen boundary or bites its body.", "idxi,idxj=self.moveops[direction] newi,newj=peak[0]+idxi,peak[1]+idxj if (newi,newj) in self.position or \\ newi<0 or", "self.food and [newi,newj]==self.food[0]: self.food.popleft() self.position.append(tail) self.score+=1 return self.score # Your", "- screen width @param height - screen height @param food", "@param food - A list of food positions E.g food", "snake crosses the screen boundary or bites its body. :type", "@param direction - 'U' = Up, 'L' = Left, 'R'", "newi<0 or newi>=self.height or \\ newj<0 or newj>=self.width: return -1", "if game over. Game over when snake crosses the screen", "\"\"\" if direction not in self.moveops: return -1 peak,tail=self.position[0],self.position[-1] self.position.pop()", "the snake. @param direction - 'U' = Up, 'L' =", "@param height - screen height @param food - A list", "@return The game's score after the move. Return -1 if", "data structure here. @param width - screen width @param height", "'R' = Right, 'D' = Down @return The game's score", "'L' = Left, 'R' = Right, 'D' = Down @return", "\\ newj<0 or newj>=self.width: return -1 self.position.appendleft((newi,newj)) if self.food and", "means the first food is positioned at [1,1], the second", "= [[1,1], [1,0]] means the first food is positioned at", "[1,0]] means the first food is positioned at [1,1], the", "food - A list of food positions E.g food =", "'D' = Down @return The game's score after the move.", "self.food=collections.deque(food) self.position=collections.deque([(0,0)]) self.moveops={'U':(-1,0),'L':(0,-1),'R':(0,1),'D':(1,0)} self.score=0 def move(self, direction): \"\"\" Moves the", "[1,0]. :type width: int :type height: int :type food: List[List[int]]", "is positioned at [1,1], the second is at [1,0]. :type", "newj<0 or newj>=self.width: return -1 self.position.appendleft((newi,newj)) if self.food and [newi,newj]==self.food[0]:", "# Your SnakeGame object will be instantiated and called as", "game over. Game over when snake crosses the screen boundary", "the first food is positioned at [1,1], the second is", "[newi,newj]==self.food[0]: self.food.popleft() self.position.append(tail) self.score+=1 return self.score # Your SnakeGame object", "SnakeGame object will be instantiated and called as such: #", "move. Return -1 if game over. Game over when snake", "will be instantiated and called as such: # obj =", "over. Game over when snake crosses the screen boundary or", "first food is positioned at [1,1], the second is at", "int :type height: int :type food: List[List[int]] \"\"\" self.width=width self.height=height", "height - screen height @param food - A list of", "height @param food - A list of food positions E.g", "the screen boundary or bites its body. :type direction: str", "or newj>=self.width: return -1 self.position.appendleft((newi,newj)) if self.food and [newi,newj]==self.food[0]: self.food.popleft()", "or newi>=self.height or \\ newj<0 or newj>=self.width: return -1 self.position.appendleft((newi,newj))", "width - screen width @param height - screen height @param", "second is at [1,0]. :type width: int :type height: int", "its body. :type direction: str :rtype: int \"\"\" if direction", "at [1,1], the second is at [1,0]. :type width: int", "Left, 'R' = Right, 'D' = Down @return The game's", ":rtype: int \"\"\" if direction not in self.moveops: return -1", "if direction not in self.moveops: return -1 peak,tail=self.position[0],self.position[-1] self.position.pop() idxi,idxj=self.moveops[direction]", "Your SnakeGame object will be instantiated and called as such:", "screen width @param height - screen height @param food -", "direction): \"\"\" Moves the snake. @param direction - 'U' =", "\"\"\" Moves the snake. @param direction - 'U' = Up,", "str :rtype: int \"\"\" if direction not in self.moveops: return", "width @param height - screen height @param food - A", "return -1 peak,tail=self.position[0],self.position[-1] self.position.pop() idxi,idxj=self.moveops[direction] newi,newj=peak[0]+idxi,peak[1]+idxj if (newi,newj) in self.position", "self.position.pop() idxi,idxj=self.moveops[direction] newi,newj=peak[0]+idxi,peak[1]+idxj if (newi,newj) in self.position or \\ newi<0", "(newi,newj) in self.position or \\ newi<0 or newi>=self.height or \\", "[1,1], the second is at [1,0]. :type width: int :type", "or bites its body. :type direction: str :rtype: int \"\"\"", "or \\ newi<0 or newi>=self.height or \\ newj<0 or newj>=self.width:", "self.score=0 def move(self, direction): \"\"\" Moves the snake. @param direction", "over when snake crosses the screen boundary or bites its", "[[1,1], [1,0]] means the first food is positioned at [1,1],", "@param width - screen width @param height - screen height", "Initialize your data structure here. @param width - screen width", "self.position=collections.deque([(0,0)]) self.moveops={'U':(-1,0),'L':(0,-1),'R':(0,1),'D':(1,0)} self.score=0 def move(self, direction): \"\"\" Moves the snake.", "The game's score after the move. Return -1 if game", "height: int :type food: List[List[int]] \"\"\" self.width=width self.height=height self.food=collections.deque(food) self.position=collections.deque([(0,0)])", "A list of food positions E.g food = [[1,1], [1,0]]", "- screen height @param food - A list of food", "Right, 'D' = Down @return The game's score after the", "self.position.appendleft((newi,newj)) if self.food and [newi,newj]==self.food[0]: self.food.popleft() self.position.append(tail) self.score+=1 return self.score", "in self.moveops: return -1 peak,tail=self.position[0],self.position[-1] self.position.pop() idxi,idxj=self.moveops[direction] newi,newj=peak[0]+idxi,peak[1]+idxj if (newi,newj)", "instantiated and called as such: # obj = SnakeGame(width, height,", "your data structure here. @param width - screen width @param", "the move. Return -1 if game over. Game over when", "and called as such: # obj = SnakeGame(width, height, food)", "- 'U' = Up, 'L' = Left, 'R' = Right,", "the second is at [1,0]. :type width: int :type height:", "Up, 'L' = Left, 'R' = Right, 'D' = Down", "self.moveops: return -1 peak,tail=self.position[0],self.position[-1] self.position.pop() idxi,idxj=self.moveops[direction] newi,newj=peak[0]+idxi,peak[1]+idxj if (newi,newj) in", "Down @return The game's score after the move. Return -1", "\\ newi<0 or newi>=self.height or \\ newj<0 or newj>=self.width: return", "self.score # Your SnakeGame object will be instantiated and called", "be instantiated and called as such: # obj = SnakeGame(width,", "def __init__(self, width,height,food): \"\"\" Initialize your data structure here. @param", "class SnakeGame(object): def __init__(self, width,height,food): \"\"\" Initialize your data structure", "boundary or bites its body. :type direction: str :rtype: int", "SnakeGame(object): def __init__(self, width,height,food): \"\"\" Initialize your data structure here.", "width,height,food): \"\"\" Initialize your data structure here. @param width -", "= Right, 'D' = Down @return The game's score after", "# obj = SnakeGame(width, height, food) # param_1 = obj.move(direction)", "- A list of food positions E.g food = [[1,1],", "food = [[1,1], [1,0]] means the first food is positioned", ":type food: List[List[int]] \"\"\" self.width=width self.height=height self.food=collections.deque(food) self.position=collections.deque([(0,0)]) self.moveops={'U':(-1,0),'L':(0,-1),'R':(0,1),'D':(1,0)} self.score=0", "<gh_stars>0 class SnakeGame(object): def __init__(self, width,height,food): \"\"\" Initialize your data", "or \\ newj<0 or newj>=self.width: return -1 self.position.appendleft((newi,newj)) if self.food", "def move(self, direction): \"\"\" Moves the snake. @param direction -", "self.moveops={'U':(-1,0),'L':(0,-1),'R':(0,1),'D':(1,0)} self.score=0 def move(self, direction): \"\"\" Moves the snake. @param", "\"\"\" Initialize your data structure here. @param width - screen", ":type direction: str :rtype: int \"\"\" if direction not in", "self.position or \\ newi<0 or newi>=self.height or \\ newj<0 or", "not in self.moveops: return -1 peak,tail=self.position[0],self.position[-1] self.position.pop() idxi,idxj=self.moveops[direction] newi,newj=peak[0]+idxi,peak[1]+idxj if", "here. @param width - screen width @param height - screen", "in self.position or \\ newi<0 or newi>=self.height or \\ newj<0", ":type height: int :type food: List[List[int]] \"\"\" self.width=width self.height=height self.food=collections.deque(food)", "is at [1,0]. :type width: int :type height: int :type", "move(self, direction): \"\"\" Moves the snake. @param direction - 'U'", "as such: # obj = SnakeGame(width, height, food) # param_1", "peak,tail=self.position[0],self.position[-1] self.position.pop() idxi,idxj=self.moveops[direction] newi,newj=peak[0]+idxi,peak[1]+idxj if (newi,newj) in self.position or \\", "food is positioned at [1,1], the second is at [1,0].", "= Left, 'R' = Right, 'D' = Down @return The", "Game over when snake crosses the screen boundary or bites", "Return -1 if game over. Game over when snake crosses", "if self.food and [newi,newj]==self.food[0]: self.food.popleft() self.position.append(tail) self.score+=1 return self.score #", "crosses the screen boundary or bites its body. :type direction:", "direction: str :rtype: int \"\"\" if direction not in self.moveops:", "self.position.append(tail) self.score+=1 return self.score # Your SnakeGame object will be", "int :type food: List[List[int]] \"\"\" self.width=width self.height=height self.food=collections.deque(food) self.position=collections.deque([(0,0)]) self.moveops={'U':(-1,0),'L':(0,-1),'R':(0,1),'D':(1,0)}", "-1 peak,tail=self.position[0],self.position[-1] self.position.pop() idxi,idxj=self.moveops[direction] newi,newj=peak[0]+idxi,peak[1]+idxj if (newi,newj) in self.position or", "newj>=self.width: return -1 self.position.appendleft((newi,newj)) if self.food and [newi,newj]==self.food[0]: self.food.popleft() self.position.append(tail)", "and [newi,newj]==self.food[0]: self.food.popleft() self.position.append(tail) self.score+=1 return self.score # Your SnakeGame", "-1 if game over. Game over when snake crosses the", "self.food.popleft() self.position.append(tail) self.score+=1 return self.score # Your SnakeGame object will", "List[List[int]] \"\"\" self.width=width self.height=height self.food=collections.deque(food) self.position=collections.deque([(0,0)]) self.moveops={'U':(-1,0),'L':(0,-1),'R':(0,1),'D':(1,0)} self.score=0 def move(self,", "screen height @param food - A list of food positions", "int \"\"\" if direction not in self.moveops: return -1 peak,tail=self.position[0],self.position[-1]", "newi,newj=peak[0]+idxi,peak[1]+idxj if (newi,newj) in self.position or \\ newi<0 or newi>=self.height", "self.height=height self.food=collections.deque(food) self.position=collections.deque([(0,0)]) self.moveops={'U':(-1,0),'L':(0,-1),'R':(0,1),'D':(1,0)} self.score=0 def move(self, direction): \"\"\" Moves", "if (newi,newj) in self.position or \\ newi<0 or newi>=self.height or", "body. :type direction: str :rtype: int \"\"\" if direction not", "__init__(self, width,height,food): \"\"\" Initialize your data structure here. @param width", "direction not in self.moveops: return -1 peak,tail=self.position[0],self.position[-1] self.position.pop() idxi,idxj=self.moveops[direction] newi,newj=peak[0]+idxi,peak[1]+idxj", "after the move. Return -1 if game over. Game over", "-1 self.position.appendleft((newi,newj)) if self.food and [newi,newj]==self.food[0]: self.food.popleft() self.position.append(tail) self.score+=1 return", "positions E.g food = [[1,1], [1,0]] means the first food", "positioned at [1,1], the second is at [1,0]. :type width:", "= Down @return The game's score after the move. Return", "score after the move. Return -1 if game over. Game", "width: int :type height: int :type food: List[List[int]] \"\"\" self.width=width", "object will be instantiated and called as such: # obj", "of food positions E.g food = [[1,1], [1,0]] means the", "snake. @param direction - 'U' = Up, 'L' = Left,", "\"\"\" self.width=width self.height=height self.food=collections.deque(food) self.position=collections.deque([(0,0)]) self.moveops={'U':(-1,0),'L':(0,-1),'R':(0,1),'D':(1,0)} self.score=0 def move(self, direction):", "bites its body. :type direction: str :rtype: int \"\"\" if", "called as such: # obj = SnakeGame(width, height, food) #", "structure here. @param width - screen width @param height -", "Moves the snake. @param direction - 'U' = Up, 'L'", "direction - 'U' = Up, 'L' = Left, 'R' =", "such: # obj = SnakeGame(width, height, food) # param_1 =", "food: List[List[int]] \"\"\" self.width=width self.height=height self.food=collections.deque(food) self.position=collections.deque([(0,0)]) self.moveops={'U':(-1,0),'L':(0,-1),'R':(0,1),'D':(1,0)} self.score=0 def", "return self.score # Your SnakeGame object will be instantiated and", "self.width=width self.height=height self.food=collections.deque(food) self.position=collections.deque([(0,0)]) self.moveops={'U':(-1,0),'L':(0,-1),'R':(0,1),'D':(1,0)} self.score=0 def move(self, direction): \"\"\"", "screen boundary or bites its body. :type direction: str :rtype:", "at [1,0]. :type width: int :type height: int :type food:", "list of food positions E.g food = [[1,1], [1,0]] means", ":type width: int :type height: int :type food: List[List[int]] \"\"\"", "newi>=self.height or \\ newj<0 or newj>=self.width: return -1 self.position.appendleft((newi,newj)) if", "'U' = Up, 'L' = Left, 'R' = Right, 'D'", "return -1 self.position.appendleft((newi,newj)) if self.food and [newi,newj]==self.food[0]: self.food.popleft() self.position.append(tail) self.score+=1", "food positions E.g food = [[1,1], [1,0]] means the first", "self.score+=1 return self.score # Your SnakeGame object will be instantiated", "E.g food = [[1,1], [1,0]] means the first food is", "game's score after the move. Return -1 if game over.", "= Up, 'L' = Left, 'R' = Right, 'D' =" ]
[ "azul import ( config, require, ) from azul.logging import (", "= ( catalog.name for catalog in config.catalogs.values() if catalog.plugins['repository'] ==", "set(chain(*map(config.tdr_sources, tdr_catalogs))): source = TDRSourceName.parse(source) api_project = tdr.lookup_source_project(source) require(api_project ==", ") from azul.terra import ( TDRClient, TDRSourceName, ) log =", "= TDRSourceName.parse(source) api_project = tdr.lookup_source_project(source) require(api_project == source.project, 'Actual Google", "source differs from configured ' 'one', api_project, source) tdr.check_api_access(source) tdr.check_bigquery_access(source)", "tdr.lookup_source_project(source) require(api_project == source.project, 'Actual Google project of TDR source", ") import logging from azul import ( config, require, )", "'one', api_project, source) tdr.check_api_access(source) tdr.check_bigquery_access(source) if __name__ == '__main__': main()", "from azul.logging import ( configure_script_logging, ) from azul.terra import (", "== 'tdr' ) for source in set(chain(*map(config.tdr_sources, tdr_catalogs))): source =", "TDRClient() tdr.register_with_sam() tdr_catalogs = ( catalog.name for catalog in config.catalogs.values()", "source in set(chain(*map(config.tdr_sources, tdr_catalogs))): source = TDRSourceName.parse(source) api_project = tdr.lookup_source_project(source)", "( catalog.name for catalog in config.catalogs.values() if catalog.plugins['repository'] == 'tdr'", "catalog.plugins['repository'] == 'tdr' ) for source in set(chain(*map(config.tdr_sources, tdr_catalogs))): source", ") log = logging.getLogger(__name__) def main(): configure_script_logging(log) tdr = TDRClient()", "import logging from azul import ( config, require, ) from", "'tdr' ) for source in set(chain(*map(config.tdr_sources, tdr_catalogs))): source = TDRSourceName.parse(source)", ") for source in set(chain(*map(config.tdr_sources, tdr_catalogs))): source = TDRSourceName.parse(source) api_project", "import ( config, require, ) from azul.logging import ( configure_script_logging,", "tdr_catalogs = ( catalog.name for catalog in config.catalogs.values() if catalog.plugins['repository']", "catalog.name for catalog in config.catalogs.values() if catalog.plugins['repository'] == 'tdr' )", "== source.project, 'Actual Google project of TDR source differs from", "require, ) from azul.logging import ( configure_script_logging, ) from azul.terra", "TDRClient, TDRSourceName, ) log = logging.getLogger(__name__) def main(): configure_script_logging(log) tdr", "log = logging.getLogger(__name__) def main(): configure_script_logging(log) tdr = TDRClient() tdr.register_with_sam()", "in set(chain(*map(config.tdr_sources, tdr_catalogs))): source = TDRSourceName.parse(source) api_project = tdr.lookup_source_project(source) require(api_project", "from azul import ( config, require, ) from azul.logging import", "import ( configure_script_logging, ) from azul.terra import ( TDRClient, TDRSourceName,", "= logging.getLogger(__name__) def main(): configure_script_logging(log) tdr = TDRClient() tdr.register_with_sam() tdr_catalogs", "main(): configure_script_logging(log) tdr = TDRClient() tdr.register_with_sam() tdr_catalogs = ( catalog.name", "for catalog in config.catalogs.values() if catalog.plugins['repository'] == 'tdr' ) for", "TDRSourceName, ) log = logging.getLogger(__name__) def main(): configure_script_logging(log) tdr =", "catalog in config.catalogs.values() if catalog.plugins['repository'] == 'tdr' ) for source", "differs from configured ' 'one', api_project, source) tdr.check_api_access(source) tdr.check_bigquery_access(source) if", "for source in set(chain(*map(config.tdr_sources, tdr_catalogs))): source = TDRSourceName.parse(source) api_project =", "' 'one', api_project, source) tdr.check_api_access(source) tdr.check_bigquery_access(source) if __name__ == '__main__':", ") from azul.logging import ( configure_script_logging, ) from azul.terra import", "azul.terra import ( TDRClient, TDRSourceName, ) log = logging.getLogger(__name__) def", "import ( TDRClient, TDRSourceName, ) log = logging.getLogger(__name__) def main():", "configure_script_logging(log) tdr = TDRClient() tdr.register_with_sam() tdr_catalogs = ( catalog.name for", "( TDRClient, TDRSourceName, ) log = logging.getLogger(__name__) def main(): configure_script_logging(log)", "in config.catalogs.values() if catalog.plugins['repository'] == 'tdr' ) for source in", "= tdr.lookup_source_project(source) require(api_project == source.project, 'Actual Google project of TDR", "source = TDRSourceName.parse(source) api_project = tdr.lookup_source_project(source) require(api_project == source.project, 'Actual", "api_project = tdr.lookup_source_project(source) require(api_project == source.project, 'Actual Google project of", "logging from azul import ( config, require, ) from azul.logging", "TDRSourceName.parse(source) api_project = tdr.lookup_source_project(source) require(api_project == source.project, 'Actual Google project", "chain, ) import logging from azul import ( config, require,", "configured ' 'one', api_project, source) tdr.check_api_access(source) tdr.check_bigquery_access(source) if __name__ ==", "logging.getLogger(__name__) def main(): configure_script_logging(log) tdr = TDRClient() tdr.register_with_sam() tdr_catalogs =", "= TDRClient() tdr.register_with_sam() tdr_catalogs = ( catalog.name for catalog in", "if catalog.plugins['repository'] == 'tdr' ) for source in set(chain(*map(config.tdr_sources, tdr_catalogs))):", "tdr.register_with_sam() tdr_catalogs = ( catalog.name for catalog in config.catalogs.values() if", "Google project of TDR source differs from configured ' 'one',", "( config, require, ) from azul.logging import ( configure_script_logging, )", "( chain, ) import logging from azul import ( config,", "config, require, ) from azul.logging import ( configure_script_logging, ) from", "def main(): configure_script_logging(log) tdr = TDRClient() tdr.register_with_sam() tdr_catalogs = (", "tdr = TDRClient() tdr.register_with_sam() tdr_catalogs = ( catalog.name for catalog", "source.project, 'Actual Google project of TDR source differs from configured", "import ( chain, ) import logging from azul import (", "( configure_script_logging, ) from azul.terra import ( TDRClient, TDRSourceName, )", "itertools import ( chain, ) import logging from azul import", "of TDR source differs from configured ' 'one', api_project, source)", "TDR source differs from configured ' 'one', api_project, source) tdr.check_api_access(source)", "from azul.terra import ( TDRClient, TDRSourceName, ) log = logging.getLogger(__name__)", "from itertools import ( chain, ) import logging from azul", "'Actual Google project of TDR source differs from configured '", "config.catalogs.values() if catalog.plugins['repository'] == 'tdr' ) for source in set(chain(*map(config.tdr_sources,", "tdr_catalogs))): source = TDRSourceName.parse(source) api_project = tdr.lookup_source_project(source) require(api_project == source.project,", "project of TDR source differs from configured ' 'one', api_project,", "azul.logging import ( configure_script_logging, ) from azul.terra import ( TDRClient,", "from configured ' 'one', api_project, source) tdr.check_api_access(source) tdr.check_bigquery_access(source) if __name__", "require(api_project == source.project, 'Actual Google project of TDR source differs", "configure_script_logging, ) from azul.terra import ( TDRClient, TDRSourceName, ) log" ]
[ "self.loads_map = True self.joined_after_change_map = True class Players: def __init__(self,", "player.nickname = new_nickname break def all_nicknames(self): return [player.nickname for player", "__init__(self, nickname, vapor_id, player_id, ip): self.nickname = nickname self.vapor_id =", "class Player: def __init__(self, nickname, vapor_id, player_id, ip): self.nickname =", "return player def get_all_vapor_ids(self): return [player.vapor_id for player in self.players]", "for player in self.players: if vapor_id == player.vapor_id: return player", "player_from_vapor_id(self, vapor_id): for player in self.players: if vapor_id == player.vapor_id:", "self.joined_after_change_map = True class Players: def __init__(self, main_object, modded, lobby):", "player.not_joined self.main.on_client_join(player) if self.check_if_everyone_joined_after_change_map(): self.map_changed = False def check_nickname_existence(self, nickname):", "get_all_players(self, nicknames, vapor_ids, player_ids, ips): players_list = [nicknames, vapor_ids, player_ids,", "vapor_id, player_id, ip): self.nickname = nickname self.vapor_id = vapor_id self.player_id", "if player.loads_map and player.joined_after_change_map: player.joined_after_change_map = False elif player.loads_map and", "= True self.loads_map = True self.joined_after_change_map = True class Players:", "self.players: for player in self.players: player.loads_map = True def check_if_everyone_joined_after_change_map(self):", "self.player_id = player_id self.ip = ip self.not_joined = True self.loads_map", "= nickname self.vapor_id = vapor_id self.player_id = player_id self.ip =", "self.commands.change_map(self.lobby) def nickname_change(self, old_nickname, new_nickname): for player in self.players: if", "player.joined_after_change_map: player.loads_map = False player.joined_after_change_map = True self.main.on_player_map_change(player, self.map_changed) if", "lobby self.commands = None def get_commands_object(self, commands_object): self.commands = commands_object", "nickname, vapor_id, player_id, ip): self.nickname = nickname self.vapor_id = vapor_id", "= False self.lobby = lobby self.commands = None def get_commands_object(self,", "range(len(nicknames)): self.players.append(Player(*[player[count] for player in players_list])) def add(self, nickname, vapor_id,", "player.loads_map = True def check_if_everyone_joined_after_change_map(self): for player in self.players: if", "elif player.loads_map and not player.joined_after_change_map: player.loads_map = False player.joined_after_change_map =", "hasattr(player, \"not_joined\"): del player.not_joined self.main.on_client_join(player) if self.check_if_everyone_joined_after_change_map(): self.map_changed = False", "[nicknames, vapor_ids, player_ids, ips] for count in range(len(nicknames)): self.players.append(Player(*[player[count] for", "self.players.append(Player(*[player[count] for player in players_list])) def add(self, nickname, vapor_id, player_id,", "self.players: if nickname == player.nickname: self.players.remove(player) break if self.lobby and", "break def all_nicknames(self): return [player.nickname for player in self.players] def", "player_id): for player in self.players: if player_id == player.player_id: return", "class Players: def __init__(self, main_object, modded, lobby): self.main = main_object", "True self.main.on_player_map_change(player, self.map_changed) if hasattr(player, \"not_joined\"): del player.not_joined self.main.on_client_join(player) if", "hasattr(player, \"not_joined\"): if player.loads_map and player.joined_after_change_map: player.joined_after_change_map = False elif", "= vapor_id self.player_id = player_id self.ip = ip self.not_joined =", "return True return False def get_all_players(self, nicknames, vapor_ids, player_ids, ips):", "if self.lobby and len(self.players) == 0: self.commands.change_map(self.lobby) def nickname_change(self, old_nickname,", "player.loads_map and not player.joined_after_change_map: return False return True def _on_player_info_ev(self,", "return True def _on_player_info_ev(self, player_id): player = [player for player", "= new_nickname break def all_nicknames(self): return [player.nickname for player in", "new_nickname): for player in self.players: if old_nickname == player.nickname: player.nickname", "return False return True def _on_player_info_ev(self, player_id): player = [player", "not player.joined_after_change_map: player.loads_map = False player.joined_after_change_map = True self.main.on_player_map_change(player, self.map_changed)", "self.players: if old_nickname == player.nickname: player.nickname = new_nickname break def", "vapor_id == player.vapor_id: return player def player_from_player_id(self, player_id): for player", "def add(self, nickname, vapor_id, player_id, ip): self.players.append(Player(nickname, vapor_id, player_id, ip))", "players_list])) def add(self, nickname, vapor_id, player_id, ip): self.players.append(Player(nickname, vapor_id, player_id,", "self.players: player.loads_map = True def check_if_everyone_joined_after_change_map(self): for player in self.players:", "player.joined_after_change_map = False elif player.loads_map and not player.joined_after_change_map: player.loads_map =", "all_nicknames(self): return [player.nickname for player in self.players] def player_from_nickname(self, nickname):", "def player_from_vapor_id(self, vapor_id): for player in self.players: if vapor_id ==", "player.loads_map and player.joined_after_change_map: player.joined_after_change_map = False elif player.loads_map and not", "count in range(len(nicknames)): self.players.append(Player(*[player[count] for player in players_list])) def add(self,", "= True def check_if_everyone_joined_after_change_map(self): for player in self.players: if player.loads_map", "in self.players: player.loads_map = True def check_if_everyone_joined_after_change_map(self): for player in", "True def check_if_everyone_joined_after_change_map(self): for player in self.players: if player.loads_map and", "commands_object): self.commands = commands_object def _on_map_change(self, map_name): self.map_changed = map_name", "map_name): self.map_changed = map_name if self.modded and self.players: for player", "= [player for player in self.players if player.player_id == player_id][0]", "False def get_all_players(self, nicknames, vapor_ids, player_ids, ips): players_list = [nicknames,", "player in self.players: if nickname == player.nickname: self.players.remove(player) break if", "old_nickname == player.nickname: player.nickname = new_nickname break def all_nicknames(self): return", "if nickname == player.nickname: return True return False def get_all_players(self,", "in self.players: if nickname == player.nickname: return True return False", "nickname): for player in self.players: if nickname == player.nickname: return", "player.nickname: player.nickname = new_nickname break def all_nicknames(self): return [player.nickname for", "and not player.joined_after_change_map: player.loads_map = False player.joined_after_change_map = True self.main.on_player_map_change(player,", "if vapor_id == player.vapor_id: return player def player_from_player_id(self, player_id): for", "def player_from_player_id(self, player_id): for player in self.players: if player_id ==", "= [] self.modded = modded self.map_changed = False self.lobby =", "new_nickname break def all_nicknames(self): return [player.nickname for player in self.players]", "self.check_if_everyone_joined_after_change_map(): self.map_changed = False def check_nickname_existence(self, nickname): for player in", "= True self.main.on_player_map_change(player, self.map_changed) if hasattr(player, \"not_joined\"): del player.not_joined self.main.on_client_join(player)", "and self.players: for player in self.players: player.loads_map = True def", "self.main.on_client_join(player) if self.check_if_everyone_joined_after_change_map(): self.map_changed = False def check_nickname_existence(self, nickname): for", "def _on_player_info_ev(self, player_id): player = [player for player in self.players", "== 0: self.commands.change_map(self.lobby) def nickname_change(self, old_nickname, new_nickname): for player in", "= True self.joined_after_change_map = True class Players: def __init__(self, main_object,", "return player def player_from_vapor_id(self, vapor_id): for player in self.players: if", "nickname, vapor_id, player_id, ip): self.players.append(Player(nickname, vapor_id, player_id, ip)) def remove(self,", "self.modded and self.players: for player in self.players: player.loads_map = True", "None def get_commands_object(self, commands_object): self.commands = commands_object def _on_map_change(self, map_name):", "\"not_joined\"): if player.loads_map and player.joined_after_change_map: player.joined_after_change_map = False elif player.loads_map", "def all_nicknames(self): return [player.nickname for player in self.players] def player_from_nickname(self,", "and not player.joined_after_change_map: return False return True def _on_player_info_ev(self, player_id):", "vapor_id): for player in self.players: if vapor_id == player.vapor_id: return", "def check_nickname_existence(self, nickname): for player in self.players: if nickname ==", "= False elif player.loads_map and not player.joined_after_change_map: player.loads_map = False", "if nickname == player.nickname: self.players.remove(player) break if self.lobby and len(self.players)", "for player in self.players: if player.loads_map and not player.joined_after_change_map: return", "return [player.nickname for player in self.players] def player_from_nickname(self, nickname): for", "self.not_joined = True self.loads_map = True self.joined_after_change_map = True class", "main_object, modded, lobby): self.main = main_object self.players = [] self.modded", "def get_commands_object(self, commands_object): self.commands = commands_object def _on_map_change(self, map_name): self.map_changed", "if self.modded and self.players: for player in self.players: player.loads_map =", "== player_id][0] if self.map_changed or hasattr(player, \"not_joined\"): if player.loads_map and", "for player in self.players: if nickname == player.nickname: return True", "== player.nickname: player.nickname = new_nickname break def all_nicknames(self): return [player.nickname", "self.main = main_object self.players = [] self.modded = modded self.map_changed", "self.players: if nickname == player.nickname: return True return False def", "False elif player.loads_map and not player.joined_after_change_map: player.loads_map = False player.joined_after_change_map", "def nickname_change(self, old_nickname, new_nickname): for player in self.players: if old_nickname", "if old_nickname == player.nickname: player.nickname = new_nickname break def all_nicknames(self):", "False def check_nickname_existence(self, nickname): for player in self.players: if nickname", "ip): self.nickname = nickname self.vapor_id = vapor_id self.player_id = player_id", "nicknames, vapor_ids, player_ids, ips): players_list = [nicknames, vapor_ids, player_ids, ips]", "vapor_id, player_id, ip): self.players.append(Player(nickname, vapor_id, player_id, ip)) def remove(self, nickname):", "= lobby self.commands = None def get_commands_object(self, commands_object): self.commands =", "get_commands_object(self, commands_object): self.commands = commands_object def _on_map_change(self, map_name): self.map_changed =", "False return True def _on_player_info_ev(self, player_id): player = [player for", "self.lobby and len(self.players) == 0: self.commands.change_map(self.lobby) def nickname_change(self, old_nickname, new_nickname):", "vapor_ids, player_ids, ips] for count in range(len(nicknames)): self.players.append(Player(*[player[count] for player", "nickname self.vapor_id = vapor_id self.player_id = player_id self.ip = ip", "in self.players: if old_nickname == player.nickname: player.nickname = new_nickname break", "self.players: if player_id == player.player_id: return player def get_all_vapor_ids(self): return", "self.commands = commands_object def _on_map_change(self, map_name): self.map_changed = map_name if", "player_id][0] if self.map_changed or hasattr(player, \"not_joined\"): if player.loads_map and player.joined_after_change_map:", "player.nickname: return player def player_from_vapor_id(self, vapor_id): for player in self.players:", "nickname == player.nickname: return player def player_from_vapor_id(self, vapor_id): for player", "True self.joined_after_change_map = True class Players: def __init__(self, main_object, modded,", "commands_object def _on_map_change(self, map_name): self.map_changed = map_name if self.modded and", "old_nickname, new_nickname): for player in self.players: if old_nickname == player.nickname:", "self.players.append(Player(nickname, vapor_id, player_id, ip)) def remove(self, nickname): for player in", "[player.nickname for player in self.players] def player_from_nickname(self, nickname): for player", "self.players: if player.loads_map and not player.joined_after_change_map: return False return True", "self.players] def player_from_nickname(self, nickname): for player in self.players: if nickname", "if player_id == player.player_id: return player def get_all_vapor_ids(self): return [player.vapor_id", "player.player_id: return player def get_all_vapor_ids(self): return [player.vapor_id for player in", "player in self.players: player.loads_map = True def check_if_everyone_joined_after_change_map(self): for player", "= None def get_commands_object(self, commands_object): self.commands = commands_object def _on_map_change(self,", "nickname == player.nickname: return True return False def get_all_players(self, nicknames,", "player.player_id == player_id][0] if self.map_changed or hasattr(player, \"not_joined\"): if player.loads_map", "self.ip = ip self.not_joined = True self.loads_map = True self.joined_after_change_map", "in self.players] def player_from_nickname(self, nickname): for player in self.players: if", "player_id): player = [player for player in self.players if player.player_id", "in self.players: if nickname == player.nickname: self.players.remove(player) break if self.lobby", "def player_from_nickname(self, nickname): for player in self.players: if nickname ==", "for player in self.players: if nickname == player.nickname: return player", "in self.players: if nickname == player.nickname: return player def player_from_vapor_id(self,", "add(self, nickname, vapor_id, player_id, ip): self.players.append(Player(nickname, vapor_id, player_id, ip)) def", "def remove(self, nickname): for player in self.players: if nickname ==", "player def player_from_vapor_id(self, vapor_id): for player in self.players: if vapor_id", "_on_player_info_ev(self, player_id): player = [player for player in self.players if", "self.players: if nickname == player.nickname: return player def player_from_vapor_id(self, vapor_id):", "for player in self.players if player.player_id == player_id][0] if self.map_changed", "player_id, ip): self.players.append(Player(nickname, vapor_id, player_id, ip)) def remove(self, nickname): for", "player in self.players] def player_from_nickname(self, nickname): for player in self.players:", "self.main.on_player_map_change(player, self.map_changed) if hasattr(player, \"not_joined\"): del player.not_joined self.main.on_client_join(player) if self.check_if_everyone_joined_after_change_map():", "nickname): for player in self.players: if nickname == player.nickname: self.players.remove(player)", "Player: def __init__(self, nickname, vapor_id, player_id, ip): self.nickname = nickname", "player_id, ip): self.nickname = nickname self.vapor_id = vapor_id self.player_id =", "player def player_from_player_id(self, player_id): for player in self.players: if player_id", "player_id == player.player_id: return player def get_all_vapor_ids(self): return [player.vapor_id for", "and player.joined_after_change_map: player.joined_after_change_map = False elif player.loads_map and not player.joined_after_change_map:", "if player.loads_map and not player.joined_after_change_map: return False return True def", "== player.nickname: return True return False def get_all_players(self, nicknames, vapor_ids,", "check_nickname_existence(self, nickname): for player in self.players: if nickname == player.nickname:", "nickname == player.nickname: self.players.remove(player) break if self.lobby and len(self.players) ==", "self.map_changed = map_name if self.modded and self.players: for player in", "= commands_object def _on_map_change(self, map_name): self.map_changed = map_name if self.modded", "player in self.players: if nickname == player.nickname: return True return", "ip)) def remove(self, nickname): for player in self.players: if nickname", "nickname_change(self, old_nickname, new_nickname): for player in self.players: if old_nickname ==", "player in self.players: if player_id == player.player_id: return player def", "if player.player_id == player_id][0] if self.map_changed or hasattr(player, \"not_joined\"): if", "del player.not_joined self.main.on_client_join(player) if self.check_if_everyone_joined_after_change_map(): self.map_changed = False def check_nickname_existence(self,", "return False def get_all_players(self, nicknames, vapor_ids, player_ids, ips): players_list =", "player.joined_after_change_map: return False return True def _on_player_info_ev(self, player_id): player =", "in self.players: if vapor_id == player.vapor_id: return player def player_from_player_id(self,", "self.vapor_id = vapor_id self.player_id = player_id self.ip = ip self.not_joined", "player = [player for player in self.players if player.player_id ==", "player.nickname: return True return False def get_all_players(self, nicknames, vapor_ids, player_ids,", "self.players: if vapor_id == player.vapor_id: return player def player_from_player_id(self, player_id):", "player in self.players if player.player_id == player_id][0] if self.map_changed or", "False self.lobby = lobby self.commands = None def get_commands_object(self, commands_object):", "def get_all_players(self, nicknames, vapor_ids, player_ids, ips): players_list = [nicknames, vapor_ids,", "= player_id self.ip = ip self.not_joined = True self.loads_map =", "player_ids, ips] for count in range(len(nicknames)): self.players.append(Player(*[player[count] for player in", "for count in range(len(nicknames)): self.players.append(Player(*[player[count] for player in players_list])) def", "player in self.players: if player.loads_map and not player.joined_after_change_map: return False", "== player.player_id: return player def get_all_vapor_ids(self): return [player.vapor_id for player", "_on_map_change(self, map_name): self.map_changed = map_name if self.modded and self.players: for", "main_object self.players = [] self.modded = modded self.map_changed = False", "player.loads_map = False player.joined_after_change_map = True self.main.on_player_map_change(player, self.map_changed) if hasattr(player,", "True self.loads_map = True self.joined_after_change_map = True class Players: def", "player.nickname: self.players.remove(player) break if self.lobby and len(self.players) == 0: self.commands.change_map(self.lobby)", "player_id self.ip = ip self.not_joined = True self.loads_map = True", "self.map_changed = False self.lobby = lobby self.commands = None def", "player in self.players: if nickname == player.nickname: return player def", "for player in self.players: if nickname == player.nickname: self.players.remove(player) break", "player_from_player_id(self, player_id): for player in self.players: if player_id == player.player_id:", "len(self.players) == 0: self.commands.change_map(self.lobby) def nickname_change(self, old_nickname, new_nickname): for player", "= map_name if self.modded and self.players: for player in self.players:", "ips): players_list = [nicknames, vapor_ids, player_ids, ips] for count in", "player_id, ip)) def remove(self, nickname): for player in self.players: if", "in range(len(nicknames)): self.players.append(Player(*[player[count] for player in players_list])) def add(self, nickname,", "True class Players: def __init__(self, main_object, modded, lobby): self.main =", "player.joined_after_change_map: player.joined_after_change_map = False elif player.loads_map and not player.joined_after_change_map: player.loads_map", "in self.players: if player.loads_map and not player.joined_after_change_map: return False return", "for player in self.players: player.loads_map = True def check_if_everyone_joined_after_change_map(self): for", "player in self.players: if old_nickname == player.nickname: player.nickname = new_nickname", "if nickname == player.nickname: return player def player_from_vapor_id(self, vapor_id): for", "for player in self.players] def player_from_nickname(self, nickname): for player in", "= ip self.not_joined = True self.loads_map = True self.joined_after_change_map =", "self.players = [] self.modded = modded self.map_changed = False self.lobby", "and len(self.players) == 0: self.commands.change_map(self.lobby) def nickname_change(self, old_nickname, new_nickname): for", "True return False def get_all_players(self, nicknames, vapor_ids, player_ids, ips): players_list", "= False def check_nickname_existence(self, nickname): for player in self.players: if", "= False player.joined_after_change_map = True self.main.on_player_map_change(player, self.map_changed) if hasattr(player, \"not_joined\"):", "player in self.players: if vapor_id == player.vapor_id: return player def", "if self.map_changed or hasattr(player, \"not_joined\"): if player.loads_map and player.joined_after_change_map: player.joined_after_change_map", "in self.players: if player_id == player.player_id: return player def get_all_vapor_ids(self):", "self.players.remove(player) break if self.lobby and len(self.players) == 0: self.commands.change_map(self.lobby) def", "lobby): self.main = main_object self.players = [] self.modded = modded", "Players: def __init__(self, main_object, modded, lobby): self.main = main_object self.players", "= True class Players: def __init__(self, main_object, modded, lobby): self.main", "== player.nickname: self.players.remove(player) break if self.lobby and len(self.players) == 0:", "def check_if_everyone_joined_after_change_map(self): for player in self.players: if player.loads_map and not", "= [nicknames, vapor_ids, player_ids, ips] for count in range(len(nicknames)): self.players.append(Player(*[player[count]", "self.nickname = nickname self.vapor_id = vapor_id self.player_id = player_id self.ip", "ip self.not_joined = True self.loads_map = True self.joined_after_change_map = True", "0: self.commands.change_map(self.lobby) def nickname_change(self, old_nickname, new_nickname): for player in self.players:", "player_ids, ips): players_list = [nicknames, vapor_ids, player_ids, ips] for count", "modded self.map_changed = False self.lobby = lobby self.commands = None", "for player in self.players: if player_id == player.player_id: return player", "or hasattr(player, \"not_joined\"): if player.loads_map and player.joined_after_change_map: player.joined_after_change_map = False", "def __init__(self, nickname, vapor_id, player_id, ip): self.nickname = nickname self.vapor_id", "if hasattr(player, \"not_joined\"): del player.not_joined self.main.on_client_join(player) if self.check_if_everyone_joined_after_change_map(): self.map_changed =", "__init__(self, main_object, modded, lobby): self.main = main_object self.players = []", "in self.players if player.player_id == player_id][0] if self.map_changed or hasattr(player,", "\"not_joined\"): del player.not_joined self.main.on_client_join(player) if self.check_if_everyone_joined_after_change_map(): self.map_changed = False def", "False player.joined_after_change_map = True self.main.on_player_map_change(player, self.map_changed) if hasattr(player, \"not_joined\"): del", "players_list = [nicknames, vapor_ids, player_ids, ips] for count in range(len(nicknames)):", "self.commands = None def get_commands_object(self, commands_object): self.commands = commands_object def", "player in players_list])) def add(self, nickname, vapor_id, player_id, ip): self.players.append(Player(nickname,", "for player in players_list])) def add(self, nickname, vapor_id, player_id, ip):", "= main_object self.players = [] self.modded = modded self.map_changed =", "in players_list])) def add(self, nickname, vapor_id, player_id, ip): self.players.append(Player(nickname, vapor_id,", "self.lobby = lobby self.commands = None def get_commands_object(self, commands_object): self.commands", "player.joined_after_change_map = True self.main.on_player_map_change(player, self.map_changed) if hasattr(player, \"not_joined\"): del player.not_joined", "== player.nickname: return player def player_from_vapor_id(self, vapor_id): for player in", "check_if_everyone_joined_after_change_map(self): for player in self.players: if player.loads_map and not player.joined_after_change_map:", "self.players if player.player_id == player_id][0] if self.map_changed or hasattr(player, \"not_joined\"):", "self.map_changed = False def check_nickname_existence(self, nickname): for player in self.players:", "vapor_id, player_id, ip)) def remove(self, nickname): for player in self.players:", "not player.joined_after_change_map: return False return True def _on_player_info_ev(self, player_id): player", "player.loads_map and not player.joined_after_change_map: player.loads_map = False player.joined_after_change_map = True", "player.vapor_id: return player def player_from_player_id(self, player_id): for player in self.players:", "remove(self, nickname): for player in self.players: if nickname == player.nickname:", "vapor_id self.player_id = player_id self.ip = ip self.not_joined = True", "modded, lobby): self.main = main_object self.players = [] self.modded =", "ip): self.players.append(Player(nickname, vapor_id, player_id, ip)) def remove(self, nickname): for player", "break if self.lobby and len(self.players) == 0: self.commands.change_map(self.lobby) def nickname_change(self,", "= modded self.map_changed = False self.lobby = lobby self.commands =", "self.map_changed or hasattr(player, \"not_joined\"): if player.loads_map and player.joined_after_change_map: player.joined_after_change_map =", "self.modded = modded self.map_changed = False self.lobby = lobby self.commands", "def __init__(self, main_object, modded, lobby): self.main = main_object self.players =", "== player.vapor_id: return player def player_from_player_id(self, player_id): for player in", "[] self.modded = modded self.map_changed = False self.lobby = lobby", "if self.check_if_everyone_joined_after_change_map(): self.map_changed = False def check_nickname_existence(self, nickname): for player", "True def _on_player_info_ev(self, player_id): player = [player for player in", "def _on_map_change(self, map_name): self.map_changed = map_name if self.modded and self.players:", "for player in self.players: if old_nickname == player.nickname: player.nickname =", "self.map_changed) if hasattr(player, \"not_joined\"): del player.not_joined self.main.on_client_join(player) if self.check_if_everyone_joined_after_change_map(): self.map_changed", "player_from_nickname(self, nickname): for player in self.players: if nickname == player.nickname:", "return player def player_from_player_id(self, player_id): for player in self.players: if", "map_name if self.modded and self.players: for player in self.players: player.loads_map", "ips] for count in range(len(nicknames)): self.players.append(Player(*[player[count] for player in players_list]))", "vapor_ids, player_ids, ips): players_list = [nicknames, vapor_ids, player_ids, ips] for", "[player for player in self.players if player.player_id == player_id][0] if" ]
[ "'children'): return an_error() # The target must be a node", "a \"replace with the parent\"; if (or when) we'll introduce", "but I'd rather move in the # direction of \"relax", "edit_note.text) return edit_note.s_address, posacts, False if isinstance(edit_note, InsertNodeSibbling): if structure.s_cursor", "return new_cursor, [], False if isinstance(edit_note, CursorDFS): dfs = s_dfs(structure.tree,", "node: fall back to the parent new_cursor = parent_s_address else:", "add a child node to a non-node return an_error() index", "Note\") def do_move(structure, edit_note, target_parent_path, target_index): selection_edge_0 = edit_note.selection_edge_0 selection_edge_1", "insert_hash = node_for_s_address(structure.tree, source_parent_path + [source_index]).metadata.nout_hash p, hash_ = calc_possibility(NoteSlur(Insert(target_index", "1: # if the deleted node was the only node:", "Delete n times at the \"lo\" index (everything shifting to", "+ weave_disjoint_replaces( structure.tree, target_parent_path, wdr_hash, source_parent_path, hash_) else: posacts =", "a sense that it may # create some asymmetries. For", "express \"weave those together, rewriting indices as required\". # In", "a child node to a non-node return an_error() index =", "return an_error() source_parent_path = selection_edge_0[:-1] source_parent = node_for_s_address(structure.tree, source_parent_path) target_parent", "we add \"Move\" to the # clef. # Another way", "new_s_cursor = delete_from else: new_s_cursor = structure.s_cursor # \"stay in", "as a \"replace with the parent\"; if (or when) we'll", "the MoveReplace) into the Clef, we should note the move", "ancestor or [b] to not care so # much about", "# point of view in a non-atomic way in the", "everything descends from the root node) return an_error() source_parent_path =", "# we do _not_ fetch hash_ here, the idea being:", "to continue operating on the the same \"future\". But in", "TextInsert): posacts = insert_text_at(structure.tree, edit_note.parent_s_address, edit_note.index, edit_note.text) new_s_cursor = edit_note.parent_s_address", "posacts, False if isinstance(edit_note, SwapSibbling): if structure.s_cursor == []: return", "structure.s_cursor) if not hasattr(cursor_node, 'children'): return an_error() # The target", "with the general idea of \"we only check that the", "somehow connect the parents.... # (For the case of \"parents", "def an_error(): return structure.s_cursor, [], True if selection_edge_0[:-1] != selection_edge_1[:-1]:", "point, we do not check for arbitrary programming errors here).", "structure.tree, parent_s_address) return new_cursor, posacts, False if isinstance(edit_note, EncloseWithParent): cursor_node", "This is illegal. Moving something to a child of itself:", "= [] source_index_lo, source_index_hi = sorted([selection_edge_0[-1], selection_edge_1[-1]]) hash_ = target_parent.metadata.nout_hash", "sibblings parent = node_for_s_address(structure.tree, s_cursor[:-1]) index = s_cursor[-1] + edit_node.direction", "return move_cursor(s_cursor[:-1] + [index]) \"\"\" if isinstance(edit_note, CursorSet): return move_cursor(edit_note.s_address)", "precisely the # number of insertions that happened. (If we", "before we delete. If we do this on the same", "Note: we just Delete n times at the \"lo\" index", "(said differently: # the longest_common_prefix of both parents matches one", "- 1): return an_error() return move_cursor(dfs[dfs_index]) \"\"\"At some point I", "the same parent, and the insertions happen at lower indices", "i, child in enumerate(removed_node.children): p, hash_ = calc_possibility(NoteSlur(Insert(structure.s_cursor[-1] + i,", "sibblings to the root is not possible (it would lead", "I am not sure about this one yet: should we", "if (or when) we'll introduce # \"Move\" into the Clef,", "should note the move here. parent_s_address = structure.s_cursor[:-1] delete_at_index =", "is assumed to exist.) return an_error() delete_from = structure.s_cursor[:-1] delete_at_index", "such assumptions fit with the general idea of \"we only", "== []: # I am not sure about this one", "structure.s_cursor[:-1], structure.s_cursor[-1] + edit_note.direction) if isinstance(edit_note, LeaveChildrenBehind): cursor_node = node_for_s_address(structure.tree,", "- 1): return an_error() return move_cursor(s_cursor[:-1] + [index]) \"\"\" if", "do_move(structure, edit_note, target_parent_path, target_index): selection_edge_0 = edit_note.selection_edge_0 selection_edge_1 = edit_note.selection_edge_1", "assumed to exist.) return an_error() delete_from = structure.s_cursor[:-1] delete_at_index =", "node_for_s_address(structure.tree, target_parent_path) # For now, the \"edit move\" operations are", "return an_error() return move_cursor(dfs[dfs_index]) \"\"\"At some point I had \"regular", "we delete. If we do this on the same parent,", "sibblings) new_s_cursor = delete_from else: new_s_cursor = structure.s_cursor # \"stay", "= dfs.index(structure.s_cursor) + edit_note.direction if not (0 <= dfs_index <=", "= calc_possibility(NoteSlur(Insert(structure.s_cursor[-1] + i, child.metadata.nout_hash), hash_)) posacts.append(p) # In general,", "the deletions must take place, by precisely the # number", "I did this using the idea \"just don't reset hash_\"...", "of itself: # I simply don't know what it would", "hash_ here, the idea being: it's the hash we just", "[target_index])[:len(selection_edge_0)] <= selection_edge_1: # If the full target location, truncated", "introduce # \"Move\" into the Clef, we should note the", "root is not possible (it would lead to a forest)", "some tools to \"realinearize while preserving # meaning\". I.e. we", "ask to add a child node to a non-node return", "the \"edit move\" operations are simply implemented as a \"insert", "[0, 1]; such assumptions fit with the general idea of", "the same s_address will be great: post-deletion you'll be in", "return new_s_cursor, posacts, False if isinstance(edit_note, EDelete): if structure.s_cursor ==", "\"be smart about the meaning of the selection's # edges\",", "return an_error() # adding sibblings to the root is not", "problem at all, is because we implement something that is", "weave_disjoint_replaces( structure.tree, target_parent_path, wdr_hash, source_parent_path, hash_) else: posacts = posacts", "there is no sibbling of the root node # edit_note.direction", "we just Delete n times at the \"lo\" index (everything", "from the user's # point of view in a non-atomic", "move\" is \"at the end\". This \"seems intuitive\" (but #", "the # source node, such a single-parent restriction is indeed", "This \"seems intuitive\" (but # that may just be habituation).", "may be illegal parent_node = node_for_s_address(structure.tree, parent_s_address) if len(parent_node.children) ==", "the below, we often connect notes together \"manually\", i.e. using", "return move_cursor(structure.s_cursor + [0]) raise Exception(\"Unknown Note\") def do_move(structure, edit_note,", "\"\"\" if isinstance(edit_note, CursorSet): return move_cursor(edit_note.s_address) if isinstance(edit_note, CursorParent): if", "no-op, so it's slightly less # meaningless, but here I", "illegal. Moving something to a child of itself: # I", "this on the same parent, and the insertions happen at", "[0] return new_cursor, posacts, False def move_cursor(new_cursor): return new_cursor, [],", "any case, it's wat e.g. LibreOffice does when cut/pasting. (However,", "the selection appear at the target-location, we need to change", "node to be able to add as a child return", "delete_from_hash = node_for_s_address(structure.tree, parent_s_address).metadata.nout_hash p, hash_ = calc_possibility(NoteSlur(Delete(delete_at_index), delete_from_hash)) posacts", "from dsn.s_expr.utils import ( bubble_history_up, calc_possibility, insert_text_at, insert_node_at, replace_text_at, weave_disjoint_replaces,", "if len(removed_node.children) == 0: # ... however, if there are", "or [b] to not care so # much about single-parent.", "hash_)) posacts.append(p) weave_correction = 0 cursor_correction = 0 # TODO", "(alternative: sibbling-up first, until no more sibblings) new_s_cursor = delete_from", "[p0, p1] + bubble_history_up(hash_after_insertion, structure.tree, parent_s_address) return new_cursor, posacts, False", "ignore the user's request when they ask to add a", "hash_ = calc_possibility(NoteSlur(Insert(structure.s_cursor[-1] + i, child.metadata.nout_hash), hash_)) posacts.append(p) # In", "where the deletions must take place, by precisely the #", "not hasattr(cursor_node, 'children'): return an_error() # Leave _children_ behind presupposes", "to the left after each deletion) p, hash_ = calc_possibility(NoteSlur(Delete(source_index_lo", "child.metadata.nout_hash), hash_)) posacts.append(p) # In general, leaving the cursor at", "1 idiom; -1 for deletion. new_cursor[len(new_cursor) - 1]) posacts +=", "of \"parents match exactly\", I did this using the idea", "than the deletions, they will affect the locations where the", "ancestor and the relevant children of that ancestor or [b]", "new_s_cursor, posacts, False if isinstance(edit_note, InsertNodeChild): cursor_node = node_for_s_address(structure.tree, structure.s_cursor)", "<= index <= len(parent.children) - 1): return an_error() # For", "structure.s_cursor) for i, child in enumerate(removed_node.children): p, hash_ = calc_possibility(NoteSlur(Insert(structure.s_cursor[-1]", "1): return an_error() return move_cursor(s_cursor[:-1] + [index]) \"\"\" if isinstance(edit_note,", "created. # nor do we bubble up (yet); we can", "simply implemented as a \"delete and insert\"; if (or when)", "see whether a use case arises. return an_error() # For", "[a descendant of] yourself. This is illegal. Moving something to", "existing location. If we # want to make the selection", "structure.s_cursor, index) new_s_cursor = structure.s_cursor + [index] return new_s_cursor, posacts,", "structure.s_cursor[-1] delete_from_hash = node_for_s_address(structure.tree, delete_from).metadata.nout_hash p, h = calc_possibility(NoteSlur(Delete(delete_at_index), delete_from_hash))", "with the parent\"; if (or when) we'll introduce # \"Move\"", "introduce # \"Move\" (in particular: the MoveReplace) into the Clef,", "could at least be understood to mean the no-op, so", "edit_note.direction if not (0 <= index <= len(parent.children) - 1):", "location. If we # want to make the selection appear", "if structure.s_cursor == []: return an_error() # adding sibblings to", "MoveSelectionChild): cursor_node = node_for_s_address(structure.tree, structure.s_cursor) if not hasattr(cursor_node, 'children'): return", "(For the case of \"parents match exactly\", I did this", "may be thought of as \"executing editor commands\". NOTE: in", "1): return an_error() # For now, SwapSibbling is simply implemented", "source_index_hi + 1)): # edge-inclusive range insert_hash = node_for_s_address(structure.tree, source_parent_path", "p1] + bubble_history_up(hash_after_insertion, structure.tree, parent_s_address) return new_cursor, posacts, False if", "dfs_index <= len(dfs) - 1): return an_error() return move_cursor(dfs[dfs_index]) \"\"\"At", "parent_s_address).metadata.nout_hash reinsert_later_hash = node_for_s_address(structure.tree, structure.s_cursor).metadata.nout_hash p0, hash_after_deletion = calc_possibility(NoteSlur(Delete(delete_at_index), delete_from_hash))", "len(parent_node.children) == 1: # if the deleted node was the", "MoveSelectionChild, MoveSelectionSibbling, LeaveChildrenBehind, SwapSibbling, TextInsert, TextReplace, ) def edit_note_play(structure, edit_note):", "no-longer existing location. If we # want to make the", "[index]) \"\"\" if isinstance(edit_note, CursorSet): return move_cursor(edit_note.s_address) if isinstance(edit_note, CursorParent):", "delete_from).children) - 1: # deletion makes cursor pos invalid: up", "TreeNode): # for now... we just silently ignore the user's", "preserved). # As it stands: the selection disappears automatically, because", "of length n, insertions at [0, n] are valid (insertion", "target_parent_path + [target_index + target_offset - cursor_correction] return new_cursor, posacts,", "add \"Move\" to the # clef. # Another way we", "CursorChild): cursor_node = node_for_s_address(structure.tree, structure.s_cursor) if not hasattr(cursor_node, 'children') or", "return do_move(structure, edit_note, structure.s_cursor[:-1], structure.s_cursor[-1] + edit_note.direction) if isinstance(edit_note, LeaveChildrenBehind):", "+ [source_index]).metadata.nout_hash p, hash_ = calc_possibility(NoteSlur(Insert(target_index + target_offset, insert_hash), hash_))", "is because we implement something that is atomic from the", "NOTE: in the below, we often connect notes together \"manually\",", "# Not only if the parents are exactly the same,", "being an append). index = structure.s_cursor[-1] + edit_note.direction posacts =", "that may just be habituation). In any case, it's wat", "if isinstance(edit_note, TextReplace): posacts = replace_text_at(structure.tree, edit_note.s_address, edit_note.text) return edit_note.s_address,", "now, the \"edit move\" operations are simply implemented as a", "auto-disappear if we add \"Move\" to the # clef. #", "vice versa. One possible relaxation is: make the # restriction", "!= target_parent_path: wdr_hash = hash_ hash_ = source_parent.metadata.nout_hash else: if", "node_for_s_address(structure.tree, structure.s_cursor) for i, child in enumerate(removed_node.children): p, hash_ =", "1: # deletion makes cursor pos invalid: up to parent", "# the longest_common_prefix of both parents matches one of them).", "in terms of the math), but I still have a", "False if isinstance(edit_note, EncloseWithParent): cursor_node = node_for_s_address(structure.tree, structure.s_cursor) if structure.s_cursor", "not sure about this one yet: should we have the", "move_cursor(structure.s_cursor + [0]) raise Exception(\"Unknown Note\") def do_move(structure, edit_note, target_parent_path,", "is still broken: # Not only if the parents are", "they will affect the locations where the deletions must take", "structure.s_cursor[:-1] replace_at_index = structure.s_cursor[-1] replace_on_hash = node_for_s_address(structure.tree, parent_s_address).metadata.nout_hash reinsert_later_hash =", "editor clef\", which may be thought of as \"executing editor", "EncloseWithParent): cursor_node = node_for_s_address(structure.tree, structure.s_cursor) if structure.s_cursor == []: #", "len(dfs) - 1): return an_error() return move_cursor(dfs[dfs_index]) \"\"\"At some point", "1 else: cursor_correction = source_index_hi - source_index_lo + 1 #", "- 1 - 1, # len - 1 idiom; -1", "it may # create some asymmetries. For now I'm disallowing", "node_for_s_address(structure.tree, source_parent_path) target_parent = node_for_s_address(structure.tree, target_parent_path) # For now, the", "not same-parent: this is an error. This may very well", "edit_note.direction if not (0 <= dfs_index <= len(dfs) - 1):", "# For now, SwapSibbling is simply implemented as a \"delete", "need to change the interface of edit_note_play to # include", "( CursorChild, CursorDFS, CursorParent, CursorSet, EDelete, EncloseWithParent, InsertNodeChild, InsertNodeSibbling, MoveSelectionChild,", "of as \"executing editor commands\". NOTE: in the below, we", "don't see any direct # objections (by which I mean:", "a \"insert and delete\"; if (or when) we'll introduce #", "node_for_s_address(structure.tree, structure.s_cursor) if not hasattr(cursor_node, 'children') or len(cursor_node.children) == 0:", "that is atomic from the user's # point of view", "-1 for deletion. new_cursor[len(new_cursor) - 1]) posacts += bubble_history_up(hash_, structure.tree,", "source_parent_path + [source_index]).metadata.nout_hash p, hash_ = calc_possibility(NoteSlur(Insert(target_index + target_offset, insert_hash),", "if structure.s_cursor == []: # silently ignored ('delete root' is", "\"Move\" into the Clef, we should note the move here.", "from dsn.editor.clef import ( CursorChild, CursorDFS, CursorParent, CursorSet, EDelete, EncloseWithParent,", "isinstance(edit_note, TextInsert): posacts = insert_text_at(structure.tree, edit_note.parent_s_address, edit_note.index, edit_note.text) new_s_cursor =", "an_error() # there is no sibbling of the root node", "has no sibblings parent = node_for_s_address(structure.tree, structure.s_cursor[:-1]) index = structure.s_cursor[-1]", "+ i, child.metadata.nout_hash), hash_)) posacts.append(p) # In general, leaving the", "lower indices # than the deletions, they will affect the", "dsn.editor.clef import ( CursorChild, CursorDFS, CursorParent, CursorSet, EDelete, EncloseWithParent, InsertNodeChild,", "idea that, for lists of length n, insertions at [0,", "TODO this part is still broken: # Not only if", "we can do a single bubble-up for source_index in range(source_index_lo,", "objections (by which I mean: it's possible in terms of", "is preserved). # As it stands: the selection disappears automatically,", "We insert before we delete. If we do this on", "a child return do_move(structure, edit_note, structure.s_cursor, len(cursor_node.children)) if isinstance(edit_note, MoveSelectionSibbling):", "+ bubble_history_up(h, structure.tree, delete_from) return new_s_cursor, posacts, False if isinstance(edit_note,", "if not (0 <= dfs_index <= len(dfs) - 1): return", "the left after each deletion) p, hash_ = calc_possibility(NoteSlur(Delete(source_index_lo +", "of insertions that happened. (If we reverse the order of", "+ [target_index + target_offset - cursor_correction] return new_cursor, posacts, False", "proof flows directly # from the idea that, for lists", "selection's # edges\", i.e. find the first common ancestor and", "left after each deletion) p, hash_ = calc_possibility(NoteSlur(Delete(source_index_lo + weave_correction),", "(0 <= index <= len(parent.children) - 1): return an_error() return", "prefix of the other (said differently: # the longest_common_prefix of", "an_error() return move_cursor(s_cursor[:-1] + [index]) \"\"\" if isinstance(edit_note, CursorSet): return", "the # number of insertions that happened. (If we reverse", "we have some tools to \"realinearize while preserving # meaning\".", "new_cursor = structure.s_cursor if len(removed_node.children) == 0: # ... however,", "structure.s_cursor[-1] + edit_note.direction posacts = insert_node_at(structure.tree, structure.s_cursor[:-1], index) new_s_cursor =", "(or when) we'll introduce # \"Move\" (in particular: the MoveReplace)", "the move here. parent_s_address = structure.s_cursor[:-1] delete_at_index = structure.s_cursor[-1] delete_from_hash", "# We jump the cursor to the newly enclosed location:", "cursor_node = node_for_s_address(structure.tree, structure.s_cursor) if not hasattr(cursor_node, 'children'): return an_error()", "p_replace] + bubble_history_up( hash_replace, structure.tree, parent_s_address) # We jump the", "return structure.s_cursor, [], True if isinstance(edit_note, TextInsert): posacts = insert_text_at(structure.tree,", "<= len(parent.children) - 1): return an_error() return move_cursor(s_cursor[:-1] + [index])", "= node_for_s_address(structure.tree, structure.s_cursor).metadata.nout_hash p0, hash_after_deletion = calc_possibility(NoteSlur(Delete(delete_at_index), delete_from_hash)) p1, hash_after_insertion", "a source node and to indices in the # source", "[]: return an_error() # root has no sibblings parent =", "One possible relaxation is: make the # restriction on \"same", "operations are simply implemented as a \"insert and delete\"; if", "node and to indices in the # source node, such", "move_cursor(s_cursor[:-1] + [index]) \"\"\" if isinstance(edit_note, CursorSet): return move_cursor(edit_note.s_address) if", "slide into the cursor position) posacts = [p] + bubble_history_up(h,", "target_index, because of the child-of-yourself checks at the top. weave_correction", "EncloseWithParent is simply implemented as a \"replace with the parent\";", "direct # objections (by which I mean: it's possible in", "s_dfs(structure.tree, []) dfs_index = dfs.index(structure.s_cursor) + edit_note.direction if not (0", "new_cursor, posacts, False if isinstance(edit_note, EncloseWithParent): cursor_node = node_for_s_address(structure.tree, structure.s_cursor)", "solution for \"where to put the cursor after the move\"", "dfs.index(structure.s_cursor) + edit_note.direction if not (0 <= dfs_index <= len(dfs)", "target_parent_path, wdr_hash, source_parent_path, hash_) else: posacts = posacts + bubble_history_up(hash_,", "edit_note.direction) if isinstance(edit_note, LeaveChildrenBehind): cursor_node = node_for_s_address(structure.tree, structure.s_cursor) if not", "isinstance(edit_note, CursorParent): if structure.s_cursor == []: return an_error() return move_cursor(structure.s_cursor[:-1])", "for target_offset, source_index in enumerate(range(source_index_lo, source_index_hi + 1)): # edge-inclusive", "jump the cursor to the newly enclosed location: new_cursor =", "handle the problem is once we have some tools to", "= node_for_s_address(structure.tree, s_cursor[:-1]) index = s_cursor[-1] + edit_node.direction if not", "parent (alternative: sibbling-up first, until no more sibblings) new_s_cursor =", "index <= len(parent.children) - 1): return an_error() return move_cursor(s_cursor[:-1] +", "we could consider `nouts_for_notes`. \"\"\" from s_address import node_for_s_address, s_dfs", "root has no sibblings parent = node_for_s_address(structure.tree, s_cursor[:-1]) index =", "note \"move\" using a target_node, a source node and to", "connect the parents.... # (For the case of \"parents match", "to parent (alternative: sibbling-up first, until no more sibblings) new_s_cursor", "the same location (single source item, target path # identical", "of \"we only check that the user's command can #", "new_cursor[len(new_cursor) - 1]) posacts += bubble_history_up(hash_, structure.tree, parent_s_address) return new_cursor,", "= calc_possibility( NoteSlur(Replace(replace_at_index, hash_enclosure), replace_on_hash)) posacts = [p_capo, p_create, p_enclosure,", "deletion. new_cursor[len(new_cursor) - 1]) posacts += bubble_history_up(hash_, structure.tree, parent_s_address) return", "# We insert before we delete. If we do this", "new_cursor, posacts, False def move_cursor(new_cursor): return new_cursor, [], False if", "the cursor at the same s_address will be great: post-deletion", "In that case, we need to somehow connect the parents....", "however, if there are no children to leave behind... this", "leaving the cursor at the same s_address will be great:", "target_offset, insert_hash), hash_)) posacts.append(p) weave_correction = 0 cursor_correction = 0", "implies \"same depth\", but not vice versa. One possible relaxation", "be executed at this point, we do not check for", "something to the same location (single source item, target path", "at least be understood to mean the no-op, so it's", "hash_capo)) p_enclosure, hash_enclosure = calc_possibility(NoteSlur(Insert(0, reinsert_later_hash), hash_create)) p_replace, hash_replace =", "bubble_history_up, calc_possibility, insert_text_at, insert_node_at, replace_text_at, weave_disjoint_replaces, ) from dsn.s_expr.clef import", "Replace, BecomeNode from dsn.s_expr.structure import TreeNode from dsn.editor.clef import (", "posacts, False if isinstance(edit_note, InsertNodeChild): cursor_node = node_for_s_address(structure.tree, structure.s_cursor) if", "index = structure.s_cursor[-1] + edit_note.direction posacts = insert_node_at(structure.tree, structure.s_cursor[:-1], index)", "view in a non-atomic way in the clef. The problem", "cursor_node = node_for_s_address(structure.tree, structure.s_cursor) if not isinstance(cursor_node, TreeNode): # for", "relevant children of that ancestor or [b] to not care", "have some tools to \"realinearize while preserving # meaning\". I.e.", "delete_from_hash = node_for_s_address(structure.tree, parent_s_address).metadata.nout_hash reinsert_later_hash = node_for_s_address(structure.tree, structure.s_cursor).metadata.nout_hash p0, hash_after_deletion", "\"replace with the parent\"; if (or when) we'll introduce #", "Root cannot die # For now, LeaveChildrenBehind is simply implemented", "an_error() return move_cursor(dfs[dfs_index]) \"\"\"At some point I had \"regular sibbling\"", "if isinstance(edit_note, InsertNodeSibbling): if structure.s_cursor == []: return an_error() #", "can # be executed at this point, we do not", "clef. # Another way we could handle the problem is", "not (0 <= dfs_index <= len(dfs) - 1): return an_error()", "move to [a descendant of] yourself. This is illegal. Moving", "length n, insertions at [0, n] are valid (insertion at", "parent_s_address = structure.s_cursor[:-1] replace_at_index = structure.s_cursor[-1] replace_on_hash = node_for_s_address(structure.tree, parent_s_address).metadata.nout_hash", "dsn.s_expr.clef import Delete, Insert, Replace, BecomeNode from dsn.s_expr.structure import TreeNode", "now, EncloseWithParent is simply implemented as a \"replace with the", "[p_capo, p_create, p_enclosure, p_replace] + bubble_history_up( hash_replace, structure.tree, parent_s_address) #", "selection_edge_1 = edit_note.selection_edge_1 def an_error(): return structure.s_cursor, [], True if", "len(cursor_node.children) posacts = insert_node_at(structure.tree, structure.s_cursor, index) new_s_cursor = structure.s_cursor +", "to the parent new_cursor = parent_s_address else: # otherwise, make", "to mean the no-op, so it's slightly less # meaningless,", "this is an error. This may very well be too", "insert_hash), hash_)) posacts.append(p) weave_correction = 0 cursor_correction = 0 #", "hash_) else: posacts = posacts + bubble_history_up(hash_, structure.tree, source_parent_path) #", "have a sense that it may # create some asymmetries.", "(but # that may just be habituation). In any case,", "root has no sibblings parent = node_for_s_address(structure.tree, structure.s_cursor[:-1]) index =", "the edit_clef. It looks like this: if structure.s_cursor == []:", "posacts, False def move_cursor(new_cursor): return new_cursor, [], False if isinstance(edit_note,", "= target_parent.metadata.nout_hash for target_offset, source_index in enumerate(range(source_index_lo, source_index_hi + 1)):", "of operations, we have the opposite problem) # The reason", "of edit_note_play to # include the resulting selection. new_cursor =", "path) could at least be understood to mean the no-op,", "parent_s_address) return new_cursor, posacts, False if isinstance(edit_note, MoveSelectionChild): cursor_node =", "import ( CursorChild, CursorDFS, CursorParent, CursorSet, EDelete, EncloseWithParent, InsertNodeChild, InsertNodeSibbling,", "selection disappears automatically, because it points at a no-longer existing", "isinstance(edit_note, MoveSelectionSibbling): if len(structure.s_cursor) == 0: return an_error() # there", "= calc_possibility(NoteSlur(Delete(source_index_lo + weave_correction), hash_)) posacts.append(p) if source_parent_path != target_parent_path:", "have deletions, we have insertions: at one point (e.g. once", "a \"delete and insert\"; if (or when) we'll introduce #", "# In the if-statement above, we could pick either lo/hi", "return an_error() delete_from = structure.s_cursor[:-1] delete_at_index = structure.s_cursor[-1] delete_from_hash =", "same s_address will be great: post-deletion you'll be in the", "would lead to a forest) # There is no need", "# editor) we should be able to express \"weave those", "LibreOffice, the selection is preserved). # As it stands: the", "if selection_edge_0[:-1] != selection_edge_1[:-1]: # i.e. if not same-parent: this", "\"Move\" to the # clef. # Another way we could", "would mean. Moving something to the same location (single source", "an_error() # root has no sibblings parent = node_for_s_address(structure.tree, s_cursor[:-1])", "s_cursor, posacts, error def an_error(): return structure.s_cursor, [], True if", "return new_s_cursor, posacts, False if isinstance(edit_note, InsertNodeChild): cursor_node = node_for_s_address(structure.tree,", "Tools to \"play notes for the editor clef\", which may", "LeaveChildrenBehind, SwapSibbling, TextInsert, TextReplace, ) def edit_note_play(structure, edit_note): # ::", "the no-op, so it's slightly less # meaningless, but here", "The reason we have this problem at all, is because", "an_error(): return structure.s_cursor, [], True if selection_edge_0[:-1] != selection_edge_1[:-1]: #", "up (yet); we can do a single bubble-up for source_index", "(single source item, target path # identical to the source", "if structure.s_cursor == []: # I am not sure about", "all, is because we implement something that is atomic from", "target_parent_path, target_index): selection_edge_0 = edit_note.selection_edge_0 selection_edge_1 = edit_note.selection_edge_1 def an_error():", "behind... this \"right spot\" may be illegal parent_node = node_for_s_address(structure.tree,", "if not hasattr(cursor_node, 'children'): return an_error() # Leave _children_ behind", "the source's range, # you're trying to move to [a", "continue operating on the the same \"future\". But in the", "index) new_s_cursor = structure.s_cursor + [index] return new_s_cursor, posacts, False", "point (e.g. once we build the cooperative # editor) we", "# want to make the selection appear at the target-location,", "later\" than in the other directions. One particular reason I'm", "now... we just silently ignore the user's request when they", "parent_s_address else: # otherwise, make sure to stay in bounds.", "is indeed a necessity. # Note that \"single parent\" implies", "# len - 1 idiom; -1 for deletion. new_cursor[len(new_cursor) -", "edit_node.direction if not (0 <= index <= len(parent.children) - 1):", "n, insertions at [0, n] are valid (insertion at n", "isinstance(cursor_node, TreeNode): # for now... we just silently ignore the", "enough, so I'm just calling both scenarios error-scenarios. # This", "[] source_index_lo, source_index_hi = sorted([selection_edge_0[-1], selection_edge_1[-1]]) hash_ = target_parent.metadata.nout_hash for", "p_enclosure, p_replace] + bubble_history_up( hash_replace, structure.tree, parent_s_address) # We jump", "source_parent_path != target_parent_path: wdr_hash = hash_ hash_ = source_parent.metadata.nout_hash else:", "the cursor after the move\" is \"at the end\". This", "+ edit_note.direction posacts = insert_node_at(structure.tree, structure.s_cursor[:-1], index) new_s_cursor = structure.s_cursor[:-1]", "a note \"move\" using a target_node, a source node and", "if not (0 <= index <= len(parent.children) - 1): return", "deletions must take place, by precisely the # number of", "cursor_node = node_for_s_address(structure.tree, structure.s_cursor) if structure.s_cursor == []: # I", "have insertions: at one point (e.g. once we build the", "[edit_note.index] return new_s_cursor, posacts, False if isinstance(edit_note, TextReplace): posacts =", "source_index_hi - source_index_lo + 1 # we do _not_ fetch", "at the same s_address will be great: post-deletion you'll be", "about single-parent. return an_error() if selection_edge_0 <= (target_parent_path + [target_index])[:len(selection_edge_0)]", "understood to mean the no-op, so it's slightly less #", "from s_address import node_for_s_address, s_dfs from dsn.s_expr.legato import NoteSlur, NoteCapo", "both parents matches one of them). # In that case,", "could pick either lo/hi for the comparison; source_index_lo and #", "here I don't find that enough, so I'm just calling", "= calc_possibility(NoteSlur(Delete(delete_at_index), delete_from_hash)) p1, hash_after_insertion = calc_possibility(NoteSlur(Insert(index, reinsert_later_hash), hash_after_deletion)) new_cursor", "0: # ... however, if there are no children to", "return an_error() # Leave _children_ behind presupposes the existance of", "# edge-inclusive range # Note: we just Delete n times", "# \"stay in place (although new contents slide into the", "did this using the idea \"just don't reset hash_\"... which", "== 0: return an_error() # there is no sibbling of", "if the parents are exactly the same, but also if", "# The target must be a node to be able", "can do a single bubble-up for source_index in range(source_index_lo, source_index_hi", "we build the cooperative # editor) we should be able", "node_for_s_address(structure.tree, source_parent_path + [source_index]).metadata.nout_hash p, hash_ = calc_possibility(NoteSlur(Insert(target_index + target_offset,", "in the below, we often connect notes together \"manually\", i.e.", "full target location, truncated to the length of the sources,", "1, # len - 1 idiom; -1 for deletion. new_cursor[len(new_cursor)", "reset hash_\"... which works, # because it allows you to", "new_cursor = target_parent_path + [target_index + target_offset - cursor_correction] return", "together \"manually\", i.e. using NoteSlur(..., previous_hash). As an alternative, we", "return an_error() return move_cursor(structure.s_cursor + [0]) raise Exception(\"Unknown Note\") def", "edit_note, structure.s_cursor, len(cursor_node.children)) if isinstance(edit_note, MoveSelectionSibbling): if len(structure.s_cursor) == 0:", "= [p] + bubble_history_up(h, structure.tree, delete_from) return new_s_cursor, posacts, False", "and the insertions happen at lower indices # than the", "structure.tree, target_parent_path, wdr_hash, source_parent_path, hash_) else: posacts = posacts +", "the existance of children if structure.s_cursor == []: return an_error()", "fit with the general idea of \"we only check that", "== 1: # if the deleted node was the only", "new_s_cursor = structure.s_cursor[:-1] + [index] return new_s_cursor, posacts, False if", "if not isinstance(cursor_node, TreeNode): # for now... we just silently", "from the root node) return an_error() source_parent_path = selection_edge_0[:-1] source_parent", "# For now, LeaveChildrenBehind is simply implemented as a \"delete", "the # direction of \"relax constraints later\" than in the", "instead. # Generally, the paths towards relaxation are to either", "possible relaxation is: make the # restriction on \"same depth\"", "parent_s_address).metadata.nout_hash reinsert_later_hash = node_for_s_address(structure.tree, structure.s_cursor).metadata.nout_hash p_capo, hash_capo = calc_possibility(NoteCapo()) p_create,", "selection_edge_0[:-1] source_parent = node_for_s_address(structure.tree, source_parent_path) target_parent = node_for_s_address(structure.tree, target_parent_path) #", "Moving something to a child of itself: # I simply", "add as a child return do_move(structure, edit_note, structure.s_cursor, len(cursor_node.children)) if", "edit_note, target_parent_path, target_index): selection_edge_0 = edit_note.selection_edge_0 selection_edge_1 = edit_note.selection_edge_1 def", "BecomeNode from dsn.s_expr.structure import TreeNode from dsn.editor.clef import ( CursorChild,", "was the only node: fall back to the parent new_cursor", "\"manually\", i.e. using NoteSlur(..., previous_hash). As an alternative, we could", "if I ever want to express a note \"move\" using", "# root has no sibblings parent = node_for_s_address(structure.tree, structure.s_cursor[:-1]) index", "node) return an_error() source_parent_path = selection_edge_0[:-1] source_parent = node_for_s_address(structure.tree, source_parent_path)", "TextReplace, ) def edit_note_play(structure, edit_note): # :: EditStructure, EditNote =>", "arbitrary programming errors here). The proof flows directly # from", "we'll introduce \"Move\" into # the Clef, we should note", "introduce \"Move\" into # the Clef, we should note the", "by precisely the # number of insertions that happened. (If", "structure.s_cursor).metadata.nout_hash p0, hash_after_deletion = calc_possibility(NoteSlur(Delete(delete_at_index), delete_from_hash)) p1, hash_after_insertion = calc_possibility(NoteSlur(Insert(index,", "location (single source item, target path # identical to the", "p, hash_ = calc_possibility(NoteSlur(Insert(structure.s_cursor[-1] + i, child.metadata.nout_hash), hash_)) posacts.append(p) #", "are no children to leave behind... this \"right spot\" may", "protection against moving the root node around (because everything descends", "versa. One possible relaxation is: make the # restriction on", "terms of the math), but I still have a sense", "be great: post-deletion you'll be in the right spot new_cursor", "range # Note: we just Delete n times at the", "# i.e. if not same-parent: this is an error. This", "necessity. # Note that \"single parent\" implies \"same depth\", but", "much about single-parent. return an_error() if selection_edge_0 <= (target_parent_path +", "insertions that happened. (If we reverse the order of operations,", "if not hasattr(cursor_node, 'children'): return an_error() # The target must", "[]: # silently ignored ('delete root' is not defined, because", "place (although new contents slide into the cursor position) posacts", "source_parent.metadata.nout_hash else: if target_index < source_index_lo: # We insert before", "# nor do we bubble up (yet); we can do", "hash_after_insertion = calc_possibility(NoteSlur(Insert(index, reinsert_later_hash), hash_after_deletion)) new_cursor = structure.s_cursor[:-1] + [index]", "to be able to add as a child return do_move(structure,", "False if isinstance(edit_note, InsertNodeChild): cursor_node = node_for_s_address(structure.tree, structure.s_cursor) if not", "posacts += bubble_history_up(hash_, structure.tree, parent_s_address) return new_cursor, posacts, False if", "put the cursor after the move\" is \"at the end\".", "child in enumerate(removed_node.children): p, hash_ = calc_possibility(NoteSlur(Insert(structure.s_cursor[-1] + i, child.metadata.nout_hash),", "= target_parent_path + [target_index + target_offset - cursor_correction] return new_cursor,", "the range [0, 1]; such assumptions fit with the general", "return new_cursor, posacts, False if isinstance(edit_note, EncloseWithParent): cursor_node = node_for_s_address(structure.tree,", "= structure.s_cursor[:-1] replace_at_index = structure.s_cursor[-1] replace_on_hash = node_for_s_address(structure.tree, parent_s_address).metadata.nout_hash reinsert_later_hash", "meaningless, but here I don't find that enough, so I'm", "implemented as a \"delete and insert\"; if (or when) we'll", "a # mouse-drag initiated move in LibreOffice, the selection is", "= insert_node_at(structure.tree, structure.s_cursor, index) new_s_cursor = structure.s_cursor + [index] return", "we have the opposite problem) # The reason we have", "target path # identical to the source path) could at", "tools to \"realinearize while preserving # meaning\". I.e. we have", "weave_correction = source_index_hi - source_index_lo + 1 else: cursor_correction =", "parent new_cursor = parent_s_address else: # otherwise, make sure to", "delete_from else: new_s_cursor = structure.s_cursor # \"stay in place (although", "move_cursor(new_cursor): return new_cursor, [], False if isinstance(edit_note, CursorDFS): dfs =", "= node_for_s_address(structure.tree, parent_s_address).metadata.nout_hash reinsert_later_hash = node_for_s_address(structure.tree, structure.s_cursor).metadata.nout_hash p_capo, hash_capo =", "return move_cursor(structure.s_cursor[:-1]) if isinstance(edit_note, CursorChild): cursor_node = node_for_s_address(structure.tree, structure.s_cursor) if", "CursorParent): if structure.s_cursor == []: return an_error() return move_cursor(structure.s_cursor[:-1]) if", "node_for_s_address(structure.tree, parent_s_address).metadata.nout_hash p, hash_ = calc_possibility(NoteSlur(Delete(delete_at_index), delete_from_hash)) posacts = [p]", "structure.s_cursor[-1] delete_from_hash = node_for_s_address(structure.tree, parent_s_address).metadata.nout_hash reinsert_later_hash = node_for_s_address(structure.tree, structure.s_cursor).metadata.nout_hash p0,", "is simply implemented as a \"replace with the parent\"; if", "the case of shared prefix, this won't # work. if", "reverse the order of operations, we have the opposite problem)", "source_index in enumerate(range(source_index_lo, source_index_hi + 1)): # edge-inclusive range insert_hash", "towards relaxation are to either [a] \"be smart about the", "illegal parent_node = node_for_s_address(structure.tree, parent_s_address) if len(parent_node.children) == 1: #", "to the root is not possible (it would lead to", "weave_correction = 0 cursor_correction = 0 # TODO this part", "node_for_s_address(structure.tree, parent_s_address) if len(parent_node.children) == 1: # if the deleted", "to a valid insertion point for the same reasons detailed", "if isinstance(edit_note, CursorDFS): dfs = s_dfs(structure.tree, []) dfs_index = dfs.index(structure.s_cursor)", "# ... however, if there are no children to leave", "that the new index is a valid one. (Assuming: the", "smart about the meaning of the selection's # edges\", i.e.", "in the other directions. One particular reason I'm so restrictive", "for the editor clef\", which may be thought of as", "asymmetries. For now I'm disallowing it; we'll see whether a", "part is still broken: # Not only if the parents", "identical to the source path) could at least be understood", "check that the user's command can # be executed at", "more sibblings) new_s_cursor = delete_from else: new_s_cursor = structure.s_cursor #", "descendant of] yourself. This is illegal. Moving something to a", "we could handle the problem is once we have some", "structure.s_cursor == []: # silently ignored ('delete root' is not", "move in LibreOffice, the selection is preserved). # As it", "delete\"; if (or when) we'll introduce # \"Move\" into the", "\"realinearize while preserving # meaning\". I.e. we have deletions, we", "which works, # because it allows you to continue operating", "[a] \"be smart about the meaning of the selection's #", "the locations where the deletions must take place, by precisely", "the only node: fall back to the parent new_cursor =", "does when cut/pasting. (However, for a # mouse-drag initiated move", "at a no-longer existing location. If we # want to", "1] = min( len(parent_node.children) - 1 - 1, # len", "just created. # nor do we bubble up (yet); we", "are valid (insertion at n being an append). index =", "= structure.s_cursor if len(removed_node.children) == 0: # ... however, if", "= node_for_s_address(structure.tree, structure.s_cursor[:-1]) index = structure.s_cursor[-1] + edit_note.direction if not", "edit_note, structure.s_cursor[:-1], structure.s_cursor[-1] + edit_note.direction) if isinstance(edit_note, LeaveChildrenBehind): cursor_node =", "enumerate(removed_node.children): p, hash_ = calc_possibility(NoteSlur(Insert(structure.s_cursor[-1] + i, child.metadata.nout_hash), hash_)) posacts.append(p)", "delete_from_hash = node_for_s_address(structure.tree, delete_from).metadata.nout_hash p, h = calc_possibility(NoteSlur(Delete(delete_at_index), delete_from_hash)) if", "create some asymmetries. For now I'm disallowing it; we'll see", "new_s_cursor, posacts, False if isinstance(edit_note, EDelete): if structure.s_cursor == []:", "but I still have a sense that it may #", "edit_note_play(structure, edit_note): # :: EditStructure, EditNote => (new) s_cursor, posacts,", "source's range, # you're trying to move to [a descendant", "1): return an_error() return move_cursor(dfs[dfs_index]) \"\"\"At some point I had", "= edit_note.selection_edge_0 selection_edge_1 = edit_note.selection_edge_1 def an_error(): return structure.s_cursor, [],", "express a note \"move\" using a target_node, a source node", "cursor_correction = 0 # TODO this part is still broken:", "source_index_hi = sorted([selection_edge_0[-1], selection_edge_1[-1]]) hash_ = target_parent.metadata.nout_hash for target_offset, source_index", "structure.s_cursor[-1] delete_from_hash = node_for_s_address(structure.tree, parent_s_address).metadata.nout_hash p, hash_ = calc_possibility(NoteSlur(Delete(delete_at_index), delete_from_hash))", "current solution for \"where to put the cursor after the", "is not possible (it would lead to a forest) #", "s_cursor[:-1]) index = s_cursor[-1] + edit_node.direction if not (0 <=", "be habituation). In any case, it's wat e.g. LibreOffice does", "the longest_common_prefix of both parents matches one of them). #", "parents are exactly the same, but also if one parent", "slightly less # meaningless, but here I don't find that", "structure.s_cursor == []: return an_error() return move_cursor(structure.s_cursor[:-1]) if isinstance(edit_note, CursorChild):", "they ask to add a child node to a non-node", "hash_)) posacts.append(p) # In general, leaving the cursor at the", "new_s_cursor = edit_note.parent_s_address + [edit_note.index] return new_s_cursor, posacts, False if", "the Clef, we should note the move here. parent_s_address =", "target_index): selection_edge_0 = edit_note.selection_edge_0 selection_edge_1 = edit_note.selection_edge_1 def an_error(): return", "replace_text_at, weave_disjoint_replaces, ) from dsn.s_expr.clef import Delete, Insert, Replace, BecomeNode", "= calc_possibility(NoteSlur(Delete(delete_at_index), delete_from_hash)) if delete_at_index == len(node_for_s_address(structure.tree, delete_from).children) - 1:", "this problem at all, is because we implement something that", "structure.tree, source_parent_path) # The current solution for \"where to put", "not vice versa. One possible relaxation is: make the #", "isinstance(edit_note, EDelete): if structure.s_cursor == []: # silently ignored ('delete", "the case of \"parents match exactly\", I did this using", "# work. if source_parent_path != target_parent_path: wdr_hash = hash_ hash_", "# source_index_hi will never straddle target_index, because of the child-of-yourself", "mouse-drag initiated move in LibreOffice, the selection is preserved). #", "structure.s_cursor) if not hasattr(cursor_node, 'children'): return an_error() # Leave _children_", "to change the interface of edit_note_play to # include the", "import ( bubble_history_up, calc_possibility, insert_text_at, insert_node_at, replace_text_at, weave_disjoint_replaces, ) from", "of them). # In that case, we need to somehow", "the comment on # InsertNodeSibbling return do_move(structure, edit_note, structure.s_cursor[:-1], structure.s_cursor[-1]", "CursorDFS): dfs = s_dfs(structure.tree, []) dfs_index = dfs.index(structure.s_cursor) + edit_note.direction", "node_for_s_address(structure.tree, structure.s_cursor) if structure.s_cursor == []: # I am not", "reinsert_later_hash = node_for_s_address(structure.tree, structure.s_cursor).metadata.nout_hash p_capo, hash_capo = calc_possibility(NoteCapo()) p_create, hash_create", "new contents slide into the cursor position) posacts = [p]", "raise Exception(\"Unknown Note\") def do_move(structure, edit_note, target_parent_path, target_index): selection_edge_0 =", "I had \"regular sibbling\" (as opposed to DFS sibbling) in", "at [0, n] are valid (insertion at n being an", "NoteSlur, NoteCapo from dsn.s_expr.utils import ( bubble_history_up, calc_possibility, insert_text_at, insert_node_at,", "possible in terms of the math), but I still have", "if isinstance(edit_note, LeaveChildrenBehind): cursor_node = node_for_s_address(structure.tree, structure.s_cursor) if not hasattr(cursor_node,", "+ edit_note.direction if not (0 <= index <= len(parent.children) -", "able to express \"weave those together, rewriting indices as required\".", "+ bubble_history_up(hash_after_insertion, structure.tree, parent_s_address) return new_cursor, posacts, False if isinstance(edit_note,", "... however, if there are no children to leave behind...", "source_index_lo + 1 else: cursor_correction = source_index_hi - source_index_lo +", "p, hash_ = calc_possibility(NoteSlur(Delete(delete_at_index), delete_from_hash)) posacts = [p] removed_node =", "up to parent (alternative: sibbling-up first, until no more sibblings)", "# The current solution for \"where to put the cursor", "<reponame>expressionsofchange/nerf0<gh_stars>1-10 \"\"\" Tools to \"play notes for the editor clef\",", "\"executing editor commands\". NOTE: in the below, we often connect", "rewriting indices as required\". # In the if-statement above, we", "(by which I mean: it's possible in terms of the", "# otherwise, make sure to stay in bounds. new_cursor[len(new_cursor) -", "return an_error() return move_cursor(s_cursor[:-1] + [index]) \"\"\" if isinstance(edit_note, CursorSet):", "# If the full target location, truncated to the length", "relaxation are to either [a] \"be smart about the meaning", "calc_possibility(NoteSlur(Insert(target_index + target_offset, insert_hash), hash_)) posacts.append(p) weave_correction = 0 cursor_correction", "else: posacts = posacts + bubble_history_up(hash_, structure.tree, source_parent_path) # The", "the problem is once we have some tools to \"realinearize", "item, target path # identical to the source path) could", "the newly enclosed location: new_cursor = structure.s_cursor + [0] return", "[0, n] are valid (insertion at n being an append).", "makes cursor pos invalid: up to parent (alternative: sibbling-up first,", "is atomic from the user's # point of view in", "\"play notes for the editor clef\", which may be thought", "cursor_correction = source_index_hi - source_index_lo + 1 # we do", "a valid one. (Assuming: the cursor is valid, and direction", "n times at the \"lo\" index (everything shifting to the", "one yet: should we have the option to create a", "range insert_hash = node_for_s_address(structure.tree, source_parent_path + [source_index]).metadata.nout_hash p, hash_ =", "False if isinstance(edit_note, SwapSibbling): if structure.s_cursor == []: return an_error()", "If we do this on the same parent, and the", "bubble_history_up(hash_after_insertion, structure.tree, parent_s_address) return new_cursor, posacts, False if isinstance(edit_note, MoveSelectionChild):", "interface of edit_note_play to # include the resulting selection. new_cursor", "EditNote => (new) s_cursor, posacts, error def an_error(): return structure.s_cursor,", "mean. Moving something to the same location (single source item,", "(However, for a # mouse-drag initiated move in LibreOffice, the", "structure.s_cursor, [], True if isinstance(edit_note, TextInsert): posacts = insert_text_at(structure.tree, edit_note.parent_s_address,", "is illegal. Moving something to a child of itself: #", "we bubble up (yet); we can do a single bubble-up", "the hash we just created. # nor do we bubble", "we have deletions, we have insertions: at one point (e.g.", "cannot die # For now, LeaveChildrenBehind is simply implemented as", "from dsn.s_expr.clef import Delete, Insert, Replace, BecomeNode from dsn.s_expr.structure import", "one parent is a prefix of the other (said differently:", "it stands: the selection disappears automatically, because it points at", "CursorSet): return move_cursor(edit_note.s_address) if isinstance(edit_note, CursorParent): if structure.s_cursor == []:", "have the opposite problem) # The reason we have this", "- 1, # len - 1 idiom; -1 for deletion.", "no sibblings parent = node_for_s_address(structure.tree, s_cursor[:-1]) index = s_cursor[-1] +", "+ [edit_note.index] return new_s_cursor, posacts, False if isinstance(edit_note, TextReplace): posacts", "True if isinstance(edit_note, TextInsert): posacts = insert_text_at(structure.tree, edit_note.parent_s_address, edit_note.index, edit_note.text)", "parent, and the insertions happen at lower indices # than", "False def move_cursor(new_cursor): return new_cursor, [], False if isinstance(edit_note, CursorDFS):", "be a node to be able to add as a", "first common ancestor and the relevant children of that ancestor", "insertions happen at lower indices # than the deletions, they", "particular reason I'm so restrictive # for now: if I", "+ [target_index])[:len(selection_edge_0)] <= selection_edge_1: # If the full target location,", "implement something that is atomic from the user's # point", "into the Clef, we should note the move here. parent_s_address", "+ [0]) raise Exception(\"Unknown Note\") def do_move(structure, edit_note, target_parent_path, target_index):", "LeaveChildrenBehind is simply implemented as a \"delete and insert\"; if", "this point, we do not check for arbitrary programming errors", "we need to somehow connect the parents.... # (For the", "removed_node = node_for_s_address(structure.tree, structure.s_cursor) for i, child in enumerate(removed_node.children): p,", "# deletion makes cursor pos invalid: up to parent (alternative:", "new_cursor = structure.s_cursor + [0] return new_cursor, posacts, False def", "place, by precisely the # number of insertions that happened.", "selection_edge_1: # If the full target location, truncated to the", "CursorChild, CursorDFS, CursorParent, CursorSet, EDelete, EncloseWithParent, InsertNodeChild, InsertNodeSibbling, MoveSelectionChild, MoveSelectionSibbling,", "MoveReplace) into the Clef, we should note the move here.", "\"relax constraints later\" than in the other directions. One particular", "is valid, and direction is # in the range [0,", "to put the cursor after the move\" is \"at the", "As it stands: the selection disappears automatically, because it points", "root' is not defined, because the root is assumed to", "differently: # the longest_common_prefix of both parents matches one of", "calc_possibility(NoteSlur(Delete(source_index_lo + weave_correction), hash_)) posacts.append(p) if source_parent_path != target_parent_path: posacts", "= calc_possibility(NoteCapo()) p_create, hash_create = calc_possibility(NoteSlur(BecomeNode(), hash_capo)) p_enclosure, hash_enclosure =", "check that the new index is a valid one. (Assuming:", "both scenarios error-scenarios. # This implies protection against moving the", "programming errors here). The proof flows directly # from the", "of children if structure.s_cursor == []: return an_error() # Root", "== 0: # ... however, if there are no children", "posacts.append(p) weave_correction = 0 cursor_correction = 0 # TODO this", "create a new root? I don't see any direct #", "sense that it may # create some asymmetries. For now", "for now: if I ever want to express a note", "dfs_index = dfs.index(structure.s_cursor) + edit_note.direction if not (0 <= dfs_index", "= replace_text_at(structure.tree, edit_note.s_address, edit_note.text) return edit_note.s_address, posacts, False if isinstance(edit_note,", "(as opposed to DFS sibbling) in the edit_clef. It looks", "range, # you're trying to move to [a descendant of]", "cursor at the same s_address will be great: post-deletion you'll", "= node_for_s_address(structure.tree, parent_s_address).metadata.nout_hash reinsert_later_hash = node_for_s_address(structure.tree, structure.s_cursor).metadata.nout_hash p0, hash_after_deletion =", "p_replace, hash_replace = calc_possibility( NoteSlur(Replace(replace_at_index, hash_enclosure), replace_on_hash)) posacts = [p_capo,", "insert before we delete. If we do this on the", "previous_hash). As an alternative, we could consider `nouts_for_notes`. \"\"\" from", "<= len(dfs) - 1): return an_error() return move_cursor(dfs[dfs_index]) \"\"\"At some", "include the resulting selection. new_cursor = target_parent_path + [target_index +", "matches one of them). # In that case, we need", "Insert, Replace, BecomeNode from dsn.s_expr.structure import TreeNode from dsn.editor.clef import", "the user's command can # be executed at this point,", "the clef. The problem may auto-disappear if we add \"Move\"", "be thought of as \"executing editor commands\". NOTE: in the", "node_for_s_address(structure.tree, structure.s_cursor) if not isinstance(cursor_node, TreeNode): # for now... we", "isinstance(edit_note, LeaveChildrenBehind): cursor_node = node_for_s_address(structure.tree, structure.s_cursor) if not hasattr(cursor_node, 'children'):", "selection is preserved). # As it stands: the selection disappears", "still have a sense that it may # create some", "you'll be in the right spot new_cursor = structure.s_cursor if", "In general, leaving the cursor at the same s_address will", "# adding sibblings to the root is not possible (it", "constraints later\" than in the other directions. One particular reason", "locations where the deletions must take place, by precisely the", "this: if structure.s_cursor == []: return an_error() # root has", "replace_text_at(structure.tree, edit_note.s_address, edit_note.text) return edit_note.s_address, posacts, False if isinstance(edit_note, InsertNodeSibbling):", "an_error() delete_from = structure.s_cursor[:-1] delete_at_index = structure.s_cursor[-1] delete_from_hash = node_for_s_address(structure.tree,", "do_move(structure, edit_note, structure.s_cursor, len(cursor_node.children)) if isinstance(edit_note, MoveSelectionSibbling): if len(structure.s_cursor) ==", "so I'm just calling both scenarios error-scenarios. # This implies", "either [a] \"be smart about the meaning of the selection's", "single-parent. return an_error() if selection_edge_0 <= (target_parent_path + [target_index])[:len(selection_edge_0)] <=", "in the # direction of \"relax constraints later\" than in", "parent_s_address).metadata.nout_hash p, hash_ = calc_possibility(NoteSlur(Delete(delete_at_index), delete_from_hash)) posacts = [p] removed_node", "spot new_cursor = structure.s_cursor if len(removed_node.children) == 0: # ...", "to the same location (single source item, target path #", "# objections (by which I mean: it's possible in terms", "import Delete, Insert, Replace, BecomeNode from dsn.s_expr.structure import TreeNode from", "delete_from).metadata.nout_hash p, h = calc_possibility(NoteSlur(Delete(delete_at_index), delete_from_hash)) if delete_at_index == len(node_for_s_address(structure.tree,", "parent = node_for_s_address(structure.tree, s_cursor[:-1]) index = s_cursor[-1] + edit_node.direction if", "above, we could pick either lo/hi for the comparison; source_index_lo", "!= selection_edge_1[:-1]: # i.e. if not same-parent: this is an", "of the selection's # edges\", i.e. find the first common", "insert_node_at, replace_text_at, weave_disjoint_replaces, ) from dsn.s_expr.clef import Delete, Insert, Replace,", "indeed a necessity. # Note that \"single parent\" implies \"same", "truncated to the length of the sources, is (inclusively) in", "in the edit_clef. It looks like this: if structure.s_cursor ==", "the order of operations, we have the opposite problem) #", "an_error() # Leave _children_ behind presupposes the existance of children", "p_create, hash_create = calc_possibility(NoteSlur(BecomeNode(), hash_capo)) p_enclosure, hash_enclosure = calc_possibility(NoteSlur(Insert(0, reinsert_later_hash),", "root? I don't see any direct # objections (by which", "user's request when they ask to add a child node", "0 # TODO this part is still broken: # Not", "sibbling-up first, until no more sibblings) new_s_cursor = delete_from else:", "NoteCapo from dsn.s_expr.utils import ( bubble_history_up, calc_possibility, insert_text_at, insert_node_at, replace_text_at,", "depth\", but not vice versa. One possible relaxation is: make", "posacts = replace_text_at(structure.tree, edit_note.s_address, edit_note.text) return edit_note.s_address, posacts, False if", "_children_ behind presupposes the existance of children if structure.s_cursor ==", "= s_dfs(structure.tree, []) dfs_index = dfs.index(structure.s_cursor) + edit_note.direction if not", "index is a valid one. (Assuming: the cursor is valid,", "often connect notes together \"manually\", i.e. using NoteSlur(..., previous_hash). As", "wdr_hash = hash_ hash_ = source_parent.metadata.nout_hash else: if target_index <", "here, the idea being: it's the hash we just created.", "an_error(): return structure.s_cursor, [], True if isinstance(edit_note, TextInsert): posacts =", "structure.tree, delete_from) return new_s_cursor, posacts, False if isinstance(edit_note, SwapSibbling): if", "to check that the new index is a valid one.", "new index is a valid one. (Assuming: the cursor is", "source_index_hi + 1): # edge-inclusive range # Note: we just", "we should note the move here. parent_s_address = structure.s_cursor[:-1] replace_at_index", "now: if I ever want to express a note \"move\"", "= selection_edge_0[:-1] source_parent = node_for_s_address(structure.tree, source_parent_path) target_parent = node_for_s_address(structure.tree, target_parent_path)", "atomic from the user's # point of view in a", "edit_note.direction points to a valid insertion point for the same", "the parents are exactly the same, but also if one", "fetch hash_ here, the idea being: it's the hash we", "structure.s_cursor == []: # I am not sure about this", "if structure.s_cursor == []: return an_error() return move_cursor(structure.s_cursor[:-1]) if isinstance(edit_note,", "source node, such a single-parent restriction is indeed a necessity.", "for a # mouse-drag initiated move in LibreOffice, the selection", "isinstance(edit_note, CursorChild): cursor_node = node_for_s_address(structure.tree, structure.s_cursor) if not hasattr(cursor_node, 'children')", "and insert\"; if (or when) we'll introduce \"Move\" into #", "of the root node # edit_note.direction points to a valid", "(new) s_cursor, posacts, error def an_error(): return structure.s_cursor, [], True", "want to express a note \"move\" using a target_node, a", "a child of itself: # I simply don't know what", "+ edit_note.direction) if isinstance(edit_note, LeaveChildrenBehind): cursor_node = node_for_s_address(structure.tree, structure.s_cursor) if", "structure.s_cursor[:-1] delete_at_index = structure.s_cursor[-1] delete_from_hash = node_for_s_address(structure.tree, parent_s_address).metadata.nout_hash reinsert_later_hash =", "For now, EncloseWithParent is simply implemented as a \"replace with", "relaxation is: make the # restriction on \"same depth\" instead.", "not hasattr(cursor_node, 'children'): return an_error() # The target must be", "we should be able to express \"weave those together, rewriting", "to add as a child return do_move(structure, edit_note, structure.s_cursor, len(cursor_node.children))", "# much about single-parent. return an_error() if selection_edge_0 <= (target_parent_path", "you're trying to move to [a descendant of] yourself. This", "\"Move\" (in particular: the MoveReplace) into the Clef, we should", "request when they ask to add a child node to", "# As it stands: the selection disappears automatically, because it", "of the other (said differently: # the longest_common_prefix of both", "we do not check for arbitrary programming errors here). The", "but also if one parent is a prefix of the", "children to leave behind... this \"right spot\" may be illegal", "should be able to express \"weave those together, rewriting indices", "the general idea of \"we only check that the user's", "[]: return an_error() return move_cursor(structure.s_cursor[:-1]) if isinstance(edit_note, CursorChild): cursor_node =", "CursorDFS, CursorParent, CursorSet, EDelete, EncloseWithParent, InsertNodeChild, InsertNodeSibbling, MoveSelectionChild, MoveSelectionSibbling, LeaveChildrenBehind,", "target must be a node to be able to add", "p_capo, hash_capo = calc_possibility(NoteCapo()) p_create, hash_create = calc_possibility(NoteSlur(BecomeNode(), hash_capo)) p_enclosure,", "an_error() # root has no sibblings parent = node_for_s_address(structure.tree, structure.s_cursor[:-1])", "length of the sources, is (inclusively) in the source's range,", "for deletion. new_cursor[len(new_cursor) - 1]) posacts += bubble_history_up(hash_, structure.tree, parent_s_address)", "the meaning of the selection's # edges\", i.e. find the", "least be understood to mean the no-op, so it's slightly", "For now, LeaveChildrenBehind is simply implemented as a \"delete and", "valid one. (Assuming: the cursor is valid, and direction is", "we could pick either lo/hi for the comparison; source_index_lo and", "the same reasons detailed in the comment on # InsertNodeSibbling", "= source_index_hi - source_index_lo + 1 else: cursor_correction = source_index_hi", "bubble_history_up(hash_, structure.tree, parent_s_address) return new_cursor, posacts, False if isinstance(edit_note, EncloseWithParent):", "structure.s_cursor[:-1] delete_at_index = structure.s_cursor[-1] delete_from_hash = node_for_s_address(structure.tree, parent_s_address).metadata.nout_hash p, hash_", "stay in bounds. new_cursor[len(new_cursor) - 1] = min( len(parent_node.children) -", "# you're trying to move to [a descendant of] yourself.", "target_parent.metadata.nout_hash for target_offset, source_index in enumerate(range(source_index_lo, source_index_hi + 1)): #", "[source_index]).metadata.nout_hash p, hash_ = calc_possibility(NoteSlur(Insert(target_index + target_offset, insert_hash), hash_)) posacts.append(p)", "thought of as \"executing editor commands\". NOTE: in the below,", "opposed to DFS sibbling) in the edit_clef. It looks like", "have this problem at all, is because we implement something", "structure.s_cursor + [index] return new_s_cursor, posacts, False if isinstance(edit_note, EDelete):", "replace_at_index = structure.s_cursor[-1] replace_on_hash = node_for_s_address(structure.tree, parent_s_address).metadata.nout_hash reinsert_later_hash = node_for_s_address(structure.tree,", "# edges\", i.e. find the first common ancestor and the", "= posacts + weave_disjoint_replaces( structure.tree, target_parent_path, wdr_hash, source_parent_path, hash_) else:", "same, but also if one parent is a prefix of", "child return do_move(structure, edit_note, structure.s_cursor, len(cursor_node.children)) if isinstance(edit_note, MoveSelectionSibbling): if", "# source node, such a single-parent restriction is indeed a", "root node) return an_error() source_parent_path = selection_edge_0[:-1] source_parent = node_for_s_address(structure.tree,", "way we could handle the problem is once we have", "appear at the target-location, we need to change the interface", "points to a valid insertion point for the same reasons", "a use case arises. return an_error() # For now, EncloseWithParent", "idea being: it's the hash we just created. # nor", "we should note the move here. posacts = [] source_index_lo,", "restrictive, but I'd rather move in the # direction of", "the cursor is valid, and direction is # in the", "= structure.s_cursor + [index] return new_s_cursor, posacts, False if isinstance(edit_note,", "= structure.s_cursor + [0] return new_cursor, posacts, False def move_cursor(new_cursor):", "# \"Move\" (in particular: the MoveReplace) into the Clef, we", "leave behind... this \"right spot\" may be illegal parent_node =", "are to either [a] \"be smart about the meaning of", "to \"play notes for the editor clef\", which may be", "delete_from_hash)) p1, hash_after_insertion = calc_possibility(NoteSlur(Insert(index, reinsert_later_hash), hash_after_deletion)) new_cursor = structure.s_cursor[:-1]", "in the source's range, # you're trying to move to", "for lists of length n, insertions at [0, n] are", "this \"right spot\" may be illegal parent_node = node_for_s_address(structure.tree, parent_s_address)", "find the first common ancestor and the relevant children of", "# because it allows you to continue operating on the", "the user's # point of view in a non-atomic way", "using a target_node, a source node and to indices in", "(inclusively) in the source's range, # you're trying to move", "the # restriction on \"same depth\" instead. # Generally, the", "don't know what it would mean. Moving something to the", "= structure.s_cursor[:-1] delete_at_index = structure.s_cursor[-1] delete_from_hash = node_for_s_address(structure.tree, parent_s_address).metadata.nout_hash reinsert_later_hash", "to a non-node return an_error() index = len(cursor_node.children) posacts =", "should note the move here. parent_s_address = structure.s_cursor[:-1] replace_at_index =", "from dsn.s_expr.structure import TreeNode from dsn.editor.clef import ( CursorChild, CursorDFS,", "[b] to not care so # much about single-parent. return", "parent_s_address) return new_cursor, posacts, False if isinstance(edit_note, EncloseWithParent): cursor_node =", "# For now, EncloseWithParent is simply implemented as a \"replace", "simply implemented as a \"replace with the parent\"; if (or", "reinsert_later_hash), hash_create)) p_replace, hash_replace = calc_possibility( NoteSlur(Replace(replace_at_index, hash_enclosure), replace_on_hash)) posacts", "i, child.metadata.nout_hash), hash_)) posacts.append(p) # In general, leaving the cursor", "calc_possibility(NoteSlur(Delete(delete_at_index), delete_from_hash)) posacts = [p] removed_node = node_for_s_address(structure.tree, structure.s_cursor) for", "= structure.s_cursor[-1] delete_from_hash = node_for_s_address(structure.tree, delete_from).metadata.nout_hash p, h = calc_possibility(NoteSlur(Delete(delete_at_index),", "flows directly # from the idea that, for lists of", "structure.s_cursor == []: return an_error() # Root cannot die #", "one. (Assuming: the cursor is valid, and direction is #", "== []: return an_error() return move_cursor(structure.s_cursor[:-1]) if isinstance(edit_note, CursorChild): cursor_node", "a single-parent restriction is indeed a necessity. # Note that", "calc_possibility(NoteCapo()) p_create, hash_create = calc_possibility(NoteSlur(BecomeNode(), hash_capo)) p_enclosure, hash_enclosure = calc_possibility(NoteSlur(Insert(0,", "do a single bubble-up for source_index in range(source_index_lo, source_index_hi +", "= [p0, p1] + bubble_history_up(hash_after_insertion, structure.tree, parent_s_address) return new_cursor, posacts,", "it allows you to continue operating on the the same", "direction is # in the range [0, 1]; such assumptions", "= insert_node_at(structure.tree, structure.s_cursor[:-1], index) new_s_cursor = structure.s_cursor[:-1] + [index] return", "we implement something that is atomic from the user's #", "def move_cursor(new_cursor): return new_cursor, [], False if isinstance(edit_note, CursorDFS): dfs", "whether a use case arises. return an_error() # For now,", "# than the deletions, they will affect the locations where", "calc_possibility, insert_text_at, insert_node_at, replace_text_at, weave_disjoint_replaces, ) from dsn.s_expr.clef import Delete,", "if isinstance(edit_note, SwapSibbling): if structure.s_cursor == []: return an_error() #", "I.e. we have deletions, we have insertions: at one point", "new_cursor = structure.s_cursor[:-1] + [index] posacts = [p0, p1] +", "the other directions. One particular reason I'm so restrictive #", "append). index = structure.s_cursor[-1] + edit_note.direction posacts = insert_node_at(structure.tree, structure.s_cursor[:-1],", "replace_on_hash)) posacts = [p_capo, p_create, p_enclosure, p_replace] + bubble_history_up( hash_replace,", "n being an append). index = structure.s_cursor[-1] + edit_note.direction posacts", "to the length of the sources, is (inclusively) in the", "'children') or len(cursor_node.children) == 0: return an_error() return move_cursor(structure.s_cursor +", "the idea \"just don't reset hash_\"... which works, # because", "len(removed_node.children) == 0: # ... however, if there are no", "# Another way we could handle the problem is once", "match exactly\", I did this using the idea \"just don't", "p, hash_ = calc_possibility(NoteSlur(Insert(target_index + target_offset, insert_hash), hash_)) posacts.append(p) weave_correction", "an append). index = structure.s_cursor[-1] + edit_note.direction posacts = insert_node_at(structure.tree,", "until no more sibblings) new_s_cursor = delete_from else: new_s_cursor =", "indices as required\". # In the if-statement above, we could", "source_index_hi - source_index_lo + 1 else: cursor_correction = source_index_hi -", "be illegal parent_node = node_for_s_address(structure.tree, parent_s_address) if len(parent_node.children) == 1:", "great: post-deletion you'll be in the right spot new_cursor =", "insert_node_at(structure.tree, structure.s_cursor[:-1], index) new_s_cursor = structure.s_cursor[:-1] + [index] return new_s_cursor,", "('delete root' is not defined, because the root is assumed", "against moving the root node around (because everything descends from", "alternative, we could consider `nouts_for_notes`. \"\"\" from s_address import node_for_s_address,", "# restriction on \"same depth\" instead. # Generally, the paths", "hash_replace = calc_possibility( NoteSlur(Replace(replace_at_index, hash_enclosure), replace_on_hash)) posacts = [p_capo, p_create,", "parent_s_address = structure.s_cursor[:-1] delete_at_index = structure.s_cursor[-1] delete_from_hash = node_for_s_address(structure.tree, parent_s_address).metadata.nout_hash", "delete_from_hash)) posacts = [p] removed_node = node_for_s_address(structure.tree, structure.s_cursor) for i,", "here. parent_s_address = structure.s_cursor[:-1] replace_at_index = structure.s_cursor[-1] replace_on_hash = node_for_s_address(structure.tree,", "new root? I don't see any direct # objections (by", "it points at a no-longer existing location. If we #", "structure.tree, parent_s_address) # We jump the cursor to the newly", "once we have some tools to \"realinearize while preserving #", "enumerate(range(source_index_lo, source_index_hi + 1)): # edge-inclusive range insert_hash = node_for_s_address(structure.tree,", "wat e.g. LibreOffice does when cut/pasting. (However, for a #", "# In general, leaving the cursor at the same s_address", "+ [index] return new_s_cursor, posacts, False if isinstance(edit_note, InsertNodeChild): cursor_node", "into the Clef, we should note the move here. posacts", "Leave _children_ behind presupposes the existance of children if structure.s_cursor", "because of the child-of-yourself checks at the top. weave_correction =", "LibreOffice does when cut/pasting. (However, for a # mouse-drag initiated", "each deletion) p, hash_ = calc_possibility(NoteSlur(Delete(source_index_lo + weave_correction), hash_)) posacts.append(p)", "calc_possibility(NoteSlur(Delete(delete_at_index), delete_from_hash)) p1, hash_after_insertion = calc_possibility(NoteSlur(Insert(index, reinsert_later_hash), hash_after_deletion)) new_cursor =", "we have the option to create a new root? I", "hasattr(cursor_node, 'children'): return an_error() # Leave _children_ behind presupposes the", "I'm so restrictive # for now: if I ever want", "like this: if structure.s_cursor == []: return an_error() # root", "single bubble-up for source_index in range(source_index_lo, source_index_hi + 1): #", "i.e. if not same-parent: this is an error. This may", "cursor to the newly enclosed location: new_cursor = structure.s_cursor +", "structure.s_cursor[-1] + edit_note.direction if not (0 <= index <= len(parent.children)", "For now, SwapSibbling is simply implemented as a \"delete and", "posacts = posacts + bubble_history_up(hash_, structure.tree, source_parent_path) # The current", "source path) could at least be understood to mean the", "return move_cursor(edit_note.s_address) if isinstance(edit_note, CursorParent): if structure.s_cursor == []: return", "replace_on_hash = node_for_s_address(structure.tree, parent_s_address).metadata.nout_hash reinsert_later_hash = node_for_s_address(structure.tree, structure.s_cursor).metadata.nout_hash p_capo, hash_capo", "e.g. LibreOffice does when cut/pasting. (However, for a # mouse-drag", "[]: return an_error() # adding sibblings to the root is", "of the child-of-yourself checks at the top. weave_correction = source_index_hi", "i.e. find the first common ancestor and the relevant children", "here. posacts = [] source_index_lo, source_index_hi = sorted([selection_edge_0[-1], selection_edge_1[-1]]) hash_", "do we bubble up (yet); we can do a single", "# include the resulting selection. new_cursor = target_parent_path + [target_index", "do _not_ fetch hash_ here, the idea being: it's the", "if-statement above, we could pick either lo/hi for the comparison;", "an_error() return move_cursor(structure.s_cursor + [0]) raise Exception(\"Unknown Note\") def do_move(structure,", "posacts = [p_capo, p_create, p_enclosure, p_replace] + bubble_history_up( hash_replace, structure.tree,", "only check that the user's command can # be executed", "from the idea that, for lists of length n, insertions", "reinsert_later_hash = node_for_s_address(structure.tree, structure.s_cursor).metadata.nout_hash p0, hash_after_deletion = calc_possibility(NoteSlur(Delete(delete_at_index), delete_from_hash)) p1,", "at lower indices # than the deletions, they will affect", "len(parent_node.children) - 1 - 1, # len - 1 idiom;", "cursor position) posacts = [p] + bubble_history_up(h, structure.tree, delete_from) return", "calc_possibility( NoteSlur(Replace(replace_at_index, hash_enclosure), replace_on_hash)) posacts = [p_capo, p_create, p_enclosure, p_replace]", "the selection disappears automatically, because it points at a no-longer", "number of insertions that happened. (If we reverse the order", "# There is no need to check that the new", "the same, but also if one parent is a prefix", "deletion) p, hash_ = calc_possibility(NoteSlur(Delete(source_index_lo + weave_correction), hash_)) posacts.append(p) if", "same reasons detailed in the comment on # InsertNodeSibbling return", "= source_index_hi - source_index_lo + 1 # we do _not_", "selection_edge_1[:-1]: # i.e. if not same-parent: this is an error.", "For now I'm disallowing it; we'll see whether a use", "that happened. (If we reverse the order of operations, we", "around (because everything descends from the root node) return an_error()", "<= index <= len(parent.children) - 1): return an_error() return move_cursor(s_cursor[:-1]", "note the move here. posacts = [] source_index_lo, source_index_hi =", "insert\"; if (or when) we'll introduce # \"Move\" into the", "[], False if isinstance(edit_note, CursorDFS): dfs = s_dfs(structure.tree, []) dfs_index", "the math), but I still have a sense that it", "# Root cannot die # For now, LeaveChildrenBehind is simply", "calc_possibility(NoteSlur(BecomeNode(), hash_capo)) p_enclosure, hash_enclosure = calc_possibility(NoteSlur(Insert(0, reinsert_later_hash), hash_create)) p_replace, hash_replace", "child-of-yourself checks at the top. weave_correction = source_index_hi - source_index_lo", "root is assumed to exist.) return an_error() delete_from = structure.s_cursor[:-1]", "simply implemented as a \"insert and delete\"; if (or when)", "edit_note.text) new_s_cursor = edit_note.parent_s_address + [edit_note.index] return new_s_cursor, posacts, False", "math), but I still have a sense that it may", "to indices in the # source node, such a single-parent", "the root is not possible (it would lead to a", "range(source_index_lo, source_index_hi + 1): # edge-inclusive range # Note: we", "node, such a single-parent restriction is indeed a necessity. #", "In any case, it's wat e.g. LibreOffice does when cut/pasting.", "s_dfs from dsn.s_expr.legato import NoteSlur, NoteCapo from dsn.s_expr.utils import (", "(or when) we'll introduce \"Move\" into # the Clef, we", "user's # point of view in a non-atomic way in", "want to make the selection appear at the target-location, we", "\"edit move\" operations are simply implemented as a \"insert and", "hash_)) posacts.append(p) if source_parent_path != target_parent_path: posacts = posacts +", "= s_cursor[-1] + edit_node.direction if not (0 <= index <=", "# number of insertions that happened. (If we reverse the", "= insert_text_at(structure.tree, edit_note.parent_s_address, edit_note.index, edit_note.text) new_s_cursor = edit_note.parent_s_address + [edit_note.index]", "after each deletion) p, hash_ = calc_possibility(NoteSlur(Delete(source_index_lo + weave_correction), hash_))", "source_parent_path != target_parent_path: posacts = posacts + weave_disjoint_replaces( structure.tree, target_parent_path,", "required\". # In the if-statement above, we could pick either", "posacts = posacts + weave_disjoint_replaces( structure.tree, target_parent_path, wdr_hash, source_parent_path, hash_)", "[], True if isinstance(edit_note, TextInsert): posacts = insert_text_at(structure.tree, edit_note.parent_s_address, edit_note.index,", "Generally, the paths towards relaxation are to either [a] \"be", "target-location, we need to change the interface of edit_note_play to", "- 1] = min( len(parent_node.children) - 1 - 1, #", "to move to [a descendant of] yourself. This is illegal.", "source_index_lo: # We insert before we delete. If we do", "EDelete): if structure.s_cursor == []: # silently ignored ('delete root'", "at the \"lo\" index (everything shifting to the left after", "notes for the editor clef\", which may be thought of", "case arises. return an_error() # For now, EncloseWithParent is simply", "well be too restrictive, but I'd rather move in the", "once we build the cooperative # editor) we should be", "= node_for_s_address(structure.tree, structure.s_cursor) if not hasattr(cursor_node, 'children') or len(cursor_node.children) ==", "\"delete and insert\"; if (or when) we'll introduce # \"Move\"", "the deletions, they will affect the locations where the deletions", "1]; such assumptions fit with the general idea of \"we", "\"we only check that the user's command can # be", "paths towards relaxation are to either [a] \"be smart about", "as \"executing editor commands\". NOTE: in the below, we often", "need to check that the new index is a valid", "'children'): return an_error() # Leave _children_ behind presupposes the existance", "comment on # InsertNodeSibbling return do_move(structure, edit_note, structure.s_cursor[:-1], structure.s_cursor[-1] +", "== []: return an_error() # adding sibblings to the root", "= node_for_s_address(structure.tree, structure.s_cursor) if not isinstance(cursor_node, TreeNode): # for now...", "do_move(structure, edit_note, structure.s_cursor[:-1], structure.s_cursor[-1] + edit_note.direction) if isinstance(edit_note, LeaveChildrenBehind): cursor_node", "hash_create = calc_possibility(NoteSlur(BecomeNode(), hash_capo)) p_enclosure, hash_enclosure = calc_possibility(NoteSlur(Insert(0, reinsert_later_hash), hash_create))", "at the target-location, we need to change the interface of", "children if structure.s_cursor == []: return an_error() # Root cannot", "source_index_lo + 1 # we do _not_ fetch hash_ here,", "[index] return new_s_cursor, posacts, False if isinstance(edit_note, EDelete): if structure.s_cursor", "InsertNodeChild): cursor_node = node_for_s_address(structure.tree, structure.s_cursor) if not isinstance(cursor_node, TreeNode): #", "automatically, because it points at a no-longer existing location. If", "return structure.s_cursor, [], True if selection_edge_0[:-1] != selection_edge_1[:-1]: # i.e.", "a necessity. # Note that \"single parent\" implies \"same depth\",", "edit_note.selection_edge_1 def an_error(): return structure.s_cursor, [], True if selection_edge_0[:-1] !=", "hash_enclosure), replace_on_hash)) posacts = [p_capo, p_create, p_enclosure, p_replace] + bubble_history_up(", "reasons detailed in the comment on # InsertNodeSibbling return do_move(structure,", "or len(cursor_node.children) == 0: return an_error() return move_cursor(structure.s_cursor + [0])", "hash_ = source_parent.metadata.nout_hash else: if target_index < source_index_lo: # We", "just Delete n times at the \"lo\" index (everything shifting", "(Assuming: the cursor is valid, and direction is # in", "isinstance(edit_note, MoveSelectionChild): cursor_node = node_for_s_address(structure.tree, structure.s_cursor) if not hasattr(cursor_node, 'children'):", "bubble up (yet); we can do a single bubble-up for", "see any direct # objections (by which I mean: it's", "error. This may very well be too restrictive, but I'd", "note the move here. parent_s_address = structure.s_cursor[:-1] replace_at_index = structure.s_cursor[-1]", "edge-inclusive range insert_hash = node_for_s_address(structure.tree, source_parent_path + [source_index]).metadata.nout_hash p, hash_", "\"same depth\" instead. # Generally, the paths towards relaxation are", "= 0 cursor_correction = 0 # TODO this part is", "# The reason we have this problem at all, is", "to the source path) could at least be understood to", "for the same reasons detailed in the comment on #", "direction of \"relax constraints later\" than in the other directions.", "= node_for_s_address(structure.tree, target_parent_path) # For now, the \"edit move\" operations", "those together, rewriting indices as required\". # In the if-statement", "exactly the same, but also if one parent is a", "def an_error(): return structure.s_cursor, [], True if isinstance(edit_note, TextInsert): posacts", "calc_possibility(NoteSlur(Insert(index, reinsert_later_hash), hash_after_deletion)) new_cursor = structure.s_cursor[:-1] + [index] posacts =", "h = calc_possibility(NoteSlur(Delete(delete_at_index), delete_from_hash)) if delete_at_index == len(node_for_s_address(structure.tree, delete_from).children) -", "being: it's the hash we just created. # nor do", "problem is once we have some tools to \"realinearize while", "some asymmetries. For now I'm disallowing it; we'll see whether", "structure.s_cursor[:-1], index) new_s_cursor = structure.s_cursor[:-1] + [index] return new_s_cursor, posacts,", "as a \"delete and insert\"; if (or when) we'll introduce", "intuitive\" (but # that may just be habituation). In any", "don't find that enough, so I'm just calling both scenarios", "= calc_possibility(NoteSlur(Delete(delete_at_index), delete_from_hash)) posacts = [p] removed_node = node_for_s_address(structure.tree, structure.s_cursor)", "# direction of \"relax constraints later\" than in the other", "insert\"; if (or when) we'll introduce \"Move\" into # the", "posacts, False if isinstance(edit_note, MoveSelectionChild): cursor_node = node_for_s_address(structure.tree, structure.s_cursor) if", "directly # from the idea that, for lists of length", "a target_node, a source node and to indices in the", "the root node around (because everything descends from the root", "operations, we have the opposite problem) # The reason we", "cut/pasting. (However, for a # mouse-drag initiated move in LibreOffice,", "= len(cursor_node.children) posacts = insert_node_at(structure.tree, structure.s_cursor, index) new_s_cursor = structure.s_cursor", "move in the # direction of \"relax constraints later\" than", "the first common ancestor and the relevant children of that", "make sure to stay in bounds. new_cursor[len(new_cursor) - 1] =", "hash_ = calc_possibility(NoteSlur(Delete(source_index_lo + weave_correction), hash_)) posacts.append(p) if source_parent_path !=", "only if the parents are exactly the same, but also", "case, it's wat e.g. LibreOffice does when cut/pasting. (However, for", "= node_for_s_address(structure.tree, source_parent_path) target_parent = node_for_s_address(structure.tree, target_parent_path) # For now,", "source_parent_path) target_parent = node_for_s_address(structure.tree, target_parent_path) # For now, the \"edit", "posacts = insert_node_at(structure.tree, structure.s_cursor, index) new_s_cursor = structure.s_cursor + [index]", "the paths towards relaxation are to either [a] \"be smart", "back to the parent new_cursor = parent_s_address else: # otherwise,", "same location (single source item, target path # identical to", "to a forest) # There is no need to check", "bounds. new_cursor[len(new_cursor) - 1] = min( len(parent_node.children) - 1 -", "node_for_s_address(structure.tree, structure.s_cursor[:-1]) index = structure.s_cursor[-1] + edit_note.direction if not (0", "I'd rather move in the # direction of \"relax constraints", "edit_note.parent_s_address + [edit_note.index] return new_s_cursor, posacts, False if isinstance(edit_note, TextReplace):", "= calc_possibility(NoteSlur(Insert(0, reinsert_later_hash), hash_create)) p_replace, hash_replace = calc_possibility( NoteSlur(Replace(replace_at_index, hash_enclosure),", "else: cursor_correction = source_index_hi - source_index_lo + 1 # we", "selection_edge_0 = edit_note.selection_edge_0 selection_edge_1 = edit_note.selection_edge_1 def an_error(): return structure.s_cursor,", "target location, truncated to the length of the sources, is", "location: new_cursor = structure.s_cursor + [0] return new_cursor, posacts, False", "on the same parent, and the insertions happen at lower", "never straddle target_index, because of the child-of-yourself checks at the", "hasattr(cursor_node, 'children'): return an_error() # The target must be a", "sibbling of the root node # edit_note.direction points to a", "return an_error() # For now, EncloseWithParent is simply implemented as", "move here. posacts = [] source_index_lo, source_index_hi = sorted([selection_edge_0[-1], selection_edge_1[-1]])", "the same \"future\". But in the case of shared prefix,", "way in the clef. The problem may auto-disappear if we", "parent\" implies \"same depth\", but not vice versa. One possible", "very well be too restrictive, but I'd rather move in", "here). The proof flows directly # from the idea that,", "to \"realinearize while preserving # meaning\". I.e. we have deletions,", "SwapSibbling is simply implemented as a \"delete and insert\"; if", "about this one yet: should we have the option to", "to leave behind... this \"right spot\" may be illegal parent_node", "the move here. posacts = [] source_index_lo, source_index_hi = sorted([selection_edge_0[-1],", "something to a child of itself: # I simply don't", "= node_for_s_address(structure.tree, structure.s_cursor) for i, child in enumerate(removed_node.children): p, hash_", "0 cursor_correction = 0 # TODO this part is still", "move_cursor(structure.s_cursor[:-1]) if isinstance(edit_note, CursorChild): cursor_node = node_for_s_address(structure.tree, structure.s_cursor) if not", "depth\" instead. # Generally, the paths towards relaxation are to", "you to continue operating on the the same \"future\". But", "deletion makes cursor pos invalid: up to parent (alternative: sibbling-up", "# clef. # Another way we could handle the problem", "if isinstance(edit_note, CursorChild): cursor_node = node_for_s_address(structure.tree, structure.s_cursor) if not hasattr(cursor_node,", "is simply implemented as a \"delete and insert\"; if (or", "range [0, 1]; such assumptions fit with the general idea", "edit_note_play to # include the resulting selection. new_cursor = target_parent_path", "connect notes together \"manually\", i.e. using NoteSlur(..., previous_hash). As an", "TreeNode from dsn.editor.clef import ( CursorChild, CursorDFS, CursorParent, CursorSet, EDelete,", "delete_from = structure.s_cursor[:-1] delete_at_index = structure.s_cursor[-1] delete_from_hash = node_for_s_address(structure.tree, delete_from).metadata.nout_hash", "bubble_history_up(h, structure.tree, delete_from) return new_s_cursor, posacts, False if isinstance(edit_note, SwapSibbling):", "if structure.s_cursor == []: return an_error() # root has no", "no sibblings parent = node_for_s_address(structure.tree, structure.s_cursor[:-1]) index = structure.s_cursor[-1] +", "0: return an_error() return move_cursor(structure.s_cursor + [0]) raise Exception(\"Unknown Note\")", "# in the range [0, 1]; such assumptions fit with", "indices in the # source node, such a single-parent restriction", "commands\". NOTE: in the below, we often connect notes together", "edges\", i.e. find the first common ancestor and the relevant", "new_cursor, posacts, False if isinstance(edit_note, MoveSelectionChild): cursor_node = node_for_s_address(structure.tree, structure.s_cursor)", "calc_possibility(NoteSlur(Delete(delete_at_index), delete_from_hash)) if delete_at_index == len(node_for_s_address(structure.tree, delete_from).children) - 1: #", "less # meaningless, but here I don't find that enough,", "len(structure.s_cursor) == 0: return an_error() # there is no sibbling", "The problem may auto-disappear if we add \"Move\" to the", "executed at this point, we do not check for arbitrary", "weave_disjoint_replaces, ) from dsn.s_expr.clef import Delete, Insert, Replace, BecomeNode from", "s_cursor[-1] + edit_node.direction if not (0 <= index <= len(parent.children)", "= node_for_s_address(structure.tree, parent_s_address).metadata.nout_hash p, hash_ = calc_possibility(NoteSlur(Delete(delete_at_index), delete_from_hash)) posacts =", "restriction is indeed a necessity. # Note that \"single parent\"", "will affect the locations where the deletions must take place,", "affect the locations where the deletions must take place, by", "am not sure about this one yet: should we have", "in range(source_index_lo, source_index_hi + 1): # edge-inclusive range # Note:", "structure.s_cursor + [0] return new_cursor, posacts, False def move_cursor(new_cursor): return", "this part is still broken: # Not only if the", "structure.s_cursor if len(removed_node.children) == 0: # ... however, if there", "(e.g. once we build the cooperative # editor) we should", "also if one parent is a prefix of the other", "in place (although new contents slide into the cursor position)", "hash we just created. # nor do we bubble up", "because it points at a no-longer existing location. If we", "stands: the selection disappears automatically, because it points at a", "= calc_possibility(NoteSlur(Insert(index, reinsert_later_hash), hash_after_deletion)) new_cursor = structure.s_cursor[:-1] + [index] posacts", "not care so # much about single-parent. return an_error() if", "to not care so # much about single-parent. return an_error()", "note the move here. parent_s_address = structure.s_cursor[:-1] delete_at_index = structure.s_cursor[-1]", "posacts, error def an_error(): return structure.s_cursor, [], True if isinstance(edit_note,", "# mouse-drag initiated move in LibreOffice, the selection is preserved).", "existance of children if structure.s_cursor == []: return an_error() #", "I don't find that enough, so I'm just calling both", "False if isinstance(edit_note, InsertNodeSibbling): if structure.s_cursor == []: return an_error()", "to express \"weave those together, rewriting indices as required\". #", "after the move\" is \"at the end\". This \"seems intuitive\"", "new_cursor = parent_s_address else: # otherwise, make sure to stay", "return new_cursor, posacts, False def move_cursor(new_cursor): return new_cursor, [], False", "no need to check that the new index is a", "= structure.s_cursor[-1] + edit_note.direction if not (0 <= index <=", "an error. This may very well be too restrictive, but", "build the cooperative # editor) we should be able to", "NoteSlur(..., previous_hash). As an alternative, we could consider `nouts_for_notes`. \"\"\"", "spot\" may be illegal parent_node = node_for_s_address(structure.tree, parent_s_address) if len(parent_node.children)", "ever want to express a note \"move\" using a target_node,", "do this on the same parent, and the insertions happen", "shifting to the left after each deletion) p, hash_ =", "that, for lists of length n, insertions at [0, n]", "# :: EditStructure, EditNote => (new) s_cursor, posacts, error def", "+ 1): # edge-inclusive range # Note: we just Delete", "for arbitrary programming errors here). The proof flows directly #", "NoteSlur(Replace(replace_at_index, hash_enclosure), replace_on_hash)) posacts = [p_capo, p_create, p_enclosure, p_replace] +", "\"single parent\" implies \"same depth\", but not vice versa. One", "forest) # There is no need to check that the", "import TreeNode from dsn.editor.clef import ( CursorChild, CursorDFS, CursorParent, CursorSet,", "structure.s_cursor[-1] + edit_note.direction) if isinstance(edit_note, LeaveChildrenBehind): cursor_node = node_for_s_address(structure.tree, structure.s_cursor)", "such a single-parent restriction is indeed a necessity. # Note", "case, we need to somehow connect the parents.... # (For", "the other (said differently: # the longest_common_prefix of both parents", "In the if-statement above, we could pick either lo/hi for", "( bubble_history_up, calc_possibility, insert_text_at, insert_node_at, replace_text_at, weave_disjoint_replaces, ) from dsn.s_expr.clef", "# For now, the \"edit move\" operations are simply implemented", ":: EditStructure, EditNote => (new) s_cursor, posacts, error def an_error():", "Note that \"single parent\" implies \"same depth\", but not vice", "now, LeaveChildrenBehind is simply implemented as a \"delete and insert\";", "in LibreOffice, the selection is preserved). # As it stands:", "no sibbling of the root node # edit_note.direction points to", "if isinstance(edit_note, InsertNodeChild): cursor_node = node_for_s_address(structure.tree, structure.s_cursor) if not isinstance(cursor_node,", "one point (e.g. once we build the cooperative # editor)", "+ bubble_history_up( hash_replace, structure.tree, parent_s_address) # We jump the cursor", "# root has no sibblings parent = node_for_s_address(structure.tree, s_cursor[:-1]) index", "that enough, so I'm just calling both scenarios error-scenarios. #", "an_error() return move_cursor(structure.s_cursor[:-1]) if isinstance(edit_note, CursorChild): cursor_node = node_for_s_address(structure.tree, structure.s_cursor)", "target_node, a source node and to indices in the #", "case of shared prefix, this won't # work. if source_parent_path", "posacts + weave_disjoint_replaces( structure.tree, target_parent_path, wdr_hash, source_parent_path, hash_) else: posacts", "right spot new_cursor = structure.s_cursor if len(removed_node.children) == 0: #", "isinstance(edit_note, CursorDFS): dfs = s_dfs(structure.tree, []) dfs_index = dfs.index(structure.s_cursor) +", "invalid: up to parent (alternative: sibbling-up first, until no more", "# InsertNodeSibbling return do_move(structure, edit_note, structure.s_cursor[:-1], structure.s_cursor[-1] + edit_note.direction) if", "nor do we bubble up (yet); we can do a", "on the the same \"future\". But in the case of", "# In that case, we need to somehow connect the", "no children to leave behind... this \"right spot\" may be", "+ weave_correction), hash_)) posacts.append(p) if source_parent_path != target_parent_path: posacts =", "1)): # edge-inclusive range insert_hash = node_for_s_address(structure.tree, source_parent_path + [source_index]).metadata.nout_hash", "parent_s_address) # We jump the cursor to the newly enclosed", "order of operations, we have the opposite problem) # The", "which may be thought of as \"executing editor commands\". NOTE:", "clef\", which may be thought of as \"executing editor commands\".", "There is no need to check that the new index", "edit_note.direction posacts = insert_node_at(structure.tree, structure.s_cursor[:-1], index) new_s_cursor = structure.s_cursor[:-1] +", "of shared prefix, this won't # work. if source_parent_path !=", "mean: it's possible in terms of the math), but I", "exist.) return an_error() delete_from = structure.s_cursor[:-1] delete_at_index = structure.s_cursor[-1] delete_from_hash", "editor) we should be able to express \"weave those together,", "== 0: return an_error() return move_cursor(structure.s_cursor + [0]) raise Exception(\"Unknown", "insert_text_at, insert_node_at, replace_text_at, weave_disjoint_replaces, ) from dsn.s_expr.clef import Delete, Insert,", "bubble_history_up(hash_, structure.tree, source_parent_path) # The current solution for \"where to", "I ever want to express a note \"move\" using a", "non-node return an_error() index = len(cursor_node.children) posacts = insert_node_at(structure.tree, structure.s_cursor,", "= min( len(parent_node.children) - 1 - 1, # len -", "structure.s_cursor) if structure.s_cursor == []: # I am not sure", "pick either lo/hi for the comparison; source_index_lo and # source_index_hi", "root node around (because everything descends from the root node)", "an_error() # The target must be a node to be", "that it may # create some asymmetries. For now I'm", ") def edit_note_play(structure, edit_note): # :: EditStructure, EditNote => (new)", "may auto-disappear if we add \"Move\" to the # clef.", "if isinstance(edit_note, TextInsert): posacts = insert_text_at(structure.tree, edit_note.parent_s_address, edit_note.index, edit_note.text) new_s_cursor", "the insertions happen at lower indices # than the deletions,", "edit_note): # :: EditStructure, EditNote => (new) s_cursor, posacts, error", "take place, by precisely the # number of insertions that", "source_index_hi will never straddle target_index, because of the child-of-yourself checks", "need to somehow connect the parents.... # (For the case", "preserving # meaning\". I.e. we have deletions, we have insertions:", "the cursor position) posacts = [p] + bubble_history_up(h, structure.tree, delete_from)", "[index] posacts = [p0, p1] + bubble_history_up(hash_after_insertion, structure.tree, parent_s_address) return", "# silently ignored ('delete root' is not defined, because the", "parent\"; if (or when) we'll introduce # \"Move\" (in particular:", "lead to a forest) # There is no need to", "the idea that, for lists of length n, insertions at", "\"seems intuitive\" (but # that may just be habituation). In", "has no sibblings parent = node_for_s_address(structure.tree, s_cursor[:-1]) index = s_cursor[-1]", "bubble-up for source_index in range(source_index_lo, source_index_hi + 1): # edge-inclusive", "delete_from_hash)) if delete_at_index == len(node_for_s_address(structure.tree, delete_from).children) - 1: # deletion", "move\" operations are simply implemented as a \"insert and delete\";", "posacts.append(p) if source_parent_path != target_parent_path: posacts = posacts + weave_disjoint_replaces(", "if source_parent_path != target_parent_path: wdr_hash = hash_ hash_ = source_parent.metadata.nout_hash", "insertion point for the same reasons detailed in the comment", "the root node # edit_note.direction points to a valid insertion", "hash_ hash_ = source_parent.metadata.nout_hash else: if target_index < source_index_lo: #", "- source_index_lo + 1 # we do _not_ fetch hash_", "the opposite problem) # The reason we have this problem", "scenarios error-scenarios. # This implies protection against moving the root", "The current solution for \"where to put the cursor after", "newly enclosed location: new_cursor = structure.s_cursor + [0] return new_cursor,", "this one yet: should we have the option to create", "hash_ = target_parent.metadata.nout_hash for target_offset, source_index in enumerate(range(source_index_lo, source_index_hi +", "target_parent_path: posacts = posacts + weave_disjoint_replaces( structure.tree, target_parent_path, wdr_hash, source_parent_path,", "I don't see any direct # objections (by which I", "node_for_s_address(structure.tree, structure.s_cursor) if not hasattr(cursor_node, 'children'): return an_error() # The", "we do this on the same parent, and the insertions", "\"right spot\" may be illegal parent_node = node_for_s_address(structure.tree, parent_s_address) if", "if one parent is a prefix of the other (said", "insertions at [0, n] are valid (insertion at n being", "an_error() source_parent_path = selection_edge_0[:-1] source_parent = node_for_s_address(structure.tree, source_parent_path) target_parent =", "is once we have some tools to \"realinearize while preserving", "= structure.s_cursor[-1] replace_on_hash = node_for_s_address(structure.tree, parent_s_address).metadata.nout_hash reinsert_later_hash = node_for_s_address(structure.tree, structure.s_cursor).metadata.nout_hash", "LeaveChildrenBehind): cursor_node = node_for_s_address(structure.tree, structure.s_cursor) if not hasattr(cursor_node, 'children'): return", "care so # much about single-parent. return an_error() if selection_edge_0", "node around (because everything descends from the root node) return", "InsertNodeChild, InsertNodeSibbling, MoveSelectionChild, MoveSelectionSibbling, LeaveChildrenBehind, SwapSibbling, TextInsert, TextReplace, ) def", "for \"where to put the cursor after the move\" is", "that ancestor or [b] to not care so # much", "It looks like this: if structure.s_cursor == []: return an_error()", "= sorted([selection_edge_0[-1], selection_edge_1[-1]]) hash_ = target_parent.metadata.nout_hash for target_offset, source_index in", "# from the idea that, for lists of length n,", "for now... we just silently ignore the user's request when", "and the relevant children of that ancestor or [b] to", "len - 1 idiom; -1 for deletion. new_cursor[len(new_cursor) - 1])", "EncloseWithParent, InsertNodeChild, InsertNodeSibbling, MoveSelectionChild, MoveSelectionSibbling, LeaveChildrenBehind, SwapSibbling, TextInsert, TextReplace, )", "if isinstance(edit_note, CursorSet): return move_cursor(edit_note.s_address) if isinstance(edit_note, CursorParent): if structure.s_cursor", "option to create a new root? I don't see any", "posacts, False if isinstance(edit_note, EDelete): if structure.s_cursor == []: #", "node_for_s_address, s_dfs from dsn.s_expr.legato import NoteSlur, NoteCapo from dsn.s_expr.utils import", "\"\"\" Tools to \"play notes for the editor clef\", which", "in enumerate(removed_node.children): p, hash_ = calc_possibility(NoteSlur(Insert(structure.s_cursor[-1] + i, child.metadata.nout_hash), hash_))", "the resulting selection. new_cursor = target_parent_path + [target_index + target_offset", "n] are valid (insertion at n being an append). index", "fall back to the parent new_cursor = parent_s_address else: #", "len(parent.children) - 1): return an_error() # For now, SwapSibbling is", "= [p_capo, p_create, p_enclosure, p_replace] + bubble_history_up( hash_replace, structure.tree, parent_s_address)", "not (0 <= index <= len(parent.children) - 1): return an_error()", "the new index is a valid one. (Assuming: the cursor", "child node to a non-node return an_error() index = len(cursor_node.children)", "s_address import node_for_s_address, s_dfs from dsn.s_expr.legato import NoteSlur, NoteCapo from", "are exactly the same, but also if one parent is", "if structure.s_cursor == []: return an_error() # Root cannot die", "restrictive # for now: if I ever want to express", "make the # restriction on \"same depth\" instead. # Generally,", "is no need to check that the new index is", "source_parent_path) # The current solution for \"where to put the", "index = len(cursor_node.children) posacts = insert_node_at(structure.tree, structure.s_cursor, index) new_s_cursor =", "p, hash_ = calc_possibility(NoteSlur(Delete(source_index_lo + weave_correction), hash_)) posacts.append(p) if source_parent_path", "notes together \"manually\", i.e. using NoteSlur(..., previous_hash). As an alternative,", "at one point (e.g. once we build the cooperative #", "posacts.append(p) # In general, leaving the cursor at the same", "(or when) we'll introduce # \"Move\" into the Clef, we", "return an_error() # The target must be a node to", "when) we'll introduce # \"Move\" (in particular: the MoveReplace) into", "point of view in a non-atomic way in the clef.", "a valid insertion point for the same reasons detailed in", "so it's slightly less # meaningless, but here I don't", "to express a note \"move\" using a target_node, a source", "# edge-inclusive range insert_hash = node_for_s_address(structure.tree, source_parent_path + [source_index]).metadata.nout_hash p,", "=> (new) s_cursor, posacts, error def an_error(): return structure.s_cursor, [],", "\"\"\" from s_address import node_for_s_address, s_dfs from dsn.s_expr.legato import NoteSlur,", "source_index_lo, source_index_hi = sorted([selection_edge_0[-1], selection_edge_1[-1]]) hash_ = target_parent.metadata.nout_hash for target_offset,", "len(parent.children) - 1): return an_error() return move_cursor(s_cursor[:-1] + [index]) \"\"\"", "any direct # objections (by which I mean: it's possible", "SwapSibbling, TextInsert, TextReplace, ) def edit_note_play(structure, edit_note): # :: EditStructure,", "silently ignored ('delete root' is not defined, because the root", "have the option to create a new root? I don't", "arises. return an_error() # For now, EncloseWithParent is simply implemented", "if not hasattr(cursor_node, 'children') or len(cursor_node.children) == 0: return an_error()", "find that enough, so I'm just calling both scenarios error-scenarios.", "target_parent_path) # For now, the \"edit move\" operations are simply", "return an_error() # Root cannot die # For now, LeaveChildrenBehind", "True if selection_edge_0[:-1] != selection_edge_1[:-1]: # i.e. if not same-parent:", "wdr_hash, source_parent_path, hash_) else: posacts = posacts + bubble_history_up(hash_, structure.tree,", "False if isinstance(edit_note, TextReplace): posacts = replace_text_at(structure.tree, edit_note.s_address, edit_note.text) return", "idea \"just don't reset hash_\"... which works, # because it", "structure.s_cursor).metadata.nout_hash p_capo, hash_capo = calc_possibility(NoteCapo()) p_create, hash_create = calc_possibility(NoteSlur(BecomeNode(), hash_capo))", "delete. If we do this on the same parent, and", "index) new_s_cursor = structure.s_cursor[:-1] + [index] return new_s_cursor, posacts, False", "be able to add as a child return do_move(structure, edit_note,", "Clef, we should note the move here. parent_s_address = structure.s_cursor[:-1]", "if len(parent_node.children) == 1: # if the deleted node was", "operating on the the same \"future\". But in the case", "other directions. One particular reason I'm so restrictive # for", "if isinstance(edit_note, MoveSelectionChild): cursor_node = node_for_s_address(structure.tree, structure.s_cursor) if not hasattr(cursor_node,", "the child-of-yourself checks at the top. weave_correction = source_index_hi -", "in the clef. The problem may auto-disappear if we add", "return edit_note.s_address, posacts, False if isinstance(edit_note, InsertNodeSibbling): if structure.s_cursor ==", "new_cursor[len(new_cursor) - 1] = min( len(parent_node.children) - 1 - 1,", "= structure.s_cursor[:-1] delete_at_index = structure.s_cursor[-1] delete_from_hash = node_for_s_address(structure.tree, delete_from).metadata.nout_hash p,", "\"insert and delete\"; if (or when) we'll introduce # \"Move\"", "prefix, this won't # work. if source_parent_path != target_parent_path: wdr_hash", "# I simply don't know what it would mean. Moving", "posacts = insert_text_at(structure.tree, edit_note.parent_s_address, edit_note.index, edit_note.text) new_s_cursor = edit_note.parent_s_address +", "len(node_for_s_address(structure.tree, delete_from).children) - 1: # deletion makes cursor pos invalid:", "but not vice versa. One possible relaxation is: make the", "that the user's command can # be executed at this", "if target_index < source_index_lo: # We insert before we delete.", "source_parent_path, hash_) else: posacts = posacts + bubble_history_up(hash_, structure.tree, source_parent_path)", "make the selection appear at the target-location, we need to", "p_create, p_enclosure, p_replace] + bubble_history_up( hash_replace, structure.tree, parent_s_address) # We", "\"Move\" into # the Clef, we should note the move", "no more sibblings) new_s_cursor = delete_from else: new_s_cursor = structure.s_cursor", "= node_for_s_address(structure.tree, parent_s_address) if len(parent_node.children) == 1: # if the", "- 1]) posacts += bubble_history_up(hash_, structure.tree, parent_s_address) return new_cursor, posacts,", "itself: # I simply don't know what it would mean.", "1): # edge-inclusive range # Note: we just Delete n", "the full target location, truncated to the length of the", "cooperative # editor) we should be able to express \"weave", "# edit_note.direction points to a valid insertion point for the", "structure.s_cursor[:-1] + [index] return new_s_cursor, posacts, False if isinstance(edit_note, InsertNodeChild):", "able to add as a child return do_move(structure, edit_note, structure.s_cursor,", "node_for_s_address(structure.tree, structure.s_cursor).metadata.nout_hash p_capo, hash_capo = calc_possibility(NoteCapo()) p_create, hash_create = calc_possibility(NoteSlur(BecomeNode(),", "= source_parent.metadata.nout_hash else: if target_index < source_index_lo: # We insert", "(because everything descends from the root node) return an_error() source_parent_path", "(If we reverse the order of operations, we have the", "This implies protection against moving the root node around (because", "other (said differently: # the longest_common_prefix of both parents matches", "cursor_node = node_for_s_address(structure.tree, structure.s_cursor) if not hasattr(cursor_node, 'children') or len(cursor_node.children)", "== len(node_for_s_address(structure.tree, delete_from).children) - 1: # deletion makes cursor pos", "that case, we need to somehow connect the parents.... #", "the target-location, we need to change the interface of edit_note_play", "== []: # silently ignored ('delete root' is not defined,", "child of itself: # I simply don't know what it", "parents matches one of them). # In that case, we", "to stay in bounds. new_cursor[len(new_cursor) - 1] = min( len(parent_node.children)", "single-parent restriction is indeed a necessity. # Note that \"single", "insert_node_at(structure.tree, structure.s_cursor, index) new_s_cursor = structure.s_cursor + [index] return new_s_cursor,", "there are no children to leave behind... this \"right spot\"", "new_cursor, [], False if isinstance(edit_note, CursorDFS): dfs = s_dfs(structure.tree, [])", "otherwise, make sure to stay in bounds. new_cursor[len(new_cursor) - 1]", "sibblings parent = node_for_s_address(structure.tree, structure.s_cursor[:-1]) index = structure.s_cursor[-1] + edit_note.direction", "first, until no more sibblings) new_s_cursor = delete_from else: new_s_cursor", "# (For the case of \"parents match exactly\", I did", "problem may auto-disappear if we add \"Move\" to the #", "to the newly enclosed location: new_cursor = structure.s_cursor + [0]", "(insertion at n being an append). index = structure.s_cursor[-1] +", "that \"single parent\" implies \"same depth\", but not vice versa.", "cursor after the move\" is \"at the end\". This \"seems", "[]: # I am not sure about this one yet:", "= structure.s_cursor[:-1] delete_at_index = structure.s_cursor[-1] delete_from_hash = node_for_s_address(structure.tree, parent_s_address).metadata.nout_hash p,", "edit_note.s_address, posacts, False if isinstance(edit_note, InsertNodeSibbling): if structure.s_cursor == []:", "insertions: at one point (e.g. once we build the cooperative", "below, we often connect notes together \"manually\", i.e. using NoteSlur(...,", "enclosed location: new_cursor = structure.s_cursor + [0] return new_cursor, posacts,", "hash_after_deletion)) new_cursor = structure.s_cursor[:-1] + [index] posacts = [p0, p1]", "together, rewriting indices as required\". # In the if-statement above,", "selection appear at the target-location, we need to change the", "if len(structure.s_cursor) == 0: return an_error() # there is no", "+= bubble_history_up(hash_, structure.tree, parent_s_address) return new_cursor, posacts, False if isinstance(edit_note,", "hash_enclosure = calc_possibility(NoteSlur(Insert(0, reinsert_later_hash), hash_create)) p_replace, hash_replace = calc_possibility( NoteSlur(Replace(replace_at_index,", "Delete, Insert, Replace, BecomeNode from dsn.s_expr.structure import TreeNode from dsn.editor.clef", "import NoteSlur, NoteCapo from dsn.s_expr.utils import ( bubble_history_up, calc_possibility, insert_text_at,", "a \"delete and insert\"; if (or when) we'll introduce \"Move\"", "isinstance(edit_note, SwapSibbling): if structure.s_cursor == []: return an_error() # root", "in the case of shared prefix, this won't # work.", "# identical to the source path) could at least be", "moving the root node around (because everything descends from the", "general idea of \"we only check that the user's command", "if not same-parent: this is an error. This may very", "source node and to indices in the # source node,", "= structure.s_cursor[:-1] + [index] return new_s_cursor, posacts, False if isinstance(edit_note,", "edit_note.selection_edge_0 selection_edge_1 = edit_note.selection_edge_1 def an_error(): return structure.s_cursor, [], True", "<= dfs_index <= len(dfs) - 1): return an_error() return move_cursor(dfs[dfs_index])", "yourself. This is illegal. Moving something to a child of", "sibbling\" (as opposed to DFS sibbling) in the edit_clef. It", "use case arises. return an_error() # For now, EncloseWithParent is", "same parent, and the insertions happen at lower indices #", "don't reset hash_\"... which works, # because it allows you", "from dsn.s_expr.legato import NoteSlur, NoteCapo from dsn.s_expr.utils import ( bubble_history_up,", "return an_error() # For now, SwapSibbling is simply implemented as", "selection_edge_1[-1]]) hash_ = target_parent.metadata.nout_hash for target_offset, source_index in enumerate(range(source_index_lo, source_index_hi", "detailed in the comment on # InsertNodeSibbling return do_move(structure, edit_note,", "an alternative, we could consider `nouts_for_notes`. \"\"\" from s_address import", "defined, because the root is assumed to exist.) return an_error()", "checks at the top. weave_correction = source_index_hi - source_index_lo +", "just silently ignore the user's request when they ask to", "isinstance(edit_note, CursorSet): return move_cursor(edit_note.s_address) if isinstance(edit_note, CursorParent): if structure.s_cursor ==", "if delete_at_index == len(node_for_s_address(structure.tree, delete_from).children) - 1: # deletion makes", "it's slightly less # meaningless, but here I don't find", "This may very well be too restrictive, but I'd rather", "top. weave_correction = source_index_hi - source_index_lo + 1 else: cursor_correction", "1 # we do _not_ fetch hash_ here, the idea", "user's command can # be executed at this point, we", "source item, target path # identical to the source path)", "of view in a non-atomic way in the clef. The", "delete_at_index = structure.s_cursor[-1] delete_from_hash = node_for_s_address(structure.tree, parent_s_address).metadata.nout_hash reinsert_later_hash = node_for_s_address(structure.tree,", "won't # work. if source_parent_path != target_parent_path: wdr_hash = hash_", "we have insertions: at one point (e.g. once we build", "As an alternative, we could consider `nouts_for_notes`. \"\"\" from s_address", "the move\" is \"at the end\". This \"seems intuitive\" (but", "\"move\" using a target_node, a source node and to indices", "error def an_error(): return structure.s_cursor, [], True if isinstance(edit_note, TextInsert):", "not isinstance(cursor_node, TreeNode): # for now... we just silently ignore", "to add a child node to a non-node return an_error()", "some point I had \"regular sibbling\" (as opposed to DFS", "Not only if the parents are exactly the same, but", "work. if source_parent_path != target_parent_path: wdr_hash = hash_ hash_ =", "to a child of itself: # I simply don't know", "directions. One particular reason I'm so restrictive # for now:", "is not defined, because the root is assumed to exist.)", "the source path) could at least be understood to mean", "<= (target_parent_path + [target_index])[:len(selection_edge_0)] <= selection_edge_1: # If the full", "if (or when) we'll introduce # \"Move\" (in particular: the", "< source_index_lo: # We insert before we delete. If we", "= hash_ hash_ = source_parent.metadata.nout_hash else: if target_index < source_index_lo:", "position) posacts = [p] + bubble_history_up(h, structure.tree, delete_from) return new_s_cursor,", "the comparison; source_index_lo and # source_index_hi will never straddle target_index,", "# Note: we just Delete n times at the \"lo\"", "parent_node = node_for_s_address(structure.tree, parent_s_address) if len(parent_node.children) == 1: # if", "deletions, they will affect the locations where the deletions must", "<= len(parent.children) - 1): return an_error() # For now, SwapSibbling", "the selection is preserved). # As it stands: the selection", "index = s_cursor[-1] + edit_node.direction if not (0 <= index", "cursor is valid, and direction is # in the range", "so # much about single-parent. return an_error() if selection_edge_0 <=", "calling both scenarios error-scenarios. # This implies protection against moving", "delete_at_index == len(node_for_s_address(structure.tree, delete_from).children) - 1: # deletion makes cursor", "it would mean. Moving something to the same location (single", "now, SwapSibbling is simply implemented as a \"delete and insert\";", "could consider `nouts_for_notes`. \"\"\" from s_address import node_for_s_address, s_dfs from", "[p] removed_node = node_for_s_address(structure.tree, structure.s_cursor) for i, child in enumerate(removed_node.children):", "structure.s_cursor, len(cursor_node.children)) if isinstance(edit_note, MoveSelectionSibbling): if len(structure.s_cursor) == 0: return", "# This implies protection against moving the root node around", "the sources, is (inclusively) in the source's range, # you're", "# be executed at this point, we do not check", "structure.s_cursor[:-1]) index = structure.s_cursor[-1] + edit_note.direction if not (0 <=", "posacts, False if isinstance(edit_note, TextReplace): posacts = replace_text_at(structure.tree, edit_note.s_address, edit_note.text)", "new_s_cursor = structure.s_cursor # \"stay in place (although new contents", "return do_move(structure, edit_note, structure.s_cursor, len(cursor_node.children)) if isinstance(edit_note, MoveSelectionSibbling): if len(structure.s_cursor)", "a node to be able to add as a child", "edit_note.index, edit_note.text) new_s_cursor = edit_note.parent_s_address + [edit_note.index] return new_s_cursor, posacts,", "allows you to continue operating on the the same \"future\".", "we just created. # nor do we bubble up (yet);", "and to indices in the # source node, such a", "using the idea \"just don't reset hash_\"... which works, #", "a single bubble-up for source_index in range(source_index_lo, source_index_hi + 1):", "return new_s_cursor, posacts, False if isinstance(edit_note, SwapSibbling): if structure.s_cursor ==", "is \"at the end\". This \"seems intuitive\" (but # that", "(although new contents slide into the cursor position) posacts =", "to somehow connect the parents.... # (For the case of", "pos invalid: up to parent (alternative: sibbling-up first, until no", "reason I'm so restrictive # for now: if I ever", "posacts = insert_node_at(structure.tree, structure.s_cursor[:-1], index) new_s_cursor = structure.s_cursor[:-1] + [index]", "sure about this one yet: should we have the option", "this won't # work. if source_parent_path != target_parent_path: wdr_hash =", "change the interface of edit_note_play to # include the resulting", "calc_possibility(NoteSlur(Insert(structure.s_cursor[-1] + i, child.metadata.nout_hash), hash_)) posacts.append(p) # In general, leaving", "hash_\"... which works, # because it allows you to continue", "node_for_s_address(structure.tree, structure.s_cursor).metadata.nout_hash p0, hash_after_deletion = calc_possibility(NoteSlur(Delete(delete_at_index), delete_from_hash)) p1, hash_after_insertion =", "the parent\"; if (or when) we'll introduce # \"Move\" (in", "posacts + bubble_history_up(hash_, structure.tree, source_parent_path) # The current solution for", "\"parents match exactly\", I did this using the idea \"just", "simply don't know what it would mean. Moving something to", "children of that ancestor or [b] to not care so", "else: if target_index < source_index_lo: # We insert before we", "deletions, we have insertions: at one point (e.g. once we", "\"where to put the cursor after the move\" is \"at", "is an error. This may very well be too restrictive,", "move here. parent_s_address = structure.s_cursor[:-1] replace_at_index = structure.s_cursor[-1] replace_on_hash =", "p0, hash_after_deletion = calc_possibility(NoteSlur(Delete(delete_at_index), delete_from_hash)) p1, hash_after_insertion = calc_possibility(NoteSlur(Insert(index, reinsert_later_hash),", "to create a new root? I don't see any direct", "+ 1 else: cursor_correction = source_index_hi - source_index_lo + 1", "lo/hi for the comparison; source_index_lo and # source_index_hi will never", "== []: return an_error() # root has no sibblings parent", "at the top. weave_correction = source_index_hi - source_index_lo + 1", "into the cursor position) posacts = [p] + bubble_history_up(h, structure.tree,", "to exist.) return an_error() delete_from = structure.s_cursor[:-1] delete_at_index = structure.s_cursor[-1]", "delete_from) return new_s_cursor, posacts, False if isinstance(edit_note, SwapSibbling): if structure.s_cursor", "parent_s_address) if len(parent_node.children) == 1: # if the deleted node", "in the comment on # InsertNodeSibbling return do_move(structure, edit_note, structure.s_cursor[:-1],", "and # source_index_hi will never straddle target_index, because of the", "False if isinstance(edit_note, EDelete): if structure.s_cursor == []: # silently", "editor commands\". NOTE: in the below, we often connect notes", "parents.... # (For the case of \"parents match exactly\", I", "an_error() # For now, SwapSibbling is simply implemented as a", "be able to express \"weave those together, rewriting indices as", "CursorParent, CursorSet, EDelete, EncloseWithParent, InsertNodeChild, InsertNodeSibbling, MoveSelectionChild, MoveSelectionSibbling, LeaveChildrenBehind, SwapSibbling,", "same \"future\". But in the case of shared prefix, this", "end\". This \"seems intuitive\" (but # that may just be", "in a non-atomic way in the clef. The problem may", "index (everything shifting to the left after each deletion) p,", "def edit_note_play(structure, edit_note): # :: EditStructure, EditNote => (new) s_cursor,", "presupposes the existance of children if structure.s_cursor == []: return", "idiom; -1 for deletion. new_cursor[len(new_cursor) - 1]) posacts += bubble_history_up(hash_,", "idea of \"we only check that the user's command can", "[p] + bubble_history_up(h, structure.tree, delete_from) return new_s_cursor, posacts, False if", "MoveSelectionSibbling, LeaveChildrenBehind, SwapSibbling, TextInsert, TextReplace, ) def edit_note_play(structure, edit_note): #", "should note the move here. posacts = [] source_index_lo, source_index_hi", "of \"relax constraints later\" than in the other directions. One", "= node_for_s_address(structure.tree, structure.s_cursor).metadata.nout_hash p_capo, hash_capo = calc_possibility(NoteCapo()) p_create, hash_create =", "happen at lower indices # than the deletions, they will", "because the root is assumed to exist.) return an_error() delete_from", "\"future\". But in the case of shared prefix, this won't", "a non-atomic way in the clef. The problem may auto-disappear", "assumptions fit with the general idea of \"we only check", "I'm just calling both scenarios error-scenarios. # This implies protection", "dfs = s_dfs(structure.tree, []) dfs_index = dfs.index(structure.s_cursor) + edit_note.direction if", "hasattr(cursor_node, 'children') or len(cursor_node.children) == 0: return an_error() return move_cursor(structure.s_cursor", "One particular reason I'm so restrictive # for now: if", "opposite problem) # The reason we have this problem at", "of that ancestor or [b] to not care so #", "If we # want to make the selection appear at", "return an_error() index = len(cursor_node.children) posacts = insert_node_at(structure.tree, structure.s_cursor, index)", "\"just don't reset hash_\"... which works, # because it allows", "hash_create)) p_replace, hash_replace = calc_possibility( NoteSlur(Replace(replace_at_index, hash_enclosure), replace_on_hash)) posacts =", "is: make the # restriction on \"same depth\" instead. #", "\"weave those together, rewriting indices as required\". # In the", "of] yourself. This is illegal. Moving something to a child", "may just be habituation). In any case, it's wat e.g.", "just be habituation). In any case, it's wat e.g. LibreOffice", "point for the same reasons detailed in the comment on", "the selection's # edges\", i.e. find the first common ancestor", "= calc_possibility(NoteSlur(Insert(target_index + target_offset, insert_hash), hash_)) posacts.append(p) weave_correction = 0", "posacts = [] source_index_lo, source_index_hi = sorted([selection_edge_0[-1], selection_edge_1[-1]]) hash_ =", "comparison; source_index_lo and # source_index_hi will never straddle target_index, because", "posacts, False if isinstance(edit_note, EncloseWithParent): cursor_node = node_for_s_address(structure.tree, structure.s_cursor) if", "trying to move to [a descendant of] yourself. This is", "just calling both scenarios error-scenarios. # This implies protection against", "the right spot new_cursor = structure.s_cursor if len(removed_node.children) == 0:", "straddle target_index, because of the child-of-yourself checks at the top.", "# \"Move\" into the Clef, we should note the move", "a no-longer existing location. If we # want to make", "posacts = [p0, p1] + bubble_history_up(hash_after_insertion, structure.tree, parent_s_address) return new_cursor,", "behind presupposes the existance of children if structure.s_cursor == []:", "0: return an_error() # there is no sibbling of the", "the top. weave_correction = source_index_hi - source_index_lo + 1 else:", "selection_edge_0[:-1] != selection_edge_1[:-1]: # i.e. if not same-parent: this is", "selection_edge_0 <= (target_parent_path + [target_index])[:len(selection_edge_0)] <= selection_edge_1: # If the", "as required\". # In the if-statement above, we could pick", "so restrictive # for now: if I ever want to", "looks like this: if structure.s_cursor == []: return an_error() #", "than in the other directions. One particular reason I'm so", "the cursor to the newly enclosed location: new_cursor = structure.s_cursor", "valid, and direction is # in the range [0, 1];", "same-parent: this is an error. This may very well be", "them). # In that case, we need to somehow connect", "only node: fall back to the parent new_cursor = parent_s_address", "For now, the \"edit move\" operations are simply implemented as", "the move here. parent_s_address = structure.s_cursor[:-1] replace_at_index = structure.s_cursor[-1] replace_on_hash", "meaning\". I.e. we have deletions, we have insertions: at one", "dsn.s_expr.legato import NoteSlur, NoteCapo from dsn.s_expr.utils import ( bubble_history_up, calc_possibility,", "selection. new_cursor = target_parent_path + [target_index + target_offset - cursor_correction]", "a prefix of the other (said differently: # the longest_common_prefix", "posacts = [p] removed_node = node_for_s_address(structure.tree, structure.s_cursor) for i, child", "= delete_from else: new_s_cursor = structure.s_cursor # \"stay in place", "structure.s_cursor == []: return an_error() # root has no sibblings", "to either [a] \"be smart about the meaning of the", "particular: the MoveReplace) into the Clef, we should note the", "`nouts_for_notes`. \"\"\" from s_address import node_for_s_address, s_dfs from dsn.s_expr.legato import", "target_index < source_index_lo: # We insert before we delete. If", "[index] return new_s_cursor, posacts, False if isinstance(edit_note, InsertNodeChild): cursor_node =", "DFS sibbling) in the edit_clef. It looks like this: if", "times at the \"lo\" index (everything shifting to the left", "= structure.s_cursor # \"stay in place (although new contents slide", "return new_cursor, posacts, False if isinstance(edit_note, MoveSelectionChild): cursor_node = node_for_s_address(structure.tree,", "check for arbitrary programming errors here). The proof flows directly", "if we add \"Move\" to the # clef. # Another", "node_for_s_address(structure.tree, delete_from).metadata.nout_hash p, h = calc_possibility(NoteSlur(Delete(delete_at_index), delete_from_hash)) if delete_at_index ==", "= edit_note.selection_edge_1 def an_error(): return structure.s_cursor, [], True if selection_edge_0[:-1]", "we # want to make the selection appear at the", "we'll see whether a use case arises. return an_error() #", "we have this problem at all, is because we implement", "source_index_lo and # source_index_hi will never straddle target_index, because of", "valid insertion point for the same reasons detailed in the", "return move_cursor(dfs[dfs_index]) \"\"\"At some point I had \"regular sibbling\" (as", "descends from the root node) return an_error() source_parent_path = selection_edge_0[:-1]", "node_for_s_address(structure.tree, parent_s_address).metadata.nout_hash reinsert_later_hash = node_for_s_address(structure.tree, structure.s_cursor).metadata.nout_hash p0, hash_after_deletion = calc_possibility(NoteSlur(Delete(delete_at_index),", "<= selection_edge_1: # If the full target location, truncated to", "index <= len(parent.children) - 1): return an_error() # For now,", "\"lo\" index (everything shifting to the left after each deletion)", "structure.s_cursor # \"stay in place (although new contents slide into", "still broken: # Not only if the parents are exactly", "the root is assumed to exist.) return an_error() delete_from =", "meaning of the selection's # edges\", i.e. find the first", "p_enclosure, hash_enclosure = calc_possibility(NoteSlur(Insert(0, reinsert_later_hash), hash_create)) p_replace, hash_replace = calc_possibility(", "def do_move(structure, edit_note, target_parent_path, target_index): selection_edge_0 = edit_note.selection_edge_0 selection_edge_1 =", "len(cursor_node.children)) if isinstance(edit_note, MoveSelectionSibbling): if len(structure.s_cursor) == 0: return an_error()", "= node_for_s_address(structure.tree, structure.s_cursor) if not hasattr(cursor_node, 'children'): return an_error() #", "= [p] removed_node = node_for_s_address(structure.tree, structure.s_cursor) for i, child in", "common ancestor and the relevant children of that ancestor or", "must be a node to be able to add as", "Another way we could handle the problem is once we", "hash_ = calc_possibility(NoteSlur(Insert(target_index + target_offset, insert_hash), hash_)) posacts.append(p) weave_correction =", "implemented as a \"replace with the parent\"; if (or when)", "# if the deleted node was the only node: fall", "if the deleted node was the only node: fall back", "# I am not sure about this one yet: should", "shared prefix, this won't # work. if source_parent_path != target_parent_path:", "posacts, False if isinstance(edit_note, InsertNodeSibbling): if structure.s_cursor == []: return", "+ [0] return new_cursor, posacts, False def move_cursor(new_cursor): return new_cursor,", "= structure.s_cursor[:-1] + [index] posacts = [p0, p1] + bubble_history_up(hash_after_insertion,", "TextInsert, TextReplace, ) def edit_note_play(structure, edit_note): # :: EditStructure, EditNote", "if (or when) we'll introduce \"Move\" into # the Clef,", "not possible (it would lead to a forest) # There", "# meaningless, but here I don't find that enough, so", "source_parent_path = selection_edge_0[:-1] source_parent = node_for_s_address(structure.tree, source_parent_path) target_parent = node_for_s_address(structure.tree,", "must take place, by precisely the # number of insertions", "the root node) return an_error() source_parent_path = selection_edge_0[:-1] source_parent =", "habituation). In any case, it's wat e.g. LibreOffice does when", "had \"regular sibbling\" (as opposed to DFS sibbling) in the", "+ edit_node.direction if not (0 <= index <= len(parent.children) -", "it's the hash we just created. # nor do we", "I'm disallowing it; we'll see whether a use case arises.", "mean the no-op, so it's slightly less # meaningless, but", "disallowing it; we'll see whether a use case arises. return", "possible (it would lead to a forest) # There is", "(in particular: the MoveReplace) into the Clef, we should note", "move_cursor(dfs[dfs_index]) \"\"\"At some point I had \"regular sibbling\" (as opposed", "if isinstance(edit_note, EncloseWithParent): cursor_node = node_for_s_address(structure.tree, structure.s_cursor) if structure.s_cursor ==", "the option to create a new root? I don't see", "edit_clef. It looks like this: if structure.s_cursor == []: return", "using NoteSlur(..., previous_hash). As an alternative, we could consider `nouts_for_notes`.", "what it would mean. Moving something to the same location", "# TODO this part is still broken: # Not only", "I simply don't know what it would mean. Moving something", "new_s_cursor, posacts, False if isinstance(edit_note, SwapSibbling): if structure.s_cursor == []:", "command can # be executed at this point, we do", "if there are no children to leave behind... this \"right", "calc_possibility(NoteSlur(Insert(0, reinsert_later_hash), hash_create)) p_replace, hash_replace = calc_possibility( NoteSlur(Replace(replace_at_index, hash_enclosure), replace_on_hash))", "silently ignore the user's request when they ask to add", "an_error() # Root cannot die # For now, LeaveChildrenBehind is", "hash_after_deletion = calc_possibility(NoteSlur(Delete(delete_at_index), delete_from_hash)) p1, hash_after_insertion = calc_possibility(NoteSlur(Insert(index, reinsert_later_hash), hash_after_deletion))", "s_address will be great: post-deletion you'll be in the right", "the parents.... # (For the case of \"parents match exactly\",", "at all, is because we implement something that is atomic", "implemented as a \"insert and delete\"; if (or when) we'll", "the idea being: it's the hash we just created. #", "# create some asymmetries. For now I'm disallowing it; we'll", "import node_for_s_address, s_dfs from dsn.s_expr.legato import NoteSlur, NoteCapo from dsn.s_expr.utils", "ignored ('delete root' is not defined, because the root is", "structure.tree, parent_s_address) return new_cursor, posacts, False if isinstance(edit_note, MoveSelectionChild): cursor_node", "p, h = calc_possibility(NoteSlur(Delete(delete_at_index), delete_from_hash)) if delete_at_index == len(node_for_s_address(structure.tree, delete_from).children)", "to # include the resulting selection. new_cursor = target_parent_path +", "sibbling) in the edit_clef. It looks like this: if structure.s_cursor", "= structure.s_cursor[-1] delete_from_hash = node_for_s_address(structure.tree, parent_s_address).metadata.nout_hash p, hash_ = calc_possibility(NoteSlur(Delete(delete_at_index),", "not check for arbitrary programming errors here). The proof flows", "target_parent = node_for_s_address(structure.tree, target_parent_path) # For now, the \"edit move\"", "return an_error() if selection_edge_0 <= (target_parent_path + [target_index])[:len(selection_edge_0)] <= selection_edge_1:", "on # InsertNodeSibbling return do_move(structure, edit_note, structure.s_cursor[:-1], structure.s_cursor[-1] + edit_note.direction)", "move here. parent_s_address = structure.s_cursor[:-1] delete_at_index = structure.s_cursor[-1] delete_from_hash =", "an_error() # adding sibblings to the root is not possible", "reinsert_later_hash), hash_after_deletion)) new_cursor = structure.s_cursor[:-1] + [index] posacts = [p0,", "may # create some asymmetries. For now I'm disallowing it;", "i.e. using NoteSlur(..., previous_hash). As an alternative, we could consider", "clef. The problem may auto-disappear if we add \"Move\" to", "not defined, because the root is assumed to exist.) return", "# there is no sibbling of the root node #", "new_s_cursor, posacts, False if isinstance(edit_note, TextReplace): posacts = replace_text_at(structure.tree, edit_note.s_address,", "EditStructure, EditNote => (new) s_cursor, posacts, error def an_error(): return", "# for now: if I ever want to express a", "either lo/hi for the comparison; source_index_lo and # source_index_hi will", "= parent_s_address else: # otherwise, make sure to stay in", "errors here). The proof flows directly # from the idea", "# Leave _children_ behind presupposes the existance of children if", "sources, is (inclusively) in the source's range, # you're trying", "in enumerate(range(source_index_lo, source_index_hi + 1)): # edge-inclusive range insert_hash =", "an_error() # For now, EncloseWithParent is simply implemented as a", "node_for_s_address(structure.tree, s_cursor[:-1]) index = s_cursor[-1] + edit_node.direction if not (0", "lists of length n, insertions at [0, n] are valid", "die # For now, LeaveChildrenBehind is simply implemented as a", "return new_s_cursor, posacts, False if isinstance(edit_note, TextReplace): posacts = replace_text_at(structure.tree,", "if isinstance(edit_note, EDelete): if structure.s_cursor == []: # silently ignored", "the # clef. # Another way we could handle the", "the parent new_cursor = parent_s_address else: # otherwise, make sure", "know what it would mean. Moving something to the same", "(target_parent_path + [target_index])[:len(selection_edge_0)] <= selection_edge_1: # If the full target", "will never straddle target_index, because of the child-of-yourself checks at", "Moving something to the same location (single source item, target", "because we implement something that is atomic from the user's", "while preserving # meaning\". I.e. we have deletions, we have", "initiated move in LibreOffice, the selection is preserved). # As", "be too restrictive, but I'd rather move in the #", "broken: # Not only if the parents are exactly the", "to [a descendant of] yourself. This is illegal. Moving something", "- 1): return an_error() # For now, SwapSibbling is simply", "exactly\", I did this using the idea \"just don't reset", "the editor clef\", which may be thought of as \"executing", "structure.s_cursor[-1] replace_on_hash = node_for_s_address(structure.tree, parent_s_address).metadata.nout_hash reinsert_later_hash = node_for_s_address(structure.tree, structure.s_cursor).metadata.nout_hash p_capo,", "root node # edit_note.direction points to a valid insertion point", "the relevant children of that ancestor or [b] to not", "edit_note.s_address, edit_note.text) return edit_note.s_address, posacts, False if isinstance(edit_note, InsertNodeSibbling): if", "yet: should we have the option to create a new", "point I had \"regular sibbling\" (as opposed to DFS sibbling)", "isinstance(edit_note, InsertNodeChild): cursor_node = node_for_s_address(structure.tree, structure.s_cursor) if not isinstance(cursor_node, TreeNode):", "target_offset, source_index in enumerate(range(source_index_lo, source_index_hi + 1)): # edge-inclusive range", "hash_capo = calc_possibility(NoteCapo()) p_create, hash_create = calc_possibility(NoteSlur(BecomeNode(), hash_capo)) p_enclosure, hash_enclosure", "[0]) raise Exception(\"Unknown Note\") def do_move(structure, edit_note, target_parent_path, target_index): selection_edge_0", "weave_correction), hash_)) posacts.append(p) if source_parent_path != target_parent_path: posacts = posacts", "because it allows you to continue operating on the the", "= node_for_s_address(structure.tree, structure.s_cursor) if structure.s_cursor == []: # I am", "structure.s_cursor) if not hasattr(cursor_node, 'children') or len(cursor_node.children) == 0: return", "an_error() index = len(cursor_node.children) posacts = insert_node_at(structure.tree, structure.s_cursor, index) new_s_cursor", "CursorSet, EDelete, EncloseWithParent, InsertNodeChild, InsertNodeSibbling, MoveSelectionChild, MoveSelectionSibbling, LeaveChildrenBehind, SwapSibbling, TextInsert,", "should we have the option to create a new root?", "now I'm disallowing it; we'll see whether a use case", "structure.s_cursor, [], True if selection_edge_0[:-1] != selection_edge_1[:-1]: # i.e. if", "for the comparison; source_index_lo and # source_index_hi will never straddle", "is a valid one. (Assuming: the cursor is valid, and", "= structure.s_cursor[-1] + edit_note.direction posacts = insert_node_at(structure.tree, structure.s_cursor[:-1], index) new_s_cursor", "isinstance(edit_note, TextReplace): posacts = replace_text_at(structure.tree, edit_note.s_address, edit_note.text) return edit_note.s_address, posacts,", "which I mean: it's possible in terms of the math),", "we do _not_ fetch hash_ here, the idea being: it's", "isinstance(edit_note, EncloseWithParent): cursor_node = node_for_s_address(structure.tree, structure.s_cursor) if structure.s_cursor == []:", "parent = node_for_s_address(structure.tree, structure.s_cursor[:-1]) index = structure.s_cursor[-1] + edit_note.direction if", "in the right spot new_cursor = structure.s_cursor if len(removed_node.children) ==", "parent is a prefix of the other (said differently: #", "at n being an append). index = structure.s_cursor[-1] + edit_note.direction", "if isinstance(edit_note, MoveSelectionSibbling): if len(structure.s_cursor) == 0: return an_error() #", "# for now... we just silently ignore the user's request", "node # edit_note.direction points to a valid insertion point for", "for i, child in enumerate(removed_node.children): p, hash_ = calc_possibility(NoteSlur(Insert(structure.s_cursor[-1] +", "cursor pos invalid: up to parent (alternative: sibbling-up first, until", "sure to stay in bounds. new_cursor[len(new_cursor) - 1] = min(", "min( len(parent_node.children) - 1 - 1, # len - 1", "(everything shifting to the left after each deletion) p, hash_", "the \"lo\" index (everything shifting to the left after each", "the length of the sources, is (inclusively) in the source's", "sorted([selection_edge_0[-1], selection_edge_1[-1]]) hash_ = target_parent.metadata.nout_hash for target_offset, source_index in enumerate(range(source_index_lo,", "target_parent_path: wdr_hash = hash_ hash_ = source_parent.metadata.nout_hash else: if target_index", "else: new_s_cursor = structure.s_cursor # \"stay in place (although new", "= posacts + bubble_history_up(hash_, structure.tree, source_parent_path) # The current solution", "too restrictive, but I'd rather move in the # direction", "edit_note.parent_s_address, edit_note.index, edit_note.text) new_s_cursor = edit_note.parent_s_address + [edit_note.index] return new_s_cursor,", "problem) # The reason we have this problem at all,", "may very well be too restrictive, but I'd rather move", "(yet); we can do a single bubble-up for source_index in", "path # identical to the source path) could at least", "and direction is # in the range [0, 1]; such", "when) we'll introduce # \"Move\" into the Clef, we should", "I mean: it's possible in terms of the math), but", "is a prefix of the other (said differently: # the", "(0 <= dfs_index <= len(dfs) - 1): return an_error() return", "but here I don't find that enough, so I'm just", "implies protection against moving the root node around (because everything", "!= target_parent_path: posacts = posacts + weave_disjoint_replaces( structure.tree, target_parent_path, wdr_hash,", "len(cursor_node.children) == 0: return an_error() return move_cursor(structure.s_cursor + [0]) raise", "False if isinstance(edit_note, MoveSelectionChild): cursor_node = node_for_s_address(structure.tree, structure.s_cursor) if not", "when cut/pasting. (However, for a # mouse-drag initiated move in", "# Generally, the paths towards relaxation are to either [a]", "InsertNodeSibbling): if structure.s_cursor == []: return an_error() # adding sibblings", "(it would lead to a forest) # There is no", "this using the idea \"just don't reset hash_\"... which works,", "we'll introduce # \"Move\" into the Clef, we should note", "will be great: post-deletion you'll be in the right spot", "(0 <= index <= len(parent.children) - 1): return an_error() #", "a forest) # There is no need to check that", "points at a no-longer existing location. If we # want", "index = structure.s_cursor[-1] + edit_note.direction if not (0 <= index", "[]) dfs_index = dfs.index(structure.s_cursor) + edit_note.direction if not (0 <=", "# the Clef, we should note the move here. parent_s_address", "post-deletion you'll be in the right spot new_cursor = structure.s_cursor", "= node_for_s_address(structure.tree, delete_from).metadata.nout_hash p, h = calc_possibility(NoteSlur(Delete(delete_at_index), delete_from_hash)) if delete_at_index", "the deleted node was the only node: fall back to", "- 1 idiom; -1 for deletion. new_cursor[len(new_cursor) - 1]) posacts", "# that may just be habituation). In any case, it's", "could handle the problem is once we have some tools", "an_error() if selection_edge_0 <= (target_parent_path + [target_index])[:len(selection_edge_0)] <= selection_edge_1: #", "the cooperative # editor) we should be able to express", "Exception(\"Unknown Note\") def do_move(structure, edit_note, target_parent_path, target_index): selection_edge_0 = edit_note.selection_edge_0", "we'll introduce # \"Move\" (in particular: the MoveReplace) into the", "the if-statement above, we could pick either lo/hi for the", "# meaning\". I.e. we have deletions, we have insertions: at", "in bounds. new_cursor[len(new_cursor) - 1] = min( len(parent_node.children) - 1", "+ bubble_history_up(hash_, structure.tree, source_parent_path) # The current solution for \"where", "not hasattr(cursor_node, 'children') or len(cursor_node.children) == 0: return an_error() return", "location, truncated to the length of the sources, is (inclusively)", "+ edit_note.direction if not (0 <= dfs_index <= len(dfs) -", "the Clef, we should note the move here. posacts =", "node was the only node: fall back to the parent", "when) we'll introduce \"Move\" into # the Clef, we should", "- source_index_lo + 1 else: cursor_correction = source_index_hi - source_index_lo", "non-atomic way in the clef. The problem may auto-disappear if", "is # in the range [0, 1]; such assumptions fit", "node_for_s_address(structure.tree, structure.s_cursor) if not hasattr(cursor_node, 'children'): return an_error() # Leave", "if source_parent_path != target_parent_path: posacts = posacts + weave_disjoint_replaces( structure.tree,", "return an_error() # root has no sibblings parent = node_for_s_address(structure.tree,", "node to a non-node return an_error() index = len(cursor_node.children) posacts", "something that is atomic from the user's # point of", "for source_index in range(source_index_lo, source_index_hi + 1): # edge-inclusive range", "the interface of edit_note_play to # include the resulting selection.", "works, # because it allows you to continue operating on", "return an_error() # there is no sibbling of the root", "delete_at_index = structure.s_cursor[-1] delete_from_hash = node_for_s_address(structure.tree, parent_s_address).metadata.nout_hash p, hash_ =", "restriction on \"same depth\" instead. # Generally, the paths towards", "hash_ = calc_possibility(NoteSlur(Delete(delete_at_index), delete_from_hash)) posacts = [p] removed_node = node_for_s_address(structure.tree,", "the user's request when they ask to add a child", "we should note the move here. parent_s_address = structure.s_cursor[:-1] delete_at_index", "structure.s_cursor[:-1] + [index] posacts = [p0, p1] + bubble_history_up(hash_after_insertion, structure.tree,", ") from dsn.s_expr.clef import Delete, Insert, Replace, BecomeNode from dsn.s_expr.structure", "do not check for arbitrary programming errors here). The proof", "is (inclusively) in the source's range, # you're trying to", "\"regular sibbling\" (as opposed to DFS sibbling) in the edit_clef.", "\"\"\"At some point I had \"regular sibbling\" (as opposed to", "= structure.s_cursor[-1] delete_from_hash = node_for_s_address(structure.tree, parent_s_address).metadata.nout_hash reinsert_later_hash = node_for_s_address(structure.tree, structure.s_cursor).metadata.nout_hash", "as a child return do_move(structure, edit_note, structure.s_cursor, len(cursor_node.children)) if isinstance(edit_note,", "dsn.s_expr.utils import ( bubble_history_up, calc_possibility, insert_text_at, insert_node_at, replace_text_at, weave_disjoint_replaces, )", "hash_replace, structure.tree, parent_s_address) # We jump the cursor to the", "We jump the cursor to the newly enclosed location: new_cursor", "TextReplace): posacts = replace_text_at(structure.tree, edit_note.s_address, edit_note.text) return edit_note.s_address, posacts, False", "case of \"parents match exactly\", I did this using the", "to make the selection appear at the target-location, we need", "new_s_cursor = structure.s_cursor + [index] return new_s_cursor, posacts, False if", "consider `nouts_for_notes`. \"\"\" from s_address import node_for_s_address, s_dfs from dsn.s_expr.legato", "at this point, we do not check for arbitrary programming", "as a \"insert and delete\"; if (or when) we'll introduce", "[], True if selection_edge_0[:-1] != selection_edge_1[:-1]: # i.e. if not", "we need to change the interface of edit_note_play to #", "in the # source node, such a single-parent restriction is", "in the range [0, 1]; such assumptions fit with the", "+ 1 # we do _not_ fetch hash_ here, the", "EDelete, EncloseWithParent, InsertNodeChild, InsertNodeSibbling, MoveSelectionChild, MoveSelectionSibbling, LeaveChildrenBehind, SwapSibbling, TextInsert, TextReplace,", "and delete\"; if (or when) we'll introduce # \"Move\" into", "1 - 1, # len - 1 idiom; -1 for", "= calc_possibility(NoteSlur(BecomeNode(), hash_capo)) p_enclosure, hash_enclosure = calc_possibility(NoteSlur(Insert(0, reinsert_later_hash), hash_create)) p_replace,", "is no sibbling of the root node # edit_note.direction points", "it; we'll see whether a use case arises. return an_error()", "structure.s_cursor) if not isinstance(cursor_node, TreeNode): # for now... we just", "structure.s_cursor == []: return an_error() # adding sibblings to the", "else: # otherwise, make sure to stay in bounds. new_cursor[len(new_cursor)", "move_cursor(edit_note.s_address) if isinstance(edit_note, CursorParent): if structure.s_cursor == []: return an_error()", "isinstance(edit_note, InsertNodeSibbling): if structure.s_cursor == []: return an_error() # adding", "= node_for_s_address(structure.tree, source_parent_path + [source_index]).metadata.nout_hash p, hash_ = calc_possibility(NoteSlur(Insert(target_index +", "one of them). # In that case, we need to", "source_index in range(source_index_lo, source_index_hi + 1): # edge-inclusive range #", "+ [index] return new_s_cursor, posacts, False if isinstance(edit_note, EDelete): if", "here. parent_s_address = structure.s_cursor[:-1] delete_at_index = structure.s_cursor[-1] delete_from_hash = node_for_s_address(structure.tree,", "insert_text_at(structure.tree, edit_note.parent_s_address, edit_note.index, edit_note.text) new_s_cursor = edit_note.parent_s_address + [edit_note.index] return", "return an_error() return move_cursor(structure.s_cursor[:-1]) if isinstance(edit_note, CursorChild): cursor_node = node_for_s_address(structure.tree,", "about the meaning of the selection's # edges\", i.e. find", "if selection_edge_0 <= (target_parent_path + [target_index])[:len(selection_edge_0)] <= selection_edge_1: # If", "_not_ fetch hash_ here, the idea being: it's the hash", "a non-node return an_error() index = len(cursor_node.children) posacts = insert_node_at(structure.tree,", "bubble_history_up( hash_replace, structure.tree, parent_s_address) # We jump the cursor to", "to DFS sibbling) in the edit_clef. It looks like this:", "node_for_s_address(structure.tree, parent_s_address).metadata.nout_hash reinsert_later_hash = node_for_s_address(structure.tree, structure.s_cursor).metadata.nout_hash p_capo, hash_capo = calc_possibility(NoteCapo())", "But in the case of shared prefix, this won't #", "delete_at_index = structure.s_cursor[-1] delete_from_hash = node_for_s_address(structure.tree, delete_from).metadata.nout_hash p, h =", "False if isinstance(edit_note, CursorDFS): dfs = s_dfs(structure.tree, []) dfs_index =", "= 0 # TODO this part is still broken: #", "reason we have this problem at all, is because we", "if isinstance(edit_note, CursorParent): if structure.s_cursor == []: return an_error() return", "structure.s_cursor[:-1] delete_at_index = structure.s_cursor[-1] delete_from_hash = node_for_s_address(structure.tree, delete_from).metadata.nout_hash p, h", "posacts = [p] + bubble_history_up(h, structure.tree, delete_from) return new_s_cursor, posacts,", "we reverse the order of operations, we have the opposite", "we just silently ignore the user's request when they ask", "be understood to mean the no-op, so it's slightly less", "adding sibblings to the root is not possible (it would", "dsn.s_expr.structure import TreeNode from dsn.editor.clef import ( CursorChild, CursorDFS, CursorParent,", "happened. (If we reverse the order of operations, we have", "it's wat e.g. LibreOffice does when cut/pasting. (However, for a", "If the full target location, truncated to the length of", "deleted node was the only node: fall back to the", "error-scenarios. # This implies protection against moving the root node", "+ [index] posacts = [p0, p1] + bubble_history_up(hash_after_insertion, structure.tree, parent_s_address)", "1]) posacts += bubble_history_up(hash_, structure.tree, parent_s_address) return new_cursor, posacts, False", "rather move in the # direction of \"relax constraints later\"", "The proof flows directly # from the idea that, for", "\"at the end\". This \"seems intuitive\" (but # that may", "indices # than the deletions, they will affect the locations", "are simply implemented as a \"insert and delete\"; if (or", "a new root? I don't see any direct # objections", "SwapSibbling): if structure.s_cursor == []: return an_error() # root has", "we often connect notes together \"manually\", i.e. using NoteSlur(..., previous_hash).", "\"stay in place (although new contents slide into the cursor", "edge-inclusive range # Note: we just Delete n times at", "== []: return an_error() # Root cannot die # For", "on \"same depth\" instead. # Generally, the paths towards relaxation", "general, leaving the cursor at the same s_address will be", "# Note that \"single parent\" implies \"same depth\", but not", "disappears automatically, because it points at a no-longer existing location.", "of both parents matches one of them). # In that", "longest_common_prefix of both parents matches one of them). # In", "and insert\"; if (or when) we'll introduce # \"Move\" into", "= edit_note.parent_s_address + [edit_note.index] return new_s_cursor, posacts, False if isinstance(edit_note,", "MoveSelectionSibbling): if len(structure.s_cursor) == 0: return an_error() # there is", "of the sources, is (inclusively) in the source's range, #", "resulting selection. new_cursor = target_parent_path + [target_index + target_offset -", "The target must be a node to be able to", "+ 1)): # edge-inclusive range insert_hash = node_for_s_address(structure.tree, source_parent_path +", "- 1: # deletion makes cursor pos invalid: up to", "into # the Clef, we should note the move here.", "+ [index]) \"\"\" if isinstance(edit_note, CursorSet): return move_cursor(edit_note.s_address) if isinstance(edit_note,", "source_parent = node_for_s_address(structure.tree, source_parent_path) target_parent = node_for_s_address(structure.tree, target_parent_path) # For", "\"same depth\", but not vice versa. One possible relaxation is:", "[]: return an_error() # Root cannot die # For now,", "valid (insertion at n being an append). index = structure.s_cursor[-1]", "p1, hash_after_insertion = calc_possibility(NoteSlur(Insert(index, reinsert_later_hash), hash_after_deletion)) new_cursor = structure.s_cursor[:-1] +", "InsertNodeSibbling, MoveSelectionChild, MoveSelectionSibbling, LeaveChildrenBehind, SwapSibbling, TextInsert, TextReplace, ) def edit_note_play(structure,", "be in the right spot new_cursor = structure.s_cursor if len(removed_node.children)", "contents slide into the cursor position) posacts = [p] +", "InsertNodeSibbling return do_move(structure, edit_note, structure.s_cursor[:-1], structure.s_cursor[-1] + edit_note.direction) if isinstance(edit_note,", "\"delete and insert\"; if (or when) we'll introduce \"Move\" into", "of the math), but I still have a sense that", "it's possible in terms of the math), but I still", "to the # clef. # Another way we could handle", "+ target_offset, insert_hash), hash_)) posacts.append(p) weave_correction = 0 cursor_correction =", "the the same \"future\". But in the case of shared", "when they ask to add a child node to a", "the end\". This \"seems intuitive\" (but # that may just", "I still have a sense that it may # create", "Clef, we should note the move here. posacts = []" ]
[ "Classes. Base mainly includes the description fields \"\"\" import logging", "BaseLog: \"\"\" Set a base logging. Use this as the", "this as the base class for all your work. This", "\"\"\" Set a base logging. Use this as the base", "mainly includes the description fields \"\"\" import logging from typing", "Set a base logging. Use this as the base class", "logging. Use this as the base class for all your", "we have no log otherwise self.log_root = log_root self.log =", "logging from typing import Optional from .log import Log #", "class BaseLog: \"\"\" Set a base logging. Use this as", "the base class for all your work. This adds a", "Root Log.\"\"\" # since we have no log otherwise self.log_root", "# since we have no log otherwise self.log_root = log_root", "have no log otherwise self.log_root = log_root self.log = (", "base class for all your work. This adds a logging", "log_root: Optional[Log] = None): \"\"\"Set the Root Log.\"\"\" # since", "None): \"\"\"Set the Root Log.\"\"\" # since we have no", "all Classes. Base mainly includes the description fields \"\"\" import", ".log import Log # type: ignore class BaseLog: \"\"\" Set", "import Log # type: ignore class BaseLog: \"\"\" Set a", "type: ignore class BaseLog: \"\"\" Set a base logging. Use", "\"\"\"Set the Root Log.\"\"\" # since we have no log", "since we have no log otherwise self.log_root = log_root self.log", "Base mainly includes the description fields \"\"\" import logging from", "log otherwise self.log_root = log_root self.log = ( log_root.log_class(self) if", "work. This adds a logging root. \"\"\" def __init__(self, log_root:", "a logging root. \"\"\" def __init__(self, log_root: Optional[Log] = None):", "root. \"\"\" def __init__(self, log_root: Optional[Log] = None): \"\"\"Set the", "log_root self.log = ( log_root.log_class(self) if log_root is not None", "Log # type: ignore class BaseLog: \"\"\" Set a base", "includes the description fields \"\"\" import logging from typing import", "for all your work. This adds a logging root. \"\"\"", "import logging from typing import Optional from .log import Log", "self.log = ( log_root.log_class(self) if log_root is not None else", "the Root Log.\"\"\" # since we have no log otherwise", "= log_root self.log = ( log_root.log_class(self) if log_root is not", "# type: ignore class BaseLog: \"\"\" Set a base logging.", "Use this as the base class for all your work.", "\"\"\" def __init__(self, log_root: Optional[Log] = None): \"\"\"Set the Root", "a base logging. Use this as the base class for", "log_root.log_class(self) if log_root is not None else logging.getLogger(__name__) ) self.log.debug(f\"{self=}\")", "otherwise self.log_root = log_root self.log = ( log_root.log_class(self) if log_root", "\"\"\"Base for all Classes. Base mainly includes the description fields", "typing import Optional from .log import Log # type: ignore", "your work. This adds a logging root. \"\"\" def __init__(self,", "logging root. \"\"\" def __init__(self, log_root: Optional[Log] = None): \"\"\"Set", "Optional from .log import Log # type: ignore class BaseLog:", "__init__(self, log_root: Optional[Log] = None): \"\"\"Set the Root Log.\"\"\" #", "the description fields \"\"\" import logging from typing import Optional", "def __init__(self, log_root: Optional[Log] = None): \"\"\"Set the Root Log.\"\"\"", "self.log_root = log_root self.log = ( log_root.log_class(self) if log_root is", "= ( log_root.log_class(self) if log_root is not None else logging.getLogger(__name__)", "as the base class for all your work. This adds", "( log_root.log_class(self) if log_root is not None else logging.getLogger(__name__) )", "fields \"\"\" import logging from typing import Optional from .log", "for all Classes. Base mainly includes the description fields \"\"\"", "This adds a logging root. \"\"\" def __init__(self, log_root: Optional[Log]", "base logging. Use this as the base class for all", "class for all your work. This adds a logging root.", "\"\"\" import logging from typing import Optional from .log import", "ignore class BaseLog: \"\"\" Set a base logging. Use this", "from .log import Log # type: ignore class BaseLog: \"\"\"", "all your work. This adds a logging root. \"\"\" def", "adds a logging root. \"\"\" def __init__(self, log_root: Optional[Log] =", "Optional[Log] = None): \"\"\"Set the Root Log.\"\"\" # since we", "no log otherwise self.log_root = log_root self.log = ( log_root.log_class(self)", "Log.\"\"\" # since we have no log otherwise self.log_root =", "= None): \"\"\"Set the Root Log.\"\"\" # since we have", "import Optional from .log import Log # type: ignore class", "description fields \"\"\" import logging from typing import Optional from", "from typing import Optional from .log import Log # type:" ]
[ "check that program\") continue process = subprocess. run( ['which', program],", "with a space: ').split() secure_pattern = '[\\w\\d]' for program in", "can't check that program\") continue process = subprocess. run( ['which',", "continue process = subprocess. run( ['which', program], capture_output=True, text=True) if", "= subprocess. run( ['which', program], capture_output=True, text=True) if process.returncode ==", "= '[\\w\\d]' for program in programs: if not re.match(secure_pattern, program):", "a space: ').split() secure_pattern = '[\\w\\d]' for program in programs:", "= input('Separe the programs with a space: ').split() secure_pattern =", "input('Separe the programs with a space: ').split() secure_pattern = '[\\w\\d]'", "program], capture_output=True, text=True) if process.returncode == 0: print(f'The program \"{program}\"", "program): print(\"Sorry we can't check that program\") continue process =", "process = subprocess. run( ['which', program], capture_output=True, text=True) if process.returncode", "program in programs: if not re.match(secure_pattern, program): print(\"Sorry we can't", "space: ').split() secure_pattern = '[\\w\\d]' for program in programs: if", "programs: if not re.match(secure_pattern, program): print(\"Sorry we can't check that", "import re programs = input('Separe the programs with a space:", "of the binary is: {process.stdout}') else: print(f'Sorry the {program} is", "installed') print(f'The location of the binary is: {process.stdout}') else: print(f'Sorry", "that program\") continue process = subprocess. run( ['which', program], capture_output=True,", "if process.returncode == 0: print(f'The program \"{program}\" is installed') print(f'The", "== 0: print(f'The program \"{program}\" is installed') print(f'The location of", "for program in programs: if not re.match(secure_pattern, program): print(\"Sorry we", "program\") continue process = subprocess. run( ['which', program], capture_output=True, text=True)", "run( ['which', program], capture_output=True, text=True) if process.returncode == 0: print(f'The", "print(f'The program \"{program}\" is installed') print(f'The location of the binary", "process.returncode == 0: print(f'The program \"{program}\" is installed') print(f'The location", "\"{program}\" is installed') print(f'The location of the binary is: {process.stdout}')", "location of the binary is: {process.stdout}') else: print(f'Sorry the {program}", "re.match(secure_pattern, program): print(\"Sorry we can't check that program\") continue process", "text=True) if process.returncode == 0: print(f'The program \"{program}\" is installed')", "{process.stdout}') else: print(f'Sorry the {program} is not installed') print(process.stderr) print('\\n')", "if not re.match(secure_pattern, program): print(\"Sorry we can't check that program\")", "the binary is: {process.stdout}') else: print(f'Sorry the {program} is not", "capture_output=True, text=True) if process.returncode == 0: print(f'The program \"{program}\" is", "program \"{program}\" is installed') print(f'The location of the binary is:", "the programs with a space: ').split() secure_pattern = '[\\w\\d]' for", "subprocess. run( ['which', program], capture_output=True, text=True) if process.returncode == 0:", "not re.match(secure_pattern, program): print(\"Sorry we can't check that program\") continue", "we can't check that program\") continue process = subprocess. run(", "re programs = input('Separe the programs with a space: ').split()", "binary is: {process.stdout}') else: print(f'Sorry the {program} is not installed')", "is: {process.stdout}') else: print(f'Sorry the {program} is not installed') print(process.stderr)", "subprocess import re programs = input('Separe the programs with a", "in programs: if not re.match(secure_pattern, program): print(\"Sorry we can't check", "is installed') print(f'The location of the binary is: {process.stdout}') else:", "programs = input('Separe the programs with a space: ').split() secure_pattern", "'[\\w\\d]' for program in programs: if not re.match(secure_pattern, program): print(\"Sorry", "print(\"Sorry we can't check that program\") continue process = subprocess.", "programs with a space: ').split() secure_pattern = '[\\w\\d]' for program", "0: print(f'The program \"{program}\" is installed') print(f'The location of the", "import subprocess import re programs = input('Separe the programs with", "print(f'The location of the binary is: {process.stdout}') else: print(f'Sorry the", "secure_pattern = '[\\w\\d]' for program in programs: if not re.match(secure_pattern,", "').split() secure_pattern = '[\\w\\d]' for program in programs: if not", "['which', program], capture_output=True, text=True) if process.returncode == 0: print(f'The program" ]
[ "account = cleaned_data.get('account') if account: get_adapter(self.request).validate_disconnect( account, self.accounts) return cleaned_data", "clean(self): cleaned_data = super(DisconnectForm, self).clean() account = cleaned_data.get('account') if account:", "= get_adapter().get_signup_form_initial_data( self.sociallogin) kwargs.update({ 'initial': initial, 'email_required': kwargs.get('email_required', app_settings.EMAIL_REQUIRED)}) super(SignupForm,", "def save(self, request): adapter = get_adapter(request) user = adapter.save_user(request, self.sociallogin,", "get_adapter().error_messages['email_taken'] % self.sociallogin.account.get_provider().name) class DisconnectForm(forms.Form): account = forms.ModelChoiceField(queryset=SocialAccount.objects.none(), widget=forms.RadioSelect, required=True)", "__future__ import absolute_import from django import forms from authentication.account.forms import", "account = forms.ModelChoiceField(queryset=SocialAccount.objects.none(), widget=forms.RadioSelect, required=True) def __init__(self, *args, **kwargs): self.request", "import get_adapter from .models import SocialAccount class SignupForm(BaseSignupForm): def __init__(self,", "signals from .adapter import get_adapter from .models import SocialAccount class", ".adapter import get_adapter from .models import SocialAccount class SignupForm(BaseSignupForm): def", "get_adapter from .models import SocialAccount class SignupForm(BaseSignupForm): def __init__(self, *args,", "from . import app_settings, signals from .adapter import get_adapter from", "= adapter.save_user(request, self.sociallogin, form=self) self.custom_signup(request, user) return user def validate_unique_email(self,", "get_adapter(self.request).validate_disconnect( account, self.accounts) return cleaned_data def save(self): account = self.cleaned_data['account']", "= cleaned_data.get('account') if account: get_adapter(self.request).validate_disconnect( account, self.accounts) return cleaned_data def", "import SocialAccount class SignupForm(BaseSignupForm): def __init__(self, *args, **kwargs): self.sociallogin =", "initial, 'email_required': kwargs.get('email_required', app_settings.EMAIL_REQUIRED)}) super(SignupForm, self).__init__(*args, **kwargs) def save(self, request):", "= self.accounts def clean(self): cleaned_data = super(DisconnectForm, self).clean() account =", "'email_required': kwargs.get('email_required', app_settings.EMAIL_REQUIRED)}) super(SignupForm, self).__init__(*args, **kwargs) def save(self, request): adapter", ".models import SocialAccount class SignupForm(BaseSignupForm): def __init__(self, *args, **kwargs): self.sociallogin", "self).validate_unique_email(value) except forms.ValidationError: raise forms.ValidationError( get_adapter().error_messages['email_taken'] % self.sociallogin.account.get_provider().name) class DisconnectForm(forms.Form):", "self.sociallogin = kwargs.pop('sociallogin') initial = get_adapter().get_signup_form_initial_data( self.sociallogin) kwargs.update({ 'initial': initial,", "super(DisconnectForm, self).__init__(*args, **kwargs) self.fields['account'].queryset = self.accounts def clean(self): cleaned_data =", "self.sociallogin, form=self) self.custom_signup(request, user) return user def validate_unique_email(self, value): try:", "initial = get_adapter().get_signup_form_initial_data( self.sociallogin) kwargs.update({ 'initial': initial, 'email_required': kwargs.get('email_required', app_settings.EMAIL_REQUIRED)})", "validate_unique_email(self, value): try: return super(SignupForm, self).validate_unique_email(value) except forms.ValidationError: raise forms.ValidationError(", "def __init__(self, *args, **kwargs): self.sociallogin = kwargs.pop('sociallogin') initial = get_adapter().get_signup_form_initial_data(", "authentication.account.forms import BaseSignupForm from . import app_settings, signals from .adapter", "self).clean() account = cleaned_data.get('account') if account: get_adapter(self.request).validate_disconnect( account, self.accounts) return", "from .adapter import get_adapter from .models import SocialAccount class SignupForm(BaseSignupForm):", "user def validate_unique_email(self, value): try: return super(SignupForm, self).validate_unique_email(value) except forms.ValidationError:", "try: return super(SignupForm, self).validate_unique_email(value) except forms.ValidationError: raise forms.ValidationError( get_adapter().error_messages['email_taken'] %", "import absolute_import from django import forms from authentication.account.forms import BaseSignupForm", "self.accounts) return cleaned_data def save(self): account = self.cleaned_data['account'] account.delete() signals.social_account_removed.send(sender=SocialAccount,", "from .models import SocialAccount class SignupForm(BaseSignupForm): def __init__(self, *args, **kwargs):", "return cleaned_data def save(self): account = self.cleaned_data['account'] account.delete() signals.social_account_removed.send(sender=SocialAccount, request=self.request,", "class SignupForm(BaseSignupForm): def __init__(self, *args, **kwargs): self.sociallogin = kwargs.pop('sociallogin') initial", "cleaned_data def save(self): account = self.cleaned_data['account'] account.delete() signals.social_account_removed.send(sender=SocialAccount, request=self.request, socialaccount=account)", "= forms.ModelChoiceField(queryset=SocialAccount.objects.none(), widget=forms.RadioSelect, required=True) def __init__(self, *args, **kwargs): self.request =", ". import app_settings, signals from .adapter import get_adapter from .models", "required=True) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') self.accounts =", "self.accounts = SocialAccount.objects.filter(user=self.request.user) super(DisconnectForm, self).__init__(*args, **kwargs) self.fields['account'].queryset = self.accounts def", "BaseSignupForm from . import app_settings, signals from .adapter import get_adapter", "self.fields['account'].queryset = self.accounts def clean(self): cleaned_data = super(DisconnectForm, self).clean() account", "*args, **kwargs): self.request = kwargs.pop('request') self.accounts = SocialAccount.objects.filter(user=self.request.user) super(DisconnectForm, self).__init__(*args,", "import BaseSignupForm from . import app_settings, signals from .adapter import", "adapter.save_user(request, self.sociallogin, form=self) self.custom_signup(request, user) return user def validate_unique_email(self, value):", "user) return user def validate_unique_email(self, value): try: return super(SignupForm, self).validate_unique_email(value)", "= super(DisconnectForm, self).clean() account = cleaned_data.get('account') if account: get_adapter(self.request).validate_disconnect( account,", "self.sociallogin) kwargs.update({ 'initial': initial, 'email_required': kwargs.get('email_required', app_settings.EMAIL_REQUIRED)}) super(SignupForm, self).__init__(*args, **kwargs)", "% self.sociallogin.account.get_provider().name) class DisconnectForm(forms.Form): account = forms.ModelChoiceField(queryset=SocialAccount.objects.none(), widget=forms.RadioSelect, required=True) def", "= SocialAccount.objects.filter(user=self.request.user) super(DisconnectForm, self).__init__(*args, **kwargs) self.fields['account'].queryset = self.accounts def clean(self):", "if account: get_adapter(self.request).validate_disconnect( account, self.accounts) return cleaned_data def save(self): account", "'initial': initial, 'email_required': kwargs.get('email_required', app_settings.EMAIL_REQUIRED)}) super(SignupForm, self).__init__(*args, **kwargs) def save(self,", "kwargs.get('email_required', app_settings.EMAIL_REQUIRED)}) super(SignupForm, self).__init__(*args, **kwargs) def save(self, request): adapter =", "raise forms.ValidationError( get_adapter().error_messages['email_taken'] % self.sociallogin.account.get_provider().name) class DisconnectForm(forms.Form): account = forms.ModelChoiceField(queryset=SocialAccount.objects.none(),", "user = adapter.save_user(request, self.sociallogin, form=self) self.custom_signup(request, user) return user def", "app_settings, signals from .adapter import get_adapter from .models import SocialAccount", "forms.ValidationError: raise forms.ValidationError( get_adapter().error_messages['email_taken'] % self.sociallogin.account.get_provider().name) class DisconnectForm(forms.Form): account =", "self.request = kwargs.pop('request') self.accounts = SocialAccount.objects.filter(user=self.request.user) super(DisconnectForm, self).__init__(*args, **kwargs) self.fields['account'].queryset", "= get_adapter(request) user = adapter.save_user(request, self.sociallogin, form=self) self.custom_signup(request, user) return", "super(SignupForm, self).validate_unique_email(value) except forms.ValidationError: raise forms.ValidationError( get_adapter().error_messages['email_taken'] % self.sociallogin.account.get_provider().name) class", "= kwargs.pop('sociallogin') initial = get_adapter().get_signup_form_initial_data( self.sociallogin) kwargs.update({ 'initial': initial, 'email_required':", "self).__init__(*args, **kwargs) self.fields['account'].queryset = self.accounts def clean(self): cleaned_data = super(DisconnectForm,", "forms.ModelChoiceField(queryset=SocialAccount.objects.none(), widget=forms.RadioSelect, required=True) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request')", "account, self.accounts) return cleaned_data def save(self): account = self.cleaned_data['account'] account.delete()", "**kwargs): self.request = kwargs.pop('request') self.accounts = SocialAccount.objects.filter(user=self.request.user) super(DisconnectForm, self).__init__(*args, **kwargs)", "self.accounts def clean(self): cleaned_data = super(DisconnectForm, self).clean() account = cleaned_data.get('account')", "SignupForm(BaseSignupForm): def __init__(self, *args, **kwargs): self.sociallogin = kwargs.pop('sociallogin') initial =", "DisconnectForm(forms.Form): account = forms.ModelChoiceField(queryset=SocialAccount.objects.none(), widget=forms.RadioSelect, required=True) def __init__(self, *args, **kwargs):", "import forms from authentication.account.forms import BaseSignupForm from . import app_settings,", "SocialAccount.objects.filter(user=self.request.user) super(DisconnectForm, self).__init__(*args, **kwargs) self.fields['account'].queryset = self.accounts def clean(self): cleaned_data", "__init__(self, *args, **kwargs): self.request = kwargs.pop('request') self.accounts = SocialAccount.objects.filter(user=self.request.user) super(DisconnectForm,", "**kwargs) def save(self, request): adapter = get_adapter(request) user = adapter.save_user(request,", "account: get_adapter(self.request).validate_disconnect( account, self.accounts) return cleaned_data def save(self): account =", "__init__(self, *args, **kwargs): self.sociallogin = kwargs.pop('sociallogin') initial = get_adapter().get_signup_form_initial_data( self.sociallogin)", "from authentication.account.forms import BaseSignupForm from . import app_settings, signals from", "= kwargs.pop('request') self.accounts = SocialAccount.objects.filter(user=self.request.user) super(DisconnectForm, self).__init__(*args, **kwargs) self.fields['account'].queryset =", "request): adapter = get_adapter(request) user = adapter.save_user(request, self.sociallogin, form=self) self.custom_signup(request,", "save(self, request): adapter = get_adapter(request) user = adapter.save_user(request, self.sociallogin, form=self)", "super(DisconnectForm, self).clean() account = cleaned_data.get('account') if account: get_adapter(self.request).validate_disconnect( account, self.accounts)", "SocialAccount class SignupForm(BaseSignupForm): def __init__(self, *args, **kwargs): self.sociallogin = kwargs.pop('sociallogin')", "forms from authentication.account.forms import BaseSignupForm from . import app_settings, signals", "adapter = get_adapter(request) user = adapter.save_user(request, self.sociallogin, form=self) self.custom_signup(request, user)", "absolute_import from django import forms from authentication.account.forms import BaseSignupForm from", "**kwargs) self.fields['account'].queryset = self.accounts def clean(self): cleaned_data = super(DisconnectForm, self).clean()", "self.custom_signup(request, user) return user def validate_unique_email(self, value): try: return super(SignupForm,", "*args, **kwargs): self.sociallogin = kwargs.pop('sociallogin') initial = get_adapter().get_signup_form_initial_data( self.sociallogin) kwargs.update({", "kwargs.pop('request') self.accounts = SocialAccount.objects.filter(user=self.request.user) super(DisconnectForm, self).__init__(*args, **kwargs) self.fields['account'].queryset = self.accounts", "super(SignupForm, self).__init__(*args, **kwargs) def save(self, request): adapter = get_adapter(request) user", "forms.ValidationError( get_adapter().error_messages['email_taken'] % self.sociallogin.account.get_provider().name) class DisconnectForm(forms.Form): account = forms.ModelChoiceField(queryset=SocialAccount.objects.none(), widget=forms.RadioSelect,", "class DisconnectForm(forms.Form): account = forms.ModelChoiceField(queryset=SocialAccount.objects.none(), widget=forms.RadioSelect, required=True) def __init__(self, *args,", "self.sociallogin.account.get_provider().name) class DisconnectForm(forms.Form): account = forms.ModelChoiceField(queryset=SocialAccount.objects.none(), widget=forms.RadioSelect, required=True) def __init__(self,", "def validate_unique_email(self, value): try: return super(SignupForm, self).validate_unique_email(value) except forms.ValidationError: raise", "widget=forms.RadioSelect, required=True) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') self.accounts", "**kwargs): self.sociallogin = kwargs.pop('sociallogin') initial = get_adapter().get_signup_form_initial_data( self.sociallogin) kwargs.update({ 'initial':", "kwargs.pop('sociallogin') initial = get_adapter().get_signup_form_initial_data( self.sociallogin) kwargs.update({ 'initial': initial, 'email_required': kwargs.get('email_required',", "get_adapter().get_signup_form_initial_data( self.sociallogin) kwargs.update({ 'initial': initial, 'email_required': kwargs.get('email_required', app_settings.EMAIL_REQUIRED)}) super(SignupForm, self).__init__(*args,", "from django import forms from authentication.account.forms import BaseSignupForm from .", "except forms.ValidationError: raise forms.ValidationError( get_adapter().error_messages['email_taken'] % self.sociallogin.account.get_provider().name) class DisconnectForm(forms.Form): account", "cleaned_data = super(DisconnectForm, self).clean() account = cleaned_data.get('account') if account: get_adapter(self.request).validate_disconnect(", "def clean(self): cleaned_data = super(DisconnectForm, self).clean() account = cleaned_data.get('account') if", "get_adapter(request) user = adapter.save_user(request, self.sociallogin, form=self) self.custom_signup(request, user) return user", "from __future__ import absolute_import from django import forms from authentication.account.forms", "form=self) self.custom_signup(request, user) return user def validate_unique_email(self, value): try: return", "return user def validate_unique_email(self, value): try: return super(SignupForm, self).validate_unique_email(value) except", "cleaned_data.get('account') if account: get_adapter(self.request).validate_disconnect( account, self.accounts) return cleaned_data def save(self):", "app_settings.EMAIL_REQUIRED)}) super(SignupForm, self).__init__(*args, **kwargs) def save(self, request): adapter = get_adapter(request)", "value): try: return super(SignupForm, self).validate_unique_email(value) except forms.ValidationError: raise forms.ValidationError( get_adapter().error_messages['email_taken']", "django import forms from authentication.account.forms import BaseSignupForm from . import", "def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') self.accounts = SocialAccount.objects.filter(user=self.request.user)", "self).__init__(*args, **kwargs) def save(self, request): adapter = get_adapter(request) user =", "<filename>authentication/socialaccount/forms.py from __future__ import absolute_import from django import forms from", "return super(SignupForm, self).validate_unique_email(value) except forms.ValidationError: raise forms.ValidationError( get_adapter().error_messages['email_taken'] % self.sociallogin.account.get_provider().name)", "import app_settings, signals from .adapter import get_adapter from .models import", "kwargs.update({ 'initial': initial, 'email_required': kwargs.get('email_required', app_settings.EMAIL_REQUIRED)}) super(SignupForm, self).__init__(*args, **kwargs) def" ]
[ "refreshed :return: self \"\"\" logger.info(f'Connecting to {self.server}:{self.port}') await self._command_channel.connect(self.server, self.port)", "event: HEOSEvent): raise NotImplementedError() def _handle_now_playing_changed(self, event: HEOSEvent): raise NotImplementedError()", "return self._connected @property def signed_in(self): return self._account_status == AccountStatus.SignedIn @property", "event_name: str, callback: Callable): \"\"\" Subscribe a callback function to", "str], port: int=Pytheos.DEFAULT_PORT) -> Pytheos: \"\"\" Connect to the provided", "Host to connect to :param port: Port to connect to", "\"\"\" if not channel or not channel.connected: raise ChannelUnavailableError() @property", "\"\"\" if isinstance(server, SSDPResponse): server = utils.extract_host(server.location) self.server: str =", "this as a dict. self._sources: dict = {} # FIXME?:", "raise NotImplementedError() def _handle_now_playing_changed(self, event: HEOSEvent): raise NotImplementedError() def _handle_now_playing_progress(self,", "the primary interface into the library \"\"\" from __future__ import", "\"\"\" Checks if the system is logged into HEOS and", ":return: tuple \"\"\" self._account_status, self._account_username = await self.api.system.check_account() return self._account_status,", "mapping of IDs to Sources present in the HEOS system.", "Not sure I like having this as a dict. self.api:", "\"\"\" Retrieve a specific group by ID. :param group_id: Group", "None \"\"\" while True: event = await self._event_queue.get() if event:", "= Connection() self._event_queue = asyncio.Queue() self._event_task: Optional[asyncio.Task] = None self._event_processor:", "dict = {} self._receive_events: bool = True self._account_status: Optional[AccountStatus] =", "{event!r}\") await self._event_queue.put(event) await asyncio.sleep(0.5) async def _process_events(self): \"\"\" Async", "{event!r}') loop.create_task(callback(event)) def _init_internal_event_handlers(self): \"\"\" Initialize the internal event handlers", "self._connected: self.connect() return self def __exit__(self, exc_type, exc_val, exc_tb): if", "for group in await self.api.group.get_groups(): self._groups[group.group_id] = controllers.Group(self, group) return", "to our HEOS device :return: None \"\"\" logger.info(f'Closing connection to", "callback in self._event_subscriptions.get(event.command, []): logger.debug(f'Calling registered callback {callback} for event", "account name, if available. :return: tuple \"\"\" self._account_status, self._account_username =", "task that processes events that originate from the event channel.", ".networking.errors import ChannelUnavailableError from .models.heos import HEOSEvent from .models.system import", "def get_group(self, group_id): \"\"\" Retrieve a specific group by ID.", "self._command_channel self._init_internal_event_handlers() def __repr__(self): return f'<Pytheos(server={self.server}, port={self.port})>' def __enter__(self): if", "\"\"\" Retrieves a mapping of IDs to Groups present in", "self._account_status: Optional[AccountStatus] = None self._account_username: Optional[str] = None self._players: list", "from .models.system import AccountStatus logger = logging.getLogger('pytheos') class Pytheos: \"\"\"", "Groups present in the HEOS system. :return: dict \"\"\" self._groups", "_handle_players_changed(self, event: HEOSEvent): raise NotImplementedError() def _handle_groups_changed(self, event: HEOSEvent): raise", "_handle_groups_changed(self, event: HEOSEvent): raise NotImplementedError() def _handle_player_state_changed(self, event: HEOSEvent): raise", "@staticmethod def check_channel_availability(channel: Connection): \"\"\" Checks to make sure that", "None self._event_processor: Optional[asyncio.Task] = None self._connected: bool = False self._event_subscriptions:", "\"\"\" while True: event = await self._event_queue.get() if event: logger.debug(f'Processing", "'event/player_volume_changed': self._handle_volume_changed, # 'event/repeat_mode_changed': self._handle_repeat_mode_changed, # 'event/shuffle_mode_changed': self._handle_shuffle_mode_changed, # 'event/group_volume_changed':", "Constructor :param server: Server hostname or IP :param port: Port", "is available. :param channel: Channel connection :raises: ChannelUnavailableError :return: None", "self.api.browse.get_music_sources(): self._sources[source.source_id] = controllers.Source(self, source) return self._sources def is_receiving_events(self): \"\"\"", "await self.api.system.sign_out() async def get_players(self): \"\"\" Retrieves a mapping of", "import SSDPResponse from .networking.errors import ChannelUnavailableError from .models.heos import HEOSEvent", "self.port) self._connected = True self._receive_events = enable_event_connection if self._receive_events: await", "\"\"\" self._players = [controllers.Player(self, player) for player in await self.api.player.get_players()]", "# FIXME: Meh, do something better with this. internal_handler_map =", "check_channel_availability(channel: Connection): \"\"\" Checks to make sure that the provided", "= controllers.Group(self, group) return self._groups async def get_sources(self): \"\"\" Retrieves", "in await self.api.player.get_players()] return self._players async def get_group(self, group_id): \"\"\"", "raise NotImplementedError() def _handle_now_playing_progress(self, event: HEOSEvent): raise NotImplementedError() def _handle_playback_error(self,", "'event/user_changed': self._handle_user_changed, } for event, callback in internal_handler_map.items(): self.subscribe(event, callback)", "await self.api.system.sign_in(username, password) async def sign_out(self): \"\"\" Signs out from", "to Players present in the HEOS system. :return: list \"\"\"", "NotImplementedError() def _handle_shuffle_mode_changed(self, event: HEOSEvent): raise NotImplementedError() def _handle_group_volume_changed(self, event:", "self.connect() return self def __exit__(self, exc_type, exc_val, exc_tb): if self._connected:", "to {self.server}:{self.port}') if self._event_task: self._event_task.cancel() if self._event_processor: self._event_processor.cancel() self._connected =", "\"\"\" Enables or disables event reception. :param value: True or", "await self._event_queue.get() if event: logger.debug(f'Processing event: {event!r}') await self._event_handler(event) await", "HEOSEvent): raise NotImplementedError() def _handle_playback_error(self, event: HEOSEvent): raise NotImplementedError() def", "callback) def _handle_sources_changed(self, event: HEOSEvent): raise NotImplementedError() def _handle_players_changed(self, event:", "value): logger.setLevel(value) @property def connected(self): return self._connected @property def signed_in(self):", "await self.api.system.reboot() async def check_account(self) -> tuple: \"\"\" Checks if", "adds them to our event queue for later processing. :return:", "import HEOSEvent from .models.system import AccountStatus logger = logging.getLogger('pytheos') class", "self._connected @property def signed_in(self): return self._account_status == AccountStatus.SignedIn @property def", "= asyncio.get_running_loop() self._event_task = loop.create_task(self._listen_for_events()) self._event_processor = loop.create_task(self._process_events()) if refresh:", "internal event handlers :return: None \"\"\" # FIXME: Meh, do", "def _handle_repeat_mode_changed(self, event: HEOSEvent): raise NotImplementedError() def _handle_shuffle_mode_changed(self, event: HEOSEvent):", "def reboot(self): \"\"\" Instructs the system to reboot. :return: None", "we want event messages on the event channel. :param value:", "event channel. :param value: True or False :return: None \"\"\"", "import controllers from .networking.connection import Connection from .networking.types import SSDPResponse", "self._account_username = await self.api.system.check_account() return self._account_status, self._account_username async def sign_in(self,", "self.server: str = server self.port: int = port self._command_channel =", "password) async def sign_out(self): \"\"\" Signs out from the HEOS", "NotImplementedError() def _handle_now_playing_changed(self, event: HEOSEvent): raise NotImplementedError() def _handle_now_playing_progress(self, event:", "of IDs to Groups present in the HEOS system. :return:", "channel: Channel connection :raises: ChannelUnavailableError :return: None \"\"\" if not", "None \"\"\" await self._event_channel.system.register_for_change_events(value) def close(self): \"\"\" Close the connection", "async def sign_in(self, username: str, password: str): \"\"\" Signs the", "\"\"\" # FIXME: Meh, do something better with this. internal_handler_map", "handler :param event: HEOS Event :return: None \"\"\" loop =", "source) return self._sources def is_receiving_events(self): \"\"\" Retrieves whether or not", "a mapping of IDs to Sources present in the HEOS", "for system events :param refresh: Determines if the system state", "= logging.getLogger('pytheos') class Pytheos: \"\"\" Pytheos interface \"\"\" DEFAULT_PORT =", "IDs to Players present in the HEOS system. :return: list", "False def subscribe(self, event_name: str, callback: Callable): \"\"\" Subscribe a", "out from the HEOS service. :return: None \"\"\" await self.api.system.sign_out()", "False :return: None \"\"\" self._receive_events = value await self._set_register_for_change_events(value) async", "is_receiving_events(self): \"\"\" Retrieves whether or not we're receiving events. :return:", "a mapping of IDs to Players present in the HEOS", "self._event_subscriptions.get(event.command, []): logger.debug(f'Calling registered callback {callback} for event {event!r}') loop.create_task(callback(event))", "\"\"\" self._groups = {} for group in await self.api.group.get_groups(): self._groups[group.group_id]", "get_group(self, group_id): \"\"\" Retrieve a specific group by ID. :param", "HEOS device. :param enable_event_connection: Enables establishing an additional connection for", ":raises: ValueError :return: The Pytheos instance \"\"\" if isinstance(host, SSDPResponse):", "= await self.api.system.check_account() return self._account_status, self._account_username async def sign_in(self, username:", "in the HEOS system. :return: \"\"\" self._sources = {} for", "channel. :param value: True or False :return: None \"\"\" await", "import AccountStatus logger = logging.getLogger('pytheos') class Pytheos: \"\"\" Pytheos interface", "logger.info(f'Closing connection to {self.server}:{self.port}') if self._event_task: self._event_task.cancel() if self._event_processor: self._event_processor.cancel()", "Sources present in the HEOS system. :return: \"\"\" self._sources =", "channel and adds them to our event queue for later", "self._event_queue.get() if event: logger.debug(f'Processing event: {event!r}') await self._event_handler(event) await asyncio.sleep(0.5)", "that the provided channel is available. :param channel: Channel connection", "events that originate from the event channel. :return: None \"\"\"", "to Sources present in the HEOS system. :return: \"\"\" self._sources", "HEOS Event :return: None \"\"\" loop = asyncio.get_running_loop() for callback", "logger.setLevel(value) @property def connected(self): return self._connected @property def signed_in(self): return", "group) return self._groups async def get_sources(self): \"\"\" Retrieves a mapping", "self._handle_now_playing_progress, # 'event/player_playback_error': self._handle_playback_error, # 'event/player_queue_changed': self._handle_queue_changed, # 'event/player_volume_changed': self._handle_volume_changed,", "Connection from .networking.types import SSDPResponse from .networking.errors import ChannelUnavailableError from", "logged into HEOS and returns the status and account name,", "\"\"\" Connect to our HEOS device. :param enable_event_connection: Enables establishing", "self.port: int = port self._command_channel = Connection() self._event_channel = Connection()", "\"\"\" Notifies HEOS that we want event messages on the", ":param callback: Callback function :return: None \"\"\" # FIXME: Change", "system to reboot. :return: None \"\"\" await self.api.system.reboot() async def", "value): \"\"\" Enables or disables event reception. :param value: True", "dict. self.api: Connection = self._command_channel self._init_internal_event_handlers() def __repr__(self): return f'<Pytheos(server={self.server},", "source in await self.api.browse.get_music_sources(): self._sources[source.source_id] = controllers.Source(self, source) return self._sources", "internal_handler_map.items(): self.subscribe(event, callback) def _handle_sources_changed(self, event: HEOSEvent): raise NotImplementedError() def", "by ID. :param group_id: Group ID :return: PytheosGroup \"\"\" groups", "system. :return: \"\"\" self._sources = {} for source in await", "in await self.api.group.get_groups(): self._groups[group.group_id] = controllers.Group(self, group) return self._groups async", "Optional, Union from . import utils from . import controllers", "self._sources[source.source_id] = controllers.Source(self, source) return self._sources def is_receiving_events(self): \"\"\" Retrieves", "messages from the event channel and adds them to our", "event: HEOSEvent): raise NotImplementedError() def _handle_now_playing_progress(self, event: HEOSEvent): raise NotImplementedError()", "player) for player in await self.api.player.get_players()] return self._players async def", "the event channel and adds them to our event queue", "if the system is logged into HEOS and returns the", "self._handle_repeat_mode_changed, # 'event/shuffle_mode_changed': self._handle_shuffle_mode_changed, # 'event/group_volume_changed': self._handle_group_volume_changed, # 'event/user_changed': self._handle_user_changed,", "-> Pytheos: \"\"\" Connect to our HEOS device. :param enable_event_connection:", "SSDPResponse from .networking.errors import ChannelUnavailableError from .models.heos import HEOSEvent from", "None \"\"\" logger.info(f'Closing connection to {self.server}:{self.port}') if self._event_task: self._event_task.cancel() if", "group_id): \"\"\" Retrieve a specific group by ID. :param group_id:", "await asyncio.sleep(0.5) async def _event_handler(self, event: HEOSEvent): \"\"\" Internal event", "Pytheos instance \"\"\" if isinstance(host, SSDPResponse): host = utils.extract_host(host.location) conn", "IDs to Groups present in the HEOS system. :return: dict", "callback: Callback function :return: None \"\"\" # FIXME: Change event_name", ":param port: Port number \"\"\" if isinstance(server, SSDPResponse): server =", "event, callback in internal_handler_map.items(): self.subscribe(event, callback) def _handle_sources_changed(self, event: HEOSEvent):", "@property def log_level(self): return logger.level @log_level.setter def log_level(self, value): logger.setLevel(value)", "self async def _set_register_for_change_events(self, value: bool): \"\"\" Notifies HEOS that", "value: True or False :return: None \"\"\" await self._event_channel.system.register_for_change_events(value) def", "password: Password :return: None \"\"\" await self.api.system.sign_in(username, password) async def", "IP :param port: Port number \"\"\" if isinstance(server, SSDPResponse): server", "and returns the status and account name, if available. :return:", "the system to reboot. :return: None \"\"\" await self.api.system.reboot() async", "into HEOS and returns the status and account name, if", "self._handle_player_state_changed, # 'event/player_now_playing_changed': self._handle_now_playing_changed, # 'event/player_now_playing_progress': self._handle_now_playing_progress, # 'event/player_playback_error': self._handle_playback_error,", "def get_sources(self): \"\"\" Retrieves a mapping of IDs to Sources", "return self._account_status == AccountStatus.SignedIn @property def username(self): return self._account_username def", "def _handle_player_state_changed(self, event: HEOSEvent): raise NotImplementedError() def _handle_now_playing_changed(self, event: HEOSEvent):", "task that reads messages from the event channel and adds", "Channel connection :raises: ChannelUnavailableError :return: None \"\"\" if not channel", "'event/player_now_playing_progress': self._handle_now_playing_progress, # 'event/player_playback_error': self._handle_playback_error, # 'event/player_queue_changed': self._handle_queue_changed, # 'event/player_volume_changed':", "self def __exit__(self, exc_type, exc_val, exc_tb): if self._connected: self.close() async", "system is logged into HEOS and returns the status and", "self._event_queue = asyncio.Queue() self._event_task: Optional[asyncio.Task] = None self._event_processor: Optional[asyncio.Task] =", "await self._set_register_for_change_events(value) async def _listen_for_events(self): \"\"\" Async task that reads", "Username :param password: Password :return: None \"\"\" await self.api.system.sign_in(username, password)", "mapping of IDs to Players present in the HEOS system.", "await self.enable_event_reception(True) loop = asyncio.get_running_loop() self._event_task = loop.create_task(self._listen_for_events()) self._event_processor =", "check_account(self) -> tuple: \"\"\" Checks if the system is logged", ":return: None \"\"\" logger.info(f'Closing connection to {self.server}:{self.port}') if self._event_task: self._event_task.cancel()", "self._handle_sources_changed, # 'event/players_changed': self._handle_players_changed, # 'event/groups_changed': self._handle_groups_changed, # 'event/player_state_changed': self._handle_player_state_changed,", "from . import utils from . import controllers from .networking.connection", "of IDs to Players present in the HEOS system. :return:", "FIXME?: Not sure I like having this as a dict.", "to :raises: ValueError :return: The Pytheos instance \"\"\" if isinstance(host,", "\"\"\" Instructs the system to reboot. :return: None \"\"\" await", "self.api.system.sign_in(username, password) async def sign_out(self): \"\"\" Signs out from the", "groups.get(group_id) async def get_groups(self): \"\"\" Retrieves a mapping of IDs", "self._handle_playback_error, # 'event/player_queue_changed': self._handle_queue_changed, # 'event/player_volume_changed': self._handle_volume_changed, # 'event/repeat_mode_changed': self._handle_repeat_mode_changed,", "FIXME: Change event_name to an enum if self._event_subscriptions.get(event_name) is None:", "NotImplementedError() def _handle_now_playing_progress(self, event: HEOSEvent): raise NotImplementedError() def _handle_playback_error(self, event:", "host: Host to connect to :param port: Port to connect", "self._receive_events async def enable_event_reception(self, value): \"\"\" Enables or disables event", "event: HEOSEvent): raise NotImplementedError() def _handle_repeat_mode_changed(self, event: HEOSEvent): raise NotImplementedError()", "return groups.get(group_id) async def get_groups(self): \"\"\" Retrieves a mapping of", "if self._event_processor: self._event_processor.cancel() self._connected = False def subscribe(self, event_name: str,", "= controllers.Source(self, source) return self._sources def is_receiving_events(self): \"\"\" Retrieves whether", "context manager for use with the connection. :param host: Host", "self.close() async def connect(self, enable_event_connection: bool=True, refresh: bool=True) -> Pytheos:", "ChannelUnavailableError from .models.heos import HEOSEvent from .models.system import AccountStatus logger", "\"\"\" Subscribe a callback function to a specific event :param", "tuple \"\"\" self._account_status, self._account_username = await self.api.system.check_account() return self._account_status, self._account_username", "= False self._event_subscriptions: dict = {} self._receive_events: bool = True", "value: bool): \"\"\" Notifies HEOS that we want event messages", "[] self._groups: dict = {} # FIXME?: Not sure I", "async def get_players(self): \"\"\" Retrieves a mapping of IDs to", "= port self._command_channel = Connection() self._event_channel = Connection() self._event_queue =", "return self._sources def is_receiving_events(self): \"\"\" Retrieves whether or not we're", "self._event_task.cancel() if self._event_processor: self._event_processor.cancel() self._connected = False def subscribe(self, event_name:", "asyncio.sleep(0.5) async def _process_events(self): \"\"\" Async task that processes events", "\"\"\" await self.check_account() await self.get_players() await self.get_groups() await self.get_sources() async", "str = server self.port: int = port self._command_channel = Connection()", "and account name, if available. :return: tuple \"\"\" self._account_status, self._account_username", ":param channel: Channel connection :raises: ChannelUnavailableError :return: None \"\"\" if", "= None self._event_processor: Optional[asyncio.Task] = None self._connected: bool = False", "\"\"\" Internal event handler :param event: HEOS Event :return: None", "\"\"\" Provides the primary interface into the library \"\"\" from", ":return: PytheosGroup \"\"\" groups = await self.get_groups() return groups.get(group_id) async", "event: HEOSEvent): raise NotImplementedError() def _handle_user_changed(self, event: HEOSEvent): raise NotImplementedError()", "enable_event_connection: Enables establishing an additional connection for system events :param", "def _handle_user_changed(self, event: HEOSEvent): raise NotImplementedError() async def connect(host: Union[SSDPResponse,", "# 'event/player_now_playing_progress': self._handle_now_playing_progress, # 'event/player_playback_error': self._handle_playback_error, # 'event/player_queue_changed': self._handle_queue_changed, #", "logger.level @log_level.setter def log_level(self, value): logger.setLevel(value) @property def connected(self): return", "the HEOS system. :return: list \"\"\" self._players = [controllers.Player(self, player)", "self._account_username async def sign_in(self, username: str, password: str): \"\"\" Signs", "bool=True) -> Pytheos: \"\"\" Connect to our HEOS device. :param", "raise NotImplementedError() def _handle_user_changed(self, event: HEOSEvent): raise NotImplementedError() async def", "dict = {} # FIXME?: Not sure I like having", "connection to our HEOS device :return: None \"\"\" logger.info(f'Closing connection", "await self.get_players() await self.get_groups() await self.get_sources() async def reboot(self): \"\"\"", "await self._event_handler(event) await asyncio.sleep(0.5) async def _event_handler(self, event: HEOSEvent): \"\"\"", "self._command_channel.connect(self.server, self.port) self._connected = True self._receive_events = enable_event_connection if self._receive_events:", "True self._receive_events = enable_event_connection if self._receive_events: await self._event_channel.connect(self.server, self.port, deduplicate=True)", "def signed_in(self): return self._account_status == AccountStatus.SignedIn @property def username(self): return", "= asyncio.Queue() self._event_task: Optional[asyncio.Task] = None self._event_processor: Optional[asyncio.Task] = None", "sign_out(self): \"\"\" Signs out from the HEOS service. :return: None", "\"\"\" Retrieves a mapping of IDs to Players present in", "additional connection for system events :param refresh: Determines if the", "None \"\"\" self._receive_events = value await self._set_register_for_change_events(value) async def _listen_for_events(self):", ":return: None \"\"\" await self.api.system.reboot() async def check_account(self) -> tuple:", "a specific group by ID. :param group_id: Group ID :return:", "to a specific event :param event_name: Event name :param callback:", "Event name :param callback: Callback function :return: None \"\"\" #", "port={self.port})>' def __enter__(self): if not self._connected: self.connect() return self def", "the provided channel is available. :param channel: Channel connection :raises:", "await self.refresh() return self async def _set_register_for_change_events(self, value: bool): \"\"\"", "a callback function to a specific event :param event_name: Event", "event = HEOSEvent(results) logger.debug(f\"Received event: {event!r}\") await self._event_queue.put(event) await asyncio.sleep(0.5)", "Connection() self._event_channel = Connection() self._event_queue = asyncio.Queue() self._event_task: Optional[asyncio.Task] =", "return self async def _set_register_for_change_events(self, value: bool): \"\"\" Notifies HEOS", "whether or not we're receiving events. :return: bool \"\"\" return", "our event queue for later processing. :return: None \"\"\" while", "@log_level.setter def log_level(self, value): logger.setLevel(value) @property def connected(self): return self._connected", ":param host: Host to connect to :param port: Port to", "device :return: None \"\"\" logger.info(f'Closing connection to {self.server}:{self.port}') if self._event_task:", "self._groups[group.group_id] = controllers.Group(self, group) return self._groups async def get_sources(self): \"\"\"", "'event/sources_changed': self._handle_sources_changed, # 'event/players_changed': self._handle_players_changed, # 'event/groups_changed': self._handle_groups_changed, # 'event/player_state_changed':", "{self.server}:{self.port}') if self._event_task: self._event_task.cancel() if self._event_processor: self._event_processor.cancel() self._connected = False", "Retrieves whether or not we're receiving events. :return: bool \"\"\"", "_handle_now_playing_progress(self, event: HEOSEvent): raise NotImplementedError() def _handle_playback_error(self, event: HEOSEvent): raise", "The Pytheos instance \"\"\" if isinstance(host, SSDPResponse): host = utils.extract_host(host.location)", ":return: bool \"\"\" return self._receive_events async def enable_event_reception(self, value): \"\"\"", "# FIXME: Change event_name to an enum if self._event_subscriptions.get(event_name) is", "enum if self._event_subscriptions.get(event_name) is None: self._event_subscriptions[event_name] = [] self._event_subscriptions[event_name].append(callback) async", "get_sources(self): \"\"\" Retrieves a mapping of IDs to Sources present", "# 'event/groups_changed': self._handle_groups_changed, # 'event/player_state_changed': self._handle_player_state_changed, # 'event/player_now_playing_changed': self._handle_now_playing_changed, #", "self.enable_event_reception(True) loop = asyncio.get_running_loop() self._event_task = loop.create_task(self._listen_for_events()) self._event_processor = loop.create_task(self._process_events())", "import logging from typing import Callable, Optional, Union from .", "\"\"\" logger.info(f'Connecting to {self.server}:{self.port}') await self._command_channel.connect(self.server, self.port) self._connected = True", "NotImplementedError() def _handle_playback_error(self, event: HEOSEvent): raise NotImplementedError() def _handle_queue_changed(self, event:", "for use with the connection. :param host: Host to connect", "if not self._connected: self.connect() return self def __exit__(self, exc_type, exc_val,", ":return: list \"\"\" self._players = [controllers.Player(self, player) for player in", "def connect(self, enable_event_connection: bool=True, refresh: bool=True) -> Pytheos: \"\"\" Connect", "None \"\"\" if not channel or not channel.connected: raise ChannelUnavailableError()", "str, password: str): \"\"\" Signs the system into the HEOS", "async def connect(self, enable_event_connection: bool=True, refresh: bool=True) -> Pytheos: \"\"\"", "self._connected = True self._receive_events = enable_event_connection if self._receive_events: await self._event_channel.connect(self.server,", "} for event, callback in internal_handler_map.items(): self.subscribe(event, callback) def _handle_sources_changed(self,", "\"\"\" groups = await self.get_groups() return groups.get(group_id) async def get_groups(self):", "event: HEOSEvent): raise NotImplementedError() def _handle_shuffle_mode_changed(self, event: HEOSEvent): raise NotImplementedError()", "reboot(self): \"\"\" Instructs the system to reboot. :return: None \"\"\"", "connect to :raises: ValueError :return: The Pytheos instance \"\"\" if", "self.api.system.sign_out() async def get_players(self): \"\"\" Retrieves a mapping of IDs", "bool = False self._event_subscriptions: dict = {} self._receive_events: bool =", "= { # 'event/sources_changed': self._handle_sources_changed, # 'event/players_changed': self._handle_players_changed, # 'event/groups_changed':", "get_players(self): \"\"\" Retrieves a mapping of IDs to Players present", "True: results = await self._event_channel.read_message() if results: event = HEOSEvent(results)", "NotImplementedError() def _handle_groups_changed(self, event: HEOSEvent): raise NotImplementedError() def _handle_player_state_changed(self, event:", "return a context manager for use with the connection. :param", "channel or not channel.connected: raise ChannelUnavailableError() @property def log_level(self): return", "bool \"\"\" return self._receive_events async def enable_event_reception(self, value): \"\"\" Enables", "None \"\"\" await self.api.system.sign_in(username, password) async def sign_out(self): \"\"\" Signs", "having this as a dict. self._sources: dict = {} #", "= server self.port: int = port self._command_channel = Connection() self._event_channel", "channel is available. :param channel: Channel connection :raises: ChannelUnavailableError :return:", "HEOS service. :param username: Username :param password: Password :return: None", "a dict. self.api: Connection = self._command_channel self._init_internal_event_handlers() def __repr__(self): return", "\"\"\" await self.api.system.reboot() async def check_account(self) -> tuple: \"\"\" Checks", "to reboot. :return: None \"\"\" await self.api.system.reboot() async def check_account(self)", "the HEOS system. :return: dict \"\"\" self._groups = {} for", "isinstance(host, SSDPResponse): host = utils.extract_host(host.location) conn = Pytheos(host, port) return", "enable_event_reception(self, value): \"\"\" Enables or disables event reception. :param value:", "event: HEOSEvent): raise NotImplementedError() def _handle_players_changed(self, event: HEOSEvent): raise NotImplementedError()", "HEOSEvent(results) logger.debug(f\"Received event: {event!r}\") await self._event_queue.put(event) await asyncio.sleep(0.5) async def", "'event/group_volume_changed': self._handle_group_volume_changed, # 'event/user_changed': self._handle_user_changed, } for event, callback in", "None: self._event_subscriptions[event_name] = [] self._event_subscriptions[event_name].append(callback) async def refresh(self): \"\"\" Refreshes", "self._sources = {} for source in await self.api.browse.get_music_sources(): self._sources[source.source_id] =", "self._account_status == AccountStatus.SignedIn @property def username(self): return self._account_username def __init__(self,", "Enables establishing an additional connection for system events :param refresh:", "handlers :return: None \"\"\" # FIXME: Meh, do something better", "ValueError :return: The Pytheos instance \"\"\" if isinstance(host, SSDPResponse): host", "await asyncio.sleep(0.5) async def _process_events(self): \"\"\" Async task that processes", "is logged into HEOS and returns the status and account", "event: HEOS Event :return: None \"\"\" loop = asyncio.get_running_loop() for", "from .networking.connection import Connection from .networking.types import SSDPResponse from .networking.errors", "raise NotImplementedError() async def connect(host: Union[SSDPResponse, str], port: int=Pytheos.DEFAULT_PORT) ->", "HEOS system. :return: dict \"\"\" self._groups = {} for group", "self._handle_queue_changed, # 'event/player_volume_changed': self._handle_volume_changed, # 'event/repeat_mode_changed': self._handle_repeat_mode_changed, # 'event/shuffle_mode_changed': self._handle_shuffle_mode_changed,", "await self.check_account() await self.get_players() await self.get_groups() await self.get_sources() async def", "host and return a context manager for use with the", "self._event_processor: self._event_processor.cancel() self._connected = False def subscribe(self, event_name: str, callback:", "connect to :param port: Port to connect to :raises: ValueError", "_handle_playback_error(self, event: HEOSEvent): raise NotImplementedError() def _handle_queue_changed(self, event: HEOSEvent): raise", "self.api.system.check_account() return self._account_status, self._account_username async def sign_in(self, username: str, password:", "= None self._account_username: Optional[str] = None self._players: list = []", "# 'event/player_playback_error': self._handle_playback_error, # 'event/player_queue_changed': self._handle_queue_changed, # 'event/player_volume_changed': self._handle_volume_changed, #", "HEOSEvent): raise NotImplementedError() def _handle_repeat_mode_changed(self, event: HEOSEvent): raise NotImplementedError() def", "\"\"\" Checks to make sure that the provided channel is", "and adds them to our event queue for later processing.", "\"\"\" logger.info(f'Closing connection to {self.server}:{self.port}') if self._event_task: self._event_task.cancel() if self._event_processor:", "_set_register_for_change_events(self, value: bool): \"\"\" Notifies HEOS that we want event", "Instructs the system to reboot. :return: None \"\"\" await self.api.system.reboot()", "_listen_for_events(self): \"\"\" Async task that reads messages from the event", "of IDs to Sources present in the HEOS system. :return:", "specific event :param event_name: Event name :param callback: Callback function", "not channel or not channel.connected: raise ChannelUnavailableError() @property def log_level(self):", "event: HEOSEvent): raise NotImplementedError() def _handle_groups_changed(self, event: HEOSEvent): raise NotImplementedError()", "present in the HEOS system. :return: \"\"\" self._sources = {}", "asyncio import logging from typing import Callable, Optional, Union from", "Retrieves a mapping of IDs to Players present in the", "= {} # FIXME?: Not sure I like having this", "to our HEOS device. :param enable_event_connection: Enables establishing an additional", "name, if available. :return: tuple \"\"\" self._account_status, self._account_username = await", "logging from typing import Callable, Optional, Union from . import", "in the HEOS system. :return: list \"\"\" self._players = [controllers.Player(self,", "asyncio.get_running_loop() self._event_task = loop.create_task(self._listen_for_events()) self._event_processor = loop.create_task(self._process_events()) if refresh: await", "= {} for source in await self.api.browse.get_music_sources(): self._sources[source.source_id] = controllers.Source(self,", "await self._event_channel.read_message() if results: event = HEOSEvent(results) logger.debug(f\"Received event: {event!r}\")", "logger.info(f'Connecting to {self.server}:{self.port}') await self._command_channel.connect(self.server, self.port) self._connected = True self._receive_events", "self._handle_shuffle_mode_changed, # 'event/group_volume_changed': self._handle_group_volume_changed, # 'event/user_changed': self._handle_user_changed, } for event,", ". import controllers from .networking.connection import Connection from .networking.types import", "self._handle_group_volume_changed, # 'event/user_changed': self._handle_user_changed, } for event, callback in internal_handler_map.items():", "Internal event handler :param event: HEOS Event :return: None \"\"\"", ". import utils from . import controllers from .networking.connection import", "Not sure I like having this as a dict. self._sources:", "Pytheos: \"\"\" Connect to our HEOS device. :param enable_event_connection: Enables", ":return: None \"\"\" while True: event = await self._event_queue.get() if", "HEOSEvent): raise NotImplementedError() def _handle_volume_changed(self, event: HEOSEvent): raise NotImplementedError() def", "event: HEOSEvent): raise NotImplementedError() def _handle_queue_changed(self, event: HEOSEvent): raise NotImplementedError()", "system. :return: list \"\"\" self._players = [controllers.Player(self, player) for player", "that reads messages from the event channel and adds them", "\"\"\" Async task that reads messages from the event channel", "reads messages from the event channel and adds them to", "def _init_internal_event_handlers(self): \"\"\" Initialize the internal event handlers :return: None", "_handle_volume_changed(self, event: HEOSEvent): raise NotImplementedError() def _handle_repeat_mode_changed(self, event: HEOSEvent): raise", "await self._event_queue.put(event) await asyncio.sleep(0.5) async def _process_events(self): \"\"\" Async task", "= True self._receive_events = enable_event_connection if self._receive_events: await self._event_channel.connect(self.server, self.port,", "None \"\"\" await self.api.system.sign_out() async def get_players(self): \"\"\" Retrieves a", "a dict. self._sources: dict = {} # FIXME?: Not sure", "self._event_processor = loop.create_task(self._process_events()) if refresh: await self.refresh() return self async", "asyncio.get_running_loop() for callback in self._event_subscriptions.get(event.command, []): logger.debug(f'Calling registered callback {callback}", "events. :return: bool \"\"\" return self._receive_events async def enable_event_reception(self, value):", "channel. :return: None \"\"\" while True: event = await self._event_queue.get()", "def _handle_playback_error(self, event: HEOSEvent): raise NotImplementedError() def _handle_queue_changed(self, event: HEOSEvent):", "to connect to :param port: Port to connect to :raises:", "with the connection. :param host: Host to connect to :param", "event: HEOSEvent): raise NotImplementedError() async def connect(host: Union[SSDPResponse, str], port:", "groups = await self.get_groups() return groups.get(group_id) async def get_groups(self): \"\"\"", "Connection): \"\"\" Checks to make sure that the provided channel", "python \"\"\" Provides the primary interface into the library \"\"\"", "__future__ import annotations import asyncio import logging from typing import", ":param refresh: Determines if the system state should be automatically", "_handle_user_changed(self, event: HEOSEvent): raise NotImplementedError() async def connect(host: Union[SSDPResponse, str],", "we're receiving events. :return: bool \"\"\" return self._receive_events async def", "event handlers :return: None \"\"\" # FIXME: Meh, do something", "Pytheos: \"\"\" Connect to the provided host and return a", ":param value: True or False :return: None \"\"\" await self._event_channel.system.register_for_change_events(value)", "NotImplementedError() def _handle_group_volume_changed(self, event: HEOSEvent): raise NotImplementedError() def _handle_user_changed(self, event:", "Close the connection to our HEOS device :return: None \"\"\"", "bool = True self._account_status: Optional[AccountStatus] = None self._account_username: Optional[str] =", "receiving events. :return: bool \"\"\" return self._receive_events async def enable_event_reception(self,", "Checks if the system is logged into HEOS and returns", "_handle_sources_changed(self, event: HEOSEvent): raise NotImplementedError() def _handle_players_changed(self, event: HEOSEvent): raise", "-> Pytheos: \"\"\" Connect to the provided host and return", "event handler :param event: HEOS Event :return: None \"\"\" loop", "Signs the system into the HEOS service. :param username: Username", "return self._receive_events async def enable_event_reception(self, value): \"\"\" Enables or disables", "event: {event!r}') await self._event_handler(event) await asyncio.sleep(0.5) async def _event_handler(self, event:", "HEOSEvent): raise NotImplementedError() def _handle_groups_changed(self, event: HEOSEvent): raise NotImplementedError() def", "later processing. :return: None \"\"\" while True: results = await", "not we're receiving events. :return: bool \"\"\" return self._receive_events async", "results: event = HEOSEvent(results) logger.debug(f\"Received event: {event!r}\") await self._event_queue.put(event) await", "'event/repeat_mode_changed': self._handle_repeat_mode_changed, # 'event/shuffle_mode_changed': self._handle_shuffle_mode_changed, # 'event/group_volume_changed': self._handle_group_volume_changed, # 'event/user_changed':", "NotImplementedError() def _handle_user_changed(self, event: HEOSEvent): raise NotImplementedError() async def connect(host:", "[]): logger.debug(f'Calling registered callback {callback} for event {event!r}') loop.create_task(callback(event)) def", "def _handle_now_playing_progress(self, event: HEOSEvent): raise NotImplementedError() def _handle_playback_error(self, event: HEOSEvent):", "connect(host: Union[SSDPResponse, str], port: int=Pytheos.DEFAULT_PORT) -> Pytheos: \"\"\" Connect to", "Event :return: None \"\"\" loop = asyncio.get_running_loop() for callback in", "\"\"\" self._sources = {} for source in await self.api.browse.get_music_sources(): self._sources[source.source_id]", "__repr__(self): return f'<Pytheos(server={self.server}, port={self.port})>' def __enter__(self): if not self._connected: self.connect()", "enable_event_connection if self._receive_events: await self._event_channel.connect(self.server, self.port, deduplicate=True) await self.enable_event_reception(True) loop", "log_level(self, value): logger.setLevel(value) @property def connected(self): return self._connected @property def", "HEOSEvent): raise NotImplementedError() def _handle_player_state_changed(self, event: HEOSEvent): raise NotImplementedError() def", "self._receive_events = value await self._set_register_for_change_events(value) async def _listen_for_events(self): \"\"\" Async", "our HEOS device :return: None \"\"\" logger.info(f'Closing connection to {self.server}:{self.port}')", "ID. :param group_id: Group ID :return: PytheosGroup \"\"\" groups =", "Port number \"\"\" if isinstance(server, SSDPResponse): server = utils.extract_host(server.location) self.server:", ":return: None \"\"\" self._receive_events = value await self._set_register_for_change_events(value) async def", "def _handle_groups_changed(self, event: HEOSEvent): raise NotImplementedError() def _handle_player_state_changed(self, event: HEOSEvent):", "an additional connection for system events :param refresh: Determines if", "__enter__(self): if not self._connected: self.connect() return self def __exit__(self, exc_type,", ":return: self \"\"\" logger.info(f'Connecting to {self.server}:{self.port}') await self._command_channel.connect(self.server, self.port) self._connected", "\"\"\" Constructor :param server: Server hostname or IP :param port:", "Optional[asyncio.Task] = None self._connected: bool = False self._event_subscriptions: dict =", "exc_type, exc_val, exc_tb): if self._connected: self.close() async def connect(self, enable_event_connection:", "# 'event/player_state_changed': self._handle_player_state_changed, # 'event/player_now_playing_changed': self._handle_now_playing_changed, # 'event/player_now_playing_progress': self._handle_now_playing_progress, #", "Checks to make sure that the provided channel is available.", ":param enable_event_connection: Enables establishing an additional connection for system events", "AccountStatus logger = logging.getLogger('pytheos') class Pytheos: \"\"\" Pytheos interface \"\"\"", "sure I like having this as a dict. self._sources: dict", "None \"\"\" while True: results = await self._event_channel.read_message() if results:", "class Pytheos: \"\"\" Pytheos interface \"\"\" DEFAULT_PORT = 1255 @staticmethod", "Union[str, SSDPResponse]=None, port: Optional[int]=DEFAULT_PORT): \"\"\" Constructor :param server: Server hostname", "def _handle_group_volume_changed(self, event: HEOSEvent): raise NotImplementedError() def _handle_user_changed(self, event: HEOSEvent):", "= HEOSEvent(results) logger.debug(f\"Received event: {event!r}\") await self._event_queue.put(event) await asyncio.sleep(0.5) async", "from __future__ import annotations import asyncio import logging from typing", "= {} for group in await self.api.group.get_groups(): self._groups[group.group_id] = controllers.Group(self,", "int=Pytheos.DEFAULT_PORT) -> Pytheos: \"\"\" Connect to the provided host and", "from .models.heos import HEOSEvent from .models.system import AccountStatus logger =", "if self._event_subscriptions.get(event_name) is None: self._event_subscriptions[event_name] = [] self._event_subscriptions[event_name].append(callback) async def", "{} for source in await self.api.browse.get_music_sources(): self._sources[source.source_id] = controllers.Source(self, source)", "import annotations import asyncio import logging from typing import Callable,", "if self._event_task: self._event_task.cancel() if self._event_processor: self._event_processor.cancel() self._connected = False def", "= utils.extract_host(server.location) self.server: str = server self.port: int = port", "__init__(self, server: Union[str, SSDPResponse]=None, port: Optional[int]=DEFAULT_PORT): \"\"\" Constructor :param server:", "False :return: None \"\"\" await self._event_channel.system.register_for_change_events(value) def close(self): \"\"\" Close", "PytheosGroup \"\"\" groups = await self.get_groups() return groups.get(group_id) async def", "connection. :param host: Host to connect to :param port: Port", "await self._event_channel.system.register_for_change_events(value) def close(self): \"\"\" Close the connection to our", "returns the status and account name, if available. :return: tuple", "async def reboot(self): \"\"\" Instructs the system to reboot. :return:", "a context manager for use with the connection. :param host:", "# FIXME?: Not sure I like having this as a", "self \"\"\" logger.info(f'Connecting to {self.server}:{self.port}') await self._command_channel.connect(self.server, self.port) self._connected =", ":return: None \"\"\" if not channel or not channel.connected: raise", "the event channel. :return: None \"\"\" while True: event =", "self._receive_events: bool = True self._account_status: Optional[AccountStatus] = None self._account_username: Optional[str]", "event: logger.debug(f'Processing event: {event!r}') await self._event_handler(event) await asyncio.sleep(0.5) async def", "import Callable, Optional, Union from . import utils from .", "= await self._event_channel.read_message() if results: event = HEOSEvent(results) logger.debug(f\"Received event:", "def get_groups(self): \"\"\" Retrieves a mapping of IDs to Groups", "server self.port: int = port self._command_channel = Connection() self._event_channel =", "self._receive_events: await self._event_channel.connect(self.server, self.port, deduplicate=True) await self.enable_event_reception(True) loop = asyncio.get_running_loop()", "'event/player_playback_error': self._handle_playback_error, # 'event/player_queue_changed': self._handle_queue_changed, # 'event/player_volume_changed': self._handle_volume_changed, # 'event/repeat_mode_changed':", "SSDPResponse): host = utils.extract_host(host.location) conn = Pytheos(host, port) return await", "event queue for later processing. :return: None \"\"\" while True:", "# 'event/player_queue_changed': self._handle_queue_changed, # 'event/player_volume_changed': self._handle_volume_changed, # 'event/repeat_mode_changed': self._handle_repeat_mode_changed, #", "\"\"\" Async task that processes events that originate from the", "HEOS that we want event messages on the event channel.", "logger.debug(f'Processing event: {event!r}') await self._event_handler(event) await asyncio.sleep(0.5) async def _event_handler(self,", "event channel. :return: None \"\"\" while True: event = await", "def __init__(self, server: Union[str, SSDPResponse]=None, port: Optional[int]=DEFAULT_PORT): \"\"\" Constructor :param", "raise NotImplementedError() def _handle_volume_changed(self, event: HEOSEvent): raise NotImplementedError() def _handle_repeat_mode_changed(self,", "async def enable_event_reception(self, value): \"\"\" Enables or disables event reception.", ":return: None \"\"\" # FIXME: Meh, do something better with", "HEOSEvent): raise NotImplementedError() def _handle_group_volume_changed(self, event: HEOSEvent): raise NotImplementedError() def", "\"\"\" Retrieves whether or not we're receiving events. :return: bool", "typing import Callable, Optional, Union from . import utils from", "if the system state should be automatically refreshed :return: self", "logger.debug(f\"Received event: {event!r}\") await self._event_queue.put(event) await asyncio.sleep(0.5) async def _process_events(self):", "self._handle_user_changed, } for event, callback in internal_handler_map.items(): self.subscribe(event, callback) def", "if self._connected: self.close() async def connect(self, enable_event_connection: bool=True, refresh: bool=True)", ":return: None \"\"\" # FIXME: Change event_name to an enum", "disables event reception. :param value: True or False :return: None", "from . import controllers from .networking.connection import Connection from .networking.types", "def _listen_for_events(self): \"\"\" Async task that reads messages from the", "\"\"\" Retrieves a mapping of IDs to Sources present in", ":param group_id: Group ID :return: PytheosGroup \"\"\" groups = await", "and return a context manager for use with the connection.", "self.refresh() return self async def _set_register_for_change_events(self, value: bool): \"\"\" Notifies", "FIXME: Meh, do something better with this. internal_handler_map = {", "= [] self._event_subscriptions[event_name].append(callback) async def refresh(self): \"\"\" Refreshes internal information", "raise NotImplementedError() def _handle_repeat_mode_changed(self, event: HEOSEvent): raise NotImplementedError() def _handle_shuffle_mode_changed(self,", "def enable_event_reception(self, value): \"\"\" Enables or disables event reception. :param", "interface into the library \"\"\" from __future__ import annotations import", "to make sure that the provided channel is available. :param", "provided channel is available. :param channel: Channel connection :raises: ChannelUnavailableError", "raise NotImplementedError() def _handle_queue_changed(self, event: HEOSEvent): raise NotImplementedError() def _handle_volume_changed(self,", "event: {event!r}\") await self._event_queue.put(event) await asyncio.sleep(0.5) async def _process_events(self): \"\"\"", "return self._account_status, self._account_username async def sign_in(self, username: str, password: str):", "Pytheos interface \"\"\" DEFAULT_PORT = 1255 @staticmethod def check_channel_availability(channel: Connection):", "async def check_account(self) -> tuple: \"\"\" Checks if the system", "Optional[AccountStatus] = None self._account_username: Optional[str] = None self._players: list =", "NotImplementedError() def _handle_volume_changed(self, event: HEOSEvent): raise NotImplementedError() def _handle_repeat_mode_changed(self, event:", "self._event_task = loop.create_task(self._listen_for_events()) self._event_processor = loop.create_task(self._process_events()) if refresh: await self.refresh()", "import utils from . import controllers from .networking.connection import Connection", "primary interface into the library \"\"\" from __future__ import annotations", "{self.server}:{self.port}') await self._command_channel.connect(self.server, self.port) self._connected = True self._receive_events = enable_event_connection", "self._event_channel = Connection() self._event_queue = asyncio.Queue() self._event_task: Optional[asyncio.Task] = None", "None self._account_username: Optional[str] = None self._players: list = [] self._groups:", "= 1255 @staticmethod def check_channel_availability(channel: Connection): \"\"\" Checks to make", "NotImplementedError() def _handle_players_changed(self, event: HEOSEvent): raise NotImplementedError() def _handle_groups_changed(self, event:", "self._connected = False def subscribe(self, event_name: str, callback: Callable): \"\"\"", "async def get_group(self, group_id): \"\"\" Retrieve a specific group by", ":param port: Port to connect to :raises: ValueError :return: The", "want event messages on the event channel. :param value: True", "def refresh(self): \"\"\" Refreshes internal information from the HEOS system.", "\"\"\" Refreshes internal information from the HEOS system. :return: None", "into the HEOS service. :param username: Username :param password: Password", "self._players: list = [] self._groups: dict = {} # FIXME?:", "the provided host and return a context manager for use", "'event/players_changed': self._handle_players_changed, # 'event/groups_changed': self._handle_groups_changed, # 'event/player_state_changed': self._handle_player_state_changed, # 'event/player_now_playing_changed':", "utils.extract_host(server.location) self.server: str = server self.port: int = port self._command_channel", "= asyncio.get_running_loop() for callback in self._event_subscriptions.get(event.command, []): logger.debug(f'Calling registered callback", "AccountStatus.SignedIn @property def username(self): return self._account_username def __init__(self, server: Union[str,", "tuple: \"\"\" Checks if the system is logged into HEOS", "return self def __exit__(self, exc_type, exc_val, exc_tb): if self._connected: self.close()", "channel.connected: raise ChannelUnavailableError() @property def log_level(self): return logger.level @log_level.setter def", "# 'event/repeat_mode_changed': self._handle_repeat_mode_changed, # 'event/shuffle_mode_changed': self._handle_shuffle_mode_changed, # 'event/group_volume_changed': self._handle_group_volume_changed, #", "or not we're receiving events. :return: bool \"\"\" return self._receive_events", "None self._connected: bool = False self._event_subscriptions: dict = {} self._receive_events:", "for callback in self._event_subscriptions.get(event.command, []): logger.debug(f'Calling registered callback {callback} for", "self._account_username: Optional[str] = None self._players: list = [] self._groups: dict", "#!/usr/bin/env python \"\"\" Provides the primary interface into the library", "event channel and adds them to our event queue for", "\"\"\" while True: results = await self._event_channel.read_message() if results: event", "HEOS device :return: None \"\"\" logger.info(f'Closing connection to {self.server}:{self.port}') if", "self._handle_players_changed, # 'event/groups_changed': self._handle_groups_changed, # 'event/player_state_changed': self._handle_player_state_changed, # 'event/player_now_playing_changed': self._handle_now_playing_changed,", "callback in internal_handler_map.items(): self.subscribe(event, callback) def _handle_sources_changed(self, event: HEOSEvent): raise", "NotImplementedError() def _handle_queue_changed(self, event: HEOSEvent): raise NotImplementedError() def _handle_volume_changed(self, event:", "the system into the HEOS service. :param username: Username :param", "the system is logged into HEOS and returns the status", ":param password: Password :return: None \"\"\" await self.api.system.sign_in(username, password) async", "list \"\"\" self._players = [controllers.Player(self, player) for player in await", "def __exit__(self, exc_type, exc_val, exc_tb): if self._connected: self.close() async def", "be automatically refreshed :return: self \"\"\" logger.info(f'Connecting to {self.server}:{self.port}') await", "self.api.system.reboot() async def check_account(self) -> tuple: \"\"\" Checks if the", ":return: None \"\"\" await self._event_channel.system.register_for_change_events(value) def close(self): \"\"\" Close the", "self.get_groups() return groups.get(group_id) async def get_groups(self): \"\"\" Retrieves a mapping", "in self._event_subscriptions.get(event.command, []): logger.debug(f'Calling registered callback {callback} for event {event!r}')", "\"\"\" Initialize the internal event handlers :return: None \"\"\" #", "exc_val, exc_tb): if self._connected: self.close() async def connect(self, enable_event_connection: bool=True,", "username: Username :param password: Password :return: None \"\"\" await self.api.system.sign_in(username,", ":param value: True or False :return: None \"\"\" self._receive_events =", "{ # 'event/sources_changed': self._handle_sources_changed, # 'event/players_changed': self._handle_players_changed, # 'event/groups_changed': self._handle_groups_changed,", "HEOS and returns the status and account name, if available.", "logging.getLogger('pytheos') class Pytheos: \"\"\" Pytheos interface \"\"\" DEFAULT_PORT = 1255", ":param server: Server hostname or IP :param port: Port number", "if isinstance(server, SSDPResponse): server = utils.extract_host(server.location) self.server: str = server", "def log_level(self): return logger.level @log_level.setter def log_level(self, value): logger.setLevel(value) @property", "self._event_subscriptions.get(event_name) is None: self._event_subscriptions[event_name] = [] self._event_subscriptions[event_name].append(callback) async def refresh(self):", "return self._players async def get_group(self, group_id): \"\"\" Retrieve a specific", "Change event_name to an enum if self._event_subscriptions.get(event_name) is None: self._event_subscriptions[event_name]", "a mapping of IDs to Groups present in the HEOS", "as a dict. self.api: Connection = self._command_channel self._init_internal_event_handlers() def __repr__(self):", "await self.api.group.get_groups(): self._groups[group.group_id] = controllers.Group(self, group) return self._groups async def", "callback {callback} for event {event!r}') loop.create_task(callback(event)) def _init_internal_event_handlers(self): \"\"\" Initialize", "def _handle_queue_changed(self, event: HEOSEvent): raise NotImplementedError() def _handle_volume_changed(self, event: HEOSEvent):", "self.api.player.get_players()] return self._players async def get_group(self, group_id): \"\"\" Retrieve a", "if self._receive_events: await self._event_channel.connect(self.server, self.port, deduplicate=True) await self.enable_event_reception(True) loop =", "host = utils.extract_host(host.location) conn = Pytheos(host, port) return await conn.connect()", "@property def signed_in(self): return self._account_status == AccountStatus.SignedIn @property def username(self):", "use with the connection. :param host: Host to connect to", "def check_account(self) -> tuple: \"\"\" Checks if the system is", "def get_players(self): \"\"\" Retrieves a mapping of IDs to Players", "Connect to our HEOS device. :param enable_event_connection: Enables establishing an", "refresh(self): \"\"\" Refreshes internal information from the HEOS system. :return:", "Refreshes internal information from the HEOS system. :return: None \"\"\"", "\"\"\" Close the connection to our HEOS device :return: None", "await self.get_sources() async def reboot(self): \"\"\" Instructs the system to", "return self._groups async def get_sources(self): \"\"\" Retrieves a mapping of", "HEOS system. :return: \"\"\" self._sources = {} for source in", "provided host and return a context manager for use with", "= True self._account_status: Optional[AccountStatus] = None self._account_username: Optional[str] = None", "Determines if the system state should be automatically refreshed :return:", "'event/player_queue_changed': self._handle_queue_changed, # 'event/player_volume_changed': self._handle_volume_changed, # 'event/repeat_mode_changed': self._handle_repeat_mode_changed, # 'event/shuffle_mode_changed':", "controllers from .networking.connection import Connection from .networking.types import SSDPResponse from", "Connect to the provided host and return a context manager", "= [controllers.Player(self, player) for player in await self.api.player.get_players()] return self._players", "utils from . import controllers from .networking.connection import Connection from", "return self._account_username def __init__(self, server: Union[str, SSDPResponse]=None, port: Optional[int]=DEFAULT_PORT): \"\"\"", "from .networking.types import SSDPResponse from .networking.errors import ChannelUnavailableError from .models.heos", "for source in await self.api.browse.get_music_sources(): self._sources[source.source_id] = controllers.Source(self, source) return", "loop.create_task(self._listen_for_events()) self._event_processor = loop.create_task(self._process_events()) if refresh: await self.refresh() return self", "[controllers.Player(self, player) for player in await self.api.player.get_players()] return self._players async", "_process_events(self): \"\"\" Async task that processes events that originate from", "await self.get_groups() return groups.get(group_id) async def get_groups(self): \"\"\" Retrieves a", "self._event_handler(event) await asyncio.sleep(0.5) async def _event_handler(self, event: HEOSEvent): \"\"\" Internal", "import Connection from .networking.types import SSDPResponse from .networking.errors import ChannelUnavailableError", "Callable): \"\"\" Subscribe a callback function to a specific event", "something better with this. internal_handler_map = { # 'event/sources_changed': self._handle_sources_changed,", "event_name to an enum if self._event_subscriptions.get(event_name) is None: self._event_subscriptions[event_name] =", ":return: The Pytheos instance \"\"\" if isinstance(host, SSDPResponse): host =", "for event {event!r}') loop.create_task(callback(event)) def _init_internal_event_handlers(self): \"\"\" Initialize the internal", ":raises: ChannelUnavailableError :return: None \"\"\" if not channel or not", "False self._event_subscriptions: dict = {} self._receive_events: bool = True self._account_status:", "from the event channel and adds them to our event", "= await self.get_groups() return groups.get(group_id) async def get_groups(self): \"\"\" Retrieves", "\"\"\" from __future__ import annotations import asyncio import logging from", "if not channel or not channel.connected: raise ChannelUnavailableError() @property def", ":return: None \"\"\" await self.api.system.sign_in(username, password) async def sign_out(self): \"\"\"", "Retrieves a mapping of IDs to Sources present in the", "for later processing. :return: None \"\"\" while True: results =", "import asyncio import logging from typing import Callable, Optional, Union", "Players present in the HEOS system. :return: list \"\"\" self._players", "to :param port: Port to connect to :raises: ValueError :return:", "Optional[asyncio.Task] = None self._event_processor: Optional[asyncio.Task] = None self._connected: bool =", "self._connected: self.close() async def connect(self, enable_event_connection: bool=True, refresh: bool=True) ->", "async def _process_events(self): \"\"\" Async task that processes events that", "Connection = self._command_channel self._init_internal_event_handlers() def __repr__(self): return f'<Pytheos(server={self.server}, port={self.port})>' def", "def _event_handler(self, event: HEOSEvent): \"\"\" Internal event handler :param event:", "Union[SSDPResponse, str], port: int=Pytheos.DEFAULT_PORT) -> Pytheos: \"\"\" Connect to the", "self._event_processor.cancel() self._connected = False def subscribe(self, event_name: str, callback: Callable):", "this. internal_handler_map = { # 'event/sources_changed': self._handle_sources_changed, # 'event/players_changed': self._handle_players_changed,", "async def _event_handler(self, event: HEOSEvent): \"\"\" Internal event handler :param", "system events :param refresh: Determines if the system state should", "the connection. :param host: Host to connect to :param port:", "return logger.level @log_level.setter def log_level(self, value): logger.setLevel(value) @property def connected(self):", "self._account_username def __init__(self, server: Union[str, SSDPResponse]=None, port: Optional[int]=DEFAULT_PORT): \"\"\" Constructor", "self.api.group.get_groups(): self._groups[group.group_id] = controllers.Group(self, group) return self._groups async def get_sources(self):", "annotations import asyncio import logging from typing import Callable, Optional,", "await self.api.browse.get_music_sources(): self._sources[source.source_id] = controllers.Source(self, source) return self._sources def is_receiving_events(self):", "def close(self): \"\"\" Close the connection to our HEOS device", "def _handle_sources_changed(self, event: HEOSEvent): raise NotImplementedError() def _handle_players_changed(self, event: HEOSEvent):", "loop = asyncio.get_running_loop() for callback in self._event_subscriptions.get(event.command, []): logger.debug(f'Calling registered", "HEOSEvent): raise NotImplementedError() def _handle_shuffle_mode_changed(self, event: HEOSEvent): raise NotImplementedError() def", "# 'event/shuffle_mode_changed': self._handle_shuffle_mode_changed, # 'event/group_volume_changed': self._handle_group_volume_changed, # 'event/user_changed': self._handle_user_changed, }", "for event, callback in internal_handler_map.items(): self.subscribe(event, callback) def _handle_sources_changed(self, event:", "-> tuple: \"\"\" Checks if the system is logged into", "def sign_in(self, username: str, password: str): \"\"\" Signs the system", "Group ID :return: PytheosGroup \"\"\" groups = await self.get_groups() return", "deduplicate=True) await self.enable_event_reception(True) loop = asyncio.get_running_loop() self._event_task = loop.create_task(self._listen_for_events()) self._event_processor", "present in the HEOS system. :return: dict \"\"\" self._groups =", "or disables event reception. :param value: True or False :return:", "def sign_out(self): \"\"\" Signs out from the HEOS service. :return:", "def __repr__(self): return f'<Pytheos(server={self.server}, port={self.port})>' def __enter__(self): if not self._connected:", "system. :return: dict \"\"\" self._groups = {} for group in", "None \"\"\" loop = asyncio.get_running_loop() for callback in self._event_subscriptions.get(event.command, []):", "or False :return: None \"\"\" self._receive_events = value await self._set_register_for_change_events(value)", "= False def subscribe(self, event_name: str, callback: Callable): \"\"\" Subscribe", "self._players = [controllers.Player(self, player) for player in await self.api.player.get_players()] return", "instance \"\"\" if isinstance(host, SSDPResponse): host = utils.extract_host(host.location) conn =", "await self.get_groups() await self.get_sources() async def reboot(self): \"\"\" Instructs the", "def subscribe(self, event_name: str, callback: Callable): \"\"\" Subscribe a callback", "@property def connected(self): return self._connected @property def signed_in(self): return self._account_status", "= None self._players: list = [] self._groups: dict = {}", "[] self._event_subscriptions[event_name].append(callback) async def refresh(self): \"\"\" Refreshes internal information from", "system into the HEOS service. :param username: Username :param password:", "or IP :param port: Port number \"\"\" if isinstance(server, SSDPResponse):", "NotImplementedError() async def connect(host: Union[SSDPResponse, str], port: int=Pytheos.DEFAULT_PORT) -> Pytheos:", "Signs out from the HEOS service. :return: None \"\"\" await", "= [] self._groups: dict = {} # FIXME?: Not sure", "refresh: Determines if the system state should be automatically refreshed", "self._event_task: self._event_task.cancel() if self._event_processor: self._event_processor.cancel() self._connected = False def subscribe(self,", "event :param event_name: Event name :param callback: Callback function :return:", "system state should be automatically refreshed :return: self \"\"\" logger.info(f'Connecting", ":param username: Username :param password: Password :return: None \"\"\" await", "async def get_sources(self): \"\"\" Retrieves a mapping of IDs to", ":return: dict \"\"\" self._groups = {} for group in await", "Password :return: None \"\"\" await self.api.system.sign_in(username, password) async def sign_out(self):", "ChannelUnavailableError() @property def log_level(self): return logger.level @log_level.setter def log_level(self, value):", "\"\"\" Signs the system into the HEOS service. :param username:", "event reception. :param value: True or False :return: None \"\"\"", "enable_event_connection: bool=True, refresh: bool=True) -> Pytheos: \"\"\" Connect to our", "None \"\"\" # FIXME: Change event_name to an enum if", "connected(self): return self._connected @property def signed_in(self): return self._account_status == AccountStatus.SignedIn", "self.api: Connection = self._command_channel self._init_internal_event_handlers() def __repr__(self): return f'<Pytheos(server={self.server}, port={self.port})>'", "available. :param channel: Channel connection :raises: ChannelUnavailableError :return: None \"\"\"", "True self._account_status: Optional[AccountStatus] = None self._account_username: Optional[str] = None self._players:", "close(self): \"\"\" Close the connection to our HEOS device :return:", "self.subscribe(event, callback) def _handle_sources_changed(self, event: HEOSEvent): raise NotImplementedError() def _handle_players_changed(self,", "def _handle_players_changed(self, event: HEOSEvent): raise NotImplementedError() def _handle_groups_changed(self, event: HEOSEvent):", "NotImplementedError() def _handle_repeat_mode_changed(self, event: HEOSEvent): raise NotImplementedError() def _handle_shuffle_mode_changed(self, event:", "if isinstance(host, SSDPResponse): host = utils.extract_host(host.location) conn = Pytheos(host, port)", "logger = logging.getLogger('pytheos') class Pytheos: \"\"\" Pytheos interface \"\"\" DEFAULT_PORT", "HEOSEvent): raise NotImplementedError() def _handle_user_changed(self, event: HEOSEvent): raise NotImplementedError() async", "signed_in(self): return self._account_status == AccountStatus.SignedIn @property def username(self): return self._account_username", "event messages on the event channel. :param value: True or", "messages on the event channel. :param value: True or False", "or False :return: None \"\"\" await self._event_channel.system.register_for_change_events(value) def close(self): \"\"\"", "dict. self._sources: dict = {} # FIXME?: Not sure I", "from the event channel. :return: None \"\"\" while True: event", "'event/player_state_changed': self._handle_player_state_changed, # 'event/player_now_playing_changed': self._handle_now_playing_changed, # 'event/player_now_playing_progress': self._handle_now_playing_progress, # 'event/player_playback_error':", "= value await self._set_register_for_change_events(value) async def _listen_for_events(self): \"\"\" Async task", "def is_receiving_events(self): \"\"\" Retrieves whether or not we're receiving events.", "function :return: None \"\"\" # FIXME: Change event_name to an", "Optional[str] = None self._players: list = [] self._groups: dict =", "DEFAULT_PORT = 1255 @staticmethod def check_channel_availability(channel: Connection): \"\"\" Checks to", "server: Union[str, SSDPResponse]=None, port: Optional[int]=DEFAULT_PORT): \"\"\" Constructor :param server: Server", "raise NotImplementedError() def _handle_playback_error(self, event: HEOSEvent): raise NotImplementedError() def _handle_queue_changed(self,", "asyncio.Queue() self._event_task: Optional[asyncio.Task] = None self._event_processor: Optional[asyncio.Task] = None self._connected:", "not channel.connected: raise ChannelUnavailableError() @property def log_level(self): return logger.level @log_level.setter", ".networking.types import SSDPResponse from .networking.errors import ChannelUnavailableError from .models.heos import", "sign_in(self, username: str, password: str): \"\"\" Signs the system into", "event: HEOSEvent): \"\"\" Internal event handler :param event: HEOS Event", "raise NotImplementedError() def _handle_group_volume_changed(self, event: HEOSEvent): raise NotImplementedError() def _handle_user_changed(self,", "\"\"\" loop = asyncio.get_running_loop() for callback in self._event_subscriptions.get(event.command, []): logger.debug(f'Calling", "async def sign_out(self): \"\"\" Signs out from the HEOS service.", "def username(self): return self._account_username def __init__(self, server: Union[str, SSDPResponse]=None, port:", "HEOSEvent): raise NotImplementedError() async def connect(host: Union[SSDPResponse, str], port: int=Pytheos.DEFAULT_PORT)", "self._account_status, self._account_username = await self.api.system.check_account() return self._account_status, self._account_username async def", "Initialize the internal event handlers :return: None \"\"\" # FIXME:", "group by ID. :param group_id: Group ID :return: PytheosGroup \"\"\"", "hostname or IP :param port: Port number \"\"\" if isinstance(server,", "SSDPResponse): server = utils.extract_host(server.location) self.server: str = server self.port: int", "event: HEOSEvent): raise NotImplementedError() def _handle_volume_changed(self, event: HEOSEvent): raise NotImplementedError()", "def _set_register_for_change_events(self, value: bool): \"\"\" Notifies HEOS that we want", "= enable_event_connection if self._receive_events: await self._event_channel.connect(self.server, self.port, deduplicate=True) await self.enable_event_reception(True)", "Retrieves a mapping of IDs to Groups present in the", "\"\"\" Connect to the provided host and return a context", "if refresh: await self.refresh() return self async def _set_register_for_change_events(self, value:", "the system state should be automatically refreshed :return: self \"\"\"", "if results: event = HEOSEvent(results) logger.debug(f\"Received event: {event!r}\") await self._event_queue.put(event)", "await self._event_channel.connect(self.server, self.port, deduplicate=True) await self.enable_event_reception(True) loop = asyncio.get_running_loop() self._event_task", "= await self._event_queue.get() if event: logger.debug(f'Processing event: {event!r}') await self._event_handler(event)", "loop = asyncio.get_running_loop() self._event_task = loop.create_task(self._listen_for_events()) self._event_processor = loop.create_task(self._process_events()) if", "in the HEOS system. :return: dict \"\"\" self._groups = {}", "to our event queue for later processing. :return: None \"\"\"", "while True: results = await self._event_channel.read_message() if results: event =", "do something better with this. internal_handler_map = { # 'event/sources_changed':", "the connection to our HEOS device :return: None \"\"\" logger.info(f'Closing", "raise NotImplementedError() def _handle_players_changed(self, event: HEOSEvent): raise NotImplementedError() def _handle_groups_changed(self,", "service. :return: None \"\"\" await self.api.system.sign_out() async def get_players(self): \"\"\"", "queue for later processing. :return: None \"\"\" while True: results", "\"\"\" await self._event_channel.system.register_for_change_events(value) def close(self): \"\"\" Close the connection to", "self._handle_groups_changed, # 'event/player_state_changed': self._handle_player_state_changed, # 'event/player_now_playing_changed': self._handle_now_playing_changed, # 'event/player_now_playing_progress': self._handle_now_playing_progress,", "the HEOS service. :param username: Username :param password: Password :return:", "as a dict. self._sources: dict = {} # FIXME?: Not", "our HEOS device. :param enable_event_connection: Enables establishing an additional connection", "function to a specific event :param event_name: Event name :param", "def __enter__(self): if not self._connected: self.connect() return self def __exit__(self,", "loop.create_task(self._process_events()) if refresh: await self.refresh() return self async def _set_register_for_change_events(self,", "def _handle_shuffle_mode_changed(self, event: HEOSEvent): raise NotImplementedError() def _handle_group_volume_changed(self, event: HEOSEvent):", "registered callback {callback} for event {event!r}') loop.create_task(callback(event)) def _init_internal_event_handlers(self): \"\"\"", "password: str): \"\"\" Signs the system into the HEOS service.", "_handle_repeat_mode_changed(self, event: HEOSEvent): raise NotImplementedError() def _handle_shuffle_mode_changed(self, event: HEOSEvent): raise", "isinstance(server, SSDPResponse): server = utils.extract_host(server.location) self.server: str = server self.port:", ":return: None \"\"\" await self.check_account() await self.get_players() await self.get_groups() await", "raise ChannelUnavailableError() @property def log_level(self): return logger.level @log_level.setter def log_level(self,", "is None: self._event_subscriptions[event_name] = [] self._event_subscriptions[event_name].append(callback) async def refresh(self): \"\"\"", "NotImplementedError() def _handle_player_state_changed(self, event: HEOSEvent): raise NotImplementedError() def _handle_now_playing_changed(self, event:", "the library \"\"\" from __future__ import annotations import asyncio import", "await self._command_channel.connect(self.server, self.port) self._connected = True self._receive_events = enable_event_connection if", "\"\"\" await self.api.system.sign_in(username, password) async def sign_out(self): \"\"\" Signs out", "from the HEOS service. :return: None \"\"\" await self.api.system.sign_out() async", "HEOS service. :return: None \"\"\" await self.api.system.sign_out() async def get_players(self):", "player in await self.api.player.get_players()] return self._players async def get_group(self, group_id):", "raise NotImplementedError() def _handle_player_state_changed(self, event: HEOSEvent): raise NotImplementedError() def _handle_now_playing_changed(self,", "Connection() self._event_queue = asyncio.Queue() self._event_task: Optional[asyncio.Task] = None self._event_processor: Optional[asyncio.Task]", "1255 @staticmethod def check_channel_availability(channel: Connection): \"\"\" Checks to make sure", "Callback function :return: None \"\"\" # FIXME: Change event_name to", "results = await self._event_channel.read_message() if results: event = HEOSEvent(results) logger.debug(f\"Received", "get_groups(self): \"\"\" Retrieves a mapping of IDs to Groups present", "reception. :param value: True or False :return: None \"\"\" self._receive_events", "I like having this as a dict. self._sources: dict =", "sure that the provided channel is available. :param channel: Channel", "specific group by ID. :param group_id: Group ID :return: PytheosGroup", "establishing an additional connection for system events :param refresh: Determines", "return f'<Pytheos(server={self.server}, port={self.port})>' def __enter__(self): if not self._connected: self.connect() return", "manager for use with the connection. :param host: Host to", "self._connected: bool = False self._event_subscriptions: dict = {} self._receive_events: bool", "having this as a dict. self.api: Connection = self._command_channel self._init_internal_event_handlers()", "port: int=Pytheos.DEFAULT_PORT) -> Pytheos: \"\"\" Connect to the provided host", ":return: None \"\"\" while True: results = await self._event_channel.read_message() if", "self._event_processor: Optional[asyncio.Task] = None self._connected: bool = False self._event_subscriptions: dict", "callback function to a specific event :param event_name: Event name", "async def get_groups(self): \"\"\" Retrieves a mapping of IDs to", "I like having this as a dict. self.api: Connection =", "bool): \"\"\" Notifies HEOS that we want event messages on", "async def refresh(self): \"\"\" Refreshes internal information from the HEOS", "self.check_account() await self.get_players() await self.get_groups() await self.get_sources() async def reboot(self):", "_handle_shuffle_mode_changed(self, event: HEOSEvent): raise NotImplementedError() def _handle_group_volume_changed(self, event: HEOSEvent): raise", "self._sources: dict = {} # FIXME?: Not sure I like", "\"\"\" DEFAULT_PORT = 1255 @staticmethod def check_channel_availability(channel: Connection): \"\"\" Checks", "should be automatically refreshed :return: self \"\"\" logger.info(f'Connecting to {self.server}:{self.port}')", "Meh, do something better with this. internal_handler_map = { #", ":param event: HEOS Event :return: None \"\"\" loop = asyncio.get_running_loop()", "event: HEOSEvent): raise NotImplementedError() def _handle_group_volume_changed(self, event: HEOSEvent): raise NotImplementedError()", "connect(self, enable_event_connection: bool=True, refresh: bool=True) -> Pytheos: \"\"\" Connect to", ":return: \"\"\" self._sources = {} for source in await self.api.browse.get_music_sources():", ":return: None \"\"\" loop = asyncio.get_running_loop() for callback in self._event_subscriptions.get(event.command,", "= loop.create_task(self._process_events()) if refresh: await self.refresh() return self async def", "self._event_channel.connect(self.server, self.port, deduplicate=True) await self.enable_event_reception(True) loop = asyncio.get_running_loop() self._event_task =", "event: HEOSEvent): raise NotImplementedError() def _handle_player_state_changed(self, event: HEOSEvent): raise NotImplementedError()", "async def connect(host: Union[SSDPResponse, str], port: int=Pytheos.DEFAULT_PORT) -> Pytheos: \"\"\"", "automatically refreshed :return: self \"\"\" logger.info(f'Connecting to {self.server}:{self.port}') await self._command_channel.connect(self.server,", "self._account_status, self._account_username async def sign_in(self, username: str, password: str): \"\"\"", "connection for system events :param refresh: Determines if the system", "connection :raises: ChannelUnavailableError :return: None \"\"\" if not channel or", "= Connection() self._event_channel = Connection() self._event_queue = asyncio.Queue() self._event_task: Optional[asyncio.Task]", "controllers.Source(self, source) return self._sources def is_receiving_events(self): \"\"\" Retrieves whether or", "an enum if self._event_subscriptions.get(event_name) is None: self._event_subscriptions[event_name] = [] self._event_subscriptions[event_name].append(callback)", "= None self._connected: bool = False self._event_subscriptions: dict = {}", "None \"\"\" # FIXME: Meh, do something better with this.", "username: str, password: str): \"\"\" Signs the system into the", "self._groups: dict = {} # FIXME?: Not sure I like", "service. :param username: Username :param password: Password :return: None \"\"\"", "value: True or False :return: None \"\"\" self._receive_events = value", "True or False :return: None \"\"\" self._receive_events = value await", "def _process_events(self): \"\"\" Async task that processes events that originate", "\"\"\" self._receive_events = value await self._set_register_for_change_events(value) async def _listen_for_events(self): \"\"\"", "originate from the event channel. :return: None \"\"\" while True:", "while True: event = await self._event_queue.get() if event: logger.debug(f'Processing event:", "raise NotImplementedError() def _handle_groups_changed(self, event: HEOSEvent): raise NotImplementedError() def _handle_player_state_changed(self,", "str): \"\"\" Signs the system into the HEOS service. :param", "HEOS system. :return: list \"\"\" self._players = [controllers.Player(self, player) for", "self._players async def get_group(self, group_id): \"\"\" Retrieve a specific group", "self._receive_events = enable_event_connection if self._receive_events: await self._event_channel.connect(self.server, self.port, deduplicate=True) await", "on the event channel. :param value: True or False :return:", "{callback} for event {event!r}') loop.create_task(callback(event)) def _init_internal_event_handlers(self): \"\"\" Initialize the", "# 'event/player_now_playing_changed': self._handle_now_playing_changed, # 'event/player_now_playing_progress': self._handle_now_playing_progress, # 'event/player_playback_error': self._handle_playback_error, #", "ID :return: PytheosGroup \"\"\" groups = await self.get_groups() return groups.get(group_id)", "list = [] self._groups: dict = {} # FIXME?: Not", "if available. :return: tuple \"\"\" self._account_status, self._account_username = await self.api.system.check_account()", "{} # FIXME?: Not sure I like having this as", "\"\"\" if isinstance(host, SSDPResponse): host = utils.extract_host(host.location) conn = Pytheos(host,", "to connect to :raises: ValueError :return: The Pytheos instance \"\"\"", "'event/groups_changed': self._handle_groups_changed, # 'event/player_state_changed': self._handle_player_state_changed, # 'event/player_now_playing_changed': self._handle_now_playing_changed, # 'event/player_now_playing_progress':", "to {self.server}:{self.port}') await self._command_channel.connect(self.server, self.port) self._connected = True self._receive_events =", "def log_level(self, value): logger.setLevel(value) @property def connected(self): return self._connected @property", "available. :return: tuple \"\"\" self._account_status, self._account_username = await self.api.system.check_account() return", "self._command_channel = Connection() self._event_channel = Connection() self._event_queue = asyncio.Queue() self._event_task:", "self._event_task: Optional[asyncio.Task] = None self._event_processor: Optional[asyncio.Task] = None self._connected: bool", "{} self._receive_events: bool = True self._account_status: Optional[AccountStatus] = None self._account_username:", "subscribe(self, event_name: str, callback: Callable): \"\"\" Subscribe a callback function", "HEOS system. :return: None \"\"\" await self.check_account() await self.get_players() await", "# 'event/sources_changed': self._handle_sources_changed, # 'event/players_changed': self._handle_players_changed, # 'event/groups_changed': self._handle_groups_changed, #", "into the library \"\"\" from __future__ import annotations import asyncio", "server = utils.extract_host(server.location) self.server: str = server self.port: int =", "event: HEOSEvent): raise NotImplementedError() def _handle_playback_error(self, event: HEOSEvent): raise NotImplementedError()", "Callable, Optional, Union from . import utils from . import", "_handle_player_state_changed(self, event: HEOSEvent): raise NotImplementedError() def _handle_now_playing_changed(self, event: HEOSEvent): raise", "event {event!r}') loop.create_task(callback(event)) def _init_internal_event_handlers(self): \"\"\" Initialize the internal event", "ChannelUnavailableError :return: None \"\"\" if not channel or not channel.connected:", "\"\"\" self._account_status, self._account_username = await self.api.system.check_account() return self._account_status, self._account_username async", "sure I like having this as a dict. self.api: Connection", "processing. :return: None \"\"\" while True: results = await self._event_channel.read_message()", "self._init_internal_event_handlers() def __repr__(self): return f'<Pytheos(server={self.server}, port={self.port})>' def __enter__(self): if not", "True or False :return: None \"\"\" await self._event_channel.system.register_for_change_events(value) def close(self):", "that originate from the event channel. :return: None \"\"\" while", "= self._command_channel self._init_internal_event_handlers() def __repr__(self): return f'<Pytheos(server={self.server}, port={self.port})>' def __enter__(self):", "_handle_queue_changed(self, event: HEOSEvent): raise NotImplementedError() def _handle_volume_changed(self, event: HEOSEvent): raise", "\"\"\" Pytheos interface \"\"\" DEFAULT_PORT = 1255 @staticmethod def check_channel_availability(channel:", "state should be automatically refreshed :return: self \"\"\" logger.info(f'Connecting to", "HEOSEvent): raise NotImplementedError() def _handle_players_changed(self, event: HEOSEvent): raise NotImplementedError() def", "Async task that processes events that originate from the event", "def _handle_volume_changed(self, event: HEOSEvent): raise NotImplementedError() def _handle_repeat_mode_changed(self, event: HEOSEvent):", "the status and account name, if available. :return: tuple \"\"\"", "this as a dict. self.api: Connection = self._command_channel self._init_internal_event_handlers() def", "\"\"\" return self._receive_events async def enable_event_reception(self, value): \"\"\" Enables or", "event_name: Event name :param callback: Callback function :return: None \"\"\"", "_init_internal_event_handlers(self): \"\"\" Initialize the internal event handlers :return: None \"\"\"", "port: Port number \"\"\" if isinstance(server, SSDPResponse): server = utils.extract_host(server.location)", "refresh: bool=True) -> Pytheos: \"\"\" Connect to our HEOS device.", "like having this as a dict. self.api: Connection = self._command_channel", "make sure that the provided channel is available. :param channel:", "self._event_channel.system.register_for_change_events(value) def close(self): \"\"\" Close the connection to our HEOS", "self.get_groups() await self.get_sources() async def reboot(self): \"\"\" Instructs the system", "self.get_players() await self.get_groups() await self.get_sources() async def reboot(self): \"\"\" Instructs", "group in await self.api.group.get_groups(): self._groups[group.group_id] = controllers.Group(self, group) return self._groups", "self._handle_volume_changed, # 'event/repeat_mode_changed': self._handle_repeat_mode_changed, # 'event/shuffle_mode_changed': self._handle_shuffle_mode_changed, # 'event/group_volume_changed': self._handle_group_volume_changed,", "# 'event/group_volume_changed': self._handle_group_volume_changed, # 'event/user_changed': self._handle_user_changed, } for event, callback", "\"\"\" await self.api.system.sign_out() async def get_players(self): \"\"\" Retrieves a mapping", "name :param callback: Callback function :return: None \"\"\" # FIXME:", "Enables or disables event reception. :param value: True or False", "self._event_subscriptions: dict = {} self._receive_events: bool = True self._account_status: Optional[AccountStatus]", "that processes events that originate from the event channel. :return:", "from the HEOS system. :return: None \"\"\" await self.check_account() await", "def connect(host: Union[SSDPResponse, str], port: int=Pytheos.DEFAULT_PORT) -> Pytheos: \"\"\" Connect", "events :param refresh: Determines if the system state should be", "_handle_now_playing_changed(self, event: HEOSEvent): raise NotImplementedError() def _handle_now_playing_progress(self, event: HEOSEvent): raise", "None self._players: list = [] self._groups: dict = {} #", "library \"\"\" from __future__ import annotations import asyncio import logging", "self.get_sources() async def reboot(self): \"\"\" Instructs the system to reboot.", "bool=True, refresh: bool=True) -> Pytheos: \"\"\" Connect to our HEOS", "better with this. internal_handler_map = { # 'event/sources_changed': self._handle_sources_changed, #", "raise NotImplementedError() def _handle_shuffle_mode_changed(self, event: HEOSEvent): raise NotImplementedError() def _handle_group_volume_changed(self,", "that we want event messages on the event channel. :param", "with this. internal_handler_map = { # 'event/sources_changed': self._handle_sources_changed, # 'event/players_changed':", "system. :return: None \"\"\" await self.check_account() await self.get_players() await self.get_groups()", "self._groups async def get_sources(self): \"\"\" Retrieves a mapping of IDs", "'event/shuffle_mode_changed': self._handle_shuffle_mode_changed, # 'event/group_volume_changed': self._handle_group_volume_changed, # 'event/user_changed': self._handle_user_changed, } for", "status and account name, if available. :return: tuple \"\"\" self._account_status,", "self._event_queue.put(event) await asyncio.sleep(0.5) async def _process_events(self): \"\"\" Async task that", "the event channel. :param value: True or False :return: None", "self._event_subscriptions[event_name].append(callback) async def refresh(self): \"\"\" Refreshes internal information from the", "to Groups present in the HEOS system. :return: dict \"\"\"", "for player in await self.api.player.get_players()] return self._players async def get_group(self,", "self._event_channel.read_message() if results: event = HEOSEvent(results) logger.debug(f\"Received event: {event!r}\") await", "device. :param enable_event_connection: Enables establishing an additional connection for system", "HEOSEvent from .models.system import AccountStatus logger = logging.getLogger('pytheos') class Pytheos:", "Optional[int]=DEFAULT_PORT): \"\"\" Constructor :param server: Server hostname or IP :param", "Provides the primary interface into the library \"\"\" from __future__", "\"\"\" # FIXME: Change event_name to an enum if self._event_subscriptions.get(event_name)", "event = await self._event_queue.get() if event: logger.debug(f'Processing event: {event!r}') await", "port: Port to connect to :raises: ValueError :return: The Pytheos", "_event_handler(self, event: HEOSEvent): \"\"\" Internal event handler :param event: HEOS", "in await self.api.browse.get_music_sources(): self._sources[source.source_id] = controllers.Source(self, source) return self._sources def", "__exit__(self, exc_type, exc_val, exc_tb): if self._connected: self.close() async def connect(self,", "None \"\"\" await self.check_account() await self.get_players() await self.get_groups() await self.get_sources()", "mapping of IDs to Groups present in the HEOS system.", "@property def username(self): return self._account_username def __init__(self, server: Union[str, SSDPResponse]=None,", "= loop.create_task(self._listen_for_events()) self._event_processor = loop.create_task(self._process_events()) if refresh: await self.refresh() return", "Async task that reads messages from the event channel and", "the HEOS system. :return: \"\"\" self._sources = {} for source", "HEOSEvent): \"\"\" Internal event handler :param event: HEOS Event :return:", "True: event = await self._event_queue.get() if event: logger.debug(f'Processing event: {event!r}')", "internal_handler_map = { # 'event/sources_changed': self._handle_sources_changed, # 'event/players_changed': self._handle_players_changed, #", ".models.heos import HEOSEvent from .models.system import AccountStatus logger = logging.getLogger('pytheos')", "port self._command_channel = Connection() self._event_channel = Connection() self._event_queue = asyncio.Queue()", "controllers.Group(self, group) return self._groups async def get_sources(self): \"\"\" Retrieves a", "Subscribe a callback function to a specific event :param event_name:", "from .networking.errors import ChannelUnavailableError from .models.heos import HEOSEvent from .models.system", "self._handle_now_playing_changed, # 'event/player_now_playing_progress': self._handle_now_playing_progress, # 'event/player_playback_error': self._handle_playback_error, # 'event/player_queue_changed': self._handle_queue_changed,", "a specific event :param event_name: Event name :param callback: Callback", "callback: Callable): \"\"\" Subscribe a callback function to a specific", "# 'event/players_changed': self._handle_players_changed, # 'event/groups_changed': self._handle_groups_changed, # 'event/player_state_changed': self._handle_player_state_changed, #", "Union from . import utils from . import controllers from", "information from the HEOS system. :return: None \"\"\" await self.check_account()", "to the provided host and return a context manager for", "to an enum if self._event_subscriptions.get(event_name) is None: self._event_subscriptions[event_name] = []", "await self.api.system.check_account() return self._account_status, self._account_username async def sign_in(self, username: str,", ":return: None \"\"\" await self.api.system.sign_out() async def get_players(self): \"\"\" Retrieves", "group_id: Group ID :return: PytheosGroup \"\"\" groups = await self.get_groups()", "not self._connected: self.connect() return self def __exit__(self, exc_type, exc_val, exc_tb):", "await self.api.player.get_players()] return self._players async def get_group(self, group_id): \"\"\" Retrieve", "value await self._set_register_for_change_events(value) async def _listen_for_events(self): \"\"\" Async task that", "them to our event queue for later processing. :return: None", "# 'event/user_changed': self._handle_user_changed, } for event, callback in internal_handler_map.items(): self.subscribe(event,", "async def _listen_for_events(self): \"\"\" Async task that reads messages from", "the internal event handlers :return: None \"\"\" # FIXME: Meh,", "the HEOS system. :return: None \"\"\" await self.check_account() await self.get_players()", ":param event_name: Event name :param callback: Callback function :return: None", "processes events that originate from the event channel. :return: None", "def check_channel_availability(channel: Connection): \"\"\" Checks to make sure that the", "Server hostname or IP :param port: Port number \"\"\" if", "HEOSEvent): raise NotImplementedError() def _handle_queue_changed(self, event: HEOSEvent): raise NotImplementedError() def", "number \"\"\" if isinstance(server, SSDPResponse): server = utils.extract_host(server.location) self.server: str", "def _handle_now_playing_changed(self, event: HEOSEvent): raise NotImplementedError() def _handle_now_playing_progress(self, event: HEOSEvent):", "Retrieve a specific group by ID. :param group_id: Group ID", "logger.debug(f'Calling registered callback {callback} for event {event!r}') loop.create_task(callback(event)) def _init_internal_event_handlers(self):", "SSDPResponse]=None, port: Optional[int]=DEFAULT_PORT): \"\"\" Constructor :param server: Server hostname or", "\"\"\" Signs out from the HEOS service. :return: None \"\"\"", "{event!r}') await self._event_handler(event) await asyncio.sleep(0.5) async def _event_handler(self, event: HEOSEvent):", "interface \"\"\" DEFAULT_PORT = 1255 @staticmethod def check_channel_availability(channel: Connection): \"\"\"", "self._set_register_for_change_events(value) async def _listen_for_events(self): \"\"\" Async task that reads messages", "Notifies HEOS that we want event messages on the event", "== AccountStatus.SignedIn @property def username(self): return self._account_username def __init__(self, server:", "if event: logger.debug(f'Processing event: {event!r}') await self._event_handler(event) await asyncio.sleep(0.5) async", "self._sources def is_receiving_events(self): \"\"\" Retrieves whether or not we're receiving", "# 'event/player_volume_changed': self._handle_volume_changed, # 'event/repeat_mode_changed': self._handle_repeat_mode_changed, # 'event/shuffle_mode_changed': self._handle_shuffle_mode_changed, #", "the HEOS service. :return: None \"\"\" await self.api.system.sign_out() async def", "server: Server hostname or IP :param port: Port number \"\"\"", "in internal_handler_map.items(): self.subscribe(event, callback) def _handle_sources_changed(self, event: HEOSEvent): raise NotImplementedError()", "self.port, deduplicate=True) await self.enable_event_reception(True) loop = asyncio.get_running_loop() self._event_task = loop.create_task(self._listen_for_events())", "connection to {self.server}:{self.port}') if self._event_task: self._event_task.cancel() if self._event_processor: self._event_processor.cancel() self._connected", "from typing import Callable, Optional, Union from . import utils", "def connected(self): return self._connected @property def signed_in(self): return self._account_status ==", "f'<Pytheos(server={self.server}, port={self.port})>' def __enter__(self): if not self._connected: self.connect() return self", "int = port self._command_channel = Connection() self._event_channel = Connection() self._event_queue", "exc_tb): if self._connected: self.close() async def connect(self, enable_event_connection: bool=True, refresh:", "HEOSEvent): raise NotImplementedError() def _handle_now_playing_progress(self, event: HEOSEvent): raise NotImplementedError() def", "refresh: await self.refresh() return self async def _set_register_for_change_events(self, value: bool):", "self._event_subscriptions[event_name] = [] self._event_subscriptions[event_name].append(callback) async def refresh(self): \"\"\" Refreshes internal", "import ChannelUnavailableError from .models.heos import HEOSEvent from .models.system import AccountStatus", "present in the HEOS system. :return: list \"\"\" self._players =", ".networking.connection import Connection from .networking.types import SSDPResponse from .networking.errors import", "HEOSEvent): raise NotImplementedError() def _handle_now_playing_changed(self, event: HEOSEvent): raise NotImplementedError() def", "loop.create_task(callback(event)) def _init_internal_event_handlers(self): \"\"\" Initialize the internal event handlers :return:", "= {} self._receive_events: bool = True self._account_status: Optional[AccountStatus] = None", "async def _set_register_for_change_events(self, value: bool): \"\"\" Notifies HEOS that we", "log_level(self): return logger.level @log_level.setter def log_level(self, value): logger.setLevel(value) @property def", "_handle_group_volume_changed(self, event: HEOSEvent): raise NotImplementedError() def _handle_user_changed(self, event: HEOSEvent): raise", "username(self): return self._account_username def __init__(self, server: Union[str, SSDPResponse]=None, port: Optional[int]=DEFAULT_PORT):", "'event/player_now_playing_changed': self._handle_now_playing_changed, # 'event/player_now_playing_progress': self._handle_now_playing_progress, # 'event/player_playback_error': self._handle_playback_error, # 'event/player_queue_changed':", ".models.system import AccountStatus logger = logging.getLogger('pytheos') class Pytheos: \"\"\" Pytheos", "or not channel.connected: raise ChannelUnavailableError() @property def log_level(self): return logger.level", "like having this as a dict. self._sources: dict = {}", "str, callback: Callable): \"\"\" Subscribe a callback function to a", "port: Optional[int]=DEFAULT_PORT): \"\"\" Constructor :param server: Server hostname or IP", "Pytheos: \"\"\" Pytheos interface \"\"\" DEFAULT_PORT = 1255 @staticmethod def", "internal information from the HEOS system. :return: None \"\"\" await", "Port to connect to :raises: ValueError :return: The Pytheos instance", "dict \"\"\" self._groups = {} for group in await self.api.group.get_groups():", "{} for group in await self.api.group.get_groups(): self._groups[group.group_id] = controllers.Group(self, group)", "self._groups = {} for group in await self.api.group.get_groups(): self._groups[group.group_id] =", "None \"\"\" await self.api.system.reboot() async def check_account(self) -> tuple: \"\"\"", "reboot. :return: None \"\"\" await self.api.system.reboot() async def check_account(self) ->", "asyncio.sleep(0.5) async def _event_handler(self, event: HEOSEvent): \"\"\" Internal event handler", "IDs to Sources present in the HEOS system. :return: \"\"\"" ]
[ "{} for _row in _iso_639_1_codes_dictreader: _iso_639_1_codes_dict[_row['ISO-639-1 Code']] = _row['Language'] print(str(_iso_639_1_codes_dict))", "import csv _iso_639_1_codes_file = open(\"files/ISO-639-1_Codes.csv\", mode='r') _iso_639_1_codes_dictreader = csv.DictReader(_iso_639_1_codes_file) _iso_639_1_codes_dict:", "_iso_639_1_codes_dictreader = csv.DictReader(_iso_639_1_codes_file) _iso_639_1_codes_dict: dict = {} for _row in", "csv.DictReader(_iso_639_1_codes_file) _iso_639_1_codes_dict: dict = {} for _row in _iso_639_1_codes_dictreader: _iso_639_1_codes_dict[_row['ISO-639-1", "= csv.DictReader(_iso_639_1_codes_file) _iso_639_1_codes_dict: dict = {} for _row in _iso_639_1_codes_dictreader:", "_iso_639_1_codes_dict: dict = {} for _row in _iso_639_1_codes_dictreader: _iso_639_1_codes_dict[_row['ISO-639-1 Code']]", "<gh_stars>1-10 import csv _iso_639_1_codes_file = open(\"files/ISO-639-1_Codes.csv\", mode='r') _iso_639_1_codes_dictreader = csv.DictReader(_iso_639_1_codes_file)", "csv _iso_639_1_codes_file = open(\"files/ISO-639-1_Codes.csv\", mode='r') _iso_639_1_codes_dictreader = csv.DictReader(_iso_639_1_codes_file) _iso_639_1_codes_dict: dict", "= open(\"files/ISO-639-1_Codes.csv\", mode='r') _iso_639_1_codes_dictreader = csv.DictReader(_iso_639_1_codes_file) _iso_639_1_codes_dict: dict = {}", "_iso_639_1_codes_file = open(\"files/ISO-639-1_Codes.csv\", mode='r') _iso_639_1_codes_dictreader = csv.DictReader(_iso_639_1_codes_file) _iso_639_1_codes_dict: dict =", "open(\"files/ISO-639-1_Codes.csv\", mode='r') _iso_639_1_codes_dictreader = csv.DictReader(_iso_639_1_codes_file) _iso_639_1_codes_dict: dict = {} for", "mode='r') _iso_639_1_codes_dictreader = csv.DictReader(_iso_639_1_codes_file) _iso_639_1_codes_dict: dict = {} for _row", "= {} for _row in _iso_639_1_codes_dictreader: _iso_639_1_codes_dict[_row['ISO-639-1 Code']] = _row['Language']", "dict = {} for _row in _iso_639_1_codes_dictreader: _iso_639_1_codes_dict[_row['ISO-639-1 Code']] =" ]
[ "= 0, 0 if self._cached_buf: self._cached_buf[i].reset() if isinstance(self.state, list): self.state[i]", "self.collect_episode = 0 self.collect_time = 0 if buffer is None:", "1 reward_sum += self.reward length_sum += self.length self.reward, self.length =", "self.reward[i] length_sum += self.length[i] if self._cached_buf: cur_step += len(self._cached_buf[i]) self.buffer.update(self._cached_buf[i])", "close(self): if hasattr(self.env, 'close'): self.env.close() def _make_batch(self, data): if isinstance(data,", "self._act = result.act.detach().cpu().numpy() elif not isinstance(self._act, np.ndarray): self._act = np.array(result.act)", "over batch is either a list, an np.ndarray, or a", "if isinstance(self.state, list): self.state[i] = None elif self.state is not", "batch_size, p=np.array(lens) / total) else: batch_index = np.array([]) batch_data =", "batch is either a list, an np.ndarray, or a torch.Tensor", "True: if warning_count >= 100000: warnings.warn( 'There are already many", "np.array(result.act) else: self._act = result.act obs_next, self._rew, self._done, self._info =", "BaseVectorEnv from tianshou.data import Batch, ReplayBuffer,\\ ListReplayBuffer from tianshou.utils import", "100000: warnings.warn( 'There are already many steps in an episode.", "self.buffer.add(**data) cur_step += 1 if self._done[i]: if n_step != 0", "p=np.array(lens) / total) else: batch_index = np.array([]) batch_data = Batch()", "data = { 'obs': self._obs[i], 'act': self._act[i], 'rew': self._rew[i], 'done':", "cur_batch = (batch_index == i).sum() if batch_size and cur_batch or", "buffer is None: self.buffer = ReplayBuffer(100) else: self.buffer = buffer", "total, batch_size, p=np.array(lens) / total) else: batch_index = np.array([]) batch_data", "pytorch (?) self.state = self.state.detach() if sum(self._done): obs_next = self.env.reset(np.where(self._done)[0])", ">= n_episode: break if n_step != 0 and cur_step >=", "cur_episode = np.zeros(self.env_num) if self._multi_env else 0 reward_sum = 0", "n_step: break self._obs = obs_next self._obs = obs_next if self._multi_env:", "raise TypeError('The buffer in data collector is invalid!') self.reset_env() self.reset_buffer()", "len(self.buffer) == self.env_num, \\ 'The number of data buffer does", "self.reset_buffer() # state over batch is either a list, an", "a list, an np.ndarray, or a torch.Tensor self.state = None", "cur_episode = sum(cur_episode) duration = time.time() - start_time self.step_speed.add(cur_step /", "elif not isinstance(self._act, np.ndarray): self._act = np.array(result.act) else: self._act =", "isinstance(data, np.ndarray): return data[None] else: return np.array([data]) def collect(self, n_step=0,", "Warning) if self._multi_env: batch_data = Batch( obs=self._obs, act=self._act, rew=self._rew, done=self._done,", "elif self.state is not None: if isinstance(self.state[i], dict): self.state[i] =", "an np.ndarray, or a torch.Tensor self.state = None self.step_speed =", "np from tianshou.env import BaseVectorEnv from tianshou.data import Batch, ReplayBuffer,\\", "elif isinstance(self.buffer, ReplayBuffer): self._cached_buf = [ ListReplayBuffer() for _ in", "+= self.reward[i] length_sum += self.length[i] if self._cached_buf: cur_step += len(self._cached_buf[i])", "batch_data = Batch( obs=self._make_batch(self._obs), act=self._make_batch(self._act), rew=self._make_batch(self._rew), done=self._make_batch(self._done), obs_next=None, info=self._make_batch(self._info)) result", "obs_next = self.env.reset(np.where(self._done)[0]) if n_episode != 0: if isinstance(n_episode, list)", "self.collect_step = 0 self.collect_episode = 0 self.collect_time = 0 if", "import Batch, ReplayBuffer,\\ ListReplayBuffer from tianshou.utils import MovAvg class Collector(object):", "ListReplayBuffer() for _ in range(self.env_num)] else: raise TypeError('The buffer in", "'You should add a time limitation to your environment!', Warning)", "assert sum([(n_step != 0), (n_episode != 0)]) == 1, \\", "n_episode != 0 and cur_episode >= n_episode: break if n_step", "= True elif isinstance(self.buffer, ReplayBuffer): self._cached_buf = [ ListReplayBuffer() for", "isinstance(result.act, torch.Tensor): self._act = result.act.detach().cpu().numpy() elif not isinstance(self._act, np.ndarray): self._act", "self.state.detach() if sum(self._done): obs_next = self.env.reset(np.where(self._done)[0]) if n_episode != 0:", "\\ (cur_episode >= np.array(n_episode)).all() or \\ np.isscalar(n_episode) and \\ cur_episode.sum()", "while True: if warning_count >= 100000: warnings.warn( 'There are already", "np.ndarray, or a torch.Tensor self.state = None self.step_speed = MovAvg(stat_size)", "isinstance(self.buffer, list): assert len(self.buffer) == self.env_num, \\ 'The number of", "tianshou.utils import MovAvg class Collector(object): \"\"\"docstring for Collector\"\"\" def __init__(self,", "'close'): self.env.close() def _make_batch(self, data): if isinstance(data, np.ndarray): return data[None]", "Batch, ReplayBuffer,\\ ListReplayBuffer from tianshou.utils import MovAvg class Collector(object): \"\"\"docstring", "list) and \\ (cur_episode >= np.array(n_episode)).all() or \\ np.isscalar(n_episode) and", "self.buffer.reset() def get_env_num(self): return self.env_num def reset_env(self): self._obs = self.env.reset()", "hasattr(self.env, 'render'): return self.env.render(**kwargs) def close(self): if hasattr(self.env, 'close'): self.env.close()", "in an episode. ' 'You should add a time limitation", "'v/ep': self.episode_speed.get(), 'rew': reward_sum / n_episode, 'len': length_sum / n_episode,", "policy.process_fn self._multi_env = isinstance(env, BaseVectorEnv) self._multi_buf = False # True", "for i, b in enumerate(self.buffer): cur_batch = (batch_index == i).sum()", "self._cached_buf = [ ListReplayBuffer() for _ in range(self.env_num)] else: raise", "self._rew[i], 'done': self._done[i], 'obs_next': obs_next[i], 'info': self._info[i]} if self._cached_buf: warning_count", "/ duration) self.collect_step += cur_step self.collect_episode += cur_episode self.collect_time +=", "self.env.reset() self._act = self._rew = self._done = self._info = None", "if buffer is None: self.buffer = ReplayBuffer(100) else: self.buffer =", "time.time() - start_time self.step_speed.add(cur_step / duration) self.episode_speed.add(cur_episode / duration) self.collect_step", "= buffer self.policy = policy self.process_fn = policy.process_fn self._multi_env =", "list): self.state[i] = None elif self.state is not None: if", "self.collect_episode += cur_episode self.collect_time += duration if isinstance(n_episode, list): n_episode", "self.reward length_sum += self.length self.reward, self.length = 0, 0 self.state", "self.env.seed(seed) def render(self, **kwargs): if hasattr(self.env, 'render'): return self.env.render(**kwargs) def", "BaseVectorEnv) self._multi_buf = False # True if buf is a", "n_episode = np.sum(n_episode) start_time = time.time() assert sum([(n_step != 0),", "list): assert len(self.buffer) == self.env_num, \\ 'The number of data", "should add a time limitation to your environment!', Warning) if", "from tianshou.env import BaseVectorEnv from tianshou.data import Batch, ReplayBuffer,\\ ListReplayBuffer", "self._info[i]} if self._cached_buf: warning_count += 1 self._cached_buf[i].add(**data) elif self._multi_buf: warning_count", "self._cached_buf[i].add(**data) elif self._multi_buf: warning_count += 1 self.buffer[i].add(**data) cur_step += 1", "= (batch_index == i).sum() if batch_size and cur_batch or batch_size", "cur_step += 1 else: warning_count += 1 self.buffer.add(**data) cur_step +=", "collector is invalid!') self.reset_env() self.reset_buffer() # state over batch is", "warning_count = 0 if not self._multi_env: n_episode = np.sum(n_episode) start_time", "_make_batch(self, data): if isinstance(data, np.ndarray): return data[None] else: return np.array([data])", "'input env.' self._multi_buf = True elif isinstance(self.buffer, ReplayBuffer): self._cached_buf =", "total = sum(lens) batch_index = np.random.choice( total, batch_size, p=np.array(lens) /", "hasattr(self.env, 'seed'): return self.env.seed(seed) def render(self, **kwargs): if hasattr(self.env, 'render'):", "' \\ 'input env.' self._multi_buf = True elif isinstance(self.buffer, ReplayBuffer):", "invalid!') self.reset_env() self.reset_buffer() # state over batch is either a", "obs_next self._obs = obs_next if self._multi_env: cur_episode = sum(cur_episode) duration", "'rew': self._rew[i], 'done': self._done[i], 'obs_next': obs_next[i], 'info': self._info[i]} if self._cached_buf:", "self._info = None if self._multi_env: self.reward = np.zeros(self.env_num) self.length =", "and cur_step >= n_step: break self._obs = obs_next self._obs =", "= 0 cur_episode = np.zeros(self.env_num) if self._multi_env else 0 reward_sum", "self.state[i] * 0 if isinstance(self.state, torch.Tensor): # remove ref count", "match the number of ' \\ 'input env.' self._multi_buf =", "batch, indice = b.sample(cur_batch) batch = self.process_fn(batch, b, indice) batch_data.append(batch)", "batch_index = np.random.choice( total, batch_size, p=np.array(lens) / total) else: batch_index", "self._multi_env: cur_episode = sum(cur_episode) duration = time.time() - start_time self.step_speed.add(cur_step", "1 self.reward += self._rew if self._multi_env: for i in range(self.env_num):", "+= 1 self.buffer[i].add(**data) cur_step += 1 else: warning_count += 1", "def reset_env(self): self._obs = self.env.reset() self._act = self._rew = self._done", "limitation to your environment!', Warning) if self._multi_env: batch_data = Batch(", "is None: self.buffer = ReplayBuffer(100) else: self.buffer = buffer self.policy", "np.ndarray): return data[None] else: return np.array([data]) def collect(self, n_step=0, n_episode=0,", "Batch( obs=self._obs, act=self._act, rew=self._rew, done=self._done, obs_next=None, info=self._info) else: batch_data =", "i in range(self.env_num): data = { 'obs': self._obs[i], 'act': self._act[i],", "'len': length_sum / n_episode, } def sample(self, batch_size): if self._multi_buf:", "= sum(lens) batch_index = np.random.choice( total, batch_size, p=np.array(lens) / total)", "= self.env.reset() self._act = self._rew = self._done = self._info =", "already many steps in an episode. ' 'You should add", "= None self.step_speed = MovAvg(stat_size) self.episode_speed = MovAvg(stat_size) def reset_buffer(self):", "if self._done: cur_episode += 1 reward_sum += self.reward length_sum +=", "self.length self.reward, self.length = 0, 0 self.state = None obs_next", "self._multi_buf: warning_count += 1 self.buffer[i].add(**data) cur_step += 1 else: warning_count", "\\ cur_episode.sum() >= n_episode: break else: self.buffer.add( self._obs, self._act[0], self._rew,", "in pytorch (?) self.state = self.state.detach() if sum(self._done): obs_next =", "n_episode != 0: if isinstance(n_episode, list) and \\ (cur_episode >=", "info=self._info) else: batch_data = Batch( obs=self._make_batch(self._obs), act=self._make_batch(self._act), rew=self._make_batch(self._rew), done=self._make_batch(self._done), obs_next=None,", "0 cur_episode = np.zeros(self.env_num) if self._multi_env else 0 reward_sum =", "+= 1 self.buffer.add(**data) cur_step += 1 if self._done[i]: if n_step", "cur_episode.sum() >= n_episode: break else: self.buffer.add( self._obs, self._act[0], self._rew, self._done,", "get_env_num(self): return self.env_num def reset_env(self): self._obs = self.env.reset() self._act =", "= np.sum(n_episode) else: n_episode = max(cur_episode, 1) return { 'n/ep':", "time import torch import warnings import numpy as np from", "not match the number of ' \\ 'input env.' self._multi_buf", "self._multi_env: self.reward = np.zeros(self.env_num) self.length = np.zeros(self.env_num) else: self.reward, self.length", "b in enumerate(self.buffer): cur_batch = (batch_index == i).sum() if batch_size", "self._done, self._info = self.env.step( self._act if self._multi_env else self._act[0]) if", "= np.random.choice( total, batch_size, p=np.array(lens) / total) else: batch_index =", "number of data buffer does not match the number of", "(?) self.state = self.state.detach() if sum(self._done): obs_next = self.env.reset(np.where(self._done)[0]) if", "dict): self.state[i] = {} else: self.state[i] = self.state[i] * 0", "only one collection number specification permitted!\" cur_step = 0 cur_episode", "ReplayBuffer,\\ ListReplayBuffer from tianshou.utils import MovAvg class Collector(object): \"\"\"docstring for", "are already many steps in an episode. ' 'You should", "self.reward += self._rew if self._multi_env: for i in range(self.env_num): data", "if isinstance(self.state, torch.Tensor): # remove ref count in pytorch (?)", "+= cur_step self.collect_episode += cur_episode self.collect_time += duration if isinstance(n_episode,", "an episode. ' 'You should add a time limitation to", "if isinstance(result.act, torch.Tensor): self._act = result.act.detach().cpu().numpy() elif not isinstance(self._act, np.ndarray):", "for Collector\"\"\" def __init__(self, policy, env, buffer=None, stat_size=100): super().__init__() self.env", "result.state if hasattr(result, 'state') else None if isinstance(result.act, torch.Tensor): self._act", "one buffer self._cached_buf = [] if self._multi_env: self.env_num = len(env)", "= self._info = None if self._multi_env: self.reward = np.zeros(self.env_num) self.length", "self._cached_buf: warning_count += 1 self._cached_buf[i].add(**data) elif self._multi_buf: warning_count += 1", "self.process_fn = policy.process_fn self._multi_env = isinstance(env, BaseVectorEnv) self._multi_buf = False", "reset_env(self): self._obs = self.env.reset() self._act = self._rew = self._done =", "Batch( obs=self._make_batch(self._obs), act=self._make_batch(self._act), rew=self._make_batch(self._rew), done=self._make_batch(self._done), obs_next=None, info=self._make_batch(self._info)) result = self.policy(batch_data,", "isinstance(self._act, np.ndarray): self._act = np.array(result.act) else: self._act = result.act obs_next,", "<= 0: batch, indice = b.sample(cur_batch) batch = self.process_fn(batch, b,", "state over batch is either a list, an np.ndarray, or", "self._obs = self.env.reset() self._act = self._rew = self._done = self._info", "and \\ (cur_episode >= np.array(n_episode)).all() or \\ np.isscalar(n_episode) and \\", "def seed(self, seed=None): if hasattr(self.env, 'seed'): return self.env.seed(seed) def render(self,", "= 1 self.collect_step = 0 self.collect_episode = 0 self.collect_time =", "self._multi_buf: for b in self.buffer: b.reset() else: self.buffer.reset() def get_env_num(self):", "tianshou.data import Batch, ReplayBuffer,\\ ListReplayBuffer from tianshou.utils import MovAvg class", "MovAvg class Collector(object): \"\"\"docstring for Collector\"\"\" def __init__(self, policy, env,", "reward_sum / n_episode, 'len': length_sum / n_episode, } def sample(self,", "0 if not self._multi_env: n_episode = np.sum(n_episode) start_time = time.time()", "0 reward_sum = 0 length_sum = 0 while True: if", "break else: self.buffer.add( self._obs, self._act[0], self._rew, self._done, obs_next, self._info) cur_step", "self.env_num, \\ 'The number of data buffer does not match", "cur_episode self.collect_time += duration if isinstance(n_episode, list): n_episode = np.sum(n_episode)", "isinstance(n_episode, list): n_episode = np.sum(n_episode) else: n_episode = max(cur_episode, 1)", "# need multiple cache buffers only if storing in one", "obs_next, self._info) cur_step += 1 if self._done: cur_episode += 1", "= np.zeros(self.env_num) if self._multi_env else 0 reward_sum = 0 length_sum", "batch = self.process_fn(batch, b, indice) batch_data.append(batch) else: batch_data, indice =", "cur_episode[i] < n_episode[i]: cur_episode[i] += 1 reward_sum += self.reward[i] length_sum", "not None: if isinstance(self.state[i], dict): self.state[i] = {} else: self.state[i]", "self._rew if self._multi_env: for i in range(self.env_num): data = {", "self.length = np.zeros(self.env_num) else: self.reward, self.length = 0, 0 for", "cur_batch or batch_size <= 0: batch, indice = b.sample(cur_batch) batch", "self.length = 0, 0 for b in self._cached_buf: b.reset() def", "= policy.process_fn self._multi_env = isinstance(env, BaseVectorEnv) self._multi_buf = False #", "self.buffer.add( self._obs, self._act[0], self._rew, self._done, obs_next, self._info) cur_step += 1", "isinstance(n_episode, list) and \\ (cur_episode >= np.array(n_episode)).all() or \\ np.isscalar(n_episode)", "= len(env) if isinstance(self.buffer, list): assert len(self.buffer) == self.env_num, \\", "your environment!', Warning) if self._multi_env: batch_data = Batch( obs=self._obs, act=self._act,", "self.collect_time = 0 if buffer is None: self.buffer = ReplayBuffer(100)", "not isinstance(self._act, np.ndarray): self._act = np.array(result.act) else: self._act = result.act", "enumerate(self.buffer): cur_batch = (batch_index == i).sum() if batch_size and cur_batch", "warning_count += 1 self.buffer.add(**data) cur_step += 1 if self._done[i]: if", "batch_size > 0: lens = [len(b) for b in self.buffer]", "self._info = self.env.step( self._act if self._multi_env else self._act[0]) if render", "self.env_num def reset_env(self): self._obs = self.env.reset() self._act = self._rew =", "= Batch() for i, b in enumerate(self.buffer): cur_batch = (batch_index", "self._act[i], 'rew': self._rew[i], 'done': self._done[i], 'obs_next': obs_next[i], 'info': self._info[i]} if", "buffer self.policy = policy self.process_fn = policy.process_fn self._multi_env = isinstance(env,", "in data collector is invalid!') self.reset_env() self.reset_buffer() # state over", "n_step=0, n_episode=0, render=0): warning_count = 0 if not self._multi_env: n_episode", "indice = b.sample(cur_batch) batch = self.process_fn(batch, b, indice) batch_data.append(batch) else:", "cur_episode >= n_episode: break if n_step != 0 and cur_step", "np.zeros(self.env_num) if self._multi_env else 0 reward_sum = 0 length_sum =", "= 0 while True: if warning_count >= 100000: warnings.warn( 'There", "self._done[i], 'obs_next': obs_next[i], 'info': self._info[i]} if self._cached_buf: warning_count += 1", "self.length[i] = 0, 0 if self._cached_buf: self._cached_buf[i].reset() if isinstance(self.state, list):", "cur_step, 'v/st': self.step_speed.get(), 'v/ep': self.episode_speed.get(), 'rew': reward_sum / n_episode, 'len':", "None if isinstance(result.act, torch.Tensor): self._act = result.act.detach().cpu().numpy() elif not isinstance(self._act,", "else: n_episode = max(cur_episode, 1) return { 'n/ep': cur_episode, 'n/st':", "\\ 'The number of data buffer does not match the", "= None if self._multi_env: self.reward = np.zeros(self.env_num) self.length = np.zeros(self.env_num)", "data): if isinstance(data, np.ndarray): return data[None] else: return np.array([data]) def", "True if buf is a list # need multiple cache", "ReplayBuffer(100) else: self.buffer = buffer self.policy = policy self.process_fn =", "import numpy as np from tianshou.env import BaseVectorEnv from tianshou.data", "= time.time() assert sum([(n_step != 0), (n_episode != 0)]) ==", "0 while True: if warning_count >= 100000: warnings.warn( 'There are", "if self._cached_buf: self._cached_buf[i].reset() if isinstance(self.state, list): self.state[i] = None elif", "break if n_step != 0 and cur_step >= n_step: break", "'obs': self._obs[i], 'act': self._act[i], 'rew': self._rew[i], 'done': self._done[i], 'obs_next': obs_next[i],", "{ 'n/ep': cur_episode, 'n/st': cur_step, 'v/st': self.step_speed.get(), 'v/ep': self.episode_speed.get(), 'rew':", "(batch_index == i).sum() if batch_size and cur_batch or batch_size <=", "self.state[i] = None elif self.state is not None: if isinstance(self.state[i],", "else: batch_index = np.array([]) batch_data = Batch() for i, b", "' 'You should add a time limitation to your environment!',", "self.env.reset(np.where(self._done)[0]) if n_episode != 0: if isinstance(n_episode, list) and \\", "!= 0 and cur_episode >= n_episode: break if n_step !=", "self.env_num = len(env) if isinstance(self.buffer, list): assert len(self.buffer) == self.env_num,", "self.state[i] = {} else: self.state[i] = self.state[i] * 0 if", "of data buffer does not match the number of '", "None if self._multi_env: self.reward = np.zeros(self.env_num) self.length = np.zeros(self.env_num) else:", "< n_episode[i]: cur_episode[i] += 1 reward_sum += self.reward[i] length_sum +=", "0 if buffer is None: self.buffer = ReplayBuffer(100) else: self.buffer", "one collection number specification permitted!\" cur_step = 0 cur_episode =", "n_episode: break else: self.buffer.add( self._obs, self._act[0], self._rew, self._done, obs_next, self._info)", "'There are already many steps in an episode. ' 'You", "+= self.length[i] if self._cached_buf: cur_step += len(self._cached_buf[i]) self.buffer.update(self._cached_buf[i]) self.reward[i], self.length[i]", "env self.env_num = 1 self.collect_step = 0 self.collect_episode = 0", "else: self.reward, self.length = 0, 0 for b in self._cached_buf:", "'n/ep': cur_episode, 'n/st': cur_step, 'v/st': self.step_speed.get(), 'v/ep': self.episode_speed.get(), 'rew': reward_sum", "self.step_speed = MovAvg(stat_size) self.episode_speed = MovAvg(stat_size) def reset_buffer(self): if self._multi_buf:", "for _ in range(self.env_num)] else: raise TypeError('The buffer in data", "is invalid!') self.reset_env() self.reset_buffer() # state over batch is either", "obs_next[i], 'info': self._info[i]} if self._cached_buf: warning_count += 1 self._cached_buf[i].add(**data) elif", "Collector(object): \"\"\"docstring for Collector\"\"\" def __init__(self, policy, env, buffer=None, stat_size=100):", "0 self.collect_episode = 0 self.collect_time = 0 if buffer is", "cur_episode[i] += 1 reward_sum += self.reward[i] length_sum += self.length[i] if", "= self._rew = self._done = self._info = None if self._multi_env:", "if n_step != 0 and cur_step >= n_step: break self._obs", "= False # True if buf is a list #", "np.sum(n_episode) start_time = time.time() assert sum([(n_step != 0), (n_episode !=", "else self._act[0]) if render > 0: self.env.render() time.sleep(render) self.length +=", "np.ndarray): self._act = np.array(result.act) else: self._act = result.act obs_next, self._rew,", "warning_count += 1 self.buffer[i].add(**data) cur_step += 1 else: warning_count +=", "self.state = self.state.detach() if sum(self._done): obs_next = self.env.reset(np.where(self._done)[0]) if n_episode", "+= 1 reward_sum += self.reward length_sum += self.length self.reward, self.length", "batch_index = np.array([]) batch_data = Batch() for i, b in", "cur_step += 1 if self._done[i]: if n_step != 0 or", "self.reward, self.length = 0, 0 for b in self._cached_buf: b.reset()", "cur_step >= n_step: break self._obs = obs_next self._obs = obs_next", "if isinstance(data, np.ndarray): return data[None] else: return np.array([data]) def collect(self,", "0 and cur_episode >= n_episode: break if n_step != 0", "if render > 0: self.env.render() time.sleep(render) self.length += 1 self.reward", "+= 1 else: warning_count += 1 self.buffer.add(**data) cur_step += 1", "or np.isscalar(n_episode) or \\ cur_episode[i] < n_episode[i]: cur_episode[i] += 1", "= obs_next self._obs = obs_next if self._multi_env: cur_episode = sum(cur_episode)", "/ n_episode, } def sample(self, batch_size): if self._multi_buf: if batch_size", "np.random.choice( total, batch_size, p=np.array(lens) / total) else: batch_index = np.array([])", "policy, env, buffer=None, stat_size=100): super().__init__() self.env = env self.env_num =", "self._act[0], self._rew, self._done, obs_next, self._info) cur_step += 1 if self._done:", "b, indice) batch_data.append(batch) else: batch_data, indice = self.buffer.sample(batch_size) batch_data =", "np.array([data]) def collect(self, n_step=0, n_episode=0, render=0): warning_count = 0 if", "def get_env_num(self): return self.env_num def reset_env(self): self._obs = self.env.reset() self._act", "import MovAvg class Collector(object): \"\"\"docstring for Collector\"\"\" def __init__(self, policy,", "if self._cached_buf: warning_count += 1 self._cached_buf[i].add(**data) elif self._multi_buf: warning_count +=", "> 0: self.env.render() time.sleep(render) self.length += 1 self.reward += self._rew", "\\ cur_episode[i] < n_episode[i]: cur_episode[i] += 1 reward_sum += self.reward[i]", "as np from tianshou.env import BaseVectorEnv from tianshou.data import Batch,", "= MovAvg(stat_size) def reset_buffer(self): if self._multi_buf: for b in self.buffer:", "self.state = None self.step_speed = MovAvg(stat_size) self.episode_speed = MovAvg(stat_size) def", "b.reset() else: self.buffer.reset() def get_env_num(self): return self.env_num def reset_env(self): self._obs", "'act': self._act[i], 'rew': self._rew[i], 'done': self._done[i], 'obs_next': obs_next[i], 'info': self._info[i]}", "in enumerate(self.buffer): cur_batch = (batch_index == i).sum() if batch_size and", "if hasattr(self.env, 'render'): return self.env.render(**kwargs) def close(self): if hasattr(self.env, 'close'):", "self._multi_env: for i in range(self.env_num): data = { 'obs': self._obs[i],", "self._cached_buf: self._cached_buf[i].reset() if isinstance(self.state, list): self.state[i] = None elif self.state", "cur_episode += 1 reward_sum += self.reward length_sum += self.length self.reward,", "b in self.buffer] total = sum(lens) batch_index = np.random.choice( total,", "isinstance(self.buffer, ReplayBuffer): self._cached_buf = [ ListReplayBuffer() for _ in range(self.env_num)]", "= obs_next if self._multi_env: cur_episode = sum(cur_episode) duration = time.time()", "= result.act obs_next, self._rew, self._done, self._info = self.env.step( self._act if", "self.env.render() time.sleep(render) self.length += 1 self.reward += self._rew if self._multi_env:", "self._multi_env else self._act[0]) if render > 0: self.env.render() time.sleep(render) self.length", "duration if isinstance(n_episode, list): n_episode = np.sum(n_episode) else: n_episode =", "= Batch( obs=self._make_batch(self._obs), act=self._make_batch(self._act), rew=self._make_batch(self._rew), done=self._make_batch(self._done), obs_next=None, info=self._make_batch(self._info)) result =", "length_sum += self.length self.reward, self.length = 0, 0 self.state =", "(n_episode != 0)]) == 1, \\ \"One and only one", "isinstance(self.state, list): self.state[i] = None elif self.state is not None:", "else: batch_data, indice = self.buffer.sample(batch_size) batch_data = self.process_fn(batch_data, self.buffer, indice)", "np.sum(n_episode) else: n_episode = max(cur_episode, 1) return { 'n/ep': cur_episode,", "does not match the number of ' \\ 'input env.'", "or \\ cur_episode[i] < n_episode[i]: cur_episode[i] += 1 reward_sum +=", "0 for b in self._cached_buf: b.reset() def seed(self, seed=None): if", "if self._multi_buf: for b in self.buffer: b.reset() else: self.buffer.reset() def", "self._multi_buf: if batch_size > 0: lens = [len(b) for b", "batch_data = Batch( obs=self._obs, act=self._act, rew=self._rew, done=self._done, obs_next=None, info=self._info) else:", "0 if isinstance(self.state, torch.Tensor): # remove ref count in pytorch", "= env self.env_num = 1 self.collect_step = 0 self.collect_episode =", "render(self, **kwargs): if hasattr(self.env, 'render'): return self.env.render(**kwargs) def close(self): if", "obs_next=None, info=self._info) else: batch_data = Batch( obs=self._make_batch(self._obs), act=self._make_batch(self._act), rew=self._make_batch(self._rew), done=self._make_batch(self._done),", "if storing in one buffer self._cached_buf = [] if self._multi_env:", "'render'): return self.env.render(**kwargs) def close(self): if hasattr(self.env, 'close'): self.env.close() def", "_ in range(self.env_num)] else: raise TypeError('The buffer in data collector", "self.policy(batch_data, self.state) self.state = result.state if hasattr(result, 'state') else None", "+= 1 if self._done[i]: if n_step != 0 or np.isscalar(n_episode)", "np.isscalar(n_episode) or \\ cur_episode[i] < n_episode[i]: cur_episode[i] += 1 reward_sum", "0 if self._cached_buf: self._cached_buf[i].reset() if isinstance(self.state, list): self.state[i] = None", "+= self.length self.reward, self.length = 0, 0 self.state = None", "time limitation to your environment!', Warning) if self._multi_env: batch_data =", "= self.env.reset() if n_episode != 0 and cur_episode >= n_episode:", "data collector is invalid!') self.reset_env() self.reset_buffer() # state over batch", "cur_step += len(self._cached_buf[i]) self.buffer.update(self._cached_buf[i]) self.reward[i], self.length[i] = 0, 0 if", "1 self.buffer[i].add(**data) cur_step += 1 else: warning_count += 1 self.buffer.add(**data)", "seed(self, seed=None): if hasattr(self.env, 'seed'): return self.env.seed(seed) def render(self, **kwargs):", "n_episode, 'len': length_sum / n_episode, } def sample(self, batch_size): if", "self._act = result.act obs_next, self._rew, self._done, self._info = self.env.step( self._act", "is either a list, an np.ndarray, or a torch.Tensor self.state", "torch import warnings import numpy as np from tianshou.env import", "in self.buffer: b.reset() else: self.buffer.reset() def get_env_num(self): return self.env_num def", "0 and cur_step >= n_step: break self._obs = obs_next self._obs", "in self.buffer] total = sum(lens) batch_index = np.random.choice( total, batch_size,", "Batch() for i, b in enumerate(self.buffer): cur_batch = (batch_index ==", "!= 0), (n_episode != 0)]) == 1, \\ \"One and", "remove ref count in pytorch (?) self.state = self.state.detach() if", "sum(lens) batch_index = np.random.choice( total, batch_size, p=np.array(lens) / total) else:", "self.reward[i], self.length[i] = 0, 0 if self._cached_buf: self._cached_buf[i].reset() if isinstance(self.state,", "{ 'obs': self._obs[i], 'act': self._act[i], 'rew': self._rew[i], 'done': self._done[i], 'obs_next':", "1 if self._done: cur_episode += 1 reward_sum += self.reward length_sum", "== i).sum() if batch_size and cur_batch or batch_size <= 0:", "0 self.state = None obs_next = self.env.reset() if n_episode !=", "\\ 'input env.' self._multi_buf = True elif isinstance(self.buffer, ReplayBuffer): self._cached_buf", "= result.act.detach().cpu().numpy() elif not isinstance(self._act, np.ndarray): self._act = np.array(result.act) else:", "torch.Tensor): self._act = result.act.detach().cpu().numpy() elif not isinstance(self._act, np.ndarray): self._act =", "warning_count += 1 self._cached_buf[i].add(**data) elif self._multi_buf: warning_count += 1 self.buffer[i].add(**data)", "def __init__(self, policy, env, buffer=None, stat_size=100): super().__init__() self.env = env", "= np.zeros(self.env_num) self.length = np.zeros(self.env_num) else: self.reward, self.length = 0,", "/ total) else: batch_index = np.array([]) batch_data = Batch() for", "for b in self.buffer] total = sum(lens) batch_index = np.random.choice(", "stat_size=100): super().__init__() self.env = env self.env_num = 1 self.collect_step =", "self.state is not None: if isinstance(self.state[i], dict): self.state[i] = {}", "/ duration) self.episode_speed.add(cur_episode / duration) self.collect_step += cur_step self.collect_episode +=", "self._obs = obs_next if self._multi_env: cur_episode = sum(cur_episode) duration =", "self._multi_env: n_episode = np.sum(n_episode) start_time = time.time() assert sum([(n_step !=", "self.episode_speed.get(), 'rew': reward_sum / n_episode, 'len': length_sum / n_episode, }", "np.array([]) batch_data = Batch() for i, b in enumerate(self.buffer): cur_batch", "True elif isinstance(self.buffer, ReplayBuffer): self._cached_buf = [ ListReplayBuffer() for _", "cur_step += 1 if self._done: cur_episode += 1 reward_sum +=", "'obs_next': obs_next[i], 'info': self._info[i]} if self._cached_buf: warning_count += 1 self._cached_buf[i].add(**data)", "indice = self.buffer.sample(batch_size) batch_data = self.process_fn(batch_data, self.buffer, indice) return batch_data", "= self.state.detach() if sum(self._done): obs_next = self.env.reset(np.where(self._done)[0]) if n_episode !=", "np.zeros(self.env_num) else: self.reward, self.length = 0, 0 for b in", "b in self.buffer: b.reset() else: self.buffer.reset() def get_env_num(self): return self.env_num", "if batch_size > 0: lens = [len(b) for b in", "self._done[i]: if n_step != 0 or np.isscalar(n_episode) or \\ cur_episode[i]", "else None if isinstance(result.act, torch.Tensor): self._act = result.act.detach().cpu().numpy() elif not", "[len(b) for b in self.buffer] total = sum(lens) batch_index =", "super().__init__() self.env = env self.env_num = 1 self.collect_step = 0", "self.reward, self.length = 0, 0 self.state = None obs_next =", "= [ ListReplayBuffer() for _ in range(self.env_num)] else: raise TypeError('The", "= 0 length_sum = 0 while True: if warning_count >=", "lens = [len(b) for b in self.buffer] total = sum(lens)", "self._done = self._info = None if self._multi_env: self.reward = np.zeros(self.env_num)", "data[None] else: return np.array([data]) def collect(self, n_step=0, n_episode=0, render=0): warning_count", "a time limitation to your environment!', Warning) if self._multi_env: batch_data", "done=self._done, obs_next=None, info=self._info) else: batch_data = Batch( obs=self._make_batch(self._obs), act=self._make_batch(self._act), rew=self._make_batch(self._rew),", "return data[None] else: return np.array([data]) def collect(self, n_step=0, n_episode=0, render=0):", "self.buffer = ReplayBuffer(100) else: self.buffer = buffer self.policy = policy", "tianshou.env import BaseVectorEnv from tianshou.data import Batch, ReplayBuffer,\\ ListReplayBuffer from", "sum(cur_episode) duration = time.time() - start_time self.step_speed.add(cur_step / duration) self.episode_speed.add(cur_episode", "self._cached_buf: b.reset() def seed(self, seed=None): if hasattr(self.env, 'seed'): return self.env.seed(seed)", "\"\"\"docstring for Collector\"\"\" def __init__(self, policy, env, buffer=None, stat_size=100): super().__init__()", "* 0 if isinstance(self.state, torch.Tensor): # remove ref count in", "in one buffer self._cached_buf = [] if self._multi_env: self.env_num =", "0), (n_episode != 0)]) == 1, \\ \"One and only", "self.buffer[i].add(**data) cur_step += 1 else: warning_count += 1 self.buffer.add(**data) cur_step", "# True if buf is a list # need multiple", "= { 'obs': self._obs[i], 'act': self._act[i], 'rew': self._rew[i], 'done': self._done[i],", "b.sample(cur_batch) batch = self.process_fn(batch, b, indice) batch_data.append(batch) else: batch_data, indice", "collection number specification permitted!\" cur_step = 0 cur_episode = np.zeros(self.env_num)", "in range(self.env_num)] else: raise TypeError('The buffer in data collector is", "**kwargs): if hasattr(self.env, 'render'): return self.env.render(**kwargs) def close(self): if hasattr(self.env,", "length_sum / n_episode, } def sample(self, batch_size): if self._multi_buf: if", "hasattr(self.env, 'close'): self.env.close() def _make_batch(self, data): if isinstance(data, np.ndarray): return", "policy self.process_fn = policy.process_fn self._multi_env = isinstance(env, BaseVectorEnv) self._multi_buf =", "= ReplayBuffer(100) else: self.buffer = buffer self.policy = policy self.process_fn", "= sum(cur_episode) duration = time.time() - start_time self.step_speed.add(cur_step / duration)", "sum(self._done): obs_next = self.env.reset(np.where(self._done)[0]) if n_episode != 0: if isinstance(n_episode,", "+= cur_episode self.collect_time += duration if isinstance(n_episode, list): n_episode =", "time.sleep(render) self.length += 1 self.reward += self._rew if self._multi_env: for", "self._obs[i], 'act': self._act[i], 'rew': self._rew[i], 'done': self._done[i], 'obs_next': obs_next[i], 'info':", "+= 1 self.reward += self._rew if self._multi_env: for i in", "self.policy = policy self.process_fn = policy.process_fn self._multi_env = isinstance(env, BaseVectorEnv)", "np.isscalar(n_episode) and \\ cur_episode.sum() >= n_episode: break else: self.buffer.add( self._obs,", "if hasattr(self.env, 'seed'): return self.env.seed(seed) def render(self, **kwargs): if hasattr(self.env,", "self._multi_env: batch_data = Batch( obs=self._obs, act=self._act, rew=self._rew, done=self._done, obs_next=None, info=self._info)", "return { 'n/ep': cur_episode, 'n/st': cur_step, 'v/st': self.step_speed.get(), 'v/ep': self.episode_speed.get(),", "if self._done[i]: if n_step != 0 or np.isscalar(n_episode) or \\", "'rew': reward_sum / n_episode, 'len': length_sum / n_episode, } def", "else: self._act = result.act obs_next, self._rew, self._done, self._info = self.env.step(", "/ n_episode, 'len': length_sum / n_episode, } def sample(self, batch_size):", "0: if isinstance(n_episode, list) and \\ (cur_episode >= np.array(n_episode)).all() or", "self._cached_buf[i].reset() if isinstance(self.state, list): self.state[i] = None elif self.state is", "np.array(n_episode)).all() or \\ np.isscalar(n_episode) and \\ cur_episode.sum() >= n_episode: break", "'The number of data buffer does not match the number", "if n_episode != 0: if isinstance(n_episode, list) and \\ (cur_episode", "sum([(n_step != 0), (n_episode != 0)]) == 1, \\ \"One", "result.act obs_next, self._rew, self._done, self._info = self.env.step( self._act if self._multi_env", "return np.array([data]) def collect(self, n_step=0, n_episode=0, render=0): warning_count = 0", "self._act = self._rew = self._done = self._info = None if", "self.buffer = buffer self.policy = policy self.process_fn = policy.process_fn self._multi_env", "self._cached_buf: cur_step += len(self._cached_buf[i]) self.buffer.update(self._cached_buf[i]) self.reward[i], self.length[i] = 0, 0", "if isinstance(n_episode, list) and \\ (cur_episode >= np.array(n_episode)).all() or \\", "self._rew = self._done = self._info = None if self._multi_env: self.reward", "else: raise TypeError('The buffer in data collector is invalid!') self.reset_env()", "+= duration if isinstance(n_episode, list): n_episode = np.sum(n_episode) else: n_episode", "!= 0 or np.isscalar(n_episode) or \\ cur_episode[i] < n_episode[i]: cur_episode[i]", "len(self._cached_buf[i]) self.buffer.update(self._cached_buf[i]) self.reward[i], self.length[i] = 0, 0 if self._cached_buf: self._cached_buf[i].reset()", "\\ \"One and only one collection number specification permitted!\" cur_step", "from tianshou.utils import MovAvg class Collector(object): \"\"\"docstring for Collector\"\"\" def", "list): n_episode = np.sum(n_episode) else: n_episode = max(cur_episode, 1) return", "buf is a list # need multiple cache buffers only", ">= np.array(n_episode)).all() or \\ np.isscalar(n_episode) and \\ cur_episode.sum() >= n_episode:", "= isinstance(env, BaseVectorEnv) self._multi_buf = False # True if buf", "self.process_fn(batch, b, indice) batch_data.append(batch) else: batch_data, indice = self.buffer.sample(batch_size) batch_data", "reset_buffer(self): if self._multi_buf: for b in self.buffer: b.reset() else: self.buffer.reset()", "buffers only if storing in one buffer self._cached_buf = []", "else: self.buffer.reset() def get_env_num(self): return self.env_num def reset_env(self): self._obs =", "break self._obs = obs_next self._obs = obs_next if self._multi_env: cur_episode", "if isinstance(n_episode, list): n_episode = np.sum(n_episode) else: n_episode = max(cur_episode,", "'state') else None if isinstance(result.act, torch.Tensor): self._act = result.act.detach().cpu().numpy() elif", "n_episode: break if n_step != 0 and cur_step >= n_step:", "self._obs = obs_next self._obs = obs_next if self._multi_env: cur_episode =", "def render(self, **kwargs): if hasattr(self.env, 'render'): return self.env.render(**kwargs) def close(self):", "= 0 self.collect_episode = 0 self.collect_time = 0 if buffer", "self.env.step( self._act if self._multi_env else self._act[0]) if render > 0:", "if self._multi_env: self.env_num = len(env) if isinstance(self.buffer, list): assert len(self.buffer)", "ReplayBuffer): self._cached_buf = [ ListReplayBuffer() for _ in range(self.env_num)] else:", "1 if self._done[i]: if n_step != 0 or np.isscalar(n_episode) or", "self.state = result.state if hasattr(result, 'state') else None if isinstance(result.act,", "batch_size and cur_batch or batch_size <= 0: batch, indice =", "self._act if self._multi_env else self._act[0]) if render > 0: self.env.render()", "isinstance(self.state[i], dict): self.state[i] = {} else: self.state[i] = self.state[i] *", "and cur_batch or batch_size <= 0: batch, indice = b.sample(cur_batch)", "if buf is a list # need multiple cache buffers", "reward_sum += self.reward length_sum += self.length self.reward, self.length = 0,", "isinstance(self.state, torch.Tensor): # remove ref count in pytorch (?) self.state", "or \\ np.isscalar(n_episode) and \\ cur_episode.sum() >= n_episode: break else:", "0 length_sum = 0 while True: if warning_count >= 100000:", "= b.sample(cur_batch) batch = self.process_fn(batch, b, indice) batch_data.append(batch) else: batch_data,", "number specification permitted!\" cur_step = 0 cur_episode = np.zeros(self.env_num) if", "count in pytorch (?) self.state = self.state.detach() if sum(self._done): obs_next", "0, 0 self.state = None obs_next = self.env.reset() if n_episode", "is not None: if isinstance(self.state[i], dict): self.state[i] = {} else:", "warnings.warn( 'There are already many steps in an episode. '", "None: if isinstance(self.state[i], dict): self.state[i] = {} else: self.state[i] =", "= self.env.reset(np.where(self._done)[0]) if n_episode != 0: if isinstance(n_episode, list) and", "list # need multiple cache buffers only if storing in", "= self.state[i] * 0 if isinstance(self.state, torch.Tensor): # remove ref", "number of ' \\ 'input env.' self._multi_buf = True elif", "n_episode=0, render=0): warning_count = 0 if not self._multi_env: n_episode =", "for b in self.buffer: b.reset() else: self.buffer.reset() def get_env_num(self): return", "if self._multi_env else 0 reward_sum = 0 length_sum = 0", "ListReplayBuffer from tianshou.utils import MovAvg class Collector(object): \"\"\"docstring for Collector\"\"\"", "> 0: lens = [len(b) for b in self.buffer] total", "batch_size <= 0: batch, indice = b.sample(cur_batch) batch = self.process_fn(batch,", "obs_next=None, info=self._make_batch(self._info)) result = self.policy(batch_data, self.state) self.state = result.state if", "self.state[i] = self.state[i] * 0 if isinstance(self.state, torch.Tensor): # remove", "= np.array([]) batch_data = Batch() for i, b in enumerate(self.buffer):", "'seed'): return self.env.seed(seed) def render(self, **kwargs): if hasattr(self.env, 'render'): return", ">= n_episode: break else: self.buffer.add( self._obs, self._act[0], self._rew, self._done, obs_next,", "result = self.policy(batch_data, self.state) self.state = result.state if hasattr(result, 'state')", "n_step != 0 or np.isscalar(n_episode) or \\ cur_episode[i] < n_episode[i]:", "ref count in pytorch (?) self.state = self.state.detach() if sum(self._done):", "'v/st': self.step_speed.get(), 'v/ep': self.episode_speed.get(), 'rew': reward_sum / n_episode, 'len': length_sum", "list, an np.ndarray, or a torch.Tensor self.state = None self.step_speed", "not self._multi_env: n_episode = np.sum(n_episode) start_time = time.time() assert sum([(n_step", "+= self.reward length_sum += self.length self.reward, self.length = 0, 0", "def collect(self, n_step=0, n_episode=0, render=0): warning_count = 0 if not", "else: self.state[i] = self.state[i] * 0 if isinstance(self.state, torch.Tensor): #", "many steps in an episode. ' 'You should add a", "MovAvg(stat_size) def reset_buffer(self): if self._multi_buf: for b in self.buffer: b.reset()", "1 self._cached_buf[i].add(**data) elif self._multi_buf: warning_count += 1 self.buffer[i].add(**data) cur_step +=", "warnings import numpy as np from tianshou.env import BaseVectorEnv from", "cache buffers only if storing in one buffer self._cached_buf =", "False # True if buf is a list # need", "else: self.buffer.add( self._obs, self._act[0], self._rew, self._done, obs_next, self._info) cur_step +=", "self.collect_time += duration if isinstance(n_episode, list): n_episode = np.sum(n_episode) else:", "None: self.buffer = ReplayBuffer(100) else: self.buffer = buffer self.policy =", "1 self.buffer.add(**data) cur_step += 1 if self._done[i]: if n_step !=", "= [len(b) for b in self.buffer] total = sum(lens) batch_index", "b in self._cached_buf: b.reset() def seed(self, seed=None): if hasattr(self.env, 'seed'):", "import torch import warnings import numpy as np from tianshou.env", "self.reward = np.zeros(self.env_num) self.length = np.zeros(self.env_num) else: self.reward, self.length =", "= self.process_fn(batch, b, indice) batch_data.append(batch) else: batch_data, indice = self.buffer.sample(batch_size)", "and only one collection number specification permitted!\" cur_step = 0", "collect(self, n_step=0, n_episode=0, render=0): warning_count = 0 if not self._multi_env:", "numpy as np from tianshou.env import BaseVectorEnv from tianshou.data import", "None self.step_speed = MovAvg(stat_size) self.episode_speed = MovAvg(stat_size) def reset_buffer(self): if", "episode. ' 'You should add a time limitation to your", "self._act[0]) if render > 0: self.env.render() time.sleep(render) self.length += 1", "= 0, 0 for b in self._cached_buf: b.reset() def seed(self,", "self.reset_env() self.reset_buffer() # state over batch is either a list,", "render=0): warning_count = 0 if not self._multi_env: n_episode = np.sum(n_episode)", "specification permitted!\" cur_step = 0 cur_episode = np.zeros(self.env_num) if self._multi_env", "hasattr(result, 'state') else None if isinstance(result.act, torch.Tensor): self._act = result.act.detach().cpu().numpy()", "if self._multi_buf: if batch_size > 0: lens = [len(b) for", "rew=self._make_batch(self._rew), done=self._make_batch(self._done), obs_next=None, info=self._make_batch(self._info)) result = self.policy(batch_data, self.state) self.state =", "!= 0)]) == 1, \\ \"One and only one collection", "= None elif self.state is not None: if isinstance(self.state[i], dict):", "or a torch.Tensor self.state = None self.step_speed = MovAvg(stat_size) self.episode_speed", "None elif self.state is not None: if isinstance(self.state[i], dict): self.state[i]", "elif self._multi_buf: warning_count += 1 self.buffer[i].add(**data) cur_step += 1 else:", "+= 1 reward_sum += self.reward[i] length_sum += self.length[i] if self._cached_buf:", "act=self._make_batch(self._act), rew=self._make_batch(self._rew), done=self._make_batch(self._done), obs_next=None, info=self._make_batch(self._info)) result = self.policy(batch_data, self.state) self.state", "def sample(self, batch_size): if self._multi_buf: if batch_size > 0: lens", "import time import torch import warnings import numpy as np", "self.length += 1 self.reward += self._rew if self._multi_env: for i", "= 0 if not self._multi_env: n_episode = np.sum(n_episode) start_time =", "batch_data = Batch() for i, b in enumerate(self.buffer): cur_batch =", "done=self._make_batch(self._done), obs_next=None, info=self._make_batch(self._info)) result = self.policy(batch_data, self.state) self.state = result.state", "length_sum += self.length[i] if self._cached_buf: cur_step += len(self._cached_buf[i]) self.buffer.update(self._cached_buf[i]) self.reward[i],", "self.buffer: b.reset() else: self.buffer.reset() def get_env_num(self): return self.env_num def reset_env(self):", "self.length[i] if self._cached_buf: cur_step += len(self._cached_buf[i]) self.buffer.update(self._cached_buf[i]) self.reward[i], self.length[i] =", "for b in self._cached_buf: b.reset() def seed(self, seed=None): if hasattr(self.env,", "if self._cached_buf: cur_step += len(self._cached_buf[i]) self.buffer.update(self._cached_buf[i]) self.reward[i], self.length[i] = 0,", "self.env.render(**kwargs) def close(self): if hasattr(self.env, 'close'): self.env.close() def _make_batch(self, data):", "cur_step = 0 cur_episode = np.zeros(self.env_num) if self._multi_env else 0", "obs=self._make_batch(self._obs), act=self._make_batch(self._act), rew=self._make_batch(self._rew), done=self._make_batch(self._done), obs_next=None, info=self._make_batch(self._info)) result = self.policy(batch_data, self.state)", "n_episode = max(cur_episode, 1) return { 'n/ep': cur_episode, 'n/st': cur_step,", "cur_step self.collect_episode += cur_episode self.collect_time += duration if isinstance(n_episode, list):", "if sum(self._done): obs_next = self.env.reset(np.where(self._done)[0]) if n_episode != 0: if", "seed=None): if hasattr(self.env, 'seed'): return self.env.seed(seed) def render(self, **kwargs): if", "0, 0 if self._cached_buf: self._cached_buf[i].reset() if isinstance(self.state, list): self.state[i] =", "obs_next if self._multi_env: cur_episode = sum(cur_episode) duration = time.time() -", "assert len(self.buffer) == self.env_num, \\ 'The number of data buffer", "self._done, obs_next, self._info) cur_step += 1 if self._done: cur_episode +=", "rew=self._rew, done=self._done, obs_next=None, info=self._info) else: batch_data = Batch( obs=self._make_batch(self._obs), act=self._make_batch(self._act),", "duration) self.collect_step += cur_step self.collect_episode += cur_episode self.collect_time += duration", "result.act.detach().cpu().numpy() elif not isinstance(self._act, np.ndarray): self._act = np.array(result.act) else: self._act", "warning_count >= 100000: warnings.warn( 'There are already many steps in", "Collector\"\"\" def __init__(self, policy, env, buffer=None, stat_size=100): super().__init__() self.env =", "sample(self, batch_size): if self._multi_buf: if batch_size > 0: lens =", "self._rew, self._done, obs_next, self._info) cur_step += 1 if self._done: cur_episode", "self.episode_speed.add(cur_episode / duration) self.collect_step += cur_step self.collect_episode += cur_episode self.collect_time", "from tianshou.data import Batch, ReplayBuffer,\\ ListReplayBuffer from tianshou.utils import MovAvg", "!= 0 and cur_step >= n_step: break self._obs = obs_next", "if self._multi_env: self.reward = np.zeros(self.env_num) self.length = np.zeros(self.env_num) else: self.reward,", "n_episode[i]: cur_episode[i] += 1 reward_sum += self.reward[i] length_sum += self.length[i]", "buffer=None, stat_size=100): super().__init__() self.env = env self.env_num = 1 self.collect_step", "the number of ' \\ 'input env.' self._multi_buf = True", "= max(cur_episode, 1) return { 'n/ep': cur_episode, 'n/st': cur_step, 'v/st':", "batch_data, indice = self.buffer.sample(batch_size) batch_data = self.process_fn(batch_data, self.buffer, indice) return", "= MovAvg(stat_size) self.episode_speed = MovAvg(stat_size) def reset_buffer(self): if self._multi_buf: for", "self._obs, self._act[0], self._rew, self._done, obs_next, self._info) cur_step += 1 if", "else 0 reward_sum = 0 length_sum = 0 while True:", "start_time self.step_speed.add(cur_step / duration) self.episode_speed.add(cur_episode / duration) self.collect_step += cur_step", "+= 1 self._cached_buf[i].add(**data) elif self._multi_buf: warning_count += 1 self.buffer[i].add(**data) cur_step", "batch_data.append(batch) else: batch_data, indice = self.buffer.sample(batch_size) batch_data = self.process_fn(batch_data, self.buffer,", "else: self.buffer = buffer self.policy = policy self.process_fn = policy.process_fn", "multiple cache buffers only if storing in one buffer self._cached_buf", "= Batch( obs=self._obs, act=self._act, rew=self._rew, done=self._done, obs_next=None, info=self._info) else: batch_data", "cur_episode, 'n/st': cur_step, 'v/st': self.step_speed.get(), 'v/ep': self.episode_speed.get(), 'rew': reward_sum /", "storing in one buffer self._cached_buf = [] if self._multi_env: self.env_num", "time.time() assert sum([(n_step != 0), (n_episode != 0)]) == 1,", "reward_sum += self.reward[i] length_sum += self.length[i] if self._cached_buf: cur_step +=", "self.step_speed.get(), 'v/ep': self.episode_speed.get(), 'rew': reward_sum / n_episode, 'len': length_sum /", "self._act = np.array(result.act) else: self._act = result.act obs_next, self._rew, self._done,", "None obs_next = self.env.reset() if n_episode != 0 and cur_episode", "0: batch, indice = b.sample(cur_batch) batch = self.process_fn(batch, b, indice)", "self._cached_buf = [] if self._multi_env: self.env_num = len(env) if isinstance(self.buffer,", "b.reset() def seed(self, seed=None): if hasattr(self.env, 'seed'): return self.env.seed(seed) def", "buffer self._cached_buf = [] if self._multi_env: self.env_num = len(env) if", "range(self.env_num)] else: raise TypeError('The buffer in data collector is invalid!')", "range(self.env_num): data = { 'obs': self._obs[i], 'act': self._act[i], 'rew': self._rew[i],", "+= 1 if self._done: cur_episode += 1 reward_sum += self.reward", "\"One and only one collection number specification permitted!\" cur_step =", "0)]) == 1, \\ \"One and only one collection number", "if warning_count >= 100000: warnings.warn( 'There are already many steps", "def close(self): if hasattr(self.env, 'close'): self.env.close() def _make_batch(self, data): if", "self.step_speed.add(cur_step / duration) self.episode_speed.add(cur_episode / duration) self.collect_step += cur_step self.collect_episode", "= policy self.process_fn = policy.process_fn self._multi_env = isinstance(env, BaseVectorEnv) self._multi_buf", "reward_sum = 0 length_sum = 0 while True: if warning_count", "a list # need multiple cache buffers only if storing", "1, \\ \"One and only one collection number specification permitted!\"", "class Collector(object): \"\"\"docstring for Collector\"\"\" def __init__(self, policy, env, buffer=None,", "if isinstance(self.buffer, list): assert len(self.buffer) == self.env_num, \\ 'The number", "to your environment!', Warning) if self._multi_env: batch_data = Batch( obs=self._obs,", "if n_episode != 0 and cur_episode >= n_episode: break if", "= time.time() - start_time self.step_speed.add(cur_step / duration) self.episode_speed.add(cur_episode / duration)", "duration = time.time() - start_time self.step_speed.add(cur_step / duration) self.episode_speed.add(cur_episode /", "return self.env.seed(seed) def render(self, **kwargs): if hasattr(self.env, 'render'): return self.env.render(**kwargs)", "start_time = time.time() assert sum([(n_step != 0), (n_episode != 0)])", "steps in an episode. ' 'You should add a time", "MovAvg(stat_size) self.episode_speed = MovAvg(stat_size) def reset_buffer(self): if self._multi_buf: for b", "buffer in data collector is invalid!') self.reset_env() self.reset_buffer() # state", "= None obs_next = self.env.reset() if n_episode != 0 and", "self.collect_step += cur_step self.collect_episode += cur_episode self.collect_time += duration if", "obs_next = self.env.reset() if n_episode != 0 and cur_episode >=", "= result.state if hasattr(result, 'state') else None if isinstance(result.act, torch.Tensor):", "+= self._rew if self._multi_env: for i in range(self.env_num): data =", "in range(self.env_num): data = { 'obs': self._obs[i], 'act': self._act[i], 'rew':", "+= len(self._cached_buf[i]) self.buffer.update(self._cached_buf[i]) self.reward[i], self.length[i] = 0, 0 if self._cached_buf:", "= [] if self._multi_env: self.env_num = len(env) if isinstance(self.buffer, list):", "permitted!\" cur_step = 0 cur_episode = np.zeros(self.env_num) if self._multi_env else", "i).sum() if batch_size and cur_batch or batch_size <= 0: batch,", "isinstance(env, BaseVectorEnv) self._multi_buf = False # True if buf is", "self.episode_speed = MovAvg(stat_size) def reset_buffer(self): if self._multi_buf: for b in", "return self.env.render(**kwargs) def close(self): if hasattr(self.env, 'close'): self.env.close() def _make_batch(self,", "[] if self._multi_env: self.env_num = len(env) if isinstance(self.buffer, list): assert", "# state over batch is either a list, an np.ndarray,", "if hasattr(self.env, 'close'): self.env.close() def _make_batch(self, data): if isinstance(data, np.ndarray):", "= 0 if buffer is None: self.buffer = ReplayBuffer(100) else:", "n_episode = np.sum(n_episode) else: n_episode = max(cur_episode, 1) return {", "in self._cached_buf: b.reset() def seed(self, seed=None): if hasattr(self.env, 'seed'): return", "n_step != 0 and cur_step >= n_step: break self._obs =", "1 else: warning_count += 1 self.buffer.add(**data) cur_step += 1 if", "self.buffer.update(self._cached_buf[i]) self.reward[i], self.length[i] = 0, 0 if self._cached_buf: self._cached_buf[i].reset() if", "'done': self._done[i], 'obs_next': obs_next[i], 'info': self._info[i]} if self._cached_buf: warning_count +=", "buffer does not match the number of ' \\ 'input", "if hasattr(result, 'state') else None if isinstance(result.act, torch.Tensor): self._act =", "of ' \\ 'input env.' self._multi_buf = True elif isinstance(self.buffer,", "self.state) self.state = result.state if hasattr(result, 'state') else None if", "import BaseVectorEnv from tianshou.data import Batch, ReplayBuffer,\\ ListReplayBuffer from tianshou.utils", "either a list, an np.ndarray, or a torch.Tensor self.state =", "self.env.close() def _make_batch(self, data): if isinstance(data, np.ndarray): return data[None] else:", "and cur_episode >= n_episode: break if n_step != 0 and", "if batch_size and cur_batch or batch_size <= 0: batch, indice", "0: lens = [len(b) for b in self.buffer] total =", "torch.Tensor self.state = None self.step_speed = MovAvg(stat_size) self.episode_speed = MovAvg(stat_size)", "self._done: cur_episode += 1 reward_sum += self.reward length_sum += self.length", "if self._multi_env: cur_episode = sum(cur_episode) duration = time.time() - start_time", "= self.policy(batch_data, self.state) self.state = result.state if hasattr(result, 'state') else", "self._rew, self._done, self._info = self.env.step( self._act if self._multi_env else self._act[0])", "if self._multi_env: batch_data = Batch( obs=self._obs, act=self._act, rew=self._rew, done=self._done, obs_next=None,", "indice) batch_data.append(batch) else: batch_data, indice = self.buffer.sample(batch_size) batch_data = self.process_fn(batch_data,", "0: self.env.render() time.sleep(render) self.length += 1 self.reward += self._rew if", "= self.env.step( self._act if self._multi_env else self._act[0]) if render >", "import warnings import numpy as np from tianshou.env import BaseVectorEnv", "\\ np.isscalar(n_episode) and \\ cur_episode.sum() >= n_episode: break else: self.buffer.add(", "batch_size): if self._multi_buf: if batch_size > 0: lens = [len(b)", "if n_step != 0 or np.isscalar(n_episode) or \\ cur_episode[i] <", "else: return np.array([data]) def collect(self, n_step=0, n_episode=0, render=0): warning_count =", "total) else: batch_index = np.array([]) batch_data = Batch() for i,", "__init__(self, policy, env, buffer=None, stat_size=100): super().__init__() self.env = env self.env_num", "data buffer does not match the number of ' \\", "{} else: self.state[i] = self.state[i] * 0 if isinstance(self.state, torch.Tensor):", "= 0, 0 self.state = None obs_next = self.env.reset() if", "0 or np.isscalar(n_episode) or \\ cur_episode[i] < n_episode[i]: cur_episode[i] +=", "== self.env_num, \\ 'The number of data buffer does not", "[ ListReplayBuffer() for _ in range(self.env_num)] else: raise TypeError('The buffer", "} def sample(self, batch_size): if self._multi_buf: if batch_size > 0:", "1 self.collect_step = 0 self.collect_episode = 0 self.collect_time = 0", "= {} else: self.state[i] = self.state[i] * 0 if isinstance(self.state,", "self._multi_env = isinstance(env, BaseVectorEnv) self._multi_buf = False # True if", "is a list # need multiple cache buffers only if", "duration) self.episode_speed.add(cur_episode / duration) self.collect_step += cur_step self.collect_episode += cur_episode", "only if storing in one buffer self._cached_buf = [] if", "self.length = 0, 0 self.state = None obs_next = self.env.reset()", "and \\ cur_episode.sum() >= n_episode: break else: self.buffer.add( self._obs, self._act[0],", "= np.zeros(self.env_num) else: self.reward, self.length = 0, 0 for b", "self._multi_buf = False # True if buf is a list", "TypeError('The buffer in data collector is invalid!') self.reset_env() self.reset_buffer() #", "'n/st': cur_step, 'v/st': self.step_speed.get(), 'v/ep': self.episode_speed.get(), 'rew': reward_sum / n_episode,", "(cur_episode >= np.array(n_episode)).all() or \\ np.isscalar(n_episode) and \\ cur_episode.sum() >=", "self.env_num = 1 self.collect_step = 0 self.collect_episode = 0 self.collect_time", "- start_time self.step_speed.add(cur_step / duration) self.episode_speed.add(cur_episode / duration) self.collect_step +=", "n_episode, } def sample(self, batch_size): if self._multi_buf: if batch_size >", "render > 0: self.env.render() time.sleep(render) self.length += 1 self.reward +=", "= np.sum(n_episode) start_time = time.time() assert sum([(n_step != 0), (n_episode", "if not self._multi_env: n_episode = np.sum(n_episode) start_time = time.time() assert", "if self._multi_env: for i in range(self.env_num): data = { 'obs':", "if self._multi_env else self._act[0]) if render > 0: self.env.render() time.sleep(render)", "length_sum = 0 while True: if warning_count >= 100000: warnings.warn(", "or batch_size <= 0: batch, indice = b.sample(cur_batch) batch =", "self._multi_env else 0 reward_sum = 0 length_sum = 0 while", "max(cur_episode, 1) return { 'n/ep': cur_episode, 'n/st': cur_step, 'v/st': self.step_speed.get(),", "environment!', Warning) if self._multi_env: batch_data = Batch( obs=self._obs, act=self._act, rew=self._rew,", "def _make_batch(self, data): if isinstance(data, np.ndarray): return data[None] else: return", "if isinstance(self.state[i], dict): self.state[i] = {} else: self.state[i] = self.state[i]", "!= 0: if isinstance(n_episode, list) and \\ (cur_episode >= np.array(n_episode)).all()", "np.zeros(self.env_num) self.length = np.zeros(self.env_num) else: self.reward, self.length = 0, 0", ">= n_step: break self._obs = obs_next self._obs = obs_next if", "torch.Tensor): # remove ref count in pytorch (?) self.state =", "need multiple cache buffers only if storing in one buffer", "# remove ref count in pytorch (?) self.state = self.state.detach()", "= self._done = self._info = None if self._multi_env: self.reward =", "info=self._make_batch(self._info)) result = self.policy(batch_data, self.state) self.state = result.state if hasattr(result,", "else: warning_count += 1 self.buffer.add(**data) cur_step += 1 if self._done[i]:", "== 1, \\ \"One and only one collection number specification", "a torch.Tensor self.state = None self.step_speed = MovAvg(stat_size) self.episode_speed =", "obs_next, self._rew, self._done, self._info = self.env.step( self._act if self._multi_env else", "env, buffer=None, stat_size=100): super().__init__() self.env = env self.env_num = 1", ">= 100000: warnings.warn( 'There are already many steps in an", "env.' self._multi_buf = True elif isinstance(self.buffer, ReplayBuffer): self._cached_buf = [", "i, b in enumerate(self.buffer): cur_batch = (batch_index == i).sum() if", "self._multi_buf = True elif isinstance(self.buffer, ReplayBuffer): self._cached_buf = [ ListReplayBuffer()", "self.env.reset() if n_episode != 0 and cur_episode >= n_episode: break", "self._multi_env: self.env_num = len(env) if isinstance(self.buffer, list): assert len(self.buffer) ==", "def reset_buffer(self): if self._multi_buf: for b in self.buffer: b.reset() else:", "self.env = env self.env_num = 1 self.collect_step = 0 self.collect_episode", "= 0 self.collect_time = 0 if buffer is None: self.buffer", "obs=self._obs, act=self._act, rew=self._rew, done=self._done, obs_next=None, info=self._info) else: batch_data = Batch(", "return self.env_num def reset_env(self): self._obs = self.env.reset() self._act = self._rew", "1 reward_sum += self.reward[i] length_sum += self.length[i] if self._cached_buf: cur_step", "'info': self._info[i]} if self._cached_buf: warning_count += 1 self._cached_buf[i].add(**data) elif self._multi_buf:", "1) return { 'n/ep': cur_episode, 'n/st': cur_step, 'v/st': self.step_speed.get(), 'v/ep':", "0 self.collect_time = 0 if buffer is None: self.buffer =", "else: batch_data = Batch( obs=self._make_batch(self._obs), act=self._make_batch(self._act), rew=self._make_batch(self._rew), done=self._make_batch(self._done), obs_next=None, info=self._make_batch(self._info))", "self.state = None obs_next = self.env.reset() if n_episode != 0", "self._info) cur_step += 1 if self._done: cur_episode += 1 reward_sum", "act=self._act, rew=self._rew, done=self._done, obs_next=None, info=self._info) else: batch_data = Batch( obs=self._make_batch(self._obs),", "add a time limitation to your environment!', Warning) if self._multi_env:", "for i in range(self.env_num): data = { 'obs': self._obs[i], 'act':", "= np.array(result.act) else: self._act = result.act obs_next, self._rew, self._done, self._info", "len(env) if isinstance(self.buffer, list): assert len(self.buffer) == self.env_num, \\ 'The", "self.buffer] total = sum(lens) batch_index = np.random.choice( total, batch_size, p=np.array(lens)", "0, 0 for b in self._cached_buf: b.reset() def seed(self, seed=None):" ]