id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
230,900
airspeed-velocity/asv
asv/extern/asizeof.py
Asizer.reset
def reset(self, align=8, clip=80, code=False, derive=False, detail=0, ignored=True, infer=False, limit=100, stats=0, stream=None): '''Reset options, state, etc. The available options and default values are: *align=8* -- size alignment *clip=80* -- clip repr() strings *code=False* -- incl. (byte)code size *derive=False* -- derive from super type *detail=0* -- Asized refs level *ignored=True* -- ignore certain types *infer=False* -- try to infer types *limit=100* -- recursion limit *stats=0.0* -- print statistics, see function **asizeof** *stream=None* -- output stream for printing See function **asizeof** for a description of the options. ''' # options self._align_ = align self._clip_ = clip self._code_ = code self._derive_ = derive self._detail_ = detail # for Asized only self._infer_ = infer self._limit_ = limit self._stats_ = stats self._stream = stream if ignored: self._ign_d = _kind_ignored else: self._ign_d = None # clear state self._clear() self.set(align=align, code=code, stats=stats)
python
def reset(self, align=8, clip=80, code=False, derive=False, detail=0, ignored=True, infer=False, limit=100, stats=0, stream=None): '''Reset options, state, etc. The available options and default values are: *align=8* -- size alignment *clip=80* -- clip repr() strings *code=False* -- incl. (byte)code size *derive=False* -- derive from super type *detail=0* -- Asized refs level *ignored=True* -- ignore certain types *infer=False* -- try to infer types *limit=100* -- recursion limit *stats=0.0* -- print statistics, see function **asizeof** *stream=None* -- output stream for printing See function **asizeof** for a description of the options. ''' # options self._align_ = align self._clip_ = clip self._code_ = code self._derive_ = derive self._detail_ = detail # for Asized only self._infer_ = infer self._limit_ = limit self._stats_ = stats self._stream = stream if ignored: self._ign_d = _kind_ignored else: self._ign_d = None # clear state self._clear() self.set(align=align, code=code, stats=stats)
[ "def", "reset", "(", "self", ",", "align", "=", "8", ",", "clip", "=", "80", ",", "code", "=", "False", ",", "derive", "=", "False", ",", "detail", "=", "0", ",", "ignored", "=", "True", ",", "infer", "=", "False", ",", "limit", "=", "100", ","...
Reset options, state, etc. The available options and default values are: *align=8* -- size alignment *clip=80* -- clip repr() strings *code=False* -- incl. (byte)code size *derive=False* -- derive from super type *detail=0* -- Asized refs level *ignored=True* -- ignore certain types *infer=False* -- try to infer types *limit=100* -- recursion limit *stats=0.0* -- print statistics, see function **asizeof** *stream=None* -- output stream for printing See function **asizeof** for a description of the options.
[ "Reset", "options", "state", "etc", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L1912-L1957
230,901
airspeed-velocity/asv
asv/plugins/conda.py
_find_conda
def _find_conda(): """Find the conda executable robustly across conda versions. Returns ------- conda : str Path to the conda executable. Raises ------ IOError If the executable cannot be found in either the CONDA_EXE environment variable or in the PATH. Notes ----- In POSIX platforms in conda >= 4.4, conda can be set up as a bash function rather than an executable. (This is to enable the syntax ``conda activate env-name``.) In this case, the environment variable ``CONDA_EXE`` contains the path to the conda executable. In other cases, we use standard search for the appropriate name in the PATH. See https://github.com/airspeed-velocity/asv/issues/645 for more details. """ if 'CONDA_EXE' in os.environ: conda = os.environ['CONDA_EXE'] else: conda = util.which('conda') return conda
python
def _find_conda(): if 'CONDA_EXE' in os.environ: conda = os.environ['CONDA_EXE'] else: conda = util.which('conda') return conda
[ "def", "_find_conda", "(", ")", ":", "if", "'CONDA_EXE'", "in", "os", ".", "environ", ":", "conda", "=", "os", ".", "environ", "[", "'CONDA_EXE'", "]", "else", ":", "conda", "=", "util", ".", "which", "(", "'conda'", ")", "return", "conda" ]
Find the conda executable robustly across conda versions. Returns ------- conda : str Path to the conda executable. Raises ------ IOError If the executable cannot be found in either the CONDA_EXE environment variable or in the PATH. Notes ----- In POSIX platforms in conda >= 4.4, conda can be set up as a bash function rather than an executable. (This is to enable the syntax ``conda activate env-name``.) In this case, the environment variable ``CONDA_EXE`` contains the path to the conda executable. In other cases, we use standard search for the appropriate name in the PATH. See https://github.com/airspeed-velocity/asv/issues/645 for more details.
[ "Find", "the", "conda", "executable", "robustly", "across", "conda", "versions", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/plugins/conda.py#L20-L48
230,902
airspeed-velocity/asv
asv/benchmark.py
recvall
def recvall(sock, size): """ Receive data of given size from a socket connection """ data = b"" while len(data) < size: s = sock.recv(size - len(data)) data += s if not s: raise RuntimeError("did not receive data from socket " "(size {}, got only {!r})".format(size, data)) return data
python
def recvall(sock, size): data = b"" while len(data) < size: s = sock.recv(size - len(data)) data += s if not s: raise RuntimeError("did not receive data from socket " "(size {}, got only {!r})".format(size, data)) return data
[ "def", "recvall", "(", "sock", ",", "size", ")", ":", "data", "=", "b\"\"", "while", "len", "(", "data", ")", "<", "size", ":", "s", "=", "sock", ".", "recv", "(", "size", "-", "len", "(", "data", ")", ")", "data", "+=", "s", "if", "not", "s"...
Receive data of given size from a socket connection
[ "Receive", "data", "of", "given", "size", "from", "a", "socket", "connection" ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/benchmark.py#L252-L263
230,903
airspeed-velocity/asv
asv/benchmark.py
get_source_code
def get_source_code(items): """ Extract source code of given items, and concatenate and dedent it. """ sources = [] prev_class_name = None for func in items: try: lines, lineno = inspect.getsourcelines(func) except TypeError: continue if not lines: continue src = "\n".join(line.rstrip() for line in lines) src = textwrap.dedent(src) class_name = None if inspect.ismethod(func): # Add class name if hasattr(func, 'im_class'): class_name = func.im_class.__name__ elif hasattr(func, '__qualname__'): names = func.__qualname__.split('.') if len(names) > 1: class_name = names[-2] if class_name and prev_class_name != class_name: src = "class {0}:\n {1}".format( class_name, src.replace("\n", "\n ")) elif class_name: src = " {1}".format( class_name, src.replace("\n", "\n ")) sources.append(src) prev_class_name = class_name return "\n\n".join(sources).rstrip()
python
def get_source_code(items): sources = [] prev_class_name = None for func in items: try: lines, lineno = inspect.getsourcelines(func) except TypeError: continue if not lines: continue src = "\n".join(line.rstrip() for line in lines) src = textwrap.dedent(src) class_name = None if inspect.ismethod(func): # Add class name if hasattr(func, 'im_class'): class_name = func.im_class.__name__ elif hasattr(func, '__qualname__'): names = func.__qualname__.split('.') if len(names) > 1: class_name = names[-2] if class_name and prev_class_name != class_name: src = "class {0}:\n {1}".format( class_name, src.replace("\n", "\n ")) elif class_name: src = " {1}".format( class_name, src.replace("\n", "\n ")) sources.append(src) prev_class_name = class_name return "\n\n".join(sources).rstrip()
[ "def", "get_source_code", "(", "items", ")", ":", "sources", "=", "[", "]", "prev_class_name", "=", "None", "for", "func", "in", "items", ":", "try", ":", "lines", ",", "lineno", "=", "inspect", ".", "getsourcelines", "(", "func", ")", "except", "TypeErr...
Extract source code of given items, and concatenate and dedent it.
[ "Extract", "source", "code", "of", "given", "items", "and", "concatenate", "and", "dedent", "it", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/benchmark.py#L303-L342
230,904
airspeed-velocity/asv
asv/benchmark.py
disc_modules
def disc_modules(module_name, ignore_import_errors=False): """ Recursively import a module and all sub-modules in the package Yields ------ module Imported module in the package tree """ if not ignore_import_errors: module = import_module(module_name) else: try: module = import_module(module_name) except BaseException: traceback.print_exc() return yield module if getattr(module, '__path__', None): for _, name, _ in pkgutil.iter_modules(module.__path__, module_name + '.'): for item in disc_modules(name, ignore_import_errors=ignore_import_errors): yield item
python
def disc_modules(module_name, ignore_import_errors=False): if not ignore_import_errors: module = import_module(module_name) else: try: module = import_module(module_name) except BaseException: traceback.print_exc() return yield module if getattr(module, '__path__', None): for _, name, _ in pkgutil.iter_modules(module.__path__, module_name + '.'): for item in disc_modules(name, ignore_import_errors=ignore_import_errors): yield item
[ "def", "disc_modules", "(", "module_name", ",", "ignore_import_errors", "=", "False", ")", ":", "if", "not", "ignore_import_errors", ":", "module", "=", "import_module", "(", "module_name", ")", "else", ":", "try", ":", "module", "=", "import_module", "(", "mo...
Recursively import a module and all sub-modules in the package Yields ------ module Imported module in the package tree
[ "Recursively", "import", "a", "module", "and", "all", "sub", "-", "modules", "in", "the", "package" ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/benchmark.py#L832-L856
230,905
airspeed-velocity/asv
asv/benchmark.py
disc_benchmarks
def disc_benchmarks(root, ignore_import_errors=False): """ Discover all benchmarks in a given directory tree, yielding Benchmark objects For each class definition, looks for any methods with a special name. For each free function, yields all functions with a special name. """ root_name = os.path.basename(root) for module in disc_modules(root_name, ignore_import_errors=ignore_import_errors): for attr_name, module_attr in ( (k, v) for k, v in module.__dict__.items() if not k.startswith('_') ): if inspect.isclass(module_attr): for name, class_attr in inspect.getmembers(module_attr): if (inspect.isfunction(class_attr) or inspect.ismethod(class_attr)): benchmark = _get_benchmark(name, module, module_attr, class_attr) if benchmark is not None: yield benchmark elif inspect.isfunction(module_attr): benchmark = _get_benchmark(attr_name, module, None, module_attr) if benchmark is not None: yield benchmark
python
def disc_benchmarks(root, ignore_import_errors=False): root_name = os.path.basename(root) for module in disc_modules(root_name, ignore_import_errors=ignore_import_errors): for attr_name, module_attr in ( (k, v) for k, v in module.__dict__.items() if not k.startswith('_') ): if inspect.isclass(module_attr): for name, class_attr in inspect.getmembers(module_attr): if (inspect.isfunction(class_attr) or inspect.ismethod(class_attr)): benchmark = _get_benchmark(name, module, module_attr, class_attr) if benchmark is not None: yield benchmark elif inspect.isfunction(module_attr): benchmark = _get_benchmark(attr_name, module, None, module_attr) if benchmark is not None: yield benchmark
[ "def", "disc_benchmarks", "(", "root", ",", "ignore_import_errors", "=", "False", ")", ":", "root_name", "=", "os", ".", "path", ".", "basename", "(", "root", ")", "for", "module", "in", "disc_modules", "(", "root_name", ",", "ignore_import_errors", "=", "ig...
Discover all benchmarks in a given directory tree, yielding Benchmark objects For each class definition, looks for any methods with a special name. For each free function, yields all functions with a special name.
[ "Discover", "all", "benchmarks", "in", "a", "given", "directory", "tree", "yielding", "Benchmark", "objects" ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/benchmark.py#L859-L889
230,906
airspeed-velocity/asv
asv/benchmark.py
get_benchmark_from_name
def get_benchmark_from_name(root, name, extra_params=None): """ Create a benchmark from a fully-qualified benchmark name. Parameters ---------- root : str Path to the root of a benchmark suite. name : str Fully-qualified name to a specific benchmark. """ if '-' in name: try: name, param_idx = name.split('-', 1) param_idx = int(param_idx) except ValueError: raise ValueError("Benchmark id %r is invalid" % (name,)) else: param_idx = None update_sys_path(root) benchmark = None # try to directly import benchmark function by guessing its import module # name parts = name.split('.') for i in [1, 2]: path = os.path.join(root, *parts[:-i]) + '.py' if not os.path.isfile(path): continue modname = '.'.join([os.path.basename(root)] + parts[:-i]) module = import_module(modname) try: module_attr = getattr(module, parts[-i]) except AttributeError: break if i == 1 and inspect.isfunction(module_attr): benchmark = _get_benchmark(parts[-i], module, None, module_attr) break elif i == 2 and inspect.isclass(module_attr): try: class_attr = getattr(module_attr, parts[-1]) except AttributeError: break if (inspect.isfunction(class_attr) or inspect.ismethod(class_attr)): benchmark = _get_benchmark(parts[-1], module, module_attr, class_attr) break if benchmark is None: for benchmark in disc_benchmarks(root): if benchmark.name == name: break else: raise ValueError( "Could not find benchmark '{0}'".format(name)) if param_idx is not None: benchmark.set_param_idx(param_idx) if extra_params: class ExtraBenchmarkAttrs: pass for key, value in extra_params.items(): setattr(ExtraBenchmarkAttrs, key, value) benchmark._attr_sources.insert(0, ExtraBenchmarkAttrs) return benchmark
python
def get_benchmark_from_name(root, name, extra_params=None): if '-' in name: try: name, param_idx = name.split('-', 1) param_idx = int(param_idx) except ValueError: raise ValueError("Benchmark id %r is invalid" % (name,)) else: param_idx = None update_sys_path(root) benchmark = None # try to directly import benchmark function by guessing its import module # name parts = name.split('.') for i in [1, 2]: path = os.path.join(root, *parts[:-i]) + '.py' if not os.path.isfile(path): continue modname = '.'.join([os.path.basename(root)] + parts[:-i]) module = import_module(modname) try: module_attr = getattr(module, parts[-i]) except AttributeError: break if i == 1 and inspect.isfunction(module_attr): benchmark = _get_benchmark(parts[-i], module, None, module_attr) break elif i == 2 and inspect.isclass(module_attr): try: class_attr = getattr(module_attr, parts[-1]) except AttributeError: break if (inspect.isfunction(class_attr) or inspect.ismethod(class_attr)): benchmark = _get_benchmark(parts[-1], module, module_attr, class_attr) break if benchmark is None: for benchmark in disc_benchmarks(root): if benchmark.name == name: break else: raise ValueError( "Could not find benchmark '{0}'".format(name)) if param_idx is not None: benchmark.set_param_idx(param_idx) if extra_params: class ExtraBenchmarkAttrs: pass for key, value in extra_params.items(): setattr(ExtraBenchmarkAttrs, key, value) benchmark._attr_sources.insert(0, ExtraBenchmarkAttrs) return benchmark
[ "def", "get_benchmark_from_name", "(", "root", ",", "name", ",", "extra_params", "=", "None", ")", ":", "if", "'-'", "in", "name", ":", "try", ":", "name", ",", "param_idx", "=", "name", ".", "split", "(", "'-'", ",", "1", ")", "param_idx", "=", "int...
Create a benchmark from a fully-qualified benchmark name. Parameters ---------- root : str Path to the root of a benchmark suite. name : str Fully-qualified name to a specific benchmark.
[ "Create", "a", "benchmark", "from", "a", "fully", "-", "qualified", "benchmark", "name", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/benchmark.py#L892-L962
230,907
airspeed-velocity/asv
asv/benchmark.py
list_benchmarks
def list_benchmarks(root, fp): """ List all of the discovered benchmarks to fp as JSON. """ update_sys_path(root) # Streaming of JSON back out to the master process fp.write('[') first = True for benchmark in disc_benchmarks(root): if not first: fp.write(', ') clean = dict( (k, v) for (k, v) in benchmark.__dict__.items() if isinstance(v, (str, int, float, list, dict, bool)) and not k.startswith('_')) json.dump(clean, fp, skipkeys=True) first = False fp.write(']')
python
def list_benchmarks(root, fp): update_sys_path(root) # Streaming of JSON back out to the master process fp.write('[') first = True for benchmark in disc_benchmarks(root): if not first: fp.write(', ') clean = dict( (k, v) for (k, v) in benchmark.__dict__.items() if isinstance(v, (str, int, float, list, dict, bool)) and not k.startswith('_')) json.dump(clean, fp, skipkeys=True) first = False fp.write(']')
[ "def", "list_benchmarks", "(", "root", ",", "fp", ")", ":", "update_sys_path", "(", "root", ")", "# Streaming of JSON back out to the master process", "fp", ".", "write", "(", "'['", ")", "first", "=", "True", "for", "benchmark", "in", "disc_benchmarks", "(", "r...
List all of the discovered benchmarks to fp as JSON.
[ "List", "all", "of", "the", "discovered", "benchmarks", "to", "fp", "as", "JSON", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/benchmark.py#L965-L984
230,908
airspeed-velocity/asv
asv/benchmark.py
Benchmark.insert_param
def insert_param(self, param): """ Insert a parameter at the front of the parameter list. """ self._current_params = tuple([param] + list(self._current_params))
python
def insert_param(self, param): self._current_params = tuple([param] + list(self._current_params))
[ "def", "insert_param", "(", "self", ",", "param", ")", ":", "self", ".", "_current_params", "=", "tuple", "(", "[", "param", "]", "+", "list", "(", "self", ".", "_current_params", ")", ")" ]
Insert a parameter at the front of the parameter list.
[ "Insert", "a", "parameter", "at", "the", "front", "of", "the", "parameter", "list", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/benchmark.py#L462-L466
230,909
airspeed-velocity/asv
asv/build_cache.py
BuildCache._get_cache_dir
def _get_cache_dir(self, commit_hash): """ Get the cache dir and timestamp file corresponding to a given commit hash. """ path = os.path.join(self._path, commit_hash) stamp = path + ".timestamp" return path, stamp
python
def _get_cache_dir(self, commit_hash): path = os.path.join(self._path, commit_hash) stamp = path + ".timestamp" return path, stamp
[ "def", "_get_cache_dir", "(", "self", ",", "commit_hash", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_path", ",", "commit_hash", ")", "stamp", "=", "path", "+", "\".timestamp\"", "return", "path", ",", "stamp" ]
Get the cache dir and timestamp file corresponding to a given commit hash.
[ "Get", "the", "cache", "dir", "and", "timestamp", "file", "corresponding", "to", "a", "given", "commit", "hash", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/build_cache.py#L41-L47
230,910
airspeed-velocity/asv
asv/feed.py
write_atom
def write_atom(dest, entries, author, title, address, updated=None, link=None, language="en"): """ Write an atom feed to a file. Parameters ---------- dest : str Destination file path, or a file-like object entries : list of FeedEntry Feed entries. author : str Author of the feed. title : str Title for the feed. address : str Address (domain name or email) to be used in building unique IDs. updated : datetime, optional Time stamp for the feed. If not given, take from the newest entry. link : str, optional Link for the feed. language : str, optional Language of the feed. Default is 'en'. """ if updated is None: if entries: updated = max(entry.updated for entry in entries) else: updated = datetime.datetime.utcnow() root = etree.Element(ATOM_NS + 'feed') # id (obligatory) el = etree.Element(ATOM_NS + 'id') el.text = _get_id(address, None, ["feed", author, title]) root.append(el) # author (obligatory) el = etree.Element(ATOM_NS + 'author') el2 = etree.Element(ATOM_NS + 'name') el2.text = author el.append(el2) root.append(el) # title (obligatory) el = etree.Element(ATOM_NS + 'title') el.attrib[XML_NS + 'lang'] = language el.text = title root.append(el) # updated (obligatory) el = etree.Element(ATOM_NS + 'updated') el.text = updated.strftime('%Y-%m-%dT%H:%M:%SZ') root.append(el) # link if link is not None: el = etree.Element(ATOM_NS + 'link') el.attrib[ATOM_NS + 'href'] = link root.append(el) # entries for entry in entries: root.append(entry.get_atom(address, language)) tree = etree.ElementTree(root) def write(f): if sys.version_info[:2] < (2, 7): _etree_py26_write(f, tree) else: tree.write(f, xml_declaration=True, default_namespace=ATOM_NS[1:-1], encoding=str('utf-8')) if hasattr(dest, 'write'): write(dest) else: with util.long_path_open(dest, 'wb') as f: write(f)
python
def write_atom(dest, entries, author, title, address, updated=None, link=None, language="en"): if updated is None: if entries: updated = max(entry.updated for entry in entries) else: updated = datetime.datetime.utcnow() root = etree.Element(ATOM_NS + 'feed') # id (obligatory) el = etree.Element(ATOM_NS + 'id') el.text = _get_id(address, None, ["feed", author, title]) root.append(el) # author (obligatory) el = etree.Element(ATOM_NS + 'author') el2 = etree.Element(ATOM_NS + 'name') el2.text = author el.append(el2) root.append(el) # title (obligatory) el = etree.Element(ATOM_NS + 'title') el.attrib[XML_NS + 'lang'] = language el.text = title root.append(el) # updated (obligatory) el = etree.Element(ATOM_NS + 'updated') el.text = updated.strftime('%Y-%m-%dT%H:%M:%SZ') root.append(el) # link if link is not None: el = etree.Element(ATOM_NS + 'link') el.attrib[ATOM_NS + 'href'] = link root.append(el) # entries for entry in entries: root.append(entry.get_atom(address, language)) tree = etree.ElementTree(root) def write(f): if sys.version_info[:2] < (2, 7): _etree_py26_write(f, tree) else: tree.write(f, xml_declaration=True, default_namespace=ATOM_NS[1:-1], encoding=str('utf-8')) if hasattr(dest, 'write'): write(dest) else: with util.long_path_open(dest, 'wb') as f: write(f)
[ "def", "write_atom", "(", "dest", ",", "entries", ",", "author", ",", "title", ",", "address", ",", "updated", "=", "None", ",", "link", "=", "None", ",", "language", "=", "\"en\"", ")", ":", "if", "updated", "is", "None", ":", "if", "entries", ":", ...
Write an atom feed to a file. Parameters ---------- dest : str Destination file path, or a file-like object entries : list of FeedEntry Feed entries. author : str Author of the feed. title : str Title for the feed. address : str Address (domain name or email) to be used in building unique IDs. updated : datetime, optional Time stamp for the feed. If not given, take from the newest entry. link : str, optional Link for the feed. language : str, optional Language of the feed. Default is 'en'.
[ "Write", "an", "atom", "feed", "to", "a", "file", "." ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/feed.py#L89-L169
230,911
airspeed-velocity/asv
asv/feed.py
_etree_py26_write
def _etree_py26_write(f, tree): """ Compatibility workaround for ElementTree shipped with py2.6 """ f.write("<?xml version='1.0' encoding='utf-8'?>\n".encode('utf-8')) if etree.VERSION[:3] == '1.2': def fixtag(tag, namespaces): if tag == XML_NS + 'lang': return 'xml:lang', "" if '}' in tag: j = tag.index('}') + 1 tag = tag[j:] xmlns = '' if tag == 'feed': xmlns = ('xmlns', str('http://www.w3.org/2005/Atom')) namespaces['http://www.w3.org/2005/Atom'] = 'xmlns' return tag, xmlns else: fixtag = etree.fixtag old_fixtag = etree.fixtag etree.fixtag = fixtag try: tree.write(f, encoding=str('utf-8')) finally: etree.fixtag = old_fixtag
python
def _etree_py26_write(f, tree): f.write("<?xml version='1.0' encoding='utf-8'?>\n".encode('utf-8')) if etree.VERSION[:3] == '1.2': def fixtag(tag, namespaces): if tag == XML_NS + 'lang': return 'xml:lang', "" if '}' in tag: j = tag.index('}') + 1 tag = tag[j:] xmlns = '' if tag == 'feed': xmlns = ('xmlns', str('http://www.w3.org/2005/Atom')) namespaces['http://www.w3.org/2005/Atom'] = 'xmlns' return tag, xmlns else: fixtag = etree.fixtag old_fixtag = etree.fixtag etree.fixtag = fixtag try: tree.write(f, encoding=str('utf-8')) finally: etree.fixtag = old_fixtag
[ "def", "_etree_py26_write", "(", "f", ",", "tree", ")", ":", "f", ".", "write", "(", "\"<?xml version='1.0' encoding='utf-8'?>\\n\"", ".", "encode", "(", "'utf-8'", ")", ")", "if", "etree", ".", "VERSION", "[", ":", "3", "]", "==", "'1.2'", ":", "def", "...
Compatibility workaround for ElementTree shipped with py2.6
[ "Compatibility", "workaround", "for", "ElementTree", "shipped", "with", "py2", ".", "6" ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/feed.py#L172-L198
230,912
airspeed-velocity/asv
asv/feed.py
_get_id
def _get_id(owner, date, content): """ Generate an unique Atom id for the given content """ h = hashlib.sha256() # Hash still contains the original project url, keep as is h.update("github.com/spacetelescope/asv".encode('utf-8')) for x in content: if x is None: h.update(",".encode('utf-8')) else: h.update(x.encode('utf-8')) h.update(",".encode('utf-8')) if date is None: date = datetime.datetime(1970, 1, 1) return "tag:{0},{1}:/{2}".format(owner, date.strftime('%Y-%m-%d'), h.hexdigest())
python
def _get_id(owner, date, content): h = hashlib.sha256() # Hash still contains the original project url, keep as is h.update("github.com/spacetelescope/asv".encode('utf-8')) for x in content: if x is None: h.update(",".encode('utf-8')) else: h.update(x.encode('utf-8')) h.update(",".encode('utf-8')) if date is None: date = datetime.datetime(1970, 1, 1) return "tag:{0},{1}:/{2}".format(owner, date.strftime('%Y-%m-%d'), h.hexdigest())
[ "def", "_get_id", "(", "owner", ",", "date", ",", "content", ")", ":", "h", "=", "hashlib", ".", "sha256", "(", ")", "# Hash still contains the original project url, keep as is", "h", ".", "update", "(", "\"github.com/spacetelescope/asv\"", ".", "encode", "(", "'u...
Generate an unique Atom id for the given content
[ "Generate", "an", "unique", "Atom", "id", "for", "the", "given", "content" ]
d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/feed.py#L201-L217
230,913
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/gcp_hub_client.py
GcpHubClient.InitializeDebuggeeLabels
def InitializeDebuggeeLabels(self, flags): """Initialize debuggee labels from environment variables and flags. The caller passes all the flags that the the debuglet got. This function will only use the flags used to label the debuggee. Flags take precedence over environment variables. Debuggee description is formatted from available flags. Args: flags: dictionary of debuglet command line flags. """ self._debuggee_labels = {} for (label, var_names) in six.iteritems(_DEBUGGEE_LABELS): # var_names is a list of possible environment variables that may contain # the label value. Find the first one that is set. for name in var_names: value = os.environ.get(name) if value: # Special case for module. We omit the "default" module # to stay consistent with AppEngine. if label == labels.Debuggee.MODULE and value == 'default': break self._debuggee_labels[label] = value break if flags: self._debuggee_labels.update( {name: value for (name, value) in six.iteritems(flags) if name in _DEBUGGEE_LABELS}) self._debuggee_labels['projectid'] = self._project_id
python
def InitializeDebuggeeLabels(self, flags): self._debuggee_labels = {} for (label, var_names) in six.iteritems(_DEBUGGEE_LABELS): # var_names is a list of possible environment variables that may contain # the label value. Find the first one that is set. for name in var_names: value = os.environ.get(name) if value: # Special case for module. We omit the "default" module # to stay consistent with AppEngine. if label == labels.Debuggee.MODULE and value == 'default': break self._debuggee_labels[label] = value break if flags: self._debuggee_labels.update( {name: value for (name, value) in six.iteritems(flags) if name in _DEBUGGEE_LABELS}) self._debuggee_labels['projectid'] = self._project_id
[ "def", "InitializeDebuggeeLabels", "(", "self", ",", "flags", ")", ":", "self", ".", "_debuggee_labels", "=", "{", "}", "for", "(", "label", ",", "var_names", ")", "in", "six", ".", "iteritems", "(", "_DEBUGGEE_LABELS", ")", ":", "# var_names is a list of poss...
Initialize debuggee labels from environment variables and flags. The caller passes all the flags that the the debuglet got. This function will only use the flags used to label the debuggee. Flags take precedence over environment variables. Debuggee description is formatted from available flags. Args: flags: dictionary of debuglet command line flags.
[ "Initialize", "debuggee", "labels", "from", "environment", "variables", "and", "flags", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/gcp_hub_client.py#L146-L178
230,914
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/gcp_hub_client.py
GcpHubClient.SetupAuth
def SetupAuth(self, project_id=None, project_number=None, service_account_json_file=None): """Sets up authentication with Google APIs. This will use the credentials from service_account_json_file if provided, falling back to application default credentials. See https://cloud.google.com/docs/authentication/production. Args: project_id: GCP project ID (e.g. myproject). If not provided, will attempt to retrieve it from the credentials. project_number: GCP project number (e.g. 72386324623). If not provided, project_id will be used in its place. service_account_json_file: JSON file to use for credentials. If not provided, will default to application default credentials. Raises: NoProjectIdError: If the project id cannot be determined. """ if service_account_json_file: self._credentials = ( service_account.Credentials.from_service_account_file( service_account_json_file, scopes=_CLOUD_PLATFORM_SCOPE)) if not project_id: with open(service_account_json_file) as f: project_id = json.load(f).get('project_id') else: self._credentials, credentials_project_id = google.auth.default( scopes=_CLOUD_PLATFORM_SCOPE) project_id = project_id or credentials_project_id if not project_id: raise NoProjectIdError( 'Unable to determine the project id from the API credentials. ' 'Please specify the project id using the --project_id flag.') self._project_id = project_id self._project_number = project_number or project_id
python
def SetupAuth(self, project_id=None, project_number=None, service_account_json_file=None): if service_account_json_file: self._credentials = ( service_account.Credentials.from_service_account_file( service_account_json_file, scopes=_CLOUD_PLATFORM_SCOPE)) if not project_id: with open(service_account_json_file) as f: project_id = json.load(f).get('project_id') else: self._credentials, credentials_project_id = google.auth.default( scopes=_CLOUD_PLATFORM_SCOPE) project_id = project_id or credentials_project_id if not project_id: raise NoProjectIdError( 'Unable to determine the project id from the API credentials. ' 'Please specify the project id using the --project_id flag.') self._project_id = project_id self._project_number = project_number or project_id
[ "def", "SetupAuth", "(", "self", ",", "project_id", "=", "None", ",", "project_number", "=", "None", ",", "service_account_json_file", "=", "None", ")", ":", "if", "service_account_json_file", ":", "self", ".", "_credentials", "=", "(", "service_account", ".", ...
Sets up authentication with Google APIs. This will use the credentials from service_account_json_file if provided, falling back to application default credentials. See https://cloud.google.com/docs/authentication/production. Args: project_id: GCP project ID (e.g. myproject). If not provided, will attempt to retrieve it from the credentials. project_number: GCP project number (e.g. 72386324623). If not provided, project_id will be used in its place. service_account_json_file: JSON file to use for credentials. If not provided, will default to application default credentials. Raises: NoProjectIdError: If the project id cannot be determined.
[ "Sets", "up", "authentication", "with", "Google", "APIs", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/gcp_hub_client.py#L180-L218
230,915
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/gcp_hub_client.py
GcpHubClient.Start
def Start(self): """Starts the worker thread.""" self._shutdown = False self._main_thread = threading.Thread(target=self._MainThreadProc) self._main_thread.name = 'Cloud Debugger main worker thread' self._main_thread.daemon = True self._main_thread.start()
python
def Start(self): self._shutdown = False self._main_thread = threading.Thread(target=self._MainThreadProc) self._main_thread.name = 'Cloud Debugger main worker thread' self._main_thread.daemon = True self._main_thread.start()
[ "def", "Start", "(", "self", ")", ":", "self", ".", "_shutdown", "=", "False", "self", ".", "_main_thread", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "_MainThreadProc", ")", "self", ".", "_main_thread", ".", "name", "=", "'Cloud D...
Starts the worker thread.
[ "Starts", "the", "worker", "thread", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/gcp_hub_client.py#L220-L227
230,916
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/gcp_hub_client.py
GcpHubClient.Stop
def Stop(self): """Signals the worker threads to shut down and waits until it exits.""" self._shutdown = True self._new_updates.set() # Wake up the transmission thread. if self._main_thread is not None: self._main_thread.join() self._main_thread = None if self._transmission_thread is not None: self._transmission_thread.join() self._transmission_thread = None
python
def Stop(self): self._shutdown = True self._new_updates.set() # Wake up the transmission thread. if self._main_thread is not None: self._main_thread.join() self._main_thread = None if self._transmission_thread is not None: self._transmission_thread.join() self._transmission_thread = None
[ "def", "Stop", "(", "self", ")", ":", "self", ".", "_shutdown", "=", "True", "self", ".", "_new_updates", ".", "set", "(", ")", "# Wake up the transmission thread.", "if", "self", ".", "_main_thread", "is", "not", "None", ":", "self", ".", "_main_thread", ...
Signals the worker threads to shut down and waits until it exits.
[ "Signals", "the", "worker", "threads", "to", "shut", "down", "and", "waits", "until", "it", "exits", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/gcp_hub_client.py#L229-L240
230,917
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/gcp_hub_client.py
GcpHubClient.EnqueueBreakpointUpdate
def EnqueueBreakpointUpdate(self, breakpoint): """Asynchronously updates the specified breakpoint on the backend. This function returns immediately. The worker thread is actually doing all the work. The worker thread is responsible to retry the transmission in case of transient errors. Args: breakpoint: breakpoint in either final or non-final state. """ with self._transmission_thread_startup_lock: if self._transmission_thread is None: self._transmission_thread = threading.Thread( target=self._TransmissionThreadProc) self._transmission_thread.name = 'Cloud Debugger transmission thread' self._transmission_thread.daemon = True self._transmission_thread.start() self._transmission_queue.append((breakpoint, 0)) self._new_updates.set()
python
def EnqueueBreakpointUpdate(self, breakpoint): with self._transmission_thread_startup_lock: if self._transmission_thread is None: self._transmission_thread = threading.Thread( target=self._TransmissionThreadProc) self._transmission_thread.name = 'Cloud Debugger transmission thread' self._transmission_thread.daemon = True self._transmission_thread.start() self._transmission_queue.append((breakpoint, 0)) self._new_updates.set()
[ "def", "EnqueueBreakpointUpdate", "(", "self", ",", "breakpoint", ")", ":", "with", "self", ".", "_transmission_thread_startup_lock", ":", "if", "self", ".", "_transmission_thread", "is", "None", ":", "self", ".", "_transmission_thread", "=", "threading", ".", "Th...
Asynchronously updates the specified breakpoint on the backend. This function returns immediately. The worker thread is actually doing all the work. The worker thread is responsible to retry the transmission in case of transient errors. Args: breakpoint: breakpoint in either final or non-final state.
[ "Asynchronously", "updates", "the", "specified", "breakpoint", "on", "the", "backend", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/gcp_hub_client.py#L242-L261
230,918
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/gcp_hub_client.py
GcpHubClient._MainThreadProc
def _MainThreadProc(self): """Entry point for the worker thread.""" registration_required = True while not self._shutdown: if registration_required: service = self._BuildService() registration_required, delay = self._RegisterDebuggee(service) if not registration_required: registration_required, delay = self._ListActiveBreakpoints(service) if self.on_idle is not None: self.on_idle() if not self._shutdown: time.sleep(delay)
python
def _MainThreadProc(self): registration_required = True while not self._shutdown: if registration_required: service = self._BuildService() registration_required, delay = self._RegisterDebuggee(service) if not registration_required: registration_required, delay = self._ListActiveBreakpoints(service) if self.on_idle is not None: self.on_idle() if not self._shutdown: time.sleep(delay)
[ "def", "_MainThreadProc", "(", "self", ")", ":", "registration_required", "=", "True", "while", "not", "self", ".", "_shutdown", ":", "if", "registration_required", ":", "service", "=", "self", ".", "_BuildService", "(", ")", "registration_required", ",", "delay...
Entry point for the worker thread.
[ "Entry", "point", "for", "the", "worker", "thread", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/gcp_hub_client.py#L271-L286
230,919
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/gcp_hub_client.py
GcpHubClient._TransmissionThreadProc
def _TransmissionThreadProc(self): """Entry point for the transmission worker thread.""" reconnect = True while not self._shutdown: self._new_updates.clear() if reconnect: service = self._BuildService() reconnect = False reconnect, delay = self._TransmitBreakpointUpdates(service) self._new_updates.wait(delay)
python
def _TransmissionThreadProc(self): reconnect = True while not self._shutdown: self._new_updates.clear() if reconnect: service = self._BuildService() reconnect = False reconnect, delay = self._TransmitBreakpointUpdates(service) self._new_updates.wait(delay)
[ "def", "_TransmissionThreadProc", "(", "self", ")", ":", "reconnect", "=", "True", "while", "not", "self", ".", "_shutdown", ":", "self", ".", "_new_updates", ".", "clear", "(", ")", "if", "reconnect", ":", "service", "=", "self", ".", "_BuildService", "("...
Entry point for the transmission worker thread.
[ "Entry", "point", "for", "the", "transmission", "worker", "thread", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/gcp_hub_client.py#L288-L301
230,920
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/gcp_hub_client.py
GcpHubClient._RegisterDebuggee
def _RegisterDebuggee(self, service): """Single attempt to register the debuggee. If the registration succeeds, sets self._debuggee_id to the registered debuggee ID. Args: service: client to use for API calls Returns: (registration_required, delay) tuple """ try: request = {'debuggee': self._GetDebuggee()} try: response = service.debuggees().register(body=request).execute() # self._project_number will refer to the project id on initialization if # the project number is not available. The project field in the debuggee # will always refer to the project number. Update so the server will not # have to do id->number translations in the future. project_number = response['debuggee'].get('project') self._project_number = project_number or self._project_number self._debuggee_id = response['debuggee']['id'] native.LogInfo('Debuggee registered successfully, ID: %s' % ( self._debuggee_id)) self.register_backoff.Succeeded() return (False, 0) # Proceed immediately to list active breakpoints. except BaseException: native.LogInfo('Failed to register debuggee: %s, %s' % (request, traceback.format_exc())) except BaseException: native.LogWarning('Debuggee information not available: ' + traceback.format_exc()) return (True, self.register_backoff.Failed())
python
def _RegisterDebuggee(self, service): try: request = {'debuggee': self._GetDebuggee()} try: response = service.debuggees().register(body=request).execute() # self._project_number will refer to the project id on initialization if # the project number is not available. The project field in the debuggee # will always refer to the project number. Update so the server will not # have to do id->number translations in the future. project_number = response['debuggee'].get('project') self._project_number = project_number or self._project_number self._debuggee_id = response['debuggee']['id'] native.LogInfo('Debuggee registered successfully, ID: %s' % ( self._debuggee_id)) self.register_backoff.Succeeded() return (False, 0) # Proceed immediately to list active breakpoints. except BaseException: native.LogInfo('Failed to register debuggee: %s, %s' % (request, traceback.format_exc())) except BaseException: native.LogWarning('Debuggee information not available: ' + traceback.format_exc()) return (True, self.register_backoff.Failed())
[ "def", "_RegisterDebuggee", "(", "self", ",", "service", ")", ":", "try", ":", "request", "=", "{", "'debuggee'", ":", "self", ".", "_GetDebuggee", "(", ")", "}", "try", ":", "response", "=", "service", ".", "debuggees", "(", ")", ".", "register", "(",...
Single attempt to register the debuggee. If the registration succeeds, sets self._debuggee_id to the registered debuggee ID. Args: service: client to use for API calls Returns: (registration_required, delay) tuple
[ "Single", "attempt", "to", "register", "the", "debuggee", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/gcp_hub_client.py#L303-L340
230,921
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/gcp_hub_client.py
GcpHubClient._ListActiveBreakpoints
def _ListActiveBreakpoints(self, service): """Single attempt query the list of active breakpoints. Must not be called before the debuggee has been registered. If the request fails, this function resets self._debuggee_id, which triggers repeated debuggee registration. Args: service: client to use for API calls Returns: (registration_required, delay) tuple """ try: response = service.debuggees().breakpoints().list( debuggeeId=self._debuggee_id, waitToken=self._wait_token, successOnTimeout=True).execute() if not response.get('waitExpired'): self._wait_token = response.get('nextWaitToken') breakpoints = response.get('breakpoints') or [] if self._breakpoints != breakpoints: self._breakpoints = breakpoints native.LogInfo( 'Breakpoints list changed, %d active, wait token: %s' % ( len(self._breakpoints), self._wait_token)) self.on_active_breakpoints_changed(copy.deepcopy(self._breakpoints)) except BaseException: native.LogInfo('Failed to query active breakpoints: ' + traceback.format_exc()) # Forget debuggee ID to trigger repeated debuggee registration. Once the # registration succeeds, the worker thread will retry this query self._debuggee_id = None return (True, self.list_backoff.Failed()) self.list_backoff.Succeeded() return (False, 0)
python
def _ListActiveBreakpoints(self, service): try: response = service.debuggees().breakpoints().list( debuggeeId=self._debuggee_id, waitToken=self._wait_token, successOnTimeout=True).execute() if not response.get('waitExpired'): self._wait_token = response.get('nextWaitToken') breakpoints = response.get('breakpoints') or [] if self._breakpoints != breakpoints: self._breakpoints = breakpoints native.LogInfo( 'Breakpoints list changed, %d active, wait token: %s' % ( len(self._breakpoints), self._wait_token)) self.on_active_breakpoints_changed(copy.deepcopy(self._breakpoints)) except BaseException: native.LogInfo('Failed to query active breakpoints: ' + traceback.format_exc()) # Forget debuggee ID to trigger repeated debuggee registration. Once the # registration succeeds, the worker thread will retry this query self._debuggee_id = None return (True, self.list_backoff.Failed()) self.list_backoff.Succeeded() return (False, 0)
[ "def", "_ListActiveBreakpoints", "(", "self", ",", "service", ")", ":", "try", ":", "response", "=", "service", ".", "debuggees", "(", ")", ".", "breakpoints", "(", ")", ".", "list", "(", "debuggeeId", "=", "self", ".", "_debuggee_id", ",", "waitToken", ...
Single attempt query the list of active breakpoints. Must not be called before the debuggee has been registered. If the request fails, this function resets self._debuggee_id, which triggers repeated debuggee registration. Args: service: client to use for API calls Returns: (registration_required, delay) tuple
[ "Single", "attempt", "query", "the", "list", "of", "active", "breakpoints", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/gcp_hub_client.py#L342-L379
230,922
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/gcp_hub_client.py
GcpHubClient._TransmitBreakpointUpdates
def _TransmitBreakpointUpdates(self, service): """Tries to send pending breakpoint updates to the backend. Sends all the pending breakpoint updates. In case of transient failures, the breakpoint is inserted back to the top of the queue. Application failures are not retried (for example updating breakpoint in a final state). Each pending breakpoint maintains a retry counter. After repeated transient failures the breakpoint is discarded and dropped from the queue. Args: service: client to use for API calls Returns: (reconnect, timeout) tuple. The first element ("reconnect") is set to true on unexpected HTTP responses. The caller should discard the HTTP connection and create a new one. The second element ("timeout") is set to None if all pending breakpoints were sent successfully. Otherwise returns time interval in seconds to stall before retrying. """ reconnect = False retry_list = [] # There is only one consumer, so two step pop is safe. while self._transmission_queue: breakpoint, retry_count = self._transmission_queue.popleft() try: service.debuggees().breakpoints().update( debuggeeId=self._debuggee_id, id=breakpoint['id'], body={'breakpoint': breakpoint}).execute() native.LogInfo('Breakpoint %s update transmitted successfully' % ( breakpoint['id'])) except apiclient.errors.HttpError as err: # Treat 400 error codes (except timeout) as application error that will # not be retried. All other errors are assumed to be transient. status = err.resp.status is_transient = ((status >= 500) or (status == 408)) if is_transient and retry_count < self.max_transmit_attempts - 1: native.LogInfo('Failed to send breakpoint %s update: %s' % ( breakpoint['id'], traceback.format_exc())) retry_list.append((breakpoint, retry_count + 1)) elif is_transient: native.LogWarning( 'Breakpoint %s retry count exceeded maximum' % breakpoint['id']) else: # This is very common if multiple instances are sending final update # simultaneously. native.LogInfo('%s, breakpoint: %s' % (err, breakpoint['id'])) except BaseException: native.LogWarning( 'Fatal error sending breakpoint %s update: %s' % ( breakpoint['id'], traceback.format_exc())) reconnect = True self._transmission_queue.extend(retry_list) if not self._transmission_queue: self.update_backoff.Succeeded() # Nothing to send, wait until next breakpoint update. return (reconnect, None) else: return (reconnect, self.update_backoff.Failed())
python
def _TransmitBreakpointUpdates(self, service): reconnect = False retry_list = [] # There is only one consumer, so two step pop is safe. while self._transmission_queue: breakpoint, retry_count = self._transmission_queue.popleft() try: service.debuggees().breakpoints().update( debuggeeId=self._debuggee_id, id=breakpoint['id'], body={'breakpoint': breakpoint}).execute() native.LogInfo('Breakpoint %s update transmitted successfully' % ( breakpoint['id'])) except apiclient.errors.HttpError as err: # Treat 400 error codes (except timeout) as application error that will # not be retried. All other errors are assumed to be transient. status = err.resp.status is_transient = ((status >= 500) or (status == 408)) if is_transient and retry_count < self.max_transmit_attempts - 1: native.LogInfo('Failed to send breakpoint %s update: %s' % ( breakpoint['id'], traceback.format_exc())) retry_list.append((breakpoint, retry_count + 1)) elif is_transient: native.LogWarning( 'Breakpoint %s retry count exceeded maximum' % breakpoint['id']) else: # This is very common if multiple instances are sending final update # simultaneously. native.LogInfo('%s, breakpoint: %s' % (err, breakpoint['id'])) except BaseException: native.LogWarning( 'Fatal error sending breakpoint %s update: %s' % ( breakpoint['id'], traceback.format_exc())) reconnect = True self._transmission_queue.extend(retry_list) if not self._transmission_queue: self.update_backoff.Succeeded() # Nothing to send, wait until next breakpoint update. return (reconnect, None) else: return (reconnect, self.update_backoff.Failed())
[ "def", "_TransmitBreakpointUpdates", "(", "self", ",", "service", ")", ":", "reconnect", "=", "False", "retry_list", "=", "[", "]", "# There is only one consumer, so two step pop is safe.", "while", "self", ".", "_transmission_queue", ":", "breakpoint", ",", "retry_coun...
Tries to send pending breakpoint updates to the backend. Sends all the pending breakpoint updates. In case of transient failures, the breakpoint is inserted back to the top of the queue. Application failures are not retried (for example updating breakpoint in a final state). Each pending breakpoint maintains a retry counter. After repeated transient failures the breakpoint is discarded and dropped from the queue. Args: service: client to use for API calls Returns: (reconnect, timeout) tuple. The first element ("reconnect") is set to true on unexpected HTTP responses. The caller should discard the HTTP connection and create a new one. The second element ("timeout") is set to None if all pending breakpoints were sent successfully. Otherwise returns time interval in seconds to stall before retrying.
[ "Tries", "to", "send", "pending", "breakpoint", "updates", "to", "the", "backend", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/gcp_hub_client.py#L381-L445
230,923
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/gcp_hub_client.py
GcpHubClient._GetDebuggee
def _GetDebuggee(self): """Builds the debuggee structure.""" major_version = 'v' + version.__version__.split('.')[0] python_version = ''.join(platform.python_version().split('.')[:2]) agent_version = ('google.com/python%s-gcp/%s' % (python_version, major_version)) debuggee = { 'project': self._project_number, 'description': self._GetDebuggeeDescription(), 'labels': self._debuggee_labels, 'agentVersion': agent_version, } source_context = self._ReadAppJsonFile('source-context.json') if source_context: debuggee['sourceContexts'] = [source_context] debuggee['uniquifier'] = self._ComputeUniquifier(debuggee) return debuggee
python
def _GetDebuggee(self): major_version = 'v' + version.__version__.split('.')[0] python_version = ''.join(platform.python_version().split('.')[:2]) agent_version = ('google.com/python%s-gcp/%s' % (python_version, major_version)) debuggee = { 'project': self._project_number, 'description': self._GetDebuggeeDescription(), 'labels': self._debuggee_labels, 'agentVersion': agent_version, } source_context = self._ReadAppJsonFile('source-context.json') if source_context: debuggee['sourceContexts'] = [source_context] debuggee['uniquifier'] = self._ComputeUniquifier(debuggee) return debuggee
[ "def", "_GetDebuggee", "(", "self", ")", ":", "major_version", "=", "'v'", "+", "version", ".", "__version__", ".", "split", "(", "'.'", ")", "[", "0", "]", "python_version", "=", "''", ".", "join", "(", "platform", ".", "python_version", "(", ")", "."...
Builds the debuggee structure.
[ "Builds", "the", "debuggee", "structure", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/gcp_hub_client.py#L447-L467
230,924
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/gcp_hub_client.py
GcpHubClient._GetDebuggeeDescription
def _GetDebuggeeDescription(self): """Formats debuggee description based on debuggee labels.""" return '-'.join(self._debuggee_labels[label] for label in _DESCRIPTION_LABELS if label in self._debuggee_labels)
python
def _GetDebuggeeDescription(self): return '-'.join(self._debuggee_labels[label] for label in _DESCRIPTION_LABELS if label in self._debuggee_labels)
[ "def", "_GetDebuggeeDescription", "(", "self", ")", ":", "return", "'-'", ".", "join", "(", "self", ".", "_debuggee_labels", "[", "label", "]", "for", "label", "in", "_DESCRIPTION_LABELS", "if", "label", "in", "self", ".", "_debuggee_labels", ")" ]
Formats debuggee description based on debuggee labels.
[ "Formats", "debuggee", "description", "based", "on", "debuggee", "labels", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/gcp_hub_client.py#L469-L473
230,925
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/gcp_hub_client.py
GcpHubClient._ComputeUniquifier
def _ComputeUniquifier(self, debuggee): """Computes debuggee uniquifier. The debuggee uniquifier has to be identical on all instances. Therefore the uniquifier should not include any random numbers and should only be based on inputs that are guaranteed to be the same on all instances. Args: debuggee: complete debuggee message without the uniquifier Returns: Hex string of SHA1 hash of project information, debuggee labels and debuglet version. """ uniquifier = hashlib.sha1() # Compute hash of application files if we don't have source context. This # way we can still distinguish between different deployments. if ('minorversion' not in debuggee.get('labels', []) and 'sourceContexts' not in debuggee): uniquifier_computer.ComputeApplicationUniquifier(uniquifier) return uniquifier.hexdigest()
python
def _ComputeUniquifier(self, debuggee): uniquifier = hashlib.sha1() # Compute hash of application files if we don't have source context. This # way we can still distinguish between different deployments. if ('minorversion' not in debuggee.get('labels', []) and 'sourceContexts' not in debuggee): uniquifier_computer.ComputeApplicationUniquifier(uniquifier) return uniquifier.hexdigest()
[ "def", "_ComputeUniquifier", "(", "self", ",", "debuggee", ")", ":", "uniquifier", "=", "hashlib", ".", "sha1", "(", ")", "# Compute hash of application files if we don't have source context. This", "# way we can still distinguish between different deployments.", "if", "(", "'m...
Computes debuggee uniquifier. The debuggee uniquifier has to be identical on all instances. Therefore the uniquifier should not include any random numbers and should only be based on inputs that are guaranteed to be the same on all instances. Args: debuggee: complete debuggee message without the uniquifier Returns: Hex string of SHA1 hash of project information, debuggee labels and debuglet version.
[ "Computes", "debuggee", "uniquifier", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/gcp_hub_client.py#L475-L497
230,926
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/gcp_hub_client.py
GcpHubClient._ReadAppJsonFile
def _ReadAppJsonFile(self, relative_path): """Reads JSON file from an application directory. Args: relative_path: file name relative to application root directory. Returns: Parsed JSON data or None if the file does not exist, can't be read or not a valid JSON file. """ try: with open(os.path.join(sys.path[0], relative_path), 'r') as f: return json.load(f) except (IOError, ValueError): return None
python
def _ReadAppJsonFile(self, relative_path): try: with open(os.path.join(sys.path[0], relative_path), 'r') as f: return json.load(f) except (IOError, ValueError): return None
[ "def", "_ReadAppJsonFile", "(", "self", ",", "relative_path", ")", ":", "try", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "sys", ".", "path", "[", "0", "]", ",", "relative_path", ")", ",", "'r'", ")", "as", "f", ":", "return", ...
Reads JSON file from an application directory. Args: relative_path: file name relative to application root directory. Returns: Parsed JSON data or None if the file does not exist, can't be read or not a valid JSON file.
[ "Reads", "JSON", "file", "from", "an", "application", "directory", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/gcp_hub_client.py#L499-L513
230,927
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/capture_collector.py
NormalizePath
def NormalizePath(path): """Removes any Python system path prefix from the given path. Python keeps almost all paths absolute. This is not what we actually want to return. This loops through system paths (directories in which Python will load modules). If "path" is relative to one of them, the directory prefix is removed. Args: path: absolute path to normalize (relative paths will not be altered) Returns: Relative path if "path" is within one of the sys.path directories or the input otherwise. """ path = os.path.normpath(path) for sys_path in sys.path: if not sys_path: continue # Append '/' at the end of the path if it's not there already. sys_path = os.path.join(sys_path, '') if path.startswith(sys_path): return path[len(sys_path):] return path
python
def NormalizePath(path): path = os.path.normpath(path) for sys_path in sys.path: if not sys_path: continue # Append '/' at the end of the path if it's not there already. sys_path = os.path.join(sys_path, '') if path.startswith(sys_path): return path[len(sys_path):] return path
[ "def", "NormalizePath", "(", "path", ")", ":", "path", "=", "os", ".", "path", ".", "normpath", "(", "path", ")", "for", "sys_path", "in", "sys", ".", "path", ":", "if", "not", "sys_path", ":", "continue", "# Append '/' at the end of the path if it's not there...
Removes any Python system path prefix from the given path. Python keeps almost all paths absolute. This is not what we actually want to return. This loops through system paths (directories in which Python will load modules). If "path" is relative to one of them, the directory prefix is removed. Args: path: absolute path to normalize (relative paths will not be altered) Returns: Relative path if "path" is within one of the sys.path directories or the input otherwise.
[ "Removes", "any", "Python", "system", "path", "prefix", "from", "the", "given", "path", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/capture_collector.py#L77-L104
230,928
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/capture_collector.py
DetermineType
def DetermineType(value): """Determines the type of val, returning a "full path" string. For example: DetermineType(5) -> __builtin__.int DetermineType(Foo()) -> com.google.bar.Foo Args: value: Any value, the value is irrelevant as only the type metadata is checked Returns: Type path string. None if type cannot be determined. """ object_type = type(value) if not hasattr(object_type, '__name__'): return None type_string = getattr(object_type, '__module__', '') if type_string: type_string += '.' type_string += object_type.__name__ return type_string
python
def DetermineType(value): object_type = type(value) if not hasattr(object_type, '__name__'): return None type_string = getattr(object_type, '__module__', '') if type_string: type_string += '.' type_string += object_type.__name__ return type_string
[ "def", "DetermineType", "(", "value", ")", ":", "object_type", "=", "type", "(", "value", ")", "if", "not", "hasattr", "(", "object_type", ",", "'__name__'", ")", ":", "return", "None", "type_string", "=", "getattr", "(", "object_type", ",", "'__module__'", ...
Determines the type of val, returning a "full path" string. For example: DetermineType(5) -> __builtin__.int DetermineType(Foo()) -> com.google.bar.Foo Args: value: Any value, the value is irrelevant as only the type metadata is checked Returns: Type path string. None if type cannot be determined.
[ "Determines", "the", "type", "of", "val", "returning", "a", "full", "path", "string", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/capture_collector.py#L107-L131
230,929
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/capture_collector.py
GetLoggingLocation
def GetLoggingLocation(): """Search for and return the file and line number from the log collector. Returns: (pathname, lineno, func_name) The full path, line number, and function name for the logpoint location. """ frame = inspect.currentframe() this_file = frame.f_code.co_filename frame = frame.f_back while frame: if this_file == frame.f_code.co_filename: if 'cdbg_logging_location' in frame.f_locals: ret = frame.f_locals['cdbg_logging_location'] if len(ret) != 3: return (None, None, None) return ret frame = frame.f_back return (None, None, None)
python
def GetLoggingLocation(): frame = inspect.currentframe() this_file = frame.f_code.co_filename frame = frame.f_back while frame: if this_file == frame.f_code.co_filename: if 'cdbg_logging_location' in frame.f_locals: ret = frame.f_locals['cdbg_logging_location'] if len(ret) != 3: return (None, None, None) return ret frame = frame.f_back return (None, None, None)
[ "def", "GetLoggingLocation", "(", ")", ":", "frame", "=", "inspect", ".", "currentframe", "(", ")", "this_file", "=", "frame", ".", "f_code", ".", "co_filename", "frame", "=", "frame", ".", "f_back", "while", "frame", ":", "if", "this_file", "==", "frame",...
Search for and return the file and line number from the log collector. Returns: (pathname, lineno, func_name) The full path, line number, and function name for the logpoint location.
[ "Search", "for", "and", "return", "the", "file", "and", "line", "number", "from", "the", "log", "collector", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/capture_collector.py#L157-L175
230,930
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/capture_collector.py
SetLogger
def SetLogger(logger): """Sets the logger object to use for all 'LOG' breakpoint actions.""" global log_info_message global log_warning_message global log_error_message log_info_message = logger.info log_warning_message = logger.warning log_error_message = logger.error logger.addFilter(LineNoFilter())
python
def SetLogger(logger): global log_info_message global log_warning_message global log_error_message log_info_message = logger.info log_warning_message = logger.warning log_error_message = logger.error logger.addFilter(LineNoFilter())
[ "def", "SetLogger", "(", "logger", ")", ":", "global", "log_info_message", "global", "log_warning_message", "global", "log_error_message", "log_info_message", "=", "logger", ".", "info", "log_warning_message", "=", "logger", ".", "warning", "log_error_message", "=", "...
Sets the logger object to use for all 'LOG' breakpoint actions.
[ "Sets", "the", "logger", "object", "to", "use", "for", "all", "LOG", "breakpoint", "actions", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/capture_collector.py#L178-L186
230,931
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/capture_collector.py
_EvaluateExpression
def _EvaluateExpression(frame, expression): """Compiles and evaluates watched expression. Args: frame: evaluation context. expression: watched expression to compile and evaluate. Returns: (False, status) on error or (True, value) on success. """ try: code = compile(expression, '<watched_expression>', 'eval') except (TypeError, ValueError) as e: # expression string contains null bytes. return (False, { 'isError': True, 'refersTo': 'VARIABLE_NAME', 'description': { 'format': 'Invalid expression', 'parameters': [str(e)]}}) except SyntaxError as e: return (False, { 'isError': True, 'refersTo': 'VARIABLE_NAME', 'description': { 'format': 'Expression could not be compiled: $0', 'parameters': [e.msg]}}) try: return (True, native.CallImmutable(frame, code)) except BaseException as e: # pylint: disable=broad-except return (False, { 'isError': True, 'refersTo': 'VARIABLE_VALUE', 'description': { 'format': 'Exception occurred: $0', 'parameters': [str(e)]}})
python
def _EvaluateExpression(frame, expression): try: code = compile(expression, '<watched_expression>', 'eval') except (TypeError, ValueError) as e: # expression string contains null bytes. return (False, { 'isError': True, 'refersTo': 'VARIABLE_NAME', 'description': { 'format': 'Invalid expression', 'parameters': [str(e)]}}) except SyntaxError as e: return (False, { 'isError': True, 'refersTo': 'VARIABLE_NAME', 'description': { 'format': 'Expression could not be compiled: $0', 'parameters': [e.msg]}}) try: return (True, native.CallImmutable(frame, code)) except BaseException as e: # pylint: disable=broad-except return (False, { 'isError': True, 'refersTo': 'VARIABLE_VALUE', 'description': { 'format': 'Exception occurred: $0', 'parameters': [str(e)]}})
[ "def", "_EvaluateExpression", "(", "frame", ",", "expression", ")", ":", "try", ":", "code", "=", "compile", "(", "expression", ",", "'<watched_expression>'", ",", "'eval'", ")", "except", "(", "TypeError", ",", "ValueError", ")", "as", "e", ":", "# expressi...
Compiles and evaluates watched expression. Args: frame: evaluation context. expression: watched expression to compile and evaluate. Returns: (False, status) on error or (True, value) on success.
[ "Compiles", "and", "evaluates", "watched", "expression", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/capture_collector.py#L855-L891
230,932
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/capture_collector.py
_GetFrameCodeObjectName
def _GetFrameCodeObjectName(frame): """Gets the code object name for the frame. Args: frame: the frame to get the name from Returns: The function name if the code is a static function or the class name with the method name if it is an member function. """ # This functions under the assumption that member functions will name their # first parameter argument 'self' but has some edge-cases. if frame.f_code.co_argcount >= 1 and 'self' == frame.f_code.co_varnames[0]: return (frame.f_locals['self'].__class__.__name__ + '.' + frame.f_code.co_name) else: return frame.f_code.co_name
python
def _GetFrameCodeObjectName(frame): # This functions under the assumption that member functions will name their # first parameter argument 'self' but has some edge-cases. if frame.f_code.co_argcount >= 1 and 'self' == frame.f_code.co_varnames[0]: return (frame.f_locals['self'].__class__.__name__ + '.' + frame.f_code.co_name) else: return frame.f_code.co_name
[ "def", "_GetFrameCodeObjectName", "(", "frame", ")", ":", "# This functions under the assumption that member functions will name their", "# first parameter argument 'self' but has some edge-cases.", "if", "frame", ".", "f_code", ".", "co_argcount", ">=", "1", "and", "'self'", "==...
Gets the code object name for the frame. Args: frame: the frame to get the name from Returns: The function name if the code is a static function or the class name with the method name if it is an member function.
[ "Gets", "the", "code", "object", "name", "for", "the", "frame", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/capture_collector.py#L894-L910
230,933
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/capture_collector.py
CaptureCollector.Collect
def Collect(self, top_frame): """Collects call stack, local variables and objects. Starts collection from the specified frame. We don't start from the top frame to exclude the frames due to debugger. Updates the content of self.breakpoint. Args: top_frame: top frame to start data collection. """ # Evaluate call stack. frame = top_frame top_line = self.breakpoint['location']['line'] breakpoint_frames = self.breakpoint['stackFrames'] try: # Evaluate watched expressions. if 'expressions' in self.breakpoint: self.breakpoint['evaluatedExpressions'] = [ self._CaptureExpression(top_frame, expression) for expression in self.breakpoint['expressions']] while frame and (len(breakpoint_frames) < self.max_frames): line = top_line if frame == top_frame else frame.f_lineno code = frame.f_code if len(breakpoint_frames) < self.max_expand_frames: frame_arguments, frame_locals = self.CaptureFrameLocals(frame) else: frame_arguments = [] frame_locals = [] breakpoint_frames.append({ 'function': _GetFrameCodeObjectName(frame), 'location': { 'path': NormalizePath(code.co_filename), 'line': line }, 'arguments': frame_arguments, 'locals': frame_locals }) frame = frame.f_back except BaseException as e: # pylint: disable=broad-except # The variable table will get serialized even though there was a failure. # The results can be useful for diagnosing the internal error. self.breakpoint['status'] = { 'isError': True, 'description': { 'format': ('INTERNAL ERROR: Failed while capturing locals ' 'of frame $0: $1'), 'parameters': [str(len(breakpoint_frames)), str(e)]}} # Number of entries in _var_table. Starts at 1 (index 0 is the 'buffer full' # status value). num_vars = 1 # Explore variables table in BFS fashion. The variables table will grow # inside CaptureVariable as we encounter new references. while (num_vars < len(self._var_table)) and ( self._total_size < self.max_size): self._var_table[num_vars] = self.CaptureVariable( self._var_table[num_vars], 0, self.default_capture_limits, can_enqueue=False) # Move on to the next entry in the variable table. num_vars += 1 # Trim variables table and change make all references to variables that # didn't make it point to var_index of 0 ("buffer full") self.TrimVariableTable(num_vars) self._CaptureEnvironmentLabels() self._CaptureRequestLogId() self._CaptureUserId()
python
def Collect(self, top_frame): # Evaluate call stack. frame = top_frame top_line = self.breakpoint['location']['line'] breakpoint_frames = self.breakpoint['stackFrames'] try: # Evaluate watched expressions. if 'expressions' in self.breakpoint: self.breakpoint['evaluatedExpressions'] = [ self._CaptureExpression(top_frame, expression) for expression in self.breakpoint['expressions']] while frame and (len(breakpoint_frames) < self.max_frames): line = top_line if frame == top_frame else frame.f_lineno code = frame.f_code if len(breakpoint_frames) < self.max_expand_frames: frame_arguments, frame_locals = self.CaptureFrameLocals(frame) else: frame_arguments = [] frame_locals = [] breakpoint_frames.append({ 'function': _GetFrameCodeObjectName(frame), 'location': { 'path': NormalizePath(code.co_filename), 'line': line }, 'arguments': frame_arguments, 'locals': frame_locals }) frame = frame.f_back except BaseException as e: # pylint: disable=broad-except # The variable table will get serialized even though there was a failure. # The results can be useful for diagnosing the internal error. self.breakpoint['status'] = { 'isError': True, 'description': { 'format': ('INTERNAL ERROR: Failed while capturing locals ' 'of frame $0: $1'), 'parameters': [str(len(breakpoint_frames)), str(e)]}} # Number of entries in _var_table. Starts at 1 (index 0 is the 'buffer full' # status value). num_vars = 1 # Explore variables table in BFS fashion. The variables table will grow # inside CaptureVariable as we encounter new references. while (num_vars < len(self._var_table)) and ( self._total_size < self.max_size): self._var_table[num_vars] = self.CaptureVariable( self._var_table[num_vars], 0, self.default_capture_limits, can_enqueue=False) # Move on to the next entry in the variable table. num_vars += 1 # Trim variables table and change make all references to variables that # didn't make it point to var_index of 0 ("buffer full") self.TrimVariableTable(num_vars) self._CaptureEnvironmentLabels() self._CaptureRequestLogId() self._CaptureUserId()
[ "def", "Collect", "(", "self", ",", "top_frame", ")", ":", "# Evaluate call stack.", "frame", "=", "top_frame", "top_line", "=", "self", ".", "breakpoint", "[", "'location'", "]", "[", "'line'", "]", "breakpoint_frames", "=", "self", ".", "breakpoint", "[", ...
Collects call stack, local variables and objects. Starts collection from the specified frame. We don't start from the top frame to exclude the frames due to debugger. Updates the content of self.breakpoint. Args: top_frame: top frame to start data collection.
[ "Collects", "call", "stack", "local", "variables", "and", "objects", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/capture_collector.py#L286-L358
230,934
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/capture_collector.py
CaptureCollector.CaptureFrameLocals
def CaptureFrameLocals(self, frame): """Captures local variables and arguments of the specified frame. Args: frame: frame to capture locals and arguments. Returns: (arguments, locals) tuple. """ # Capture all local variables (including method arguments). variables = {n: self.CaptureNamedVariable(n, v, 1, self.default_capture_limits) for n, v in six.viewitems(frame.f_locals)} # Split between locals and arguments (keeping arguments in the right order). nargs = frame.f_code.co_argcount if frame.f_code.co_flags & inspect.CO_VARARGS: nargs += 1 if frame.f_code.co_flags & inspect.CO_VARKEYWORDS: nargs += 1 frame_arguments = [] for argname in frame.f_code.co_varnames[:nargs]: if argname in variables: frame_arguments.append(variables.pop(argname)) return (frame_arguments, list(six.viewvalues(variables)))
python
def CaptureFrameLocals(self, frame): # Capture all local variables (including method arguments). variables = {n: self.CaptureNamedVariable(n, v, 1, self.default_capture_limits) for n, v in six.viewitems(frame.f_locals)} # Split between locals and arguments (keeping arguments in the right order). nargs = frame.f_code.co_argcount if frame.f_code.co_flags & inspect.CO_VARARGS: nargs += 1 if frame.f_code.co_flags & inspect.CO_VARKEYWORDS: nargs += 1 frame_arguments = [] for argname in frame.f_code.co_varnames[:nargs]: if argname in variables: frame_arguments.append(variables.pop(argname)) return (frame_arguments, list(six.viewvalues(variables)))
[ "def", "CaptureFrameLocals", "(", "self", ",", "frame", ")", ":", "# Capture all local variables (including method arguments).", "variables", "=", "{", "n", ":", "self", ".", "CaptureNamedVariable", "(", "n", ",", "v", ",", "1", ",", "self", ".", "default_capture_...
Captures local variables and arguments of the specified frame. Args: frame: frame to capture locals and arguments. Returns: (arguments, locals) tuple.
[ "Captures", "local", "variables", "and", "arguments", "of", "the", "specified", "frame", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/capture_collector.py#L360-L383
230,935
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/capture_collector.py
CaptureCollector.CaptureNamedVariable
def CaptureNamedVariable(self, name, value, depth, limits): """Appends name to the product of CaptureVariable. Args: name: name of the variable. value: data to capture depth: nested depth of dictionaries and vectors so far. limits: Per-object limits for capturing variable data. Returns: Formatted captured data as per Variable proto with name. """ if not hasattr(name, '__dict__'): name = str(name) else: # TODO(vlif): call str(name) with immutability verifier here. name = str(id(name)) self._total_size += len(name) v = (self.CheckDataVisiblity(value) or self.CaptureVariable(value, depth, limits)) v['name'] = name return v
python
def CaptureNamedVariable(self, name, value, depth, limits): if not hasattr(name, '__dict__'): name = str(name) else: # TODO(vlif): call str(name) with immutability verifier here. name = str(id(name)) self._total_size += len(name) v = (self.CheckDataVisiblity(value) or self.CaptureVariable(value, depth, limits)) v['name'] = name return v
[ "def", "CaptureNamedVariable", "(", "self", ",", "name", ",", "value", ",", "depth", ",", "limits", ")", ":", "if", "not", "hasattr", "(", "name", ",", "'__dict__'", ")", ":", "name", "=", "str", "(", "name", ")", "else", ":", "# TODO(vlif): call str(nam...
Appends name to the product of CaptureVariable. Args: name: name of the variable. value: data to capture depth: nested depth of dictionaries and vectors so far. limits: Per-object limits for capturing variable data. Returns: Formatted captured data as per Variable proto with name.
[ "Appends", "name", "to", "the", "product", "of", "CaptureVariable", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/capture_collector.py#L385-L406
230,936
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/capture_collector.py
CaptureCollector.CheckDataVisiblity
def CheckDataVisiblity(self, value): """Returns a status object if the given name is not visible. Args: value: The value to check. The actual value here is not important but the value's metadata (e.g. package and type) will be checked. Returns: None if the value is visible. A variable structure with an error status if the value should not be visible. """ if not self.data_visibility_policy: return None visible, reason = self.data_visibility_policy.IsDataVisible( DetermineType(value)) if visible: return None return { 'status': { 'isError': True, 'refersTo': 'VARIABLE_NAME', 'description': { 'format': reason } } }
python
def CheckDataVisiblity(self, value): if not self.data_visibility_policy: return None visible, reason = self.data_visibility_policy.IsDataVisible( DetermineType(value)) if visible: return None return { 'status': { 'isError': True, 'refersTo': 'VARIABLE_NAME', 'description': { 'format': reason } } }
[ "def", "CheckDataVisiblity", "(", "self", ",", "value", ")", ":", "if", "not", "self", ".", "data_visibility_policy", ":", "return", "None", "visible", ",", "reason", "=", "self", ".", "data_visibility_policy", ".", "IsDataVisible", "(", "DetermineType", "(", ...
Returns a status object if the given name is not visible. Args: value: The value to check. The actual value here is not important but the value's metadata (e.g. package and type) will be checked. Returns: None if the value is visible. A variable structure with an error status if the value should not be visible.
[ "Returns", "a", "status", "object", "if", "the", "given", "name", "is", "not", "visible", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/capture_collector.py#L408-L436
230,937
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/capture_collector.py
CaptureCollector.CaptureVariablesList
def CaptureVariablesList(self, items, depth, empty_message, limits): """Captures list of named items. Args: items: iterable of (name, value) tuples. depth: nested depth of dictionaries and vectors for items. empty_message: info status message to set if items is empty. limits: Per-object limits for capturing variable data. Returns: List of formatted variable objects. """ v = [] for name, value in items: if (self._total_size >= self.max_size) or ( len(v) >= limits.max_list_items): v.append({ 'status': { 'refersTo': 'VARIABLE_VALUE', 'description': { 'format': ('Only first $0 items were captured. Use in an ' 'expression to see all items.'), 'parameters': [str(len(v))]}}}) break v.append(self.CaptureNamedVariable(name, value, depth, limits)) if not v: return [{'status': { 'refersTo': 'VARIABLE_NAME', 'description': {'format': empty_message}}}] return v
python
def CaptureVariablesList(self, items, depth, empty_message, limits): v = [] for name, value in items: if (self._total_size >= self.max_size) or ( len(v) >= limits.max_list_items): v.append({ 'status': { 'refersTo': 'VARIABLE_VALUE', 'description': { 'format': ('Only first $0 items were captured. Use in an ' 'expression to see all items.'), 'parameters': [str(len(v))]}}}) break v.append(self.CaptureNamedVariable(name, value, depth, limits)) if not v: return [{'status': { 'refersTo': 'VARIABLE_NAME', 'description': {'format': empty_message}}}] return v
[ "def", "CaptureVariablesList", "(", "self", ",", "items", ",", "depth", ",", "empty_message", ",", "limits", ")", ":", "v", "=", "[", "]", "for", "name", ",", "value", "in", "items", ":", "if", "(", "self", ".", "_total_size", ">=", "self", ".", "max...
Captures list of named items. Args: items: iterable of (name, value) tuples. depth: nested depth of dictionaries and vectors for items. empty_message: info status message to set if items is empty. limits: Per-object limits for capturing variable data. Returns: List of formatted variable objects.
[ "Captures", "list", "of", "named", "items", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/capture_collector.py#L438-L470
230,938
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/capture_collector.py
CaptureCollector.CaptureVariable
def CaptureVariable(self, value, depth, limits, can_enqueue=True): """Try-Except wrapped version of CaptureVariableInternal.""" try: return self.CaptureVariableInternal(value, depth, limits, can_enqueue) except BaseException as e: # pylint: disable=broad-except return { 'status': { 'isError': True, 'refersTo': 'VARIABLE_VALUE', 'description': { 'format': ('Failed to capture variable: $0'), 'parameters': [str(e)] } } }
python
def CaptureVariable(self, value, depth, limits, can_enqueue=True): try: return self.CaptureVariableInternal(value, depth, limits, can_enqueue) except BaseException as e: # pylint: disable=broad-except return { 'status': { 'isError': True, 'refersTo': 'VARIABLE_VALUE', 'description': { 'format': ('Failed to capture variable: $0'), 'parameters': [str(e)] } } }
[ "def", "CaptureVariable", "(", "self", ",", "value", ",", "depth", ",", "limits", ",", "can_enqueue", "=", "True", ")", ":", "try", ":", "return", "self", ".", "CaptureVariableInternal", "(", "value", ",", "depth", ",", "limits", ",", "can_enqueue", ")", ...
Try-Except wrapped version of CaptureVariableInternal.
[ "Try", "-", "Except", "wrapped", "version", "of", "CaptureVariableInternal", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/capture_collector.py#L472-L486
230,939
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/capture_collector.py
CaptureCollector._CaptureExpression
def _CaptureExpression(self, frame, expression): """Evalutes the expression and captures it into a Variable object. Args: frame: evaluation context. expression: watched expression to compile and evaluate. Returns: Variable object (which will have error status if the expression fails to evaluate). """ rc, value = _EvaluateExpression(frame, expression) if not rc: return {'name': expression, 'status': value} return self.CaptureNamedVariable(expression, value, 0, self.expression_capture_limits)
python
def _CaptureExpression(self, frame, expression): rc, value = _EvaluateExpression(frame, expression) if not rc: return {'name': expression, 'status': value} return self.CaptureNamedVariable(expression, value, 0, self.expression_capture_limits)
[ "def", "_CaptureExpression", "(", "self", ",", "frame", ",", "expression", ")", ":", "rc", ",", "value", "=", "_EvaluateExpression", "(", "frame", ",", "expression", ")", "if", "not", "rc", ":", "return", "{", "'name'", ":", "expression", ",", "'status'", ...
Evalutes the expression and captures it into a Variable object. Args: frame: evaluation context. expression: watched expression to compile and evaluate. Returns: Variable object (which will have error status if the expression fails to evaluate).
[ "Evalutes", "the", "expression", "and", "captures", "it", "into", "a", "Variable", "object", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/capture_collector.py#L593-L609
230,940
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/capture_collector.py
CaptureCollector.TrimVariableTable
def TrimVariableTable(self, new_size): """Trims the variable table in the formatted breakpoint message. Removes trailing entries in variables table. Then scans the entire breakpoint message and replaces references to the trimmed variables to point to var_index of 0 ("buffer full"). Args: new_size: desired size of variables table. """ def ProcessBufferFull(variables): for variable in variables: var_index = variable.get('varTableIndex') if var_index is not None and (var_index >= new_size): variable['varTableIndex'] = 0 # Buffer full. members = variable.get('members') if members is not None: ProcessBufferFull(members) del self._var_table[new_size:] ProcessBufferFull(self.breakpoint['evaluatedExpressions']) for stack_frame in self.breakpoint['stackFrames']: ProcessBufferFull(stack_frame['arguments']) ProcessBufferFull(stack_frame['locals']) ProcessBufferFull(self._var_table)
python
def TrimVariableTable(self, new_size): def ProcessBufferFull(variables): for variable in variables: var_index = variable.get('varTableIndex') if var_index is not None and (var_index >= new_size): variable['varTableIndex'] = 0 # Buffer full. members = variable.get('members') if members is not None: ProcessBufferFull(members) del self._var_table[new_size:] ProcessBufferFull(self.breakpoint['evaluatedExpressions']) for stack_frame in self.breakpoint['stackFrames']: ProcessBufferFull(stack_frame['arguments']) ProcessBufferFull(stack_frame['locals']) ProcessBufferFull(self._var_table)
[ "def", "TrimVariableTable", "(", "self", ",", "new_size", ")", ":", "def", "ProcessBufferFull", "(", "variables", ")", ":", "for", "variable", "in", "variables", ":", "var_index", "=", "variable", ".", "get", "(", "'varTableIndex'", ")", "if", "var_index", "...
Trims the variable table in the formatted breakpoint message. Removes trailing entries in variables table. Then scans the entire breakpoint message and replaces references to the trimmed variables to point to var_index of 0 ("buffer full"). Args: new_size: desired size of variables table.
[ "Trims", "the", "variable", "table", "in", "the", "formatted", "breakpoint", "message", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/capture_collector.py#L611-L636
230,941
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/capture_collector.py
CaptureCollector._CaptureEnvironmentLabels
def _CaptureEnvironmentLabels(self): """Captures information about the environment, if possible.""" if 'labels' not in self.breakpoint: self.breakpoint['labels'] = {} if callable(breakpoint_labels_collector): for (key, value) in six.iteritems(breakpoint_labels_collector()): self.breakpoint['labels'][key] = value
python
def _CaptureEnvironmentLabels(self): if 'labels' not in self.breakpoint: self.breakpoint['labels'] = {} if callable(breakpoint_labels_collector): for (key, value) in six.iteritems(breakpoint_labels_collector()): self.breakpoint['labels'][key] = value
[ "def", "_CaptureEnvironmentLabels", "(", "self", ")", ":", "if", "'labels'", "not", "in", "self", ".", "breakpoint", ":", "self", ".", "breakpoint", "[", "'labels'", "]", "=", "{", "}", "if", "callable", "(", "breakpoint_labels_collector", ")", ":", "for", ...
Captures information about the environment, if possible.
[ "Captures", "information", "about", "the", "environment", "if", "possible", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/capture_collector.py#L638-L645
230,942
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/capture_collector.py
CaptureCollector._CaptureRequestLogId
def _CaptureRequestLogId(self): """Captures the request log id if possible. The request log id is stored inside the breakpoint labels. """ # pylint: disable=not-callable if callable(request_log_id_collector): request_log_id = request_log_id_collector() if request_log_id: # We have a request_log_id, save it into the breakpoint labels self.breakpoint['labels'][ labels.Breakpoint.REQUEST_LOG_ID] = request_log_id
python
def _CaptureRequestLogId(self): # pylint: disable=not-callable if callable(request_log_id_collector): request_log_id = request_log_id_collector() if request_log_id: # We have a request_log_id, save it into the breakpoint labels self.breakpoint['labels'][ labels.Breakpoint.REQUEST_LOG_ID] = request_log_id
[ "def", "_CaptureRequestLogId", "(", "self", ")", ":", "# pylint: disable=not-callable", "if", "callable", "(", "request_log_id_collector", ")", ":", "request_log_id", "=", "request_log_id_collector", "(", ")", "if", "request_log_id", ":", "# We have a request_log_id, save i...
Captures the request log id if possible. The request log id is stored inside the breakpoint labels.
[ "Captures", "the", "request", "log", "id", "if", "possible", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/capture_collector.py#L647-L658
230,943
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/capture_collector.py
CaptureCollector._CaptureUserId
def _CaptureUserId(self): """Captures the user id of the end user, if possible.""" user_kind, user_id = user_id_collector() if user_kind and user_id: self.breakpoint['evaluatedUserId'] = {'kind': user_kind, 'id': user_id}
python
def _CaptureUserId(self): user_kind, user_id = user_id_collector() if user_kind and user_id: self.breakpoint['evaluatedUserId'] = {'kind': user_kind, 'id': user_id}
[ "def", "_CaptureUserId", "(", "self", ")", ":", "user_kind", ",", "user_id", "=", "user_id_collector", "(", ")", "if", "user_kind", "and", "user_id", ":", "self", ".", "breakpoint", "[", "'evaluatedUserId'", "]", "=", "{", "'kind'", ":", "user_kind", ",", ...
Captures the user id of the end user, if possible.
[ "Captures", "the", "user", "id", "of", "the", "end", "user", "if", "possible", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/capture_collector.py#L660-L664
230,944
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/capture_collector.py
LogCollector.Log
def Log(self, frame): """Captures the minimal application states, formats it and logs the message. Args: frame: Python stack frame of breakpoint hit. Returns: None on success or status message on error. """ # Return error if log methods were not configured globally. if not self._log_message: return {'isError': True, 'description': {'format': LOG_ACTION_NOT_SUPPORTED}} if self._quota_recovery_start_time: ms_elapsed = (time.time() - self._quota_recovery_start_time) * 1000 if ms_elapsed > self.quota_recovery_ms: # We are out of the recovery period, clear the time and continue self._quota_recovery_start_time = None else: # We are in the recovery period, exit return # Evaluate watched expressions. message = 'LOGPOINT: ' + _FormatMessage( self._definition.get('logMessageFormat', ''), self._EvaluateExpressions(frame)) line = self._definition['location']['line'] cdbg_logging_location = (NormalizePath(frame.f_code.co_filename), line, _GetFrameCodeObjectName(frame)) if native.ApplyDynamicLogsQuota(len(message)): self._log_message(message) else: self._quota_recovery_start_time = time.time() self._log_message(DYNAMIC_LOG_OUT_OF_QUOTA) del cdbg_logging_location return None
python
def Log(self, frame): # Return error if log methods were not configured globally. if not self._log_message: return {'isError': True, 'description': {'format': LOG_ACTION_NOT_SUPPORTED}} if self._quota_recovery_start_time: ms_elapsed = (time.time() - self._quota_recovery_start_time) * 1000 if ms_elapsed > self.quota_recovery_ms: # We are out of the recovery period, clear the time and continue self._quota_recovery_start_time = None else: # We are in the recovery period, exit return # Evaluate watched expressions. message = 'LOGPOINT: ' + _FormatMessage( self._definition.get('logMessageFormat', ''), self._EvaluateExpressions(frame)) line = self._definition['location']['line'] cdbg_logging_location = (NormalizePath(frame.f_code.co_filename), line, _GetFrameCodeObjectName(frame)) if native.ApplyDynamicLogsQuota(len(message)): self._log_message(message) else: self._quota_recovery_start_time = time.time() self._log_message(DYNAMIC_LOG_OUT_OF_QUOTA) del cdbg_logging_location return None
[ "def", "Log", "(", "self", ",", "frame", ")", ":", "# Return error if log methods were not configured globally.", "if", "not", "self", ".", "_log_message", ":", "return", "{", "'isError'", ":", "True", ",", "'description'", ":", "{", "'format'", ":", "LOG_ACTION_N...
Captures the minimal application states, formats it and logs the message. Args: frame: Python stack frame of breakpoint hit. Returns: None on success or status message on error.
[ "Captures", "the", "minimal", "application", "states", "formats", "it", "and", "logs", "the", "message", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/capture_collector.py#L715-L753
230,945
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/capture_collector.py
LogCollector._EvaluateExpressions
def _EvaluateExpressions(self, frame): """Evaluates watched expressions into a string form. If expression evaluation fails, the error message is used as evaluated expression string. Args: frame: Python stack frame of breakpoint hit. Returns: Array of strings where each string corresponds to the breakpoint expression with the same index. """ return [self._FormatExpression(frame, expression) for expression in self._definition.get('expressions') or []]
python
def _EvaluateExpressions(self, frame): return [self._FormatExpression(frame, expression) for expression in self._definition.get('expressions') or []]
[ "def", "_EvaluateExpressions", "(", "self", ",", "frame", ")", ":", "return", "[", "self", ".", "_FormatExpression", "(", "frame", ",", "expression", ")", "for", "expression", "in", "self", ".", "_definition", ".", "get", "(", "'expressions'", ")", "or", "...
Evaluates watched expressions into a string form. If expression evaluation fails, the error message is used as evaluated expression string. Args: frame: Python stack frame of breakpoint hit. Returns: Array of strings where each string corresponds to the breakpoint expression with the same index.
[ "Evaluates", "watched", "expressions", "into", "a", "string", "form", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/capture_collector.py#L755-L769
230,946
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/capture_collector.py
LogCollector._FormatExpression
def _FormatExpression(self, frame, expression): """Evaluates a single watched expression and formats it into a string form. If expression evaluation fails, returns error message string. Args: frame: Python stack frame in which the expression is evaluated. expression: string expression to evaluate. Returns: Formatted expression value that can be used in the log message. """ rc, value = _EvaluateExpression(frame, expression) if not rc: message = _FormatMessage(value['description']['format'], value['description'].get('parameters')) return '<' + message + '>' return self._FormatValue(value)
python
def _FormatExpression(self, frame, expression): rc, value = _EvaluateExpression(frame, expression) if not rc: message = _FormatMessage(value['description']['format'], value['description'].get('parameters')) return '<' + message + '>' return self._FormatValue(value)
[ "def", "_FormatExpression", "(", "self", ",", "frame", ",", "expression", ")", ":", "rc", ",", "value", "=", "_EvaluateExpression", "(", "frame", ",", "expression", ")", "if", "not", "rc", ":", "message", "=", "_FormatMessage", "(", "value", "[", "'descrip...
Evaluates a single watched expression and formats it into a string form. If expression evaluation fails, returns error message string. Args: frame: Python stack frame in which the expression is evaluated. expression: string expression to evaluate. Returns: Formatted expression value that can be used in the log message.
[ "Evaluates", "a", "single", "watched", "expression", "and", "formats", "it", "into", "a", "string", "form", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/capture_collector.py#L771-L789
230,947
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/capture_collector.py
LogCollector._FormatValue
def _FormatValue(self, value, level=0): """Pretty-prints an object for a logger. This function is very similar to the standard pprint. The main difference is that it enforces limits to make sure we never produce an extremely long string or take too much time. Args: value: Python object to print. level: current recursion level. Returns: Formatted string. """ def FormatDictItem(key_value): """Formats single dictionary item.""" key, value = key_value return (self._FormatValue(key, level + 1) + ': ' + self._FormatValue(value, level + 1)) def LimitedEnumerate(items, formatter, level=0): """Returns items in the specified enumerable enforcing threshold.""" count = 0 limit = self.max_sublist_items if level > 0 else self.max_list_items for item in items: if count == limit: yield '...' break yield formatter(item) count += 1 def FormatList(items, formatter, level=0): """Formats a list using a custom item formatter enforcing threshold.""" return ', '.join(LimitedEnumerate(items, formatter, level=level)) if isinstance(value, _PRIMITIVE_TYPES): return _TrimString(repr(value), # Primitive type, always immutable. self.max_value_len) if isinstance(value, _DATE_TYPES): return str(value) if level > self.max_depth: return str(type(value)) if isinstance(value, dict): return '{' + FormatList(six.iteritems(value), FormatDictItem) + '}' if isinstance(value, _VECTOR_TYPES): return _ListTypeFormatString(value).format(FormatList( value, lambda item: self._FormatValue(item, level + 1), level=level)) if isinstance(value, types.FunctionType): return 'function ' + value.__name__ if hasattr(value, '__dict__') and value.__dict__: return self._FormatValue(value.__dict__, level) return str(type(value))
python
def _FormatValue(self, value, level=0): def FormatDictItem(key_value): """Formats single dictionary item.""" key, value = key_value return (self._FormatValue(key, level + 1) + ': ' + self._FormatValue(value, level + 1)) def LimitedEnumerate(items, formatter, level=0): """Returns items in the specified enumerable enforcing threshold.""" count = 0 limit = self.max_sublist_items if level > 0 else self.max_list_items for item in items: if count == limit: yield '...' break yield formatter(item) count += 1 def FormatList(items, formatter, level=0): """Formats a list using a custom item formatter enforcing threshold.""" return ', '.join(LimitedEnumerate(items, formatter, level=level)) if isinstance(value, _PRIMITIVE_TYPES): return _TrimString(repr(value), # Primitive type, always immutable. self.max_value_len) if isinstance(value, _DATE_TYPES): return str(value) if level > self.max_depth: return str(type(value)) if isinstance(value, dict): return '{' + FormatList(six.iteritems(value), FormatDictItem) + '}' if isinstance(value, _VECTOR_TYPES): return _ListTypeFormatString(value).format(FormatList( value, lambda item: self._FormatValue(item, level + 1), level=level)) if isinstance(value, types.FunctionType): return 'function ' + value.__name__ if hasattr(value, '__dict__') and value.__dict__: return self._FormatValue(value.__dict__, level) return str(type(value))
[ "def", "_FormatValue", "(", "self", ",", "value", ",", "level", "=", "0", ")", ":", "def", "FormatDictItem", "(", "key_value", ")", ":", "\"\"\"Formats single dictionary item.\"\"\"", "key", ",", "value", "=", "key_value", "return", "(", "self", ".", "_FormatV...
Pretty-prints an object for a logger. This function is very similar to the standard pprint. The main difference is that it enforces limits to make sure we never produce an extremely long string or take too much time. Args: value: Python object to print. level: current recursion level. Returns: Formatted string.
[ "Pretty", "-", "prints", "an", "object", "for", "a", "logger", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/capture_collector.py#L791-L852
230,948
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/yaml_data_visibility_config_reader.py
OpenAndRead
def OpenAndRead(relative_path='debugger-blacklist.yaml'): """Attempts to find the yaml configuration file, then read it. Args: relative_path: Optional relative path override. Returns: A Config object if the open and read were successful, None if the file does not exist (which is not considered an error). Raises: Error (some subclass): As thrown by the called Read() function. """ # Note: This logic follows the convention established by source-context.json try: with open(os.path.join(sys.path[0], relative_path), 'r') as f: return Read(f) except IOError: return None
python
def OpenAndRead(relative_path='debugger-blacklist.yaml'): # Note: This logic follows the convention established by source-context.json try: with open(os.path.join(sys.path[0], relative_path), 'r') as f: return Read(f) except IOError: return None
[ "def", "OpenAndRead", "(", "relative_path", "=", "'debugger-blacklist.yaml'", ")", ":", "# Note: This logic follows the convention established by source-context.json", "try", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "sys", ".", "path", "[", "0", ...
Attempts to find the yaml configuration file, then read it. Args: relative_path: Optional relative path override. Returns: A Config object if the open and read were successful, None if the file does not exist (which is not considered an error). Raises: Error (some subclass): As thrown by the called Read() function.
[ "Attempts", "to", "find", "the", "yaml", "configuration", "file", "then", "read", "it", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/yaml_data_visibility_config_reader.py#L72-L91
230,949
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/yaml_data_visibility_config_reader.py
Read
def Read(f): """Reads and returns Config data from a yaml file. Args: f: Yaml file to parse. Returns: Config object as defined in this file. Raises: Error (some subclass): If there is a problem loading or parsing the file. """ try: yaml_data = yaml.load(f) except yaml.YAMLError as e: raise ParseError('%s' % e) except IOError as e: raise YAMLLoadError('%s' % e) _CheckData(yaml_data) try: return Config( yaml_data.get('blacklist', ()), yaml_data.get('whitelist', ('*'))) except UnicodeDecodeError as e: raise YAMLLoadError('%s' % e)
python
def Read(f): try: yaml_data = yaml.load(f) except yaml.YAMLError as e: raise ParseError('%s' % e) except IOError as e: raise YAMLLoadError('%s' % e) _CheckData(yaml_data) try: return Config( yaml_data.get('blacklist', ()), yaml_data.get('whitelist', ('*'))) except UnicodeDecodeError as e: raise YAMLLoadError('%s' % e)
[ "def", "Read", "(", "f", ")", ":", "try", ":", "yaml_data", "=", "yaml", ".", "load", "(", "f", ")", "except", "yaml", ".", "YAMLError", "as", "e", ":", "raise", "ParseError", "(", "'%s'", "%", "e", ")", "except", "IOError", "as", "e", ":", "rais...
Reads and returns Config data from a yaml file. Args: f: Yaml file to parse. Returns: Config object as defined in this file. Raises: Error (some subclass): If there is a problem loading or parsing the file.
[ "Reads", "and", "returns", "Config", "data", "from", "a", "yaml", "file", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/yaml_data_visibility_config_reader.py#L94-L120
230,950
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/yaml_data_visibility_config_reader.py
_CheckData
def _CheckData(yaml_data): """Checks data for illegal keys and formatting.""" legal_keys = set(('blacklist', 'whitelist')) unknown_keys = set(yaml_data) - legal_keys if unknown_keys: raise UnknownConfigKeyError( 'Unknown keys in configuration: %s' % unknown_keys) for key, data in six.iteritems(yaml_data): _AssertDataIsList(key, data)
python
def _CheckData(yaml_data): legal_keys = set(('blacklist', 'whitelist')) unknown_keys = set(yaml_data) - legal_keys if unknown_keys: raise UnknownConfigKeyError( 'Unknown keys in configuration: %s' % unknown_keys) for key, data in six.iteritems(yaml_data): _AssertDataIsList(key, data)
[ "def", "_CheckData", "(", "yaml_data", ")", ":", "legal_keys", "=", "set", "(", "(", "'blacklist'", ",", "'whitelist'", ")", ")", "unknown_keys", "=", "set", "(", "yaml_data", ")", "-", "legal_keys", "if", "unknown_keys", ":", "raise", "UnknownConfigKeyError",...
Checks data for illegal keys and formatting.
[ "Checks", "data", "for", "illegal", "keys", "and", "formatting", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/yaml_data_visibility_config_reader.py#L123-L132
230,951
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/yaml_data_visibility_config_reader.py
_AssertDataIsList
def _AssertDataIsList(key, lst): """Assert that lst contains list data and is not structured.""" # list and tuple are supported. Not supported are direct strings # and dictionary; these indicate too much or two little structure. if not isinstance(lst, list) and not isinstance(lst, tuple): raise NotAListError('%s must be a list' % key) # each list entry must be a string for element in lst: if not isinstance(element, str): raise ElementNotAStringError('Unsupported list element %s found in %s', (element, lst))
python
def _AssertDataIsList(key, lst): # list and tuple are supported. Not supported are direct strings # and dictionary; these indicate too much or two little structure. if not isinstance(lst, list) and not isinstance(lst, tuple): raise NotAListError('%s must be a list' % key) # each list entry must be a string for element in lst: if not isinstance(element, str): raise ElementNotAStringError('Unsupported list element %s found in %s', (element, lst))
[ "def", "_AssertDataIsList", "(", "key", ",", "lst", ")", ":", "# list and tuple are supported. Not supported are direct strings", "# and dictionary; these indicate too much or two little structure.", "if", "not", "isinstance", "(", "lst", ",", "list", ")", "and", "not", "isi...
Assert that lst contains list data and is not structured.
[ "Assert", "that", "lst", "contains", "list", "data", "and", "is", "not", "structured", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/yaml_data_visibility_config_reader.py#L135-L147
230,952
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/python_breakpoint.py
_StripCommonPathPrefix
def _StripCommonPathPrefix(paths): """Removes path common prefix from a list of path strings.""" # Find the longest common prefix in terms of characters. common_prefix = os.path.commonprefix(paths) # Truncate at last segment boundary. E.g. '/aa/bb1/x.py' and '/a/bb2/x.py' # have '/aa/bb' as the common prefix, but we should strip '/aa/' instead. # If there's no '/' found, returns -1+1=0. common_prefix_len = common_prefix.rfind('/') + 1 return [path[common_prefix_len:] for path in paths]
python
def _StripCommonPathPrefix(paths): # Find the longest common prefix in terms of characters. common_prefix = os.path.commonprefix(paths) # Truncate at last segment boundary. E.g. '/aa/bb1/x.py' and '/a/bb2/x.py' # have '/aa/bb' as the common prefix, but we should strip '/aa/' instead. # If there's no '/' found, returns -1+1=0. common_prefix_len = common_prefix.rfind('/') + 1 return [path[common_prefix_len:] for path in paths]
[ "def", "_StripCommonPathPrefix", "(", "paths", ")", ":", "# Find the longest common prefix in terms of characters.", "common_prefix", "=", "os", ".", "path", ".", "commonprefix", "(", "paths", ")", "# Truncate at last segment boundary. E.g. '/aa/bb1/x.py' and '/a/bb2/x.py'", "# h...
Removes path common prefix from a list of path strings.
[ "Removes", "path", "common", "prefix", "from", "a", "list", "of", "path", "strings", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/python_breakpoint.py#L94-L102
230,953
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/python_breakpoint.py
_MultipleModulesFoundError
def _MultipleModulesFoundError(path, candidates): """Generates an error message to be used when multiple matches are found. Args: path: The breakpoint location path that the user provided. candidates: List of paths that match the user provided path. Must contain at least 2 entries (throws AssertionError otherwise). Returns: A (format, parameters) tuple that should be used in the description field of the breakpoint error status. """ assert len(candidates) > 1 params = [path] + _StripCommonPathPrefix(candidates[:2]) if len(candidates) == 2: fmt = ERROR_LOCATION_MULTIPLE_MODULES_3 else: fmt = ERROR_LOCATION_MULTIPLE_MODULES_4 params.append(str(len(candidates) - 2)) return fmt, params
python
def _MultipleModulesFoundError(path, candidates): assert len(candidates) > 1 params = [path] + _StripCommonPathPrefix(candidates[:2]) if len(candidates) == 2: fmt = ERROR_LOCATION_MULTIPLE_MODULES_3 else: fmt = ERROR_LOCATION_MULTIPLE_MODULES_4 params.append(str(len(candidates) - 2)) return fmt, params
[ "def", "_MultipleModulesFoundError", "(", "path", ",", "candidates", ")", ":", "assert", "len", "(", "candidates", ")", ">", "1", "params", "=", "[", "path", "]", "+", "_StripCommonPathPrefix", "(", "candidates", "[", ":", "2", "]", ")", "if", "len", "("...
Generates an error message to be used when multiple matches are found. Args: path: The breakpoint location path that the user provided. candidates: List of paths that match the user provided path. Must contain at least 2 entries (throws AssertionError otherwise). Returns: A (format, parameters) tuple that should be used in the description field of the breakpoint error status.
[ "Generates", "an", "error", "message", "to", "be", "used", "when", "multiple", "matches", "are", "found", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/python_breakpoint.py#L105-L124
230,954
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/python_breakpoint.py
_NormalizePath
def _NormalizePath(path): """Removes surrounding whitespace, leading separator and normalize.""" # TODO(emrekultursay): Calling os.path.normpath "may change the meaning of a # path that contains symbolic links" (e.g., "A/foo/../B" != "A/B" if foo is a # symlink). This might cause trouble when matching against loaded module # paths. We should try to avoid using it. # Example: # > import symlink.a # > symlink.a.__file__ # symlink/a.py # > import target.a # > starget.a.__file__ # target/a.py # Python interpreter treats these as two separate modules. So, we also need to # handle them the same way. return os.path.normpath(path.strip().lstrip(os.sep))
python
def _NormalizePath(path): # TODO(emrekultursay): Calling os.path.normpath "may change the meaning of a # path that contains symbolic links" (e.g., "A/foo/../B" != "A/B" if foo is a # symlink). This might cause trouble when matching against loaded module # paths. We should try to avoid using it. # Example: # > import symlink.a # > symlink.a.__file__ # symlink/a.py # > import target.a # > starget.a.__file__ # target/a.py # Python interpreter treats these as two separate modules. So, we also need to # handle them the same way. return os.path.normpath(path.strip().lstrip(os.sep))
[ "def", "_NormalizePath", "(", "path", ")", ":", "# TODO(emrekultursay): Calling os.path.normpath \"may change the meaning of a", "# path that contains symbolic links\" (e.g., \"A/foo/../B\" != \"A/B\" if foo is a", "# symlink). This might cause trouble when matching against loaded module", "# path...
Removes surrounding whitespace, leading separator and normalize.
[ "Removes", "surrounding", "whitespace", "leading", "separator", "and", "normalize", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/python_breakpoint.py#L127-L142
230,955
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/python_breakpoint.py
PythonBreakpoint.Clear
def Clear(self): """Clears the breakpoint and releases all breakpoint resources. This function is assumed to be called by BreakpointsManager. Therefore we don't call CompleteBreakpoint from here. """ self._RemoveImportHook() if self._cookie is not None: native.LogInfo('Clearing breakpoint %s' % self.GetBreakpointId()) native.ClearConditionalBreakpoint(self._cookie) self._cookie = None self._completed = True
python
def Clear(self): self._RemoveImportHook() if self._cookie is not None: native.LogInfo('Clearing breakpoint %s' % self.GetBreakpointId()) native.ClearConditionalBreakpoint(self._cookie) self._cookie = None self._completed = True
[ "def", "Clear", "(", "self", ")", ":", "self", ".", "_RemoveImportHook", "(", ")", "if", "self", ".", "_cookie", "is", "not", "None", ":", "native", ".", "LogInfo", "(", "'Clearing breakpoint %s'", "%", "self", ".", "GetBreakpointId", "(", ")", ")", "nat...
Clears the breakpoint and releases all breakpoint resources. This function is assumed to be called by BreakpointsManager. Therefore we don't call CompleteBreakpoint from here.
[ "Clears", "the", "breakpoint", "and", "releases", "all", "breakpoint", "resources", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/python_breakpoint.py#L223-L235
230,956
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/python_breakpoint.py
PythonBreakpoint.GetExpirationTime
def GetExpirationTime(self): """Computes the timestamp at which this breakpoint will expire.""" # TODO(emrekultursay): Move this to a common method. if '.' not in self.definition['createTime']: fmt = '%Y-%m-%dT%H:%M:%S%Z' else: fmt = '%Y-%m-%dT%H:%M:%S.%f%Z' create_datetime = datetime.strptime( self.definition['createTime'].replace('Z', 'UTC'), fmt) return create_datetime + self.expiration_period
python
def GetExpirationTime(self): # TODO(emrekultursay): Move this to a common method. if '.' not in self.definition['createTime']: fmt = '%Y-%m-%dT%H:%M:%S%Z' else: fmt = '%Y-%m-%dT%H:%M:%S.%f%Z' create_datetime = datetime.strptime( self.definition['createTime'].replace('Z', 'UTC'), fmt) return create_datetime + self.expiration_period
[ "def", "GetExpirationTime", "(", "self", ")", ":", "# TODO(emrekultursay): Move this to a common method.", "if", "'.'", "not", "in", "self", ".", "definition", "[", "'createTime'", "]", ":", "fmt", "=", "'%Y-%m-%dT%H:%M:%S%Z'", "else", ":", "fmt", "=", "'%Y-%m-%dT%H...
Computes the timestamp at which this breakpoint will expire.
[ "Computes", "the", "timestamp", "at", "which", "this", "breakpoint", "will", "expire", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/python_breakpoint.py#L240-L250
230,957
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/python_breakpoint.py
PythonBreakpoint.ExpireBreakpoint
def ExpireBreakpoint(self): """Expires this breakpoint.""" # Let only one thread capture the data and complete the breakpoint. if not self._SetCompleted(): return if self.definition.get('action') == 'LOG': message = ERROR_AGE_LOGPOINT_EXPIRED_0 else: message = ERROR_AGE_SNAPSHOT_EXPIRED_0 self._CompleteBreakpoint({ 'status': { 'isError': True, 'refersTo': 'BREAKPOINT_AGE', 'description': {'format': message}}})
python
def ExpireBreakpoint(self): # Let only one thread capture the data and complete the breakpoint. if not self._SetCompleted(): return if self.definition.get('action') == 'LOG': message = ERROR_AGE_LOGPOINT_EXPIRED_0 else: message = ERROR_AGE_SNAPSHOT_EXPIRED_0 self._CompleteBreakpoint({ 'status': { 'isError': True, 'refersTo': 'BREAKPOINT_AGE', 'description': {'format': message}}})
[ "def", "ExpireBreakpoint", "(", "self", ")", ":", "# Let only one thread capture the data and complete the breakpoint.", "if", "not", "self", ".", "_SetCompleted", "(", ")", ":", "return", "if", "self", ".", "definition", ".", "get", "(", "'action'", ")", "==", "'...
Expires this breakpoint.
[ "Expires", "this", "breakpoint", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/python_breakpoint.py#L252-L266
230,958
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/python_breakpoint.py
PythonBreakpoint._ActivateBreakpoint
def _ActivateBreakpoint(self, module): """Sets the breakpoint in the loaded module, or complete with error.""" # First remove the import hook (if installed). self._RemoveImportHook() line = self.definition['location']['line'] # Find the code object in which the breakpoint is being set. status, codeobj = module_explorer.GetCodeObjectAtLine(module, line) if not status: # First two parameters are common: the line of the breakpoint and the # module we are trying to insert the breakpoint in. # TODO(emrekultursay): Do not display the entire path of the file. Either # strip some prefix, or display the path in the breakpoint. params = [str(line), os.path.splitext(module.__file__)[0] + '.py'] # The next 0, 1, or 2 parameters are the alternative lines to set the # breakpoint at, displayed for the user's convenience. alt_lines = (str(l) for l in codeobj if l is not None) params += alt_lines if len(params) == 4: fmt = ERROR_LOCATION_NO_CODE_FOUND_AT_LINE_4 elif len(params) == 3: fmt = ERROR_LOCATION_NO_CODE_FOUND_AT_LINE_3 else: fmt = ERROR_LOCATION_NO_CODE_FOUND_AT_LINE_2 self._CompleteBreakpoint({ 'status': { 'isError': True, 'refersTo': 'BREAKPOINT_SOURCE_LOCATION', 'description': { 'format': fmt, 'parameters': params}}}) return # Compile the breakpoint condition. condition = None if self.definition.get('condition'): try: condition = compile(self.definition.get('condition'), '<condition_expression>', 'eval') except (TypeError, ValueError) as e: # condition string contains null bytes. self._CompleteBreakpoint({ 'status': { 'isError': True, 'refersTo': 'BREAKPOINT_CONDITION', 'description': { 'format': 'Invalid expression', 'parameters': [str(e)]}}}) return except SyntaxError as e: self._CompleteBreakpoint({ 'status': { 'isError': True, 'refersTo': 'BREAKPOINT_CONDITION', 'description': { 'format': 'Expression could not be compiled: $0', 'parameters': [e.msg]}}}) return native.LogInfo('Creating new Python breakpoint %s in %s, line %d' % ( self.GetBreakpointId(), codeobj, line)) self._cookie = native.SetConditionalBreakpoint( codeobj, line, condition, self._BreakpointEvent)
python
def _ActivateBreakpoint(self, module): # First remove the import hook (if installed). self._RemoveImportHook() line = self.definition['location']['line'] # Find the code object in which the breakpoint is being set. status, codeobj = module_explorer.GetCodeObjectAtLine(module, line) if not status: # First two parameters are common: the line of the breakpoint and the # module we are trying to insert the breakpoint in. # TODO(emrekultursay): Do not display the entire path of the file. Either # strip some prefix, or display the path in the breakpoint. params = [str(line), os.path.splitext(module.__file__)[0] + '.py'] # The next 0, 1, or 2 parameters are the alternative lines to set the # breakpoint at, displayed for the user's convenience. alt_lines = (str(l) for l in codeobj if l is not None) params += alt_lines if len(params) == 4: fmt = ERROR_LOCATION_NO_CODE_FOUND_AT_LINE_4 elif len(params) == 3: fmt = ERROR_LOCATION_NO_CODE_FOUND_AT_LINE_3 else: fmt = ERROR_LOCATION_NO_CODE_FOUND_AT_LINE_2 self._CompleteBreakpoint({ 'status': { 'isError': True, 'refersTo': 'BREAKPOINT_SOURCE_LOCATION', 'description': { 'format': fmt, 'parameters': params}}}) return # Compile the breakpoint condition. condition = None if self.definition.get('condition'): try: condition = compile(self.definition.get('condition'), '<condition_expression>', 'eval') except (TypeError, ValueError) as e: # condition string contains null bytes. self._CompleteBreakpoint({ 'status': { 'isError': True, 'refersTo': 'BREAKPOINT_CONDITION', 'description': { 'format': 'Invalid expression', 'parameters': [str(e)]}}}) return except SyntaxError as e: self._CompleteBreakpoint({ 'status': { 'isError': True, 'refersTo': 'BREAKPOINT_CONDITION', 'description': { 'format': 'Expression could not be compiled: $0', 'parameters': [e.msg]}}}) return native.LogInfo('Creating new Python breakpoint %s in %s, line %d' % ( self.GetBreakpointId(), codeobj, line)) self._cookie = native.SetConditionalBreakpoint( codeobj, line, condition, self._BreakpointEvent)
[ "def", "_ActivateBreakpoint", "(", "self", ",", "module", ")", ":", "# First remove the import hook (if installed).", "self", ".", "_RemoveImportHook", "(", ")", "line", "=", "self", ".", "definition", "[", "'location'", "]", "[", "'line'", "]", "# Find the code obj...
Sets the breakpoint in the loaded module, or complete with error.
[ "Sets", "the", "breakpoint", "in", "the", "loaded", "module", "or", "complete", "with", "error", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/python_breakpoint.py#L268-L341
230,959
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/python_breakpoint.py
PythonBreakpoint._CompleteBreakpoint
def _CompleteBreakpoint(self, data, is_incremental=True): """Sends breakpoint update and deactivates the breakpoint.""" if is_incremental: data = dict(self.definition, **data) data['isFinalState'] = True self._hub_client.EnqueueBreakpointUpdate(data) self._breakpoints_manager.CompleteBreakpoint(self.GetBreakpointId()) self.Clear()
python
def _CompleteBreakpoint(self, data, is_incremental=True): if is_incremental: data = dict(self.definition, **data) data['isFinalState'] = True self._hub_client.EnqueueBreakpointUpdate(data) self._breakpoints_manager.CompleteBreakpoint(self.GetBreakpointId()) self.Clear()
[ "def", "_CompleteBreakpoint", "(", "self", ",", "data", ",", "is_incremental", "=", "True", ")", ":", "if", "is_incremental", ":", "data", "=", "dict", "(", "self", ".", "definition", ",", "*", "*", "data", ")", "data", "[", "'isFinalState'", "]", "=", ...
Sends breakpoint update and deactivates the breakpoint.
[ "Sends", "breakpoint", "update", "and", "deactivates", "the", "breakpoint", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/python_breakpoint.py#L349-L357
230,960
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/python_breakpoint.py
PythonBreakpoint._SetCompleted
def _SetCompleted(self): """Atomically marks the breakpoint as completed. Returns: True if the breakpoint wasn't marked already completed or False if the breakpoint was already completed. """ with self._lock: if self._completed: return False self._completed = True return True
python
def _SetCompleted(self): with self._lock: if self._completed: return False self._completed = True return True
[ "def", "_SetCompleted", "(", "self", ")", ":", "with", "self", ".", "_lock", ":", "if", "self", ".", "_completed", ":", "return", "False", "self", ".", "_completed", "=", "True", "return", "True" ]
Atomically marks the breakpoint as completed. Returns: True if the breakpoint wasn't marked already completed or False if the breakpoint was already completed.
[ "Atomically", "marks", "the", "breakpoint", "as", "completed", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/python_breakpoint.py#L359-L370
230,961
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/python_breakpoint.py
PythonBreakpoint._BreakpointEvent
def _BreakpointEvent(self, event, frame): """Callback invoked by cdbg_native when breakpoint hits. Args: event: breakpoint event (see kIntegerConstants in native_module.cc). frame: Python stack frame of breakpoint hit or None for other events. """ error_status = None if event != native.BREAKPOINT_EVENT_HIT: error_status = _BREAKPOINT_EVENT_STATUS[event] elif self.definition.get('action') == 'LOG': error_status = self._collector.Log(frame) if not error_status: return # Log action successful, no need to clear the breakpoint. # Let only one thread capture the data and complete the breakpoint. if not self._SetCompleted(): return self.Clear() if error_status: self._CompleteBreakpoint({'status': error_status}) return collector = capture_collector.CaptureCollector( self.definition, self.data_visibility_policy) # TODO(b/69119299): This is a temporary try/except. All exceptions should be # caught inside Collect and converted into breakpoint error messages. try: collector.Collect(frame) except BaseException as e: # pylint: disable=broad-except native.LogInfo('Internal error during data capture: %s' % repr(e)) error_status = {'isError': True, 'description': { 'format': ('Internal error while capturing data: %s' % repr(e))}} self._CompleteBreakpoint({'status': error_status}) return except: # pylint: disable=bare-except native.LogInfo('Unknown exception raised') error_status = {'isError': True, 'description': { 'format': 'Unknown internal error'}} self._CompleteBreakpoint({'status': error_status}) return self._CompleteBreakpoint(collector.breakpoint, is_incremental=False)
python
def _BreakpointEvent(self, event, frame): error_status = None if event != native.BREAKPOINT_EVENT_HIT: error_status = _BREAKPOINT_EVENT_STATUS[event] elif self.definition.get('action') == 'LOG': error_status = self._collector.Log(frame) if not error_status: return # Log action successful, no need to clear the breakpoint. # Let only one thread capture the data and complete the breakpoint. if not self._SetCompleted(): return self.Clear() if error_status: self._CompleteBreakpoint({'status': error_status}) return collector = capture_collector.CaptureCollector( self.definition, self.data_visibility_policy) # TODO(b/69119299): This is a temporary try/except. All exceptions should be # caught inside Collect and converted into breakpoint error messages. try: collector.Collect(frame) except BaseException as e: # pylint: disable=broad-except native.LogInfo('Internal error during data capture: %s' % repr(e)) error_status = {'isError': True, 'description': { 'format': ('Internal error while capturing data: %s' % repr(e))}} self._CompleteBreakpoint({'status': error_status}) return except: # pylint: disable=bare-except native.LogInfo('Unknown exception raised') error_status = {'isError': True, 'description': { 'format': 'Unknown internal error'}} self._CompleteBreakpoint({'status': error_status}) return self._CompleteBreakpoint(collector.breakpoint, is_incremental=False)
[ "def", "_BreakpointEvent", "(", "self", ",", "event", ",", "frame", ")", ":", "error_status", "=", "None", "if", "event", "!=", "native", ".", "BREAKPOINT_EVENT_HIT", ":", "error_status", "=", "_BREAKPOINT_EVENT_STATUS", "[", "event", "]", "elif", "self", ".",...
Callback invoked by cdbg_native when breakpoint hits. Args: event: breakpoint event (see kIntegerConstants in native_module.cc). frame: Python stack frame of breakpoint hit or None for other events.
[ "Callback", "invoked", "by", "cdbg_native", "when", "breakpoint", "hits", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/python_breakpoint.py#L372-L421
230,962
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/module_search2.py
Search
def Search(path): """Search sys.path to find a source file that matches path. The provided input path may have an unknown number of irrelevant outer directories (e.g., /garbage1/garbage2/real1/real2/x.py'). This function does multiple search iterations until an actual Python module file that matches the input path is found. At each iteration, it strips one leading directory from the path and searches the directories at sys.path for a match. Examples: sys.path: ['/x1/x2', '/y1/y2'] Search order: [.pyo|.pyc|.py] /x1/x2/a/b/c /x1/x2/b/c /x1/x2/c /y1/y2/a/b/c /y1/y2/b/c /y1/y2/c Filesystem: ['/y1/y2/a/b/c.pyc'] 1) Search('a/b/c.py') Returns '/y1/y2/a/b/c.pyc' 2) Search('q/w/a/b/c.py') Returns '/y1/y2/a/b/c.pyc' 3) Search('q/w/c.py') Returns 'q/w/c.py' The provided input path may also be relative to an unknown directory. The path may include some or all outer package names. Examples (continued): 4) Search('c.py') Returns 'c.py' 5) Search('b/c.py') Returns 'b/c.py' Args: path: Path that describes a source file. Must contain .py file extension. Must not contain any leading os.sep character. Returns: Full path to the matched source file, if a match is found. Otherwise, returns the input path. Raises: AssertionError: if the provided path is an absolute path, or if it does not have a .py extension. """ def SearchCandidates(p): """Generates all candidates for the fuzzy search of p.""" while p: yield p (_, _, p) = p.partition(os.sep) # Verify that the os.sep is already stripped from the input. assert not path.startswith(os.sep) # Strip the file extension, it will not be needed. src_root, src_ext = os.path.splitext(path) assert src_ext == '.py' # Search longer suffixes first. Move to shorter suffixes only if longer # suffixes do not result in any matches. for src_part in SearchCandidates(src_root): # Search is done in sys.path order, which gives higher priority to earlier # entries in sys.path list. for sys_path in sys.path: f = os.path.join(sys_path, src_part) # The order in which we search the extensions does not matter. for ext in ('.pyo', '.pyc', '.py'): # The os.path.exists check internally follows symlinks and flattens # relative paths, so we don't have to deal with it. fext = f + ext if os.path.exists(fext): # Once we identify a matching file in the filesystem, we should # preserve the (1) potentially-symlinked and (2) # potentially-non-flattened file path (f+ext), because that's exactly # how we expect it to appear in sys.modules when we search the file # there. return fext # A matching file was not found in sys.path directories. return path
python
def Search(path): def SearchCandidates(p): """Generates all candidates for the fuzzy search of p.""" while p: yield p (_, _, p) = p.partition(os.sep) # Verify that the os.sep is already stripped from the input. assert not path.startswith(os.sep) # Strip the file extension, it will not be needed. src_root, src_ext = os.path.splitext(path) assert src_ext == '.py' # Search longer suffixes first. Move to shorter suffixes only if longer # suffixes do not result in any matches. for src_part in SearchCandidates(src_root): # Search is done in sys.path order, which gives higher priority to earlier # entries in sys.path list. for sys_path in sys.path: f = os.path.join(sys_path, src_part) # The order in which we search the extensions does not matter. for ext in ('.pyo', '.pyc', '.py'): # The os.path.exists check internally follows symlinks and flattens # relative paths, so we don't have to deal with it. fext = f + ext if os.path.exists(fext): # Once we identify a matching file in the filesystem, we should # preserve the (1) potentially-symlinked and (2) # potentially-non-flattened file path (f+ext), because that's exactly # how we expect it to appear in sys.modules when we search the file # there. return fext # A matching file was not found in sys.path directories. return path
[ "def", "Search", "(", "path", ")", ":", "def", "SearchCandidates", "(", "p", ")", ":", "\"\"\"Generates all candidates for the fuzzy search of p.\"\"\"", "while", "p", ":", "yield", "p", "(", "_", ",", "_", ",", "p", ")", "=", "p", ".", "partition", "(", "...
Search sys.path to find a source file that matches path. The provided input path may have an unknown number of irrelevant outer directories (e.g., /garbage1/garbage2/real1/real2/x.py'). This function does multiple search iterations until an actual Python module file that matches the input path is found. At each iteration, it strips one leading directory from the path and searches the directories at sys.path for a match. Examples: sys.path: ['/x1/x2', '/y1/y2'] Search order: [.pyo|.pyc|.py] /x1/x2/a/b/c /x1/x2/b/c /x1/x2/c /y1/y2/a/b/c /y1/y2/b/c /y1/y2/c Filesystem: ['/y1/y2/a/b/c.pyc'] 1) Search('a/b/c.py') Returns '/y1/y2/a/b/c.pyc' 2) Search('q/w/a/b/c.py') Returns '/y1/y2/a/b/c.pyc' 3) Search('q/w/c.py') Returns 'q/w/c.py' The provided input path may also be relative to an unknown directory. The path may include some or all outer package names. Examples (continued): 4) Search('c.py') Returns 'c.py' 5) Search('b/c.py') Returns 'b/c.py' Args: path: Path that describes a source file. Must contain .py file extension. Must not contain any leading os.sep character. Returns: Full path to the matched source file, if a match is found. Otherwise, returns the input path. Raises: AssertionError: if the provided path is an absolute path, or if it does not have a .py extension.
[ "Search", "sys", ".", "path", "to", "find", "a", "source", "file", "that", "matches", "path", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/module_search2.py#L21-L105
230,963
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/__init__.py
_StartDebugger
def _StartDebugger(): """Configures and starts the debugger.""" global _hub_client global _breakpoints_manager cdbg_native.InitializeModule(_flags) _hub_client = gcp_hub_client.GcpHubClient() visibility_policy = _GetVisibilityPolicy() _breakpoints_manager = breakpoints_manager.BreakpointsManager( _hub_client, visibility_policy) # Set up loggers for logpoints. capture_collector.SetLogger(logging.getLogger()) capture_collector.CaptureCollector.pretty_printers.append( appengine_pretty_printers.PrettyPrinter) _hub_client.on_active_breakpoints_changed = ( _breakpoints_manager.SetActiveBreakpoints) _hub_client.on_idle = _breakpoints_manager.CheckBreakpointsExpiration _hub_client.SetupAuth( _flags.get('project_id'), _flags.get('project_number'), _flags.get('service_account_json_file')) _hub_client.InitializeDebuggeeLabels(_flags) _hub_client.Start()
python
def _StartDebugger(): global _hub_client global _breakpoints_manager cdbg_native.InitializeModule(_flags) _hub_client = gcp_hub_client.GcpHubClient() visibility_policy = _GetVisibilityPolicy() _breakpoints_manager = breakpoints_manager.BreakpointsManager( _hub_client, visibility_policy) # Set up loggers for logpoints. capture_collector.SetLogger(logging.getLogger()) capture_collector.CaptureCollector.pretty_printers.append( appengine_pretty_printers.PrettyPrinter) _hub_client.on_active_breakpoints_changed = ( _breakpoints_manager.SetActiveBreakpoints) _hub_client.on_idle = _breakpoints_manager.CheckBreakpointsExpiration _hub_client.SetupAuth( _flags.get('project_id'), _flags.get('project_number'), _flags.get('service_account_json_file')) _hub_client.InitializeDebuggeeLabels(_flags) _hub_client.Start()
[ "def", "_StartDebugger", "(", ")", ":", "global", "_hub_client", "global", "_breakpoints_manager", "cdbg_native", ".", "InitializeModule", "(", "_flags", ")", "_hub_client", "=", "gcp_hub_client", ".", "GcpHubClient", "(", ")", "visibility_policy", "=", "_GetVisibilit...
Configures and starts the debugger.
[ "Configures", "and", "starts", "the", "debugger", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/__init__.py#L46-L74
230,964
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/__init__.py
_GetVisibilityPolicy
def _GetVisibilityPolicy(): """If a debugger configuration is found, create a visibility policy.""" try: visibility_config = yaml_data_visibility_config_reader.OpenAndRead() except yaml_data_visibility_config_reader.Error as err: return error_data_visibility_policy.ErrorDataVisibilityPolicy( 'Could not process debugger config: %s' % err) if visibility_config: return glob_data_visibility_policy.GlobDataVisibilityPolicy( visibility_config.blacklist_patterns, visibility_config.whitelist_patterns) return None
python
def _GetVisibilityPolicy(): try: visibility_config = yaml_data_visibility_config_reader.OpenAndRead() except yaml_data_visibility_config_reader.Error as err: return error_data_visibility_policy.ErrorDataVisibilityPolicy( 'Could not process debugger config: %s' % err) if visibility_config: return glob_data_visibility_policy.GlobDataVisibilityPolicy( visibility_config.blacklist_patterns, visibility_config.whitelist_patterns) return None
[ "def", "_GetVisibilityPolicy", "(", ")", ":", "try", ":", "visibility_config", "=", "yaml_data_visibility_config_reader", ".", "OpenAndRead", "(", ")", "except", "yaml_data_visibility_config_reader", ".", "Error", "as", "err", ":", "return", "error_data_visibility_policy"...
If a debugger configuration is found, create a visibility policy.
[ "If", "a", "debugger", "configuration", "is", "found", "create", "a", "visibility", "policy", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/__init__.py#L77-L90
230,965
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/__init__.py
_DebuggerMain
def _DebuggerMain(): """Starts the debugger and runs the application with debugger attached.""" global _flags # The first argument is cdbg module, which we don't care. del sys.argv[0] # Parse debugger flags until we encounter '--'. _flags = {} while sys.argv[0]: arg = sys.argv[0] del sys.argv[0] if arg == '--': break (name, value) = arg.strip('-').split('=', 2) _flags[name] = value _StartDebugger() # Run the app. The following code was mostly copied from pdb.py. app_path = sys.argv[0] sys.path[0] = os.path.dirname(app_path) import __main__ # pylint: disable=g-import-not-at-top __main__.__dict__.clear() __main__.__dict__.update({'__name__': '__main__', '__file__': app_path, '__builtins__': __builtins__}) locals = globals = __main__.__dict__ # pylint: disable=redefined-builtin sys.modules['__main__'] = __main__ with open(app_path) as f: code = compile(f.read(), app_path, 'exec') exec(code, globals, locals)
python
def _DebuggerMain(): global _flags # The first argument is cdbg module, which we don't care. del sys.argv[0] # Parse debugger flags until we encounter '--'. _flags = {} while sys.argv[0]: arg = sys.argv[0] del sys.argv[0] if arg == '--': break (name, value) = arg.strip('-').split('=', 2) _flags[name] = value _StartDebugger() # Run the app. The following code was mostly copied from pdb.py. app_path = sys.argv[0] sys.path[0] = os.path.dirname(app_path) import __main__ # pylint: disable=g-import-not-at-top __main__.__dict__.clear() __main__.__dict__.update({'__name__': '__main__', '__file__': app_path, '__builtins__': __builtins__}) locals = globals = __main__.__dict__ # pylint: disable=redefined-builtin sys.modules['__main__'] = __main__ with open(app_path) as f: code = compile(f.read(), app_path, 'exec') exec(code, globals, locals)
[ "def", "_DebuggerMain", "(", ")", ":", "global", "_flags", "# The first argument is cdbg module, which we don't care.", "del", "sys", ".", "argv", "[", "0", "]", "# Parse debugger flags until we encounter '--'.", "_flags", "=", "{", "}", "while", "sys", ".", "argv", "...
Starts the debugger and runs the application with debugger attached.
[ "Starts", "the", "debugger", "and", "runs", "the", "application", "with", "debugger", "attached", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/__init__.py#L93-L130
230,966
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/glob_data_visibility_policy.py
_Matches
def _Matches(path, pattern_list): """Returns true if path matches any patten found in pattern_list. Args: path: A dot separated path to a package, class, method or variable pattern_list: A list of wildcard patterns Returns: True if path matches any wildcard found in pattern_list. """ # Note: This code does not scale to large pattern_list sizes. return any(fnmatch.fnmatchcase(path, pattern) for pattern in pattern_list)
python
def _Matches(path, pattern_list): # Note: This code does not scale to large pattern_list sizes. return any(fnmatch.fnmatchcase(path, pattern) for pattern in pattern_list)
[ "def", "_Matches", "(", "path", ",", "pattern_list", ")", ":", "# Note: This code does not scale to large pattern_list sizes.", "return", "any", "(", "fnmatch", ".", "fnmatchcase", "(", "path", ",", "pattern", ")", "for", "pattern", "in", "pattern_list", ")" ]
Returns true if path matches any patten found in pattern_list. Args: path: A dot separated path to a package, class, method or variable pattern_list: A list of wildcard patterns Returns: True if path matches any wildcard found in pattern_list.
[ "Returns", "true", "if", "path", "matches", "any", "patten", "found", "in", "pattern_list", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/glob_data_visibility_policy.py#L77-L88
230,967
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/breakpoints_manager.py
BreakpointsManager.SetActiveBreakpoints
def SetActiveBreakpoints(self, breakpoints_data): """Adds new breakpoints and removes missing ones. Args: breakpoints_data: updated list of active breakpoints. """ with self._lock: ids = set([x['id'] for x in breakpoints_data]) # Clear breakpoints that no longer show up in active breakpoints list. for breakpoint_id in six.viewkeys(self._active) - ids: self._active.pop(breakpoint_id).Clear() # Create new breakpoints. self._active.update([ (x['id'], python_breakpoint.PythonBreakpoint( x, self._hub_client, self, self.data_visibility_policy)) for x in breakpoints_data if x['id'] in ids - six.viewkeys(self._active) - self._completed]) # Remove entries from completed_breakpoints_ that weren't listed in # breakpoints_data vector. These are confirmed to have been removed by the # hub and the debuglet can now assume that they will never show up ever # again. The backend never reuses breakpoint IDs. self._completed &= ids if self._active: self._next_expiration = datetime.min # Not known. else: self._next_expiration = datetime.max
python
def SetActiveBreakpoints(self, breakpoints_data): with self._lock: ids = set([x['id'] for x in breakpoints_data]) # Clear breakpoints that no longer show up in active breakpoints list. for breakpoint_id in six.viewkeys(self._active) - ids: self._active.pop(breakpoint_id).Clear() # Create new breakpoints. self._active.update([ (x['id'], python_breakpoint.PythonBreakpoint( x, self._hub_client, self, self.data_visibility_policy)) for x in breakpoints_data if x['id'] in ids - six.viewkeys(self._active) - self._completed]) # Remove entries from completed_breakpoints_ that weren't listed in # breakpoints_data vector. These are confirmed to have been removed by the # hub and the debuglet can now assume that they will never show up ever # again. The backend never reuses breakpoint IDs. self._completed &= ids if self._active: self._next_expiration = datetime.min # Not known. else: self._next_expiration = datetime.max
[ "def", "SetActiveBreakpoints", "(", "self", ",", "breakpoints_data", ")", ":", "with", "self", ".", "_lock", ":", "ids", "=", "set", "(", "[", "x", "[", "'id'", "]", "for", "x", "in", "breakpoints_data", "]", ")", "# Clear breakpoints that no longer show up in...
Adds new breakpoints and removes missing ones. Args: breakpoints_data: updated list of active breakpoints.
[ "Adds", "new", "breakpoints", "and", "removes", "missing", "ones", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/breakpoints_manager.py#L65-L98
230,968
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/breakpoints_manager.py
BreakpointsManager.CompleteBreakpoint
def CompleteBreakpoint(self, breakpoint_id): """Marks the specified breaking as completed. Appends the ID to set of completed breakpoints and clears it. Args: breakpoint_id: breakpoint ID to complete. """ with self._lock: self._completed.add(breakpoint_id) if breakpoint_id in self._active: self._active.pop(breakpoint_id).Clear()
python
def CompleteBreakpoint(self, breakpoint_id): with self._lock: self._completed.add(breakpoint_id) if breakpoint_id in self._active: self._active.pop(breakpoint_id).Clear()
[ "def", "CompleteBreakpoint", "(", "self", ",", "breakpoint_id", ")", ":", "with", "self", ".", "_lock", ":", "self", ".", "_completed", ".", "add", "(", "breakpoint_id", ")", "if", "breakpoint_id", "in", "self", ".", "_active", ":", "self", ".", "_active",...
Marks the specified breaking as completed. Appends the ID to set of completed breakpoints and clears it. Args: breakpoint_id: breakpoint ID to complete.
[ "Marks", "the", "specified", "breaking", "as", "completed", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/breakpoints_manager.py#L100-L111
230,969
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/breakpoints_manager.py
BreakpointsManager.CheckBreakpointsExpiration
def CheckBreakpointsExpiration(self): """Completes all breakpoints that have been active for too long.""" with self._lock: current_time = BreakpointsManager.GetCurrentTime() if self._next_expiration > current_time: return expired_breakpoints = [] self._next_expiration = datetime.max for breakpoint in six.itervalues(self._active): expiration_time = breakpoint.GetExpirationTime() if expiration_time <= current_time: expired_breakpoints.append(breakpoint) else: self._next_expiration = min(self._next_expiration, expiration_time) for breakpoint in expired_breakpoints: breakpoint.ExpireBreakpoint()
python
def CheckBreakpointsExpiration(self): with self._lock: current_time = BreakpointsManager.GetCurrentTime() if self._next_expiration > current_time: return expired_breakpoints = [] self._next_expiration = datetime.max for breakpoint in six.itervalues(self._active): expiration_time = breakpoint.GetExpirationTime() if expiration_time <= current_time: expired_breakpoints.append(breakpoint) else: self._next_expiration = min(self._next_expiration, expiration_time) for breakpoint in expired_breakpoints: breakpoint.ExpireBreakpoint()
[ "def", "CheckBreakpointsExpiration", "(", "self", ")", ":", "with", "self", ".", "_lock", ":", "current_time", "=", "BreakpointsManager", ".", "GetCurrentTime", "(", ")", "if", "self", ".", "_next_expiration", ">", "current_time", ":", "return", "expired_breakpoin...
Completes all breakpoints that have been active for too long.
[ "Completes", "all", "breakpoints", "that", "have", "been", "active", "for", "too", "long", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/breakpoints_manager.py#L113-L130
230,970
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/appengine_pretty_printers.py
PrettyPrinter
def PrettyPrinter(obj): """Pretty printers for AppEngine objects.""" if ndb and isinstance(obj, ndb.Model): return six.iteritems(obj.to_dict()), 'ndb.Model(%s)' % type(obj).__name__ if messages and isinstance(obj, messages.Enum): return [('name', obj.name), ('number', obj.number)], type(obj).__name__ return None
python
def PrettyPrinter(obj): if ndb and isinstance(obj, ndb.Model): return six.iteritems(obj.to_dict()), 'ndb.Model(%s)' % type(obj).__name__ if messages and isinstance(obj, messages.Enum): return [('name', obj.name), ('number', obj.number)], type(obj).__name__ return None
[ "def", "PrettyPrinter", "(", "obj", ")", ":", "if", "ndb", "and", "isinstance", "(", "obj", ",", "ndb", ".", "Model", ")", ":", "return", "six", ".", "iteritems", "(", "obj", ".", "to_dict", "(", ")", ")", ",", "'ndb.Model(%s)'", "%", "type", "(", ...
Pretty printers for AppEngine objects.
[ "Pretty", "printers", "for", "AppEngine", "objects", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/appengine_pretty_printers.py#L30-L39
230,971
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/module_utils2.py
IsPathSuffix
def IsPathSuffix(mod_path, path): """Checks whether path is a full path suffix of mod_path. Args: mod_path: Must be an absolute path to a source file. Must not have file extension. path: A relative path. Must not have file extension. Returns: True if path is a full path suffix of mod_path. False otherwise. """ return (mod_path.endswith(path) and (len(mod_path) == len(path) or mod_path[:-len(path)].endswith(os.sep)))
python
def IsPathSuffix(mod_path, path): return (mod_path.endswith(path) and (len(mod_path) == len(path) or mod_path[:-len(path)].endswith(os.sep)))
[ "def", "IsPathSuffix", "(", "mod_path", ",", "path", ")", ":", "return", "(", "mod_path", ".", "endswith", "(", "path", ")", "and", "(", "len", "(", "mod_path", ")", "==", "len", "(", "path", ")", "or", "mod_path", "[", ":", "-", "len", "(", "path"...
Checks whether path is a full path suffix of mod_path. Args: mod_path: Must be an absolute path to a source file. Must not have file extension. path: A relative path. Must not have file extension. Returns: True if path is a full path suffix of mod_path. False otherwise.
[ "Checks", "whether", "path", "is", "a", "full", "path", "suffix", "of", "mod_path", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/module_utils2.py#L21-L34
230,972
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/module_utils2.py
GetLoadedModuleBySuffix
def GetLoadedModuleBySuffix(path): """Searches sys.modules to find a module with the given file path. Args: path: Path to the source file. It can be relative or absolute, as suffix match can handle both. If absolute, it must have already been sanitized. Algorithm: The given path must be a full suffix of a loaded module to be a valid match. File extensions are ignored when performing suffix match. Example: path: 'a/b/c.py' modules: {'a': 'a.py', 'a.b': 'a/b.py', 'a.b.c': 'a/b/c.pyc'] returns: module('a.b.c') Returns: The module that corresponds to path, or None if such module was not found. """ root = os.path.splitext(path)[0] for module in sys.modules.values(): mod_root = os.path.splitext(getattr(module, '__file__', None) or '')[0] if not mod_root: continue # While mod_root can contain symlinks, we cannot eliminate them. This is # because, we must perform exactly the same transformations on mod_root and # path, yet path can be relative to an unknown directory which prevents # identifying and eliminating symbolic links. # # Therefore, we only convert relative to absolute path. if not os.path.isabs(mod_root): mod_root = os.path.join(os.getcwd(), mod_root) if IsPathSuffix(mod_root, root): return module return None
python
def GetLoadedModuleBySuffix(path): root = os.path.splitext(path)[0] for module in sys.modules.values(): mod_root = os.path.splitext(getattr(module, '__file__', None) or '')[0] if not mod_root: continue # While mod_root can contain symlinks, we cannot eliminate them. This is # because, we must perform exactly the same transformations on mod_root and # path, yet path can be relative to an unknown directory which prevents # identifying and eliminating symbolic links. # # Therefore, we only convert relative to absolute path. if not os.path.isabs(mod_root): mod_root = os.path.join(os.getcwd(), mod_root) if IsPathSuffix(mod_root, root): return module return None
[ "def", "GetLoadedModuleBySuffix", "(", "path", ")", ":", "root", "=", "os", ".", "path", ".", "splitext", "(", "path", ")", "[", "0", "]", "for", "module", "in", "sys", ".", "modules", ".", "values", "(", ")", ":", "mod_root", "=", "os", ".", "path...
Searches sys.modules to find a module with the given file path. Args: path: Path to the source file. It can be relative or absolute, as suffix match can handle both. If absolute, it must have already been sanitized. Algorithm: The given path must be a full suffix of a loaded module to be a valid match. File extensions are ignored when performing suffix match. Example: path: 'a/b/c.py' modules: {'a': 'a.py', 'a.b': 'a/b.py', 'a.b.c': 'a/b/c.pyc'] returns: module('a.b.c') Returns: The module that corresponds to path, or None if such module was not found.
[ "Searches", "sys", ".", "modules", "to", "find", "a", "module", "with", "the", "given", "file", "path", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/module_utils2.py#L37-L77
230,973
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/module_explorer.py
GetCodeObjectAtLine
def GetCodeObjectAtLine(module, line): """Searches for a code object at the specified line in the specified module. Args: module: module to explore. line: 1-based line number of the statement. Returns: (True, Code object) on success or (False, (prev_line, next_line)) on failure, where prev_line and next_line are the closest lines with code above and below the specified line, or None if they do not exist. """ if not hasattr(module, '__file__'): return (False, (None, None)) prev_line = 0 next_line = six.MAXSIZE for code_object in _GetModuleCodeObjects(module): for co_line_number in _GetLineNumbers(code_object): if co_line_number == line: return (True, code_object) elif co_line_number < line: prev_line = max(prev_line, co_line_number) elif co_line_number > line: next_line = min(next_line, co_line_number) break prev_line = None if prev_line == 0 else prev_line next_line = None if next_line == six.MAXSIZE else next_line return (False, (prev_line, next_line))
python
def GetCodeObjectAtLine(module, line): if not hasattr(module, '__file__'): return (False, (None, None)) prev_line = 0 next_line = six.MAXSIZE for code_object in _GetModuleCodeObjects(module): for co_line_number in _GetLineNumbers(code_object): if co_line_number == line: return (True, code_object) elif co_line_number < line: prev_line = max(prev_line, co_line_number) elif co_line_number > line: next_line = min(next_line, co_line_number) break prev_line = None if prev_line == 0 else prev_line next_line = None if next_line == six.MAXSIZE else next_line return (False, (prev_line, next_line))
[ "def", "GetCodeObjectAtLine", "(", "module", ",", "line", ")", ":", "if", "not", "hasattr", "(", "module", ",", "'__file__'", ")", ":", "return", "(", "False", ",", "(", "None", ",", "None", ")", ")", "prev_line", "=", "0", "next_line", "=", "six", "...
Searches for a code object at the specified line in the specified module. Args: module: module to explore. line: 1-based line number of the statement. Returns: (True, Code object) on success or (False, (prev_line, next_line)) on failure, where prev_line and next_line are the closest lines with code above and below the specified line, or None if they do not exist.
[ "Searches", "for", "a", "code", "object", "at", "the", "specified", "line", "in", "the", "specified", "module", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/module_explorer.py#L43-L73
230,974
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/module_explorer.py
_GetLineNumbers
def _GetLineNumbers(code_object): """Generator for getting the line numbers of a code object. Args: code_object: the code object. Yields: The next line number in the code object. """ # Get the line number deltas, which are the odd number entries, from the # lnotab. See # https://svn.python.org/projects/python/branches/pep-0384/Objects/lnotab_notes.txt # In Python 3, this is just a byte array. In Python 2 it is a string so the # numerical values have to be extracted from the individual characters. if six.PY3: line_incrs = code_object.co_lnotab[1::2] else: line_incrs = (ord(c) for c in code_object.co_lnotab[1::2]) current_line = code_object.co_firstlineno for line_incr in line_incrs: current_line += line_incr yield current_line
python
def _GetLineNumbers(code_object): # Get the line number deltas, which are the odd number entries, from the # lnotab. See # https://svn.python.org/projects/python/branches/pep-0384/Objects/lnotab_notes.txt # In Python 3, this is just a byte array. In Python 2 it is a string so the # numerical values have to be extracted from the individual characters. if six.PY3: line_incrs = code_object.co_lnotab[1::2] else: line_incrs = (ord(c) for c in code_object.co_lnotab[1::2]) current_line = code_object.co_firstlineno for line_incr in line_incrs: current_line += line_incr yield current_line
[ "def", "_GetLineNumbers", "(", "code_object", ")", ":", "# Get the line number deltas, which are the odd number entries, from the", "# lnotab. See", "# https://svn.python.org/projects/python/branches/pep-0384/Objects/lnotab_notes.txt", "# In Python 3, this is just a byte array. In Python 2 it is a...
Generator for getting the line numbers of a code object. Args: code_object: the code object. Yields: The next line number in the code object.
[ "Generator", "for", "getting", "the", "line", "numbers", "of", "a", "code", "object", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/module_explorer.py#L76-L97
230,975
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/module_explorer.py
_GetModuleCodeObjects
def _GetModuleCodeObjects(module): """Gets all code objects defined in the specified module. There are two BFS traversals involved. One in this function and the other in _FindCodeObjectsReferents. Only the BFS in _FindCodeObjectsReferents has a depth limit. This function does not. The motivation is that this function explores code object of the module and they can have any arbitrary nesting level. _FindCodeObjectsReferents, on the other hand, traverses through class definitions and random references. It's much more expensive and will likely go into unrelated objects. There is also a limit on how many total objects are going to be traversed in all. This limit makes sure that if something goes wrong, the lookup doesn't hang. Args: module: module to explore. Returns: Set of code objects defined in module. """ visit_recorder = _VisitRecorder() current = [module] code_objects = set() while current: current = _FindCodeObjectsReferents(module, current, visit_recorder) code_objects |= current # Unfortunately Python code objects don't implement tp_traverse, so this # type can't be used with gc.get_referents. The workaround is to get the # relevant objects explicitly here. current = [code_object.co_consts for code_object in current] return code_objects
python
def _GetModuleCodeObjects(module): visit_recorder = _VisitRecorder() current = [module] code_objects = set() while current: current = _FindCodeObjectsReferents(module, current, visit_recorder) code_objects |= current # Unfortunately Python code objects don't implement tp_traverse, so this # type can't be used with gc.get_referents. The workaround is to get the # relevant objects explicitly here. current = [code_object.co_consts for code_object in current] return code_objects
[ "def", "_GetModuleCodeObjects", "(", "module", ")", ":", "visit_recorder", "=", "_VisitRecorder", "(", ")", "current", "=", "[", "module", "]", "code_objects", "=", "set", "(", ")", "while", "current", ":", "current", "=", "_FindCodeObjectsReferents", "(", "mo...
Gets all code objects defined in the specified module. There are two BFS traversals involved. One in this function and the other in _FindCodeObjectsReferents. Only the BFS in _FindCodeObjectsReferents has a depth limit. This function does not. The motivation is that this function explores code object of the module and they can have any arbitrary nesting level. _FindCodeObjectsReferents, on the other hand, traverses through class definitions and random references. It's much more expensive and will likely go into unrelated objects. There is also a limit on how many total objects are going to be traversed in all. This limit makes sure that if something goes wrong, the lookup doesn't hang. Args: module: module to explore. Returns: Set of code objects defined in module.
[ "Gets", "all", "code", "objects", "defined", "in", "the", "specified", "module", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/module_explorer.py#L100-L134
230,976
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/module_explorer.py
_FindCodeObjectsReferents
def _FindCodeObjectsReferents(module, start_objects, visit_recorder): """Looks for all the code objects referenced by objects in start_objects. The traversal implemented by this function is a shallow one. In other words if the reference chain is a -> b -> co1 -> c -> co2, this function will return [co1] only. The traversal is implemented with BFS. The maximum depth is limited to avoid touching all the objects in the process. Each object is only visited once using visit_recorder. Args: module: module in which we are looking for code objects. start_objects: initial set of objects for the BFS traversal. visit_recorder: instance of _VisitRecorder class to ensure each object is visited at most once. Returns: List of code objects. """ def CheckIgnoreCodeObject(code_object): """Checks if the code object can be ignored. Code objects that are not implemented in the module, or are from a lambda or generator expression can be ignored. If the module was precompiled, the code object may point to .py file, while the module says that it originated from .pyc file. We just strip extension altogether to work around it. Args: code_object: code object that we want to check against module. Returns: True if the code object can be ignored, False otherwise. """ if code_object.co_name in ('<lambda>', '<genexpr>'): return True code_object_file = os.path.splitext(code_object.co_filename)[0] module_file = os.path.splitext(module.__file__)[0] # The simple case. if code_object_file == module_file: return False return True def CheckIgnoreClass(cls): """Returns True if the class is definitely not coming from "module".""" cls_module = sys.modules.get(cls.__module__) if not cls_module: return False # We can't tell for sure, so explore this class. return ( cls_module is not module and getattr(cls_module, '__file__', None) != module.__file__) code_objects = set() current = start_objects for obj in current: visit_recorder.Record(current) depth = 0 while current and depth < _MAX_REFERENTS_BFS_DEPTH: new_current = [] for current_obj in current: referents = gc.get_referents(current_obj) if (current_obj is not module.__dict__ and len(referents) > _MAX_OBJECT_REFERENTS): continue for obj in referents: if isinstance(obj, _BFS_IGNORE_TYPES) or not visit_recorder.Record(obj): continue if isinstance(obj, types.CodeType) and CheckIgnoreCodeObject(obj): continue if isinstance(obj, six.class_types) and CheckIgnoreClass(obj): continue if isinstance(obj, types.CodeType): code_objects.add(obj) else: new_current.append(obj) current = new_current depth += 1 return code_objects
python
def _FindCodeObjectsReferents(module, start_objects, visit_recorder): def CheckIgnoreCodeObject(code_object): """Checks if the code object can be ignored. Code objects that are not implemented in the module, or are from a lambda or generator expression can be ignored. If the module was precompiled, the code object may point to .py file, while the module says that it originated from .pyc file. We just strip extension altogether to work around it. Args: code_object: code object that we want to check against module. Returns: True if the code object can be ignored, False otherwise. """ if code_object.co_name in ('<lambda>', '<genexpr>'): return True code_object_file = os.path.splitext(code_object.co_filename)[0] module_file = os.path.splitext(module.__file__)[0] # The simple case. if code_object_file == module_file: return False return True def CheckIgnoreClass(cls): """Returns True if the class is definitely not coming from "module".""" cls_module = sys.modules.get(cls.__module__) if not cls_module: return False # We can't tell for sure, so explore this class. return ( cls_module is not module and getattr(cls_module, '__file__', None) != module.__file__) code_objects = set() current = start_objects for obj in current: visit_recorder.Record(current) depth = 0 while current and depth < _MAX_REFERENTS_BFS_DEPTH: new_current = [] for current_obj in current: referents = gc.get_referents(current_obj) if (current_obj is not module.__dict__ and len(referents) > _MAX_OBJECT_REFERENTS): continue for obj in referents: if isinstance(obj, _BFS_IGNORE_TYPES) or not visit_recorder.Record(obj): continue if isinstance(obj, types.CodeType) and CheckIgnoreCodeObject(obj): continue if isinstance(obj, six.class_types) and CheckIgnoreClass(obj): continue if isinstance(obj, types.CodeType): code_objects.add(obj) else: new_current.append(obj) current = new_current depth += 1 return code_objects
[ "def", "_FindCodeObjectsReferents", "(", "module", ",", "start_objects", ",", "visit_recorder", ")", ":", "def", "CheckIgnoreCodeObject", "(", "code_object", ")", ":", "\"\"\"Checks if the code object can be ignored.\n\n Code objects that are not implemented in the module, or are ...
Looks for all the code objects referenced by objects in start_objects. The traversal implemented by this function is a shallow one. In other words if the reference chain is a -> b -> co1 -> c -> co2, this function will return [co1] only. The traversal is implemented with BFS. The maximum depth is limited to avoid touching all the objects in the process. Each object is only visited once using visit_recorder. Args: module: module in which we are looking for code objects. start_objects: initial set of objects for the BFS traversal. visit_recorder: instance of _VisitRecorder class to ensure each object is visited at most once. Returns: List of code objects.
[ "Looks", "for", "all", "the", "code", "objects", "referenced", "by", "objects", "in", "start_objects", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/module_explorer.py#L137-L227
230,977
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/module_explorer.py
_VisitRecorder.Record
def Record(self, obj): """Records the object as visited. Args: obj: visited object. Returns: True if the object hasn't been previously visited or False if it has already been recorded or the quota has been exhausted. """ if len(self._visit_recorder_objects) >= _MAX_VISIT_OBJECTS: return False obj_id = id(obj) if obj_id in self._visit_recorder_objects: return False self._visit_recorder_objects[obj_id] = obj return True
python
def Record(self, obj): if len(self._visit_recorder_objects) >= _MAX_VISIT_OBJECTS: return False obj_id = id(obj) if obj_id in self._visit_recorder_objects: return False self._visit_recorder_objects[obj_id] = obj return True
[ "def", "Record", "(", "self", ",", "obj", ")", ":", "if", "len", "(", "self", ".", "_visit_recorder_objects", ")", ">=", "_MAX_VISIT_OBJECTS", ":", "return", "False", "obj_id", "=", "id", "(", "obj", ")", "if", "obj_id", "in", "self", ".", "_visit_record...
Records the object as visited. Args: obj: visited object. Returns: True if the object hasn't been previously visited or False if it has already been recorded or the quota has been exhausted.
[ "Records", "the", "object", "as", "visited", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/module_explorer.py#L242-L260
230,978
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/backoff.py
Backoff.Failed
def Failed(self): """Indicates that a request has failed. Returns: Time interval to wait before retrying (in seconds). """ interval = self._current_interval_sec self._current_interval_sec = min( self.max_interval_sec, self._current_interval_sec * self.multiplier) return interval
python
def Failed(self): interval = self._current_interval_sec self._current_interval_sec = min( self.max_interval_sec, self._current_interval_sec * self.multiplier) return interval
[ "def", "Failed", "(", "self", ")", ":", "interval", "=", "self", ".", "_current_interval_sec", "self", ".", "_current_interval_sec", "=", "min", "(", "self", ".", "max_interval_sec", ",", "self", ".", "_current_interval_sec", "*", "self", ".", "multiplier", ")...
Indicates that a request has failed. Returns: Time interval to wait before retrying (in seconds).
[ "Indicates", "that", "a", "request", "has", "failed", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/backoff.py#L49-L58
230,979
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/uniquifier_computer.py
ComputeApplicationUniquifier
def ComputeApplicationUniquifier(hash_obj): """Computes hash of application files. Application files can be anywhere on the disk. The application is free to import a Python module from an arbitrary path ok the disk. It is also impossible to distinguish application files from third party libraries. Third party libraries are typically installed with "pip" and there is not a good way to guarantee that all instances of the application are going to have exactly the same version of each package. There is also a huge amount of files in all sys.path directories and it will take too much time to traverse them all. We therefore make an assumption that application files are only located in sys.path[0]. When traversing files in sys.path, we can expect both .py and .pyc files. For source deployment, we will find both .py and .pyc files. In this case we will only index .py files and ignored .pyc file. In case of binary deployment, only .pyc file will be there. The naive way to hash files would be to read the file content and compute some sort of a hash (e.g. SHA1). This can be expensive as well, so instead we just hash file name and file size. It is a good enough heuristics to identify modified files across different deployments. Args: hash_obj: hash aggregator to update with application uniquifier. """ def ProcessDirectory(path, relative_path, depth=1): """Recursively computes application uniquifier for a particular directory. Args: path: absolute path of the directory to start. relative_path: path relative to sys.path[0] depth: current recursion depth. """ if depth > _MAX_DEPTH: return try: names = os.listdir(path) except BaseException: return # Sort file names to ensure consistent hash regardless of order returned # by os.listdir. This will also put .py files before .pyc and .pyo files. modules = set() for name in sorted(names): current_path = os.path.join(path, name) if not os.path.isdir(current_path): file_name, ext = os.path.splitext(name) if ext not in ('.py', '.pyc', '.pyo'): continue # This is not an application file. if file_name in modules: continue # This is a .pyc file and we already indexed .py file. modules.add(file_name) ProcessApplicationFile(current_path, os.path.join(relative_path, name)) elif IsPackage(current_path): ProcessDirectory(current_path, os.path.join(relative_path, name), depth + 1) def IsPackage(path): """Checks if the specified directory is a valid Python package.""" init_base_path = os.path.join(path, '__init__.py') return (os.path.isfile(init_base_path) or os.path.isfile(init_base_path + 'c') or os.path.isfile(init_base_path + 'o')) def ProcessApplicationFile(path, relative_path): """Updates the hash with the specified application file.""" hash_obj.update(relative_path.encode()) hash_obj.update(':'.encode()) try: hash_obj.update(str(os.stat(path).st_size).encode()) except BaseException: pass hash_obj.update('\n'.encode()) ProcessDirectory(sys.path[0], '')
python
def ComputeApplicationUniquifier(hash_obj): def ProcessDirectory(path, relative_path, depth=1): """Recursively computes application uniquifier for a particular directory. Args: path: absolute path of the directory to start. relative_path: path relative to sys.path[0] depth: current recursion depth. """ if depth > _MAX_DEPTH: return try: names = os.listdir(path) except BaseException: return # Sort file names to ensure consistent hash regardless of order returned # by os.listdir. This will also put .py files before .pyc and .pyo files. modules = set() for name in sorted(names): current_path = os.path.join(path, name) if not os.path.isdir(current_path): file_name, ext = os.path.splitext(name) if ext not in ('.py', '.pyc', '.pyo'): continue # This is not an application file. if file_name in modules: continue # This is a .pyc file and we already indexed .py file. modules.add(file_name) ProcessApplicationFile(current_path, os.path.join(relative_path, name)) elif IsPackage(current_path): ProcessDirectory(current_path, os.path.join(relative_path, name), depth + 1) def IsPackage(path): """Checks if the specified directory is a valid Python package.""" init_base_path = os.path.join(path, '__init__.py') return (os.path.isfile(init_base_path) or os.path.isfile(init_base_path + 'c') or os.path.isfile(init_base_path + 'o')) def ProcessApplicationFile(path, relative_path): """Updates the hash with the specified application file.""" hash_obj.update(relative_path.encode()) hash_obj.update(':'.encode()) try: hash_obj.update(str(os.stat(path).st_size).encode()) except BaseException: pass hash_obj.update('\n'.encode()) ProcessDirectory(sys.path[0], '')
[ "def", "ComputeApplicationUniquifier", "(", "hash_obj", ")", ":", "def", "ProcessDirectory", "(", "path", ",", "relative_path", ",", "depth", "=", "1", ")", ":", "\"\"\"Recursively computes application uniquifier for a particular directory.\n\n Args:\n path: absolute path...
Computes hash of application files. Application files can be anywhere on the disk. The application is free to import a Python module from an arbitrary path ok the disk. It is also impossible to distinguish application files from third party libraries. Third party libraries are typically installed with "pip" and there is not a good way to guarantee that all instances of the application are going to have exactly the same version of each package. There is also a huge amount of files in all sys.path directories and it will take too much time to traverse them all. We therefore make an assumption that application files are only located in sys.path[0]. When traversing files in sys.path, we can expect both .py and .pyc files. For source deployment, we will find both .py and .pyc files. In this case we will only index .py files and ignored .pyc file. In case of binary deployment, only .pyc file will be there. The naive way to hash files would be to read the file content and compute some sort of a hash (e.g. SHA1). This can be expensive as well, so instead we just hash file name and file size. It is a good enough heuristics to identify modified files across different deployments. Args: hash_obj: hash aggregator to update with application uniquifier.
[ "Computes", "hash", "of", "application", "files", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/uniquifier_computer.py#L37-L117
230,980
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/imphook2.py
AddImportCallbackBySuffix
def AddImportCallbackBySuffix(path, callback): """Register import hook. This function overrides the default import process. Then whenever a module whose suffix matches path is imported, the callback will be invoked. A module may be imported multiple times. Import event only means that the Python code contained an "import" statement. The actual loading and initialization of a new module normally happens only once, at which time the callback will be invoked. This function does not validates the existence of such a module and it's the responsibility of the caller. TODO(erezh): handle module reload. Args: path: python module file path. It may be missing the directories for the outer packages, and therefore, requires suffix comparison to match against loaded modules. If it contains all outer packages, it may contain the sys.path as well. It might contain an incorrect file extension (e.g., py vs. pyc). callback: callable to invoke upon module load. Returns: Function object to invoke to remove the installed callback. """ def RemoveCallback(): # This is a read-if-del operation on _import_callbacks. Lock to prevent # callbacks from being inserted just before the key is deleted. Thus, it # must be locked also when inserting a new entry below. On the other hand # read only access, in the import hook, does not require a lock. with _import_callbacks_lock: callbacks = _import_callbacks.get(path) if callbacks: callbacks.remove(callback) if not callbacks: del _import_callbacks[path] with _import_callbacks_lock: _import_callbacks.setdefault(path, set()).add(callback) _InstallImportHookBySuffix() return RemoveCallback
python
def AddImportCallbackBySuffix(path, callback): def RemoveCallback(): # This is a read-if-del operation on _import_callbacks. Lock to prevent # callbacks from being inserted just before the key is deleted. Thus, it # must be locked also when inserting a new entry below. On the other hand # read only access, in the import hook, does not require a lock. with _import_callbacks_lock: callbacks = _import_callbacks.get(path) if callbacks: callbacks.remove(callback) if not callbacks: del _import_callbacks[path] with _import_callbacks_lock: _import_callbacks.setdefault(path, set()).add(callback) _InstallImportHookBySuffix() return RemoveCallback
[ "def", "AddImportCallbackBySuffix", "(", "path", ",", "callback", ")", ":", "def", "RemoveCallback", "(", ")", ":", "# This is a read-if-del operation on _import_callbacks. Lock to prevent", "# callbacks from being inserted just before the key is deleted. Thus, it", "# must be locked a...
Register import hook. This function overrides the default import process. Then whenever a module whose suffix matches path is imported, the callback will be invoked. A module may be imported multiple times. Import event only means that the Python code contained an "import" statement. The actual loading and initialization of a new module normally happens only once, at which time the callback will be invoked. This function does not validates the existence of such a module and it's the responsibility of the caller. TODO(erezh): handle module reload. Args: path: python module file path. It may be missing the directories for the outer packages, and therefore, requires suffix comparison to match against loaded modules. If it contains all outer packages, it may contain the sys.path as well. It might contain an incorrect file extension (e.g., py vs. pyc). callback: callable to invoke upon module load. Returns: Function object to invoke to remove the installed callback.
[ "Register", "import", "hook", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/imphook2.py#L59-L101
230,981
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/imphook2.py
_InstallImportHookBySuffix
def _InstallImportHookBySuffix(): """Lazily installs import hook.""" global _real_import if _real_import: return # Import hook already installed _real_import = getattr(builtins, '__import__') assert _real_import builtins.__import__ = _ImportHookBySuffix if six.PY3: # In Python 2, importlib.import_module calls __import__ internally so # overriding __import__ is enough. In Python 3, they are separate so it also # needs to be overwritten. global _real_import_module _real_import_module = importlib.import_module assert _real_import_module importlib.import_module = _ImportModuleHookBySuffix
python
def _InstallImportHookBySuffix(): global _real_import if _real_import: return # Import hook already installed _real_import = getattr(builtins, '__import__') assert _real_import builtins.__import__ = _ImportHookBySuffix if six.PY3: # In Python 2, importlib.import_module calls __import__ internally so # overriding __import__ is enough. In Python 3, they are separate so it also # needs to be overwritten. global _real_import_module _real_import_module = importlib.import_module assert _real_import_module importlib.import_module = _ImportModuleHookBySuffix
[ "def", "_InstallImportHookBySuffix", "(", ")", ":", "global", "_real_import", "if", "_real_import", ":", "return", "# Import hook already installed", "_real_import", "=", "getattr", "(", "builtins", ",", "'__import__'", ")", "assert", "_real_import", "builtins", ".", ...
Lazily installs import hook.
[ "Lazily", "installs", "import", "hook", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/imphook2.py#L104-L122
230,982
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/imphook2.py
_IncrementNestLevel
def _IncrementNestLevel(): """Increments the per thread nest level of imports.""" # This is the top call to import (no nesting), init the per-thread nest level # and names set. if getattr(_import_local, 'nest_level', None) is None: _import_local.nest_level = 0 if _import_local.nest_level == 0: # Re-initialize names set at each top-level import to prevent any # accidental unforeseen memory leak. _import_local.names = set() _import_local.nest_level += 1
python
def _IncrementNestLevel(): # This is the top call to import (no nesting), init the per-thread nest level # and names set. if getattr(_import_local, 'nest_level', None) is None: _import_local.nest_level = 0 if _import_local.nest_level == 0: # Re-initialize names set at each top-level import to prevent any # accidental unforeseen memory leak. _import_local.names = set() _import_local.nest_level += 1
[ "def", "_IncrementNestLevel", "(", ")", ":", "# This is the top call to import (no nesting), init the per-thread nest level", "# and names set.", "if", "getattr", "(", "_import_local", ",", "'nest_level'", ",", "None", ")", "is", "None", ":", "_import_local", ".", "nest_lev...
Increments the per thread nest level of imports.
[ "Increments", "the", "per", "thread", "nest", "level", "of", "imports", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/imphook2.py#L125-L137
230,983
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/imphook2.py
_ProcessImportBySuffix
def _ProcessImportBySuffix(name, fromlist, globals): """Processes an import. Calculates the possible names generated from an import and invokes registered callbacks if needed. Args: name: Argument as passed to the importer. fromlist: Argument as passed to the importer. globals: Argument as passed to the importer. """ _import_local.nest_level -= 1 # To improve common code path performance, compute the loaded modules only # if there are any import callbacks. if _import_callbacks: # Collect the names of all modules that might be newly loaded as a result # of this import. Add them in a thread-local list. _import_local.names |= _GenerateNames(name, fromlist, globals) # Invoke the callbacks only on the top-level import call. if _import_local.nest_level == 0: _InvokeImportCallbackBySuffix(_import_local.names) # To be safe, we clear the names set every time we exit a top level import. if _import_local.nest_level == 0: _import_local.names.clear()
python
def _ProcessImportBySuffix(name, fromlist, globals): _import_local.nest_level -= 1 # To improve common code path performance, compute the loaded modules only # if there are any import callbacks. if _import_callbacks: # Collect the names of all modules that might be newly loaded as a result # of this import. Add them in a thread-local list. _import_local.names |= _GenerateNames(name, fromlist, globals) # Invoke the callbacks only on the top-level import call. if _import_local.nest_level == 0: _InvokeImportCallbackBySuffix(_import_local.names) # To be safe, we clear the names set every time we exit a top level import. if _import_local.nest_level == 0: _import_local.names.clear()
[ "def", "_ProcessImportBySuffix", "(", "name", ",", "fromlist", ",", "globals", ")", ":", "_import_local", ".", "nest_level", "-=", "1", "# To improve common code path performance, compute the loaded modules only", "# if there are any import callbacks.", "if", "_import_callbacks",...
Processes an import. Calculates the possible names generated from an import and invokes registered callbacks if needed. Args: name: Argument as passed to the importer. fromlist: Argument as passed to the importer. globals: Argument as passed to the importer.
[ "Processes", "an", "import", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/imphook2.py#L141-L167
230,984
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/imphook2.py
_ImportHookBySuffix
def _ImportHookBySuffix( name, globals=None, locals=None, fromlist=None, level=None): """Callback when an import statement is executed by the Python interpreter. Argument names have to exactly match those of __import__. Otherwise calls to __import__ that use keyword syntax will fail: __import('a', fromlist=[]). """ _IncrementNestLevel() if level is None: # A level of 0 means absolute import, positive values means relative # imports, and -1 means to try both an absolute and relative import. # Since imports were disambiguated in Python 3, -1 is not a valid value. # The default values are 0 and -1 for Python 3 and 3 respectively. # https://docs.python.org/2/library/functions.html#__import__ # https://docs.python.org/3/library/functions.html#__import__ level = 0 if six.PY3 else -1 try: # Really import modules. module = _real_import(name, globals, locals, fromlist, level) finally: # This _real_import call may raise an exception (e.g., ImportError). # However, there might be several modules already loaded before the # exception was raised. For instance: # a.py # import b # success # import c # ImportError exception. # In this case, an 'import a' statement would have the side effect of # importing module 'b'. This should trigger the import hooks for module # 'b'. To achieve this, we always search/invoke import callbacks (i.e., # even when an exception is raised). # # Important Note: Do not use 'return' inside the finally block. It will # cause any pending exception to be discarded. _ProcessImportBySuffix(name, fromlist, globals) return module
python
def _ImportHookBySuffix( name, globals=None, locals=None, fromlist=None, level=None): _IncrementNestLevel() if level is None: # A level of 0 means absolute import, positive values means relative # imports, and -1 means to try both an absolute and relative import. # Since imports were disambiguated in Python 3, -1 is not a valid value. # The default values are 0 and -1 for Python 3 and 3 respectively. # https://docs.python.org/2/library/functions.html#__import__ # https://docs.python.org/3/library/functions.html#__import__ level = 0 if six.PY3 else -1 try: # Really import modules. module = _real_import(name, globals, locals, fromlist, level) finally: # This _real_import call may raise an exception (e.g., ImportError). # However, there might be several modules already loaded before the # exception was raised. For instance: # a.py # import b # success # import c # ImportError exception. # In this case, an 'import a' statement would have the side effect of # importing module 'b'. This should trigger the import hooks for module # 'b'. To achieve this, we always search/invoke import callbacks (i.e., # even when an exception is raised). # # Important Note: Do not use 'return' inside the finally block. It will # cause any pending exception to be discarded. _ProcessImportBySuffix(name, fromlist, globals) return module
[ "def", "_ImportHookBySuffix", "(", "name", ",", "globals", "=", "None", ",", "locals", "=", "None", ",", "fromlist", "=", "None", ",", "level", "=", "None", ")", ":", "_IncrementNestLevel", "(", ")", "if", "level", "is", "None", ":", "# A level of 0 means ...
Callback when an import statement is executed by the Python interpreter. Argument names have to exactly match those of __import__. Otherwise calls to __import__ that use keyword syntax will fail: __import('a', fromlist=[]).
[ "Callback", "when", "an", "import", "statement", "is", "executed", "by", "the", "Python", "interpreter", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/imphook2.py#L171-L208
230,985
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/imphook2.py
_ResolveRelativeImport
def _ResolveRelativeImport(name, package): """Resolves a relative import into an absolute path. This is mostly an adapted version of the logic found in the backported version of import_module in Python 2.7. https://github.com/python/cpython/blob/2.7/Lib/importlib/__init__.py Args: name: relative name imported, such as '.a' or '..b.c' package: absolute package path, such as 'a.b.c.d.e' Returns: The absolute path of the name to be imported, or None if it is invalid. Examples: _ResolveRelativeImport('.c', 'a.b') -> 'a.b.c' _ResolveRelativeImport('..c', 'a.b') -> 'a.c' _ResolveRelativeImport('...c', 'a.c') -> None """ level = sum(1 for c in itertools.takewhile(lambda c: c == '.', name)) if level == 1: return package + name else: parts = package.split('.')[:-(level - 1)] if not parts: return None parts.append(name[level:]) return '.'.join(parts)
python
def _ResolveRelativeImport(name, package): level = sum(1 for c in itertools.takewhile(lambda c: c == '.', name)) if level == 1: return package + name else: parts = package.split('.')[:-(level - 1)] if not parts: return None parts.append(name[level:]) return '.'.join(parts)
[ "def", "_ResolveRelativeImport", "(", "name", ",", "package", ")", ":", "level", "=", "sum", "(", "1", "for", "c", "in", "itertools", ".", "takewhile", "(", "lambda", "c", ":", "c", "==", "'.'", ",", "name", ")", ")", "if", "level", "==", "1", ":",...
Resolves a relative import into an absolute path. This is mostly an adapted version of the logic found in the backported version of import_module in Python 2.7. https://github.com/python/cpython/blob/2.7/Lib/importlib/__init__.py Args: name: relative name imported, such as '.a' or '..b.c' package: absolute package path, such as 'a.b.c.d.e' Returns: The absolute path of the name to be imported, or None if it is invalid. Examples: _ResolveRelativeImport('.c', 'a.b') -> 'a.b.c' _ResolveRelativeImport('..c', 'a.b') -> 'a.c' _ResolveRelativeImport('...c', 'a.c') -> None
[ "Resolves", "a", "relative", "import", "into", "an", "absolute", "path", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/imphook2.py#L211-L237
230,986
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/imphook2.py
_ImportModuleHookBySuffix
def _ImportModuleHookBySuffix(name, package=None): """Callback when a module is imported through importlib.import_module.""" _IncrementNestLevel() try: # Really import modules. module = _real_import_module(name, package) finally: if name.startswith('.'): if package: name = _ResolveRelativeImport(name, package) else: # Should not happen. Relative imports require the package argument. name = None if name: _ProcessImportBySuffix(name, None, None) return module
python
def _ImportModuleHookBySuffix(name, package=None): _IncrementNestLevel() try: # Really import modules. module = _real_import_module(name, package) finally: if name.startswith('.'): if package: name = _ResolveRelativeImport(name, package) else: # Should not happen. Relative imports require the package argument. name = None if name: _ProcessImportBySuffix(name, None, None) return module
[ "def", "_ImportModuleHookBySuffix", "(", "name", ",", "package", "=", "None", ")", ":", "_IncrementNestLevel", "(", ")", "try", ":", "# Really import modules.", "module", "=", "_real_import_module", "(", "name", ",", "package", ")", "finally", ":", "if", "name",...
Callback when a module is imported through importlib.import_module.
[ "Callback", "when", "a", "module", "is", "imported", "through", "importlib", ".", "import_module", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/imphook2.py#L240-L257
230,987
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/imphook2.py
_GenerateNames
def _GenerateNames(name, fromlist, globals): """Generates the names of modules that might be loaded via this import. Args: name: Argument as passed to the importer. fromlist: Argument as passed to the importer. globals: Argument as passed to the importer. Returns: A set that contains the names of all modules that are loaded by the currently executing import statement, as they would show up in sys.modules. The returned set may contain module names that were already loaded before the execution of this import statement. The returned set may contain names that are not real modules. """ def GetCurrentPackage(globals): """Finds the name of the package for the currently executing module.""" if not globals: return None # Get the name of the module/package that the current import is being # executed in. current = globals.get('__name__') if not current: return None # Check if the current module is really a module, or a package. current_file = globals.get('__file__') if not current_file: return None root = os.path.splitext(os.path.basename(current_file))[0] if root == '__init__': # The current import happened from a package. Return the package. return current else: # The current import happened from a module. Return the package that # contains the module. return current.rpartition('.')[0] # A Python module can be addressed in two ways: # 1. Using a path relative to the currently executing module's path. For # instance, module p1/p2/m3.py imports p1/p2/p3/m4.py using 'import p3.m4'. # 2. Using a path relative to sys.path. For instance, module p1/p2/m3.py # imports p1/p2/p3/m4.py using 'import p1.p2.p3.m4'. # # The Python importer uses the 'globals' argument to identify the module that # the current import is being performed in. The actual logic is very # complicated, and we only approximate it here to limit the performance # overhead (See import.c in the interpreter for details). Here, we only use # the value of the globals['__name__'] for this purpose. # # Note: The Python importer prioritizes the current package over sys.path. For # instance, if 'p1.p2.m3' imports 'm4', then 'p1.p2.m4' is a better match than # the top level 'm4'. However, the debugger does not have to implement this, # because breakpoint paths are not described relative to some other file. They # are always assumed to be relative to the sys.path directories. If the user # sets breakpoint inside 'm4.py', then we can map it to either the top level # 'm4' or 'p1.p2.m4', i.e., both are valid matches. curpkg = GetCurrentPackage(globals) names = set() # A Python module can be imported using two syntaxes: # 1. import p1.p2.m3 # 2. from p1.p2 import m3 # # When the regular 'import p1.p2.m3' syntax is used, the name of the module # being imported is passed in the 'name' argument (e.g., name='p1.p2.m3', # fromlist=None). # # When the from-import syntax is used, then fromlist contains the leaf names # of the modules, and name contains the containing package. For instance, if # name='a.b', fromlist=['c', 'd'], then we add ['a.b.c', 'a.b.d']. # # Corner cases: # 1. The fromlist syntax can be used to import a function from a module. # For instance, 'from p1.p2.m3 import func'. # 2. Sometimes, the importer is passed a dummy fromlist=['__doc__'] (see # import.c in the interpreter for details). # Due to these corner cases, the returned set may contain entries that are not # names of real modules. for from_entry in fromlist or []: # Name relative to sys.path. # For relative imports such as 'from . import x', name will be the empty # string. Thus we should not prepend a '.' to the entry. entry = (name + '.' + from_entry) if name else from_entry names.add(entry) # Name relative to the currently executing module's package. if curpkg: names.add(curpkg + '.' + entry) # Generate all names from name. For instance, if name='a.b.c', then # we need to add ['a.b.c', 'a.b', 'a']. while name: # Name relative to sys.path. names.add(name) # Name relative to currently executing module's package. if curpkg: names.add(curpkg + '.' + name) name = name.rpartition('.')[0] return names
python
def _GenerateNames(name, fromlist, globals): def GetCurrentPackage(globals): """Finds the name of the package for the currently executing module.""" if not globals: return None # Get the name of the module/package that the current import is being # executed in. current = globals.get('__name__') if not current: return None # Check if the current module is really a module, or a package. current_file = globals.get('__file__') if not current_file: return None root = os.path.splitext(os.path.basename(current_file))[0] if root == '__init__': # The current import happened from a package. Return the package. return current else: # The current import happened from a module. Return the package that # contains the module. return current.rpartition('.')[0] # A Python module can be addressed in two ways: # 1. Using a path relative to the currently executing module's path. For # instance, module p1/p2/m3.py imports p1/p2/p3/m4.py using 'import p3.m4'. # 2. Using a path relative to sys.path. For instance, module p1/p2/m3.py # imports p1/p2/p3/m4.py using 'import p1.p2.p3.m4'. # # The Python importer uses the 'globals' argument to identify the module that # the current import is being performed in. The actual logic is very # complicated, and we only approximate it here to limit the performance # overhead (See import.c in the interpreter for details). Here, we only use # the value of the globals['__name__'] for this purpose. # # Note: The Python importer prioritizes the current package over sys.path. For # instance, if 'p1.p2.m3' imports 'm4', then 'p1.p2.m4' is a better match than # the top level 'm4'. However, the debugger does not have to implement this, # because breakpoint paths are not described relative to some other file. They # are always assumed to be relative to the sys.path directories. If the user # sets breakpoint inside 'm4.py', then we can map it to either the top level # 'm4' or 'p1.p2.m4', i.e., both are valid matches. curpkg = GetCurrentPackage(globals) names = set() # A Python module can be imported using two syntaxes: # 1. import p1.p2.m3 # 2. from p1.p2 import m3 # # When the regular 'import p1.p2.m3' syntax is used, the name of the module # being imported is passed in the 'name' argument (e.g., name='p1.p2.m3', # fromlist=None). # # When the from-import syntax is used, then fromlist contains the leaf names # of the modules, and name contains the containing package. For instance, if # name='a.b', fromlist=['c', 'd'], then we add ['a.b.c', 'a.b.d']. # # Corner cases: # 1. The fromlist syntax can be used to import a function from a module. # For instance, 'from p1.p2.m3 import func'. # 2. Sometimes, the importer is passed a dummy fromlist=['__doc__'] (see # import.c in the interpreter for details). # Due to these corner cases, the returned set may contain entries that are not # names of real modules. for from_entry in fromlist or []: # Name relative to sys.path. # For relative imports such as 'from . import x', name will be the empty # string. Thus we should not prepend a '.' to the entry. entry = (name + '.' + from_entry) if name else from_entry names.add(entry) # Name relative to the currently executing module's package. if curpkg: names.add(curpkg + '.' + entry) # Generate all names from name. For instance, if name='a.b.c', then # we need to add ['a.b.c', 'a.b', 'a']. while name: # Name relative to sys.path. names.add(name) # Name relative to currently executing module's package. if curpkg: names.add(curpkg + '.' + name) name = name.rpartition('.')[0] return names
[ "def", "_GenerateNames", "(", "name", ",", "fromlist", ",", "globals", ")", ":", "def", "GetCurrentPackage", "(", "globals", ")", ":", "\"\"\"Finds the name of the package for the currently executing module.\"\"\"", "if", "not", "globals", ":", "return", "None", "# Get ...
Generates the names of modules that might be loaded via this import. Args: name: Argument as passed to the importer. fromlist: Argument as passed to the importer. globals: Argument as passed to the importer. Returns: A set that contains the names of all modules that are loaded by the currently executing import statement, as they would show up in sys.modules. The returned set may contain module names that were already loaded before the execution of this import statement. The returned set may contain names that are not real modules.
[ "Generates", "the", "names", "of", "modules", "that", "might", "be", "loaded", "via", "this", "import", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/imphook2.py#L260-L362
230,988
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/imphook2.py
_InvokeImportCallbackBySuffix
def _InvokeImportCallbackBySuffix(names): """Invokes import callbacks for newly loaded modules. Uses a path suffix match to identify whether a loaded module matches the file path provided by the user. Args: names: A set of names for modules that are loaded by the current import. The set may contain some superfluous entries that were already loaded before this import, or some entries that do not correspond to a module. The list is expected to be much smaller than the exact sys.modules so that a linear search is not as costly. """ def GetModuleFromName(name, path): """Returns the loaded module for this name/path, or None if not found. Args: name: A string that may represent the name of a loaded Python module. path: If 'name' ends with '.*', then the last path component in 'path' is used to identify what the wildcard may map to. Does not contain file extension. Returns: The loaded module for the given name and path, or None if a loaded module was not found. """ # The from-import syntax can be used as 'from p1.p2 import *'. In this case, # we cannot know what modules will match the wildcard. However, we know that # the wildcard can only be used to import leaf modules. So, we guess that # the leaf module will have the same name as the leaf file name the user # provided. For instance, # User input path = 'foo.py' # Currently executing import: # from pkg1.pkg2 import * # Then, we combine: # 1. 'pkg1.pkg2' from import's outer package and # 2. Add 'foo' as our guess for the leaf module name. # So, we will search for modules with name similar to 'pkg1.pkg2.foo'. if name.endswith('.*'): # Replace the final '*' with the name of the module we are looking for. name = name.rpartition('.')[0] + '.' + path.split('/')[-1] # Check if the module was loaded. return sys.modules.get(name) # _import_callbacks might change during iteration because RemoveCallback() # might delete items. Iterate over a copy to avoid a # 'dictionary changed size during iteration' error. for path, callbacks in list(_import_callbacks.items()): root = os.path.splitext(path)[0] nonempty_names = (n for n in names if n) modules = (GetModuleFromName(name, root) for name in nonempty_names) nonempty_modules = (m for m in modules if m) for module in nonempty_modules: # TODO(emrekultursay): Write unit test to cover None case. mod_file = getattr(module, '__file__', None) if not mod_file: continue mod_root = os.path.splitext(mod_file)[0] # If the module is relative, add the curdir prefix to convert it to # absolute path. Note that we don't use os.path.abspath because it # also normalizes the path (which has side effects we don't want). if not os.path.isabs(mod_root): mod_root = os.path.join(os.curdir, mod_root) if module_utils2.IsPathSuffix(mod_root, root): for callback in callbacks.copy(): callback(module) break
python
def _InvokeImportCallbackBySuffix(names): def GetModuleFromName(name, path): """Returns the loaded module for this name/path, or None if not found. Args: name: A string that may represent the name of a loaded Python module. path: If 'name' ends with '.*', then the last path component in 'path' is used to identify what the wildcard may map to. Does not contain file extension. Returns: The loaded module for the given name and path, or None if a loaded module was not found. """ # The from-import syntax can be used as 'from p1.p2 import *'. In this case, # we cannot know what modules will match the wildcard. However, we know that # the wildcard can only be used to import leaf modules. So, we guess that # the leaf module will have the same name as the leaf file name the user # provided. For instance, # User input path = 'foo.py' # Currently executing import: # from pkg1.pkg2 import * # Then, we combine: # 1. 'pkg1.pkg2' from import's outer package and # 2. Add 'foo' as our guess for the leaf module name. # So, we will search for modules with name similar to 'pkg1.pkg2.foo'. if name.endswith('.*'): # Replace the final '*' with the name of the module we are looking for. name = name.rpartition('.')[0] + '.' + path.split('/')[-1] # Check if the module was loaded. return sys.modules.get(name) # _import_callbacks might change during iteration because RemoveCallback() # might delete items. Iterate over a copy to avoid a # 'dictionary changed size during iteration' error. for path, callbacks in list(_import_callbacks.items()): root = os.path.splitext(path)[0] nonempty_names = (n for n in names if n) modules = (GetModuleFromName(name, root) for name in nonempty_names) nonempty_modules = (m for m in modules if m) for module in nonempty_modules: # TODO(emrekultursay): Write unit test to cover None case. mod_file = getattr(module, '__file__', None) if not mod_file: continue mod_root = os.path.splitext(mod_file)[0] # If the module is relative, add the curdir prefix to convert it to # absolute path. Note that we don't use os.path.abspath because it # also normalizes the path (which has side effects we don't want). if not os.path.isabs(mod_root): mod_root = os.path.join(os.curdir, mod_root) if module_utils2.IsPathSuffix(mod_root, root): for callback in callbacks.copy(): callback(module) break
[ "def", "_InvokeImportCallbackBySuffix", "(", "names", ")", ":", "def", "GetModuleFromName", "(", "name", ",", "path", ")", ":", "\"\"\"Returns the loaded module for this name/path, or None if not found.\n\n Args:\n name: A string that may represent the name of a loaded Python mod...
Invokes import callbacks for newly loaded modules. Uses a path suffix match to identify whether a loaded module matches the file path provided by the user. Args: names: A set of names for modules that are loaded by the current import. The set may contain some superfluous entries that were already loaded before this import, or some entries that do not correspond to a module. The list is expected to be much smaller than the exact sys.modules so that a linear search is not as costly.
[ "Invokes", "import", "callbacks", "for", "newly", "loaded", "modules", "." ]
89ce3782c98b814838a3ecb5479ed3882368cbee
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/imphook2.py#L365-L437
230,989
nateshmbhat/pyttsx3
pyttsx3/__init__.py
init
def init(driverName=None, debug=False): ''' Constructs a new TTS engine instance or reuses the existing instance for the driver name. @param driverName: Name of the platform specific driver to use. If None, selects the default driver for the operating system. @type: str @param debug: Debugging output enabled or not @type debug: bool @return: Engine instance @rtype: L{engine.Engine} ''' try: eng = _activeEngines[driverName] except KeyError: eng = Engine(driverName, debug) _activeEngines[driverName] = eng return eng
python
def init(driverName=None, debug=False): ''' Constructs a new TTS engine instance or reuses the existing instance for the driver name. @param driverName: Name of the platform specific driver to use. If None, selects the default driver for the operating system. @type: str @param debug: Debugging output enabled or not @type debug: bool @return: Engine instance @rtype: L{engine.Engine} ''' try: eng = _activeEngines[driverName] except KeyError: eng = Engine(driverName, debug) _activeEngines[driverName] = eng return eng
[ "def", "init", "(", "driverName", "=", "None", ",", "debug", "=", "False", ")", ":", "try", ":", "eng", "=", "_activeEngines", "[", "driverName", "]", "except", "KeyError", ":", "eng", "=", "Engine", "(", "driverName", ",", "debug", ")", "_activeEngines"...
Constructs a new TTS engine instance or reuses the existing instance for the driver name. @param driverName: Name of the platform specific driver to use. If None, selects the default driver for the operating system. @type: str @param debug: Debugging output enabled or not @type debug: bool @return: Engine instance @rtype: L{engine.Engine}
[ "Constructs", "a", "new", "TTS", "engine", "instance", "or", "reuses", "the", "existing", "instance", "for", "the", "driver", "name", "." ]
0f304bff4812d50937393f1e3d7f89c9862a1623
https://github.com/nateshmbhat/pyttsx3/blob/0f304bff4812d50937393f1e3d7f89c9862a1623/pyttsx3/__init__.py#L6-L24
230,990
nateshmbhat/pyttsx3
pyttsx3/drivers/dummy.py
DummyDriver.startLoop
def startLoop(self): ''' Starts a blocking run loop in which driver callbacks are properly invoked. @precondition: There was no previous successful call to L{startLoop} without an intervening call to L{stopLoop}. ''' first = True self._looping = True while self._looping: if first: self._proxy.setBusy(False) first = False time.sleep(0.5)
python
def startLoop(self): ''' Starts a blocking run loop in which driver callbacks are properly invoked. @precondition: There was no previous successful call to L{startLoop} without an intervening call to L{stopLoop}. ''' first = True self._looping = True while self._looping: if first: self._proxy.setBusy(False) first = False time.sleep(0.5)
[ "def", "startLoop", "(", "self", ")", ":", "first", "=", "True", "self", ".", "_looping", "=", "True", "while", "self", ".", "_looping", ":", "if", "first", ":", "self", ".", "_proxy", ".", "setBusy", "(", "False", ")", "first", "=", "False", "time",...
Starts a blocking run loop in which driver callbacks are properly invoked. @precondition: There was no previous successful call to L{startLoop} without an intervening call to L{stopLoop}.
[ "Starts", "a", "blocking", "run", "loop", "in", "which", "driver", "callbacks", "are", "properly", "invoked", "." ]
0f304bff4812d50937393f1e3d7f89c9862a1623
https://github.com/nateshmbhat/pyttsx3/blob/0f304bff4812d50937393f1e3d7f89c9862a1623/pyttsx3/drivers/dummy.py#L58-L72
230,991
nateshmbhat/pyttsx3
pyttsx3/engine.py
Engine._notify
def _notify(self, topic, **kwargs): """ Invokes callbacks for an event topic. @param topic: String event name @type topic: str @param kwargs: Values associated with the event @type kwargs: dict """ for cb in self._connects.get(topic, []): try: cb(**kwargs) except Exception: if self._debug: traceback.print_exc()
python
def _notify(self, topic, **kwargs): for cb in self._connects.get(topic, []): try: cb(**kwargs) except Exception: if self._debug: traceback.print_exc()
[ "def", "_notify", "(", "self", ",", "topic", ",", "*", "*", "kwargs", ")", ":", "for", "cb", "in", "self", ".", "_connects", ".", "get", "(", "topic", ",", "[", "]", ")", ":", "try", ":", "cb", "(", "*", "*", "kwargs", ")", "except", "Exception...
Invokes callbacks for an event topic. @param topic: String event name @type topic: str @param kwargs: Values associated with the event @type kwargs: dict
[ "Invokes", "callbacks", "for", "an", "event", "topic", "." ]
0f304bff4812d50937393f1e3d7f89c9862a1623
https://github.com/nateshmbhat/pyttsx3/blob/0f304bff4812d50937393f1e3d7f89c9862a1623/pyttsx3/engine.py#L37-L51
230,992
nateshmbhat/pyttsx3
pyttsx3/engine.py
Engine.disconnect
def disconnect(self, token): """ Unregisters a callback for an event topic. @param token: Token of the callback to unregister @type token: dict """ topic = token['topic'] try: arr = self._connects[topic] except KeyError: return arr.remove(token['cb']) if len(arr) == 0: del self._connects[topic]
python
def disconnect(self, token): topic = token['topic'] try: arr = self._connects[topic] except KeyError: return arr.remove(token['cb']) if len(arr) == 0: del self._connects[topic]
[ "def", "disconnect", "(", "self", ",", "token", ")", ":", "topic", "=", "token", "[", "'topic'", "]", "try", ":", "arr", "=", "self", ".", "_connects", "[", "topic", "]", "except", "KeyError", ":", "return", "arr", ".", "remove", "(", "token", "[", ...
Unregisters a callback for an event topic. @param token: Token of the callback to unregister @type token: dict
[ "Unregisters", "a", "callback", "for", "an", "event", "topic", "." ]
0f304bff4812d50937393f1e3d7f89c9862a1623
https://github.com/nateshmbhat/pyttsx3/blob/0f304bff4812d50937393f1e3d7f89c9862a1623/pyttsx3/engine.py#L74-L88
230,993
nateshmbhat/pyttsx3
pyttsx3/engine.py
Engine.save_to_file
def save_to_file(self, text, filename, name=None): ''' Adds an utterance to speak to the event queue. @param text: Text to sepak @type text: unicode @param filename: the name of file to save. @param name: Name to associate with this utterance. Included in notifications about this utterance. @type name: str ''' self.proxy.save_to_file(text, filename, name)
python
def save_to_file(self, text, filename, name=None): ''' Adds an utterance to speak to the event queue. @param text: Text to sepak @type text: unicode @param filename: the name of file to save. @param name: Name to associate with this utterance. Included in notifications about this utterance. @type name: str ''' self.proxy.save_to_file(text, filename, name)
[ "def", "save_to_file", "(", "self", ",", "text", ",", "filename", ",", "name", "=", "None", ")", ":", "self", ".", "proxy", ".", "save_to_file", "(", "text", ",", "filename", ",", "name", ")" ]
Adds an utterance to speak to the event queue. @param text: Text to sepak @type text: unicode @param filename: the name of file to save. @param name: Name to associate with this utterance. Included in notifications about this utterance. @type name: str
[ "Adds", "an", "utterance", "to", "speak", "to", "the", "event", "queue", "." ]
0f304bff4812d50937393f1e3d7f89c9862a1623
https://github.com/nateshmbhat/pyttsx3/blob/0f304bff4812d50937393f1e3d7f89c9862a1623/pyttsx3/engine.py#L108-L119
230,994
nateshmbhat/pyttsx3
pyttsx3/engine.py
Engine.runAndWait
def runAndWait(self): """ Runs an event loop until all commands queued up until this method call complete. Blocks during the event loop and returns when the queue is cleared. @raise RuntimeError: When the loop is already running """ if self._inLoop: raise RuntimeError('run loop already started') self._inLoop = True self._driverLoop = True self.proxy.runAndWait()
python
def runAndWait(self): if self._inLoop: raise RuntimeError('run loop already started') self._inLoop = True self._driverLoop = True self.proxy.runAndWait()
[ "def", "runAndWait", "(", "self", ")", ":", "if", "self", ".", "_inLoop", ":", "raise", "RuntimeError", "(", "'run loop already started'", ")", "self", ".", "_inLoop", "=", "True", "self", ".", "_driverLoop", "=", "True", "self", ".", "proxy", ".", "runAnd...
Runs an event loop until all commands queued up until this method call complete. Blocks during the event loop and returns when the queue is cleared. @raise RuntimeError: When the loop is already running
[ "Runs", "an", "event", "loop", "until", "all", "commands", "queued", "up", "until", "this", "method", "call", "complete", ".", "Blocks", "during", "the", "event", "loop", "and", "returns", "when", "the", "queue", "is", "cleared", "." ]
0f304bff4812d50937393f1e3d7f89c9862a1623
https://github.com/nateshmbhat/pyttsx3/blob/0f304bff4812d50937393f1e3d7f89c9862a1623/pyttsx3/engine.py#L168-L180
230,995
nateshmbhat/pyttsx3
pyttsx3/engine.py
Engine.startLoop
def startLoop(self, useDriverLoop=True): """ Starts an event loop to process queued commands and callbacks. @param useDriverLoop: If True, uses the run loop provided by the driver (the default). If False, assumes the caller will enter its own run loop which will pump any events for the TTS engine properly. @type useDriverLoop: bool @raise RuntimeError: When the loop is already running """ if self._inLoop: raise RuntimeError('run loop already started') self._inLoop = True self._driverLoop = useDriverLoop self.proxy.startLoop(self._driverLoop)
python
def startLoop(self, useDriverLoop=True): if self._inLoop: raise RuntimeError('run loop already started') self._inLoop = True self._driverLoop = useDriverLoop self.proxy.startLoop(self._driverLoop)
[ "def", "startLoop", "(", "self", ",", "useDriverLoop", "=", "True", ")", ":", "if", "self", ".", "_inLoop", ":", "raise", "RuntimeError", "(", "'run loop already started'", ")", "self", ".", "_inLoop", "=", "True", "self", ".", "_driverLoop", "=", "useDriver...
Starts an event loop to process queued commands and callbacks. @param useDriverLoop: If True, uses the run loop provided by the driver (the default). If False, assumes the caller will enter its own run loop which will pump any events for the TTS engine properly. @type useDriverLoop: bool @raise RuntimeError: When the loop is already running
[ "Starts", "an", "event", "loop", "to", "process", "queued", "commands", "and", "callbacks", "." ]
0f304bff4812d50937393f1e3d7f89c9862a1623
https://github.com/nateshmbhat/pyttsx3/blob/0f304bff4812d50937393f1e3d7f89c9862a1623/pyttsx3/engine.py#L182-L196
230,996
nateshmbhat/pyttsx3
pyttsx3/engine.py
Engine.endLoop
def endLoop(self): """ Stops a running event loop. @raise RuntimeError: When the loop is not running """ if not self._inLoop: raise RuntimeError('run loop not started') self.proxy.endLoop(self._driverLoop) self._inLoop = False
python
def endLoop(self): if not self._inLoop: raise RuntimeError('run loop not started') self.proxy.endLoop(self._driverLoop) self._inLoop = False
[ "def", "endLoop", "(", "self", ")", ":", "if", "not", "self", ".", "_inLoop", ":", "raise", "RuntimeError", "(", "'run loop not started'", ")", "self", ".", "proxy", ".", "endLoop", "(", "self", ".", "_driverLoop", ")", "self", ".", "_inLoop", "=", "Fals...
Stops a running event loop. @raise RuntimeError: When the loop is not running
[ "Stops", "a", "running", "event", "loop", "." ]
0f304bff4812d50937393f1e3d7f89c9862a1623
https://github.com/nateshmbhat/pyttsx3/blob/0f304bff4812d50937393f1e3d7f89c9862a1623/pyttsx3/engine.py#L198-L207
230,997
nateshmbhat/pyttsx3
pyttsx3/engine.py
Engine.iterate
def iterate(self): """ Must be called regularly when using an external event loop. """ if not self._inLoop: raise RuntimeError('run loop not started') elif self._driverLoop: raise RuntimeError('iterate not valid in driver run loop') self.proxy.iterate()
python
def iterate(self): if not self._inLoop: raise RuntimeError('run loop not started') elif self._driverLoop: raise RuntimeError('iterate not valid in driver run loop') self.proxy.iterate()
[ "def", "iterate", "(", "self", ")", ":", "if", "not", "self", ".", "_inLoop", ":", "raise", "RuntimeError", "(", "'run loop not started'", ")", "elif", "self", ".", "_driverLoop", ":", "raise", "RuntimeError", "(", "'iterate not valid in driver run loop'", ")", ...
Must be called regularly when using an external event loop.
[ "Must", "be", "called", "regularly", "when", "using", "an", "external", "event", "loop", "." ]
0f304bff4812d50937393f1e3d7f89c9862a1623
https://github.com/nateshmbhat/pyttsx3/blob/0f304bff4812d50937393f1e3d7f89c9862a1623/pyttsx3/engine.py#L209-L217
230,998
nateshmbhat/pyttsx3
pyttsx3/driver.py
DriverProxy._push
def _push(self, mtd, args, name=None): ''' Adds a command to the queue. @param mtd: Method to invoke to process the command @type mtd: method @param args: Arguments to apply when invoking the method @type args: tuple @param name: Name associated with the command @type name: str ''' self._queue.append((mtd, args, name)) self._pump()
python
def _push(self, mtd, args, name=None): ''' Adds a command to the queue. @param mtd: Method to invoke to process the command @type mtd: method @param args: Arguments to apply when invoking the method @type args: tuple @param name: Name associated with the command @type name: str ''' self._queue.append((mtd, args, name)) self._pump()
[ "def", "_push", "(", "self", ",", "mtd", ",", "args", ",", "name", "=", "None", ")", ":", "self", ".", "_queue", ".", "append", "(", "(", "mtd", ",", "args", ",", "name", ")", ")", "self", ".", "_pump", "(", ")" ]
Adds a command to the queue. @param mtd: Method to invoke to process the command @type mtd: method @param args: Arguments to apply when invoking the method @type args: tuple @param name: Name associated with the command @type name: str
[ "Adds", "a", "command", "to", "the", "queue", "." ]
0f304bff4812d50937393f1e3d7f89c9862a1623
https://github.com/nateshmbhat/pyttsx3/blob/0f304bff4812d50937393f1e3d7f89c9862a1623/pyttsx3/driver.py#L92-L104
230,999
nateshmbhat/pyttsx3
pyttsx3/driver.py
DriverProxy._pump
def _pump(self): ''' Attempts to process the next command in the queue if one exists and the driver is not currently busy. ''' while (not self._busy) and len(self._queue): cmd = self._queue.pop(0) self._name = cmd[2] try: cmd[0](*cmd[1]) except Exception as e: self.notify('error', exception=e) if self._debug: traceback.print_exc()
python
def _pump(self): ''' Attempts to process the next command in the queue if one exists and the driver is not currently busy. ''' while (not self._busy) and len(self._queue): cmd = self._queue.pop(0) self._name = cmd[2] try: cmd[0](*cmd[1]) except Exception as e: self.notify('error', exception=e) if self._debug: traceback.print_exc()
[ "def", "_pump", "(", "self", ")", ":", "while", "(", "not", "self", ".", "_busy", ")", "and", "len", "(", "self", ".", "_queue", ")", ":", "cmd", "=", "self", ".", "_queue", ".", "pop", "(", "0", ")", "self", ".", "_name", "=", "cmd", "[", "2...
Attempts to process the next command in the queue if one exists and the driver is not currently busy.
[ "Attempts", "to", "process", "the", "next", "command", "in", "the", "queue", "if", "one", "exists", "and", "the", "driver", "is", "not", "currently", "busy", "." ]
0f304bff4812d50937393f1e3d7f89c9862a1623
https://github.com/nateshmbhat/pyttsx3/blob/0f304bff4812d50937393f1e3d7f89c9862a1623/pyttsx3/driver.py#L106-L119