repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
spotify/luigi
luigi/contrib/hdfs/snakebite_client.py
SnakebiteHdfsClient.get_bite
def get_bite(self): """ If Luigi has forked, we have a different PID, and need to reconnect. """ config = hdfs_config.hdfs() if self.pid != os.getpid() or not self._bite: client_kwargs = dict(filter( lambda k_v: k_v[1] is not None and k_v[1] != '', six.iteritems({ 'hadoop_version': config.client_version, 'effective_user': config.effective_user, }) )) if config.snakebite_autoconfig: """ This is fully backwards compatible with the vanilla Client and can be used for a non HA cluster as well. This client tries to read ``${HADOOP_PATH}/conf/hdfs-site.xml`` to get the address of the namenode. The behaviour is the same as Client. """ from snakebite.client import AutoConfigClient self._bite = AutoConfigClient(**client_kwargs) else: from snakebite.client import Client self._bite = Client(config.namenode_host, config.namenode_port, **client_kwargs) return self._bite
python
def get_bite(self): """ If Luigi has forked, we have a different PID, and need to reconnect. """ config = hdfs_config.hdfs() if self.pid != os.getpid() or not self._bite: client_kwargs = dict(filter( lambda k_v: k_v[1] is not None and k_v[1] != '', six.iteritems({ 'hadoop_version': config.client_version, 'effective_user': config.effective_user, }) )) if config.snakebite_autoconfig: """ This is fully backwards compatible with the vanilla Client and can be used for a non HA cluster as well. This client tries to read ``${HADOOP_PATH}/conf/hdfs-site.xml`` to get the address of the namenode. The behaviour is the same as Client. """ from snakebite.client import AutoConfigClient self._bite = AutoConfigClient(**client_kwargs) else: from snakebite.client import Client self._bite = Client(config.namenode_host, config.namenode_port, **client_kwargs) return self._bite
[ "def", "get_bite", "(", "self", ")", ":", "config", "=", "hdfs_config", ".", "hdfs", "(", ")", "if", "self", ".", "pid", "!=", "os", ".", "getpid", "(", ")", "or", "not", "self", ".", "_bite", ":", "client_kwargs", "=", "dict", "(", "filter", "(", "lambda", "k_v", ":", "k_v", "[", "1", "]", "is", "not", "None", "and", "k_v", "[", "1", "]", "!=", "''", ",", "six", ".", "iteritems", "(", "{", "'hadoop_version'", ":", "config", ".", "client_version", ",", "'effective_user'", ":", "config", ".", "effective_user", ",", "}", ")", ")", ")", "if", "config", ".", "snakebite_autoconfig", ":", "\"\"\"\n This is fully backwards compatible with the vanilla Client and can be used for a non HA cluster as well.\n This client tries to read ``${HADOOP_PATH}/conf/hdfs-site.xml`` to get the address of the namenode.\n The behaviour is the same as Client.\n \"\"\"", "from", "snakebite", ".", "client", "import", "AutoConfigClient", "self", ".", "_bite", "=", "AutoConfigClient", "(", "*", "*", "client_kwargs", ")", "else", ":", "from", "snakebite", ".", "client", "import", "Client", "self", ".", "_bite", "=", "Client", "(", "config", ".", "namenode_host", ",", "config", ".", "namenode_port", ",", "*", "*", "client_kwargs", ")", "return", "self", ".", "_bite" ]
If Luigi has forked, we have a different PID, and need to reconnect.
[ "If", "Luigi", "has", "forked", "we", "have", "a", "different", "PID", "and", "need", "to", "reconnect", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hdfs/snakebite_client.py#L58-L81
train
spotify/luigi
luigi/contrib/hdfs/snakebite_client.py
SnakebiteHdfsClient.move
def move(self, path, dest): """ Use snakebite.rename, if available. :param path: source file(s) :type path: either a string or sequence of strings :param dest: destination file (single input) or directory (multiple) :type dest: string :return: list of renamed items """ parts = dest.rstrip('/').split('/') if len(parts) > 1: dir_path = '/'.join(parts[0:-1]) if not self.exists(dir_path): self.mkdir(dir_path, parents=True) return list(self.get_bite().rename(self.list_path(path), dest))
python
def move(self, path, dest): """ Use snakebite.rename, if available. :param path: source file(s) :type path: either a string or sequence of strings :param dest: destination file (single input) or directory (multiple) :type dest: string :return: list of renamed items """ parts = dest.rstrip('/').split('/') if len(parts) > 1: dir_path = '/'.join(parts[0:-1]) if not self.exists(dir_path): self.mkdir(dir_path, parents=True) return list(self.get_bite().rename(self.list_path(path), dest))
[ "def", "move", "(", "self", ",", "path", ",", "dest", ")", ":", "parts", "=", "dest", ".", "rstrip", "(", "'/'", ")", ".", "split", "(", "'/'", ")", "if", "len", "(", "parts", ")", ">", "1", ":", "dir_path", "=", "'/'", ".", "join", "(", "parts", "[", "0", ":", "-", "1", "]", ")", "if", "not", "self", ".", "exists", "(", "dir_path", ")", ":", "self", ".", "mkdir", "(", "dir_path", ",", "parents", "=", "True", ")", "return", "list", "(", "self", ".", "get_bite", "(", ")", ".", "rename", "(", "self", ".", "list_path", "(", "path", ")", ",", "dest", ")", ")" ]
Use snakebite.rename, if available. :param path: source file(s) :type path: either a string or sequence of strings :param dest: destination file (single input) or directory (multiple) :type dest: string :return: list of renamed items
[ "Use", "snakebite", ".", "rename", "if", "available", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hdfs/snakebite_client.py#L93-L108
train
spotify/luigi
luigi/contrib/hdfs/snakebite_client.py
SnakebiteHdfsClient.rename_dont_move
def rename_dont_move(self, path, dest): """ Use snakebite.rename_dont_move, if available. :param path: source path (single input) :type path: string :param dest: destination path :type dest: string :return: True if succeeded :raises: snakebite.errors.FileAlreadyExistsException """ from snakebite.errors import FileAlreadyExistsException try: self.get_bite().rename2(path, dest, overwriteDest=False) except FileAlreadyExistsException: # Unfortunately python2 don't allow exception chaining. raise luigi.target.FileAlreadyExists()
python
def rename_dont_move(self, path, dest): """ Use snakebite.rename_dont_move, if available. :param path: source path (single input) :type path: string :param dest: destination path :type dest: string :return: True if succeeded :raises: snakebite.errors.FileAlreadyExistsException """ from snakebite.errors import FileAlreadyExistsException try: self.get_bite().rename2(path, dest, overwriteDest=False) except FileAlreadyExistsException: # Unfortunately python2 don't allow exception chaining. raise luigi.target.FileAlreadyExists()
[ "def", "rename_dont_move", "(", "self", ",", "path", ",", "dest", ")", ":", "from", "snakebite", ".", "errors", "import", "FileAlreadyExistsException", "try", ":", "self", ".", "get_bite", "(", ")", ".", "rename2", "(", "path", ",", "dest", ",", "overwriteDest", "=", "False", ")", "except", "FileAlreadyExistsException", ":", "# Unfortunately python2 don't allow exception chaining.", "raise", "luigi", ".", "target", ".", "FileAlreadyExists", "(", ")" ]
Use snakebite.rename_dont_move, if available. :param path: source path (single input) :type path: string :param dest: destination path :type dest: string :return: True if succeeded :raises: snakebite.errors.FileAlreadyExistsException
[ "Use", "snakebite", ".", "rename_dont_move", "if", "available", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hdfs/snakebite_client.py#L110-L126
train
spotify/luigi
luigi/contrib/hdfs/snakebite_client.py
SnakebiteHdfsClient.remove
def remove(self, path, recursive=True, skip_trash=False): """ Use snakebite.delete, if available. :param path: delete-able file(s) or directory(ies) :type path: either a string or a sequence of strings :param recursive: delete directories trees like \\*nix: rm -r :type recursive: boolean, default is True :param skip_trash: do or don't move deleted items into the trash first :type skip_trash: boolean, default is False (use trash) :return: list of deleted items """ return list(self.get_bite().delete(self.list_path(path), recurse=recursive))
python
def remove(self, path, recursive=True, skip_trash=False): """ Use snakebite.delete, if available. :param path: delete-able file(s) or directory(ies) :type path: either a string or a sequence of strings :param recursive: delete directories trees like \\*nix: rm -r :type recursive: boolean, default is True :param skip_trash: do or don't move deleted items into the trash first :type skip_trash: boolean, default is False (use trash) :return: list of deleted items """ return list(self.get_bite().delete(self.list_path(path), recurse=recursive))
[ "def", "remove", "(", "self", ",", "path", ",", "recursive", "=", "True", ",", "skip_trash", "=", "False", ")", ":", "return", "list", "(", "self", ".", "get_bite", "(", ")", ".", "delete", "(", "self", ".", "list_path", "(", "path", ")", ",", "recurse", "=", "recursive", ")", ")" ]
Use snakebite.delete, if available. :param path: delete-able file(s) or directory(ies) :type path: either a string or a sequence of strings :param recursive: delete directories trees like \\*nix: rm -r :type recursive: boolean, default is True :param skip_trash: do or don't move deleted items into the trash first :type skip_trash: boolean, default is False (use trash) :return: list of deleted items
[ "Use", "snakebite", ".", "delete", "if", "available", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hdfs/snakebite_client.py#L128-L140
train
spotify/luigi
luigi/contrib/hdfs/snakebite_client.py
SnakebiteHdfsClient.chmod
def chmod(self, path, permissions, recursive=False): """ Use snakebite.chmod, if available. :param path: update-able file(s) :type path: either a string or sequence of strings :param permissions: \\*nix style permission number :type permissions: octal :param recursive: change just listed entry(ies) or all in directories :type recursive: boolean, default is False :return: list of all changed items """ if type(permissions) == str: permissions = int(permissions, 8) return list(self.get_bite().chmod(self.list_path(path), permissions, recursive))
python
def chmod(self, path, permissions, recursive=False): """ Use snakebite.chmod, if available. :param path: update-able file(s) :type path: either a string or sequence of strings :param permissions: \\*nix style permission number :type permissions: octal :param recursive: change just listed entry(ies) or all in directories :type recursive: boolean, default is False :return: list of all changed items """ if type(permissions) == str: permissions = int(permissions, 8) return list(self.get_bite().chmod(self.list_path(path), permissions, recursive))
[ "def", "chmod", "(", "self", ",", "path", ",", "permissions", ",", "recursive", "=", "False", ")", ":", "if", "type", "(", "permissions", ")", "==", "str", ":", "permissions", "=", "int", "(", "permissions", ",", "8", ")", "return", "list", "(", "self", ".", "get_bite", "(", ")", ".", "chmod", "(", "self", ".", "list_path", "(", "path", ")", ",", "permissions", ",", "recursive", ")", ")" ]
Use snakebite.chmod, if available. :param path: update-able file(s) :type path: either a string or sequence of strings :param permissions: \\*nix style permission number :type permissions: octal :param recursive: change just listed entry(ies) or all in directories :type recursive: boolean, default is False :return: list of all changed items
[ "Use", "snakebite", ".", "chmod", "if", "available", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hdfs/snakebite_client.py#L142-L157
train
spotify/luigi
luigi/contrib/hdfs/snakebite_client.py
SnakebiteHdfsClient.chown
def chown(self, path, owner, group, recursive=False): """ Use snakebite.chown/chgrp, if available. One of owner or group must be set. Just setting group calls chgrp. :param path: update-able file(s) :type path: either a string or sequence of strings :param owner: new owner, can be blank :type owner: string :param group: new group, can be blank :type group: string :param recursive: change just listed entry(ies) or all in directories :type recursive: boolean, default is False :return: list of all changed items """ bite = self.get_bite() if owner: if group: return all(bite.chown(self.list_path(path), "%s:%s" % (owner, group), recurse=recursive)) return all(bite.chown(self.list_path(path), owner, recurse=recursive)) return list(bite.chgrp(self.list_path(path), group, recurse=recursive))
python
def chown(self, path, owner, group, recursive=False): """ Use snakebite.chown/chgrp, if available. One of owner or group must be set. Just setting group calls chgrp. :param path: update-able file(s) :type path: either a string or sequence of strings :param owner: new owner, can be blank :type owner: string :param group: new group, can be blank :type group: string :param recursive: change just listed entry(ies) or all in directories :type recursive: boolean, default is False :return: list of all changed items """ bite = self.get_bite() if owner: if group: return all(bite.chown(self.list_path(path), "%s:%s" % (owner, group), recurse=recursive)) return all(bite.chown(self.list_path(path), owner, recurse=recursive)) return list(bite.chgrp(self.list_path(path), group, recurse=recursive))
[ "def", "chown", "(", "self", ",", "path", ",", "owner", ",", "group", ",", "recursive", "=", "False", ")", ":", "bite", "=", "self", ".", "get_bite", "(", ")", "if", "owner", ":", "if", "group", ":", "return", "all", "(", "bite", ".", "chown", "(", "self", ".", "list_path", "(", "path", ")", ",", "\"%s:%s\"", "%", "(", "owner", ",", "group", ")", ",", "recurse", "=", "recursive", ")", ")", "return", "all", "(", "bite", ".", "chown", "(", "self", ".", "list_path", "(", "path", ")", ",", "owner", ",", "recurse", "=", "recursive", ")", ")", "return", "list", "(", "bite", ".", "chgrp", "(", "self", ".", "list_path", "(", "path", ")", ",", "group", ",", "recurse", "=", "recursive", ")", ")" ]
Use snakebite.chown/chgrp, if available. One of owner or group must be set. Just setting group calls chgrp. :param path: update-able file(s) :type path: either a string or sequence of strings :param owner: new owner, can be blank :type owner: string :param group: new group, can be blank :type group: string :param recursive: change just listed entry(ies) or all in directories :type recursive: boolean, default is False :return: list of all changed items
[ "Use", "snakebite", ".", "chown", "/", "chgrp", "if", "available", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hdfs/snakebite_client.py#L159-L181
train
spotify/luigi
luigi/contrib/hdfs/snakebite_client.py
SnakebiteHdfsClient.count
def count(self, path): """ Use snakebite.count, if available. :param path: directory to count the contents of :type path: string :return: dictionary with content_size, dir_count and file_count keys """ try: res = self.get_bite().count(self.list_path(path)).next() dir_count = res['directoryCount'] file_count = res['fileCount'] content_size = res['spaceConsumed'] except StopIteration: dir_count = file_count = content_size = 0 return {'content_size': content_size, 'dir_count': dir_count, 'file_count': file_count}
python
def count(self, path): """ Use snakebite.count, if available. :param path: directory to count the contents of :type path: string :return: dictionary with content_size, dir_count and file_count keys """ try: res = self.get_bite().count(self.list_path(path)).next() dir_count = res['directoryCount'] file_count = res['fileCount'] content_size = res['spaceConsumed'] except StopIteration: dir_count = file_count = content_size = 0 return {'content_size': content_size, 'dir_count': dir_count, 'file_count': file_count}
[ "def", "count", "(", "self", ",", "path", ")", ":", "try", ":", "res", "=", "self", ".", "get_bite", "(", ")", ".", "count", "(", "self", ".", "list_path", "(", "path", ")", ")", ".", "next", "(", ")", "dir_count", "=", "res", "[", "'directoryCount'", "]", "file_count", "=", "res", "[", "'fileCount'", "]", "content_size", "=", "res", "[", "'spaceConsumed'", "]", "except", "StopIteration", ":", "dir_count", "=", "file_count", "=", "content_size", "=", "0", "return", "{", "'content_size'", ":", "content_size", ",", "'dir_count'", ":", "dir_count", ",", "'file_count'", ":", "file_count", "}" ]
Use snakebite.count, if available. :param path: directory to count the contents of :type path: string :return: dictionary with content_size, dir_count and file_count keys
[ "Use", "snakebite", ".", "count", "if", "available", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hdfs/snakebite_client.py#L183-L199
train
spotify/luigi
luigi/contrib/hdfs/snakebite_client.py
SnakebiteHdfsClient.get
def get(self, path, local_destination): """ Use snakebite.copyToLocal, if available. :param path: HDFS file :type path: string :param local_destination: path on the system running Luigi :type local_destination: string """ return list(self.get_bite().copyToLocal(self.list_path(path), local_destination))
python
def get(self, path, local_destination): """ Use snakebite.copyToLocal, if available. :param path: HDFS file :type path: string :param local_destination: path on the system running Luigi :type local_destination: string """ return list(self.get_bite().copyToLocal(self.list_path(path), local_destination))
[ "def", "get", "(", "self", ",", "path", ",", "local_destination", ")", ":", "return", "list", "(", "self", ".", "get_bite", "(", ")", ".", "copyToLocal", "(", "self", ".", "list_path", "(", "path", ")", ",", "local_destination", ")", ")" ]
Use snakebite.copyToLocal, if available. :param path: HDFS file :type path: string :param local_destination: path on the system running Luigi :type local_destination: string
[ "Use", "snakebite", ".", "copyToLocal", "if", "available", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hdfs/snakebite_client.py#L213-L223
train
spotify/luigi
luigi/contrib/hdfs/snakebite_client.py
SnakebiteHdfsClient.get_merge
def get_merge(self, path, local_destination): """ Using snakebite getmerge to implement this. :param path: HDFS directory :param local_destination: path on the system running Luigi :return: merge of the directory """ return list(self.get_bite().getmerge(path=path, dst=local_destination))
python
def get_merge(self, path, local_destination): """ Using snakebite getmerge to implement this. :param path: HDFS directory :param local_destination: path on the system running Luigi :return: merge of the directory """ return list(self.get_bite().getmerge(path=path, dst=local_destination))
[ "def", "get_merge", "(", "self", ",", "path", ",", "local_destination", ")", ":", "return", "list", "(", "self", ".", "get_bite", "(", ")", ".", "getmerge", "(", "path", "=", "path", ",", "dst", "=", "local_destination", ")", ")" ]
Using snakebite getmerge to implement this. :param path: HDFS directory :param local_destination: path on the system running Luigi :return: merge of the directory
[ "Using", "snakebite", "getmerge", "to", "implement", "this", ".", ":", "param", "path", ":", "HDFS", "directory", ":", "param", "local_destination", ":", "path", "on", "the", "system", "running", "Luigi", ":", "return", ":", "merge", "of", "the", "directory" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hdfs/snakebite_client.py#L225-L232
train
spotify/luigi
luigi/contrib/hdfs/snakebite_client.py
SnakebiteHdfsClient.mkdir
def mkdir(self, path, parents=True, mode=0o755, raise_if_exists=False): """ Use snakebite.mkdir, if available. Snakebite's mkdir method allows control over full path creation, so by default, tell it to build a full path to work like ``hadoop fs -mkdir``. :param path: HDFS path to create :type path: string :param parents: create any missing parent directories :type parents: boolean, default is True :param mode: \\*nix style owner/group/other permissions :type mode: octal, default 0755 """ result = list(self.get_bite().mkdir(self.list_path(path), create_parent=parents, mode=mode)) if raise_if_exists and "ile exists" in result[0].get('error', ''): raise luigi.target.FileAlreadyExists("%s exists" % (path, )) return result
python
def mkdir(self, path, parents=True, mode=0o755, raise_if_exists=False): """ Use snakebite.mkdir, if available. Snakebite's mkdir method allows control over full path creation, so by default, tell it to build a full path to work like ``hadoop fs -mkdir``. :param path: HDFS path to create :type path: string :param parents: create any missing parent directories :type parents: boolean, default is True :param mode: \\*nix style owner/group/other permissions :type mode: octal, default 0755 """ result = list(self.get_bite().mkdir(self.list_path(path), create_parent=parents, mode=mode)) if raise_if_exists and "ile exists" in result[0].get('error', ''): raise luigi.target.FileAlreadyExists("%s exists" % (path, )) return result
[ "def", "mkdir", "(", "self", ",", "path", ",", "parents", "=", "True", ",", "mode", "=", "0o755", ",", "raise_if_exists", "=", "False", ")", ":", "result", "=", "list", "(", "self", ".", "get_bite", "(", ")", ".", "mkdir", "(", "self", ".", "list_path", "(", "path", ")", ",", "create_parent", "=", "parents", ",", "mode", "=", "mode", ")", ")", "if", "raise_if_exists", "and", "\"ile exists\"", "in", "result", "[", "0", "]", ".", "get", "(", "'error'", ",", "''", ")", ":", "raise", "luigi", ".", "target", ".", "FileAlreadyExists", "(", "\"%s exists\"", "%", "(", "path", ",", ")", ")", "return", "result" ]
Use snakebite.mkdir, if available. Snakebite's mkdir method allows control over full path creation, so by default, tell it to build a full path to work like ``hadoop fs -mkdir``. :param path: HDFS path to create :type path: string :param parents: create any missing parent directories :type parents: boolean, default is True :param mode: \\*nix style owner/group/other permissions :type mode: octal, default 0755
[ "Use", "snakebite", ".", "mkdir", "if", "available", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hdfs/snakebite_client.py#L234-L252
train
spotify/luigi
luigi/contrib/hdfs/snakebite_client.py
SnakebiteHdfsClient.listdir
def listdir(self, path, ignore_directories=False, ignore_files=False, include_size=False, include_type=False, include_time=False, recursive=False): """ Use snakebite.ls to get the list of items in a directory. :param path: the directory to list :type path: string :param ignore_directories: if True, do not yield directory entries :type ignore_directories: boolean, default is False :param ignore_files: if True, do not yield file entries :type ignore_files: boolean, default is False :param include_size: include the size in bytes of the current item :type include_size: boolean, default is False (do not include) :param include_type: include the type (d or f) of the current item :type include_type: boolean, default is False (do not include) :param include_time: include the last modification time of the current item :type include_time: boolean, default is False (do not include) :param recursive: list subdirectory contents :type recursive: boolean, default is False (do not recurse) :return: yield with a string, or if any of the include_* settings are true, a tuple starting with the path, and include_* items in order """ bite = self.get_bite() for entry in bite.ls(self.list_path(path), recurse=recursive): if ignore_directories and entry['file_type'] == 'd': continue if ignore_files and entry['file_type'] == 'f': continue rval = [entry['path'], ] if include_size: rval.append(entry['length']) if include_type: rval.append(entry['file_type']) if include_time: rval.append(datetime.datetime.fromtimestamp(entry['modification_time'] / 1000)) if len(rval) > 1: yield tuple(rval) else: yield rval[0]
python
def listdir(self, path, ignore_directories=False, ignore_files=False, include_size=False, include_type=False, include_time=False, recursive=False): """ Use snakebite.ls to get the list of items in a directory. :param path: the directory to list :type path: string :param ignore_directories: if True, do not yield directory entries :type ignore_directories: boolean, default is False :param ignore_files: if True, do not yield file entries :type ignore_files: boolean, default is False :param include_size: include the size in bytes of the current item :type include_size: boolean, default is False (do not include) :param include_type: include the type (d or f) of the current item :type include_type: boolean, default is False (do not include) :param include_time: include the last modification time of the current item :type include_time: boolean, default is False (do not include) :param recursive: list subdirectory contents :type recursive: boolean, default is False (do not recurse) :return: yield with a string, or if any of the include_* settings are true, a tuple starting with the path, and include_* items in order """ bite = self.get_bite() for entry in bite.ls(self.list_path(path), recurse=recursive): if ignore_directories and entry['file_type'] == 'd': continue if ignore_files and entry['file_type'] == 'f': continue rval = [entry['path'], ] if include_size: rval.append(entry['length']) if include_type: rval.append(entry['file_type']) if include_time: rval.append(datetime.datetime.fromtimestamp(entry['modification_time'] / 1000)) if len(rval) > 1: yield tuple(rval) else: yield rval[0]
[ "def", "listdir", "(", "self", ",", "path", ",", "ignore_directories", "=", "False", ",", "ignore_files", "=", "False", ",", "include_size", "=", "False", ",", "include_type", "=", "False", ",", "include_time", "=", "False", ",", "recursive", "=", "False", ")", ":", "bite", "=", "self", ".", "get_bite", "(", ")", "for", "entry", "in", "bite", ".", "ls", "(", "self", ".", "list_path", "(", "path", ")", ",", "recurse", "=", "recursive", ")", ":", "if", "ignore_directories", "and", "entry", "[", "'file_type'", "]", "==", "'d'", ":", "continue", "if", "ignore_files", "and", "entry", "[", "'file_type'", "]", "==", "'f'", ":", "continue", "rval", "=", "[", "entry", "[", "'path'", "]", ",", "]", "if", "include_size", ":", "rval", ".", "append", "(", "entry", "[", "'length'", "]", ")", "if", "include_type", ":", "rval", ".", "append", "(", "entry", "[", "'file_type'", "]", ")", "if", "include_time", ":", "rval", ".", "append", "(", "datetime", ".", "datetime", ".", "fromtimestamp", "(", "entry", "[", "'modification_time'", "]", "/", "1000", ")", ")", "if", "len", "(", "rval", ")", ">", "1", ":", "yield", "tuple", "(", "rval", ")", "else", ":", "yield", "rval", "[", "0", "]" ]
Use snakebite.ls to get the list of items in a directory. :param path: the directory to list :type path: string :param ignore_directories: if True, do not yield directory entries :type ignore_directories: boolean, default is False :param ignore_files: if True, do not yield file entries :type ignore_files: boolean, default is False :param include_size: include the size in bytes of the current item :type include_size: boolean, default is False (do not include) :param include_type: include the type (d or f) of the current item :type include_type: boolean, default is False (do not include) :param include_time: include the last modification time of the current item :type include_time: boolean, default is False (do not include) :param recursive: list subdirectory contents :type recursive: boolean, default is False (do not recurse) :return: yield with a string, or if any of the include_* settings are true, a tuple starting with the path, and include_* items in order
[ "Use", "snakebite", ".", "ls", "to", "get", "the", "list", "of", "items", "in", "a", "directory", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hdfs/snakebite_client.py#L254-L293
train
spotify/luigi
luigi/configuration/base_parser.py
BaseParser.instance
def instance(cls, *args, **kwargs): """ Singleton getter """ if cls._instance is None: cls._instance = cls(*args, **kwargs) loaded = cls._instance.reload() logging.getLogger('luigi-interface').info('Loaded %r', loaded) return cls._instance
python
def instance(cls, *args, **kwargs): """ Singleton getter """ if cls._instance is None: cls._instance = cls(*args, **kwargs) loaded = cls._instance.reload() logging.getLogger('luigi-interface').info('Loaded %r', loaded) return cls._instance
[ "def", "instance", "(", "cls", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "cls", ".", "_instance", "is", "None", ":", "cls", ".", "_instance", "=", "cls", "(", "*", "args", ",", "*", "*", "kwargs", ")", "loaded", "=", "cls", ".", "_instance", ".", "reload", "(", ")", "logging", ".", "getLogger", "(", "'luigi-interface'", ")", ".", "info", "(", "'Loaded %r'", ",", "loaded", ")", "return", "cls", ".", "_instance" ]
Singleton getter
[ "Singleton", "getter" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/configuration/base_parser.py#L25-L32
train
spotify/luigi
luigi/task_register.py
load_task
def load_task(module, task_name, params_str): """ Imports task dynamically given a module and a task name. """ if module is not None: __import__(module) task_cls = Register.get_task_cls(task_name) return task_cls.from_str_params(params_str)
python
def load_task(module, task_name, params_str): """ Imports task dynamically given a module and a task name. """ if module is not None: __import__(module) task_cls = Register.get_task_cls(task_name) return task_cls.from_str_params(params_str)
[ "def", "load_task", "(", "module", ",", "task_name", ",", "params_str", ")", ":", "if", "module", "is", "not", "None", ":", "__import__", "(", "module", ")", "task_cls", "=", "Register", ".", "get_task_cls", "(", "task_name", ")", "return", "task_cls", ".", "from_str_params", "(", "params_str", ")" ]
Imports task dynamically given a module and a task name.
[ "Imports", "task", "dynamically", "given", "a", "module", "and", "a", "task", "name", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/task_register.py#L246-L253
train
spotify/luigi
luigi/task_register.py
Register.task_family
def task_family(cls): """ Internal note: This function will be deleted soon. """ if not cls.get_task_namespace(): return cls.__name__ else: return "{}.{}".format(cls.get_task_namespace(), cls.__name__)
python
def task_family(cls): """ Internal note: This function will be deleted soon. """ if not cls.get_task_namespace(): return cls.__name__ else: return "{}.{}".format(cls.get_task_namespace(), cls.__name__)
[ "def", "task_family", "(", "cls", ")", ":", "if", "not", "cls", ".", "get_task_namespace", "(", ")", ":", "return", "cls", ".", "__name__", "else", ":", "return", "\"{}.{}\"", ".", "format", "(", "cls", ".", "get_task_namespace", "(", ")", ",", "cls", ".", "__name__", ")" ]
Internal note: This function will be deleted soon.
[ "Internal", "note", ":", "This", "function", "will", "be", "deleted", "soon", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/task_register.py#L118-L125
train
spotify/luigi
luigi/task_register.py
Register._get_reg
def _get_reg(cls): """Return all of the registered classes. :return: an ``dict`` of task_family -> class """ # We have to do this on-demand in case task names have changed later reg = dict() for task_cls in cls._reg: if not task_cls._visible_in_registry: continue name = task_cls.get_task_family() if name in reg and \ (reg[name] == Register.AMBIGUOUS_CLASS or # Check so issubclass doesn't crash not issubclass(task_cls, reg[name])): # Registering two different classes - this means we can't instantiate them by name # The only exception is if one class is a subclass of the other. In that case, we # instantiate the most-derived class (this fixes some issues with decorator wrappers). reg[name] = Register.AMBIGUOUS_CLASS else: reg[name] = task_cls return reg
python
def _get_reg(cls): """Return all of the registered classes. :return: an ``dict`` of task_family -> class """ # We have to do this on-demand in case task names have changed later reg = dict() for task_cls in cls._reg: if not task_cls._visible_in_registry: continue name = task_cls.get_task_family() if name in reg and \ (reg[name] == Register.AMBIGUOUS_CLASS or # Check so issubclass doesn't crash not issubclass(task_cls, reg[name])): # Registering two different classes - this means we can't instantiate them by name # The only exception is if one class is a subclass of the other. In that case, we # instantiate the most-derived class (this fixes some issues with decorator wrappers). reg[name] = Register.AMBIGUOUS_CLASS else: reg[name] = task_cls return reg
[ "def", "_get_reg", "(", "cls", ")", ":", "# We have to do this on-demand in case task names have changed later", "reg", "=", "dict", "(", ")", "for", "task_cls", "in", "cls", ".", "_reg", ":", "if", "not", "task_cls", ".", "_visible_in_registry", ":", "continue", "name", "=", "task_cls", ".", "get_task_family", "(", ")", "if", "name", "in", "reg", "and", "(", "reg", "[", "name", "]", "==", "Register", ".", "AMBIGUOUS_CLASS", "or", "# Check so issubclass doesn't crash", "not", "issubclass", "(", "task_cls", ",", "reg", "[", "name", "]", ")", ")", ":", "# Registering two different classes - this means we can't instantiate them by name", "# The only exception is if one class is a subclass of the other. In that case, we", "# instantiate the most-derived class (this fixes some issues with decorator wrappers).", "reg", "[", "name", "]", "=", "Register", ".", "AMBIGUOUS_CLASS", "else", ":", "reg", "[", "name", "]", "=", "task_cls", "return", "reg" ]
Return all of the registered classes. :return: an ``dict`` of task_family -> class
[ "Return", "all", "of", "the", "registered", "classes", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/task_register.py#L128-L150
train
spotify/luigi
luigi/task_register.py
Register._set_reg
def _set_reg(cls, reg): """The writing complement of _get_reg """ cls._reg = [task_cls for task_cls in reg.values() if task_cls is not cls.AMBIGUOUS_CLASS]
python
def _set_reg(cls, reg): """The writing complement of _get_reg """ cls._reg = [task_cls for task_cls in reg.values() if task_cls is not cls.AMBIGUOUS_CLASS]
[ "def", "_set_reg", "(", "cls", ",", "reg", ")", ":", "cls", ".", "_reg", "=", "[", "task_cls", "for", "task_cls", "in", "reg", ".", "values", "(", ")", "if", "task_cls", "is", "not", "cls", ".", "AMBIGUOUS_CLASS", "]" ]
The writing complement of _get_reg
[ "The", "writing", "complement", "of", "_get_reg" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/task_register.py#L153-L156
train
spotify/luigi
luigi/task_register.py
Register.get_task_cls
def get_task_cls(cls, name): """ Returns an unambiguous class or raises an exception. """ task_cls = cls._get_reg().get(name) if not task_cls: raise TaskClassNotFoundException(cls._missing_task_msg(name)) if task_cls == cls.AMBIGUOUS_CLASS: raise TaskClassAmbigiousException('Task %r is ambiguous' % name) return task_cls
python
def get_task_cls(cls, name): """ Returns an unambiguous class or raises an exception. """ task_cls = cls._get_reg().get(name) if not task_cls: raise TaskClassNotFoundException(cls._missing_task_msg(name)) if task_cls == cls.AMBIGUOUS_CLASS: raise TaskClassAmbigiousException('Task %r is ambiguous' % name) return task_cls
[ "def", "get_task_cls", "(", "cls", ",", "name", ")", ":", "task_cls", "=", "cls", ".", "_get_reg", "(", ")", ".", "get", "(", "name", ")", "if", "not", "task_cls", ":", "raise", "TaskClassNotFoundException", "(", "cls", ".", "_missing_task_msg", "(", "name", ")", ")", "if", "task_cls", "==", "cls", ".", "AMBIGUOUS_CLASS", ":", "raise", "TaskClassAmbigiousException", "(", "'Task %r is ambiguous'", "%", "name", ")", "return", "task_cls" ]
Returns an unambiguous class or raises an exception.
[ "Returns", "an", "unambiguous", "class", "or", "raises", "an", "exception", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/task_register.py#L173-L183
train
spotify/luigi
luigi/task_register.py
Register.get_all_params
def get_all_params(cls): """ Compiles and returns all parameters for all :py:class:`Task`. :return: a generator of tuples (TODO: we should make this more elegant) """ for task_name, task_cls in six.iteritems(cls._get_reg()): if task_cls == cls.AMBIGUOUS_CLASS: continue for param_name, param_obj in task_cls.get_params(): yield task_name, (not task_cls.use_cmdline_section), param_name, param_obj
python
def get_all_params(cls): """ Compiles and returns all parameters for all :py:class:`Task`. :return: a generator of tuples (TODO: we should make this more elegant) """ for task_name, task_cls in six.iteritems(cls._get_reg()): if task_cls == cls.AMBIGUOUS_CLASS: continue for param_name, param_obj in task_cls.get_params(): yield task_name, (not task_cls.use_cmdline_section), param_name, param_obj
[ "def", "get_all_params", "(", "cls", ")", ":", "for", "task_name", ",", "task_cls", "in", "six", ".", "iteritems", "(", "cls", ".", "_get_reg", "(", ")", ")", ":", "if", "task_cls", "==", "cls", ".", "AMBIGUOUS_CLASS", ":", "continue", "for", "param_name", ",", "param_obj", "in", "task_cls", ".", "get_params", "(", ")", ":", "yield", "task_name", ",", "(", "not", "task_cls", ".", "use_cmdline_section", ")", ",", "param_name", ",", "param_obj" ]
Compiles and returns all parameters for all :py:class:`Task`. :return: a generator of tuples (TODO: we should make this more elegant)
[ "Compiles", "and", "returns", "all", "parameters", "for", "all", ":", "py", ":", "class", ":", "Task", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/task_register.py#L186-L196
train
spotify/luigi
luigi/task_register.py
Register._editdistance
def _editdistance(a, b): """ Simple unweighted Levenshtein distance """ r0 = range(0, len(b) + 1) r1 = [0] * (len(b) + 1) for i in range(0, len(a)): r1[0] = i + 1 for j in range(0, len(b)): c = 0 if a[i] is b[j] else 1 r1[j + 1] = min(r1[j] + 1, r0[j + 1] + 1, r0[j] + c) r0 = r1[:] return r1[len(b)]
python
def _editdistance(a, b): """ Simple unweighted Levenshtein distance """ r0 = range(0, len(b) + 1) r1 = [0] * (len(b) + 1) for i in range(0, len(a)): r1[0] = i + 1 for j in range(0, len(b)): c = 0 if a[i] is b[j] else 1 r1[j + 1] = min(r1[j] + 1, r0[j + 1] + 1, r0[j] + c) r0 = r1[:] return r1[len(b)]
[ "def", "_editdistance", "(", "a", ",", "b", ")", ":", "r0", "=", "range", "(", "0", ",", "len", "(", "b", ")", "+", "1", ")", "r1", "=", "[", "0", "]", "*", "(", "len", "(", "b", ")", "+", "1", ")", "for", "i", "in", "range", "(", "0", ",", "len", "(", "a", ")", ")", ":", "r1", "[", "0", "]", "=", "i", "+", "1", "for", "j", "in", "range", "(", "0", ",", "len", "(", "b", ")", ")", ":", "c", "=", "0", "if", "a", "[", "i", "]", "is", "b", "[", "j", "]", "else", "1", "r1", "[", "j", "+", "1", "]", "=", "min", "(", "r1", "[", "j", "]", "+", "1", ",", "r0", "[", "j", "+", "1", "]", "+", "1", ",", "r0", "[", "j", "]", "+", "c", ")", "r0", "=", "r1", "[", ":", "]", "return", "r1", "[", "len", "(", "b", ")", "]" ]
Simple unweighted Levenshtein distance
[ "Simple", "unweighted", "Levenshtein", "distance" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/task_register.py#L199-L213
train
spotify/luigi
luigi/task_register.py
Register._module_parents
def _module_parents(module_name): ''' >>> list(Register._module_parents('a.b')) ['a.b', 'a', ''] ''' spl = module_name.split('.') for i in range(len(spl), 0, -1): yield '.'.join(spl[0:i]) if module_name: yield ''
python
def _module_parents(module_name): ''' >>> list(Register._module_parents('a.b')) ['a.b', 'a', ''] ''' spl = module_name.split('.') for i in range(len(spl), 0, -1): yield '.'.join(spl[0:i]) if module_name: yield ''
[ "def", "_module_parents", "(", "module_name", ")", ":", "spl", "=", "module_name", ".", "split", "(", "'.'", ")", "for", "i", "in", "range", "(", "len", "(", "spl", ")", ",", "0", ",", "-", "1", ")", ":", "yield", "'.'", ".", "join", "(", "spl", "[", "0", ":", "i", "]", ")", "if", "module_name", ":", "yield", "''" ]
>>> list(Register._module_parents('a.b')) ['a.b', 'a', '']
[ ">>>", "list", "(", "Register", ".", "_module_parents", "(", "a", ".", "b", "))", "[", "a", ".", "b", "a", "]" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/task_register.py#L234-L243
train
spotify/luigi
luigi/contrib/ecs.py
_get_task_statuses
def _get_task_statuses(task_ids, cluster): """ Retrieve task statuses from ECS API Returns list of {RUNNING|PENDING|STOPPED} for each id in task_ids """ response = client.describe_tasks(tasks=task_ids, cluster=cluster) # Error checking if response['failures'] != []: raise Exception('There were some failures:\n{0}'.format( response['failures'])) status_code = response['ResponseMetadata']['HTTPStatusCode'] if status_code != 200: msg = 'Task status request received status code {0}:\n{1}' raise Exception(msg.format(status_code, response)) return [t['lastStatus'] for t in response['tasks']]
python
def _get_task_statuses(task_ids, cluster): """ Retrieve task statuses from ECS API Returns list of {RUNNING|PENDING|STOPPED} for each id in task_ids """ response = client.describe_tasks(tasks=task_ids, cluster=cluster) # Error checking if response['failures'] != []: raise Exception('There were some failures:\n{0}'.format( response['failures'])) status_code = response['ResponseMetadata']['HTTPStatusCode'] if status_code != 200: msg = 'Task status request received status code {0}:\n{1}' raise Exception(msg.format(status_code, response)) return [t['lastStatus'] for t in response['tasks']]
[ "def", "_get_task_statuses", "(", "task_ids", ",", "cluster", ")", ":", "response", "=", "client", ".", "describe_tasks", "(", "tasks", "=", "task_ids", ",", "cluster", "=", "cluster", ")", "# Error checking", "if", "response", "[", "'failures'", "]", "!=", "[", "]", ":", "raise", "Exception", "(", "'There were some failures:\\n{0}'", ".", "format", "(", "response", "[", "'failures'", "]", ")", ")", "status_code", "=", "response", "[", "'ResponseMetadata'", "]", "[", "'HTTPStatusCode'", "]", "if", "status_code", "!=", "200", ":", "msg", "=", "'Task status request received status code {0}:\\n{1}'", "raise", "Exception", "(", "msg", ".", "format", "(", "status_code", ",", "response", ")", ")", "return", "[", "t", "[", "'lastStatus'", "]", "for", "t", "in", "response", "[", "'tasks'", "]", "]" ]
Retrieve task statuses from ECS API Returns list of {RUNNING|PENDING|STOPPED} for each id in task_ids
[ "Retrieve", "task", "statuses", "from", "ECS", "API" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/ecs.py#L68-L85
train
spotify/luigi
luigi/contrib/ecs.py
_track_tasks
def _track_tasks(task_ids, cluster): """Poll task status until STOPPED""" while True: statuses = _get_task_statuses(task_ids, cluster) if all([status == 'STOPPED' for status in statuses]): logger.info('ECS tasks {0} STOPPED'.format(','.join(task_ids))) break time.sleep(POLL_TIME) logger.debug('ECS task status for tasks {0}: {1}'.format(task_ids, statuses))
python
def _track_tasks(task_ids, cluster): """Poll task status until STOPPED""" while True: statuses = _get_task_statuses(task_ids, cluster) if all([status == 'STOPPED' for status in statuses]): logger.info('ECS tasks {0} STOPPED'.format(','.join(task_ids))) break time.sleep(POLL_TIME) logger.debug('ECS task status for tasks {0}: {1}'.format(task_ids, statuses))
[ "def", "_track_tasks", "(", "task_ids", ",", "cluster", ")", ":", "while", "True", ":", "statuses", "=", "_get_task_statuses", "(", "task_ids", ",", "cluster", ")", "if", "all", "(", "[", "status", "==", "'STOPPED'", "for", "status", "in", "statuses", "]", ")", ":", "logger", ".", "info", "(", "'ECS tasks {0} STOPPED'", ".", "format", "(", "','", ".", "join", "(", "task_ids", ")", ")", ")", "break", "time", ".", "sleep", "(", "POLL_TIME", ")", "logger", ".", "debug", "(", "'ECS task status for tasks {0}: {1}'", ".", "format", "(", "task_ids", ",", "statuses", ")", ")" ]
Poll task status until STOPPED
[ "Poll", "task", "status", "until", "STOPPED" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/ecs.py#L88-L96
train
spotify/luigi
luigi/contrib/rdbms.py
CopyToTable.create_table
def create_table(self, connection): """ Override to provide code for creating the target table. By default it will be created using types (optionally) specified in columns. If overridden, use the provided connection object for setting up the table in order to create the table and insert data using the same transaction. """ if len(self.columns[0]) == 1: # only names of columns specified, no types raise NotImplementedError("create_table() not implemented for %r and columns types not specified" % self.table) elif len(self.columns[0]) == 2: # if columns is specified as (name, type) tuples coldefs = ','.join( '{name} {type}'.format(name=name, type=type) for name, type in self.columns ) query = "CREATE TABLE {table} ({coldefs})".format(table=self.table, coldefs=coldefs) connection.cursor().execute(query)
python
def create_table(self, connection): """ Override to provide code for creating the target table. By default it will be created using types (optionally) specified in columns. If overridden, use the provided connection object for setting up the table in order to create the table and insert data using the same transaction. """ if len(self.columns[0]) == 1: # only names of columns specified, no types raise NotImplementedError("create_table() not implemented for %r and columns types not specified" % self.table) elif len(self.columns[0]) == 2: # if columns is specified as (name, type) tuples coldefs = ','.join( '{name} {type}'.format(name=name, type=type) for name, type in self.columns ) query = "CREATE TABLE {table} ({coldefs})".format(table=self.table, coldefs=coldefs) connection.cursor().execute(query)
[ "def", "create_table", "(", "self", ",", "connection", ")", ":", "if", "len", "(", "self", ".", "columns", "[", "0", "]", ")", "==", "1", ":", "# only names of columns specified, no types", "raise", "NotImplementedError", "(", "\"create_table() not implemented for %r and columns types not specified\"", "%", "self", ".", "table", ")", "elif", "len", "(", "self", ".", "columns", "[", "0", "]", ")", "==", "2", ":", "# if columns is specified as (name, type) tuples", "coldefs", "=", "','", ".", "join", "(", "'{name} {type}'", ".", "format", "(", "name", "=", "name", ",", "type", "=", "type", ")", "for", "name", ",", "type", "in", "self", ".", "columns", ")", "query", "=", "\"CREATE TABLE {table} ({coldefs})\"", ".", "format", "(", "table", "=", "self", ".", "table", ",", "coldefs", "=", "coldefs", ")", "connection", ".", "cursor", "(", ")", ".", "execute", "(", "query", ")" ]
Override to provide code for creating the target table. By default it will be created using types (optionally) specified in columns. If overridden, use the provided connection object for setting up the table in order to create the table and insert data using the same transaction.
[ "Override", "to", "provide", "code", "for", "creating", "the", "target", "table", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/rdbms.py#L201-L219
train
spotify/luigi
luigi/contrib/rdbms.py
CopyToTable.init_copy
def init_copy(self, connection): """ Override to perform custom queries. Any code here will be formed in the same transaction as the main copy, just prior to copying data. Example use cases include truncating the table or removing all data older than X in the database to keep a rolling window of data available in the table. """ # TODO: remove this after sufficient time so most people using the # clear_table attribtue will have noticed it doesn't work anymore if hasattr(self, "clear_table"): raise Exception("The clear_table attribute has been removed. Override init_copy instead!") if self.enable_metadata_columns: self._add_metadata_columns(connection.cursor())
python
def init_copy(self, connection): """ Override to perform custom queries. Any code here will be formed in the same transaction as the main copy, just prior to copying data. Example use cases include truncating the table or removing all data older than X in the database to keep a rolling window of data available in the table. """ # TODO: remove this after sufficient time so most people using the # clear_table attribtue will have noticed it doesn't work anymore if hasattr(self, "clear_table"): raise Exception("The clear_table attribute has been removed. Override init_copy instead!") if self.enable_metadata_columns: self._add_metadata_columns(connection.cursor())
[ "def", "init_copy", "(", "self", ",", "connection", ")", ":", "# TODO: remove this after sufficient time so most people using the", "# clear_table attribtue will have noticed it doesn't work anymore", "if", "hasattr", "(", "self", ",", "\"clear_table\"", ")", ":", "raise", "Exception", "(", "\"The clear_table attribute has been removed. Override init_copy instead!\"", ")", "if", "self", ".", "enable_metadata_columns", ":", "self", ".", "_add_metadata_columns", "(", "connection", ".", "cursor", "(", ")", ")" ]
Override to perform custom queries. Any code here will be formed in the same transaction as the main copy, just prior to copying data. Example use cases include truncating the table or removing all data older than X in the database to keep a rolling window of data available in the table.
[ "Override", "to", "perform", "custom", "queries", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/rdbms.py#L232-L247
train
spotify/luigi
luigi/util.py
common_params
def common_params(task_instance, task_cls): """ Grab all the values in task_instance that are found in task_cls. """ if not isinstance(task_cls, task.Register): raise TypeError("task_cls must be an uninstantiated Task") task_instance_param_names = dict(task_instance.get_params()).keys() task_cls_params_dict = dict(task_cls.get_params()) task_cls_param_names = task_cls_params_dict.keys() common_param_names = set(task_instance_param_names).intersection(set(task_cls_param_names)) common_param_vals = [(key, task_cls_params_dict[key]) for key in common_param_names] common_kwargs = dict((key, task_instance.param_kwargs[key]) for key in common_param_names) vals = dict(task_instance.get_param_values(common_param_vals, [], common_kwargs)) return vals
python
def common_params(task_instance, task_cls): """ Grab all the values in task_instance that are found in task_cls. """ if not isinstance(task_cls, task.Register): raise TypeError("task_cls must be an uninstantiated Task") task_instance_param_names = dict(task_instance.get_params()).keys() task_cls_params_dict = dict(task_cls.get_params()) task_cls_param_names = task_cls_params_dict.keys() common_param_names = set(task_instance_param_names).intersection(set(task_cls_param_names)) common_param_vals = [(key, task_cls_params_dict[key]) for key in common_param_names] common_kwargs = dict((key, task_instance.param_kwargs[key]) for key in common_param_names) vals = dict(task_instance.get_param_values(common_param_vals, [], common_kwargs)) return vals
[ "def", "common_params", "(", "task_instance", ",", "task_cls", ")", ":", "if", "not", "isinstance", "(", "task_cls", ",", "task", ".", "Register", ")", ":", "raise", "TypeError", "(", "\"task_cls must be an uninstantiated Task\"", ")", "task_instance_param_names", "=", "dict", "(", "task_instance", ".", "get_params", "(", ")", ")", ".", "keys", "(", ")", "task_cls_params_dict", "=", "dict", "(", "task_cls", ".", "get_params", "(", ")", ")", "task_cls_param_names", "=", "task_cls_params_dict", ".", "keys", "(", ")", "common_param_names", "=", "set", "(", "task_instance_param_names", ")", ".", "intersection", "(", "set", "(", "task_cls_param_names", ")", ")", "common_param_vals", "=", "[", "(", "key", ",", "task_cls_params_dict", "[", "key", "]", ")", "for", "key", "in", "common_param_names", "]", "common_kwargs", "=", "dict", "(", "(", "key", ",", "task_instance", ".", "param_kwargs", "[", "key", "]", ")", "for", "key", "in", "common_param_names", ")", "vals", "=", "dict", "(", "task_instance", ".", "get_param_values", "(", "common_param_vals", ",", "[", "]", ",", "common_kwargs", ")", ")", "return", "vals" ]
Grab all the values in task_instance that are found in task_cls.
[ "Grab", "all", "the", "values", "in", "task_instance", "that", "are", "found", "in", "task_cls", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/util.py#L234-L248
train
spotify/luigi
luigi/util.py
delegates
def delegates(task_that_delegates): """ Lets a task call methods on subtask(s). The way this works is that the subtask is run as a part of the task, but the task itself doesn't have to care about the requirements of the subtasks. The subtask doesn't exist from the scheduler's point of view, and its dependencies are instead required by the main task. Example: .. code-block:: python class PowersOfN(luigi.Task): n = luigi.IntParameter() def f(self, x): return x ** self.n @delegates class T(luigi.Task): def subtasks(self): return PowersOfN(5) def run(self): print self.subtasks().f(42) """ if not hasattr(task_that_delegates, 'subtasks'): # This method can (optionally) define a couple of delegate tasks that # will be accessible as interfaces, meaning that the task can access # those tasks and run methods defined on them, etc raise AttributeError('%s needs to implement the method "subtasks"' % task_that_delegates) @task._task_wraps(task_that_delegates) class Wrapped(task_that_delegates): def deps(self): # Overrides method in base class return task.flatten(self.requires()) + task.flatten([t.deps() for t in task.flatten(self.subtasks())]) def run(self): for t in task.flatten(self.subtasks()): t.run() task_that_delegates.run(self) return Wrapped
python
def delegates(task_that_delegates): """ Lets a task call methods on subtask(s). The way this works is that the subtask is run as a part of the task, but the task itself doesn't have to care about the requirements of the subtasks. The subtask doesn't exist from the scheduler's point of view, and its dependencies are instead required by the main task. Example: .. code-block:: python class PowersOfN(luigi.Task): n = luigi.IntParameter() def f(self, x): return x ** self.n @delegates class T(luigi.Task): def subtasks(self): return PowersOfN(5) def run(self): print self.subtasks().f(42) """ if not hasattr(task_that_delegates, 'subtasks'): # This method can (optionally) define a couple of delegate tasks that # will be accessible as interfaces, meaning that the task can access # those tasks and run methods defined on them, etc raise AttributeError('%s needs to implement the method "subtasks"' % task_that_delegates) @task._task_wraps(task_that_delegates) class Wrapped(task_that_delegates): def deps(self): # Overrides method in base class return task.flatten(self.requires()) + task.flatten([t.deps() for t in task.flatten(self.subtasks())]) def run(self): for t in task.flatten(self.subtasks()): t.run() task_that_delegates.run(self) return Wrapped
[ "def", "delegates", "(", "task_that_delegates", ")", ":", "if", "not", "hasattr", "(", "task_that_delegates", ",", "'subtasks'", ")", ":", "# This method can (optionally) define a couple of delegate tasks that", "# will be accessible as interfaces, meaning that the task can access", "# those tasks and run methods defined on them, etc", "raise", "AttributeError", "(", "'%s needs to implement the method \"subtasks\"'", "%", "task_that_delegates", ")", "@", "task", ".", "_task_wraps", "(", "task_that_delegates", ")", "class", "Wrapped", "(", "task_that_delegates", ")", ":", "def", "deps", "(", "self", ")", ":", "# Overrides method in base class", "return", "task", ".", "flatten", "(", "self", ".", "requires", "(", ")", ")", "+", "task", ".", "flatten", "(", "[", "t", ".", "deps", "(", ")", "for", "t", "in", "task", ".", "flatten", "(", "self", ".", "subtasks", "(", ")", ")", "]", ")", "def", "run", "(", "self", ")", ":", "for", "t", "in", "task", ".", "flatten", "(", "self", ".", "subtasks", "(", ")", ")", ":", "t", ".", "run", "(", ")", "task_that_delegates", ".", "run", "(", "self", ")", "return", "Wrapped" ]
Lets a task call methods on subtask(s). The way this works is that the subtask is run as a part of the task, but the task itself doesn't have to care about the requirements of the subtasks. The subtask doesn't exist from the scheduler's point of view, and its dependencies are instead required by the main task. Example: .. code-block:: python class PowersOfN(luigi.Task): n = luigi.IntParameter() def f(self, x): return x ** self.n @delegates class T(luigi.Task): def subtasks(self): return PowersOfN(5) def run(self): print self.subtasks().f(42)
[ "Lets", "a", "task", "call", "methods", "on", "subtask", "(", "s", ")", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/util.py#L380-L419
train
spotify/luigi
luigi/util.py
previous
def previous(task): """ Return a previous Task of the same family. By default checks if this task family only has one non-global parameter and if it is a DateParameter, DateHourParameter or DateIntervalParameter in which case it returns with the time decremented by 1 (hour, day or interval) """ params = task.get_params() previous_params = {} previous_date_params = {} for param_name, param_obj in params: param_value = getattr(task, param_name) if isinstance(param_obj, parameter.DateParameter): previous_date_params[param_name] = param_value - datetime.timedelta(days=1) elif isinstance(param_obj, parameter.DateSecondParameter): previous_date_params[param_name] = param_value - datetime.timedelta(seconds=1) elif isinstance(param_obj, parameter.DateMinuteParameter): previous_date_params[param_name] = param_value - datetime.timedelta(minutes=1) elif isinstance(param_obj, parameter.DateHourParameter): previous_date_params[param_name] = param_value - datetime.timedelta(hours=1) elif isinstance(param_obj, parameter.DateIntervalParameter): previous_date_params[param_name] = param_value.prev() else: previous_params[param_name] = param_value previous_params.update(previous_date_params) if len(previous_date_params) == 0: raise NotImplementedError("No task parameter - can't determine previous task") elif len(previous_date_params) > 1: raise NotImplementedError("Too many date-related task parameters - can't determine previous task") else: return task.clone(**previous_params)
python
def previous(task): """ Return a previous Task of the same family. By default checks if this task family only has one non-global parameter and if it is a DateParameter, DateHourParameter or DateIntervalParameter in which case it returns with the time decremented by 1 (hour, day or interval) """ params = task.get_params() previous_params = {} previous_date_params = {} for param_name, param_obj in params: param_value = getattr(task, param_name) if isinstance(param_obj, parameter.DateParameter): previous_date_params[param_name] = param_value - datetime.timedelta(days=1) elif isinstance(param_obj, parameter.DateSecondParameter): previous_date_params[param_name] = param_value - datetime.timedelta(seconds=1) elif isinstance(param_obj, parameter.DateMinuteParameter): previous_date_params[param_name] = param_value - datetime.timedelta(minutes=1) elif isinstance(param_obj, parameter.DateHourParameter): previous_date_params[param_name] = param_value - datetime.timedelta(hours=1) elif isinstance(param_obj, parameter.DateIntervalParameter): previous_date_params[param_name] = param_value.prev() else: previous_params[param_name] = param_value previous_params.update(previous_date_params) if len(previous_date_params) == 0: raise NotImplementedError("No task parameter - can't determine previous task") elif len(previous_date_params) > 1: raise NotImplementedError("Too many date-related task parameters - can't determine previous task") else: return task.clone(**previous_params)
[ "def", "previous", "(", "task", ")", ":", "params", "=", "task", ".", "get_params", "(", ")", "previous_params", "=", "{", "}", "previous_date_params", "=", "{", "}", "for", "param_name", ",", "param_obj", "in", "params", ":", "param_value", "=", "getattr", "(", "task", ",", "param_name", ")", "if", "isinstance", "(", "param_obj", ",", "parameter", ".", "DateParameter", ")", ":", "previous_date_params", "[", "param_name", "]", "=", "param_value", "-", "datetime", ".", "timedelta", "(", "days", "=", "1", ")", "elif", "isinstance", "(", "param_obj", ",", "parameter", ".", "DateSecondParameter", ")", ":", "previous_date_params", "[", "param_name", "]", "=", "param_value", "-", "datetime", ".", "timedelta", "(", "seconds", "=", "1", ")", "elif", "isinstance", "(", "param_obj", ",", "parameter", ".", "DateMinuteParameter", ")", ":", "previous_date_params", "[", "param_name", "]", "=", "param_value", "-", "datetime", ".", "timedelta", "(", "minutes", "=", "1", ")", "elif", "isinstance", "(", "param_obj", ",", "parameter", ".", "DateHourParameter", ")", ":", "previous_date_params", "[", "param_name", "]", "=", "param_value", "-", "datetime", ".", "timedelta", "(", "hours", "=", "1", ")", "elif", "isinstance", "(", "param_obj", ",", "parameter", ".", "DateIntervalParameter", ")", ":", "previous_date_params", "[", "param_name", "]", "=", "param_value", ".", "prev", "(", ")", "else", ":", "previous_params", "[", "param_name", "]", "=", "param_value", "previous_params", ".", "update", "(", "previous_date_params", ")", "if", "len", "(", "previous_date_params", ")", "==", "0", ":", "raise", "NotImplementedError", "(", "\"No task parameter - can't determine previous task\"", ")", "elif", "len", "(", "previous_date_params", ")", ">", "1", ":", "raise", "NotImplementedError", "(", "\"Too many date-related task parameters - can't determine previous task\"", ")", "else", ":", "return", "task", ".", "clone", "(", "*", "*", "previous_params", ")" ]
Return a previous Task of the same family. By default checks if this task family only has one non-global parameter and if it is a DateParameter, DateHourParameter or DateIntervalParameter in which case it returns with the time decremented by 1 (hour, day or interval)
[ "Return", "a", "previous", "Task", "of", "the", "same", "family", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/util.py#L422-L457
train
spotify/luigi
luigi/contrib/hdfs/hadoopcli_clients.py
create_hadoopcli_client
def create_hadoopcli_client(): """ Given that we want one of the hadoop cli clients (unlike snakebite), this one will return the right one. """ version = hdfs_config.get_configured_hadoop_version() if version == "cdh4": return HdfsClient() elif version == "cdh3": return HdfsClientCdh3() elif version == "apache1": return HdfsClientApache1() else: raise ValueError("Error: Unknown version specified in Hadoop version" "configuration parameter")
python
def create_hadoopcli_client(): """ Given that we want one of the hadoop cli clients (unlike snakebite), this one will return the right one. """ version = hdfs_config.get_configured_hadoop_version() if version == "cdh4": return HdfsClient() elif version == "cdh3": return HdfsClientCdh3() elif version == "apache1": return HdfsClientApache1() else: raise ValueError("Error: Unknown version specified in Hadoop version" "configuration parameter")
[ "def", "create_hadoopcli_client", "(", ")", ":", "version", "=", "hdfs_config", ".", "get_configured_hadoop_version", "(", ")", "if", "version", "==", "\"cdh4\"", ":", "return", "HdfsClient", "(", ")", "elif", "version", "==", "\"cdh3\"", ":", "return", "HdfsClientCdh3", "(", ")", "elif", "version", "==", "\"apache1\"", ":", "return", "HdfsClientApache1", "(", ")", "else", ":", "raise", "ValueError", "(", "\"Error: Unknown version specified in Hadoop version\"", "\"configuration parameter\"", ")" ]
Given that we want one of the hadoop cli clients (unlike snakebite), this one will return the right one.
[ "Given", "that", "we", "want", "one", "of", "the", "hadoop", "cli", "clients", "(", "unlike", "snakebite", ")", "this", "one", "will", "return", "the", "right", "one", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hdfs/hadoopcli_clients.py#L39-L53
train
spotify/luigi
luigi/contrib/hdfs/hadoopcli_clients.py
HdfsClient.exists
def exists(self, path): """ Use ``hadoop fs -stat`` to check file existence. """ cmd = load_hadoop_cmd() + ['fs', '-stat', path] logger.debug('Running file existence check: %s', subprocess.list2cmdline(cmd)) p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True, universal_newlines=True) stdout, stderr = p.communicate() if p.returncode == 0: return True else: not_found_pattern = "^.*No such file or directory$" not_found_re = re.compile(not_found_pattern) for line in stderr.split('\n'): if not_found_re.match(line): return False raise hdfs_error.HDFSCliError(cmd, p.returncode, stdout, stderr)
python
def exists(self, path): """ Use ``hadoop fs -stat`` to check file existence. """ cmd = load_hadoop_cmd() + ['fs', '-stat', path] logger.debug('Running file existence check: %s', subprocess.list2cmdline(cmd)) p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True, universal_newlines=True) stdout, stderr = p.communicate() if p.returncode == 0: return True else: not_found_pattern = "^.*No such file or directory$" not_found_re = re.compile(not_found_pattern) for line in stderr.split('\n'): if not_found_re.match(line): return False raise hdfs_error.HDFSCliError(cmd, p.returncode, stdout, stderr)
[ "def", "exists", "(", "self", ",", "path", ")", ":", "cmd", "=", "load_hadoop_cmd", "(", ")", "+", "[", "'fs'", ",", "'-stat'", ",", "path", "]", "logger", ".", "debug", "(", "'Running file existence check: %s'", ",", "subprocess", ".", "list2cmdline", "(", "cmd", ")", ")", "p", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ",", "close_fds", "=", "True", ",", "universal_newlines", "=", "True", ")", "stdout", ",", "stderr", "=", "p", ".", "communicate", "(", ")", "if", "p", ".", "returncode", "==", "0", ":", "return", "True", "else", ":", "not_found_pattern", "=", "\"^.*No such file or directory$\"", "not_found_re", "=", "re", ".", "compile", "(", "not_found_pattern", ")", "for", "line", "in", "stderr", ".", "split", "(", "'\\n'", ")", ":", "if", "not_found_re", ".", "match", "(", "line", ")", ":", "return", "False", "raise", "hdfs_error", ".", "HDFSCliError", "(", "cmd", ",", "p", ".", "returncode", ",", "stdout", ",", "stderr", ")" ]
Use ``hadoop fs -stat`` to check file existence.
[ "Use", "hadoop", "fs", "-", "stat", "to", "check", "file", "existence", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hdfs/hadoopcli_clients.py#L71-L88
train
spotify/luigi
luigi/contrib/hdfs/hadoopcli_clients.py
HdfsClientCdh3.mkdir
def mkdir(self, path, parents=True, raise_if_exists=False): """ No explicit -p switch, this version of Hadoop always creates parent directories. """ try: self.call_check(load_hadoop_cmd() + ['fs', '-mkdir', path]) except hdfs_error.HDFSCliError as ex: if "File exists" in ex.stderr: if raise_if_exists: raise FileAlreadyExists(ex.stderr) else: raise
python
def mkdir(self, path, parents=True, raise_if_exists=False): """ No explicit -p switch, this version of Hadoop always creates parent directories. """ try: self.call_check(load_hadoop_cmd() + ['fs', '-mkdir', path]) except hdfs_error.HDFSCliError as ex: if "File exists" in ex.stderr: if raise_if_exists: raise FileAlreadyExists(ex.stderr) else: raise
[ "def", "mkdir", "(", "self", ",", "path", ",", "parents", "=", "True", ",", "raise_if_exists", "=", "False", ")", ":", "try", ":", "self", ".", "call_check", "(", "load_hadoop_cmd", "(", ")", "+", "[", "'fs'", ",", "'-mkdir'", ",", "path", "]", ")", "except", "hdfs_error", ".", "HDFSCliError", "as", "ex", ":", "if", "\"File exists\"", "in", "ex", ".", "stderr", ":", "if", "raise_if_exists", ":", "raise", "FileAlreadyExists", "(", "ex", ".", "stderr", ")", "else", ":", "raise" ]
No explicit -p switch, this version of Hadoop always creates parent directories.
[ "No", "explicit", "-", "p", "switch", "this", "version", "of", "Hadoop", "always", "creates", "parent", "directories", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hdfs/hadoopcli_clients.py#L225-L236
train
spotify/luigi
luigi/contrib/hive.py
run_hive
def run_hive(args, check_return_code=True): """ Runs the `hive` from the command line, passing in the given args, and returning stdout. With the apache release of Hive, so of the table existence checks (which are done using DESCRIBE do not exit with a return code of 0 so we need an option to ignore the return code and just return stdout for parsing """ cmd = load_hive_cmd() + args p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate() if check_return_code and p.returncode != 0: raise HiveCommandError("Hive command: {0} failed with error code: {1}".format(" ".join(cmd), p.returncode), stdout, stderr) return stdout.decode('utf-8')
python
def run_hive(args, check_return_code=True): """ Runs the `hive` from the command line, passing in the given args, and returning stdout. With the apache release of Hive, so of the table existence checks (which are done using DESCRIBE do not exit with a return code of 0 so we need an option to ignore the return code and just return stdout for parsing """ cmd = load_hive_cmd() + args p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate() if check_return_code and p.returncode != 0: raise HiveCommandError("Hive command: {0} failed with error code: {1}".format(" ".join(cmd), p.returncode), stdout, stderr) return stdout.decode('utf-8')
[ "def", "run_hive", "(", "args", ",", "check_return_code", "=", "True", ")", ":", "cmd", "=", "load_hive_cmd", "(", ")", "+", "args", "p", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "stdout", ",", "stderr", "=", "p", ".", "communicate", "(", ")", "if", "check_return_code", "and", "p", ".", "returncode", "!=", "0", ":", "raise", "HiveCommandError", "(", "\"Hive command: {0} failed with error code: {1}\"", ".", "format", "(", "\" \"", ".", "join", "(", "cmd", ")", ",", "p", ".", "returncode", ")", ",", "stdout", ",", "stderr", ")", "return", "stdout", ".", "decode", "(", "'utf-8'", ")" ]
Runs the `hive` from the command line, passing in the given args, and returning stdout. With the apache release of Hive, so of the table existence checks (which are done using DESCRIBE do not exit with a return code of 0 so we need an option to ignore the return code and just return stdout for parsing
[ "Runs", "the", "hive", "from", "the", "command", "line", "passing", "in", "the", "given", "args", "and", "returning", "stdout", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hive.py#L56-L71
train
spotify/luigi
luigi/contrib/hive.py
run_hive_script
def run_hive_script(script): """ Runs the contents of the given script in hive and returns stdout. """ if not os.path.isfile(script): raise RuntimeError("Hive script: {0} does not exist.".format(script)) return run_hive(['-f', script])
python
def run_hive_script(script): """ Runs the contents of the given script in hive and returns stdout. """ if not os.path.isfile(script): raise RuntimeError("Hive script: {0} does not exist.".format(script)) return run_hive(['-f', script])
[ "def", "run_hive_script", "(", "script", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "script", ")", ":", "raise", "RuntimeError", "(", "\"Hive script: {0} does not exist.\"", ".", "format", "(", "script", ")", ")", "return", "run_hive", "(", "[", "'-f'", ",", "script", "]", ")" ]
Runs the contents of the given script in hive and returns stdout.
[ "Runs", "the", "contents", "of", "the", "given", "script", "in", "hive", "and", "returns", "stdout", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hive.py#L81-L87
train
spotify/luigi
luigi/contrib/hive.py
HiveQueryTask.hiveconfs
def hiveconfs(self): """ Returns a dict of key=value settings to be passed along to the hive command line via --hiveconf. By default, sets mapred.job.name to task_id and if not None, sets: * mapred.reduce.tasks (n_reduce_tasks) * mapred.fairscheduler.pool (pool) or mapred.job.queue.name (pool) * hive.exec.reducers.bytes.per.reducer (bytes_per_reducer) * hive.exec.reducers.max (reducers_max) """ jcs = {} jcs['mapred.job.name'] = "'" + self.task_id + "'" if self.n_reduce_tasks is not None: jcs['mapred.reduce.tasks'] = self.n_reduce_tasks if self.pool is not None: # Supporting two schedulers: fair (default) and capacity using the same option scheduler_type = luigi.configuration.get_config().get('hadoop', 'scheduler', 'fair') if scheduler_type == 'fair': jcs['mapred.fairscheduler.pool'] = self.pool elif scheduler_type == 'capacity': jcs['mapred.job.queue.name'] = self.pool if self.bytes_per_reducer is not None: jcs['hive.exec.reducers.bytes.per.reducer'] = self.bytes_per_reducer if self.reducers_max is not None: jcs['hive.exec.reducers.max'] = self.reducers_max return jcs
python
def hiveconfs(self): """ Returns a dict of key=value settings to be passed along to the hive command line via --hiveconf. By default, sets mapred.job.name to task_id and if not None, sets: * mapred.reduce.tasks (n_reduce_tasks) * mapred.fairscheduler.pool (pool) or mapred.job.queue.name (pool) * hive.exec.reducers.bytes.per.reducer (bytes_per_reducer) * hive.exec.reducers.max (reducers_max) """ jcs = {} jcs['mapred.job.name'] = "'" + self.task_id + "'" if self.n_reduce_tasks is not None: jcs['mapred.reduce.tasks'] = self.n_reduce_tasks if self.pool is not None: # Supporting two schedulers: fair (default) and capacity using the same option scheduler_type = luigi.configuration.get_config().get('hadoop', 'scheduler', 'fair') if scheduler_type == 'fair': jcs['mapred.fairscheduler.pool'] = self.pool elif scheduler_type == 'capacity': jcs['mapred.job.queue.name'] = self.pool if self.bytes_per_reducer is not None: jcs['hive.exec.reducers.bytes.per.reducer'] = self.bytes_per_reducer if self.reducers_max is not None: jcs['hive.exec.reducers.max'] = self.reducers_max return jcs
[ "def", "hiveconfs", "(", "self", ")", ":", "jcs", "=", "{", "}", "jcs", "[", "'mapred.job.name'", "]", "=", "\"'\"", "+", "self", ".", "task_id", "+", "\"'\"", "if", "self", ".", "n_reduce_tasks", "is", "not", "None", ":", "jcs", "[", "'mapred.reduce.tasks'", "]", "=", "self", ".", "n_reduce_tasks", "if", "self", ".", "pool", "is", "not", "None", ":", "# Supporting two schedulers: fair (default) and capacity using the same option", "scheduler_type", "=", "luigi", ".", "configuration", ".", "get_config", "(", ")", ".", "get", "(", "'hadoop'", ",", "'scheduler'", ",", "'fair'", ")", "if", "scheduler_type", "==", "'fair'", ":", "jcs", "[", "'mapred.fairscheduler.pool'", "]", "=", "self", ".", "pool", "elif", "scheduler_type", "==", "'capacity'", ":", "jcs", "[", "'mapred.job.queue.name'", "]", "=", "self", ".", "pool", "if", "self", ".", "bytes_per_reducer", "is", "not", "None", ":", "jcs", "[", "'hive.exec.reducers.bytes.per.reducer'", "]", "=", "self", ".", "bytes_per_reducer", "if", "self", ".", "reducers_max", "is", "not", "None", ":", "jcs", "[", "'hive.exec.reducers.max'", "]", "=", "self", ".", "reducers_max", "return", "jcs" ]
Returns a dict of key=value settings to be passed along to the hive command line via --hiveconf. By default, sets mapred.job.name to task_id and if not None, sets: * mapred.reduce.tasks (n_reduce_tasks) * mapred.fairscheduler.pool (pool) or mapred.job.queue.name (pool) * hive.exec.reducers.bytes.per.reducer (bytes_per_reducer) * hive.exec.reducers.max (reducers_max)
[ "Returns", "a", "dict", "of", "key", "=", "value", "settings", "to", "be", "passed", "along", "to", "the", "hive", "command", "line", "via", "--", "hiveconf", ".", "By", "default", "sets", "mapred", ".", "job", ".", "name", "to", "task_id", "and", "if", "not", "None", "sets", ":" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hive.py#L298-L324
train
spotify/luigi
luigi/contrib/hive.py
HiveQueryRunner.prepare_outputs
def prepare_outputs(self, job): """ Called before job is started. If output is a `FileSystemTarget`, create parent directories so the hive command won't fail """ outputs = flatten(job.output()) for o in outputs: if isinstance(o, FileSystemTarget): parent_dir = os.path.dirname(o.path) if parent_dir and not o.fs.exists(parent_dir): logger.info("Creating parent directory %r", parent_dir) try: # there is a possible race condition # which needs to be handled here o.fs.mkdir(parent_dir) except FileAlreadyExists: pass
python
def prepare_outputs(self, job): """ Called before job is started. If output is a `FileSystemTarget`, create parent directories so the hive command won't fail """ outputs = flatten(job.output()) for o in outputs: if isinstance(o, FileSystemTarget): parent_dir = os.path.dirname(o.path) if parent_dir and not o.fs.exists(parent_dir): logger.info("Creating parent directory %r", parent_dir) try: # there is a possible race condition # which needs to be handled here o.fs.mkdir(parent_dir) except FileAlreadyExists: pass
[ "def", "prepare_outputs", "(", "self", ",", "job", ")", ":", "outputs", "=", "flatten", "(", "job", ".", "output", "(", ")", ")", "for", "o", "in", "outputs", ":", "if", "isinstance", "(", "o", ",", "FileSystemTarget", ")", ":", "parent_dir", "=", "os", ".", "path", ".", "dirname", "(", "o", ".", "path", ")", "if", "parent_dir", "and", "not", "o", ".", "fs", ".", "exists", "(", "parent_dir", ")", ":", "logger", ".", "info", "(", "\"Creating parent directory %r\"", ",", "parent_dir", ")", "try", ":", "# there is a possible race condition", "# which needs to be handled here", "o", ".", "fs", ".", "mkdir", "(", "parent_dir", ")", "except", "FileAlreadyExists", ":", "pass" ]
Called before job is started. If output is a `FileSystemTarget`, create parent directories so the hive command won't fail
[ "Called", "before", "job", "is", "started", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hive.py#L335-L352
train
spotify/luigi
luigi/contrib/hive.py
HiveTableTarget.path
def path(self): """ Returns the path to this table in HDFS. """ location = self.client.table_location(self.table, self.database) if not location: raise Exception("Couldn't find location for table: {0}".format(str(self))) return location
python
def path(self): """ Returns the path to this table in HDFS. """ location = self.client.table_location(self.table, self.database) if not location: raise Exception("Couldn't find location for table: {0}".format(str(self))) return location
[ "def", "path", "(", "self", ")", ":", "location", "=", "self", ".", "client", ".", "table_location", "(", "self", ".", "table", ",", "self", ".", "database", ")", "if", "not", "location", ":", "raise", "Exception", "(", "\"Couldn't find location for table: {0}\"", ".", "format", "(", "str", "(", "self", ")", ")", ")", "return", "location" ]
Returns the path to this table in HDFS.
[ "Returns", "the", "path", "to", "this", "table", "in", "HDFS", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hive.py#L404-L411
train
spotify/luigi
luigi/contrib/redis_store.py
RedisTarget.touch
def touch(self): """ Mark this update as complete. We index the parameters `update_id` and `date`. """ marker_key = self.marker_key() self.redis_client.hset(marker_key, 'update_id', self.update_id) self.redis_client.hset(marker_key, 'date', datetime.datetime.now()) if self.expire is not None: self.redis_client.expire(marker_key, self.expire)
python
def touch(self): """ Mark this update as complete. We index the parameters `update_id` and `date`. """ marker_key = self.marker_key() self.redis_client.hset(marker_key, 'update_id', self.update_id) self.redis_client.hset(marker_key, 'date', datetime.datetime.now()) if self.expire is not None: self.redis_client.expire(marker_key, self.expire)
[ "def", "touch", "(", "self", ")", ":", "marker_key", "=", "self", ".", "marker_key", "(", ")", "self", ".", "redis_client", ".", "hset", "(", "marker_key", ",", "'update_id'", ",", "self", ".", "update_id", ")", "self", ".", "redis_client", ".", "hset", "(", "marker_key", ",", "'date'", ",", "datetime", ".", "datetime", ".", "now", "(", ")", ")", "if", "self", ".", "expire", "is", "not", "None", ":", "self", ".", "redis_client", ".", "expire", "(", "marker_key", ",", "self", ".", "expire", ")" ]
Mark this update as complete. We index the parameters `update_id` and `date`.
[ "Mark", "this", "update", "as", "complete", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/redis_store.py#L82-L93
train
spotify/luigi
luigi/cmdline_parser.py
CmdlineParser.global_instance
def global_instance(cls, cmdline_args, allow_override=False): """ Meant to be used as a context manager. """ orig_value = cls._instance assert (orig_value is None) or allow_override new_value = None try: new_value = CmdlineParser(cmdline_args) cls._instance = new_value yield new_value finally: assert cls._instance is new_value cls._instance = orig_value
python
def global_instance(cls, cmdline_args, allow_override=False): """ Meant to be used as a context manager. """ orig_value = cls._instance assert (orig_value is None) or allow_override new_value = None try: new_value = CmdlineParser(cmdline_args) cls._instance = new_value yield new_value finally: assert cls._instance is new_value cls._instance = orig_value
[ "def", "global_instance", "(", "cls", ",", "cmdline_args", ",", "allow_override", "=", "False", ")", ":", "orig_value", "=", "cls", ".", "_instance", "assert", "(", "orig_value", "is", "None", ")", "or", "allow_override", "new_value", "=", "None", "try", ":", "new_value", "=", "CmdlineParser", "(", "cmdline_args", ")", "cls", ".", "_instance", "=", "new_value", "yield", "new_value", "finally", ":", "assert", "cls", ".", "_instance", "is", "new_value", "cls", ".", "_instance", "=", "orig_value" ]
Meant to be used as a context manager.
[ "Meant", "to", "be", "used", "as", "a", "context", "manager", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/cmdline_parser.py#L44-L57
train
spotify/luigi
luigi/cmdline_parser.py
CmdlineParser._get_task_kwargs
def _get_task_kwargs(self): """ Get the local task arguments as a dictionary. The return value is in the form ``dict(my_param='my_value', ...)`` """ res = {} for (param_name, param_obj) in self._get_task_cls().get_params(): attr = getattr(self.known_args, param_name) if attr: res.update(((param_name, param_obj.parse(attr)),)) return res
python
def _get_task_kwargs(self): """ Get the local task arguments as a dictionary. The return value is in the form ``dict(my_param='my_value', ...)`` """ res = {} for (param_name, param_obj) in self._get_task_cls().get_params(): attr = getattr(self.known_args, param_name) if attr: res.update(((param_name, param_obj.parse(attr)),)) return res
[ "def", "_get_task_kwargs", "(", "self", ")", ":", "res", "=", "{", "}", "for", "(", "param_name", ",", "param_obj", ")", "in", "self", ".", "_get_task_cls", "(", ")", ".", "get_params", "(", ")", ":", "attr", "=", "getattr", "(", "self", ".", "known_args", ",", "param_name", ")", "if", "attr", ":", "res", ".", "update", "(", "(", "(", "param_name", ",", "param_obj", ".", "parse", "(", "attr", ")", ")", ",", ")", ")", "return", "res" ]
Get the local task arguments as a dictionary. The return value is in the form ``dict(my_param='my_value', ...)``
[ "Get", "the", "local", "task", "arguments", "as", "a", "dictionary", ".", "The", "return", "value", "is", "in", "the", "form", "dict", "(", "my_param", "=", "my_value", "...", ")" ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/cmdline_parser.py#L122-L133
train
spotify/luigi
luigi/cmdline_parser.py
CmdlineParser._possibly_exit_with_help
def _possibly_exit_with_help(parser, known_args): """ Check if the user passed --help[-all], if so, print a message and exit. """ if known_args.core_help or known_args.core_help_all: parser.print_help() sys.exit()
python
def _possibly_exit_with_help(parser, known_args): """ Check if the user passed --help[-all], if so, print a message and exit. """ if known_args.core_help or known_args.core_help_all: parser.print_help() sys.exit()
[ "def", "_possibly_exit_with_help", "(", "parser", ",", "known_args", ")", ":", "if", "known_args", ".", "core_help", "or", "known_args", ".", "core_help_all", ":", "parser", ".", "print_help", "(", ")", "sys", ".", "exit", "(", ")" ]
Check if the user passed --help[-all], if so, print a message and exit.
[ "Check", "if", "the", "user", "passed", "--", "help", "[", "-", "all", "]", "if", "so", "print", "a", "message", "and", "exit", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/cmdline_parser.py#L145-L151
train
spotify/luigi
luigi/contrib/scalding.py
ScaldingJobTask.relpath
def relpath(self, current_file, rel_path): """ Compute path given current file and relative path. """ script_dir = os.path.dirname(os.path.abspath(current_file)) rel_path = os.path.abspath(os.path.join(script_dir, rel_path)) return rel_path
python
def relpath(self, current_file, rel_path): """ Compute path given current file and relative path. """ script_dir = os.path.dirname(os.path.abspath(current_file)) rel_path = os.path.abspath(os.path.join(script_dir, rel_path)) return rel_path
[ "def", "relpath", "(", "self", ",", "current_file", ",", "rel_path", ")", ":", "script_dir", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "current_file", ")", ")", "rel_path", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "script_dir", ",", "rel_path", ")", ")", "return", "rel_path" ]
Compute path given current file and relative path.
[ "Compute", "path", "given", "current", "file", "and", "relative", "path", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/scalding.py#L245-L251
train
spotify/luigi
luigi/contrib/scalding.py
ScaldingJobTask.args
def args(self): """ Returns an array of args to pass to the job. """ arglist = [] for k, v in six.iteritems(self.requires_hadoop()): arglist.append('--' + k) arglist.extend([t.output().path for t in flatten(v)]) arglist.extend(['--output', self.output()]) arglist.extend(self.job_args()) return arglist
python
def args(self): """ Returns an array of args to pass to the job. """ arglist = [] for k, v in six.iteritems(self.requires_hadoop()): arglist.append('--' + k) arglist.extend([t.output().path for t in flatten(v)]) arglist.extend(['--output', self.output()]) arglist.extend(self.job_args()) return arglist
[ "def", "args", "(", "self", ")", ":", "arglist", "=", "[", "]", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "self", ".", "requires_hadoop", "(", ")", ")", ":", "arglist", ".", "append", "(", "'--'", "+", "k", ")", "arglist", ".", "extend", "(", "[", "t", ".", "output", "(", ")", ".", "path", "for", "t", "in", "flatten", "(", "v", ")", "]", ")", "arglist", ".", "extend", "(", "[", "'--output'", ",", "self", ".", "output", "(", ")", "]", ")", "arglist", ".", "extend", "(", "self", ".", "job_args", "(", ")", ")", "return", "arglist" ]
Returns an array of args to pass to the job.
[ "Returns", "an", "array", "of", "args", "to", "pass", "to", "the", "job", "." ]
c5eca1c3c3ee2a7eb612486192a0da146710a1e9
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/scalding.py#L300-L310
train
tensorflow/tensorboard
tensorboard/summary/writer/event_file_writer.py
EventFileWriter.add_event
def add_event(self, event): """Adds an event to the event file. Args: event: An `Event` protocol buffer. """ if not isinstance(event, event_pb2.Event): raise TypeError("Expected an event_pb2.Event proto, " " but got %s" % type(event)) self._async_writer.write(event.SerializeToString())
python
def add_event(self, event): """Adds an event to the event file. Args: event: An `Event` protocol buffer. """ if not isinstance(event, event_pb2.Event): raise TypeError("Expected an event_pb2.Event proto, " " but got %s" % type(event)) self._async_writer.write(event.SerializeToString())
[ "def", "add_event", "(", "self", ",", "event", ")", ":", "if", "not", "isinstance", "(", "event", ",", "event_pb2", ".", "Event", ")", ":", "raise", "TypeError", "(", "\"Expected an event_pb2.Event proto, \"", "\" but got %s\"", "%", "type", "(", "event", ")", ")", "self", ".", "_async_writer", ".", "write", "(", "event", ".", "SerializeToString", "(", ")", ")" ]
Adds an event to the event file. Args: event: An `Event` protocol buffer.
[ "Adds", "an", "event", "to", "the", "event", "file", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/summary/writer/event_file_writer.py#L88-L97
train
tensorflow/tensorboard
tensorboard/summary/writer/event_file_writer.py
_AsyncWriter.write
def write(self, bytestring): '''Enqueue the given bytes to be written asychronously''' with self._lock: if self._closed: raise IOError('Writer is closed') self._byte_queue.put(bytestring)
python
def write(self, bytestring): '''Enqueue the given bytes to be written asychronously''' with self._lock: if self._closed: raise IOError('Writer is closed') self._byte_queue.put(bytestring)
[ "def", "write", "(", "self", ",", "bytestring", ")", ":", "with", "self", ".", "_lock", ":", "if", "self", ".", "_closed", ":", "raise", "IOError", "(", "'Writer is closed'", ")", "self", ".", "_byte_queue", ".", "put", "(", "bytestring", ")" ]
Enqueue the given bytes to be written asychronously
[ "Enqueue", "the", "given", "bytes", "to", "be", "written", "asychronously" ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/summary/writer/event_file_writer.py#L140-L145
train
tensorflow/tensorboard
tensorboard/summary/writer/event_file_writer.py
_AsyncWriter.flush
def flush(self): '''Write all the enqueued bytestring before this flush call to disk. Block until all the above bytestring are written. ''' with self._lock: if self._closed: raise IOError('Writer is closed') self._byte_queue.join() self._writer.flush()
python
def flush(self): '''Write all the enqueued bytestring before this flush call to disk. Block until all the above bytestring are written. ''' with self._lock: if self._closed: raise IOError('Writer is closed') self._byte_queue.join() self._writer.flush()
[ "def", "flush", "(", "self", ")", ":", "with", "self", ".", "_lock", ":", "if", "self", ".", "_closed", ":", "raise", "IOError", "(", "'Writer is closed'", ")", "self", ".", "_byte_queue", ".", "join", "(", ")", "self", ".", "_writer", ".", "flush", "(", ")" ]
Write all the enqueued bytestring before this flush call to disk. Block until all the above bytestring are written.
[ "Write", "all", "the", "enqueued", "bytestring", "before", "this", "flush", "call", "to", "disk", ".", "Block", "until", "all", "the", "above", "bytestring", "are", "written", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/summary/writer/event_file_writer.py#L147-L155
train
tensorflow/tensorboard
tensorboard/summary/writer/event_file_writer.py
_AsyncWriter.close
def close(self): '''Closes the underlying writer, flushing any pending writes first.''' if not self._closed: with self._lock: if not self._closed: self._closed = True self._worker.stop() self._writer.flush() self._writer.close()
python
def close(self): '''Closes the underlying writer, flushing any pending writes first.''' if not self._closed: with self._lock: if not self._closed: self._closed = True self._worker.stop() self._writer.flush() self._writer.close()
[ "def", "close", "(", "self", ")", ":", "if", "not", "self", ".", "_closed", ":", "with", "self", ".", "_lock", ":", "if", "not", "self", ".", "_closed", ":", "self", ".", "_closed", "=", "True", "self", ".", "_worker", ".", "stop", "(", ")", "self", ".", "_writer", ".", "flush", "(", ")", "self", ".", "_writer", ".", "close", "(", ")" ]
Closes the underlying writer, flushing any pending writes first.
[ "Closes", "the", "underlying", "writer", "flushing", "any", "pending", "writes", "first", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/summary/writer/event_file_writer.py#L157-L165
train
tensorflow/tensorboard
tensorboard/plugins/debugger/interactive_debugger_server_lib.py
_extract_device_name_from_event
def _extract_device_name_from_event(event): """Extract device name from a tf.Event proto carrying tensor value.""" plugin_data_content = json.loads( tf.compat.as_str(event.summary.value[0].metadata.plugin_data.content)) return plugin_data_content['device']
python
def _extract_device_name_from_event(event): """Extract device name from a tf.Event proto carrying tensor value.""" plugin_data_content = json.loads( tf.compat.as_str(event.summary.value[0].metadata.plugin_data.content)) return plugin_data_content['device']
[ "def", "_extract_device_name_from_event", "(", "event", ")", ":", "plugin_data_content", "=", "json", ".", "loads", "(", "tf", ".", "compat", ".", "as_str", "(", "event", ".", "summary", ".", "value", "[", "0", "]", ".", "metadata", ".", "plugin_data", ".", "content", ")", ")", "return", "plugin_data_content", "[", "'device'", "]" ]
Extract device name from a tf.Event proto carrying tensor value.
[ "Extract", "device", "name", "from", "a", "tf", ".", "Event", "proto", "carrying", "tensor", "value", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/debugger/interactive_debugger_server_lib.py#L48-L52
train
tensorflow/tensorboard
tensorboard/plugins/debugger/interactive_debugger_server_lib.py
_comm_tensor_data
def _comm_tensor_data(device_name, node_name, maybe_base_expanded_node_name, output_slot, debug_op, tensor_value, wall_time): """Create a dict() as the outgoing data in the tensor data comm route. Note: The tensor data in the comm route does not include the value of the tensor in its entirety in general. Only if a tensor satisfies the following conditions will its entire value be included in the return value of this method: 1. Has a numeric data type (e.g., float32, int32) and has fewer than 5 elements. 2. Is a string tensor and has fewer than 5 elements. Each string element is up to 40 bytes. Args: device_name: Name of the device that the tensor is on. node_name: (Original) name of the node that produces the tensor. maybe_base_expanded_node_name: Possbily base-expanded node name. output_slot: Output slot number. debug_op: Name of the debug op. tensor_value: Value of the tensor, as a numpy.ndarray. wall_time: Wall timestamp for the tensor. Returns: A dict representing the tensor data. """ output_slot = int(output_slot) logger.info( 'Recording tensor value: %s, %d, %s', node_name, output_slot, debug_op) tensor_values = None if isinstance(tensor_value, debug_data.InconvertibleTensorProto): if not tensor_value.initialized: tensor_dtype = UNINITIALIZED_TAG tensor_shape = UNINITIALIZED_TAG else: tensor_dtype = UNSUPPORTED_TAG tensor_shape = UNSUPPORTED_TAG tensor_values = NA_TAG else: tensor_dtype = tensor_helper.translate_dtype(tensor_value.dtype) tensor_shape = tensor_value.shape # The /comm endpoint should respond with tensor values only if the tensor is # small enough. Otherwise, the detailed values sould be queried through a # dedicated tensor_data that supports slicing. if tensor_helper.numel(tensor_shape) < 5: _, _, tensor_values = tensor_helper.array_view(tensor_value) if tensor_dtype == 'string' and tensor_value is not None: tensor_values = tensor_helper.process_buffers_for_display( tensor_values, limit=STRING_ELEMENT_MAX_LEN) return { 'type': 'tensor', 'timestamp': wall_time, 'data': { 'device_name': device_name, 'node_name': node_name, 'maybe_base_expanded_node_name': maybe_base_expanded_node_name, 'output_slot': output_slot, 'debug_op': debug_op, 'dtype': tensor_dtype, 'shape': tensor_shape, 'values': tensor_values, }, }
python
def _comm_tensor_data(device_name, node_name, maybe_base_expanded_node_name, output_slot, debug_op, tensor_value, wall_time): """Create a dict() as the outgoing data in the tensor data comm route. Note: The tensor data in the comm route does not include the value of the tensor in its entirety in general. Only if a tensor satisfies the following conditions will its entire value be included in the return value of this method: 1. Has a numeric data type (e.g., float32, int32) and has fewer than 5 elements. 2. Is a string tensor and has fewer than 5 elements. Each string element is up to 40 bytes. Args: device_name: Name of the device that the tensor is on. node_name: (Original) name of the node that produces the tensor. maybe_base_expanded_node_name: Possbily base-expanded node name. output_slot: Output slot number. debug_op: Name of the debug op. tensor_value: Value of the tensor, as a numpy.ndarray. wall_time: Wall timestamp for the tensor. Returns: A dict representing the tensor data. """ output_slot = int(output_slot) logger.info( 'Recording tensor value: %s, %d, %s', node_name, output_slot, debug_op) tensor_values = None if isinstance(tensor_value, debug_data.InconvertibleTensorProto): if not tensor_value.initialized: tensor_dtype = UNINITIALIZED_TAG tensor_shape = UNINITIALIZED_TAG else: tensor_dtype = UNSUPPORTED_TAG tensor_shape = UNSUPPORTED_TAG tensor_values = NA_TAG else: tensor_dtype = tensor_helper.translate_dtype(tensor_value.dtype) tensor_shape = tensor_value.shape # The /comm endpoint should respond with tensor values only if the tensor is # small enough. Otherwise, the detailed values sould be queried through a # dedicated tensor_data that supports slicing. if tensor_helper.numel(tensor_shape) < 5: _, _, tensor_values = tensor_helper.array_view(tensor_value) if tensor_dtype == 'string' and tensor_value is not None: tensor_values = tensor_helper.process_buffers_for_display( tensor_values, limit=STRING_ELEMENT_MAX_LEN) return { 'type': 'tensor', 'timestamp': wall_time, 'data': { 'device_name': device_name, 'node_name': node_name, 'maybe_base_expanded_node_name': maybe_base_expanded_node_name, 'output_slot': output_slot, 'debug_op': debug_op, 'dtype': tensor_dtype, 'shape': tensor_shape, 'values': tensor_values, }, }
[ "def", "_comm_tensor_data", "(", "device_name", ",", "node_name", ",", "maybe_base_expanded_node_name", ",", "output_slot", ",", "debug_op", ",", "tensor_value", ",", "wall_time", ")", ":", "output_slot", "=", "int", "(", "output_slot", ")", "logger", ".", "info", "(", "'Recording tensor value: %s, %d, %s'", ",", "node_name", ",", "output_slot", ",", "debug_op", ")", "tensor_values", "=", "None", "if", "isinstance", "(", "tensor_value", ",", "debug_data", ".", "InconvertibleTensorProto", ")", ":", "if", "not", "tensor_value", ".", "initialized", ":", "tensor_dtype", "=", "UNINITIALIZED_TAG", "tensor_shape", "=", "UNINITIALIZED_TAG", "else", ":", "tensor_dtype", "=", "UNSUPPORTED_TAG", "tensor_shape", "=", "UNSUPPORTED_TAG", "tensor_values", "=", "NA_TAG", "else", ":", "tensor_dtype", "=", "tensor_helper", ".", "translate_dtype", "(", "tensor_value", ".", "dtype", ")", "tensor_shape", "=", "tensor_value", ".", "shape", "# The /comm endpoint should respond with tensor values only if the tensor is", "# small enough. Otherwise, the detailed values sould be queried through a", "# dedicated tensor_data that supports slicing.", "if", "tensor_helper", ".", "numel", "(", "tensor_shape", ")", "<", "5", ":", "_", ",", "_", ",", "tensor_values", "=", "tensor_helper", ".", "array_view", "(", "tensor_value", ")", "if", "tensor_dtype", "==", "'string'", "and", "tensor_value", "is", "not", "None", ":", "tensor_values", "=", "tensor_helper", ".", "process_buffers_for_display", "(", "tensor_values", ",", "limit", "=", "STRING_ELEMENT_MAX_LEN", ")", "return", "{", "'type'", ":", "'tensor'", ",", "'timestamp'", ":", "wall_time", ",", "'data'", ":", "{", "'device_name'", ":", "device_name", ",", "'node_name'", ":", "node_name", ",", "'maybe_base_expanded_node_name'", ":", "maybe_base_expanded_node_name", ",", "'output_slot'", ":", "output_slot", ",", "'debug_op'", ":", "debug_op", ",", "'dtype'", ":", "tensor_dtype", ",", "'shape'", ":", "tensor_shape", ",", "'values'", ":", "tensor_values", ",", "}", ",", "}" ]
Create a dict() as the outgoing data in the tensor data comm route. Note: The tensor data in the comm route does not include the value of the tensor in its entirety in general. Only if a tensor satisfies the following conditions will its entire value be included in the return value of this method: 1. Has a numeric data type (e.g., float32, int32) and has fewer than 5 elements. 2. Is a string tensor and has fewer than 5 elements. Each string element is up to 40 bytes. Args: device_name: Name of the device that the tensor is on. node_name: (Original) name of the node that produces the tensor. maybe_base_expanded_node_name: Possbily base-expanded node name. output_slot: Output slot number. debug_op: Name of the debug op. tensor_value: Value of the tensor, as a numpy.ndarray. wall_time: Wall timestamp for the tensor. Returns: A dict representing the tensor data.
[ "Create", "a", "dict", "()", "as", "the", "outgoing", "data", "in", "the", "tensor", "data", "comm", "route", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/debugger/interactive_debugger_server_lib.py#L72-L140
train
tensorflow/tensorboard
tensorboard/plugins/debugger/interactive_debugger_server_lib.py
RunStates.add_graph
def add_graph(self, run_key, device_name, graph_def, debug=False): """Add a GraphDef. Args: run_key: A key for the run, containing information about the feeds, fetches, and targets. device_name: The name of the device that the `GraphDef` is for. graph_def: An instance of the `GraphDef` proto. debug: Whether `graph_def` consists of the debug ops. """ graph_dict = (self._run_key_to_debug_graphs if debug else self._run_key_to_original_graphs) if not run_key in graph_dict: graph_dict[run_key] = dict() # Mapping device_name to GraphDef. graph_dict[run_key][tf.compat.as_str(device_name)] = ( debug_graphs_helper.DebugGraphWrapper(graph_def))
python
def add_graph(self, run_key, device_name, graph_def, debug=False): """Add a GraphDef. Args: run_key: A key for the run, containing information about the feeds, fetches, and targets. device_name: The name of the device that the `GraphDef` is for. graph_def: An instance of the `GraphDef` proto. debug: Whether `graph_def` consists of the debug ops. """ graph_dict = (self._run_key_to_debug_graphs if debug else self._run_key_to_original_graphs) if not run_key in graph_dict: graph_dict[run_key] = dict() # Mapping device_name to GraphDef. graph_dict[run_key][tf.compat.as_str(device_name)] = ( debug_graphs_helper.DebugGraphWrapper(graph_def))
[ "def", "add_graph", "(", "self", ",", "run_key", ",", "device_name", ",", "graph_def", ",", "debug", "=", "False", ")", ":", "graph_dict", "=", "(", "self", ".", "_run_key_to_debug_graphs", "if", "debug", "else", "self", ".", "_run_key_to_original_graphs", ")", "if", "not", "run_key", "in", "graph_dict", ":", "graph_dict", "[", "run_key", "]", "=", "dict", "(", ")", "# Mapping device_name to GraphDef.", "graph_dict", "[", "run_key", "]", "[", "tf", ".", "compat", ".", "as_str", "(", "device_name", ")", "]", "=", "(", "debug_graphs_helper", ".", "DebugGraphWrapper", "(", "graph_def", ")", ")" ]
Add a GraphDef. Args: run_key: A key for the run, containing information about the feeds, fetches, and targets. device_name: The name of the device that the `GraphDef` is for. graph_def: An instance of the `GraphDef` proto. debug: Whether `graph_def` consists of the debug ops.
[ "Add", "a", "GraphDef", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/debugger/interactive_debugger_server_lib.py#L162-L177
train
tensorflow/tensorboard
tensorboard/plugins/debugger/interactive_debugger_server_lib.py
RunStates.get_graphs
def get_graphs(self, run_key, debug=False): """Get the runtime GraphDef protos associated with a run key. Args: run_key: A Session.run kay. debug: Whether the debugger-decoratedgraph is to be retrieved. Returns: A `dict` mapping device name to `GraphDef` protos. """ graph_dict = (self._run_key_to_debug_graphs if debug else self._run_key_to_original_graphs) graph_wrappers = graph_dict.get(run_key, {}) graph_defs = dict() for device_name, wrapper in graph_wrappers.items(): graph_defs[device_name] = wrapper.graph_def return graph_defs
python
def get_graphs(self, run_key, debug=False): """Get the runtime GraphDef protos associated with a run key. Args: run_key: A Session.run kay. debug: Whether the debugger-decoratedgraph is to be retrieved. Returns: A `dict` mapping device name to `GraphDef` protos. """ graph_dict = (self._run_key_to_debug_graphs if debug else self._run_key_to_original_graphs) graph_wrappers = graph_dict.get(run_key, {}) graph_defs = dict() for device_name, wrapper in graph_wrappers.items(): graph_defs[device_name] = wrapper.graph_def return graph_defs
[ "def", "get_graphs", "(", "self", ",", "run_key", ",", "debug", "=", "False", ")", ":", "graph_dict", "=", "(", "self", ".", "_run_key_to_debug_graphs", "if", "debug", "else", "self", ".", "_run_key_to_original_graphs", ")", "graph_wrappers", "=", "graph_dict", ".", "get", "(", "run_key", ",", "{", "}", ")", "graph_defs", "=", "dict", "(", ")", "for", "device_name", ",", "wrapper", "in", "graph_wrappers", ".", "items", "(", ")", ":", "graph_defs", "[", "device_name", "]", "=", "wrapper", ".", "graph_def", "return", "graph_defs" ]
Get the runtime GraphDef protos associated with a run key. Args: run_key: A Session.run kay. debug: Whether the debugger-decoratedgraph is to be retrieved. Returns: A `dict` mapping device name to `GraphDef` protos.
[ "Get", "the", "runtime", "GraphDef", "protos", "associated", "with", "a", "run", "key", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/debugger/interactive_debugger_server_lib.py#L179-L195
train
tensorflow/tensorboard
tensorboard/plugins/debugger/interactive_debugger_server_lib.py
RunStates.get_graph
def get_graph(self, run_key, device_name, debug=False): """Get the runtime GraphDef proto associated with a run key and a device. Args: run_key: A Session.run kay. device_name: Name of the device in question. debug: Whether the debugger-decoratedgraph is to be retrieved. Returns: A `GraphDef` proto. """ return self.get_graphs(run_key, debug=debug).get(device_name, None)
python
def get_graph(self, run_key, device_name, debug=False): """Get the runtime GraphDef proto associated with a run key and a device. Args: run_key: A Session.run kay. device_name: Name of the device in question. debug: Whether the debugger-decoratedgraph is to be retrieved. Returns: A `GraphDef` proto. """ return self.get_graphs(run_key, debug=debug).get(device_name, None)
[ "def", "get_graph", "(", "self", ",", "run_key", ",", "device_name", ",", "debug", "=", "False", ")", ":", "return", "self", ".", "get_graphs", "(", "run_key", ",", "debug", "=", "debug", ")", ".", "get", "(", "device_name", ",", "None", ")" ]
Get the runtime GraphDef proto associated with a run key and a device. Args: run_key: A Session.run kay. device_name: Name of the device in question. debug: Whether the debugger-decoratedgraph is to be retrieved. Returns: A `GraphDef` proto.
[ "Get", "the", "runtime", "GraphDef", "proto", "associated", "with", "a", "run", "key", "and", "a", "device", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/debugger/interactive_debugger_server_lib.py#L197-L208
train
tensorflow/tensorboard
tensorboard/plugins/debugger/interactive_debugger_server_lib.py
RunStates.get_maybe_base_expanded_node_name
def get_maybe_base_expanded_node_name(self, node_name, run_key, device_name): """Obtain possibly base-expanded node name. Base-expansion is the transformation of a node name which happens to be the name scope of other nodes in the same graph. For example, if two nodes, called 'a/b' and 'a/b/read' in a graph, the name of the first node will be base-expanded to 'a/b/(b)'. This method uses caching to avoid unnecessary recomputation. Args: node_name: Name of the node. run_key: The run key to which the node belongs. graph_def: GraphDef to which the node belongs. Raises: ValueError: If `run_key` and/or `device_name` do not exist in the record. """ device_name = tf.compat.as_str(device_name) if run_key not in self._run_key_to_original_graphs: raise ValueError('Unknown run_key: %s' % run_key) if device_name not in self._run_key_to_original_graphs[run_key]: raise ValueError( 'Unknown device for run key "%s": %s' % (run_key, device_name)) return self._run_key_to_original_graphs[ run_key][device_name].maybe_base_expanded_node_name(node_name)
python
def get_maybe_base_expanded_node_name(self, node_name, run_key, device_name): """Obtain possibly base-expanded node name. Base-expansion is the transformation of a node name which happens to be the name scope of other nodes in the same graph. For example, if two nodes, called 'a/b' and 'a/b/read' in a graph, the name of the first node will be base-expanded to 'a/b/(b)'. This method uses caching to avoid unnecessary recomputation. Args: node_name: Name of the node. run_key: The run key to which the node belongs. graph_def: GraphDef to which the node belongs. Raises: ValueError: If `run_key` and/or `device_name` do not exist in the record. """ device_name = tf.compat.as_str(device_name) if run_key not in self._run_key_to_original_graphs: raise ValueError('Unknown run_key: %s' % run_key) if device_name not in self._run_key_to_original_graphs[run_key]: raise ValueError( 'Unknown device for run key "%s": %s' % (run_key, device_name)) return self._run_key_to_original_graphs[ run_key][device_name].maybe_base_expanded_node_name(node_name)
[ "def", "get_maybe_base_expanded_node_name", "(", "self", ",", "node_name", ",", "run_key", ",", "device_name", ")", ":", "device_name", "=", "tf", ".", "compat", ".", "as_str", "(", "device_name", ")", "if", "run_key", "not", "in", "self", ".", "_run_key_to_original_graphs", ":", "raise", "ValueError", "(", "'Unknown run_key: %s'", "%", "run_key", ")", "if", "device_name", "not", "in", "self", ".", "_run_key_to_original_graphs", "[", "run_key", "]", ":", "raise", "ValueError", "(", "'Unknown device for run key \"%s\": %s'", "%", "(", "run_key", ",", "device_name", ")", ")", "return", "self", ".", "_run_key_to_original_graphs", "[", "run_key", "]", "[", "device_name", "]", ".", "maybe_base_expanded_node_name", "(", "node_name", ")" ]
Obtain possibly base-expanded node name. Base-expansion is the transformation of a node name which happens to be the name scope of other nodes in the same graph. For example, if two nodes, called 'a/b' and 'a/b/read' in a graph, the name of the first node will be base-expanded to 'a/b/(b)'. This method uses caching to avoid unnecessary recomputation. Args: node_name: Name of the node. run_key: The run key to which the node belongs. graph_def: GraphDef to which the node belongs. Raises: ValueError: If `run_key` and/or `device_name` do not exist in the record.
[ "Obtain", "possibly", "base", "-", "expanded", "node", "name", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/debugger/interactive_debugger_server_lib.py#L218-L243
train
tensorflow/tensorboard
tensorboard/plugins/debugger/interactive_debugger_server_lib.py
InteractiveDebuggerDataStreamHandler.on_core_metadata_event
def on_core_metadata_event(self, event): """Implementation of the core metadata-carrying Event proto callback. Args: event: An Event proto that contains core metadata about the debugged Session::Run() in its log_message.message field, as a JSON string. See the doc string of debug_data.DebugDumpDir.core_metadata for details. """ core_metadata = json.loads(event.log_message.message) input_names = ','.join(core_metadata['input_names']) output_names = ','.join(core_metadata['output_names']) target_nodes = ','.join(core_metadata['target_nodes']) self._run_key = RunKey(input_names, output_names, target_nodes) if not self._graph_defs: self._graph_defs_arrive_first = False else: for device_name in self._graph_defs: self._add_graph_def(device_name, self._graph_defs[device_name]) self._outgoing_channel.put(_comm_metadata(self._run_key, event.wall_time)) # Wait for acknowledgement from client. Blocks until an item is got. logger.info('on_core_metadata_event() waiting for client ack (meta)...') self._incoming_channel.get() logger.info('on_core_metadata_event() client ack received (meta).')
python
def on_core_metadata_event(self, event): """Implementation of the core metadata-carrying Event proto callback. Args: event: An Event proto that contains core metadata about the debugged Session::Run() in its log_message.message field, as a JSON string. See the doc string of debug_data.DebugDumpDir.core_metadata for details. """ core_metadata = json.loads(event.log_message.message) input_names = ','.join(core_metadata['input_names']) output_names = ','.join(core_metadata['output_names']) target_nodes = ','.join(core_metadata['target_nodes']) self._run_key = RunKey(input_names, output_names, target_nodes) if not self._graph_defs: self._graph_defs_arrive_first = False else: for device_name in self._graph_defs: self._add_graph_def(device_name, self._graph_defs[device_name]) self._outgoing_channel.put(_comm_metadata(self._run_key, event.wall_time)) # Wait for acknowledgement from client. Blocks until an item is got. logger.info('on_core_metadata_event() waiting for client ack (meta)...') self._incoming_channel.get() logger.info('on_core_metadata_event() client ack received (meta).')
[ "def", "on_core_metadata_event", "(", "self", ",", "event", ")", ":", "core_metadata", "=", "json", ".", "loads", "(", "event", ".", "log_message", ".", "message", ")", "input_names", "=", "','", ".", "join", "(", "core_metadata", "[", "'input_names'", "]", ")", "output_names", "=", "','", ".", "join", "(", "core_metadata", "[", "'output_names'", "]", ")", "target_nodes", "=", "','", ".", "join", "(", "core_metadata", "[", "'target_nodes'", "]", ")", "self", ".", "_run_key", "=", "RunKey", "(", "input_names", ",", "output_names", ",", "target_nodes", ")", "if", "not", "self", ".", "_graph_defs", ":", "self", ".", "_graph_defs_arrive_first", "=", "False", "else", ":", "for", "device_name", "in", "self", ".", "_graph_defs", ":", "self", ".", "_add_graph_def", "(", "device_name", ",", "self", ".", "_graph_defs", "[", "device_name", "]", ")", "self", ".", "_outgoing_channel", ".", "put", "(", "_comm_metadata", "(", "self", ".", "_run_key", ",", "event", ".", "wall_time", ")", ")", "# Wait for acknowledgement from client. Blocks until an item is got.", "logger", ".", "info", "(", "'on_core_metadata_event() waiting for client ack (meta)...'", ")", "self", ".", "_incoming_channel", ".", "get", "(", ")", "logger", ".", "info", "(", "'on_core_metadata_event() client ack received (meta).'", ")" ]
Implementation of the core metadata-carrying Event proto callback. Args: event: An Event proto that contains core metadata about the debugged Session::Run() in its log_message.message field, as a JSON string. See the doc string of debug_data.DebugDumpDir.core_metadata for details.
[ "Implementation", "of", "the", "core", "metadata", "-", "carrying", "Event", "proto", "callback", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/debugger/interactive_debugger_server_lib.py#L286-L311
train
tensorflow/tensorboard
tensorboard/plugins/debugger/interactive_debugger_server_lib.py
InteractiveDebuggerDataStreamHandler.on_graph_def
def on_graph_def(self, graph_def, device_name, wall_time): """Implementation of the GraphDef-carrying Event proto callback. Args: graph_def: A GraphDef proto. N.B.: The GraphDef is from the core runtime of a debugged Session::Run() call, after graph partition. Therefore it may differ from the GraphDef available to the general TensorBoard. For example, the GraphDef in general TensorBoard may get partitioned for multiple devices (CPUs and GPUs), each of which will generate a GraphDef event proto sent to this method. device_name: Name of the device on which the graph was created. wall_time: An epoch timestamp (in microseconds) for the graph. """ # For now, we do nothing with the graph def. However, we must define this # method to satisfy the handler's interface. Furthermore, we may use the # graph in the future (for instance to provide a graph if there is no graph # provided otherwise). del wall_time self._graph_defs[device_name] = graph_def if not self._graph_defs_arrive_first: self._add_graph_def(device_name, graph_def) self._incoming_channel.get()
python
def on_graph_def(self, graph_def, device_name, wall_time): """Implementation of the GraphDef-carrying Event proto callback. Args: graph_def: A GraphDef proto. N.B.: The GraphDef is from the core runtime of a debugged Session::Run() call, after graph partition. Therefore it may differ from the GraphDef available to the general TensorBoard. For example, the GraphDef in general TensorBoard may get partitioned for multiple devices (CPUs and GPUs), each of which will generate a GraphDef event proto sent to this method. device_name: Name of the device on which the graph was created. wall_time: An epoch timestamp (in microseconds) for the graph. """ # For now, we do nothing with the graph def. However, we must define this # method to satisfy the handler's interface. Furthermore, we may use the # graph in the future (for instance to provide a graph if there is no graph # provided otherwise). del wall_time self._graph_defs[device_name] = graph_def if not self._graph_defs_arrive_first: self._add_graph_def(device_name, graph_def) self._incoming_channel.get()
[ "def", "on_graph_def", "(", "self", ",", "graph_def", ",", "device_name", ",", "wall_time", ")", ":", "# For now, we do nothing with the graph def. However, we must define this", "# method to satisfy the handler's interface. Furthermore, we may use the", "# graph in the future (for instance to provide a graph if there is no graph", "# provided otherwise).", "del", "wall_time", "self", ".", "_graph_defs", "[", "device_name", "]", "=", "graph_def", "if", "not", "self", ".", "_graph_defs_arrive_first", ":", "self", ".", "_add_graph_def", "(", "device_name", ",", "graph_def", ")", "self", ".", "_incoming_channel", ".", "get", "(", ")" ]
Implementation of the GraphDef-carrying Event proto callback. Args: graph_def: A GraphDef proto. N.B.: The GraphDef is from the core runtime of a debugged Session::Run() call, after graph partition. Therefore it may differ from the GraphDef available to the general TensorBoard. For example, the GraphDef in general TensorBoard may get partitioned for multiple devices (CPUs and GPUs), each of which will generate a GraphDef event proto sent to this method. device_name: Name of the device on which the graph was created. wall_time: An epoch timestamp (in microseconds) for the graph.
[ "Implementation", "of", "the", "GraphDef", "-", "carrying", "Event", "proto", "callback", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/debugger/interactive_debugger_server_lib.py#L322-L345
train
tensorflow/tensorboard
tensorboard/plugins/debugger/interactive_debugger_server_lib.py
InteractiveDebuggerDataStreamHandler.on_value_event
def on_value_event(self, event): """Records the summary values based on an updated message from the debugger. Logs an error message if writing the event to disk fails. Args: event: The Event proto to be processed. """ if not event.summary.value: logger.info('The summary of the event lacks a value.') return None # The node name property in the event proto is actually a watch key, which # is a concatenation of several pieces of data. watch_key = event.summary.value[0].node_name tensor_value = debug_data.load_tensor_from_event(event) device_name = _extract_device_name_from_event(event) node_name, output_slot, debug_op = ( event.summary.value[0].node_name.split(':')) maybe_base_expanded_node_name = ( self._run_states.get_maybe_base_expanded_node_name(node_name, self._run_key, device_name)) self._tensor_store.add(watch_key, tensor_value) self._outgoing_channel.put(_comm_tensor_data( device_name, node_name, maybe_base_expanded_node_name, output_slot, debug_op, tensor_value, event.wall_time)) logger.info('on_value_event(): waiting for client ack (tensors)...') self._incoming_channel.get() logger.info('on_value_event(): client ack received (tensor).') # Determine if the particular debug watch key is in the current list of # breakpoints. If it is, send an EventReply() to unblock the debug op. if self._is_debug_node_in_breakpoints(event.summary.value[0].node_name): logger.info('Sending empty EventReply for breakpoint: %s', event.summary.value[0].node_name) # TODO(cais): Support receiving and sending tensor value from front-end. return debug_service_pb2.EventReply() return None
python
def on_value_event(self, event): """Records the summary values based on an updated message from the debugger. Logs an error message if writing the event to disk fails. Args: event: The Event proto to be processed. """ if not event.summary.value: logger.info('The summary of the event lacks a value.') return None # The node name property in the event proto is actually a watch key, which # is a concatenation of several pieces of data. watch_key = event.summary.value[0].node_name tensor_value = debug_data.load_tensor_from_event(event) device_name = _extract_device_name_from_event(event) node_name, output_slot, debug_op = ( event.summary.value[0].node_name.split(':')) maybe_base_expanded_node_name = ( self._run_states.get_maybe_base_expanded_node_name(node_name, self._run_key, device_name)) self._tensor_store.add(watch_key, tensor_value) self._outgoing_channel.put(_comm_tensor_data( device_name, node_name, maybe_base_expanded_node_name, output_slot, debug_op, tensor_value, event.wall_time)) logger.info('on_value_event(): waiting for client ack (tensors)...') self._incoming_channel.get() logger.info('on_value_event(): client ack received (tensor).') # Determine if the particular debug watch key is in the current list of # breakpoints. If it is, send an EventReply() to unblock the debug op. if self._is_debug_node_in_breakpoints(event.summary.value[0].node_name): logger.info('Sending empty EventReply for breakpoint: %s', event.summary.value[0].node_name) # TODO(cais): Support receiving and sending tensor value from front-end. return debug_service_pb2.EventReply() return None
[ "def", "on_value_event", "(", "self", ",", "event", ")", ":", "if", "not", "event", ".", "summary", ".", "value", ":", "logger", ".", "info", "(", "'The summary of the event lacks a value.'", ")", "return", "None", "# The node name property in the event proto is actually a watch key, which", "# is a concatenation of several pieces of data.", "watch_key", "=", "event", ".", "summary", ".", "value", "[", "0", "]", ".", "node_name", "tensor_value", "=", "debug_data", ".", "load_tensor_from_event", "(", "event", ")", "device_name", "=", "_extract_device_name_from_event", "(", "event", ")", "node_name", ",", "output_slot", ",", "debug_op", "=", "(", "event", ".", "summary", ".", "value", "[", "0", "]", ".", "node_name", ".", "split", "(", "':'", ")", ")", "maybe_base_expanded_node_name", "=", "(", "self", ".", "_run_states", ".", "get_maybe_base_expanded_node_name", "(", "node_name", ",", "self", ".", "_run_key", ",", "device_name", ")", ")", "self", ".", "_tensor_store", ".", "add", "(", "watch_key", ",", "tensor_value", ")", "self", ".", "_outgoing_channel", ".", "put", "(", "_comm_tensor_data", "(", "device_name", ",", "node_name", ",", "maybe_base_expanded_node_name", ",", "output_slot", ",", "debug_op", ",", "tensor_value", ",", "event", ".", "wall_time", ")", ")", "logger", ".", "info", "(", "'on_value_event(): waiting for client ack (tensors)...'", ")", "self", ".", "_incoming_channel", ".", "get", "(", ")", "logger", ".", "info", "(", "'on_value_event(): client ack received (tensor).'", ")", "# Determine if the particular debug watch key is in the current list of", "# breakpoints. If it is, send an EventReply() to unblock the debug op.", "if", "self", ".", "_is_debug_node_in_breakpoints", "(", "event", ".", "summary", ".", "value", "[", "0", "]", ".", "node_name", ")", ":", "logger", ".", "info", "(", "'Sending empty EventReply for breakpoint: %s'", ",", "event", ".", "summary", ".", "value", "[", "0", "]", ".", "node_name", ")", "# TODO(cais): Support receiving and sending tensor value from front-end.", "return", "debug_service_pb2", ".", "EventReply", "(", ")", "return", "None" ]
Records the summary values based on an updated message from the debugger. Logs an error message if writing the event to disk fails. Args: event: The Event proto to be processed.
[ "Records", "the", "summary", "values", "based", "on", "an", "updated", "message", "from", "the", "debugger", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/debugger/interactive_debugger_server_lib.py#L347-L386
train
tensorflow/tensorboard
tensorboard/plugins/debugger/interactive_debugger_server_lib.py
SourceManager.add_debugged_source_file
def add_debugged_source_file(self, debugged_source_file): """Add a DebuggedSourceFile proto.""" # TODO(cais): Should the key include a host name, for certain distributed # cases? key = debugged_source_file.file_path self._source_file_host[key] = debugged_source_file.host self._source_file_last_modified[key] = debugged_source_file.last_modified self._source_file_bytes[key] = debugged_source_file.bytes self._source_file_content[key] = debugged_source_file.lines
python
def add_debugged_source_file(self, debugged_source_file): """Add a DebuggedSourceFile proto.""" # TODO(cais): Should the key include a host name, for certain distributed # cases? key = debugged_source_file.file_path self._source_file_host[key] = debugged_source_file.host self._source_file_last_modified[key] = debugged_source_file.last_modified self._source_file_bytes[key] = debugged_source_file.bytes self._source_file_content[key] = debugged_source_file.lines
[ "def", "add_debugged_source_file", "(", "self", ",", "debugged_source_file", ")", ":", "# TODO(cais): Should the key include a host name, for certain distributed", "# cases?", "key", "=", "debugged_source_file", ".", "file_path", "self", ".", "_source_file_host", "[", "key", "]", "=", "debugged_source_file", ".", "host", "self", ".", "_source_file_last_modified", "[", "key", "]", "=", "debugged_source_file", ".", "last_modified", "self", ".", "_source_file_bytes", "[", "key", "]", "=", "debugged_source_file", ".", "bytes", "self", ".", "_source_file_content", "[", "key", "]", "=", "debugged_source_file", ".", "lines" ]
Add a DebuggedSourceFile proto.
[ "Add", "a", "DebuggedSourceFile", "proto", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/debugger/interactive_debugger_server_lib.py#L414-L422
train
tensorflow/tensorboard
tensorboard/plugins/debugger/interactive_debugger_server_lib.py
SourceManager.get_op_traceback
def get_op_traceback(self, op_name): """Get the traceback of an op in the latest version of the TF graph. Args: op_name: Name of the op. Returns: Creation traceback of the op, in the form of a list of 2-tuples: (file_path, lineno) Raises: ValueError: If the op with the given name cannot be found in the latest version of the graph that this SourceManager instance has received, or if this SourceManager instance has not received any graph traceback yet. """ if not self._graph_traceback: raise ValueError('No graph traceback has been received yet.') for op_log_entry in self._graph_traceback.log_entries: if op_log_entry.name == op_name: return self._code_def_to_traceback_list(op_log_entry.code_def) raise ValueError( 'No op named "%s" can be found in the graph of the latest version ' ' (%d).' % (op_name, self._graph_version))
python
def get_op_traceback(self, op_name): """Get the traceback of an op in the latest version of the TF graph. Args: op_name: Name of the op. Returns: Creation traceback of the op, in the form of a list of 2-tuples: (file_path, lineno) Raises: ValueError: If the op with the given name cannot be found in the latest version of the graph that this SourceManager instance has received, or if this SourceManager instance has not received any graph traceback yet. """ if not self._graph_traceback: raise ValueError('No graph traceback has been received yet.') for op_log_entry in self._graph_traceback.log_entries: if op_log_entry.name == op_name: return self._code_def_to_traceback_list(op_log_entry.code_def) raise ValueError( 'No op named "%s" can be found in the graph of the latest version ' ' (%d).' % (op_name, self._graph_version))
[ "def", "get_op_traceback", "(", "self", ",", "op_name", ")", ":", "if", "not", "self", ".", "_graph_traceback", ":", "raise", "ValueError", "(", "'No graph traceback has been received yet.'", ")", "for", "op_log_entry", "in", "self", ".", "_graph_traceback", ".", "log_entries", ":", "if", "op_log_entry", ".", "name", "==", "op_name", ":", "return", "self", ".", "_code_def_to_traceback_list", "(", "op_log_entry", ".", "code_def", ")", "raise", "ValueError", "(", "'No op named \"%s\" can be found in the graph of the latest version '", "' (%d).'", "%", "(", "op_name", ",", "self", ".", "_graph_version", ")", ")" ]
Get the traceback of an op in the latest version of the TF graph. Args: op_name: Name of the op. Returns: Creation traceback of the op, in the form of a list of 2-tuples: (file_path, lineno) Raises: ValueError: If the op with the given name cannot be found in the latest version of the graph that this SourceManager instance has received, or if this SourceManager instance has not received any graph traceback yet.
[ "Get", "the", "traceback", "of", "an", "op", "in", "the", "latest", "version", "of", "the", "TF", "graph", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/debugger/interactive_debugger_server_lib.py#L443-L465
train
tensorflow/tensorboard
tensorboard/plugins/debugger/interactive_debugger_server_lib.py
SourceManager.get_file_tracebacks
def get_file_tracebacks(self, file_path): """Get the lists of ops created at lines of a specified source file. Args: file_path: Path to the source file. Returns: A dict mapping line number to a list of 2-tuples, `(op_name, stack_position)` `op_name` is the name of the name of the op whose creation traceback includes the line. `stack_position` is the position of the line in the op's creation traceback, represented as a 0-based integer. Raises: ValueError: If `file_path` does not point to a source file that has been received by this instance of `SourceManager`. """ if file_path not in self._source_file_content: raise ValueError( 'Source file of path "%s" has not been received by this instance of ' 'SourceManager.' % file_path) lineno_to_op_names_and_stack_position = dict() for op_log_entry in self._graph_traceback.log_entries: for stack_pos, trace in enumerate(op_log_entry.code_def.traces): if self._graph_traceback.id_to_string[trace.file_id] == file_path: if trace.lineno not in lineno_to_op_names_and_stack_position: lineno_to_op_names_and_stack_position[trace.lineno] = [] lineno_to_op_names_and_stack_position[trace.lineno].append( (op_log_entry.name, stack_pos)) return lineno_to_op_names_and_stack_position
python
def get_file_tracebacks(self, file_path): """Get the lists of ops created at lines of a specified source file. Args: file_path: Path to the source file. Returns: A dict mapping line number to a list of 2-tuples, `(op_name, stack_position)` `op_name` is the name of the name of the op whose creation traceback includes the line. `stack_position` is the position of the line in the op's creation traceback, represented as a 0-based integer. Raises: ValueError: If `file_path` does not point to a source file that has been received by this instance of `SourceManager`. """ if file_path not in self._source_file_content: raise ValueError( 'Source file of path "%s" has not been received by this instance of ' 'SourceManager.' % file_path) lineno_to_op_names_and_stack_position = dict() for op_log_entry in self._graph_traceback.log_entries: for stack_pos, trace in enumerate(op_log_entry.code_def.traces): if self._graph_traceback.id_to_string[trace.file_id] == file_path: if trace.lineno not in lineno_to_op_names_and_stack_position: lineno_to_op_names_and_stack_position[trace.lineno] = [] lineno_to_op_names_and_stack_position[trace.lineno].append( (op_log_entry.name, stack_pos)) return lineno_to_op_names_and_stack_position
[ "def", "get_file_tracebacks", "(", "self", ",", "file_path", ")", ":", "if", "file_path", "not", "in", "self", ".", "_source_file_content", ":", "raise", "ValueError", "(", "'Source file of path \"%s\" has not been received by this instance of '", "'SourceManager.'", "%", "file_path", ")", "lineno_to_op_names_and_stack_position", "=", "dict", "(", ")", "for", "op_log_entry", "in", "self", ".", "_graph_traceback", ".", "log_entries", ":", "for", "stack_pos", ",", "trace", "in", "enumerate", "(", "op_log_entry", ".", "code_def", ".", "traces", ")", ":", "if", "self", ".", "_graph_traceback", ".", "id_to_string", "[", "trace", ".", "file_id", "]", "==", "file_path", ":", "if", "trace", ".", "lineno", "not", "in", "lineno_to_op_names_and_stack_position", ":", "lineno_to_op_names_and_stack_position", "[", "trace", ".", "lineno", "]", "=", "[", "]", "lineno_to_op_names_and_stack_position", "[", "trace", ".", "lineno", "]", ".", "append", "(", "(", "op_log_entry", ".", "name", ",", "stack_pos", ")", ")", "return", "lineno_to_op_names_and_stack_position" ]
Get the lists of ops created at lines of a specified source file. Args: file_path: Path to the source file. Returns: A dict mapping line number to a list of 2-tuples, `(op_name, stack_position)` `op_name` is the name of the name of the op whose creation traceback includes the line. `stack_position` is the position of the line in the op's creation traceback, represented as a 0-based integer. Raises: ValueError: If `file_path` does not point to a source file that has been received by this instance of `SourceManager`.
[ "Get", "the", "lists", "of", "ops", "created", "at", "lines", "of", "a", "specified", "source", "file", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/debugger/interactive_debugger_server_lib.py#L467-L498
train
tensorflow/tensorboard
tensorboard/plugins/debugger/interactive_debugger_server_lib.py
InteractiveDebuggerDataServer.query_tensor_store
def query_tensor_store(self, watch_key, time_indices=None, slicing=None, mapping=None): """Query tensor store for a given debugged tensor value. Args: watch_key: The watch key of the debugged tensor being sought. Format: <node_name>:<output_slot>:<debug_op> E.g., Dense_1/MatMul:0:DebugIdentity. time_indices: Optional time indices string By default, the lastest time index ('-1') is returned. slicing: Optional slicing string. mapping: Optional mapping string, e.g., 'image/png'. Returns: If mapping is `None`, the possibly sliced values as a nested list of values or its mapped format. A `list` of nested `list` of values, If mapping is not `None`, the format of the return value will depend on the mapping. """ return self._tensor_store.query(watch_key, time_indices=time_indices, slicing=slicing, mapping=mapping)
python
def query_tensor_store(self, watch_key, time_indices=None, slicing=None, mapping=None): """Query tensor store for a given debugged tensor value. Args: watch_key: The watch key of the debugged tensor being sought. Format: <node_name>:<output_slot>:<debug_op> E.g., Dense_1/MatMul:0:DebugIdentity. time_indices: Optional time indices string By default, the lastest time index ('-1') is returned. slicing: Optional slicing string. mapping: Optional mapping string, e.g., 'image/png'. Returns: If mapping is `None`, the possibly sliced values as a nested list of values or its mapped format. A `list` of nested `list` of values, If mapping is not `None`, the format of the return value will depend on the mapping. """ return self._tensor_store.query(watch_key, time_indices=time_indices, slicing=slicing, mapping=mapping)
[ "def", "query_tensor_store", "(", "self", ",", "watch_key", ",", "time_indices", "=", "None", ",", "slicing", "=", "None", ",", "mapping", "=", "None", ")", ":", "return", "self", ".", "_tensor_store", ".", "query", "(", "watch_key", ",", "time_indices", "=", "time_indices", ",", "slicing", "=", "slicing", ",", "mapping", "=", "mapping", ")" ]
Query tensor store for a given debugged tensor value. Args: watch_key: The watch key of the debugged tensor being sought. Format: <node_name>:<output_slot>:<debug_op> E.g., Dense_1/MatMul:0:DebugIdentity. time_indices: Optional time indices string By default, the lastest time index ('-1') is returned. slicing: Optional slicing string. mapping: Optional mapping string, e.g., 'image/png'. Returns: If mapping is `None`, the possibly sliced values as a nested list of values or its mapped format. A `list` of nested `list` of values, If mapping is not `None`, the format of the return value will depend on the mapping.
[ "Query", "tensor", "store", "for", "a", "given", "debugged", "tensor", "value", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/debugger/interactive_debugger_server_lib.py#L564-L589
train
tensorflow/tensorboard
tensorboard/backend/http_util.py
Respond
def Respond(request, content, content_type, code=200, expires=0, content_encoding=None, encoding='utf-8'): """Construct a werkzeug Response. Responses are transmitted to the browser with compression if: a) the browser supports it; b) it's sane to compress the content_type in question; and c) the content isn't already compressed, as indicated by the content_encoding parameter. Browser and proxy caching is completely disabled by default. If the expires parameter is greater than zero then the response will be able to be cached by the browser for that many seconds; however, proxies are still forbidden from caching so that developers can bypass the cache with Ctrl+Shift+R. For textual content that isn't JSON, the encoding parameter is used as the transmission charset which is automatically appended to the Content-Type header. That is unless of course the content_type parameter contains a charset parameter. If the two disagree, the characters in content will be transcoded to the latter. If content_type declares a JSON media type, then content MAY be a dict, list, tuple, or set, in which case this function has an implicit composition with json_util.Cleanse and json.dumps. The encoding parameter is used to decode byte strings within the JSON object; therefore transmitting binary data within JSON is not permitted. JSON is transmitted as ASCII unless the content_type parameter explicitly defines a charset parameter, in which case the serialized JSON bytes will use that instead of escape sequences. Args: request: A werkzeug Request object. Used mostly to check the Accept-Encoding header. content: Payload data as byte string, unicode string, or maybe JSON. content_type: Media type and optionally an output charset. code: Numeric HTTP status code to use. expires: Second duration for browser caching. content_encoding: Encoding if content is already encoded, e.g. 'gzip'. encoding: Input charset if content parameter has byte strings. Returns: A werkzeug Response object (a WSGI application). """ mimetype = _EXTRACT_MIMETYPE_PATTERN.search(content_type).group(0) charset_match = _EXTRACT_CHARSET_PATTERN.search(content_type) charset = charset_match.group(1) if charset_match else encoding textual = charset_match or mimetype in _TEXTUAL_MIMETYPES if (mimetype in _JSON_MIMETYPES and isinstance(content, (dict, list, set, tuple))): content = json.dumps(json_util.Cleanse(content, encoding), ensure_ascii=not charset_match) if charset != encoding: content = tf.compat.as_text(content, encoding) content = tf.compat.as_bytes(content, charset) if textual and not charset_match and mimetype not in _JSON_MIMETYPES: content_type += '; charset=' + charset gzip_accepted = _ALLOWS_GZIP_PATTERN.search( request.headers.get('Accept-Encoding', '')) # Automatically gzip uncompressed text data if accepted. if textual and not content_encoding and gzip_accepted: out = six.BytesIO() # Set mtime to zero to make payload for a given input deterministic. with gzip.GzipFile(fileobj=out, mode='wb', compresslevel=3, mtime=0) as f: f.write(content) content = out.getvalue() content_encoding = 'gzip' content_length = len(content) direct_passthrough = False # Automatically streamwise-gunzip precompressed data if not accepted. if content_encoding == 'gzip' and not gzip_accepted: gzip_file = gzip.GzipFile(fileobj=six.BytesIO(content), mode='rb') # Last 4 bytes of gzip formatted data (little-endian) store the original # content length mod 2^32; we just assume it's the content length. That # means we can't streamwise-gunzip >4 GB precompressed file; this is ok. content_length = struct.unpack('<I', content[-4:])[0] content = werkzeug.wsgi.wrap_file(request.environ, gzip_file) content_encoding = None direct_passthrough = True headers = [] headers.append(('Content-Length', str(content_length))) if content_encoding: headers.append(('Content-Encoding', content_encoding)) if expires > 0: e = wsgiref.handlers.format_date_time(time.time() + float(expires)) headers.append(('Expires', e)) headers.append(('Cache-Control', 'private, max-age=%d' % expires)) else: headers.append(('Expires', '0')) headers.append(('Cache-Control', 'no-cache, must-revalidate')) if request.method == 'HEAD': content = None return werkzeug.wrappers.Response( response=content, status=code, headers=headers, content_type=content_type, direct_passthrough=direct_passthrough)
python
def Respond(request, content, content_type, code=200, expires=0, content_encoding=None, encoding='utf-8'): """Construct a werkzeug Response. Responses are transmitted to the browser with compression if: a) the browser supports it; b) it's sane to compress the content_type in question; and c) the content isn't already compressed, as indicated by the content_encoding parameter. Browser and proxy caching is completely disabled by default. If the expires parameter is greater than zero then the response will be able to be cached by the browser for that many seconds; however, proxies are still forbidden from caching so that developers can bypass the cache with Ctrl+Shift+R. For textual content that isn't JSON, the encoding parameter is used as the transmission charset which is automatically appended to the Content-Type header. That is unless of course the content_type parameter contains a charset parameter. If the two disagree, the characters in content will be transcoded to the latter. If content_type declares a JSON media type, then content MAY be a dict, list, tuple, or set, in which case this function has an implicit composition with json_util.Cleanse and json.dumps. The encoding parameter is used to decode byte strings within the JSON object; therefore transmitting binary data within JSON is not permitted. JSON is transmitted as ASCII unless the content_type parameter explicitly defines a charset parameter, in which case the serialized JSON bytes will use that instead of escape sequences. Args: request: A werkzeug Request object. Used mostly to check the Accept-Encoding header. content: Payload data as byte string, unicode string, or maybe JSON. content_type: Media type and optionally an output charset. code: Numeric HTTP status code to use. expires: Second duration for browser caching. content_encoding: Encoding if content is already encoded, e.g. 'gzip'. encoding: Input charset if content parameter has byte strings. Returns: A werkzeug Response object (a WSGI application). """ mimetype = _EXTRACT_MIMETYPE_PATTERN.search(content_type).group(0) charset_match = _EXTRACT_CHARSET_PATTERN.search(content_type) charset = charset_match.group(1) if charset_match else encoding textual = charset_match or mimetype in _TEXTUAL_MIMETYPES if (mimetype in _JSON_MIMETYPES and isinstance(content, (dict, list, set, tuple))): content = json.dumps(json_util.Cleanse(content, encoding), ensure_ascii=not charset_match) if charset != encoding: content = tf.compat.as_text(content, encoding) content = tf.compat.as_bytes(content, charset) if textual and not charset_match and mimetype not in _JSON_MIMETYPES: content_type += '; charset=' + charset gzip_accepted = _ALLOWS_GZIP_PATTERN.search( request.headers.get('Accept-Encoding', '')) # Automatically gzip uncompressed text data if accepted. if textual and not content_encoding and gzip_accepted: out = six.BytesIO() # Set mtime to zero to make payload for a given input deterministic. with gzip.GzipFile(fileobj=out, mode='wb', compresslevel=3, mtime=0) as f: f.write(content) content = out.getvalue() content_encoding = 'gzip' content_length = len(content) direct_passthrough = False # Automatically streamwise-gunzip precompressed data if not accepted. if content_encoding == 'gzip' and not gzip_accepted: gzip_file = gzip.GzipFile(fileobj=six.BytesIO(content), mode='rb') # Last 4 bytes of gzip formatted data (little-endian) store the original # content length mod 2^32; we just assume it's the content length. That # means we can't streamwise-gunzip >4 GB precompressed file; this is ok. content_length = struct.unpack('<I', content[-4:])[0] content = werkzeug.wsgi.wrap_file(request.environ, gzip_file) content_encoding = None direct_passthrough = True headers = [] headers.append(('Content-Length', str(content_length))) if content_encoding: headers.append(('Content-Encoding', content_encoding)) if expires > 0: e = wsgiref.handlers.format_date_time(time.time() + float(expires)) headers.append(('Expires', e)) headers.append(('Cache-Control', 'private, max-age=%d' % expires)) else: headers.append(('Expires', '0')) headers.append(('Cache-Control', 'no-cache, must-revalidate')) if request.method == 'HEAD': content = None return werkzeug.wrappers.Response( response=content, status=code, headers=headers, content_type=content_type, direct_passthrough=direct_passthrough)
[ "def", "Respond", "(", "request", ",", "content", ",", "content_type", ",", "code", "=", "200", ",", "expires", "=", "0", ",", "content_encoding", "=", "None", ",", "encoding", "=", "'utf-8'", ")", ":", "mimetype", "=", "_EXTRACT_MIMETYPE_PATTERN", ".", "search", "(", "content_type", ")", ".", "group", "(", "0", ")", "charset_match", "=", "_EXTRACT_CHARSET_PATTERN", ".", "search", "(", "content_type", ")", "charset", "=", "charset_match", ".", "group", "(", "1", ")", "if", "charset_match", "else", "encoding", "textual", "=", "charset_match", "or", "mimetype", "in", "_TEXTUAL_MIMETYPES", "if", "(", "mimetype", "in", "_JSON_MIMETYPES", "and", "isinstance", "(", "content", ",", "(", "dict", ",", "list", ",", "set", ",", "tuple", ")", ")", ")", ":", "content", "=", "json", ".", "dumps", "(", "json_util", ".", "Cleanse", "(", "content", ",", "encoding", ")", ",", "ensure_ascii", "=", "not", "charset_match", ")", "if", "charset", "!=", "encoding", ":", "content", "=", "tf", ".", "compat", ".", "as_text", "(", "content", ",", "encoding", ")", "content", "=", "tf", ".", "compat", ".", "as_bytes", "(", "content", ",", "charset", ")", "if", "textual", "and", "not", "charset_match", "and", "mimetype", "not", "in", "_JSON_MIMETYPES", ":", "content_type", "+=", "'; charset='", "+", "charset", "gzip_accepted", "=", "_ALLOWS_GZIP_PATTERN", ".", "search", "(", "request", ".", "headers", ".", "get", "(", "'Accept-Encoding'", ",", "''", ")", ")", "# Automatically gzip uncompressed text data if accepted.", "if", "textual", "and", "not", "content_encoding", "and", "gzip_accepted", ":", "out", "=", "six", ".", "BytesIO", "(", ")", "# Set mtime to zero to make payload for a given input deterministic.", "with", "gzip", ".", "GzipFile", "(", "fileobj", "=", "out", ",", "mode", "=", "'wb'", ",", "compresslevel", "=", "3", ",", "mtime", "=", "0", ")", "as", "f", ":", "f", ".", "write", "(", "content", ")", "content", "=", "out", ".", "getvalue", "(", ")", "content_encoding", "=", "'gzip'", "content_length", "=", "len", "(", "content", ")", "direct_passthrough", "=", "False", "# Automatically streamwise-gunzip precompressed data if not accepted.", "if", "content_encoding", "==", "'gzip'", "and", "not", "gzip_accepted", ":", "gzip_file", "=", "gzip", ".", "GzipFile", "(", "fileobj", "=", "six", ".", "BytesIO", "(", "content", ")", ",", "mode", "=", "'rb'", ")", "# Last 4 bytes of gzip formatted data (little-endian) store the original", "# content length mod 2^32; we just assume it's the content length. That", "# means we can't streamwise-gunzip >4 GB precompressed file; this is ok.", "content_length", "=", "struct", ".", "unpack", "(", "'<I'", ",", "content", "[", "-", "4", ":", "]", ")", "[", "0", "]", "content", "=", "werkzeug", ".", "wsgi", ".", "wrap_file", "(", "request", ".", "environ", ",", "gzip_file", ")", "content_encoding", "=", "None", "direct_passthrough", "=", "True", "headers", "=", "[", "]", "headers", ".", "append", "(", "(", "'Content-Length'", ",", "str", "(", "content_length", ")", ")", ")", "if", "content_encoding", ":", "headers", ".", "append", "(", "(", "'Content-Encoding'", ",", "content_encoding", ")", ")", "if", "expires", ">", "0", ":", "e", "=", "wsgiref", ".", "handlers", ".", "format_date_time", "(", "time", ".", "time", "(", ")", "+", "float", "(", "expires", ")", ")", "headers", ".", "append", "(", "(", "'Expires'", ",", "e", ")", ")", "headers", ".", "append", "(", "(", "'Cache-Control'", ",", "'private, max-age=%d'", "%", "expires", ")", ")", "else", ":", "headers", ".", "append", "(", "(", "'Expires'", ",", "'0'", ")", ")", "headers", ".", "append", "(", "(", "'Cache-Control'", ",", "'no-cache, must-revalidate'", ")", ")", "if", "request", ".", "method", "==", "'HEAD'", ":", "content", "=", "None", "return", "werkzeug", ".", "wrappers", ".", "Response", "(", "response", "=", "content", ",", "status", "=", "code", ",", "headers", "=", "headers", ",", "content_type", "=", "content_type", ",", "direct_passthrough", "=", "direct_passthrough", ")" ]
Construct a werkzeug Response. Responses are transmitted to the browser with compression if: a) the browser supports it; b) it's sane to compress the content_type in question; and c) the content isn't already compressed, as indicated by the content_encoding parameter. Browser and proxy caching is completely disabled by default. If the expires parameter is greater than zero then the response will be able to be cached by the browser for that many seconds; however, proxies are still forbidden from caching so that developers can bypass the cache with Ctrl+Shift+R. For textual content that isn't JSON, the encoding parameter is used as the transmission charset which is automatically appended to the Content-Type header. That is unless of course the content_type parameter contains a charset parameter. If the two disagree, the characters in content will be transcoded to the latter. If content_type declares a JSON media type, then content MAY be a dict, list, tuple, or set, in which case this function has an implicit composition with json_util.Cleanse and json.dumps. The encoding parameter is used to decode byte strings within the JSON object; therefore transmitting binary data within JSON is not permitted. JSON is transmitted as ASCII unless the content_type parameter explicitly defines a charset parameter, in which case the serialized JSON bytes will use that instead of escape sequences. Args: request: A werkzeug Request object. Used mostly to check the Accept-Encoding header. content: Payload data as byte string, unicode string, or maybe JSON. content_type: Media type and optionally an output charset. code: Numeric HTTP status code to use. expires: Second duration for browser caching. content_encoding: Encoding if content is already encoded, e.g. 'gzip'. encoding: Input charset if content parameter has byte strings. Returns: A werkzeug Response object (a WSGI application).
[ "Construct", "a", "werkzeug", "Response", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/backend/http_util.py#L64-L165
train
tensorflow/tensorboard
tensorboard/plugins/hparams/backend_context.py
_find_longest_parent_path
def _find_longest_parent_path(path_set, path): """Finds the longest "parent-path" of 'path' in 'path_set'. This function takes and returns "path-like" strings which are strings made of strings separated by os.sep. No file access is performed here, so these strings need not correspond to actual files in some file-system.. This function returns the longest ancestor path For example, for path_set=["/foo/bar", "/foo", "/bar/foo"] and path="/foo/bar/sub_dir", returns "/foo/bar". Args: path_set: set of path-like strings -- e.g. a list of strings separated by os.sep. No actual disk-access is performed here, so these need not correspond to actual files. path: a path-like string. Returns: The element in path_set which is the longest parent directory of 'path'. """ # This could likely be more efficiently implemented with a trie # data-structure, but we don't want to add an extra dependency for that. while path not in path_set: if not path: return None path = os.path.dirname(path) return path
python
def _find_longest_parent_path(path_set, path): """Finds the longest "parent-path" of 'path' in 'path_set'. This function takes and returns "path-like" strings which are strings made of strings separated by os.sep. No file access is performed here, so these strings need not correspond to actual files in some file-system.. This function returns the longest ancestor path For example, for path_set=["/foo/bar", "/foo", "/bar/foo"] and path="/foo/bar/sub_dir", returns "/foo/bar". Args: path_set: set of path-like strings -- e.g. a list of strings separated by os.sep. No actual disk-access is performed here, so these need not correspond to actual files. path: a path-like string. Returns: The element in path_set which is the longest parent directory of 'path'. """ # This could likely be more efficiently implemented with a trie # data-structure, but we don't want to add an extra dependency for that. while path not in path_set: if not path: return None path = os.path.dirname(path) return path
[ "def", "_find_longest_parent_path", "(", "path_set", ",", "path", ")", ":", "# This could likely be more efficiently implemented with a trie", "# data-structure, but we don't want to add an extra dependency for that.", "while", "path", "not", "in", "path_set", ":", "if", "not", "path", ":", "return", "None", "path", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", "return", "path" ]
Finds the longest "parent-path" of 'path' in 'path_set'. This function takes and returns "path-like" strings which are strings made of strings separated by os.sep. No file access is performed here, so these strings need not correspond to actual files in some file-system.. This function returns the longest ancestor path For example, for path_set=["/foo/bar", "/foo", "/bar/foo"] and path="/foo/bar/sub_dir", returns "/foo/bar". Args: path_set: set of path-like strings -- e.g. a list of strings separated by os.sep. No actual disk-access is performed here, so these need not correspond to actual files. path: a path-like string. Returns: The element in path_set which is the longest parent directory of 'path'.
[ "Finds", "the", "longest", "parent", "-", "path", "of", "path", "in", "path_set", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/hparams/backend_context.py#L252-L277
train
tensorflow/tensorboard
tensorboard/plugins/hparams/backend_context.py
_protobuf_value_type
def _protobuf_value_type(value): """Returns the type of the google.protobuf.Value message as an api.DataType. Returns None if the type of 'value' is not one of the types supported in api_pb2.DataType. Args: value: google.protobuf.Value message. """ if value.HasField("number_value"): return api_pb2.DATA_TYPE_FLOAT64 if value.HasField("string_value"): return api_pb2.DATA_TYPE_STRING if value.HasField("bool_value"): return api_pb2.DATA_TYPE_BOOL return None
python
def _protobuf_value_type(value): """Returns the type of the google.protobuf.Value message as an api.DataType. Returns None if the type of 'value' is not one of the types supported in api_pb2.DataType. Args: value: google.protobuf.Value message. """ if value.HasField("number_value"): return api_pb2.DATA_TYPE_FLOAT64 if value.HasField("string_value"): return api_pb2.DATA_TYPE_STRING if value.HasField("bool_value"): return api_pb2.DATA_TYPE_BOOL return None
[ "def", "_protobuf_value_type", "(", "value", ")", ":", "if", "value", ".", "HasField", "(", "\"number_value\"", ")", ":", "return", "api_pb2", ".", "DATA_TYPE_FLOAT64", "if", "value", ".", "HasField", "(", "\"string_value\"", ")", ":", "return", "api_pb2", ".", "DATA_TYPE_STRING", "if", "value", ".", "HasField", "(", "\"bool_value\"", ")", ":", "return", "api_pb2", ".", "DATA_TYPE_BOOL", "return", "None" ]
Returns the type of the google.protobuf.Value message as an api.DataType. Returns None if the type of 'value' is not one of the types supported in api_pb2.DataType. Args: value: google.protobuf.Value message.
[ "Returns", "the", "type", "of", "the", "google", ".", "protobuf", ".", "Value", "message", "as", "an", "api", ".", "DataType", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/hparams/backend_context.py#L280-L295
train
tensorflow/tensorboard
tensorboard/plugins/hparams/backend_context.py
_protobuf_value_to_string
def _protobuf_value_to_string(value): """Returns a string representation of given google.protobuf.Value message. Args: value: google.protobuf.Value message. Assumed to be of type 'number', 'string' or 'bool'. """ value_in_json = json_format.MessageToJson(value) if value.HasField("string_value"): # Remove the quotations. return value_in_json[1:-1] return value_in_json
python
def _protobuf_value_to_string(value): """Returns a string representation of given google.protobuf.Value message. Args: value: google.protobuf.Value message. Assumed to be of type 'number', 'string' or 'bool'. """ value_in_json = json_format.MessageToJson(value) if value.HasField("string_value"): # Remove the quotations. return value_in_json[1:-1] return value_in_json
[ "def", "_protobuf_value_to_string", "(", "value", ")", ":", "value_in_json", "=", "json_format", ".", "MessageToJson", "(", "value", ")", "if", "value", ".", "HasField", "(", "\"string_value\"", ")", ":", "# Remove the quotations.", "return", "value_in_json", "[", "1", ":", "-", "1", "]", "return", "value_in_json" ]
Returns a string representation of given google.protobuf.Value message. Args: value: google.protobuf.Value message. Assumed to be of type 'number', 'string' or 'bool'.
[ "Returns", "a", "string", "representation", "of", "given", "google", ".", "protobuf", ".", "Value", "message", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/hparams/backend_context.py#L298-L309
train
tensorflow/tensorboard
tensorboard/plugins/hparams/backend_context.py
Context._find_experiment_tag
def _find_experiment_tag(self): """Finds the experiment associcated with the metadata.EXPERIMENT_TAG tag. Caches the experiment if it was found. Returns: The experiment or None if no such experiment is found. """ with self._experiment_from_tag_lock: if self._experiment_from_tag is None: mapping = self.multiplexer.PluginRunToTagToContent( metadata.PLUGIN_NAME) for tag_to_content in mapping.values(): if metadata.EXPERIMENT_TAG in tag_to_content: self._experiment_from_tag = metadata.parse_experiment_plugin_data( tag_to_content[metadata.EXPERIMENT_TAG]) break return self._experiment_from_tag
python
def _find_experiment_tag(self): """Finds the experiment associcated with the metadata.EXPERIMENT_TAG tag. Caches the experiment if it was found. Returns: The experiment or None if no such experiment is found. """ with self._experiment_from_tag_lock: if self._experiment_from_tag is None: mapping = self.multiplexer.PluginRunToTagToContent( metadata.PLUGIN_NAME) for tag_to_content in mapping.values(): if metadata.EXPERIMENT_TAG in tag_to_content: self._experiment_from_tag = metadata.parse_experiment_plugin_data( tag_to_content[metadata.EXPERIMENT_TAG]) break return self._experiment_from_tag
[ "def", "_find_experiment_tag", "(", "self", ")", ":", "with", "self", ".", "_experiment_from_tag_lock", ":", "if", "self", ".", "_experiment_from_tag", "is", "None", ":", "mapping", "=", "self", ".", "multiplexer", ".", "PluginRunToTagToContent", "(", "metadata", ".", "PLUGIN_NAME", ")", "for", "tag_to_content", "in", "mapping", ".", "values", "(", ")", ":", "if", "metadata", ".", "EXPERIMENT_TAG", "in", "tag_to_content", ":", "self", ".", "_experiment_from_tag", "=", "metadata", ".", "parse_experiment_plugin_data", "(", "tag_to_content", "[", "metadata", ".", "EXPERIMENT_TAG", "]", ")", "break", "return", "self", ".", "_experiment_from_tag" ]
Finds the experiment associcated with the metadata.EXPERIMENT_TAG tag. Caches the experiment if it was found. Returns: The experiment or None if no such experiment is found.
[ "Finds", "the", "experiment", "associcated", "with", "the", "metadata", ".", "EXPERIMENT_TAG", "tag", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/hparams/backend_context.py#L91-L108
train
tensorflow/tensorboard
tensorboard/plugins/hparams/backend_context.py
Context._compute_experiment_from_runs
def _compute_experiment_from_runs(self): """Computes a minimal Experiment protocol buffer by scanning the runs.""" hparam_infos = self._compute_hparam_infos() if not hparam_infos: return None metric_infos = self._compute_metric_infos() return api_pb2.Experiment(hparam_infos=hparam_infos, metric_infos=metric_infos)
python
def _compute_experiment_from_runs(self): """Computes a minimal Experiment protocol buffer by scanning the runs.""" hparam_infos = self._compute_hparam_infos() if not hparam_infos: return None metric_infos = self._compute_metric_infos() return api_pb2.Experiment(hparam_infos=hparam_infos, metric_infos=metric_infos)
[ "def", "_compute_experiment_from_runs", "(", "self", ")", ":", "hparam_infos", "=", "self", ".", "_compute_hparam_infos", "(", ")", "if", "not", "hparam_infos", ":", "return", "None", "metric_infos", "=", "self", ".", "_compute_metric_infos", "(", ")", "return", "api_pb2", ".", "Experiment", "(", "hparam_infos", "=", "hparam_infos", ",", "metric_infos", "=", "metric_infos", ")" ]
Computes a minimal Experiment protocol buffer by scanning the runs.
[ "Computes", "a", "minimal", "Experiment", "protocol", "buffer", "by", "scanning", "the", "runs", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/hparams/backend_context.py#L110-L117
train
tensorflow/tensorboard
tensorboard/plugins/hparams/backend_context.py
Context._compute_hparam_infos
def _compute_hparam_infos(self): """Computes a list of api_pb2.HParamInfo from the current run, tag info. Finds all the SessionStartInfo messages and collects the hparams values appearing in each one. For each hparam attempts to deduce a type that fits all its values. Finally, sets the 'domain' of the resulting HParamInfo to be discrete if the type is string and the number of distinct values is small enough. Returns: A list of api_pb2.HParamInfo messages. """ run_to_tag_to_content = self.multiplexer.PluginRunToTagToContent( metadata.PLUGIN_NAME) # Construct a dict mapping an hparam name to its list of values. hparams = collections.defaultdict(list) for tag_to_content in run_to_tag_to_content.values(): if metadata.SESSION_START_INFO_TAG not in tag_to_content: continue start_info = metadata.parse_session_start_info_plugin_data( tag_to_content[metadata.SESSION_START_INFO_TAG]) for (name, value) in six.iteritems(start_info.hparams): hparams[name].append(value) # Try to construct an HParamInfo for each hparam from its name and list # of values. result = [] for (name, values) in six.iteritems(hparams): hparam_info = self._compute_hparam_info_from_values(name, values) if hparam_info is not None: result.append(hparam_info) return result
python
def _compute_hparam_infos(self): """Computes a list of api_pb2.HParamInfo from the current run, tag info. Finds all the SessionStartInfo messages and collects the hparams values appearing in each one. For each hparam attempts to deduce a type that fits all its values. Finally, sets the 'domain' of the resulting HParamInfo to be discrete if the type is string and the number of distinct values is small enough. Returns: A list of api_pb2.HParamInfo messages. """ run_to_tag_to_content = self.multiplexer.PluginRunToTagToContent( metadata.PLUGIN_NAME) # Construct a dict mapping an hparam name to its list of values. hparams = collections.defaultdict(list) for tag_to_content in run_to_tag_to_content.values(): if metadata.SESSION_START_INFO_TAG not in tag_to_content: continue start_info = metadata.parse_session_start_info_plugin_data( tag_to_content[metadata.SESSION_START_INFO_TAG]) for (name, value) in six.iteritems(start_info.hparams): hparams[name].append(value) # Try to construct an HParamInfo for each hparam from its name and list # of values. result = [] for (name, values) in six.iteritems(hparams): hparam_info = self._compute_hparam_info_from_values(name, values) if hparam_info is not None: result.append(hparam_info) return result
[ "def", "_compute_hparam_infos", "(", "self", ")", ":", "run_to_tag_to_content", "=", "self", ".", "multiplexer", ".", "PluginRunToTagToContent", "(", "metadata", ".", "PLUGIN_NAME", ")", "# Construct a dict mapping an hparam name to its list of values.", "hparams", "=", "collections", ".", "defaultdict", "(", "list", ")", "for", "tag_to_content", "in", "run_to_tag_to_content", ".", "values", "(", ")", ":", "if", "metadata", ".", "SESSION_START_INFO_TAG", "not", "in", "tag_to_content", ":", "continue", "start_info", "=", "metadata", ".", "parse_session_start_info_plugin_data", "(", "tag_to_content", "[", "metadata", ".", "SESSION_START_INFO_TAG", "]", ")", "for", "(", "name", ",", "value", ")", "in", "six", ".", "iteritems", "(", "start_info", ".", "hparams", ")", ":", "hparams", "[", "name", "]", ".", "append", "(", "value", ")", "# Try to construct an HParamInfo for each hparam from its name and list", "# of values.", "result", "=", "[", "]", "for", "(", "name", ",", "values", ")", "in", "six", ".", "iteritems", "(", "hparams", ")", ":", "hparam_info", "=", "self", ".", "_compute_hparam_info_from_values", "(", "name", ",", "values", ")", "if", "hparam_info", "is", "not", "None", ":", "result", ".", "append", "(", "hparam_info", ")", "return", "result" ]
Computes a list of api_pb2.HParamInfo from the current run, tag info. Finds all the SessionStartInfo messages and collects the hparams values appearing in each one. For each hparam attempts to deduce a type that fits all its values. Finally, sets the 'domain' of the resulting HParamInfo to be discrete if the type is string and the number of distinct values is small enough. Returns: A list of api_pb2.HParamInfo messages.
[ "Computes", "a", "list", "of", "api_pb2", ".", "HParamInfo", "from", "the", "current", "run", "tag", "info", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/hparams/backend_context.py#L119-L150
train
tensorflow/tensorboard
tensorboard/plugins/hparams/backend_context.py
Context._compute_hparam_info_from_values
def _compute_hparam_info_from_values(self, name, values): """Builds an HParamInfo message from the hparam name and list of values. Args: name: string. The hparam name. values: list of google.protobuf.Value messages. The list of values for the hparam. Returns: An api_pb2.HParamInfo message. """ # Figure out the type from the values. # Ignore values whose type is not listed in api_pb2.DataType # If all values have the same type, then that is the type used. # Otherwise, the returned type is DATA_TYPE_STRING. result = api_pb2.HParamInfo(name=name, type=api_pb2.DATA_TYPE_UNSET) distinct_values = set( _protobuf_value_to_string(v) for v in values if _protobuf_value_type(v)) for v in values: v_type = _protobuf_value_type(v) if not v_type: continue if result.type == api_pb2.DATA_TYPE_UNSET: result.type = v_type elif result.type != v_type: result.type = api_pb2.DATA_TYPE_STRING if result.type == api_pb2.DATA_TYPE_STRING: # A string result.type does not change, so we can exit the loop. break # If we couldn't figure out a type, then we can't compute the hparam_info. if result.type == api_pb2.DATA_TYPE_UNSET: return None # If the result is a string, set the domain to be the distinct values if # there aren't too many of them. if (result.type == api_pb2.DATA_TYPE_STRING and len(distinct_values) <= self._max_domain_discrete_len): result.domain_discrete.extend(distinct_values) return result
python
def _compute_hparam_info_from_values(self, name, values): """Builds an HParamInfo message from the hparam name and list of values. Args: name: string. The hparam name. values: list of google.protobuf.Value messages. The list of values for the hparam. Returns: An api_pb2.HParamInfo message. """ # Figure out the type from the values. # Ignore values whose type is not listed in api_pb2.DataType # If all values have the same type, then that is the type used. # Otherwise, the returned type is DATA_TYPE_STRING. result = api_pb2.HParamInfo(name=name, type=api_pb2.DATA_TYPE_UNSET) distinct_values = set( _protobuf_value_to_string(v) for v in values if _protobuf_value_type(v)) for v in values: v_type = _protobuf_value_type(v) if not v_type: continue if result.type == api_pb2.DATA_TYPE_UNSET: result.type = v_type elif result.type != v_type: result.type = api_pb2.DATA_TYPE_STRING if result.type == api_pb2.DATA_TYPE_STRING: # A string result.type does not change, so we can exit the loop. break # If we couldn't figure out a type, then we can't compute the hparam_info. if result.type == api_pb2.DATA_TYPE_UNSET: return None # If the result is a string, set the domain to be the distinct values if # there aren't too many of them. if (result.type == api_pb2.DATA_TYPE_STRING and len(distinct_values) <= self._max_domain_discrete_len): result.domain_discrete.extend(distinct_values) return result
[ "def", "_compute_hparam_info_from_values", "(", "self", ",", "name", ",", "values", ")", ":", "# Figure out the type from the values.", "# Ignore values whose type is not listed in api_pb2.DataType", "# If all values have the same type, then that is the type used.", "# Otherwise, the returned type is DATA_TYPE_STRING.", "result", "=", "api_pb2", ".", "HParamInfo", "(", "name", "=", "name", ",", "type", "=", "api_pb2", ".", "DATA_TYPE_UNSET", ")", "distinct_values", "=", "set", "(", "_protobuf_value_to_string", "(", "v", ")", "for", "v", "in", "values", "if", "_protobuf_value_type", "(", "v", ")", ")", "for", "v", "in", "values", ":", "v_type", "=", "_protobuf_value_type", "(", "v", ")", "if", "not", "v_type", ":", "continue", "if", "result", ".", "type", "==", "api_pb2", ".", "DATA_TYPE_UNSET", ":", "result", ".", "type", "=", "v_type", "elif", "result", ".", "type", "!=", "v_type", ":", "result", ".", "type", "=", "api_pb2", ".", "DATA_TYPE_STRING", "if", "result", ".", "type", "==", "api_pb2", ".", "DATA_TYPE_STRING", ":", "# A string result.type does not change, so we can exit the loop.", "break", "# If we couldn't figure out a type, then we can't compute the hparam_info.", "if", "result", ".", "type", "==", "api_pb2", ".", "DATA_TYPE_UNSET", ":", "return", "None", "# If the result is a string, set the domain to be the distinct values if", "# there aren't too many of them.", "if", "(", "result", ".", "type", "==", "api_pb2", ".", "DATA_TYPE_STRING", "and", "len", "(", "distinct_values", ")", "<=", "self", ".", "_max_domain_discrete_len", ")", ":", "result", ".", "domain_discrete", ".", "extend", "(", "distinct_values", ")", "return", "result" ]
Builds an HParamInfo message from the hparam name and list of values. Args: name: string. The hparam name. values: list of google.protobuf.Value messages. The list of values for the hparam. Returns: An api_pb2.HParamInfo message.
[ "Builds", "an", "HParamInfo", "message", "from", "the", "hparam", "name", "and", "list", "of", "values", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/hparams/backend_context.py#L152-L192
train
tensorflow/tensorboard
tensorboard/plugins/hparams/backend_context.py
Context._compute_metric_names
def _compute_metric_names(self): """Computes the list of metric names from all the scalar (run, tag) pairs. The return value is a list of (tag, group) pairs representing the metric names. The list is sorted in Python tuple-order (lexicographical). For example, if the scalar (run, tag) pairs are: ("exp/session1", "loss") ("exp/session2", "loss") ("exp/session2/eval", "loss") ("exp/session2/validation", "accuracy") ("exp/no-session", "loss_2"), and the runs corresponding to sessions are "exp/session1", "exp/session2", this method will return [("loss", ""), ("loss", "/eval"), ("accuracy", "/validation")] More precisely, each scalar (run, tag) pair is converted to a (tag, group) metric name, where group is the suffix of run formed by removing the longest prefix which is a session run. If no session run is a prefix of 'run', the pair is skipped. Returns: A python list containing pairs. Each pair is a (tag, group) pair representing a metric name used in some session. """ session_runs = self._build_session_runs_set() metric_names_set = set() run_to_tag_to_content = self.multiplexer.PluginRunToTagToContent( scalar_metadata.PLUGIN_NAME) for (run, tag_to_content) in six.iteritems(run_to_tag_to_content): session = _find_longest_parent_path(session_runs, run) if not session: continue group = os.path.relpath(run, session) # relpath() returns "." for the 'session' directory, we use an empty # string. if group == ".": group = "" metric_names_set.update((tag, group) for tag in tag_to_content.keys()) metric_names_list = list(metric_names_set) # Sort metrics for determinism. metric_names_list.sort() return metric_names_list
python
def _compute_metric_names(self): """Computes the list of metric names from all the scalar (run, tag) pairs. The return value is a list of (tag, group) pairs representing the metric names. The list is sorted in Python tuple-order (lexicographical). For example, if the scalar (run, tag) pairs are: ("exp/session1", "loss") ("exp/session2", "loss") ("exp/session2/eval", "loss") ("exp/session2/validation", "accuracy") ("exp/no-session", "loss_2"), and the runs corresponding to sessions are "exp/session1", "exp/session2", this method will return [("loss", ""), ("loss", "/eval"), ("accuracy", "/validation")] More precisely, each scalar (run, tag) pair is converted to a (tag, group) metric name, where group is the suffix of run formed by removing the longest prefix which is a session run. If no session run is a prefix of 'run', the pair is skipped. Returns: A python list containing pairs. Each pair is a (tag, group) pair representing a metric name used in some session. """ session_runs = self._build_session_runs_set() metric_names_set = set() run_to_tag_to_content = self.multiplexer.PluginRunToTagToContent( scalar_metadata.PLUGIN_NAME) for (run, tag_to_content) in six.iteritems(run_to_tag_to_content): session = _find_longest_parent_path(session_runs, run) if not session: continue group = os.path.relpath(run, session) # relpath() returns "." for the 'session' directory, we use an empty # string. if group == ".": group = "" metric_names_set.update((tag, group) for tag in tag_to_content.keys()) metric_names_list = list(metric_names_set) # Sort metrics for determinism. metric_names_list.sort() return metric_names_list
[ "def", "_compute_metric_names", "(", "self", ")", ":", "session_runs", "=", "self", ".", "_build_session_runs_set", "(", ")", "metric_names_set", "=", "set", "(", ")", "run_to_tag_to_content", "=", "self", ".", "multiplexer", ".", "PluginRunToTagToContent", "(", "scalar_metadata", ".", "PLUGIN_NAME", ")", "for", "(", "run", ",", "tag_to_content", ")", "in", "six", ".", "iteritems", "(", "run_to_tag_to_content", ")", ":", "session", "=", "_find_longest_parent_path", "(", "session_runs", ",", "run", ")", "if", "not", "session", ":", "continue", "group", "=", "os", ".", "path", ".", "relpath", "(", "run", ",", "session", ")", "# relpath() returns \".\" for the 'session' directory, we use an empty", "# string.", "if", "group", "==", "\".\"", ":", "group", "=", "\"\"", "metric_names_set", ".", "update", "(", "(", "tag", ",", "group", ")", "for", "tag", "in", "tag_to_content", ".", "keys", "(", ")", ")", "metric_names_list", "=", "list", "(", "metric_names_set", ")", "# Sort metrics for determinism.", "metric_names_list", ".", "sort", "(", ")", "return", "metric_names_list" ]
Computes the list of metric names from all the scalar (run, tag) pairs. The return value is a list of (tag, group) pairs representing the metric names. The list is sorted in Python tuple-order (lexicographical). For example, if the scalar (run, tag) pairs are: ("exp/session1", "loss") ("exp/session2", "loss") ("exp/session2/eval", "loss") ("exp/session2/validation", "accuracy") ("exp/no-session", "loss_2"), and the runs corresponding to sessions are "exp/session1", "exp/session2", this method will return [("loss", ""), ("loss", "/eval"), ("accuracy", "/validation")] More precisely, each scalar (run, tag) pair is converted to a (tag, group) metric name, where group is the suffix of run formed by removing the longest prefix which is a session run. If no session run is a prefix of 'run', the pair is skipped. Returns: A python list containing pairs. Each pair is a (tag, group) pair representing a metric name used in some session.
[ "Computes", "the", "list", "of", "metric", "names", "from", "all", "the", "scalar", "(", "run", "tag", ")", "pairs", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/hparams/backend_context.py#L198-L240
train
tensorflow/tensorboard
tensorboard/plugins/hparams/get_experiment.py
Handler.run
def run(self): """Handles the request specified on construction. Returns: An Experiment object. """ experiment = self._context.experiment() if experiment is None: raise error.HParamsError( "Can't find an HParams-plugin experiment data in" " the log directory. Note that it takes some time to" " scan the log directory; if you just started" " Tensorboard it could be that we haven't finished" " scanning it yet. Consider trying again in a" " few seconds.") return experiment
python
def run(self): """Handles the request specified on construction. Returns: An Experiment object. """ experiment = self._context.experiment() if experiment is None: raise error.HParamsError( "Can't find an HParams-plugin experiment data in" " the log directory. Note that it takes some time to" " scan the log directory; if you just started" " Tensorboard it could be that we haven't finished" " scanning it yet. Consider trying again in a" " few seconds.") return experiment
[ "def", "run", "(", "self", ")", ":", "experiment", "=", "self", ".", "_context", ".", "experiment", "(", ")", "if", "experiment", "is", "None", ":", "raise", "error", ".", "HParamsError", "(", "\"Can't find an HParams-plugin experiment data in\"", "\" the log directory. Note that it takes some time to\"", "\" scan the log directory; if you just started\"", "\" Tensorboard it could be that we haven't finished\"", "\" scanning it yet. Consider trying again in a\"", "\" few seconds.\"", ")", "return", "experiment" ]
Handles the request specified on construction. Returns: An Experiment object.
[ "Handles", "the", "request", "specified", "on", "construction", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/hparams/get_experiment.py#L36-L52
train
tensorflow/tensorboard
tensorboard/plugins/hparams/summary.py
experiment_pb
def experiment_pb( hparam_infos, metric_infos, user='', description='', time_created_secs=None): """Creates a summary that defines a hyperparameter-tuning experiment. Args: hparam_infos: Array of api_pb2.HParamInfo messages. Describes the hyperparameters used in the experiment. metric_infos: Array of api_pb2.MetricInfo messages. Describes the metrics used in the experiment. See the documentation at the top of this file for how to populate this. user: String. An id for the user running the experiment description: String. A description for the experiment. May contain markdown. time_created_secs: float. The time the experiment is created in seconds since the UNIX epoch. If None uses the current time. Returns: A summary protobuffer containing the experiment definition. """ if time_created_secs is None: time_created_secs = time.time() experiment = api_pb2.Experiment( description=description, user=user, time_created_secs=time_created_secs, hparam_infos=hparam_infos, metric_infos=metric_infos) return _summary(metadata.EXPERIMENT_TAG, plugin_data_pb2.HParamsPluginData(experiment=experiment))
python
def experiment_pb( hparam_infos, metric_infos, user='', description='', time_created_secs=None): """Creates a summary that defines a hyperparameter-tuning experiment. Args: hparam_infos: Array of api_pb2.HParamInfo messages. Describes the hyperparameters used in the experiment. metric_infos: Array of api_pb2.MetricInfo messages. Describes the metrics used in the experiment. See the documentation at the top of this file for how to populate this. user: String. An id for the user running the experiment description: String. A description for the experiment. May contain markdown. time_created_secs: float. The time the experiment is created in seconds since the UNIX epoch. If None uses the current time. Returns: A summary protobuffer containing the experiment definition. """ if time_created_secs is None: time_created_secs = time.time() experiment = api_pb2.Experiment( description=description, user=user, time_created_secs=time_created_secs, hparam_infos=hparam_infos, metric_infos=metric_infos) return _summary(metadata.EXPERIMENT_TAG, plugin_data_pb2.HParamsPluginData(experiment=experiment))
[ "def", "experiment_pb", "(", "hparam_infos", ",", "metric_infos", ",", "user", "=", "''", ",", "description", "=", "''", ",", "time_created_secs", "=", "None", ")", ":", "if", "time_created_secs", "is", "None", ":", "time_created_secs", "=", "time", ".", "time", "(", ")", "experiment", "=", "api_pb2", ".", "Experiment", "(", "description", "=", "description", ",", "user", "=", "user", ",", "time_created_secs", "=", "time_created_secs", ",", "hparam_infos", "=", "hparam_infos", ",", "metric_infos", "=", "metric_infos", ")", "return", "_summary", "(", "metadata", ".", "EXPERIMENT_TAG", ",", "plugin_data_pb2", ".", "HParamsPluginData", "(", "experiment", "=", "experiment", ")", ")" ]
Creates a summary that defines a hyperparameter-tuning experiment. Args: hparam_infos: Array of api_pb2.HParamInfo messages. Describes the hyperparameters used in the experiment. metric_infos: Array of api_pb2.MetricInfo messages. Describes the metrics used in the experiment. See the documentation at the top of this file for how to populate this. user: String. An id for the user running the experiment description: String. A description for the experiment. May contain markdown. time_created_secs: float. The time the experiment is created in seconds since the UNIX epoch. If None uses the current time. Returns: A summary protobuffer containing the experiment definition.
[ "Creates", "a", "summary", "that", "defines", "a", "hyperparameter", "-", "tuning", "experiment", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/hparams/summary.py#L49-L80
train
tensorflow/tensorboard
tensorboard/plugins/hparams/summary.py
session_start_pb
def session_start_pb(hparams, model_uri='', monitor_url='', group_name='', start_time_secs=None): """Constructs a SessionStartInfo protobuffer. Creates a summary that contains a training session metadata information. One such summary per training session should be created. Each should have a different run. Args: hparams: A dictionary with string keys. Describes the hyperparameter values used in the session, mapping each hyperparameter name to its value. Supported value types are `bool`, `int`, `float`, `str`, `list`, `tuple`. The type of value must correspond to the type of hyperparameter (defined in the corresponding api_pb2.HParamInfo member of the Experiment protobuf) as follows: +-----------------+---------------------------------+ |Hyperparameter | Allowed (Python) value types | |type | | +-----------------+---------------------------------+ |DATA_TYPE_BOOL | bool | |DATA_TYPE_FLOAT64| int, float | |DATA_TYPE_STRING | six.string_types, tuple, list | +-----------------+---------------------------------+ Tuple and list instances will be converted to their string representation. model_uri: See the comment for the field with the same name of plugin_data_pb2.SessionStartInfo. monitor_url: See the comment for the field with the same name of plugin_data_pb2.SessionStartInfo. group_name: See the comment for the field with the same name of plugin_data_pb2.SessionStartInfo. start_time_secs: float. The time to use as the session start time. Represented as seconds since the UNIX epoch. If None uses the current time. Returns: The summary protobuffer mentioned above. """ if start_time_secs is None: start_time_secs = time.time() session_start_info = plugin_data_pb2.SessionStartInfo( model_uri=model_uri, monitor_url=monitor_url, group_name=group_name, start_time_secs=start_time_secs) for (hp_name, hp_val) in six.iteritems(hparams): if isinstance(hp_val, (float, int)): session_start_info.hparams[hp_name].number_value = hp_val elif isinstance(hp_val, six.string_types): session_start_info.hparams[hp_name].string_value = hp_val elif isinstance(hp_val, bool): session_start_info.hparams[hp_name].bool_value = hp_val elif isinstance(hp_val, (list, tuple)): session_start_info.hparams[hp_name].string_value = str(hp_val) else: raise TypeError('hparams[%s]=%s has type: %s which is not supported' % (hp_name, hp_val, type(hp_val))) return _summary(metadata.SESSION_START_INFO_TAG, plugin_data_pb2.HParamsPluginData( session_start_info=session_start_info))
python
def session_start_pb(hparams, model_uri='', monitor_url='', group_name='', start_time_secs=None): """Constructs a SessionStartInfo protobuffer. Creates a summary that contains a training session metadata information. One such summary per training session should be created. Each should have a different run. Args: hparams: A dictionary with string keys. Describes the hyperparameter values used in the session, mapping each hyperparameter name to its value. Supported value types are `bool`, `int`, `float`, `str`, `list`, `tuple`. The type of value must correspond to the type of hyperparameter (defined in the corresponding api_pb2.HParamInfo member of the Experiment protobuf) as follows: +-----------------+---------------------------------+ |Hyperparameter | Allowed (Python) value types | |type | | +-----------------+---------------------------------+ |DATA_TYPE_BOOL | bool | |DATA_TYPE_FLOAT64| int, float | |DATA_TYPE_STRING | six.string_types, tuple, list | +-----------------+---------------------------------+ Tuple and list instances will be converted to their string representation. model_uri: See the comment for the field with the same name of plugin_data_pb2.SessionStartInfo. monitor_url: See the comment for the field with the same name of plugin_data_pb2.SessionStartInfo. group_name: See the comment for the field with the same name of plugin_data_pb2.SessionStartInfo. start_time_secs: float. The time to use as the session start time. Represented as seconds since the UNIX epoch. If None uses the current time. Returns: The summary protobuffer mentioned above. """ if start_time_secs is None: start_time_secs = time.time() session_start_info = plugin_data_pb2.SessionStartInfo( model_uri=model_uri, monitor_url=monitor_url, group_name=group_name, start_time_secs=start_time_secs) for (hp_name, hp_val) in six.iteritems(hparams): if isinstance(hp_val, (float, int)): session_start_info.hparams[hp_name].number_value = hp_val elif isinstance(hp_val, six.string_types): session_start_info.hparams[hp_name].string_value = hp_val elif isinstance(hp_val, bool): session_start_info.hparams[hp_name].bool_value = hp_val elif isinstance(hp_val, (list, tuple)): session_start_info.hparams[hp_name].string_value = str(hp_val) else: raise TypeError('hparams[%s]=%s has type: %s which is not supported' % (hp_name, hp_val, type(hp_val))) return _summary(metadata.SESSION_START_INFO_TAG, plugin_data_pb2.HParamsPluginData( session_start_info=session_start_info))
[ "def", "session_start_pb", "(", "hparams", ",", "model_uri", "=", "''", ",", "monitor_url", "=", "''", ",", "group_name", "=", "''", ",", "start_time_secs", "=", "None", ")", ":", "if", "start_time_secs", "is", "None", ":", "start_time_secs", "=", "time", ".", "time", "(", ")", "session_start_info", "=", "plugin_data_pb2", ".", "SessionStartInfo", "(", "model_uri", "=", "model_uri", ",", "monitor_url", "=", "monitor_url", ",", "group_name", "=", "group_name", ",", "start_time_secs", "=", "start_time_secs", ")", "for", "(", "hp_name", ",", "hp_val", ")", "in", "six", ".", "iteritems", "(", "hparams", ")", ":", "if", "isinstance", "(", "hp_val", ",", "(", "float", ",", "int", ")", ")", ":", "session_start_info", ".", "hparams", "[", "hp_name", "]", ".", "number_value", "=", "hp_val", "elif", "isinstance", "(", "hp_val", ",", "six", ".", "string_types", ")", ":", "session_start_info", ".", "hparams", "[", "hp_name", "]", ".", "string_value", "=", "hp_val", "elif", "isinstance", "(", "hp_val", ",", "bool", ")", ":", "session_start_info", ".", "hparams", "[", "hp_name", "]", ".", "bool_value", "=", "hp_val", "elif", "isinstance", "(", "hp_val", ",", "(", "list", ",", "tuple", ")", ")", ":", "session_start_info", ".", "hparams", "[", "hp_name", "]", ".", "string_value", "=", "str", "(", "hp_val", ")", "else", ":", "raise", "TypeError", "(", "'hparams[%s]=%s has type: %s which is not supported'", "%", "(", "hp_name", ",", "hp_val", ",", "type", "(", "hp_val", ")", ")", ")", "return", "_summary", "(", "metadata", ".", "SESSION_START_INFO_TAG", ",", "plugin_data_pb2", ".", "HParamsPluginData", "(", "session_start_info", "=", "session_start_info", ")", ")" ]
Constructs a SessionStartInfo protobuffer. Creates a summary that contains a training session metadata information. One such summary per training session should be created. Each should have a different run. Args: hparams: A dictionary with string keys. Describes the hyperparameter values used in the session, mapping each hyperparameter name to its value. Supported value types are `bool`, `int`, `float`, `str`, `list`, `tuple`. The type of value must correspond to the type of hyperparameter (defined in the corresponding api_pb2.HParamInfo member of the Experiment protobuf) as follows: +-----------------+---------------------------------+ |Hyperparameter | Allowed (Python) value types | |type | | +-----------------+---------------------------------+ |DATA_TYPE_BOOL | bool | |DATA_TYPE_FLOAT64| int, float | |DATA_TYPE_STRING | six.string_types, tuple, list | +-----------------+---------------------------------+ Tuple and list instances will be converted to their string representation. model_uri: See the comment for the field with the same name of plugin_data_pb2.SessionStartInfo. monitor_url: See the comment for the field with the same name of plugin_data_pb2.SessionStartInfo. group_name: See the comment for the field with the same name of plugin_data_pb2.SessionStartInfo. start_time_secs: float. The time to use as the session start time. Represented as seconds since the UNIX epoch. If None uses the current time. Returns: The summary protobuffer mentioned above.
[ "Constructs", "a", "SessionStartInfo", "protobuffer", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/hparams/summary.py#L83-L147
train
tensorflow/tensorboard
tensorboard/plugins/hparams/summary.py
session_end_pb
def session_end_pb(status, end_time_secs=None): """Constructs a SessionEndInfo protobuffer. Creates a summary that contains status information for a completed training session. Should be exported after the training session is completed. One such summary per training session should be created. Each should have a different run. Args: status: A tensorboard.hparams.Status enumeration value denoting the status of the session. end_time_secs: float. The time to use as the session end time. Represented as seconds since the unix epoch. If None uses the current time. Returns: The summary protobuffer mentioned above. """ if end_time_secs is None: end_time_secs = time.time() session_end_info = plugin_data_pb2.SessionEndInfo(status=status, end_time_secs=end_time_secs) return _summary(metadata.SESSION_END_INFO_TAG, plugin_data_pb2.HParamsPluginData( session_end_info=session_end_info))
python
def session_end_pb(status, end_time_secs=None): """Constructs a SessionEndInfo protobuffer. Creates a summary that contains status information for a completed training session. Should be exported after the training session is completed. One such summary per training session should be created. Each should have a different run. Args: status: A tensorboard.hparams.Status enumeration value denoting the status of the session. end_time_secs: float. The time to use as the session end time. Represented as seconds since the unix epoch. If None uses the current time. Returns: The summary protobuffer mentioned above. """ if end_time_secs is None: end_time_secs = time.time() session_end_info = plugin_data_pb2.SessionEndInfo(status=status, end_time_secs=end_time_secs) return _summary(metadata.SESSION_END_INFO_TAG, plugin_data_pb2.HParamsPluginData( session_end_info=session_end_info))
[ "def", "session_end_pb", "(", "status", ",", "end_time_secs", "=", "None", ")", ":", "if", "end_time_secs", "is", "None", ":", "end_time_secs", "=", "time", ".", "time", "(", ")", "session_end_info", "=", "plugin_data_pb2", ".", "SessionEndInfo", "(", "status", "=", "status", ",", "end_time_secs", "=", "end_time_secs", ")", "return", "_summary", "(", "metadata", ".", "SESSION_END_INFO_TAG", ",", "plugin_data_pb2", ".", "HParamsPluginData", "(", "session_end_info", "=", "session_end_info", ")", ")" ]
Constructs a SessionEndInfo protobuffer. Creates a summary that contains status information for a completed training session. Should be exported after the training session is completed. One such summary per training session should be created. Each should have a different run. Args: status: A tensorboard.hparams.Status enumeration value denoting the status of the session. end_time_secs: float. The time to use as the session end time. Represented as seconds since the unix epoch. If None uses the current time. Returns: The summary protobuffer mentioned above.
[ "Constructs", "a", "SessionEndInfo", "protobuffer", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/hparams/summary.py#L150-L174
train
tensorflow/tensorboard
tensorboard/plugins/hparams/summary.py
_summary
def _summary(tag, hparams_plugin_data): """Returns a summary holding the given HParamsPluginData message. Helper function. Args: tag: string. The tag to use. hparams_plugin_data: The HParamsPluginData message to use. """ summary = tf.compat.v1.Summary() summary.value.add( tag=tag, metadata=metadata.create_summary_metadata(hparams_plugin_data)) return summary
python
def _summary(tag, hparams_plugin_data): """Returns a summary holding the given HParamsPluginData message. Helper function. Args: tag: string. The tag to use. hparams_plugin_data: The HParamsPluginData message to use. """ summary = tf.compat.v1.Summary() summary.value.add( tag=tag, metadata=metadata.create_summary_metadata(hparams_plugin_data)) return summary
[ "def", "_summary", "(", "tag", ",", "hparams_plugin_data", ")", ":", "summary", "=", "tf", ".", "compat", ".", "v1", ".", "Summary", "(", ")", "summary", ".", "value", ".", "add", "(", "tag", "=", "tag", ",", "metadata", "=", "metadata", ".", "create_summary_metadata", "(", "hparams_plugin_data", ")", ")", "return", "summary" ]
Returns a summary holding the given HParamsPluginData message. Helper function. Args: tag: string. The tag to use. hparams_plugin_data: The HParamsPluginData message to use.
[ "Returns", "a", "summary", "holding", "the", "given", "HParamsPluginData", "message", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/hparams/summary.py#L177-L190
train
tensorflow/tensorboard
tensorboard/backend/event_processing/plugin_asset_util.py
_IsDirectory
def _IsDirectory(parent, item): """Helper that returns if parent/item is a directory.""" return tf.io.gfile.isdir(os.path.join(parent, item))
python
def _IsDirectory(parent, item): """Helper that returns if parent/item is a directory.""" return tf.io.gfile.isdir(os.path.join(parent, item))
[ "def", "_IsDirectory", "(", "parent", ",", "item", ")", ":", "return", "tf", ".", "io", ".", "gfile", ".", "isdir", "(", "os", ".", "path", ".", "join", "(", "parent", ",", "item", ")", ")" ]
Helper that returns if parent/item is a directory.
[ "Helper", "that", "returns", "if", "parent", "/", "item", "is", "a", "directory", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/backend/event_processing/plugin_asset_util.py#L28-L30
train
tensorflow/tensorboard
tensorboard/backend/event_processing/plugin_asset_util.py
ListPlugins
def ListPlugins(logdir): """List all the plugins that have registered assets in logdir. If the plugins_dir does not exist, it returns an empty list. This maintains compatibility with old directories that have no plugins written. Args: logdir: A directory that was created by a TensorFlow events writer. Returns: a list of plugin names, as strings """ plugins_dir = os.path.join(logdir, _PLUGINS_DIR) try: entries = tf.io.gfile.listdir(plugins_dir) except tf.errors.NotFoundError: return [] # Strip trailing slashes, which listdir() includes for some filesystems # for subdirectories, after using them to bypass IsDirectory(). return [x.rstrip('/') for x in entries if x.endswith('/') or _IsDirectory(plugins_dir, x)]
python
def ListPlugins(logdir): """List all the plugins that have registered assets in logdir. If the plugins_dir does not exist, it returns an empty list. This maintains compatibility with old directories that have no plugins written. Args: logdir: A directory that was created by a TensorFlow events writer. Returns: a list of plugin names, as strings """ plugins_dir = os.path.join(logdir, _PLUGINS_DIR) try: entries = tf.io.gfile.listdir(plugins_dir) except tf.errors.NotFoundError: return [] # Strip trailing slashes, which listdir() includes for some filesystems # for subdirectories, after using them to bypass IsDirectory(). return [x.rstrip('/') for x in entries if x.endswith('/') or _IsDirectory(plugins_dir, x)]
[ "def", "ListPlugins", "(", "logdir", ")", ":", "plugins_dir", "=", "os", ".", "path", ".", "join", "(", "logdir", ",", "_PLUGINS_DIR", ")", "try", ":", "entries", "=", "tf", ".", "io", ".", "gfile", ".", "listdir", "(", "plugins_dir", ")", "except", "tf", ".", "errors", ".", "NotFoundError", ":", "return", "[", "]", "# Strip trailing slashes, which listdir() includes for some filesystems", "# for subdirectories, after using them to bypass IsDirectory().", "return", "[", "x", ".", "rstrip", "(", "'/'", ")", "for", "x", "in", "entries", "if", "x", ".", "endswith", "(", "'/'", ")", "or", "_IsDirectory", "(", "plugins_dir", ",", "x", ")", "]" ]
List all the plugins that have registered assets in logdir. If the plugins_dir does not exist, it returns an empty list. This maintains compatibility with old directories that have no plugins written. Args: logdir: A directory that was created by a TensorFlow events writer. Returns: a list of plugin names, as strings
[ "List", "all", "the", "plugins", "that", "have", "registered", "assets", "in", "logdir", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/backend/event_processing/plugin_asset_util.py#L38-L58
train
tensorflow/tensorboard
tensorboard/backend/event_processing/plugin_asset_util.py
ListAssets
def ListAssets(logdir, plugin_name): """List all the assets that are available for given plugin in a logdir. Args: logdir: A directory that was created by a TensorFlow summary.FileWriter. plugin_name: A string name of a plugin to list assets for. Returns: A string list of available plugin assets. If the plugin subdirectory does not exist (either because the logdir doesn't exist, or because the plugin didn't register) an empty list is returned. """ plugin_dir = PluginDirectory(logdir, plugin_name) try: # Strip trailing slashes, which listdir() includes for some filesystems. return [x.rstrip('/') for x in tf.io.gfile.listdir(plugin_dir)] except tf.errors.NotFoundError: return []
python
def ListAssets(logdir, plugin_name): """List all the assets that are available for given plugin in a logdir. Args: logdir: A directory that was created by a TensorFlow summary.FileWriter. plugin_name: A string name of a plugin to list assets for. Returns: A string list of available plugin assets. If the plugin subdirectory does not exist (either because the logdir doesn't exist, or because the plugin didn't register) an empty list is returned. """ plugin_dir = PluginDirectory(logdir, plugin_name) try: # Strip trailing slashes, which listdir() includes for some filesystems. return [x.rstrip('/') for x in tf.io.gfile.listdir(plugin_dir)] except tf.errors.NotFoundError: return []
[ "def", "ListAssets", "(", "logdir", ",", "plugin_name", ")", ":", "plugin_dir", "=", "PluginDirectory", "(", "logdir", ",", "plugin_name", ")", "try", ":", "# Strip trailing slashes, which listdir() includes for some filesystems.", "return", "[", "x", ".", "rstrip", "(", "'/'", ")", "for", "x", "in", "tf", ".", "io", ".", "gfile", ".", "listdir", "(", "plugin_dir", ")", "]", "except", "tf", ".", "errors", ".", "NotFoundError", ":", "return", "[", "]" ]
List all the assets that are available for given plugin in a logdir. Args: logdir: A directory that was created by a TensorFlow summary.FileWriter. plugin_name: A string name of a plugin to list assets for. Returns: A string list of available plugin assets. If the plugin subdirectory does not exist (either because the logdir doesn't exist, or because the plugin didn't register) an empty list is returned.
[ "List", "all", "the", "assets", "that", "are", "available", "for", "given", "plugin", "in", "a", "logdir", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/backend/event_processing/plugin_asset_util.py#L61-L78
train
tensorflow/tensorboard
tensorboard/backend/event_processing/plugin_asset_util.py
RetrieveAsset
def RetrieveAsset(logdir, plugin_name, asset_name): """Retrieve a particular plugin asset from a logdir. Args: logdir: A directory that was created by a TensorFlow summary.FileWriter. plugin_name: The plugin we want an asset from. asset_name: The name of the requested asset. Returns: string contents of the plugin asset. Raises: KeyError: if the asset does not exist. """ asset_path = os.path.join(PluginDirectory(logdir, plugin_name), asset_name) try: with tf.io.gfile.GFile(asset_path, "r") as f: return f.read() except tf.errors.NotFoundError: raise KeyError("Asset path %s not found" % asset_path) except tf.errors.OpError as e: raise KeyError("Couldn't read asset path: %s, OpError %s" % (asset_path, e))
python
def RetrieveAsset(logdir, plugin_name, asset_name): """Retrieve a particular plugin asset from a logdir. Args: logdir: A directory that was created by a TensorFlow summary.FileWriter. plugin_name: The plugin we want an asset from. asset_name: The name of the requested asset. Returns: string contents of the plugin asset. Raises: KeyError: if the asset does not exist. """ asset_path = os.path.join(PluginDirectory(logdir, plugin_name), asset_name) try: with tf.io.gfile.GFile(asset_path, "r") as f: return f.read() except tf.errors.NotFoundError: raise KeyError("Asset path %s not found" % asset_path) except tf.errors.OpError as e: raise KeyError("Couldn't read asset path: %s, OpError %s" % (asset_path, e))
[ "def", "RetrieveAsset", "(", "logdir", ",", "plugin_name", ",", "asset_name", ")", ":", "asset_path", "=", "os", ".", "path", ".", "join", "(", "PluginDirectory", "(", "logdir", ",", "plugin_name", ")", ",", "asset_name", ")", "try", ":", "with", "tf", ".", "io", ".", "gfile", ".", "GFile", "(", "asset_path", ",", "\"r\"", ")", "as", "f", ":", "return", "f", ".", "read", "(", ")", "except", "tf", ".", "errors", ".", "NotFoundError", ":", "raise", "KeyError", "(", "\"Asset path %s not found\"", "%", "asset_path", ")", "except", "tf", ".", "errors", ".", "OpError", "as", "e", ":", "raise", "KeyError", "(", "\"Couldn't read asset path: %s, OpError %s\"", "%", "(", "asset_path", ",", "e", ")", ")" ]
Retrieve a particular plugin asset from a logdir. Args: logdir: A directory that was created by a TensorFlow summary.FileWriter. plugin_name: The plugin we want an asset from. asset_name: The name of the requested asset. Returns: string contents of the plugin asset. Raises: KeyError: if the asset does not exist.
[ "Retrieve", "a", "particular", "plugin", "asset", "from", "a", "logdir", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/backend/event_processing/plugin_asset_util.py#L81-L103
train
tensorflow/tensorboard
tensorboard/plugins/distribution/distributions_plugin.py
DistributionsPlugin.distributions_impl
def distributions_impl(self, tag, run): """Result of the form `(body, mime_type)`, or `ValueError`.""" (histograms, mime_type) = self._histograms_plugin.histograms_impl( tag, run, downsample_to=self.SAMPLE_SIZE) return ([self._compress(histogram) for histogram in histograms], mime_type)
python
def distributions_impl(self, tag, run): """Result of the form `(body, mime_type)`, or `ValueError`.""" (histograms, mime_type) = self._histograms_plugin.histograms_impl( tag, run, downsample_to=self.SAMPLE_SIZE) return ([self._compress(histogram) for histogram in histograms], mime_type)
[ "def", "distributions_impl", "(", "self", ",", "tag", ",", "run", ")", ":", "(", "histograms", ",", "mime_type", ")", "=", "self", ".", "_histograms_plugin", ".", "histograms_impl", "(", "tag", ",", "run", ",", "downsample_to", "=", "self", ".", "SAMPLE_SIZE", ")", "return", "(", "[", "self", ".", "_compress", "(", "histogram", ")", "for", "histogram", "in", "histograms", "]", ",", "mime_type", ")" ]
Result of the form `(body, mime_type)`, or `ValueError`.
[ "Result", "of", "the", "form", "(", "body", "mime_type", ")", "or", "ValueError", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/distribution/distributions_plugin.py#L71-L76
train
tensorflow/tensorboard
tensorboard/plugins/distribution/distributions_plugin.py
DistributionsPlugin.distributions_route
def distributions_route(self, request): """Given a tag and single run, return an array of compressed histograms.""" tag = request.args.get('tag') run = request.args.get('run') try: (body, mime_type) = self.distributions_impl(tag, run) code = 200 except ValueError as e: (body, mime_type) = (str(e), 'text/plain') code = 400 return http_util.Respond(request, body, mime_type, code=code)
python
def distributions_route(self, request): """Given a tag and single run, return an array of compressed histograms.""" tag = request.args.get('tag') run = request.args.get('run') try: (body, mime_type) = self.distributions_impl(tag, run) code = 200 except ValueError as e: (body, mime_type) = (str(e), 'text/plain') code = 400 return http_util.Respond(request, body, mime_type, code=code)
[ "def", "distributions_route", "(", "self", ",", "request", ")", ":", "tag", "=", "request", ".", "args", ".", "get", "(", "'tag'", ")", "run", "=", "request", ".", "args", ".", "get", "(", "'run'", ")", "try", ":", "(", "body", ",", "mime_type", ")", "=", "self", ".", "distributions_impl", "(", "tag", ",", "run", ")", "code", "=", "200", "except", "ValueError", "as", "e", ":", "(", "body", ",", "mime_type", ")", "=", "(", "str", "(", "e", ")", ",", "'text/plain'", ")", "code", "=", "400", "return", "http_util", ".", "Respond", "(", "request", ",", "body", ",", "mime_type", ",", "code", "=", "code", ")" ]
Given a tag and single run, return an array of compressed histograms.
[ "Given", "a", "tag", "and", "single", "run", "return", "an", "array", "of", "compressed", "histograms", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/distribution/distributions_plugin.py#L92-L102
train
tensorflow/tensorboard
tensorboard/backend/event_processing/directory_watcher.py
DirectoryWatcher.Load
def Load(self): """Loads new values. The watcher will load from one path at a time; as soon as that path stops yielding events, it will move on to the next path. We assume that old paths are never modified after a newer path has been written. As a result, Load() can be called multiple times in a row without losing events that have not been yielded yet. In other words, we guarantee that every event will be yielded exactly once. Yields: All values that have not been yielded yet. Raises: DirectoryDeletedError: If the directory has been permanently deleted (as opposed to being temporarily unavailable). """ try: for event in self._LoadInternal(): yield event except tf.errors.OpError: if not tf.io.gfile.exists(self._directory): raise DirectoryDeletedError( 'Directory %s has been permanently deleted' % self._directory)
python
def Load(self): """Loads new values. The watcher will load from one path at a time; as soon as that path stops yielding events, it will move on to the next path. We assume that old paths are never modified after a newer path has been written. As a result, Load() can be called multiple times in a row without losing events that have not been yielded yet. In other words, we guarantee that every event will be yielded exactly once. Yields: All values that have not been yielded yet. Raises: DirectoryDeletedError: If the directory has been permanently deleted (as opposed to being temporarily unavailable). """ try: for event in self._LoadInternal(): yield event except tf.errors.OpError: if not tf.io.gfile.exists(self._directory): raise DirectoryDeletedError( 'Directory %s has been permanently deleted' % self._directory)
[ "def", "Load", "(", "self", ")", ":", "try", ":", "for", "event", "in", "self", ".", "_LoadInternal", "(", ")", ":", "yield", "event", "except", "tf", ".", "errors", ".", "OpError", ":", "if", "not", "tf", ".", "io", ".", "gfile", ".", "exists", "(", "self", ".", "_directory", ")", ":", "raise", "DirectoryDeletedError", "(", "'Directory %s has been permanently deleted'", "%", "self", ".", "_directory", ")" ]
Loads new values. The watcher will load from one path at a time; as soon as that path stops yielding events, it will move on to the next path. We assume that old paths are never modified after a newer path has been written. As a result, Load() can be called multiple times in a row without losing events that have not been yielded yet. In other words, we guarantee that every event will be yielded exactly once. Yields: All values that have not been yielded yet. Raises: DirectoryDeletedError: If the directory has been permanently deleted (as opposed to being temporarily unavailable).
[ "Loads", "new", "values", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/backend/event_processing/directory_watcher.py#L71-L94
train
tensorflow/tensorboard
tensorboard/backend/event_processing/directory_watcher.py
DirectoryWatcher._LoadInternal
def _LoadInternal(self): """Internal implementation of Load(). The only difference between this and Load() is that the latter will throw DirectoryDeletedError on I/O errors if it thinks that the directory has been permanently deleted. Yields: All values that have not been yielded yet. """ # If the loader exists, check it for a value. if not self._loader: self._InitializeLoader() while True: # Yield all the new events in the path we're currently loading from. for event in self._loader.Load(): yield event next_path = self._GetNextPath() if not next_path: logger.info('No path found after %s', self._path) # Current path is empty and there are no new paths, so we're done. return # There's a new path, so check to make sure there weren't any events # written between when we finished reading the current path and when we # checked for the new one. The sequence of events might look something # like this: # # 1. Event #1 written to path #1. # 2. We check for events and yield event #1 from path #1 # 3. We check for events and see that there are no more events in path #1. # 4. Event #2 is written to path #1. # 5. Event #3 is written to path #2. # 6. We check for a new path and see that path #2 exists. # # Without this loop, we would miss event #2. We're also guaranteed by the # loader contract that no more events will be written to path #1 after # events start being written to path #2, so we don't have to worry about # that. for event in self._loader.Load(): yield event logger.info('Directory watcher advancing from %s to %s', self._path, next_path) # Advance to the next path and start over. self._SetPath(next_path)
python
def _LoadInternal(self): """Internal implementation of Load(). The only difference between this and Load() is that the latter will throw DirectoryDeletedError on I/O errors if it thinks that the directory has been permanently deleted. Yields: All values that have not been yielded yet. """ # If the loader exists, check it for a value. if not self._loader: self._InitializeLoader() while True: # Yield all the new events in the path we're currently loading from. for event in self._loader.Load(): yield event next_path = self._GetNextPath() if not next_path: logger.info('No path found after %s', self._path) # Current path is empty and there are no new paths, so we're done. return # There's a new path, so check to make sure there weren't any events # written between when we finished reading the current path and when we # checked for the new one. The sequence of events might look something # like this: # # 1. Event #1 written to path #1. # 2. We check for events and yield event #1 from path #1 # 3. We check for events and see that there are no more events in path #1. # 4. Event #2 is written to path #1. # 5. Event #3 is written to path #2. # 6. We check for a new path and see that path #2 exists. # # Without this loop, we would miss event #2. We're also guaranteed by the # loader contract that no more events will be written to path #1 after # events start being written to path #2, so we don't have to worry about # that. for event in self._loader.Load(): yield event logger.info('Directory watcher advancing from %s to %s', self._path, next_path) # Advance to the next path and start over. self._SetPath(next_path)
[ "def", "_LoadInternal", "(", "self", ")", ":", "# If the loader exists, check it for a value.", "if", "not", "self", ".", "_loader", ":", "self", ".", "_InitializeLoader", "(", ")", "while", "True", ":", "# Yield all the new events in the path we're currently loading from.", "for", "event", "in", "self", ".", "_loader", ".", "Load", "(", ")", ":", "yield", "event", "next_path", "=", "self", ".", "_GetNextPath", "(", ")", "if", "not", "next_path", ":", "logger", ".", "info", "(", "'No path found after %s'", ",", "self", ".", "_path", ")", "# Current path is empty and there are no new paths, so we're done.", "return", "# There's a new path, so check to make sure there weren't any events", "# written between when we finished reading the current path and when we", "# checked for the new one. The sequence of events might look something", "# like this:", "#", "# 1. Event #1 written to path #1.", "# 2. We check for events and yield event #1 from path #1", "# 3. We check for events and see that there are no more events in path #1.", "# 4. Event #2 is written to path #1.", "# 5. Event #3 is written to path #2.", "# 6. We check for a new path and see that path #2 exists.", "#", "# Without this loop, we would miss event #2. We're also guaranteed by the", "# loader contract that no more events will be written to path #1 after", "# events start being written to path #2, so we don't have to worry about", "# that.", "for", "event", "in", "self", ".", "_loader", ".", "Load", "(", ")", ":", "yield", "event", "logger", ".", "info", "(", "'Directory watcher advancing from %s to %s'", ",", "self", ".", "_path", ",", "next_path", ")", "# Advance to the next path and start over.", "self", ".", "_SetPath", "(", "next_path", ")" ]
Internal implementation of Load(). The only difference between this and Load() is that the latter will throw DirectoryDeletedError on I/O errors if it thinks that the directory has been permanently deleted. Yields: All values that have not been yielded yet.
[ "Internal", "implementation", "of", "Load", "()", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/backend/event_processing/directory_watcher.py#L96-L145
train
tensorflow/tensorboard
tensorboard/backend/event_processing/directory_watcher.py
DirectoryWatcher._SetPath
def _SetPath(self, path): """Sets the current path to watch for new events. This also records the size of the old path, if any. If the size can't be found, an error is logged. Args: path: The full path of the file to watch. """ old_path = self._path if old_path and not io_wrapper.IsCloudPath(old_path): try: # We're done with the path, so store its size. size = tf.io.gfile.stat(old_path).length logger.debug('Setting latest size of %s to %d', old_path, size) self._finalized_sizes[old_path] = size except tf.errors.OpError as e: logger.error('Unable to get size of %s: %s', old_path, e) self._path = path self._loader = self._loader_factory(path)
python
def _SetPath(self, path): """Sets the current path to watch for new events. This also records the size of the old path, if any. If the size can't be found, an error is logged. Args: path: The full path of the file to watch. """ old_path = self._path if old_path and not io_wrapper.IsCloudPath(old_path): try: # We're done with the path, so store its size. size = tf.io.gfile.stat(old_path).length logger.debug('Setting latest size of %s to %d', old_path, size) self._finalized_sizes[old_path] = size except tf.errors.OpError as e: logger.error('Unable to get size of %s: %s', old_path, e) self._path = path self._loader = self._loader_factory(path)
[ "def", "_SetPath", "(", "self", ",", "path", ")", ":", "old_path", "=", "self", ".", "_path", "if", "old_path", "and", "not", "io_wrapper", ".", "IsCloudPath", "(", "old_path", ")", ":", "try", ":", "# We're done with the path, so store its size.", "size", "=", "tf", ".", "io", ".", "gfile", ".", "stat", "(", "old_path", ")", ".", "length", "logger", ".", "debug", "(", "'Setting latest size of %s to %d'", ",", "old_path", ",", "size", ")", "self", ".", "_finalized_sizes", "[", "old_path", "]", "=", "size", "except", "tf", ".", "errors", ".", "OpError", "as", "e", ":", "logger", ".", "error", "(", "'Unable to get size of %s: %s'", ",", "old_path", ",", "e", ")", "self", ".", "_path", "=", "path", "self", ".", "_loader", "=", "self", ".", "_loader_factory", "(", "path", ")" ]
Sets the current path to watch for new events. This also records the size of the old path, if any. If the size can't be found, an error is logged. Args: path: The full path of the file to watch.
[ "Sets", "the", "current", "path", "to", "watch", "for", "new", "events", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/backend/event_processing/directory_watcher.py#L172-L192
train
tensorflow/tensorboard
tensorboard/backend/event_processing/directory_watcher.py
DirectoryWatcher._GetNextPath
def _GetNextPath(self): """Gets the next path to load from. This function also does the checking for out-of-order writes as it iterates through the paths. Returns: The next path to load events from, or None if there are no more paths. """ paths = sorted(path for path in io_wrapper.ListDirectoryAbsolute(self._directory) if self._path_filter(path)) if not paths: return None if self._path is None: return paths[0] # Don't bother checking if the paths are GCS (which we can't check) or if # we've already detected an OOO write. if not io_wrapper.IsCloudPath(paths[0]) and not self._ooo_writes_detected: # Check the previous _OOO_WRITE_CHECK_COUNT paths for out of order writes. current_path_index = bisect.bisect_left(paths, self._path) ooo_check_start = max(0, current_path_index - self._OOO_WRITE_CHECK_COUNT) for path in paths[ooo_check_start:current_path_index]: if self._HasOOOWrite(path): self._ooo_writes_detected = True break next_paths = list(path for path in paths if self._path is None or path > self._path) if next_paths: return min(next_paths) else: return None
python
def _GetNextPath(self): """Gets the next path to load from. This function also does the checking for out-of-order writes as it iterates through the paths. Returns: The next path to load events from, or None if there are no more paths. """ paths = sorted(path for path in io_wrapper.ListDirectoryAbsolute(self._directory) if self._path_filter(path)) if not paths: return None if self._path is None: return paths[0] # Don't bother checking if the paths are GCS (which we can't check) or if # we've already detected an OOO write. if not io_wrapper.IsCloudPath(paths[0]) and not self._ooo_writes_detected: # Check the previous _OOO_WRITE_CHECK_COUNT paths for out of order writes. current_path_index = bisect.bisect_left(paths, self._path) ooo_check_start = max(0, current_path_index - self._OOO_WRITE_CHECK_COUNT) for path in paths[ooo_check_start:current_path_index]: if self._HasOOOWrite(path): self._ooo_writes_detected = True break next_paths = list(path for path in paths if self._path is None or path > self._path) if next_paths: return min(next_paths) else: return None
[ "def", "_GetNextPath", "(", "self", ")", ":", "paths", "=", "sorted", "(", "path", "for", "path", "in", "io_wrapper", ".", "ListDirectoryAbsolute", "(", "self", ".", "_directory", ")", "if", "self", ".", "_path_filter", "(", "path", ")", ")", "if", "not", "paths", ":", "return", "None", "if", "self", ".", "_path", "is", "None", ":", "return", "paths", "[", "0", "]", "# Don't bother checking if the paths are GCS (which we can't check) or if", "# we've already detected an OOO write.", "if", "not", "io_wrapper", ".", "IsCloudPath", "(", "paths", "[", "0", "]", ")", "and", "not", "self", ".", "_ooo_writes_detected", ":", "# Check the previous _OOO_WRITE_CHECK_COUNT paths for out of order writes.", "current_path_index", "=", "bisect", ".", "bisect_left", "(", "paths", ",", "self", ".", "_path", ")", "ooo_check_start", "=", "max", "(", "0", ",", "current_path_index", "-", "self", ".", "_OOO_WRITE_CHECK_COUNT", ")", "for", "path", "in", "paths", "[", "ooo_check_start", ":", "current_path_index", "]", ":", "if", "self", ".", "_HasOOOWrite", "(", "path", ")", ":", "self", ".", "_ooo_writes_detected", "=", "True", "break", "next_paths", "=", "list", "(", "path", "for", "path", "in", "paths", "if", "self", ".", "_path", "is", "None", "or", "path", ">", "self", ".", "_path", ")", "if", "next_paths", ":", "return", "min", "(", "next_paths", ")", "else", ":", "return", "None" ]
Gets the next path to load from. This function also does the checking for out-of-order writes as it iterates through the paths. Returns: The next path to load events from, or None if there are no more paths.
[ "Gets", "the", "next", "path", "to", "load", "from", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/backend/event_processing/directory_watcher.py#L194-L229
train
tensorflow/tensorboard
tensorboard/backend/event_processing/directory_watcher.py
DirectoryWatcher._HasOOOWrite
def _HasOOOWrite(self, path): """Returns whether the path has had an out-of-order write.""" # Check the sizes of each path before the current one. size = tf.io.gfile.stat(path).length old_size = self._finalized_sizes.get(path, None) if size != old_size: if old_size is None: logger.error('File %s created after file %s even though it\'s ' 'lexicographically earlier', path, self._path) else: logger.error('File %s updated even though the current file is %s', path, self._path) return True else: return False
python
def _HasOOOWrite(self, path): """Returns whether the path has had an out-of-order write.""" # Check the sizes of each path before the current one. size = tf.io.gfile.stat(path).length old_size = self._finalized_sizes.get(path, None) if size != old_size: if old_size is None: logger.error('File %s created after file %s even though it\'s ' 'lexicographically earlier', path, self._path) else: logger.error('File %s updated even though the current file is %s', path, self._path) return True else: return False
[ "def", "_HasOOOWrite", "(", "self", ",", "path", ")", ":", "# Check the sizes of each path before the current one.", "size", "=", "tf", ".", "io", ".", "gfile", ".", "stat", "(", "path", ")", ".", "length", "old_size", "=", "self", ".", "_finalized_sizes", ".", "get", "(", "path", ",", "None", ")", "if", "size", "!=", "old_size", ":", "if", "old_size", "is", "None", ":", "logger", ".", "error", "(", "'File %s created after file %s even though it\\'s '", "'lexicographically earlier'", ",", "path", ",", "self", ".", "_path", ")", "else", ":", "logger", ".", "error", "(", "'File %s updated even though the current file is %s'", ",", "path", ",", "self", ".", "_path", ")", "return", "True", "else", ":", "return", "False" ]
Returns whether the path has had an out-of-order write.
[ "Returns", "whether", "the", "path", "has", "had", "an", "out", "-", "of", "-", "order", "write", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/backend/event_processing/directory_watcher.py#L231-L245
train
tensorflow/tensorboard
tensorboard/plugins/interactive_inference/utils/platform_utils.py
example_protos_from_path
def example_protos_from_path(path, num_examples=10, start_index=0, parse_examples=True, sampling_odds=1, example_class=tf.train.Example): """Returns a number of examples from the provided path. Args: path: A string path to the examples. num_examples: The maximum number of examples to return from the path. parse_examples: If true then parses the serialized proto from the path into proto objects. Defaults to True. sampling_odds: Odds of loading an example, used for sampling. When >= 1 (the default), then all examples are loaded. example_class: tf.train.Example or tf.train.SequenceExample class to load. Defaults to tf.train.Example. Returns: A list of Example protos or serialized proto strings at the path. Raises: InvalidUserInputError: If examples cannot be procured from the path. """ def append_examples_from_iterable(iterable, examples): for value in iterable: if sampling_odds >= 1 or random.random() < sampling_odds: examples.append( example_class.FromString(value) if parse_examples else value) if len(examples) >= num_examples: return examples = [] if path.endswith('.csv'): def are_floats(values): for value in values: try: float(value) except ValueError: return False return True csv.register_dialect('CsvDialect', skipinitialspace=True) rows = csv.DictReader(open(path), dialect='CsvDialect') for row in rows: if sampling_odds < 1 and random.random() > sampling_odds: continue example = tf.train.Example() for col in row.keys(): # Parse out individual values from vertical-bar-delimited lists values = [val.strip() for val in row[col].split('|')] if are_floats(values): example.features.feature[col].float_list.value.extend( [float(val) for val in values]) else: example.features.feature[col].bytes_list.value.extend( [val.encode('utf-8') for val in values]) examples.append( example if parse_examples else example.SerializeToString()) if len(examples) >= num_examples: break return examples filenames = filepath_to_filepath_list(path) compression_types = [ '', # no compression (distinct from `None`!) 'GZIP', 'ZLIB', ] current_compression_idx = 0 current_file_index = 0 while (current_file_index < len(filenames) and current_compression_idx < len(compression_types)): try: record_iterator = tf.compat.v1.python_io.tf_record_iterator( path=filenames[current_file_index], options=tf.io.TFRecordOptions( compression_types[current_compression_idx])) append_examples_from_iterable(record_iterator, examples) current_file_index += 1 if len(examples) >= num_examples: break except tf.errors.DataLossError: current_compression_idx += 1 except (IOError, tf.errors.NotFoundError) as e: raise common_utils.InvalidUserInputError(e) if examples: return examples else: raise common_utils.InvalidUserInputError( 'No examples found at ' + path + '. Valid formats are TFRecord files.')
python
def example_protos_from_path(path, num_examples=10, start_index=0, parse_examples=True, sampling_odds=1, example_class=tf.train.Example): """Returns a number of examples from the provided path. Args: path: A string path to the examples. num_examples: The maximum number of examples to return from the path. parse_examples: If true then parses the serialized proto from the path into proto objects. Defaults to True. sampling_odds: Odds of loading an example, used for sampling. When >= 1 (the default), then all examples are loaded. example_class: tf.train.Example or tf.train.SequenceExample class to load. Defaults to tf.train.Example. Returns: A list of Example protos or serialized proto strings at the path. Raises: InvalidUserInputError: If examples cannot be procured from the path. """ def append_examples_from_iterable(iterable, examples): for value in iterable: if sampling_odds >= 1 or random.random() < sampling_odds: examples.append( example_class.FromString(value) if parse_examples else value) if len(examples) >= num_examples: return examples = [] if path.endswith('.csv'): def are_floats(values): for value in values: try: float(value) except ValueError: return False return True csv.register_dialect('CsvDialect', skipinitialspace=True) rows = csv.DictReader(open(path), dialect='CsvDialect') for row in rows: if sampling_odds < 1 and random.random() > sampling_odds: continue example = tf.train.Example() for col in row.keys(): # Parse out individual values from vertical-bar-delimited lists values = [val.strip() for val in row[col].split('|')] if are_floats(values): example.features.feature[col].float_list.value.extend( [float(val) for val in values]) else: example.features.feature[col].bytes_list.value.extend( [val.encode('utf-8') for val in values]) examples.append( example if parse_examples else example.SerializeToString()) if len(examples) >= num_examples: break return examples filenames = filepath_to_filepath_list(path) compression_types = [ '', # no compression (distinct from `None`!) 'GZIP', 'ZLIB', ] current_compression_idx = 0 current_file_index = 0 while (current_file_index < len(filenames) and current_compression_idx < len(compression_types)): try: record_iterator = tf.compat.v1.python_io.tf_record_iterator( path=filenames[current_file_index], options=tf.io.TFRecordOptions( compression_types[current_compression_idx])) append_examples_from_iterable(record_iterator, examples) current_file_index += 1 if len(examples) >= num_examples: break except tf.errors.DataLossError: current_compression_idx += 1 except (IOError, tf.errors.NotFoundError) as e: raise common_utils.InvalidUserInputError(e) if examples: return examples else: raise common_utils.InvalidUserInputError( 'No examples found at ' + path + '. Valid formats are TFRecord files.')
[ "def", "example_protos_from_path", "(", "path", ",", "num_examples", "=", "10", ",", "start_index", "=", "0", ",", "parse_examples", "=", "True", ",", "sampling_odds", "=", "1", ",", "example_class", "=", "tf", ".", "train", ".", "Example", ")", ":", "def", "append_examples_from_iterable", "(", "iterable", ",", "examples", ")", ":", "for", "value", "in", "iterable", ":", "if", "sampling_odds", ">=", "1", "or", "random", ".", "random", "(", ")", "<", "sampling_odds", ":", "examples", ".", "append", "(", "example_class", ".", "FromString", "(", "value", ")", "if", "parse_examples", "else", "value", ")", "if", "len", "(", "examples", ")", ">=", "num_examples", ":", "return", "examples", "=", "[", "]", "if", "path", ".", "endswith", "(", "'.csv'", ")", ":", "def", "are_floats", "(", "values", ")", ":", "for", "value", "in", "values", ":", "try", ":", "float", "(", "value", ")", "except", "ValueError", ":", "return", "False", "return", "True", "csv", ".", "register_dialect", "(", "'CsvDialect'", ",", "skipinitialspace", "=", "True", ")", "rows", "=", "csv", ".", "DictReader", "(", "open", "(", "path", ")", ",", "dialect", "=", "'CsvDialect'", ")", "for", "row", "in", "rows", ":", "if", "sampling_odds", "<", "1", "and", "random", ".", "random", "(", ")", ">", "sampling_odds", ":", "continue", "example", "=", "tf", ".", "train", ".", "Example", "(", ")", "for", "col", "in", "row", ".", "keys", "(", ")", ":", "# Parse out individual values from vertical-bar-delimited lists", "values", "=", "[", "val", ".", "strip", "(", ")", "for", "val", "in", "row", "[", "col", "]", ".", "split", "(", "'|'", ")", "]", "if", "are_floats", "(", "values", ")", ":", "example", ".", "features", ".", "feature", "[", "col", "]", ".", "float_list", ".", "value", ".", "extend", "(", "[", "float", "(", "val", ")", "for", "val", "in", "values", "]", ")", "else", ":", "example", ".", "features", ".", "feature", "[", "col", "]", ".", "bytes_list", ".", "value", ".", "extend", "(", "[", "val", ".", "encode", "(", "'utf-8'", ")", "for", "val", "in", "values", "]", ")", "examples", ".", "append", "(", "example", "if", "parse_examples", "else", "example", ".", "SerializeToString", "(", ")", ")", "if", "len", "(", "examples", ")", ">=", "num_examples", ":", "break", "return", "examples", "filenames", "=", "filepath_to_filepath_list", "(", "path", ")", "compression_types", "=", "[", "''", ",", "# no compression (distinct from `None`!)", "'GZIP'", ",", "'ZLIB'", ",", "]", "current_compression_idx", "=", "0", "current_file_index", "=", "0", "while", "(", "current_file_index", "<", "len", "(", "filenames", ")", "and", "current_compression_idx", "<", "len", "(", "compression_types", ")", ")", ":", "try", ":", "record_iterator", "=", "tf", ".", "compat", ".", "v1", ".", "python_io", ".", "tf_record_iterator", "(", "path", "=", "filenames", "[", "current_file_index", "]", ",", "options", "=", "tf", ".", "io", ".", "TFRecordOptions", "(", "compression_types", "[", "current_compression_idx", "]", ")", ")", "append_examples_from_iterable", "(", "record_iterator", ",", "examples", ")", "current_file_index", "+=", "1", "if", "len", "(", "examples", ")", ">=", "num_examples", ":", "break", "except", "tf", ".", "errors", ".", "DataLossError", ":", "current_compression_idx", "+=", "1", "except", "(", "IOError", ",", "tf", ".", "errors", ".", "NotFoundError", ")", "as", "e", ":", "raise", "common_utils", ".", "InvalidUserInputError", "(", "e", ")", "if", "examples", ":", "return", "examples", "else", ":", "raise", "common_utils", ".", "InvalidUserInputError", "(", "'No examples found at '", "+", "path", "+", "'. Valid formats are TFRecord files.'", ")" ]
Returns a number of examples from the provided path. Args: path: A string path to the examples. num_examples: The maximum number of examples to return from the path. parse_examples: If true then parses the serialized proto from the path into proto objects. Defaults to True. sampling_odds: Odds of loading an example, used for sampling. When >= 1 (the default), then all examples are loaded. example_class: tf.train.Example or tf.train.SequenceExample class to load. Defaults to tf.train.Example. Returns: A list of Example protos or serialized proto strings at the path. Raises: InvalidUserInputError: If examples cannot be procured from the path.
[ "Returns", "a", "number", "of", "examples", "from", "the", "provided", "path", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/interactive_inference/utils/platform_utils.py#L65-L158
train
tensorflow/tensorboard
tensorboard/plugins/interactive_inference/utils/platform_utils.py
call_servo
def call_servo(examples, serving_bundle): """Send an RPC request to the Servomatic prediction service. Args: examples: A list of examples that matches the model spec. serving_bundle: A `ServingBundle` object that contains the information to make the serving request. Returns: A ClassificationResponse or RegressionResponse proto. """ parsed_url = urlparse('http://' + serving_bundle.inference_address) channel = implementations.insecure_channel(parsed_url.hostname, parsed_url.port) stub = prediction_service_pb2.beta_create_PredictionService_stub(channel) if serving_bundle.use_predict: request = predict_pb2.PredictRequest() elif serving_bundle.model_type == 'classification': request = classification_pb2.ClassificationRequest() else: request = regression_pb2.RegressionRequest() request.model_spec.name = serving_bundle.model_name if serving_bundle.model_version is not None: request.model_spec.version.value = serving_bundle.model_version if serving_bundle.signature is not None: request.model_spec.signature_name = serving_bundle.signature if serving_bundle.use_predict: # tf.compat.v1 API used here to convert tf.example into proto. This # utility file is bundled in the witwidget pip package which has a dep # on TensorFlow. request.inputs[serving_bundle.predict_input_tensor].CopyFrom( tf.compat.v1.make_tensor_proto( values=[ex.SerializeToString() for ex in examples], dtype=types_pb2.DT_STRING)) else: request.input.example_list.examples.extend(examples) if serving_bundle.use_predict: return common_utils.convert_predict_response( stub.Predict(request, 30.0), serving_bundle) # 30 secs timeout elif serving_bundle.model_type == 'classification': return stub.Classify(request, 30.0) # 30 secs timeout else: return stub.Regress(request, 30.0)
python
def call_servo(examples, serving_bundle): """Send an RPC request to the Servomatic prediction service. Args: examples: A list of examples that matches the model spec. serving_bundle: A `ServingBundle` object that contains the information to make the serving request. Returns: A ClassificationResponse or RegressionResponse proto. """ parsed_url = urlparse('http://' + serving_bundle.inference_address) channel = implementations.insecure_channel(parsed_url.hostname, parsed_url.port) stub = prediction_service_pb2.beta_create_PredictionService_stub(channel) if serving_bundle.use_predict: request = predict_pb2.PredictRequest() elif serving_bundle.model_type == 'classification': request = classification_pb2.ClassificationRequest() else: request = regression_pb2.RegressionRequest() request.model_spec.name = serving_bundle.model_name if serving_bundle.model_version is not None: request.model_spec.version.value = serving_bundle.model_version if serving_bundle.signature is not None: request.model_spec.signature_name = serving_bundle.signature if serving_bundle.use_predict: # tf.compat.v1 API used here to convert tf.example into proto. This # utility file is bundled in the witwidget pip package which has a dep # on TensorFlow. request.inputs[serving_bundle.predict_input_tensor].CopyFrom( tf.compat.v1.make_tensor_proto( values=[ex.SerializeToString() for ex in examples], dtype=types_pb2.DT_STRING)) else: request.input.example_list.examples.extend(examples) if serving_bundle.use_predict: return common_utils.convert_predict_response( stub.Predict(request, 30.0), serving_bundle) # 30 secs timeout elif serving_bundle.model_type == 'classification': return stub.Classify(request, 30.0) # 30 secs timeout else: return stub.Regress(request, 30.0)
[ "def", "call_servo", "(", "examples", ",", "serving_bundle", ")", ":", "parsed_url", "=", "urlparse", "(", "'http://'", "+", "serving_bundle", ".", "inference_address", ")", "channel", "=", "implementations", ".", "insecure_channel", "(", "parsed_url", ".", "hostname", ",", "parsed_url", ".", "port", ")", "stub", "=", "prediction_service_pb2", ".", "beta_create_PredictionService_stub", "(", "channel", ")", "if", "serving_bundle", ".", "use_predict", ":", "request", "=", "predict_pb2", ".", "PredictRequest", "(", ")", "elif", "serving_bundle", ".", "model_type", "==", "'classification'", ":", "request", "=", "classification_pb2", ".", "ClassificationRequest", "(", ")", "else", ":", "request", "=", "regression_pb2", ".", "RegressionRequest", "(", ")", "request", ".", "model_spec", ".", "name", "=", "serving_bundle", ".", "model_name", "if", "serving_bundle", ".", "model_version", "is", "not", "None", ":", "request", ".", "model_spec", ".", "version", ".", "value", "=", "serving_bundle", ".", "model_version", "if", "serving_bundle", ".", "signature", "is", "not", "None", ":", "request", ".", "model_spec", ".", "signature_name", "=", "serving_bundle", ".", "signature", "if", "serving_bundle", ".", "use_predict", ":", "# tf.compat.v1 API used here to convert tf.example into proto. This", "# utility file is bundled in the witwidget pip package which has a dep", "# on TensorFlow.", "request", ".", "inputs", "[", "serving_bundle", ".", "predict_input_tensor", "]", ".", "CopyFrom", "(", "tf", ".", "compat", ".", "v1", ".", "make_tensor_proto", "(", "values", "=", "[", "ex", ".", "SerializeToString", "(", ")", "for", "ex", "in", "examples", "]", ",", "dtype", "=", "types_pb2", ".", "DT_STRING", ")", ")", "else", ":", "request", ".", "input", ".", "example_list", ".", "examples", ".", "extend", "(", "examples", ")", "if", "serving_bundle", ".", "use_predict", ":", "return", "common_utils", ".", "convert_predict_response", "(", "stub", ".", "Predict", "(", "request", ",", "30.0", ")", ",", "serving_bundle", ")", "# 30 secs timeout", "elif", "serving_bundle", ".", "model_type", "==", "'classification'", ":", "return", "stub", ".", "Classify", "(", "request", ",", "30.0", ")", "# 30 secs timeout", "else", ":", "return", "stub", ".", "Regress", "(", "request", ",", "30.0", ")" ]
Send an RPC request to the Servomatic prediction service. Args: examples: A list of examples that matches the model spec. serving_bundle: A `ServingBundle` object that contains the information to make the serving request. Returns: A ClassificationResponse or RegressionResponse proto.
[ "Send", "an", "RPC", "request", "to", "the", "Servomatic", "prediction", "service", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/interactive_inference/utils/platform_utils.py#L160-L205
train
tensorflow/tensorboard
tensorboard/data_compat.py
migrate_value
def migrate_value(value): """Convert `value` to a new-style value, if necessary and possible. An "old-style" value is a value that uses any `value` field other than the `tensor` field. A "new-style" value is a value that uses the `tensor` field. TensorBoard continues to support old-style values on disk; this method converts them to new-style values so that further code need only deal with one data format. Arguments: value: A `Summary.Value` object. This argument is not modified. Returns: If the `value` is an old-style value for which there is a new-style equivalent, the result is the new-style value. Otherwise---if the value is already new-style or does not yet have a new-style equivalent---the value will be returned unchanged. :type value: Summary.Value :rtype: Summary.Value """ handler = { 'histo': _migrate_histogram_value, 'image': _migrate_image_value, 'audio': _migrate_audio_value, 'simple_value': _migrate_scalar_value, }.get(value.WhichOneof('value')) return handler(value) if handler else value
python
def migrate_value(value): """Convert `value` to a new-style value, if necessary and possible. An "old-style" value is a value that uses any `value` field other than the `tensor` field. A "new-style" value is a value that uses the `tensor` field. TensorBoard continues to support old-style values on disk; this method converts them to new-style values so that further code need only deal with one data format. Arguments: value: A `Summary.Value` object. This argument is not modified. Returns: If the `value` is an old-style value for which there is a new-style equivalent, the result is the new-style value. Otherwise---if the value is already new-style or does not yet have a new-style equivalent---the value will be returned unchanged. :type value: Summary.Value :rtype: Summary.Value """ handler = { 'histo': _migrate_histogram_value, 'image': _migrate_image_value, 'audio': _migrate_audio_value, 'simple_value': _migrate_scalar_value, }.get(value.WhichOneof('value')) return handler(value) if handler else value
[ "def", "migrate_value", "(", "value", ")", ":", "handler", "=", "{", "'histo'", ":", "_migrate_histogram_value", ",", "'image'", ":", "_migrate_image_value", ",", "'audio'", ":", "_migrate_audio_value", ",", "'simple_value'", ":", "_migrate_scalar_value", ",", "}", ".", "get", "(", "value", ".", "WhichOneof", "(", "'value'", ")", ")", "return", "handler", "(", "value", ")", "if", "handler", "else", "value" ]
Convert `value` to a new-style value, if necessary and possible. An "old-style" value is a value that uses any `value` field other than the `tensor` field. A "new-style" value is a value that uses the `tensor` field. TensorBoard continues to support old-style values on disk; this method converts them to new-style values so that further code need only deal with one data format. Arguments: value: A `Summary.Value` object. This argument is not modified. Returns: If the `value` is an old-style value for which there is a new-style equivalent, the result is the new-style value. Otherwise---if the value is already new-style or does not yet have a new-style equivalent---the value will be returned unchanged. :type value: Summary.Value :rtype: Summary.Value
[ "Convert", "value", "to", "a", "new", "-", "style", "value", "if", "necessary", "and", "possible", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/data_compat.py#L32-L59
train
tensorflow/tensorboard
tensorboard/plugins/interactive_inference/interactive_inference_plugin.py
InteractiveInferencePlugin.get_plugin_apps
def get_plugin_apps(self): """Obtains a mapping between routes and handlers. Stores the logdir. Returns: A mapping between routes and handlers (functions that respond to requests). """ return { '/infer': self._infer, '/update_example': self._update_example, '/examples_from_path': self._examples_from_path_handler, '/sprite': self._serve_sprite, '/duplicate_example': self._duplicate_example, '/delete_example': self._delete_example, '/infer_mutants': self._infer_mutants_handler, '/eligible_features': self._eligible_features_from_example_handler, }
python
def get_plugin_apps(self): """Obtains a mapping between routes and handlers. Stores the logdir. Returns: A mapping between routes and handlers (functions that respond to requests). """ return { '/infer': self._infer, '/update_example': self._update_example, '/examples_from_path': self._examples_from_path_handler, '/sprite': self._serve_sprite, '/duplicate_example': self._duplicate_example, '/delete_example': self._delete_example, '/infer_mutants': self._infer_mutants_handler, '/eligible_features': self._eligible_features_from_example_handler, }
[ "def", "get_plugin_apps", "(", "self", ")", ":", "return", "{", "'/infer'", ":", "self", ".", "_infer", ",", "'/update_example'", ":", "self", ".", "_update_example", ",", "'/examples_from_path'", ":", "self", ".", "_examples_from_path_handler", ",", "'/sprite'", ":", "self", ".", "_serve_sprite", ",", "'/duplicate_example'", ":", "self", ".", "_duplicate_example", ",", "'/delete_example'", ":", "self", ".", "_delete_example", ",", "'/infer_mutants'", ":", "self", ".", "_infer_mutants_handler", ",", "'/eligible_features'", ":", "self", ".", "_eligible_features_from_example_handler", ",", "}" ]
Obtains a mapping between routes and handlers. Stores the logdir. Returns: A mapping between routes and handlers (functions that respond to requests).
[ "Obtains", "a", "mapping", "between", "routes", "and", "handlers", ".", "Stores", "the", "logdir", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/interactive_inference/interactive_inference_plugin.py#L84-L100
train
tensorflow/tensorboard
tensorboard/plugins/interactive_inference/interactive_inference_plugin.py
InteractiveInferencePlugin._examples_from_path_handler
def _examples_from_path_handler(self, request): """Returns JSON of the specified examples. Args: request: A request that should contain 'examples_path' and 'max_examples'. Returns: JSON of up to max_examlpes of the examples in the path. """ examples_count = int(request.args.get('max_examples')) examples_path = request.args.get('examples_path') sampling_odds = float(request.args.get('sampling_odds')) self.example_class = (tf.train.SequenceExample if request.args.get('sequence_examples') == 'true' else tf.train.Example) try: platform_utils.throw_if_file_access_not_allowed(examples_path, self._logdir, self._has_auth_group) example_strings = platform_utils.example_protos_from_path( examples_path, examples_count, parse_examples=False, sampling_odds=sampling_odds, example_class=self.example_class) self.examples = [ self.example_class.FromString(ex) for ex in example_strings] self.generate_sprite(example_strings) json_examples = [ json_format.MessageToJson(example) for example in self.examples ] self.updated_example_indices = set(range(len(json_examples))) return http_util.Respond( request, {'examples': json_examples, 'sprite': True if self.sprite else False}, 'application/json') except common_utils.InvalidUserInputError as e: return http_util.Respond(request, {'error': e.message}, 'application/json', code=400)
python
def _examples_from_path_handler(self, request): """Returns JSON of the specified examples. Args: request: A request that should contain 'examples_path' and 'max_examples'. Returns: JSON of up to max_examlpes of the examples in the path. """ examples_count = int(request.args.get('max_examples')) examples_path = request.args.get('examples_path') sampling_odds = float(request.args.get('sampling_odds')) self.example_class = (tf.train.SequenceExample if request.args.get('sequence_examples') == 'true' else tf.train.Example) try: platform_utils.throw_if_file_access_not_allowed(examples_path, self._logdir, self._has_auth_group) example_strings = platform_utils.example_protos_from_path( examples_path, examples_count, parse_examples=False, sampling_odds=sampling_odds, example_class=self.example_class) self.examples = [ self.example_class.FromString(ex) for ex in example_strings] self.generate_sprite(example_strings) json_examples = [ json_format.MessageToJson(example) for example in self.examples ] self.updated_example_indices = set(range(len(json_examples))) return http_util.Respond( request, {'examples': json_examples, 'sprite': True if self.sprite else False}, 'application/json') except common_utils.InvalidUserInputError as e: return http_util.Respond(request, {'error': e.message}, 'application/json', code=400)
[ "def", "_examples_from_path_handler", "(", "self", ",", "request", ")", ":", "examples_count", "=", "int", "(", "request", ".", "args", ".", "get", "(", "'max_examples'", ")", ")", "examples_path", "=", "request", ".", "args", ".", "get", "(", "'examples_path'", ")", "sampling_odds", "=", "float", "(", "request", ".", "args", ".", "get", "(", "'sampling_odds'", ")", ")", "self", ".", "example_class", "=", "(", "tf", ".", "train", ".", "SequenceExample", "if", "request", ".", "args", ".", "get", "(", "'sequence_examples'", ")", "==", "'true'", "else", "tf", ".", "train", ".", "Example", ")", "try", ":", "platform_utils", ".", "throw_if_file_access_not_allowed", "(", "examples_path", ",", "self", ".", "_logdir", ",", "self", ".", "_has_auth_group", ")", "example_strings", "=", "platform_utils", ".", "example_protos_from_path", "(", "examples_path", ",", "examples_count", ",", "parse_examples", "=", "False", ",", "sampling_odds", "=", "sampling_odds", ",", "example_class", "=", "self", ".", "example_class", ")", "self", ".", "examples", "=", "[", "self", ".", "example_class", ".", "FromString", "(", "ex", ")", "for", "ex", "in", "example_strings", "]", "self", ".", "generate_sprite", "(", "example_strings", ")", "json_examples", "=", "[", "json_format", ".", "MessageToJson", "(", "example", ")", "for", "example", "in", "self", ".", "examples", "]", "self", ".", "updated_example_indices", "=", "set", "(", "range", "(", "len", "(", "json_examples", ")", ")", ")", "return", "http_util", ".", "Respond", "(", "request", ",", "{", "'examples'", ":", "json_examples", ",", "'sprite'", ":", "True", "if", "self", ".", "sprite", "else", "False", "}", ",", "'application/json'", ")", "except", "common_utils", ".", "InvalidUserInputError", "as", "e", ":", "return", "http_util", ".", "Respond", "(", "request", ",", "{", "'error'", ":", "e", ".", "message", "}", ",", "'application/json'", ",", "code", "=", "400", ")" ]
Returns JSON of the specified examples. Args: request: A request that should contain 'examples_path' and 'max_examples'. Returns: JSON of up to max_examlpes of the examples in the path.
[ "Returns", "JSON", "of", "the", "specified", "examples", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/interactive_inference/interactive_inference_plugin.py#L123-L158
train
tensorflow/tensorboard
tensorboard/plugins/interactive_inference/interactive_inference_plugin.py
InteractiveInferencePlugin._update_example
def _update_example(self, request): """Updates the specified example. Args: request: A request that should contain 'index' and 'example'. Returns: An empty response. """ if request.method != 'POST': return http_util.Respond(request, {'error': 'invalid non-POST request'}, 'application/json', code=405) example_json = request.form['example'] index = int(request.form['index']) if index >= len(self.examples): return http_util.Respond(request, {'error': 'invalid index provided'}, 'application/json', code=400) new_example = self.example_class() json_format.Parse(example_json, new_example) self.examples[index] = new_example self.updated_example_indices.add(index) self.generate_sprite([ex.SerializeToString() for ex in self.examples]) return http_util.Respond(request, {}, 'application/json')
python
def _update_example(self, request): """Updates the specified example. Args: request: A request that should contain 'index' and 'example'. Returns: An empty response. """ if request.method != 'POST': return http_util.Respond(request, {'error': 'invalid non-POST request'}, 'application/json', code=405) example_json = request.form['example'] index = int(request.form['index']) if index >= len(self.examples): return http_util.Respond(request, {'error': 'invalid index provided'}, 'application/json', code=400) new_example = self.example_class() json_format.Parse(example_json, new_example) self.examples[index] = new_example self.updated_example_indices.add(index) self.generate_sprite([ex.SerializeToString() for ex in self.examples]) return http_util.Respond(request, {}, 'application/json')
[ "def", "_update_example", "(", "self", ",", "request", ")", ":", "if", "request", ".", "method", "!=", "'POST'", ":", "return", "http_util", ".", "Respond", "(", "request", ",", "{", "'error'", ":", "'invalid non-POST request'", "}", ",", "'application/json'", ",", "code", "=", "405", ")", "example_json", "=", "request", ".", "form", "[", "'example'", "]", "index", "=", "int", "(", "request", ".", "form", "[", "'index'", "]", ")", "if", "index", ">=", "len", "(", "self", ".", "examples", ")", ":", "return", "http_util", ".", "Respond", "(", "request", ",", "{", "'error'", ":", "'invalid index provided'", "}", ",", "'application/json'", ",", "code", "=", "400", ")", "new_example", "=", "self", ".", "example_class", "(", ")", "json_format", ".", "Parse", "(", "example_json", ",", "new_example", ")", "self", ".", "examples", "[", "index", "]", "=", "new_example", "self", ".", "updated_example_indices", ".", "add", "(", "index", ")", "self", ".", "generate_sprite", "(", "[", "ex", ".", "SerializeToString", "(", ")", "for", "ex", "in", "self", ".", "examples", "]", ")", "return", "http_util", ".", "Respond", "(", "request", ",", "{", "}", ",", "'application/json'", ")" ]
Updates the specified example. Args: request: A request that should contain 'index' and 'example'. Returns: An empty response.
[ "Updates", "the", "specified", "example", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/interactive_inference/interactive_inference_plugin.py#L165-L187
train
tensorflow/tensorboard
tensorboard/plugins/interactive_inference/interactive_inference_plugin.py
InteractiveInferencePlugin._duplicate_example
def _duplicate_example(self, request): """Duplicates the specified example. Args: request: A request that should contain 'index'. Returns: An empty response. """ index = int(request.args.get('index')) if index >= len(self.examples): return http_util.Respond(request, {'error': 'invalid index provided'}, 'application/json', code=400) new_example = self.example_class() new_example.CopyFrom(self.examples[index]) self.examples.append(new_example) self.updated_example_indices.add(len(self.examples) - 1) self.generate_sprite([ex.SerializeToString() for ex in self.examples]) return http_util.Respond(request, {}, 'application/json')
python
def _duplicate_example(self, request): """Duplicates the specified example. Args: request: A request that should contain 'index'. Returns: An empty response. """ index = int(request.args.get('index')) if index >= len(self.examples): return http_util.Respond(request, {'error': 'invalid index provided'}, 'application/json', code=400) new_example = self.example_class() new_example.CopyFrom(self.examples[index]) self.examples.append(new_example) self.updated_example_indices.add(len(self.examples) - 1) self.generate_sprite([ex.SerializeToString() for ex in self.examples]) return http_util.Respond(request, {}, 'application/json')
[ "def", "_duplicate_example", "(", "self", ",", "request", ")", ":", "index", "=", "int", "(", "request", ".", "args", ".", "get", "(", "'index'", ")", ")", "if", "index", ">=", "len", "(", "self", ".", "examples", ")", ":", "return", "http_util", ".", "Respond", "(", "request", ",", "{", "'error'", ":", "'invalid index provided'", "}", ",", "'application/json'", ",", "code", "=", "400", ")", "new_example", "=", "self", ".", "example_class", "(", ")", "new_example", ".", "CopyFrom", "(", "self", ".", "examples", "[", "index", "]", ")", "self", ".", "examples", ".", "append", "(", "new_example", ")", "self", ".", "updated_example_indices", ".", "add", "(", "len", "(", "self", ".", "examples", ")", "-", "1", ")", "self", ".", "generate_sprite", "(", "[", "ex", ".", "SerializeToString", "(", ")", "for", "ex", "in", "self", ".", "examples", "]", ")", "return", "http_util", ".", "Respond", "(", "request", ",", "{", "}", ",", "'application/json'", ")" ]
Duplicates the specified example. Args: request: A request that should contain 'index'. Returns: An empty response.
[ "Duplicates", "the", "specified", "example", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/interactive_inference/interactive_inference_plugin.py#L190-L208
train
tensorflow/tensorboard
tensorboard/plugins/interactive_inference/interactive_inference_plugin.py
InteractiveInferencePlugin._delete_example
def _delete_example(self, request): """Deletes the specified example. Args: request: A request that should contain 'index'. Returns: An empty response. """ index = int(request.args.get('index')) if index >= len(self.examples): return http_util.Respond(request, {'error': 'invalid index provided'}, 'application/json', code=400) del self.examples[index] self.updated_example_indices = set([ i if i < index else i - 1 for i in self.updated_example_indices]) self.generate_sprite([ex.SerializeToString() for ex in self.examples]) return http_util.Respond(request, {}, 'application/json')
python
def _delete_example(self, request): """Deletes the specified example. Args: request: A request that should contain 'index'. Returns: An empty response. """ index = int(request.args.get('index')) if index >= len(self.examples): return http_util.Respond(request, {'error': 'invalid index provided'}, 'application/json', code=400) del self.examples[index] self.updated_example_indices = set([ i if i < index else i - 1 for i in self.updated_example_indices]) self.generate_sprite([ex.SerializeToString() for ex in self.examples]) return http_util.Respond(request, {}, 'application/json')
[ "def", "_delete_example", "(", "self", ",", "request", ")", ":", "index", "=", "int", "(", "request", ".", "args", ".", "get", "(", "'index'", ")", ")", "if", "index", ">=", "len", "(", "self", ".", "examples", ")", ":", "return", "http_util", ".", "Respond", "(", "request", ",", "{", "'error'", ":", "'invalid index provided'", "}", ",", "'application/json'", ",", "code", "=", "400", ")", "del", "self", ".", "examples", "[", "index", "]", "self", ".", "updated_example_indices", "=", "set", "(", "[", "i", "if", "i", "<", "index", "else", "i", "-", "1", "for", "i", "in", "self", ".", "updated_example_indices", "]", ")", "self", ".", "generate_sprite", "(", "[", "ex", ".", "SerializeToString", "(", ")", "for", "ex", "in", "self", ".", "examples", "]", ")", "return", "http_util", ".", "Respond", "(", "request", ",", "{", "}", ",", "'application/json'", ")" ]
Deletes the specified example. Args: request: A request that should contain 'index'. Returns: An empty response.
[ "Deletes", "the", "specified", "example", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/interactive_inference/interactive_inference_plugin.py#L211-L228
train
tensorflow/tensorboard
tensorboard/plugins/interactive_inference/interactive_inference_plugin.py
InteractiveInferencePlugin._parse_request_arguments
def _parse_request_arguments(self, request): """Parses comma separated request arguments Args: request: A request that should contain 'inference_address', 'model_name', 'model_version', 'model_signature'. Returns: A tuple of lists for model parameters """ inference_addresses = request.args.get('inference_address').split(',') model_names = request.args.get('model_name').split(',') model_versions = request.args.get('model_version').split(',') model_signatures = request.args.get('model_signature').split(',') if len(model_names) != len(inference_addresses): raise common_utils.InvalidUserInputError('Every model should have a ' + 'name and address.') return inference_addresses, model_names, model_versions, model_signatures
python
def _parse_request_arguments(self, request): """Parses comma separated request arguments Args: request: A request that should contain 'inference_address', 'model_name', 'model_version', 'model_signature'. Returns: A tuple of lists for model parameters """ inference_addresses = request.args.get('inference_address').split(',') model_names = request.args.get('model_name').split(',') model_versions = request.args.get('model_version').split(',') model_signatures = request.args.get('model_signature').split(',') if len(model_names) != len(inference_addresses): raise common_utils.InvalidUserInputError('Every model should have a ' + 'name and address.') return inference_addresses, model_names, model_versions, model_signatures
[ "def", "_parse_request_arguments", "(", "self", ",", "request", ")", ":", "inference_addresses", "=", "request", ".", "args", ".", "get", "(", "'inference_address'", ")", ".", "split", "(", "','", ")", "model_names", "=", "request", ".", "args", ".", "get", "(", "'model_name'", ")", ".", "split", "(", "','", ")", "model_versions", "=", "request", ".", "args", ".", "get", "(", "'model_version'", ")", ".", "split", "(", "','", ")", "model_signatures", "=", "request", ".", "args", ".", "get", "(", "'model_signature'", ")", ".", "split", "(", "','", ")", "if", "len", "(", "model_names", ")", "!=", "len", "(", "inference_addresses", ")", ":", "raise", "common_utils", ".", "InvalidUserInputError", "(", "'Every model should have a '", "+", "'name and address.'", ")", "return", "inference_addresses", ",", "model_names", ",", "model_versions", ",", "model_signatures" ]
Parses comma separated request arguments Args: request: A request that should contain 'inference_address', 'model_name', 'model_version', 'model_signature'. Returns: A tuple of lists for model parameters
[ "Parses", "comma", "separated", "request", "arguments" ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/interactive_inference/interactive_inference_plugin.py#L230-L247
train
tensorflow/tensorboard
tensorboard/plugins/interactive_inference/interactive_inference_plugin.py
InteractiveInferencePlugin._infer
def _infer(self, request): """Returns JSON for the `vz-line-chart`s for a feature. Args: request: A request that should contain 'inference_address', 'model_name', 'model_type, 'model_version', 'model_signature' and 'label_vocab_path'. Returns: A list of JSON objects, one for each chart. """ label_vocab = inference_utils.get_label_vocab( request.args.get('label_vocab_path')) try: if request.method != 'GET': logger.error('%s requests are forbidden.', request.method) return http_util.Respond(request, {'error': 'invalid non-GET request'}, 'application/json', code=405) (inference_addresses, model_names, model_versions, model_signatures) = self._parse_request_arguments(request) indices_to_infer = sorted(self.updated_example_indices) examples_to_infer = [self.examples[index] for index in indices_to_infer] infer_objs = [] for model_num in xrange(len(inference_addresses)): serving_bundle = inference_utils.ServingBundle( inference_addresses[model_num], model_names[model_num], request.args.get('model_type'), model_versions[model_num], model_signatures[model_num], request.args.get('use_predict') == 'true', request.args.get('predict_input_tensor'), request.args.get('predict_output_tensor')) infer_objs.append(inference_utils.run_inference_for_inference_results( examples_to_infer, serving_bundle)) resp = {'indices': indices_to_infer, 'results': infer_objs} self.updated_example_indices = set() return http_util.Respond(request, {'inferences': json.dumps(resp), 'vocab': json.dumps(label_vocab)}, 'application/json') except common_utils.InvalidUserInputError as e: return http_util.Respond(request, {'error': e.message}, 'application/json', code=400) except AbortionError as e: return http_util.Respond(request, {'error': e.details}, 'application/json', code=400)
python
def _infer(self, request): """Returns JSON for the `vz-line-chart`s for a feature. Args: request: A request that should contain 'inference_address', 'model_name', 'model_type, 'model_version', 'model_signature' and 'label_vocab_path'. Returns: A list of JSON objects, one for each chart. """ label_vocab = inference_utils.get_label_vocab( request.args.get('label_vocab_path')) try: if request.method != 'GET': logger.error('%s requests are forbidden.', request.method) return http_util.Respond(request, {'error': 'invalid non-GET request'}, 'application/json', code=405) (inference_addresses, model_names, model_versions, model_signatures) = self._parse_request_arguments(request) indices_to_infer = sorted(self.updated_example_indices) examples_to_infer = [self.examples[index] for index in indices_to_infer] infer_objs = [] for model_num in xrange(len(inference_addresses)): serving_bundle = inference_utils.ServingBundle( inference_addresses[model_num], model_names[model_num], request.args.get('model_type'), model_versions[model_num], model_signatures[model_num], request.args.get('use_predict') == 'true', request.args.get('predict_input_tensor'), request.args.get('predict_output_tensor')) infer_objs.append(inference_utils.run_inference_for_inference_results( examples_to_infer, serving_bundle)) resp = {'indices': indices_to_infer, 'results': infer_objs} self.updated_example_indices = set() return http_util.Respond(request, {'inferences': json.dumps(resp), 'vocab': json.dumps(label_vocab)}, 'application/json') except common_utils.InvalidUserInputError as e: return http_util.Respond(request, {'error': e.message}, 'application/json', code=400) except AbortionError as e: return http_util.Respond(request, {'error': e.details}, 'application/json', code=400)
[ "def", "_infer", "(", "self", ",", "request", ")", ":", "label_vocab", "=", "inference_utils", ".", "get_label_vocab", "(", "request", ".", "args", ".", "get", "(", "'label_vocab_path'", ")", ")", "try", ":", "if", "request", ".", "method", "!=", "'GET'", ":", "logger", ".", "error", "(", "'%s requests are forbidden.'", ",", "request", ".", "method", ")", "return", "http_util", ".", "Respond", "(", "request", ",", "{", "'error'", ":", "'invalid non-GET request'", "}", ",", "'application/json'", ",", "code", "=", "405", ")", "(", "inference_addresses", ",", "model_names", ",", "model_versions", ",", "model_signatures", ")", "=", "self", ".", "_parse_request_arguments", "(", "request", ")", "indices_to_infer", "=", "sorted", "(", "self", ".", "updated_example_indices", ")", "examples_to_infer", "=", "[", "self", ".", "examples", "[", "index", "]", "for", "index", "in", "indices_to_infer", "]", "infer_objs", "=", "[", "]", "for", "model_num", "in", "xrange", "(", "len", "(", "inference_addresses", ")", ")", ":", "serving_bundle", "=", "inference_utils", ".", "ServingBundle", "(", "inference_addresses", "[", "model_num", "]", ",", "model_names", "[", "model_num", "]", ",", "request", ".", "args", ".", "get", "(", "'model_type'", ")", ",", "model_versions", "[", "model_num", "]", ",", "model_signatures", "[", "model_num", "]", ",", "request", ".", "args", ".", "get", "(", "'use_predict'", ")", "==", "'true'", ",", "request", ".", "args", ".", "get", "(", "'predict_input_tensor'", ")", ",", "request", ".", "args", ".", "get", "(", "'predict_output_tensor'", ")", ")", "infer_objs", ".", "append", "(", "inference_utils", ".", "run_inference_for_inference_results", "(", "examples_to_infer", ",", "serving_bundle", ")", ")", "resp", "=", "{", "'indices'", ":", "indices_to_infer", ",", "'results'", ":", "infer_objs", "}", "self", ".", "updated_example_indices", "=", "set", "(", ")", "return", "http_util", ".", "Respond", "(", "request", ",", "{", "'inferences'", ":", "json", ".", "dumps", "(", "resp", ")", ",", "'vocab'", ":", "json", ".", "dumps", "(", "label_vocab", ")", "}", ",", "'application/json'", ")", "except", "common_utils", ".", "InvalidUserInputError", "as", "e", ":", "return", "http_util", ".", "Respond", "(", "request", ",", "{", "'error'", ":", "e", ".", "message", "}", ",", "'application/json'", ",", "code", "=", "400", ")", "except", "AbortionError", "as", "e", ":", "return", "http_util", ".", "Respond", "(", "request", ",", "{", "'error'", ":", "e", ".", "details", "}", ",", "'application/json'", ",", "code", "=", "400", ")" ]
Returns JSON for the `vz-line-chart`s for a feature. Args: request: A request that should contain 'inference_address', 'model_name', 'model_type, 'model_version', 'model_signature' and 'label_vocab_path'. Returns: A list of JSON objects, one for each chart.
[ "Returns", "JSON", "for", "the", "vz", "-", "line", "-", "chart", "s", "for", "a", "feature", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/interactive_inference/interactive_inference_plugin.py#L250-L298
train
tensorflow/tensorboard
tensorboard/plugins/interactive_inference/interactive_inference_plugin.py
InteractiveInferencePlugin._eligible_features_from_example_handler
def _eligible_features_from_example_handler(self, request): """Returns a list of JSON objects for each feature in the example. Args: request: A request for features. Returns: A list with a JSON object for each feature. Numeric features are represented as {name: observedMin: observedMax:}. Categorical features are repesented as {name: samples:[]}. """ features_list = inference_utils.get_eligible_features( self.examples[0: NUM_EXAMPLES_TO_SCAN], NUM_MUTANTS) return http_util.Respond(request, features_list, 'application/json')
python
def _eligible_features_from_example_handler(self, request): """Returns a list of JSON objects for each feature in the example. Args: request: A request for features. Returns: A list with a JSON object for each feature. Numeric features are represented as {name: observedMin: observedMax:}. Categorical features are repesented as {name: samples:[]}. """ features_list = inference_utils.get_eligible_features( self.examples[0: NUM_EXAMPLES_TO_SCAN], NUM_MUTANTS) return http_util.Respond(request, features_list, 'application/json')
[ "def", "_eligible_features_from_example_handler", "(", "self", ",", "request", ")", ":", "features_list", "=", "inference_utils", ".", "get_eligible_features", "(", "self", ".", "examples", "[", "0", ":", "NUM_EXAMPLES_TO_SCAN", "]", ",", "NUM_MUTANTS", ")", "return", "http_util", ".", "Respond", "(", "request", ",", "features_list", ",", "'application/json'", ")" ]
Returns a list of JSON objects for each feature in the example. Args: request: A request for features. Returns: A list with a JSON object for each feature. Numeric features are represented as {name: observedMin: observedMax:}. Categorical features are repesented as {name: samples:[]}.
[ "Returns", "a", "list", "of", "JSON", "objects", "for", "each", "feature", "in", "the", "example", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/interactive_inference/interactive_inference_plugin.py#L301-L314
train
tensorflow/tensorboard
tensorboard/plugins/interactive_inference/interactive_inference_plugin.py
InteractiveInferencePlugin._infer_mutants_handler
def _infer_mutants_handler(self, request): """Returns JSON for the `vz-line-chart`s for a feature. Args: request: A request that should contain 'feature_name', 'example_index', 'inference_address', 'model_name', 'model_type', 'model_version', and 'model_signature'. Returns: A list of JSON objects, one for each chart. """ try: if request.method != 'GET': logger.error('%s requests are forbidden.', request.method) return http_util.Respond(request, {'error': 'invalid non-GET request'}, 'application/json', code=405) example_index = int(request.args.get('example_index', '0')) feature_name = request.args.get('feature_name') examples = (self.examples if example_index == -1 else [self.examples[example_index]]) (inference_addresses, model_names, model_versions, model_signatures) = self._parse_request_arguments(request) serving_bundles = [] for model_num in xrange(len(inference_addresses)): serving_bundles.append(inference_utils.ServingBundle( inference_addresses[model_num], model_names[model_num], request.args.get('model_type'), model_versions[model_num], model_signatures[model_num], request.args.get('use_predict') == 'true', request.args.get('predict_input_tensor'), request.args.get('predict_output_tensor'))) viz_params = inference_utils.VizParams( request.args.get('x_min'), request.args.get('x_max'), self.examples[0:NUM_EXAMPLES_TO_SCAN], NUM_MUTANTS, request.args.get('feature_index_pattern')) json_mapping = inference_utils.mutant_charts_for_feature( examples, feature_name, serving_bundles, viz_params) return http_util.Respond(request, json_mapping, 'application/json') except common_utils.InvalidUserInputError as e: return http_util.Respond(request, {'error': e.message}, 'application/json', code=400)
python
def _infer_mutants_handler(self, request): """Returns JSON for the `vz-line-chart`s for a feature. Args: request: A request that should contain 'feature_name', 'example_index', 'inference_address', 'model_name', 'model_type', 'model_version', and 'model_signature'. Returns: A list of JSON objects, one for each chart. """ try: if request.method != 'GET': logger.error('%s requests are forbidden.', request.method) return http_util.Respond(request, {'error': 'invalid non-GET request'}, 'application/json', code=405) example_index = int(request.args.get('example_index', '0')) feature_name = request.args.get('feature_name') examples = (self.examples if example_index == -1 else [self.examples[example_index]]) (inference_addresses, model_names, model_versions, model_signatures) = self._parse_request_arguments(request) serving_bundles = [] for model_num in xrange(len(inference_addresses)): serving_bundles.append(inference_utils.ServingBundle( inference_addresses[model_num], model_names[model_num], request.args.get('model_type'), model_versions[model_num], model_signatures[model_num], request.args.get('use_predict') == 'true', request.args.get('predict_input_tensor'), request.args.get('predict_output_tensor'))) viz_params = inference_utils.VizParams( request.args.get('x_min'), request.args.get('x_max'), self.examples[0:NUM_EXAMPLES_TO_SCAN], NUM_MUTANTS, request.args.get('feature_index_pattern')) json_mapping = inference_utils.mutant_charts_for_feature( examples, feature_name, serving_bundles, viz_params) return http_util.Respond(request, json_mapping, 'application/json') except common_utils.InvalidUserInputError as e: return http_util.Respond(request, {'error': e.message}, 'application/json', code=400)
[ "def", "_infer_mutants_handler", "(", "self", ",", "request", ")", ":", "try", ":", "if", "request", ".", "method", "!=", "'GET'", ":", "logger", ".", "error", "(", "'%s requests are forbidden.'", ",", "request", ".", "method", ")", "return", "http_util", ".", "Respond", "(", "request", ",", "{", "'error'", ":", "'invalid non-GET request'", "}", ",", "'application/json'", ",", "code", "=", "405", ")", "example_index", "=", "int", "(", "request", ".", "args", ".", "get", "(", "'example_index'", ",", "'0'", ")", ")", "feature_name", "=", "request", ".", "args", ".", "get", "(", "'feature_name'", ")", "examples", "=", "(", "self", ".", "examples", "if", "example_index", "==", "-", "1", "else", "[", "self", ".", "examples", "[", "example_index", "]", "]", ")", "(", "inference_addresses", ",", "model_names", ",", "model_versions", ",", "model_signatures", ")", "=", "self", ".", "_parse_request_arguments", "(", "request", ")", "serving_bundles", "=", "[", "]", "for", "model_num", "in", "xrange", "(", "len", "(", "inference_addresses", ")", ")", ":", "serving_bundles", ".", "append", "(", "inference_utils", ".", "ServingBundle", "(", "inference_addresses", "[", "model_num", "]", ",", "model_names", "[", "model_num", "]", ",", "request", ".", "args", ".", "get", "(", "'model_type'", ")", ",", "model_versions", "[", "model_num", "]", ",", "model_signatures", "[", "model_num", "]", ",", "request", ".", "args", ".", "get", "(", "'use_predict'", ")", "==", "'true'", ",", "request", ".", "args", ".", "get", "(", "'predict_input_tensor'", ")", ",", "request", ".", "args", ".", "get", "(", "'predict_output_tensor'", ")", ")", ")", "viz_params", "=", "inference_utils", ".", "VizParams", "(", "request", ".", "args", ".", "get", "(", "'x_min'", ")", ",", "request", ".", "args", ".", "get", "(", "'x_max'", ")", ",", "self", ".", "examples", "[", "0", ":", "NUM_EXAMPLES_TO_SCAN", "]", ",", "NUM_MUTANTS", ",", "request", ".", "args", ".", "get", "(", "'feature_index_pattern'", ")", ")", "json_mapping", "=", "inference_utils", ".", "mutant_charts_for_feature", "(", "examples", ",", "feature_name", ",", "serving_bundles", ",", "viz_params", ")", "return", "http_util", ".", "Respond", "(", "request", ",", "json_mapping", ",", "'application/json'", ")", "except", "common_utils", ".", "InvalidUserInputError", "as", "e", ":", "return", "http_util", ".", "Respond", "(", "request", ",", "{", "'error'", ":", "e", ".", "message", "}", ",", "'application/json'", ",", "code", "=", "400", ")" ]
Returns JSON for the `vz-line-chart`s for a feature. Args: request: A request that should contain 'feature_name', 'example_index', 'inference_address', 'model_name', 'model_type', 'model_version', and 'model_signature'. Returns: A list of JSON objects, one for each chart.
[ "Returns", "JSON", "for", "the", "vz", "-", "line", "-", "chart", "s", "for", "a", "feature", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/interactive_inference/interactive_inference_plugin.py#L317-L363
train
tensorflow/tensorboard
tensorboard/plugins/core/core_plugin.py
CorePlugin._serve_asset
def _serve_asset(self, path, gzipped_asset_bytes, request): """Serves a pre-gzipped static asset from the zip file.""" mimetype = mimetypes.guess_type(path)[0] or 'application/octet-stream' return http_util.Respond( request, gzipped_asset_bytes, mimetype, content_encoding='gzip')
python
def _serve_asset(self, path, gzipped_asset_bytes, request): """Serves a pre-gzipped static asset from the zip file.""" mimetype = mimetypes.guess_type(path)[0] or 'application/octet-stream' return http_util.Respond( request, gzipped_asset_bytes, mimetype, content_encoding='gzip')
[ "def", "_serve_asset", "(", "self", ",", "path", ",", "gzipped_asset_bytes", ",", "request", ")", ":", "mimetype", "=", "mimetypes", ".", "guess_type", "(", "path", ")", "[", "0", "]", "or", "'application/octet-stream'", "return", "http_util", ".", "Respond", "(", "request", ",", "gzipped_asset_bytes", ",", "mimetype", ",", "content_encoding", "=", "'gzip'", ")" ]
Serves a pre-gzipped static asset from the zip file.
[ "Serves", "a", "pre", "-", "gzipped", "static", "asset", "from", "the", "zip", "file", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/core/core_plugin.py#L105-L109
train
tensorflow/tensorboard
tensorboard/plugins/core/core_plugin.py
CorePlugin._serve_environment
def _serve_environment(self, request): """Serve a JSON object containing some base properties used by the frontend. * data_location is either a path to a directory or an address to a database (depending on which mode TensorBoard is running in). * window_title is the title of the TensorBoard web page. """ return http_util.Respond( request, { 'data_location': self._logdir or self._db_uri, 'mode': 'db' if self._db_uri else 'logdir', 'window_title': self._window_title, }, 'application/json')
python
def _serve_environment(self, request): """Serve a JSON object containing some base properties used by the frontend. * data_location is either a path to a directory or an address to a database (depending on which mode TensorBoard is running in). * window_title is the title of the TensorBoard web page. """ return http_util.Respond( request, { 'data_location': self._logdir or self._db_uri, 'mode': 'db' if self._db_uri else 'logdir', 'window_title': self._window_title, }, 'application/json')
[ "def", "_serve_environment", "(", "self", ",", "request", ")", ":", "return", "http_util", ".", "Respond", "(", "request", ",", "{", "'data_location'", ":", "self", ".", "_logdir", "or", "self", ".", "_db_uri", ",", "'mode'", ":", "'db'", "if", "self", ".", "_db_uri", "else", "'logdir'", ",", "'window_title'", ":", "self", ".", "_window_title", ",", "}", ",", "'application/json'", ")" ]
Serve a JSON object containing some base properties used by the frontend. * data_location is either a path to a directory or an address to a database (depending on which mode TensorBoard is running in). * window_title is the title of the TensorBoard web page.
[ "Serve", "a", "JSON", "object", "containing", "some", "base", "properties", "used", "by", "the", "frontend", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/core/core_plugin.py#L112-L126
train
tensorflow/tensorboard
tensorboard/plugins/core/core_plugin.py
CorePlugin._serve_runs
def _serve_runs(self, request): """Serve a JSON array of run names, ordered by run started time. Sort order is by started time (aka first event time) with empty times sorted last, and then ties are broken by sorting on the run name. """ if self._db_connection_provider: db = self._db_connection_provider() cursor = db.execute(''' SELECT run_name, started_time IS NULL as started_time_nulls_last, started_time FROM Runs ORDER BY started_time_nulls_last, started_time, run_name ''') run_names = [row[0] for row in cursor] else: # Python's list.sort is stable, so to order by started time and # then by name, we can just do the sorts in the reverse order. run_names = sorted(self._multiplexer.Runs()) def get_first_event_timestamp(run_name): try: return self._multiplexer.FirstEventTimestamp(run_name) except ValueError as e: logger.warn( 'Unable to get first event timestamp for run %s: %s', run_name, e) # Put runs without a timestamp at the end. return float('inf') run_names.sort(key=get_first_event_timestamp) return http_util.Respond(request, run_names, 'application/json')
python
def _serve_runs(self, request): """Serve a JSON array of run names, ordered by run started time. Sort order is by started time (aka first event time) with empty times sorted last, and then ties are broken by sorting on the run name. """ if self._db_connection_provider: db = self._db_connection_provider() cursor = db.execute(''' SELECT run_name, started_time IS NULL as started_time_nulls_last, started_time FROM Runs ORDER BY started_time_nulls_last, started_time, run_name ''') run_names = [row[0] for row in cursor] else: # Python's list.sort is stable, so to order by started time and # then by name, we can just do the sorts in the reverse order. run_names = sorted(self._multiplexer.Runs()) def get_first_event_timestamp(run_name): try: return self._multiplexer.FirstEventTimestamp(run_name) except ValueError as e: logger.warn( 'Unable to get first event timestamp for run %s: %s', run_name, e) # Put runs without a timestamp at the end. return float('inf') run_names.sort(key=get_first_event_timestamp) return http_util.Respond(request, run_names, 'application/json')
[ "def", "_serve_runs", "(", "self", ",", "request", ")", ":", "if", "self", ".", "_db_connection_provider", ":", "db", "=", "self", ".", "_db_connection_provider", "(", ")", "cursor", "=", "db", ".", "execute", "(", "'''\n SELECT\n run_name,\n started_time IS NULL as started_time_nulls_last,\n started_time\n FROM Runs\n ORDER BY started_time_nulls_last, started_time, run_name\n '''", ")", "run_names", "=", "[", "row", "[", "0", "]", "for", "row", "in", "cursor", "]", "else", ":", "# Python's list.sort is stable, so to order by started time and", "# then by name, we can just do the sorts in the reverse order.", "run_names", "=", "sorted", "(", "self", ".", "_multiplexer", ".", "Runs", "(", ")", ")", "def", "get_first_event_timestamp", "(", "run_name", ")", ":", "try", ":", "return", "self", ".", "_multiplexer", ".", "FirstEventTimestamp", "(", "run_name", ")", "except", "ValueError", "as", "e", ":", "logger", ".", "warn", "(", "'Unable to get first event timestamp for run %s: %s'", ",", "run_name", ",", "e", ")", "# Put runs without a timestamp at the end.", "return", "float", "(", "'inf'", ")", "run_names", ".", "sort", "(", "key", "=", "get_first_event_timestamp", ")", "return", "http_util", ".", "Respond", "(", "request", ",", "run_names", ",", "'application/json'", ")" ]
Serve a JSON array of run names, ordered by run started time. Sort order is by started time (aka first event time) with empty times sorted last, and then ties are broken by sorting on the run name.
[ "Serve", "a", "JSON", "array", "of", "run", "names", "ordered", "by", "run", "started", "time", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/core/core_plugin.py#L146-L176
train
tensorflow/tensorboard
tensorboard/plugins/core/core_plugin.py
CorePlugin._serve_experiments
def _serve_experiments(self, request): """Serve a JSON array of experiments. Experiments are ordered by experiment started time (aka first event time) with empty times sorted last, and then ties are broken by sorting on the experiment name. """ results = self.list_experiments_impl() return http_util.Respond(request, results, 'application/json')
python
def _serve_experiments(self, request): """Serve a JSON array of experiments. Experiments are ordered by experiment started time (aka first event time) with empty times sorted last, and then ties are broken by sorting on the experiment name. """ results = self.list_experiments_impl() return http_util.Respond(request, results, 'application/json')
[ "def", "_serve_experiments", "(", "self", ",", "request", ")", ":", "results", "=", "self", ".", "list_experiments_impl", "(", ")", "return", "http_util", ".", "Respond", "(", "request", ",", "results", ",", "'application/json'", ")" ]
Serve a JSON array of experiments. Experiments are ordered by experiment started time (aka first event time) with empty times sorted last, and then ties are broken by sorting on the experiment name.
[ "Serve", "a", "JSON", "array", "of", "experiments", ".", "Experiments", "are", "ordered", "by", "experiment", "started", "time", "(", "aka", "first", "event", "time", ")", "with", "empty", "times", "sorted", "last", "and", "then", "ties", "are", "broken", "by", "sorting", "on", "the", "experiment", "name", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/core/core_plugin.py#L179-L185
train
tensorflow/tensorboard
tensorboard/plugins/core/core_plugin.py
CorePlugin._serve_experiment_runs
def _serve_experiment_runs(self, request): """Serve a JSON runs of an experiment, specified with query param `experiment`, with their nested data, tag, populated. Runs returned are ordered by started time (aka first event time) with empty times sorted last, and then ties are broken by sorting on the run name. Tags are sorted by its name, displayName, and lastly, inserted time. """ results = [] if self._db_connection_provider: exp_id = request.args.get('experiment') runs_dict = collections.OrderedDict() db = self._db_connection_provider() cursor = db.execute(''' SELECT Runs.run_id, Runs.run_name, Runs.started_time, Runs.started_time IS NULL as started_time_nulls_last, Tags.tag_id, Tags.tag_name, Tags.display_name, Tags.plugin_name, Tags.inserted_time From Runs LEFT JOIN Tags ON Runs.run_id = Tags.run_id WHERE Runs.experiment_id = ? AND (Tags.tag_id IS NULL OR Tags.plugin_name IS NOT NULL) ORDER BY started_time_nulls_last, Runs.started_time, Runs.run_name, Runs.run_id, Tags.tag_name, Tags.display_name, Tags.inserted_time; ''', (exp_id,)) for row in cursor: run_id = row[0] if not run_id in runs_dict: runs_dict[run_id] = { "id": run_id, "name": row[1], "startTime": math.floor(row[2]), "tags": [], } # tag can be missing. if row[4]: runs_dict[run_id].get("tags").append({ "id": row[4], "displayName": row[6], "name": row[5], "pluginName": row[7], }) results = list(runs_dict.values()) return http_util.Respond(request, results, 'application/json')
python
def _serve_experiment_runs(self, request): """Serve a JSON runs of an experiment, specified with query param `experiment`, with their nested data, tag, populated. Runs returned are ordered by started time (aka first event time) with empty times sorted last, and then ties are broken by sorting on the run name. Tags are sorted by its name, displayName, and lastly, inserted time. """ results = [] if self._db_connection_provider: exp_id = request.args.get('experiment') runs_dict = collections.OrderedDict() db = self._db_connection_provider() cursor = db.execute(''' SELECT Runs.run_id, Runs.run_name, Runs.started_time, Runs.started_time IS NULL as started_time_nulls_last, Tags.tag_id, Tags.tag_name, Tags.display_name, Tags.plugin_name, Tags.inserted_time From Runs LEFT JOIN Tags ON Runs.run_id = Tags.run_id WHERE Runs.experiment_id = ? AND (Tags.tag_id IS NULL OR Tags.plugin_name IS NOT NULL) ORDER BY started_time_nulls_last, Runs.started_time, Runs.run_name, Runs.run_id, Tags.tag_name, Tags.display_name, Tags.inserted_time; ''', (exp_id,)) for row in cursor: run_id = row[0] if not run_id in runs_dict: runs_dict[run_id] = { "id": run_id, "name": row[1], "startTime": math.floor(row[2]), "tags": [], } # tag can be missing. if row[4]: runs_dict[run_id].get("tags").append({ "id": row[4], "displayName": row[6], "name": row[5], "pluginName": row[7], }) results = list(runs_dict.values()) return http_util.Respond(request, results, 'application/json')
[ "def", "_serve_experiment_runs", "(", "self", ",", "request", ")", ":", "results", "=", "[", "]", "if", "self", ".", "_db_connection_provider", ":", "exp_id", "=", "request", ".", "args", ".", "get", "(", "'experiment'", ")", "runs_dict", "=", "collections", ".", "OrderedDict", "(", ")", "db", "=", "self", ".", "_db_connection_provider", "(", ")", "cursor", "=", "db", ".", "execute", "(", "'''\n SELECT\n Runs.run_id,\n Runs.run_name,\n Runs.started_time,\n Runs.started_time IS NULL as started_time_nulls_last,\n Tags.tag_id,\n Tags.tag_name,\n Tags.display_name,\n Tags.plugin_name,\n Tags.inserted_time\n From Runs\n LEFT JOIN Tags ON Runs.run_id = Tags.run_id\n WHERE Runs.experiment_id = ?\n AND (Tags.tag_id IS NULL OR Tags.plugin_name IS NOT NULL)\n ORDER BY started_time_nulls_last,\n Runs.started_time,\n Runs.run_name,\n Runs.run_id,\n Tags.tag_name,\n Tags.display_name,\n Tags.inserted_time;\n '''", ",", "(", "exp_id", ",", ")", ")", "for", "row", "in", "cursor", ":", "run_id", "=", "row", "[", "0", "]", "if", "not", "run_id", "in", "runs_dict", ":", "runs_dict", "[", "run_id", "]", "=", "{", "\"id\"", ":", "run_id", ",", "\"name\"", ":", "row", "[", "1", "]", ",", "\"startTime\"", ":", "math", ".", "floor", "(", "row", "[", "2", "]", ")", ",", "\"tags\"", ":", "[", "]", ",", "}", "# tag can be missing.", "if", "row", "[", "4", "]", ":", "runs_dict", "[", "run_id", "]", ".", "get", "(", "\"tags\"", ")", ".", "append", "(", "{", "\"id\"", ":", "row", "[", "4", "]", ",", "\"displayName\"", ":", "row", "[", "6", "]", ",", "\"name\"", ":", "row", "[", "5", "]", ",", "\"pluginName\"", ":", "row", "[", "7", "]", ",", "}", ")", "results", "=", "list", "(", "runs_dict", ".", "values", "(", ")", ")", "return", "http_util", ".", "Respond", "(", "request", ",", "results", ",", "'application/json'", ")" ]
Serve a JSON runs of an experiment, specified with query param `experiment`, with their nested data, tag, populated. Runs returned are ordered by started time (aka first event time) with empty times sorted last, and then ties are broken by sorting on the run name. Tags are sorted by its name, displayName, and lastly, inserted time.
[ "Serve", "a", "JSON", "runs", "of", "an", "experiment", "specified", "with", "query", "param", "experiment", "with", "their", "nested", "data", "tag", "populated", ".", "Runs", "returned", "are", "ordered", "by", "started", "time", "(", "aka", "first", "event", "time", ")", "with", "empty", "times", "sorted", "last", "and", "then", "ties", "are", "broken", "by", "sorting", "on", "the", "run", "name", ".", "Tags", "are", "sorted", "by", "its", "name", "displayName", "and", "lastly", "inserted", "time", "." ]
8e5f497b48e40f2a774f85416b8a35ac0693c35e
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/core/core_plugin.py#L210-L264
train