id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
238,300
IDSIA/sacred
sacred/utils.py
iterate_flattened_separately
def iterate_flattened_separately(dictionary, manually_sorted_keys=None): """ Recursively iterate over the items of a dictionary in a special order. First iterate over manually sorted keys and then over all items that are non-dictionary values (sorted by keys), then over the rest (sorted by keys), providing full dotted paths for every leaf. """ if manually_sorted_keys is None: manually_sorted_keys = [] for key in manually_sorted_keys: if key in dictionary: yield key, dictionary[key] single_line_keys = [key for key in dictionary.keys() if key not in manually_sorted_keys and (not dictionary[key] or not isinstance(dictionary[key], dict))] for key in sorted(single_line_keys): yield key, dictionary[key] multi_line_keys = [key for key in dictionary.keys() if key not in manually_sorted_keys and (dictionary[key] and isinstance(dictionary[key], dict))] for key in sorted(multi_line_keys): yield key, PATHCHANGE for k, val in iterate_flattened_separately(dictionary[key], manually_sorted_keys): yield join_paths(key, k), val
python
def iterate_flattened_separately(dictionary, manually_sorted_keys=None): if manually_sorted_keys is None: manually_sorted_keys = [] for key in manually_sorted_keys: if key in dictionary: yield key, dictionary[key] single_line_keys = [key for key in dictionary.keys() if key not in manually_sorted_keys and (not dictionary[key] or not isinstance(dictionary[key], dict))] for key in sorted(single_line_keys): yield key, dictionary[key] multi_line_keys = [key for key in dictionary.keys() if key not in manually_sorted_keys and (dictionary[key] and isinstance(dictionary[key], dict))] for key in sorted(multi_line_keys): yield key, PATHCHANGE for k, val in iterate_flattened_separately(dictionary[key], manually_sorted_keys): yield join_paths(key, k), val
[ "def", "iterate_flattened_separately", "(", "dictionary", ",", "manually_sorted_keys", "=", "None", ")", ":", "if", "manually_sorted_keys", "is", "None", ":", "manually_sorted_keys", "=", "[", "]", "for", "key", "in", "manually_sorted_keys", ":", "if", "key", "in"...
Recursively iterate over the items of a dictionary in a special order. First iterate over manually sorted keys and then over all items that are non-dictionary values (sorted by keys), then over the rest (sorted by keys), providing full dotted paths for every leaf.
[ "Recursively", "iterate", "over", "the", "items", "of", "a", "dictionary", "in", "a", "special", "order", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L325-L354
238,301
IDSIA/sacred
sacred/utils.py
iterate_flattened
def iterate_flattened(d): """ Recursively iterate over the items of a dictionary. Provides a full dotted paths for every leaf. """ for key in sorted(d.keys()): value = d[key] if isinstance(value, dict) and value: for k, v in iterate_flattened(d[key]): yield join_paths(key, k), v else: yield key, value
python
def iterate_flattened(d): for key in sorted(d.keys()): value = d[key] if isinstance(value, dict) and value: for k, v in iterate_flattened(d[key]): yield join_paths(key, k), v else: yield key, value
[ "def", "iterate_flattened", "(", "d", ")", ":", "for", "key", "in", "sorted", "(", "d", ".", "keys", "(", ")", ")", ":", "value", "=", "d", "[", "key", "]", "if", "isinstance", "(", "value", ",", "dict", ")", "and", "value", ":", "for", "k", ",...
Recursively iterate over the items of a dictionary. Provides a full dotted paths for every leaf.
[ "Recursively", "iterate", "over", "the", "items", "of", "a", "dictionary", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L357-L369
238,302
IDSIA/sacred
sacred/utils.py
set_by_dotted_path
def set_by_dotted_path(d, path, value): """ Set an entry in a nested dict using a dotted path. Will create dictionaries as needed. Examples -------- >>> d = {'foo': {'bar': 7}} >>> set_by_dotted_path(d, 'foo.bar', 10) >>> d {'foo': {'bar': 10}} >>> set_by_dotted_path(d, 'foo.d.baz', 3) >>> d {'foo': {'bar': 10, 'd': {'baz': 3}}} """ split_path = path.split('.') current_option = d for p in split_path[:-1]: if p not in current_option: current_option[p] = dict() current_option = current_option[p] current_option[split_path[-1]] = value
python
def set_by_dotted_path(d, path, value): split_path = path.split('.') current_option = d for p in split_path[:-1]: if p not in current_option: current_option[p] = dict() current_option = current_option[p] current_option[split_path[-1]] = value
[ "def", "set_by_dotted_path", "(", "d", ",", "path", ",", "value", ")", ":", "split_path", "=", "path", ".", "split", "(", "'.'", ")", "current_option", "=", "d", "for", "p", "in", "split_path", "[", ":", "-", "1", "]", ":", "if", "p", "not", "in", ...
Set an entry in a nested dict using a dotted path. Will create dictionaries as needed. Examples -------- >>> d = {'foo': {'bar': 7}} >>> set_by_dotted_path(d, 'foo.bar', 10) >>> d {'foo': {'bar': 10}} >>> set_by_dotted_path(d, 'foo.d.baz', 3) >>> d {'foo': {'bar': 10, 'd': {'baz': 3}}}
[ "Set", "an", "entry", "in", "a", "nested", "dict", "using", "a", "dotted", "path", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L372-L395
238,303
IDSIA/sacred
sacred/utils.py
get_by_dotted_path
def get_by_dotted_path(d, path, default=None): """ Get an entry from nested dictionaries using a dotted path. Example: >>> get_by_dotted_path({'foo': {'a': 12}}, 'foo.a') 12 """ if not path: return d split_path = path.split('.') current_option = d for p in split_path: if p not in current_option: return default current_option = current_option[p] return current_option
python
def get_by_dotted_path(d, path, default=None): if not path: return d split_path = path.split('.') current_option = d for p in split_path: if p not in current_option: return default current_option = current_option[p] return current_option
[ "def", "get_by_dotted_path", "(", "d", ",", "path", ",", "default", "=", "None", ")", ":", "if", "not", "path", ":", "return", "d", "split_path", "=", "path", ".", "split", "(", "'.'", ")", "current_option", "=", "d", "for", "p", "in", "split_path", ...
Get an entry from nested dictionaries using a dotted path. Example: >>> get_by_dotted_path({'foo': {'a': 12}}, 'foo.a') 12
[ "Get", "an", "entry", "from", "nested", "dictionaries", "using", "a", "dotted", "path", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L398-L414
238,304
IDSIA/sacred
sacred/utils.py
iter_path_splits
def iter_path_splits(path): """ Iterate over possible splits of a dotted path. The first part can be empty the second should not be. Example: >>> list(iter_path_splits('foo.bar.baz')) [('', 'foo.bar.baz'), ('foo', 'bar.baz'), ('foo.bar', 'baz')] """ split_path = path.split('.') for i in range(len(split_path)): p1 = join_paths(*split_path[:i]) p2 = join_paths(*split_path[i:]) yield p1, p2
python
def iter_path_splits(path): split_path = path.split('.') for i in range(len(split_path)): p1 = join_paths(*split_path[:i]) p2 = join_paths(*split_path[i:]) yield p1, p2
[ "def", "iter_path_splits", "(", "path", ")", ":", "split_path", "=", "path", ".", "split", "(", "'.'", ")", "for", "i", "in", "range", "(", "len", "(", "split_path", ")", ")", ":", "p1", "=", "join_paths", "(", "*", "split_path", "[", ":", "i", "]"...
Iterate over possible splits of a dotted path. The first part can be empty the second should not be. Example: >>> list(iter_path_splits('foo.bar.baz')) [('', 'foo.bar.baz'), ('foo', 'bar.baz'), ('foo.bar', 'baz')]
[ "Iterate", "over", "possible", "splits", "of", "a", "dotted", "path", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L417-L433
238,305
IDSIA/sacred
sacred/utils.py
is_prefix
def is_prefix(pre_path, path): """Return True if pre_path is a path-prefix of path.""" pre_path = pre_path.strip('.') path = path.strip('.') return not pre_path or path.startswith(pre_path + '.')
python
def is_prefix(pre_path, path): pre_path = pre_path.strip('.') path = path.strip('.') return not pre_path or path.startswith(pre_path + '.')
[ "def", "is_prefix", "(", "pre_path", ",", "path", ")", ":", "pre_path", "=", "pre_path", ".", "strip", "(", "'.'", ")", "path", "=", "path", ".", "strip", "(", "'.'", ")", "return", "not", "pre_path", "or", "path", ".", "startswith", "(", "pre_path", ...
Return True if pre_path is a path-prefix of path.
[ "Return", "True", "if", "pre_path", "is", "a", "path", "-", "prefix", "of", "path", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L454-L458
238,306
IDSIA/sacred
sacred/utils.py
rel_path
def rel_path(base, path): """Return path relative to base.""" if base == path: return '' assert is_prefix(base, path), "{} not a prefix of {}".format(base, path) return path[len(base):].strip('.')
python
def rel_path(base, path): if base == path: return '' assert is_prefix(base, path), "{} not a prefix of {}".format(base, path) return path[len(base):].strip('.')
[ "def", "rel_path", "(", "base", ",", "path", ")", ":", "if", "base", "==", "path", ":", "return", "''", "assert", "is_prefix", "(", "base", ",", "path", ")", ",", "\"{} not a prefix of {}\"", ".", "format", "(", "base", ",", "path", ")", "return", "pat...
Return path relative to base.
[ "Return", "path", "relative", "to", "base", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L461-L466
238,307
IDSIA/sacred
sacred/utils.py
convert_to_nested_dict
def convert_to_nested_dict(dotted_dict): """Convert a dict with dotted path keys to corresponding nested dict.""" nested_dict = {} for k, v in iterate_flattened(dotted_dict): set_by_dotted_path(nested_dict, k, v) return nested_dict
python
def convert_to_nested_dict(dotted_dict): nested_dict = {} for k, v in iterate_flattened(dotted_dict): set_by_dotted_path(nested_dict, k, v) return nested_dict
[ "def", "convert_to_nested_dict", "(", "dotted_dict", ")", ":", "nested_dict", "=", "{", "}", "for", "k", ",", "v", "in", "iterate_flattened", "(", "dotted_dict", ")", ":", "set_by_dotted_path", "(", "nested_dict", ",", "k", ",", "v", ")", "return", "nested_d...
Convert a dict with dotted path keys to corresponding nested dict.
[ "Convert", "a", "dict", "with", "dotted", "path", "keys", "to", "corresponding", "nested", "dict", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L469-L474
238,308
IDSIA/sacred
sacred/utils.py
format_filtered_stacktrace
def format_filtered_stacktrace(filter_traceback='default'): """ Returns the traceback as `string`. `filter_traceback` can be one of: - 'always': always filter out sacred internals - 'default': Default behaviour: filter out sacred internals if the exception did not originate from within sacred, and print just the internal stack trace otherwise - 'never': don't filter, always print full traceback - All other values will fall back to 'never'. """ exc_type, exc_value, exc_traceback = sys.exc_info() # determine if last exception is from sacred current_tb = exc_traceback while current_tb.tb_next is not None: current_tb = current_tb.tb_next if filter_traceback == 'default' \ and _is_sacred_frame(current_tb.tb_frame): # just print sacred internal trace header = ["Exception originated from within Sacred.\n" "Traceback (most recent calls):\n"] texts = tb.format_exception(exc_type, exc_value, current_tb) return ''.join(header + texts[1:]).strip() elif filter_traceback in ('default', 'always'): # print filtered stacktrace if sys.version_info >= (3, 5): tb_exception = \ tb.TracebackException(exc_type, exc_value, exc_traceback, limit=None) return ''.join(filtered_traceback_format(tb_exception)) else: s = "Traceback (most recent calls WITHOUT Sacred internals):" current_tb = exc_traceback while current_tb is not None: if not _is_sacred_frame(current_tb.tb_frame): tb.print_tb(current_tb, 1) current_tb = current_tb.tb_next s += "\n".join(tb.format_exception_only(exc_type, exc_value)).strip() return s elif filter_traceback == 'never': # print full stacktrace return '\n'.join( tb.format_exception(exc_type, exc_value, exc_traceback)) else: raise ValueError('Unknown value for filter_traceback: ' + filter_traceback)
python
def format_filtered_stacktrace(filter_traceback='default'): exc_type, exc_value, exc_traceback = sys.exc_info() # determine if last exception is from sacred current_tb = exc_traceback while current_tb.tb_next is not None: current_tb = current_tb.tb_next if filter_traceback == 'default' \ and _is_sacred_frame(current_tb.tb_frame): # just print sacred internal trace header = ["Exception originated from within Sacred.\n" "Traceback (most recent calls):\n"] texts = tb.format_exception(exc_type, exc_value, current_tb) return ''.join(header + texts[1:]).strip() elif filter_traceback in ('default', 'always'): # print filtered stacktrace if sys.version_info >= (3, 5): tb_exception = \ tb.TracebackException(exc_type, exc_value, exc_traceback, limit=None) return ''.join(filtered_traceback_format(tb_exception)) else: s = "Traceback (most recent calls WITHOUT Sacred internals):" current_tb = exc_traceback while current_tb is not None: if not _is_sacred_frame(current_tb.tb_frame): tb.print_tb(current_tb, 1) current_tb = current_tb.tb_next s += "\n".join(tb.format_exception_only(exc_type, exc_value)).strip() return s elif filter_traceback == 'never': # print full stacktrace return '\n'.join( tb.format_exception(exc_type, exc_value, exc_traceback)) else: raise ValueError('Unknown value for filter_traceback: ' + filter_traceback)
[ "def", "format_filtered_stacktrace", "(", "filter_traceback", "=", "'default'", ")", ":", "exc_type", ",", "exc_value", ",", "exc_traceback", "=", "sys", ".", "exc_info", "(", ")", "# determine if last exception is from sacred", "current_tb", "=", "exc_traceback", "whil...
Returns the traceback as `string`. `filter_traceback` can be one of: - 'always': always filter out sacred internals - 'default': Default behaviour: filter out sacred internals if the exception did not originate from within sacred, and print just the internal stack trace otherwise - 'never': don't filter, always print full traceback - All other values will fall back to 'never'.
[ "Returns", "the", "traceback", "as", "string", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L485-L533
238,309
IDSIA/sacred
sacred/utils.py
get_inheritors
def get_inheritors(cls): """Get a set of all classes that inherit from the given class.""" subclasses = set() work = [cls] while work: parent = work.pop() for child in parent.__subclasses__(): if child not in subclasses: subclasses.add(child) work.append(child) return subclasses
python
def get_inheritors(cls): subclasses = set() work = [cls] while work: parent = work.pop() for child in parent.__subclasses__(): if child not in subclasses: subclasses.add(child) work.append(child) return subclasses
[ "def", "get_inheritors", "(", "cls", ")", ":", "subclasses", "=", "set", "(", ")", "work", "=", "[", "cls", "]", "while", "work", ":", "parent", "=", "work", ".", "pop", "(", ")", "for", "child", "in", "parent", ".", "__subclasses__", "(", ")", ":"...
Get a set of all classes that inherit from the given class.
[ "Get", "a", "set", "of", "all", "classes", "that", "inherit", "from", "the", "given", "class", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L593-L603
238,310
IDSIA/sacred
sacred/utils.py
apply_backspaces_and_linefeeds
def apply_backspaces_and_linefeeds(text): """ Interpret backspaces and linefeeds in text like a terminal would. Interpret text like a terminal by removing backspace and linefeed characters and applying them line by line. If final line ends with a carriage it keeps it to be concatenable with next output chunk. """ orig_lines = text.split('\n') orig_lines_len = len(orig_lines) new_lines = [] for orig_line_idx, orig_line in enumerate(orig_lines): chars, cursor = [], 0 orig_line_len = len(orig_line) for orig_char_idx, orig_char in enumerate(orig_line): if orig_char == '\r' and (orig_char_idx != orig_line_len - 1 or orig_line_idx != orig_lines_len - 1): cursor = 0 elif orig_char == '\b': cursor = max(0, cursor - 1) else: if (orig_char == '\r' and orig_char_idx == orig_line_len - 1 and orig_line_idx == orig_lines_len - 1): cursor = len(chars) if cursor == len(chars): chars.append(orig_char) else: chars[cursor] = orig_char cursor += 1 new_lines.append(''.join(chars)) return '\n'.join(new_lines)
python
def apply_backspaces_and_linefeeds(text): orig_lines = text.split('\n') orig_lines_len = len(orig_lines) new_lines = [] for orig_line_idx, orig_line in enumerate(orig_lines): chars, cursor = [], 0 orig_line_len = len(orig_line) for orig_char_idx, orig_char in enumerate(orig_line): if orig_char == '\r' and (orig_char_idx != orig_line_len - 1 or orig_line_idx != orig_lines_len - 1): cursor = 0 elif orig_char == '\b': cursor = max(0, cursor - 1) else: if (orig_char == '\r' and orig_char_idx == orig_line_len - 1 and orig_line_idx == orig_lines_len - 1): cursor = len(chars) if cursor == len(chars): chars.append(orig_char) else: chars[cursor] = orig_char cursor += 1 new_lines.append(''.join(chars)) return '\n'.join(new_lines)
[ "def", "apply_backspaces_and_linefeeds", "(", "text", ")", ":", "orig_lines", "=", "text", ".", "split", "(", "'\\n'", ")", "orig_lines_len", "=", "len", "(", "orig_lines", ")", "new_lines", "=", "[", "]", "for", "orig_line_idx", ",", "orig_line", "in", "enu...
Interpret backspaces and linefeeds in text like a terminal would. Interpret text like a terminal by removing backspace and linefeed characters and applying them line by line. If final line ends with a carriage it keeps it to be concatenable with next output chunk.
[ "Interpret", "backspaces", "and", "linefeeds", "in", "text", "like", "a", "terminal", "would", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L614-L647
238,311
IDSIA/sacred
sacred/utils.py
module_is_imported
def module_is_imported(modname, scope=None): """Checks if a module is imported within the current namespace.""" # return early if modname is not even cached if not module_is_in_cache(modname): return False if scope is None: # use globals() of the caller by default scope = inspect.stack()[1][0].f_globals for m in scope.values(): if isinstance(m, type(sys)) and m.__name__ == modname: return True return False
python
def module_is_imported(modname, scope=None): # return early if modname is not even cached if not module_is_in_cache(modname): return False if scope is None: # use globals() of the caller by default scope = inspect.stack()[1][0].f_globals for m in scope.values(): if isinstance(m, type(sys)) and m.__name__ == modname: return True return False
[ "def", "module_is_imported", "(", "modname", ",", "scope", "=", "None", ")", ":", "# return early if modname is not even cached", "if", "not", "module_is_in_cache", "(", "modname", ")", ":", "return", "False", "if", "scope", "is", "None", ":", "# use globals() of th...
Checks if a module is imported within the current namespace.
[ "Checks", "if", "a", "module", "is", "imported", "within", "the", "current", "namespace", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L664-L677
238,312
IDSIA/sacred
sacred/observers/telegram_obs.py
TelegramObserver.from_config
def from_config(cls, filename): """ Create a TelegramObserver from a given configuration file. The file can be in any format supported by Sacred (.json, .pickle, [.yaml]). It has to specify a ``token`` and a ``chat_id`` and can optionally set ``silent_completion``,``completed_text``, ``interrupted_text``, and ``failed_text``. """ import telegram d = load_config_file(filename) request = cls.get_proxy_request(d) if 'proxy_url' in d else None if 'token' in d and 'chat_id' in d: bot = telegram.Bot(d['token'], request=request) obs = cls(bot, **d) else: raise ValueError("Telegram configuration file must contain " "entries for 'token' and 'chat_id'!") for k in ['completed_text', 'interrupted_text', 'failed_text']: if k in d: setattr(obs, k, d[k]) return obs
python
def from_config(cls, filename): import telegram d = load_config_file(filename) request = cls.get_proxy_request(d) if 'proxy_url' in d else None if 'token' in d and 'chat_id' in d: bot = telegram.Bot(d['token'], request=request) obs = cls(bot, **d) else: raise ValueError("Telegram configuration file must contain " "entries for 'token' and 'chat_id'!") for k in ['completed_text', 'interrupted_text', 'failed_text']: if k in d: setattr(obs, k, d[k]) return obs
[ "def", "from_config", "(", "cls", ",", "filename", ")", ":", "import", "telegram", "d", "=", "load_config_file", "(", "filename", ")", "request", "=", "cls", ".", "get_proxy_request", "(", "d", ")", "if", "'proxy_url'", "in", "d", "else", "None", "if", "...
Create a TelegramObserver from a given configuration file. The file can be in any format supported by Sacred (.json, .pickle, [.yaml]). It has to specify a ``token`` and a ``chat_id`` and can optionally set ``silent_completion``,``completed_text``, ``interrupted_text``, and ``failed_text``.
[ "Create", "a", "TelegramObserver", "from", "a", "given", "configuration", "file", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/observers/telegram_obs.py#L73-L96
238,313
IDSIA/sacred
sacred/observers/mongo.py
MongoObserver.log_metrics
def log_metrics(self, metrics_by_name, info): """Store new measurements to the database. Take measurements and store them into the metrics collection in the database. Additionally, reference the metrics in the info["metrics"] dictionary. """ if self.metrics is None: # If, for whatever reason, the metrics collection has not been set # do not try to save anything there. return for key in metrics_by_name: query = {"run_id": self.run_entry['_id'], "name": key} push = {"steps": {"$each": metrics_by_name[key]["steps"]}, "values": {"$each": metrics_by_name[key]["values"]}, "timestamps": {"$each": metrics_by_name[key]["timestamps"]} } update = {"$push": push} result = self.metrics.update_one(query, update, upsert=True) if result.upserted_id is not None: # This is the first time we are storing this metric info.setdefault("metrics", []) \ .append({"name": key, "id": str(result.upserted_id)})
python
def log_metrics(self, metrics_by_name, info): if self.metrics is None: # If, for whatever reason, the metrics collection has not been set # do not try to save anything there. return for key in metrics_by_name: query = {"run_id": self.run_entry['_id'], "name": key} push = {"steps": {"$each": metrics_by_name[key]["steps"]}, "values": {"$each": metrics_by_name[key]["values"]}, "timestamps": {"$each": metrics_by_name[key]["timestamps"]} } update = {"$push": push} result = self.metrics.update_one(query, update, upsert=True) if result.upserted_id is not None: # This is the first time we are storing this metric info.setdefault("metrics", []) \ .append({"name": key, "id": str(result.upserted_id)})
[ "def", "log_metrics", "(", "self", ",", "metrics_by_name", ",", "info", ")", ":", "if", "self", ".", "metrics", "is", "None", ":", "# If, for whatever reason, the metrics collection has not been set", "# do not try to save anything there.", "return", "for", "key", "in", ...
Store new measurements to the database. Take measurements and store them into the metrics collection in the database. Additionally, reference the metrics in the info["metrics"] dictionary.
[ "Store", "new", "measurements", "to", "the", "database", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/observers/mongo.py#L220-L244
238,314
IDSIA/sacred
sacred/dependencies.py
get_digest
def get_digest(filename): """Compute the MD5 hash for a given file.""" h = hashlib.md5() with open(filename, 'rb') as f: data = f.read(1 * MB) while data: h.update(data) data = f.read(1 * MB) return h.hexdigest()
python
def get_digest(filename): h = hashlib.md5() with open(filename, 'rb') as f: data = f.read(1 * MB) while data: h.update(data) data = f.read(1 * MB) return h.hexdigest()
[ "def", "get_digest", "(", "filename", ")", ":", "h", "=", "hashlib", ".", "md5", "(", ")", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "f", ":", "data", "=", "f", ".", "read", "(", "1", "*", "MB", ")", "while", "data", ":", "h", ...
Compute the MD5 hash for a given file.
[ "Compute", "the", "MD5", "hash", "for", "a", "given", "file", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/dependencies.py#L102-L110
238,315
IDSIA/sacred
sacred/dependencies.py
get_commit_if_possible
def get_commit_if_possible(filename): """Try to retrieve VCS information for a given file. Currently only supports git using the gitpython package. Parameters ---------- filename : str Returns ------- path: str The base path of the repository commit: str The commit hash is_dirty: bool True if there are uncommitted changes in the repository """ # git if opt.has_gitpython: from git import Repo, InvalidGitRepositoryError try: directory = os.path.dirname(filename) repo = Repo(directory, search_parent_directories=True) try: path = repo.remote().url except ValueError: path = 'git:/' + repo.working_dir is_dirty = repo.is_dirty() commit = repo.head.commit.hexsha return path, commit, is_dirty except (InvalidGitRepositoryError, ValueError): pass return None, None, None
python
def get_commit_if_possible(filename): # git if opt.has_gitpython: from git import Repo, InvalidGitRepositoryError try: directory = os.path.dirname(filename) repo = Repo(directory, search_parent_directories=True) try: path = repo.remote().url except ValueError: path = 'git:/' + repo.working_dir is_dirty = repo.is_dirty() commit = repo.head.commit.hexsha return path, commit, is_dirty except (InvalidGitRepositoryError, ValueError): pass return None, None, None
[ "def", "get_commit_if_possible", "(", "filename", ")", ":", "# git", "if", "opt", ".", "has_gitpython", ":", "from", "git", "import", "Repo", ",", "InvalidGitRepositoryError", "try", ":", "directory", "=", "os", ".", "path", ".", "dirname", "(", "filename", ...
Try to retrieve VCS information for a given file. Currently only supports git using the gitpython package. Parameters ---------- filename : str Returns ------- path: str The base path of the repository commit: str The commit hash is_dirty: bool True if there are uncommitted changes in the repository
[ "Try", "to", "retrieve", "VCS", "information", "for", "a", "given", "file", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/dependencies.py#L113-L146
238,316
IDSIA/sacred
sacred/dependencies.py
convert_path_to_module_parts
def convert_path_to_module_parts(path): """Convert path to a python file into list of module names.""" module_parts = splitall(path) if module_parts[-1] in ['__init__.py', '__init__.pyc']: # remove trailing __init__.py module_parts = module_parts[:-1] else: # remove file extension module_parts[-1], _ = os.path.splitext(module_parts[-1]) return module_parts
python
def convert_path_to_module_parts(path): module_parts = splitall(path) if module_parts[-1] in ['__init__.py', '__init__.pyc']: # remove trailing __init__.py module_parts = module_parts[:-1] else: # remove file extension module_parts[-1], _ = os.path.splitext(module_parts[-1]) return module_parts
[ "def", "convert_path_to_module_parts", "(", "path", ")", ":", "module_parts", "=", "splitall", "(", "path", ")", "if", "module_parts", "[", "-", "1", "]", "in", "[", "'__init__.py'", ",", "'__init__.pyc'", "]", ":", "# remove trailing __init__.py", "module_parts",...
Convert path to a python file into list of module names.
[ "Convert", "path", "to", "a", "python", "file", "into", "list", "of", "module", "names", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/dependencies.py#L299-L308
238,317
IDSIA/sacred
sacred/dependencies.py
is_local_source
def is_local_source(filename, modname, experiment_path): """Check if a module comes from the given experiment path. Check if a module, given by name and filename, is from (a subdirectory of ) the given experiment path. This is used to determine if the module is a local source file, or rather a package dependency. Parameters ---------- filename: str The absolute filename of the module in question. (Usually module.__file__) modname: str The full name of the module including parent namespaces. experiment_path: str The base path of the experiment. Returns ------- bool: True if the module was imported locally from (a subdir of) the experiment_path, and False otherwise. """ if not is_subdir(filename, experiment_path): return False rel_path = os.path.relpath(filename, experiment_path) path_parts = convert_path_to_module_parts(rel_path) mod_parts = modname.split('.') if path_parts == mod_parts: return True if len(path_parts) > len(mod_parts): return False abs_path_parts = convert_path_to_module_parts(os.path.abspath(filename)) return all([p == m for p, m in zip(reversed(abs_path_parts), reversed(mod_parts))])
python
def is_local_source(filename, modname, experiment_path): if not is_subdir(filename, experiment_path): return False rel_path = os.path.relpath(filename, experiment_path) path_parts = convert_path_to_module_parts(rel_path) mod_parts = modname.split('.') if path_parts == mod_parts: return True if len(path_parts) > len(mod_parts): return False abs_path_parts = convert_path_to_module_parts(os.path.abspath(filename)) return all([p == m for p, m in zip(reversed(abs_path_parts), reversed(mod_parts))])
[ "def", "is_local_source", "(", "filename", ",", "modname", ",", "experiment_path", ")", ":", "if", "not", "is_subdir", "(", "filename", ",", "experiment_path", ")", ":", "return", "False", "rel_path", "=", "os", ".", "path", ".", "relpath", "(", "filename", ...
Check if a module comes from the given experiment path. Check if a module, given by name and filename, is from (a subdirectory of ) the given experiment path. This is used to determine if the module is a local source file, or rather a package dependency. Parameters ---------- filename: str The absolute filename of the module in question. (Usually module.__file__) modname: str The full name of the module including parent namespaces. experiment_path: str The base path of the experiment. Returns ------- bool: True if the module was imported locally from (a subdir of) the experiment_path, and False otherwise.
[ "Check", "if", "a", "module", "comes", "from", "the", "given", "experiment", "path", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/dependencies.py#L311-L347
238,318
IDSIA/sacred
sacred/dependencies.py
gather_sources_and_dependencies
def gather_sources_and_dependencies(globs, base_dir=None): """Scan the given globals for modules and return them as dependencies.""" experiment_path, main = get_main_file(globs) base_dir = base_dir or experiment_path gather_sources = source_discovery_strategies[SETTINGS['DISCOVER_SOURCES']] sources = gather_sources(globs, base_dir) if main is not None: sources.add(main) gather_dependencies = dependency_discovery_strategies[ SETTINGS['DISCOVER_DEPENDENCIES']] dependencies = gather_dependencies(globs, base_dir) if opt.has_numpy: # Add numpy as a dependency because it might be used for randomness dependencies.add(PackageDependency.create(opt.np)) return main, sources, dependencies
python
def gather_sources_and_dependencies(globs, base_dir=None): experiment_path, main = get_main_file(globs) base_dir = base_dir or experiment_path gather_sources = source_discovery_strategies[SETTINGS['DISCOVER_SOURCES']] sources = gather_sources(globs, base_dir) if main is not None: sources.add(main) gather_dependencies = dependency_discovery_strategies[ SETTINGS['DISCOVER_DEPENDENCIES']] dependencies = gather_dependencies(globs, base_dir) if opt.has_numpy: # Add numpy as a dependency because it might be used for randomness dependencies.add(PackageDependency.create(opt.np)) return main, sources, dependencies
[ "def", "gather_sources_and_dependencies", "(", "globs", ",", "base_dir", "=", "None", ")", ":", "experiment_path", ",", "main", "=", "get_main_file", "(", "globs", ")", "base_dir", "=", "base_dir", "or", "experiment_path", "gather_sources", "=", "source_discovery_st...
Scan the given globals for modules and return them as dependencies.
[ "Scan", "the", "given", "globals", "for", "modules", "and", "return", "them", "as", "dependencies", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/dependencies.py#L481-L501
238,319
IDSIA/sacred
sacred/config/utils.py
assert_is_valid_key
def assert_is_valid_key(key): """ Raise KeyError if a given config key violates any requirements. The requirements are the following and can be individually deactivated in ``sacred.SETTINGS.CONFIG_KEYS``: * ENFORCE_MONGO_COMPATIBLE (default: True): make sure the keys don't contain a '.' or start with a '$' * ENFORCE_JSONPICKLE_COMPATIBLE (default: True): make sure the keys do not contain any reserved jsonpickle tags This is very important. Only deactivate if you know what you are doing. * ENFORCE_STRING (default: False): make sure all keys are string. * ENFORCE_VALID_PYTHON_IDENTIFIER (default: False): make sure all keys are valid python identifiers. Parameters ---------- key: The key that should be checked Raises ------ KeyError: if the key violates any requirements """ if SETTINGS.CONFIG.ENFORCE_KEYS_MONGO_COMPATIBLE and ( isinstance(key, basestring) and ('.' in key or key[0] == '$')): raise KeyError('Invalid key "{}". Config-keys cannot ' 'contain "." or start with "$"'.format(key)) if SETTINGS.CONFIG.ENFORCE_KEYS_JSONPICKLE_COMPATIBLE and \ isinstance(key, basestring) and ( key in jsonpickle.tags.RESERVED or key.startswith('json://')): raise KeyError('Invalid key "{}". Config-keys cannot be one of the' 'reserved jsonpickle tags: {}' .format(key, jsonpickle.tags.RESERVED)) if SETTINGS.CONFIG.ENFORCE_STRING_KEYS and ( not isinstance(key, basestring)): raise KeyError('Invalid key "{}". Config-keys have to be strings, ' 'but was {}'.format(key, type(key))) if SETTINGS.CONFIG.ENFORCE_VALID_PYTHON_IDENTIFIER_KEYS and ( isinstance(key, basestring) and not PYTHON_IDENTIFIER.match(key)): raise KeyError('Key "{}" is not a valid python identifier' .format(key)) if SETTINGS.CONFIG.ENFORCE_KEYS_NO_EQUALS and ( isinstance(key, basestring) and '=' in key): raise KeyError('Invalid key "{}". Config keys may not contain an' 'equals sign ("=").'.format('='))
python
def assert_is_valid_key(key): if SETTINGS.CONFIG.ENFORCE_KEYS_MONGO_COMPATIBLE and ( isinstance(key, basestring) and ('.' in key or key[0] == '$')): raise KeyError('Invalid key "{}". Config-keys cannot ' 'contain "." or start with "$"'.format(key)) if SETTINGS.CONFIG.ENFORCE_KEYS_JSONPICKLE_COMPATIBLE and \ isinstance(key, basestring) and ( key in jsonpickle.tags.RESERVED or key.startswith('json://')): raise KeyError('Invalid key "{}". Config-keys cannot be one of the' 'reserved jsonpickle tags: {}' .format(key, jsonpickle.tags.RESERVED)) if SETTINGS.CONFIG.ENFORCE_STRING_KEYS and ( not isinstance(key, basestring)): raise KeyError('Invalid key "{}". Config-keys have to be strings, ' 'but was {}'.format(key, type(key))) if SETTINGS.CONFIG.ENFORCE_VALID_PYTHON_IDENTIFIER_KEYS and ( isinstance(key, basestring) and not PYTHON_IDENTIFIER.match(key)): raise KeyError('Key "{}" is not a valid python identifier' .format(key)) if SETTINGS.CONFIG.ENFORCE_KEYS_NO_EQUALS and ( isinstance(key, basestring) and '=' in key): raise KeyError('Invalid key "{}". Config keys may not contain an' 'equals sign ("=").'.format('='))
[ "def", "assert_is_valid_key", "(", "key", ")", ":", "if", "SETTINGS", ".", "CONFIG", ".", "ENFORCE_KEYS_MONGO_COMPATIBLE", "and", "(", "isinstance", "(", "key", ",", "basestring", ")", "and", "(", "'.'", "in", "key", "or", "key", "[", "0", "]", "==", "'$...
Raise KeyError if a given config key violates any requirements. The requirements are the following and can be individually deactivated in ``sacred.SETTINGS.CONFIG_KEYS``: * ENFORCE_MONGO_COMPATIBLE (default: True): make sure the keys don't contain a '.' or start with a '$' * ENFORCE_JSONPICKLE_COMPATIBLE (default: True): make sure the keys do not contain any reserved jsonpickle tags This is very important. Only deactivate if you know what you are doing. * ENFORCE_STRING (default: False): make sure all keys are string. * ENFORCE_VALID_PYTHON_IDENTIFIER (default: False): make sure all keys are valid python identifiers. Parameters ---------- key: The key that should be checked Raises ------ KeyError: if the key violates any requirements
[ "Raise", "KeyError", "if", "a", "given", "config", "key", "violates", "any", "requirements", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/config/utils.py#L13-L65
238,320
IDSIA/sacred
sacred/observers/slack.py
SlackObserver.from_config
def from_config(cls, filename): """ Create a SlackObserver from a given configuration file. The file can be in any format supported by Sacred (.json, .pickle, [.yaml]). It has to specify a ``webhook_url`` and can optionally set ``bot_name``, ``icon``, ``completed_text``, ``interrupted_text``, and ``failed_text``. """ d = load_config_file(filename) obs = None if 'webhook_url' in d: obs = cls(d['webhook_url']) else: raise ValueError("Slack configuration file must contain " "an entry for 'webhook_url'!") for k in ['completed_text', 'interrupted_text', 'failed_text', 'bot_name', 'icon']: if k in d: setattr(obs, k, d[k]) return obs
python
def from_config(cls, filename): d = load_config_file(filename) obs = None if 'webhook_url' in d: obs = cls(d['webhook_url']) else: raise ValueError("Slack configuration file must contain " "an entry for 'webhook_url'!") for k in ['completed_text', 'interrupted_text', 'failed_text', 'bot_name', 'icon']: if k in d: setattr(obs, k, d[k]) return obs
[ "def", "from_config", "(", "cls", ",", "filename", ")", ":", "d", "=", "load_config_file", "(", "filename", ")", "obs", "=", "None", "if", "'webhook_url'", "in", "d", ":", "obs", "=", "cls", "(", "d", "[", "'webhook_url'", "]", ")", "else", ":", "rai...
Create a SlackObserver from a given configuration file. The file can be in any format supported by Sacred (.json, .pickle, [.yaml]). It has to specify a ``webhook_url`` and can optionally set ``bot_name``, ``icon``, ``completed_text``, ``interrupted_text``, and ``failed_text``.
[ "Create", "a", "SlackObserver", "from", "a", "given", "configuration", "file", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/observers/slack.py#L44-L65
238,321
IDSIA/sacred
sacred/host_info.py
get_host_info
def get_host_info(): """Collect some information about the machine this experiment runs on. Returns ------- dict A dictionary with information about the CPU, the OS and the Python version of this machine. """ host_info = {} for k, v in host_info_gatherers.items(): try: host_info[k] = v() except IgnoreHostInfo: pass return host_info
python
def get_host_info(): host_info = {} for k, v in host_info_gatherers.items(): try: host_info[k] = v() except IgnoreHostInfo: pass return host_info
[ "def", "get_host_info", "(", ")", ":", "host_info", "=", "{", "}", "for", "k", ",", "v", "in", "host_info_gatherers", ".", "items", "(", ")", ":", "try", ":", "host_info", "[", "k", "]", "=", "v", "(", ")", "except", "IgnoreHostInfo", ":", "pass", ...
Collect some information about the machine this experiment runs on. Returns ------- dict A dictionary with information about the CPU, the OS and the Python version of this machine.
[ "Collect", "some", "information", "about", "the", "machine", "this", "experiment", "runs", "on", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/host_info.py#L27-L43
238,322
IDSIA/sacred
sacred/host_info.py
host_info_getter
def host_info_getter(func, name=None): """ The decorated function is added to the process of collecting the host_info. This just adds the decorated function to the global ``sacred.host_info.host_info_gatherers`` dictionary. The functions from that dictionary are used when collecting the host info using :py:func:`~sacred.host_info.get_host_info`. Parameters ---------- func : callable A function that can be called without arguments and returns some json-serializable information. name : str, optional The name of the corresponding entry in host_info. Defaults to the name of the function. Returns ------- The function itself. """ name = name or func.__name__ host_info_gatherers[name] = func return func
python
def host_info_getter(func, name=None): name = name or func.__name__ host_info_gatherers[name] = func return func
[ "def", "host_info_getter", "(", "func", ",", "name", "=", "None", ")", ":", "name", "=", "name", "or", "func", ".", "__name__", "host_info_gatherers", "[", "name", "]", "=", "func", "return", "func" ]
The decorated function is added to the process of collecting the host_info. This just adds the decorated function to the global ``sacred.host_info.host_info_gatherers`` dictionary. The functions from that dictionary are used when collecting the host info using :py:func:`~sacred.host_info.get_host_info`. Parameters ---------- func : callable A function that can be called without arguments and returns some json-serializable information. name : str, optional The name of the corresponding entry in host_info. Defaults to the name of the function. Returns ------- The function itself.
[ "The", "decorated", "function", "is", "added", "to", "the", "process", "of", "collecting", "the", "host_info", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/host_info.py#L47-L72
238,323
IDSIA/sacred
sacred/metrics_logger.py
linearize_metrics
def linearize_metrics(logged_metrics): """ Group metrics by name. Takes a list of individual measurements, possibly belonging to different metrics and groups them by name. :param logged_metrics: A list of ScalarMetricLogEntries :return: Measured values grouped by the metric name: {"metric_name1": {"steps": [0,1,2], "values": [4, 5, 6], "timestamps": [datetime, datetime, datetime]}, "metric_name2": {...}} """ metrics_by_name = {} for metric_entry in logged_metrics: if metric_entry.name not in metrics_by_name: metrics_by_name[metric_entry.name] = { "steps": [], "values": [], "timestamps": [], "name": metric_entry.name } metrics_by_name[metric_entry.name]["steps"] \ .append(metric_entry.step) metrics_by_name[metric_entry.name]["values"] \ .append(metric_entry.value) metrics_by_name[metric_entry.name]["timestamps"] \ .append(metric_entry.timestamp) return metrics_by_name
python
def linearize_metrics(logged_metrics): metrics_by_name = {} for metric_entry in logged_metrics: if metric_entry.name not in metrics_by_name: metrics_by_name[metric_entry.name] = { "steps": [], "values": [], "timestamps": [], "name": metric_entry.name } metrics_by_name[metric_entry.name]["steps"] \ .append(metric_entry.step) metrics_by_name[metric_entry.name]["values"] \ .append(metric_entry.value) metrics_by_name[metric_entry.name]["timestamps"] \ .append(metric_entry.timestamp) return metrics_by_name
[ "def", "linearize_metrics", "(", "logged_metrics", ")", ":", "metrics_by_name", "=", "{", "}", "for", "metric_entry", "in", "logged_metrics", ":", "if", "metric_entry", ".", "name", "not", "in", "metrics_by_name", ":", "metrics_by_name", "[", "metric_entry", ".", ...
Group metrics by name. Takes a list of individual measurements, possibly belonging to different metrics and groups them by name. :param logged_metrics: A list of ScalarMetricLogEntries :return: Measured values grouped by the metric name: {"metric_name1": {"steps": [0,1,2], "values": [4, 5, 6], "timestamps": [datetime, datetime, datetime]}, "metric_name2": {...}}
[ "Group", "metrics", "by", "name", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/metrics_logger.py#L85-L113
238,324
IDSIA/sacred
sacred/metrics_logger.py
MetricsLogger.get_last_metrics
def get_last_metrics(self): """Read all measurement events since last call of the method. :return List[ScalarMetricLogEntry] """ read_up_to = self._logged_metrics.qsize() messages = [] for i in range(read_up_to): try: messages.append(self._logged_metrics.get_nowait()) except Empty: pass return messages
python
def get_last_metrics(self): read_up_to = self._logged_metrics.qsize() messages = [] for i in range(read_up_to): try: messages.append(self._logged_metrics.get_nowait()) except Empty: pass return messages
[ "def", "get_last_metrics", "(", "self", ")", ":", "read_up_to", "=", "self", ".", "_logged_metrics", ".", "qsize", "(", ")", "messages", "=", "[", "]", "for", "i", "in", "range", "(", "read_up_to", ")", ":", "try", ":", "messages", ".", "append", "(", ...
Read all measurement events since last call of the method. :return List[ScalarMetricLogEntry]
[ "Read", "all", "measurement", "events", "since", "last", "call", "of", "the", "method", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/metrics_logger.py#L57-L69
238,325
IDSIA/sacred
sacred/commandline_options.py
gather_command_line_options
def gather_command_line_options(filter_disabled=None): """Get a sorted list of all CommandLineOption subclasses.""" if filter_disabled is None: filter_disabled = not SETTINGS.COMMAND_LINE.SHOW_DISABLED_OPTIONS options = [opt for opt in get_inheritors(CommandLineOption) if not filter_disabled or opt._enabled] return sorted(options, key=lambda opt: opt.__name__)
python
def gather_command_line_options(filter_disabled=None): if filter_disabled is None: filter_disabled = not SETTINGS.COMMAND_LINE.SHOW_DISABLED_OPTIONS options = [opt for opt in get_inheritors(CommandLineOption) if not filter_disabled or opt._enabled] return sorted(options, key=lambda opt: opt.__name__)
[ "def", "gather_command_line_options", "(", "filter_disabled", "=", "None", ")", ":", "if", "filter_disabled", "is", "None", ":", "filter_disabled", "=", "not", "SETTINGS", ".", "COMMAND_LINE", ".", "SHOW_DISABLED_OPTIONS", "options", "=", "[", "opt", "for", "opt",...
Get a sorted list of all CommandLineOption subclasses.
[ "Get", "a", "sorted", "list", "of", "all", "CommandLineOption", "subclasses", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/commandline_options.py#L159-L165
238,326
IDSIA/sacred
sacred/commandline_options.py
LoglevelOption.apply
def apply(cls, args, run): """Adjust the loglevel of the root-logger of this run.""" # TODO: sacred.initialize.create_run already takes care of this try: lvl = int(args) except ValueError: lvl = args run.root_logger.setLevel(lvl)
python
def apply(cls, args, run): # TODO: sacred.initialize.create_run already takes care of this try: lvl = int(args) except ValueError: lvl = args run.root_logger.setLevel(lvl)
[ "def", "apply", "(", "cls", ",", "args", ",", "run", ")", ":", "# TODO: sacred.initialize.create_run already takes care of this", "try", ":", "lvl", "=", "int", "(", "args", ")", "except", "ValueError", ":", "lvl", "=", "args", "run", ".", "root_logger", ".", ...
Adjust the loglevel of the root-logger of this run.
[ "Adjust", "the", "loglevel", "of", "the", "root", "-", "logger", "of", "this", "run", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/commandline_options.py#L203-L211
238,327
IDSIA/sacred
sacred/commandline_options.py
PriorityOption.apply
def apply(cls, args, run): """Add priority info for this run.""" try: priority = float(args) except ValueError: raise ValueError("The PRIORITY argument must be a number! " "(but was '{}')".format(args)) run.meta_info['priority'] = priority
python
def apply(cls, args, run): try: priority = float(args) except ValueError: raise ValueError("The PRIORITY argument must be a number! " "(but was '{}')".format(args)) run.meta_info['priority'] = priority
[ "def", "apply", "(", "cls", ",", "args", ",", "run", ")", ":", "try", ":", "priority", "=", "float", "(", "args", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "\"The PRIORITY argument must be a number! \"", "\"(but was '{}')\"", ".", "format", ...
Add priority info for this run.
[ "Add", "priority", "info", "for", "this", "run", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/commandline_options.py#L273-L280
238,328
IDSIA/sacred
sacred/ingredient.py
Ingredient.capture
def capture(self, function=None, prefix=None): """ Decorator to turn a function into a captured function. The missing arguments of captured functions are automatically filled from the configuration if possible. See :ref:`captured_functions` for more information. If a ``prefix`` is specified, the search for suitable entries is performed in the corresponding subtree of the configuration. """ if function in self.captured_functions: return function captured_function = create_captured_function(function, prefix=prefix) self.captured_functions.append(captured_function) return captured_function
python
def capture(self, function=None, prefix=None): if function in self.captured_functions: return function captured_function = create_captured_function(function, prefix=prefix) self.captured_functions.append(captured_function) return captured_function
[ "def", "capture", "(", "self", ",", "function", "=", "None", ",", "prefix", "=", "None", ")", ":", "if", "function", "in", "self", ".", "captured_functions", ":", "return", "function", "captured_function", "=", "create_captured_function", "(", "function", ",",...
Decorator to turn a function into a captured function. The missing arguments of captured functions are automatically filled from the configuration if possible. See :ref:`captured_functions` for more information. If a ``prefix`` is specified, the search for suitable entries is performed in the corresponding subtree of the configuration.
[ "Decorator", "to", "turn", "a", "function", "into", "a", "captured", "function", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L80-L95
238,329
IDSIA/sacred
sacred/ingredient.py
Ingredient.pre_run_hook
def pre_run_hook(self, func, prefix=None): """ Decorator to add a pre-run hook to this ingredient. Pre-run hooks are captured functions that are run, just before the main function is executed. """ cf = self.capture(func, prefix=prefix) self.pre_run_hooks.append(cf) return cf
python
def pre_run_hook(self, func, prefix=None): cf = self.capture(func, prefix=prefix) self.pre_run_hooks.append(cf) return cf
[ "def", "pre_run_hook", "(", "self", ",", "func", ",", "prefix", "=", "None", ")", ":", "cf", "=", "self", ".", "capture", "(", "func", ",", "prefix", "=", "prefix", ")", "self", ".", "pre_run_hooks", ".", "append", "(", "cf", ")", "return", "cf" ]
Decorator to add a pre-run hook to this ingredient. Pre-run hooks are captured functions that are run, just before the main function is executed.
[ "Decorator", "to", "add", "a", "pre", "-", "run", "hook", "to", "this", "ingredient", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L98-L107
238,330
IDSIA/sacred
sacred/ingredient.py
Ingredient.post_run_hook
def post_run_hook(self, func, prefix=None): """ Decorator to add a post-run hook to this ingredient. Post-run hooks are captured functions that are run, just after the main function is executed. """ cf = self.capture(func, prefix=prefix) self.post_run_hooks.append(cf) return cf
python
def post_run_hook(self, func, prefix=None): cf = self.capture(func, prefix=prefix) self.post_run_hooks.append(cf) return cf
[ "def", "post_run_hook", "(", "self", ",", "func", ",", "prefix", "=", "None", ")", ":", "cf", "=", "self", ".", "capture", "(", "func", ",", "prefix", "=", "prefix", ")", "self", ".", "post_run_hooks", ".", "append", "(", "cf", ")", "return", "cf" ]
Decorator to add a post-run hook to this ingredient. Post-run hooks are captured functions that are run, just after the main function is executed.
[ "Decorator", "to", "add", "a", "post", "-", "run", "hook", "to", "this", "ingredient", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L110-L119
238,331
IDSIA/sacred
sacred/ingredient.py
Ingredient.command
def command(self, function=None, prefix=None, unobserved=False): """ Decorator to define a new command for this Ingredient or Experiment. The name of the command will be the name of the function. It can be called from the command-line or by using the run_command function. Commands are automatically also captured functions. The command can be given a prefix, to restrict its configuration space to a subtree. (see ``capture`` for more information) A command can be made unobserved (i.e. ignoring all observers) by passing the unobserved=True keyword argument. """ captured_f = self.capture(function, prefix=prefix) captured_f.unobserved = unobserved self.commands[function.__name__] = captured_f return captured_f
python
def command(self, function=None, prefix=None, unobserved=False): captured_f = self.capture(function, prefix=prefix) captured_f.unobserved = unobserved self.commands[function.__name__] = captured_f return captured_f
[ "def", "command", "(", "self", ",", "function", "=", "None", ",", "prefix", "=", "None", ",", "unobserved", "=", "False", ")", ":", "captured_f", "=", "self", ".", "capture", "(", "function", ",", "prefix", "=", "prefix", ")", "captured_f", ".", "unobs...
Decorator to define a new command for this Ingredient or Experiment. The name of the command will be the name of the function. It can be called from the command-line or by using the run_command function. Commands are automatically also captured functions. The command can be given a prefix, to restrict its configuration space to a subtree. (see ``capture`` for more information) A command can be made unobserved (i.e. ignoring all observers) by passing the unobserved=True keyword argument.
[ "Decorator", "to", "define", "a", "new", "command", "for", "this", "Ingredient", "or", "Experiment", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L122-L140
238,332
IDSIA/sacred
sacred/ingredient.py
Ingredient.config
def config(self, function): """ Decorator to add a function to the configuration of the Experiment. The decorated function is turned into a :class:`~sacred.config_scope.ConfigScope` and added to the Ingredient/Experiment. When the experiment is run, this function will also be executed and all json-serializable local variables inside it will end up as entries in the configuration of the experiment. """ self.configurations.append(ConfigScope(function)) return self.configurations[-1]
python
def config(self, function): self.configurations.append(ConfigScope(function)) return self.configurations[-1]
[ "def", "config", "(", "self", ",", "function", ")", ":", "self", ".", "configurations", ".", "append", "(", "ConfigScope", "(", "function", ")", ")", "return", "self", ".", "configurations", "[", "-", "1", "]" ]
Decorator to add a function to the configuration of the Experiment. The decorated function is turned into a :class:`~sacred.config_scope.ConfigScope` and added to the Ingredient/Experiment. When the experiment is run, this function will also be executed and all json-serializable local variables inside it will end up as entries in the configuration of the experiment.
[ "Decorator", "to", "add", "a", "function", "to", "the", "configuration", "of", "the", "Experiment", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L142-L155
238,333
IDSIA/sacred
sacred/ingredient.py
Ingredient.named_config
def named_config(self, func): """ Decorator to turn a function into a named configuration. See :ref:`named_configurations`. """ config_scope = ConfigScope(func) self._add_named_config(func.__name__, config_scope) return config_scope
python
def named_config(self, func): config_scope = ConfigScope(func) self._add_named_config(func.__name__, config_scope) return config_scope
[ "def", "named_config", "(", "self", ",", "func", ")", ":", "config_scope", "=", "ConfigScope", "(", "func", ")", "self", ".", "_add_named_config", "(", "func", ".", "__name__", ",", "config_scope", ")", "return", "config_scope" ]
Decorator to turn a function into a named configuration. See :ref:`named_configurations`.
[ "Decorator", "to", "turn", "a", "function", "into", "a", "named", "configuration", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L157-L165
238,334
IDSIA/sacred
sacred/ingredient.py
Ingredient.config_hook
def config_hook(self, func): """ Decorator to add a config hook to this ingredient. Config hooks need to be a function that takes 3 parameters and returns a dictionary: (config, command_name, logger) --> dict Config hooks are run after the configuration of this Ingredient, but before any further ingredient-configurations are run. The dictionary returned by a config hook is used to update the config updates. Note that they are not restricted to the local namespace of the ingredient. """ argspec = inspect.getargspec(func) args = ['config', 'command_name', 'logger'] if not (argspec.args == args and argspec.varargs is None and argspec.keywords is None and argspec.defaults is None): raise ValueError('Wrong signature for config_hook. Expected: ' '(config, command_name, logger)') self.config_hooks.append(func) return self.config_hooks[-1]
python
def config_hook(self, func): argspec = inspect.getargspec(func) args = ['config', 'command_name', 'logger'] if not (argspec.args == args and argspec.varargs is None and argspec.keywords is None and argspec.defaults is None): raise ValueError('Wrong signature for config_hook. Expected: ' '(config, command_name, logger)') self.config_hooks.append(func) return self.config_hooks[-1]
[ "def", "config_hook", "(", "self", ",", "func", ")", ":", "argspec", "=", "inspect", ".", "getargspec", "(", "func", ")", "args", "=", "[", "'config'", ",", "'command_name'", ",", "'logger'", "]", "if", "not", "(", "argspec", ".", "args", "==", "args",...
Decorator to add a config hook to this ingredient. Config hooks need to be a function that takes 3 parameters and returns a dictionary: (config, command_name, logger) --> dict Config hooks are run after the configuration of this Ingredient, but before any further ingredient-configurations are run. The dictionary returned by a config hook is used to update the config updates. Note that they are not restricted to the local namespace of the ingredient.
[ "Decorator", "to", "add", "a", "config", "hook", "to", "this", "ingredient", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L167-L189
238,335
IDSIA/sacred
sacred/ingredient.py
Ingredient.add_package_dependency
def add_package_dependency(self, package_name, version): """ Add a package to the list of dependencies. :param package_name: The name of the package dependency :type package_name: str :param version: The (minimum) version of the package :type version: str """ if not PEP440_VERSION_PATTERN.match(version): raise ValueError('Invalid Version: "{}"'.format(version)) self.dependencies.add(PackageDependency(package_name, version))
python
def add_package_dependency(self, package_name, version): if not PEP440_VERSION_PATTERN.match(version): raise ValueError('Invalid Version: "{}"'.format(version)) self.dependencies.add(PackageDependency(package_name, version))
[ "def", "add_package_dependency", "(", "self", ",", "package_name", ",", "version", ")", ":", "if", "not", "PEP440_VERSION_PATTERN", ".", "match", "(", "version", ")", ":", "raise", "ValueError", "(", "'Invalid Version: \"{}\"'", ".", "format", "(", "version", ")...
Add a package to the list of dependencies. :param package_name: The name of the package dependency :type package_name: str :param version: The (minimum) version of the package :type version: str
[ "Add", "a", "package", "to", "the", "list", "of", "dependencies", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L272-L283
238,336
IDSIA/sacred
sacred/ingredient.py
Ingredient._gather
def _gather(self, func): """ Function needed and used by gathering functions through the decorator `gather_from_ingredients` in `Ingredient`. Don't use this function by itself outside of the decorator! By overwriting this function you can filter what is visible when gathering something (e.g. commands). See `Experiment._gather` for an example. """ for ingredient, _ in self.traverse_ingredients(): for item in func(ingredient): yield item
python
def _gather(self, func): for ingredient, _ in self.traverse_ingredients(): for item in func(ingredient): yield item
[ "def", "_gather", "(", "self", ",", "func", ")", ":", "for", "ingredient", ",", "_", "in", "self", ".", "traverse_ingredients", "(", ")", ":", "for", "item", "in", "func", "(", "ingredient", ")", ":", "yield", "item" ]
Function needed and used by gathering functions through the decorator `gather_from_ingredients` in `Ingredient`. Don't use this function by itself outside of the decorator! By overwriting this function you can filter what is visible when gathering something (e.g. commands). See `Experiment._gather` for an example.
[ "Function", "needed", "and", "used", "by", "gathering", "functions", "through", "the", "decorator", "gather_from_ingredients", "in", "Ingredient", ".", "Don", "t", "use", "this", "function", "by", "itself", "outside", "of", "the", "decorator!" ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L285-L297
238,337
IDSIA/sacred
sacred/ingredient.py
Ingredient.gather_commands
def gather_commands(self, ingredient): """Collect all commands from this ingredient and its sub-ingredients. Yields ------ cmd_name: str The full (dotted) name of the command. cmd: function The corresponding captured function. """ for command_name, command in ingredient.commands.items(): yield join_paths(ingredient.path, command_name), command
python
def gather_commands(self, ingredient): for command_name, command in ingredient.commands.items(): yield join_paths(ingredient.path, command_name), command
[ "def", "gather_commands", "(", "self", ",", "ingredient", ")", ":", "for", "command_name", ",", "command", "in", "ingredient", ".", "commands", ".", "items", "(", ")", ":", "yield", "join_paths", "(", "ingredient", ".", "path", ",", "command_name", ")", ",...
Collect all commands from this ingredient and its sub-ingredients. Yields ------ cmd_name: str The full (dotted) name of the command. cmd: function The corresponding captured function.
[ "Collect", "all", "commands", "from", "this", "ingredient", "and", "its", "sub", "-", "ingredients", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L300-L311
238,338
IDSIA/sacred
sacred/ingredient.py
Ingredient.gather_named_configs
def gather_named_configs(self, ingredient): """Collect all named configs from this ingredient and its sub-ingredients. Yields ------ config_name: str The full (dotted) name of the named config. config: ConfigScope or ConfigDict or basestring The corresponding named config. """ for config_name, config in ingredient.named_configs.items(): yield join_paths(ingredient.path, config_name), config
python
def gather_named_configs(self, ingredient): for config_name, config in ingredient.named_configs.items(): yield join_paths(ingredient.path, config_name), config
[ "def", "gather_named_configs", "(", "self", ",", "ingredient", ")", ":", "for", "config_name", ",", "config", "in", "ingredient", ".", "named_configs", ".", "items", "(", ")", ":", "yield", "join_paths", "(", "ingredient", ".", "path", ",", "config_name", ")...
Collect all named configs from this ingredient and its sub-ingredients. Yields ------ config_name: str The full (dotted) name of the named config. config: ConfigScope or ConfigDict or basestring The corresponding named config.
[ "Collect", "all", "named", "configs", "from", "this", "ingredient", "and", "its", "sub", "-", "ingredients", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L314-L326
238,339
IDSIA/sacred
sacred/ingredient.py
Ingredient.get_experiment_info
def get_experiment_info(self): """Get a dictionary with information about this experiment. Contains: * *name*: the name * *sources*: a list of sources (filename, md5) * *dependencies*: a list of package dependencies (name, version) :return: experiment information :rtype: dict """ dependencies = set() sources = set() for ing, _ in self.traverse_ingredients(): dependencies |= ing.dependencies sources |= ing.sources for dep in dependencies: dep.fill_missing_version() mainfile = (self.mainfile.to_json(self.base_dir)[0] if self.mainfile else None) def name_lower(d): return d.name.lower() return dict( name=self.path, base_dir=self.base_dir, sources=[s.to_json(self.base_dir) for s in sorted(sources)], dependencies=[d.to_json() for d in sorted(dependencies, key=name_lower)], repositories=collect_repositories(sources), mainfile=mainfile )
python
def get_experiment_info(self): dependencies = set() sources = set() for ing, _ in self.traverse_ingredients(): dependencies |= ing.dependencies sources |= ing.sources for dep in dependencies: dep.fill_missing_version() mainfile = (self.mainfile.to_json(self.base_dir)[0] if self.mainfile else None) def name_lower(d): return d.name.lower() return dict( name=self.path, base_dir=self.base_dir, sources=[s.to_json(self.base_dir) for s in sorted(sources)], dependencies=[d.to_json() for d in sorted(dependencies, key=name_lower)], repositories=collect_repositories(sources), mainfile=mainfile )
[ "def", "get_experiment_info", "(", "self", ")", ":", "dependencies", "=", "set", "(", ")", "sources", "=", "set", "(", ")", "for", "ing", ",", "_", "in", "self", ".", "traverse_ingredients", "(", ")", ":", "dependencies", "|=", "ing", ".", "dependencies"...
Get a dictionary with information about this experiment. Contains: * *name*: the name * *sources*: a list of sources (filename, md5) * *dependencies*: a list of package dependencies (name, version) :return: experiment information :rtype: dict
[ "Get", "a", "dictionary", "with", "information", "about", "this", "experiment", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L328-L362
238,340
IDSIA/sacred
sacred/ingredient.py
Ingredient.traverse_ingredients
def traverse_ingredients(self): """Recursively traverse this ingredient and its sub-ingredients. Yields ------ ingredient: sacred.Ingredient The ingredient as traversed in preorder. depth: int The depth of the ingredient starting from 0. Raises ------ CircularDependencyError: If a circular structure among ingredients was detected. """ if self._is_traversing: raise CircularDependencyError(ingredients=[self]) else: self._is_traversing = True yield self, 0 with CircularDependencyError.track(self): for ingredient in self.ingredients: for ingred, depth in ingredient.traverse_ingredients(): yield ingred, depth + 1 self._is_traversing = False
python
def traverse_ingredients(self): if self._is_traversing: raise CircularDependencyError(ingredients=[self]) else: self._is_traversing = True yield self, 0 with CircularDependencyError.track(self): for ingredient in self.ingredients: for ingred, depth in ingredient.traverse_ingredients(): yield ingred, depth + 1 self._is_traversing = False
[ "def", "traverse_ingredients", "(", "self", ")", ":", "if", "self", ".", "_is_traversing", ":", "raise", "CircularDependencyError", "(", "ingredients", "=", "[", "self", "]", ")", "else", ":", "self", ".", "_is_traversing", "=", "True", "yield", "self", ",",...
Recursively traverse this ingredient and its sub-ingredients. Yields ------ ingredient: sacred.Ingredient The ingredient as traversed in preorder. depth: int The depth of the ingredient starting from 0. Raises ------ CircularDependencyError: If a circular structure among ingredients was detected.
[ "Recursively", "traverse", "this", "ingredient", "and", "its", "sub", "-", "ingredients", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L364-L388
238,341
simonw/datasette
datasette/utils.py
path_from_row_pks
def path_from_row_pks(row, pks, use_rowid, quote=True): """ Generate an optionally URL-quoted unique identifier for a row from its primary keys.""" if use_rowid: bits = [row['rowid']] else: bits = [ row[pk]["value"] if isinstance(row[pk], dict) else row[pk] for pk in pks ] if quote: bits = [urllib.parse.quote_plus(str(bit)) for bit in bits] else: bits = [str(bit) for bit in bits] return ','.join(bits)
python
def path_from_row_pks(row, pks, use_rowid, quote=True): if use_rowid: bits = [row['rowid']] else: bits = [ row[pk]["value"] if isinstance(row[pk], dict) else row[pk] for pk in pks ] if quote: bits = [urllib.parse.quote_plus(str(bit)) for bit in bits] else: bits = [str(bit) for bit in bits] return ','.join(bits)
[ "def", "path_from_row_pks", "(", "row", ",", "pks", ",", "use_rowid", ",", "quote", "=", "True", ")", ":", "if", "use_rowid", ":", "bits", "=", "[", "row", "[", "'rowid'", "]", "]", "else", ":", "bits", "=", "[", "row", "[", "pk", "]", "[", "\"va...
Generate an optionally URL-quoted unique identifier for a row from its primary keys.
[ "Generate", "an", "optionally", "URL", "-", "quoted", "unique", "identifier", "for", "a", "row", "from", "its", "primary", "keys", "." ]
11b352b4d52fd02a422776edebb14f12e4994d3b
https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/utils.py#L75-L90
238,342
simonw/datasette
datasette/utils.py
detect_primary_keys
def detect_primary_keys(conn, table): " Figure out primary keys for a table. " table_info_rows = [ row for row in conn.execute( 'PRAGMA table_info("{}")'.format(table) ).fetchall() if row[-1] ] table_info_rows.sort(key=lambda row: row[-1]) return [str(r[1]) for r in table_info_rows]
python
def detect_primary_keys(conn, table): " Figure out primary keys for a table. " table_info_rows = [ row for row in conn.execute( 'PRAGMA table_info("{}")'.format(table) ).fetchall() if row[-1] ] table_info_rows.sort(key=lambda row: row[-1]) return [str(r[1]) for r in table_info_rows]
[ "def", "detect_primary_keys", "(", "conn", ",", "table", ")", ":", "table_info_rows", "=", "[", "row", "for", "row", "in", "conn", ".", "execute", "(", "'PRAGMA table_info(\"{}\")'", ".", "format", "(", "table", ")", ")", ".", "fetchall", "(", ")", "if", ...
Figure out primary keys for a table.
[ "Figure", "out", "primary", "keys", "for", "a", "table", "." ]
11b352b4d52fd02a422776edebb14f12e4994d3b
https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/utils.py#L478-L488
238,343
simonw/datasette
datasette/utils.py
detect_fts
def detect_fts(conn, table): "Detect if table has a corresponding FTS virtual table and return it" rows = conn.execute(detect_fts_sql(table)).fetchall() if len(rows) == 0: return None else: return rows[0][0]
python
def detect_fts(conn, table): "Detect if table has a corresponding FTS virtual table and return it" rows = conn.execute(detect_fts_sql(table)).fetchall() if len(rows) == 0: return None else: return rows[0][0]
[ "def", "detect_fts", "(", "conn", ",", "table", ")", ":", "rows", "=", "conn", ".", "execute", "(", "detect_fts_sql", "(", "table", ")", ")", ".", "fetchall", "(", ")", "if", "len", "(", "rows", ")", "==", "0", ":", "return", "None", "else", ":", ...
Detect if table has a corresponding FTS virtual table and return it
[ "Detect", "if", "table", "has", "a", "corresponding", "FTS", "virtual", "table", "and", "return", "it" ]
11b352b4d52fd02a422776edebb14f12e4994d3b
https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/utils.py#L545-L551
238,344
simonw/datasette
datasette/app.py
Datasette.metadata
def metadata(self, key=None, database=None, table=None, fallback=True): """ Looks up metadata, cascading backwards from specified level. Returns None if metadata value is not found. """ assert not (database is None and table is not None), \ "Cannot call metadata() with table= specified but not database=" databases = self._metadata.get("databases") or {} search_list = [] if database is not None: search_list.append(databases.get(database) or {}) if table is not None: table_metadata = ( (databases.get(database) or {}).get("tables") or {} ).get(table) or {} search_list.insert(0, table_metadata) search_list.append(self._metadata) if not fallback: # No fallback allowed, so just use the first one in the list search_list = search_list[:1] if key is not None: for item in search_list: if key in item: return item[key] return None else: # Return the merged list m = {} for item in search_list: m.update(item) return m
python
def metadata(self, key=None, database=None, table=None, fallback=True): assert not (database is None and table is not None), \ "Cannot call metadata() with table= specified but not database=" databases = self._metadata.get("databases") or {} search_list = [] if database is not None: search_list.append(databases.get(database) or {}) if table is not None: table_metadata = ( (databases.get(database) or {}).get("tables") or {} ).get(table) or {} search_list.insert(0, table_metadata) search_list.append(self._metadata) if not fallback: # No fallback allowed, so just use the first one in the list search_list = search_list[:1] if key is not None: for item in search_list: if key in item: return item[key] return None else: # Return the merged list m = {} for item in search_list: m.update(item) return m
[ "def", "metadata", "(", "self", ",", "key", "=", "None", ",", "database", "=", "None", ",", "table", "=", "None", ",", "fallback", "=", "True", ")", ":", "assert", "not", "(", "database", "is", "None", "and", "table", "is", "not", "None", ")", ",",...
Looks up metadata, cascading backwards from specified level. Returns None if metadata value is not found.
[ "Looks", "up", "metadata", "cascading", "backwards", "from", "specified", "level", ".", "Returns", "None", "if", "metadata", "value", "is", "not", "found", "." ]
11b352b4d52fd02a422776edebb14f12e4994d3b
https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/app.py#L239-L269
238,345
simonw/datasette
datasette/app.py
Datasette.inspect
def inspect(self): " Inspect the database and return a dictionary of table metadata " if self._inspect: return self._inspect self._inspect = {} for filename in self.files: if filename is MEMORY: self._inspect[":memory:"] = { "hash": "000", "file": ":memory:", "size": 0, "views": {}, "tables": {}, } else: path = Path(filename) name = path.stem if name in self._inspect: raise Exception("Multiple files with same stem %s" % name) try: with sqlite3.connect( "file:{}?mode=ro".format(path), uri=True ) as conn: self.prepare_connection(conn) self._inspect[name] = { "hash": inspect_hash(path), "file": str(path), "size": path.stat().st_size, "views": inspect_views(conn), "tables": inspect_tables(conn, (self.metadata("databases") or {}).get(name, {})) } except sqlite3.OperationalError as e: if (e.args[0] == 'no such module: VirtualSpatialIndex'): raise click.UsageError( "It looks like you're trying to load a SpatiaLite" " database without first loading the SpatiaLite module." "\n\nRead more: https://datasette.readthedocs.io/en/latest/spatialite.html" ) else: raise return self._inspect
python
def inspect(self): " Inspect the database and return a dictionary of table metadata " if self._inspect: return self._inspect self._inspect = {} for filename in self.files: if filename is MEMORY: self._inspect[":memory:"] = { "hash": "000", "file": ":memory:", "size": 0, "views": {}, "tables": {}, } else: path = Path(filename) name = path.stem if name in self._inspect: raise Exception("Multiple files with same stem %s" % name) try: with sqlite3.connect( "file:{}?mode=ro".format(path), uri=True ) as conn: self.prepare_connection(conn) self._inspect[name] = { "hash": inspect_hash(path), "file": str(path), "size": path.stat().st_size, "views": inspect_views(conn), "tables": inspect_tables(conn, (self.metadata("databases") or {}).get(name, {})) } except sqlite3.OperationalError as e: if (e.args[0] == 'no such module: VirtualSpatialIndex'): raise click.UsageError( "It looks like you're trying to load a SpatiaLite" " database without first loading the SpatiaLite module." "\n\nRead more: https://datasette.readthedocs.io/en/latest/spatialite.html" ) else: raise return self._inspect
[ "def", "inspect", "(", "self", ")", ":", "if", "self", ".", "_inspect", ":", "return", "self", ".", "_inspect", "self", ".", "_inspect", "=", "{", "}", "for", "filename", "in", "self", ".", "files", ":", "if", "filename", "is", "MEMORY", ":", "self",...
Inspect the database and return a dictionary of table metadata
[ "Inspect", "the", "database", "and", "return", "a", "dictionary", "of", "table", "metadata" ]
11b352b4d52fd02a422776edebb14f12e4994d3b
https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/app.py#L414-L455
238,346
simonw/datasette
datasette/app.py
Datasette.table_metadata
def table_metadata(self, database, table): "Fetch table-specific metadata." return (self.metadata("databases") or {}).get(database, {}).get( "tables", {} ).get( table, {} )
python
def table_metadata(self, database, table): "Fetch table-specific metadata." return (self.metadata("databases") or {}).get(database, {}).get( "tables", {} ).get( table, {} )
[ "def", "table_metadata", "(", "self", ",", "database", ",", "table", ")", ":", "return", "(", "self", ".", "metadata", "(", "\"databases\"", ")", "or", "{", "}", ")", ".", "get", "(", "database", ",", "{", "}", ")", ".", "get", "(", "\"tables\"", "...
Fetch table-specific metadata.
[ "Fetch", "table", "-", "specific", "metadata", "." ]
11b352b4d52fd02a422776edebb14f12e4994d3b
https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/app.py#L521-L527
238,347
simonw/datasette
datasette/app.py
Datasette.execute
async def execute( self, db_name, sql, params=None, truncate=False, custom_time_limit=None, page_size=None, ): """Executes sql against db_name in a thread""" page_size = page_size or self.page_size def sql_operation_in_thread(conn): time_limit_ms = self.sql_time_limit_ms if custom_time_limit and custom_time_limit < time_limit_ms: time_limit_ms = custom_time_limit with sqlite_timelimit(conn, time_limit_ms): try: cursor = conn.cursor() cursor.execute(sql, params or {}) max_returned_rows = self.max_returned_rows if max_returned_rows == page_size: max_returned_rows += 1 if max_returned_rows and truncate: rows = cursor.fetchmany(max_returned_rows + 1) truncated = len(rows) > max_returned_rows rows = rows[:max_returned_rows] else: rows = cursor.fetchall() truncated = False except sqlite3.OperationalError as e: if e.args == ('interrupted',): raise InterruptedError(e) print( "ERROR: conn={}, sql = {}, params = {}: {}".format( conn, repr(sql), params, e ) ) raise if truncate: return Results(rows, truncated, cursor.description) else: return Results(rows, False, cursor.description) with trace("sql", (db_name, sql.strip(), params)): results = await self.execute_against_connection_in_thread( db_name, sql_operation_in_thread ) return results
python
async def execute( self, db_name, sql, params=None, truncate=False, custom_time_limit=None, page_size=None, ): page_size = page_size or self.page_size def sql_operation_in_thread(conn): time_limit_ms = self.sql_time_limit_ms if custom_time_limit and custom_time_limit < time_limit_ms: time_limit_ms = custom_time_limit with sqlite_timelimit(conn, time_limit_ms): try: cursor = conn.cursor() cursor.execute(sql, params or {}) max_returned_rows = self.max_returned_rows if max_returned_rows == page_size: max_returned_rows += 1 if max_returned_rows and truncate: rows = cursor.fetchmany(max_returned_rows + 1) truncated = len(rows) > max_returned_rows rows = rows[:max_returned_rows] else: rows = cursor.fetchall() truncated = False except sqlite3.OperationalError as e: if e.args == ('interrupted',): raise InterruptedError(e) print( "ERROR: conn={}, sql = {}, params = {}: {}".format( conn, repr(sql), params, e ) ) raise if truncate: return Results(rows, truncated, cursor.description) else: return Results(rows, False, cursor.description) with trace("sql", (db_name, sql.strip(), params)): results = await self.execute_against_connection_in_thread( db_name, sql_operation_in_thread ) return results
[ "async", "def", "execute", "(", "self", ",", "db_name", ",", "sql", ",", "params", "=", "None", ",", "truncate", "=", "False", ",", "custom_time_limit", "=", "None", ",", "page_size", "=", "None", ",", ")", ":", "page_size", "=", "page_size", "or", "se...
Executes sql against db_name in a thread
[ "Executes", "sql", "against", "db_name", "in", "a", "thread" ]
11b352b4d52fd02a422776edebb14f12e4994d3b
https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/app.py#L580-L631
238,348
simonw/datasette
datasette/inspect.py
inspect_hash
def inspect_hash(path): " Calculate the hash of a database, efficiently. " m = hashlib.sha256() with path.open("rb") as fp: while True: data = fp.read(HASH_BLOCK_SIZE) if not data: break m.update(data) return m.hexdigest()
python
def inspect_hash(path): " Calculate the hash of a database, efficiently. " m = hashlib.sha256() with path.open("rb") as fp: while True: data = fp.read(HASH_BLOCK_SIZE) if not data: break m.update(data) return m.hexdigest()
[ "def", "inspect_hash", "(", "path", ")", ":", "m", "=", "hashlib", ".", "sha256", "(", ")", "with", "path", ".", "open", "(", "\"rb\"", ")", "as", "fp", ":", "while", "True", ":", "data", "=", "fp", ".", "read", "(", "HASH_BLOCK_SIZE", ")", "if", ...
Calculate the hash of a database, efficiently.
[ "Calculate", "the", "hash", "of", "a", "database", "efficiently", "." ]
11b352b4d52fd02a422776edebb14f12e4994d3b
https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/inspect.py#L17-L27
238,349
simonw/datasette
datasette/inspect.py
inspect_tables
def inspect_tables(conn, database_metadata): " List tables and their row counts, excluding uninteresting tables. " tables = {} table_names = [ r["name"] for r in conn.execute( 'select * from sqlite_master where type="table"' ) ] for table in table_names: table_metadata = database_metadata.get("tables", {}).get( table, {} ) try: count = conn.execute( "select count(*) from {}".format(escape_sqlite(table)) ).fetchone()[0] except sqlite3.OperationalError: # This can happen when running against a FTS virtual table # e.g. "select count(*) from some_fts;" count = 0 column_names = table_columns(conn, table) tables[table] = { "name": table, "columns": column_names, "primary_keys": detect_primary_keys(conn, table), "count": count, "hidden": table_metadata.get("hidden") or False, "fts_table": detect_fts(conn, table), } foreign_keys = get_all_foreign_keys(conn) for table, info in foreign_keys.items(): tables[table]["foreign_keys"] = info # Mark tables 'hidden' if they relate to FTS virtual tables hidden_tables = [ r["name"] for r in conn.execute( """ select name from sqlite_master where rootpage = 0 and sql like '%VIRTUAL TABLE%USING FTS%' """ ) ] if detect_spatialite(conn): # Also hide Spatialite internal tables hidden_tables += [ "ElementaryGeometries", "SpatialIndex", "geometry_columns", "spatial_ref_sys", "spatialite_history", "sql_statements_log", "sqlite_sequence", "views_geometry_columns", "virts_geometry_columns", ] + [ r["name"] for r in conn.execute( """ select name from sqlite_master where name like "idx_%" and type = "table" """ ) ] for t in tables.keys(): for hidden_table in hidden_tables: if t == hidden_table or t.startswith(hidden_table): tables[t]["hidden"] = True continue return tables
python
def inspect_tables(conn, database_metadata): " List tables and their row counts, excluding uninteresting tables. " tables = {} table_names = [ r["name"] for r in conn.execute( 'select * from sqlite_master where type="table"' ) ] for table in table_names: table_metadata = database_metadata.get("tables", {}).get( table, {} ) try: count = conn.execute( "select count(*) from {}".format(escape_sqlite(table)) ).fetchone()[0] except sqlite3.OperationalError: # This can happen when running against a FTS virtual table # e.g. "select count(*) from some_fts;" count = 0 column_names = table_columns(conn, table) tables[table] = { "name": table, "columns": column_names, "primary_keys": detect_primary_keys(conn, table), "count": count, "hidden": table_metadata.get("hidden") or False, "fts_table": detect_fts(conn, table), } foreign_keys = get_all_foreign_keys(conn) for table, info in foreign_keys.items(): tables[table]["foreign_keys"] = info # Mark tables 'hidden' if they relate to FTS virtual tables hidden_tables = [ r["name"] for r in conn.execute( """ select name from sqlite_master where rootpage = 0 and sql like '%VIRTUAL TABLE%USING FTS%' """ ) ] if detect_spatialite(conn): # Also hide Spatialite internal tables hidden_tables += [ "ElementaryGeometries", "SpatialIndex", "geometry_columns", "spatial_ref_sys", "spatialite_history", "sql_statements_log", "sqlite_sequence", "views_geometry_columns", "virts_geometry_columns", ] + [ r["name"] for r in conn.execute( """ select name from sqlite_master where name like "idx_%" and type = "table" """ ) ] for t in tables.keys(): for hidden_table in hidden_tables: if t == hidden_table or t.startswith(hidden_table): tables[t]["hidden"] = True continue return tables
[ "def", "inspect_tables", "(", "conn", ",", "database_metadata", ")", ":", "tables", "=", "{", "}", "table_names", "=", "[", "r", "[", "\"name\"", "]", "for", "r", "in", "conn", ".", "execute", "(", "'select * from sqlite_master where type=\"table\"'", ")", "]"...
List tables and their row counts, excluding uninteresting tables.
[ "List", "tables", "and", "their", "row", "counts", "excluding", "uninteresting", "tables", "." ]
11b352b4d52fd02a422776edebb14f12e4994d3b
https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/inspect.py#L35-L115
238,350
simonw/datasette
datasette/filters.py
Filters.convert_unit
def convert_unit(self, column, value): "If the user has provided a unit in the query, convert it into the column unit, if present." if column not in self.units: return value # Try to interpret the value as a unit value = self.ureg(value) if isinstance(value, numbers.Number): # It's just a bare number, assume it's the column unit return value column_unit = self.ureg(self.units[column]) return value.to(column_unit).magnitude
python
def convert_unit(self, column, value): "If the user has provided a unit in the query, convert it into the column unit, if present." if column not in self.units: return value # Try to interpret the value as a unit value = self.ureg(value) if isinstance(value, numbers.Number): # It's just a bare number, assume it's the column unit return value column_unit = self.ureg(self.units[column]) return value.to(column_unit).magnitude
[ "def", "convert_unit", "(", "self", ",", "column", ",", "value", ")", ":", "if", "column", "not", "in", "self", ".", "units", ":", "return", "value", "# Try to interpret the value as a unit", "value", "=", "self", ".", "ureg", "(", "value", ")", "if", "isi...
If the user has provided a unit in the query, convert it into the column unit, if present.
[ "If", "the", "user", "has", "provided", "a", "unit", "in", "the", "query", "convert", "it", "into", "the", "column", "unit", "if", "present", "." ]
11b352b4d52fd02a422776edebb14f12e4994d3b
https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/filters.py#L156-L168
238,351
simonw/datasette
datasette/cli.py
skeleton
def skeleton(files, metadata, sqlite_extensions): "Generate a skeleton metadata.json file for specified SQLite databases" if os.path.exists(metadata): click.secho( "File {} already exists, will not over-write".format(metadata), bg="red", fg="white", bold=True, err=True, ) sys.exit(1) app = Datasette(files, sqlite_extensions=sqlite_extensions) databases = {} for database_name, info in app.inspect().items(): databases[database_name] = { "title": None, "description": None, "description_html": None, "license": None, "license_url": None, "source": None, "source_url": None, "queries": {}, "tables": { table_name: { "title": None, "description": None, "description_html": None, "license": None, "license_url": None, "source": None, "source_url": None, "units": {}, } for table_name in (info.get("tables") or {}) }, } open(metadata, "w").write( json.dumps( { "title": None, "description": None, "description_html": None, "license": None, "license_url": None, "source": None, "source_url": None, "databases": databases, }, indent=4, ) ) click.echo("Wrote skeleton to {}".format(metadata))
python
def skeleton(files, metadata, sqlite_extensions): "Generate a skeleton metadata.json file for specified SQLite databases" if os.path.exists(metadata): click.secho( "File {} already exists, will not over-write".format(metadata), bg="red", fg="white", bold=True, err=True, ) sys.exit(1) app = Datasette(files, sqlite_extensions=sqlite_extensions) databases = {} for database_name, info in app.inspect().items(): databases[database_name] = { "title": None, "description": None, "description_html": None, "license": None, "license_url": None, "source": None, "source_url": None, "queries": {}, "tables": { table_name: { "title": None, "description": None, "description_html": None, "license": None, "license_url": None, "source": None, "source_url": None, "units": {}, } for table_name in (info.get("tables") or {}) }, } open(metadata, "w").write( json.dumps( { "title": None, "description": None, "description_html": None, "license": None, "license_url": None, "source": None, "source_url": None, "databases": databases, }, indent=4, ) ) click.echo("Wrote skeleton to {}".format(metadata))
[ "def", "skeleton", "(", "files", ",", "metadata", ",", "sqlite_extensions", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "metadata", ")", ":", "click", ".", "secho", "(", "\"File {} already exists, will not over-write\"", ".", "format", "(", "metadat...
Generate a skeleton metadata.json file for specified SQLite databases
[ "Generate", "a", "skeleton", "metadata", ".", "json", "file", "for", "specified", "SQLite", "databases" ]
11b352b4d52fd02a422776edebb14f12e4994d3b
https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/cli.py#L107-L159
238,352
simonw/datasette
datasette/cli.py
plugins
def plugins(all, plugins_dir): "List currently available plugins" app = Datasette([], plugins_dir=plugins_dir) click.echo(json.dumps(app.plugins(all), indent=4))
python
def plugins(all, plugins_dir): "List currently available plugins" app = Datasette([], plugins_dir=plugins_dir) click.echo(json.dumps(app.plugins(all), indent=4))
[ "def", "plugins", "(", "all", ",", "plugins_dir", ")", ":", "app", "=", "Datasette", "(", "[", "]", ",", "plugins_dir", "=", "plugins_dir", ")", "click", ".", "echo", "(", "json", ".", "dumps", "(", "app", ".", "plugins", "(", "all", ")", ",", "ind...
List currently available plugins
[ "List", "currently", "available", "plugins" ]
11b352b4d52fd02a422776edebb14f12e4994d3b
https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/cli.py#L169-L172
238,353
simonw/datasette
datasette/cli.py
package
def package( files, tag, metadata, extra_options, branch, template_dir, plugins_dir, static, install, spatialite, version_note, **extra_metadata ): "Package specified SQLite files into a new datasette Docker container" if not shutil.which("docker"): click.secho( ' The package command requires "docker" to be installed and configured ', bg="red", fg="white", bold=True, err=True, ) sys.exit(1) with temporary_docker_directory( files, "datasette", metadata, extra_options, branch, template_dir, plugins_dir, static, install, spatialite, version_note, extra_metadata, ): args = ["docker", "build"] if tag: args.append("-t") args.append(tag) args.append(".") call(args)
python
def package( files, tag, metadata, extra_options, branch, template_dir, plugins_dir, static, install, spatialite, version_note, **extra_metadata ): "Package specified SQLite files into a new datasette Docker container" if not shutil.which("docker"): click.secho( ' The package command requires "docker" to be installed and configured ', bg="red", fg="white", bold=True, err=True, ) sys.exit(1) with temporary_docker_directory( files, "datasette", metadata, extra_options, branch, template_dir, plugins_dir, static, install, spatialite, version_note, extra_metadata, ): args = ["docker", "build"] if tag: args.append("-t") args.append(tag) args.append(".") call(args)
[ "def", "package", "(", "files", ",", "tag", ",", "metadata", ",", "extra_options", ",", "branch", ",", "template_dir", ",", "plugins_dir", ",", "static", ",", "install", ",", "spatialite", ",", "version_note", ",", "*", "*", "extra_metadata", ")", ":", "if...
Package specified SQLite files into a new datasette Docker container
[ "Package", "specified", "SQLite", "files", "into", "a", "new", "datasette", "Docker", "container" ]
11b352b4d52fd02a422776edebb14f12e4994d3b
https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/cli.py#L222-L265
238,354
simonw/datasette
datasette/cli.py
serve
def serve( files, immutable, host, port, debug, reload, cors, sqlite_extensions, inspect_file, metadata, template_dir, plugins_dir, static, memory, config, version_note, help_config, ): """Serve up specified SQLite database files with a web UI""" if help_config: formatter = formatting.HelpFormatter() with formatter.section("Config options"): formatter.write_dl([ (option.name, '{} (default={})'.format( option.help, option.default )) for option in CONFIG_OPTIONS ]) click.echo(formatter.getvalue()) sys.exit(0) if reload: import hupper reloader = hupper.start_reloader("datasette.cli.serve") reloader.watch_files(files) if metadata: reloader.watch_files([metadata.name]) inspect_data = None if inspect_file: inspect_data = json.load(open(inspect_file)) metadata_data = None if metadata: metadata_data = json.loads(metadata.read()) click.echo("Serve! files={} (immutables={}) on port {}".format(files, immutable, port)) ds = Datasette( files, immutables=immutable, cache_headers=not debug and not reload, cors=cors, inspect_data=inspect_data, metadata=metadata_data, sqlite_extensions=sqlite_extensions, template_dir=template_dir, plugins_dir=plugins_dir, static_mounts=static, config=dict(config), memory=memory, version_note=version_note, ) # Force initial hashing/table counting ds.inspect() ds.app().run(host=host, port=port, debug=debug)
python
def serve( files, immutable, host, port, debug, reload, cors, sqlite_extensions, inspect_file, metadata, template_dir, plugins_dir, static, memory, config, version_note, help_config, ): if help_config: formatter = formatting.HelpFormatter() with formatter.section("Config options"): formatter.write_dl([ (option.name, '{} (default={})'.format( option.help, option.default )) for option in CONFIG_OPTIONS ]) click.echo(formatter.getvalue()) sys.exit(0) if reload: import hupper reloader = hupper.start_reloader("datasette.cli.serve") reloader.watch_files(files) if metadata: reloader.watch_files([metadata.name]) inspect_data = None if inspect_file: inspect_data = json.load(open(inspect_file)) metadata_data = None if metadata: metadata_data = json.loads(metadata.read()) click.echo("Serve! files={} (immutables={}) on port {}".format(files, immutable, port)) ds = Datasette( files, immutables=immutable, cache_headers=not debug and not reload, cors=cors, inspect_data=inspect_data, metadata=metadata_data, sqlite_extensions=sqlite_extensions, template_dir=template_dir, plugins_dir=plugins_dir, static_mounts=static, config=dict(config), memory=memory, version_note=version_note, ) # Force initial hashing/table counting ds.inspect() ds.app().run(host=host, port=port, debug=debug)
[ "def", "serve", "(", "files", ",", "immutable", ",", "host", ",", "port", ",", "debug", ",", "reload", ",", "cors", ",", "sqlite_extensions", ",", "inspect_file", ",", "metadata", ",", "template_dir", ",", "plugins_dir", ",", "static", ",", "memory", ",", ...
Serve up specified SQLite database files with a web UI
[ "Serve", "up", "specified", "SQLite", "database", "files", "with", "a", "web", "UI" ]
11b352b4d52fd02a422776edebb14f12e4994d3b
https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/cli.py#L340-L405
238,355
ResidentMario/missingno
missingno/missingno.py
bar
def bar(df, figsize=(24, 10), fontsize=16, labels=None, log=False, color='dimgray', inline=False, filter=None, n=0, p=0, sort=None): """ A bar chart visualization of the nullity of the given DataFrame. :param df: The input DataFrame. :param log: Whether or not to display a logorithmic plot. Defaults to False (linear). :param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default). :param n: The cap on the number of columns to include in the filtered DataFrame. :param p: The cap on the percentage fill of the columns in the filtered DataFrame. :param sort: The sort to apply to the heatmap. Should be one of "ascending", "descending", or None (default). :param figsize: The size of the figure to display. :param fontsize: The figure's font size. This default to 16. :param labels: Whether or not to display the column names. Would need to be turned off on particularly large displays. Defaults to True. :param color: The color of the filled columns. Default to the RGB multiple `(0.25, 0.25, 0.25)`. :return: If `inline` is False, the underlying `matplotlib.figure` object. Else, nothing. """ nullity_counts = len(df) - df.isnull().sum() df = nullity_filter(df, filter=filter, n=n, p=p) df = nullity_sort(df, sort=sort) plt.figure(figsize=figsize) (nullity_counts / len(df)).plot(kind='bar', figsize=figsize, fontsize=fontsize, log=log, color=color) ax1 = plt.gca() axes = [ax1] # Start appending elements, starting with a modified bottom x axis. if labels or (labels is None and len(df.columns) <= 50): ax1.set_xticklabels(ax1.get_xticklabels(), rotation=45, ha='right', fontsize=fontsize) # Create the numerical ticks. ax2 = ax1.twinx() axes.append(ax2) if not log: ax1.set_ylim([0, 1]) ax2.set_yticks(ax1.get_yticks()) ax2.set_yticklabels([int(n*len(df)) for n in ax1.get_yticks()], fontsize=fontsize) else: # For some reason when a logarithmic plot is specified `ax1` always contains two more ticks than actually # appears in the plot. The fix is to ignore the first and last entries. Also note that when a log scale # is used, we have to make it match the `ax1` layout ourselves. ax2.set_yscale('log') ax2.set_ylim(ax1.get_ylim()) ax2.set_yticklabels([int(n*len(df)) for n in ax1.get_yticks()], fontsize=fontsize) else: ax1.set_xticks([]) # Create the third axis, which displays columnar totals above the rest of the plot. ax3 = ax1.twiny() axes.append(ax3) ax3.set_xticks(ax1.get_xticks()) ax3.set_xlim(ax1.get_xlim()) ax3.set_xticklabels(nullity_counts.values, fontsize=fontsize, rotation=45, ha='left') ax3.grid(False) for ax in axes: ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['bottom'].set_visible(False) ax.spines['left'].set_visible(False) ax.xaxis.set_ticks_position('none') ax.yaxis.set_ticks_position('none') if inline: plt.show() else: return ax1
python
def bar(df, figsize=(24, 10), fontsize=16, labels=None, log=False, color='dimgray', inline=False, filter=None, n=0, p=0, sort=None): nullity_counts = len(df) - df.isnull().sum() df = nullity_filter(df, filter=filter, n=n, p=p) df = nullity_sort(df, sort=sort) plt.figure(figsize=figsize) (nullity_counts / len(df)).plot(kind='bar', figsize=figsize, fontsize=fontsize, log=log, color=color) ax1 = plt.gca() axes = [ax1] # Start appending elements, starting with a modified bottom x axis. if labels or (labels is None and len(df.columns) <= 50): ax1.set_xticklabels(ax1.get_xticklabels(), rotation=45, ha='right', fontsize=fontsize) # Create the numerical ticks. ax2 = ax1.twinx() axes.append(ax2) if not log: ax1.set_ylim([0, 1]) ax2.set_yticks(ax1.get_yticks()) ax2.set_yticklabels([int(n*len(df)) for n in ax1.get_yticks()], fontsize=fontsize) else: # For some reason when a logarithmic plot is specified `ax1` always contains two more ticks than actually # appears in the plot. The fix is to ignore the first and last entries. Also note that when a log scale # is used, we have to make it match the `ax1` layout ourselves. ax2.set_yscale('log') ax2.set_ylim(ax1.get_ylim()) ax2.set_yticklabels([int(n*len(df)) for n in ax1.get_yticks()], fontsize=fontsize) else: ax1.set_xticks([]) # Create the third axis, which displays columnar totals above the rest of the plot. ax3 = ax1.twiny() axes.append(ax3) ax3.set_xticks(ax1.get_xticks()) ax3.set_xlim(ax1.get_xlim()) ax3.set_xticklabels(nullity_counts.values, fontsize=fontsize, rotation=45, ha='left') ax3.grid(False) for ax in axes: ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['bottom'].set_visible(False) ax.spines['left'].set_visible(False) ax.xaxis.set_ticks_position('none') ax.yaxis.set_ticks_position('none') if inline: plt.show() else: return ax1
[ "def", "bar", "(", "df", ",", "figsize", "=", "(", "24", ",", "10", ")", ",", "fontsize", "=", "16", ",", "labels", "=", "None", ",", "log", "=", "False", ",", "color", "=", "'dimgray'", ",", "inline", "=", "False", ",", "filter", "=", "None", ...
A bar chart visualization of the nullity of the given DataFrame. :param df: The input DataFrame. :param log: Whether or not to display a logorithmic plot. Defaults to False (linear). :param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default). :param n: The cap on the number of columns to include in the filtered DataFrame. :param p: The cap on the percentage fill of the columns in the filtered DataFrame. :param sort: The sort to apply to the heatmap. Should be one of "ascending", "descending", or None (default). :param figsize: The size of the figure to display. :param fontsize: The figure's font size. This default to 16. :param labels: Whether or not to display the column names. Would need to be turned off on particularly large displays. Defaults to True. :param color: The color of the filled columns. Default to the RGB multiple `(0.25, 0.25, 0.25)`. :return: If `inline` is False, the underlying `matplotlib.figure` object. Else, nothing.
[ "A", "bar", "chart", "visualization", "of", "the", "nullity", "of", "the", "given", "DataFrame", "." ]
1d67f91fbab0695a919c6bb72c796db57024e0ca
https://github.com/ResidentMario/missingno/blob/1d67f91fbab0695a919c6bb72c796db57024e0ca/missingno/missingno.py#L195-L263
238,356
ResidentMario/missingno
missingno/missingno.py
heatmap
def heatmap(df, inline=False, filter=None, n=0, p=0, sort=None, figsize=(20, 12), fontsize=16, labels=True, cmap='RdBu', vmin=-1, vmax=1, cbar=True ): """ Presents a `seaborn` heatmap visualization of nullity correlation in the given DataFrame. Note that this visualization has no special support for large datasets. For those, try the dendrogram instead. :param df: The DataFrame whose completeness is being heatmapped. :param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default). See `nullity_filter()` for more information. :param n: The cap on the number of columns to include in the filtered DataFrame. See `nullity_filter()` for more information. :param p: The cap on the percentage fill of the columns in the filtered DataFrame. See `nullity_filter()` for more information. :param sort: The sort to apply to the heatmap. Should be one of "ascending", "descending", or None. See `nullity_sort()` for more information. :param figsize: The size of the figure to display. This is a `matplotlib` parameter which defaults to (20, 12). :param fontsize: The figure's font size. :param labels: Whether or not to label each matrix entry with its correlation (default is True). :param cmap: What `matplotlib` colormap to use. Defaults to `RdBu`. :param vmin: The normalized colormap threshold. Defaults to -1, e.g. the bottom of the color scale. :param vmax: The normalized colormap threshold. Defaults to 1, e.g. the bottom of the color scale. :param inline: Whether or not the figure is inline. If it's not then instead of getting plotted, this method will return its figure. :return: If `inline` is False, the underlying `matplotlib.figure` object. Else, nothing. """ # Apply filters and sorts, set up the figure. df = nullity_filter(df, filter=filter, n=n, p=p) df = nullity_sort(df, sort=sort) plt.figure(figsize=figsize) gs = gridspec.GridSpec(1, 1) ax0 = plt.subplot(gs[0]) # Remove completely filled or completely empty variables. df = df.iloc[:,[i for i, n in enumerate(np.var(df.isnull(), axis='rows')) if n > 0]] # Create and mask the correlation matrix. Construct the base heatmap. corr_mat = df.isnull().corr() mask = np.zeros_like(corr_mat) mask[np.triu_indices_from(mask)] = True if labels: sns.heatmap(corr_mat, mask=mask, cmap=cmap, ax=ax0, cbar=cbar, annot=True, annot_kws={'size': fontsize - 2}, vmin=vmin, vmax=vmax) else: sns.heatmap(corr_mat, mask=mask, cmap=cmap, ax=ax0, cbar=cbar, vmin=vmin, vmax=vmax) # Apply visual corrections and modifications. ax0.xaxis.tick_bottom() ax0.set_xticklabels(ax0.xaxis.get_majorticklabels(), rotation=45, ha='right', fontsize=fontsize) ax0.set_yticklabels(ax0.yaxis.get_majorticklabels(), fontsize=fontsize, rotation=0) ax0.set_yticklabels(ax0.yaxis.get_majorticklabels(), rotation=0, fontsize=fontsize) ax0.xaxis.set_ticks_position('none') ax0.yaxis.set_ticks_position('none') ax0.patch.set_visible(False) for text in ax0.texts: t = float(text.get_text()) if 0.95 <= t < 1: text.set_text('<1') elif -1 < t <= -0.95: text.set_text('>-1') elif t == 1: text.set_text('1') elif t == -1: text.set_text('-1') elif -0.05 < t < 0.05: text.set_text('') else: text.set_text(round(t, 1)) if inline: plt.show() else: return ax0
python
def heatmap(df, inline=False, filter=None, n=0, p=0, sort=None, figsize=(20, 12), fontsize=16, labels=True, cmap='RdBu', vmin=-1, vmax=1, cbar=True ): # Apply filters and sorts, set up the figure. df = nullity_filter(df, filter=filter, n=n, p=p) df = nullity_sort(df, sort=sort) plt.figure(figsize=figsize) gs = gridspec.GridSpec(1, 1) ax0 = plt.subplot(gs[0]) # Remove completely filled or completely empty variables. df = df.iloc[:,[i for i, n in enumerate(np.var(df.isnull(), axis='rows')) if n > 0]] # Create and mask the correlation matrix. Construct the base heatmap. corr_mat = df.isnull().corr() mask = np.zeros_like(corr_mat) mask[np.triu_indices_from(mask)] = True if labels: sns.heatmap(corr_mat, mask=mask, cmap=cmap, ax=ax0, cbar=cbar, annot=True, annot_kws={'size': fontsize - 2}, vmin=vmin, vmax=vmax) else: sns.heatmap(corr_mat, mask=mask, cmap=cmap, ax=ax0, cbar=cbar, vmin=vmin, vmax=vmax) # Apply visual corrections and modifications. ax0.xaxis.tick_bottom() ax0.set_xticklabels(ax0.xaxis.get_majorticklabels(), rotation=45, ha='right', fontsize=fontsize) ax0.set_yticklabels(ax0.yaxis.get_majorticklabels(), fontsize=fontsize, rotation=0) ax0.set_yticklabels(ax0.yaxis.get_majorticklabels(), rotation=0, fontsize=fontsize) ax0.xaxis.set_ticks_position('none') ax0.yaxis.set_ticks_position('none') ax0.patch.set_visible(False) for text in ax0.texts: t = float(text.get_text()) if 0.95 <= t < 1: text.set_text('<1') elif -1 < t <= -0.95: text.set_text('>-1') elif t == 1: text.set_text('1') elif t == -1: text.set_text('-1') elif -0.05 < t < 0.05: text.set_text('') else: text.set_text(round(t, 1)) if inline: plt.show() else: return ax0
[ "def", "heatmap", "(", "df", ",", "inline", "=", "False", ",", "filter", "=", "None", ",", "n", "=", "0", ",", "p", "=", "0", ",", "sort", "=", "None", ",", "figsize", "=", "(", "20", ",", "12", ")", ",", "fontsize", "=", "16", ",", "labels",...
Presents a `seaborn` heatmap visualization of nullity correlation in the given DataFrame. Note that this visualization has no special support for large datasets. For those, try the dendrogram instead. :param df: The DataFrame whose completeness is being heatmapped. :param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default). See `nullity_filter()` for more information. :param n: The cap on the number of columns to include in the filtered DataFrame. See `nullity_filter()` for more information. :param p: The cap on the percentage fill of the columns in the filtered DataFrame. See `nullity_filter()` for more information. :param sort: The sort to apply to the heatmap. Should be one of "ascending", "descending", or None. See `nullity_sort()` for more information. :param figsize: The size of the figure to display. This is a `matplotlib` parameter which defaults to (20, 12). :param fontsize: The figure's font size. :param labels: Whether or not to label each matrix entry with its correlation (default is True). :param cmap: What `matplotlib` colormap to use. Defaults to `RdBu`. :param vmin: The normalized colormap threshold. Defaults to -1, e.g. the bottom of the color scale. :param vmax: The normalized colormap threshold. Defaults to 1, e.g. the bottom of the color scale. :param inline: Whether or not the figure is inline. If it's not then instead of getting plotted, this method will return its figure. :return: If `inline` is False, the underlying `matplotlib.figure` object. Else, nothing.
[ "Presents", "a", "seaborn", "heatmap", "visualization", "of", "nullity", "correlation", "in", "the", "given", "DataFrame", ".", "Note", "that", "this", "visualization", "has", "no", "special", "support", "for", "large", "datasets", ".", "For", "those", "try", ...
1d67f91fbab0695a919c6bb72c796db57024e0ca
https://github.com/ResidentMario/missingno/blob/1d67f91fbab0695a919c6bb72c796db57024e0ca/missingno/missingno.py#L266-L346
238,357
ResidentMario/missingno
missingno/missingno.py
dendrogram
def dendrogram(df, method='average', filter=None, n=0, p=0, sort=None, orientation=None, figsize=None, fontsize=16, inline=False ): """ Fits a `scipy` hierarchical clustering algorithm to the given DataFrame's variables and visualizes the results as a `scipy` dendrogram. The default vertical display will fit up to 50 columns. If more than 50 columns are specified and orientation is left unspecified the dendrogram will automatically swap to a horizontal display to fit the additional variables. :param df: The DataFrame whose completeness is being dendrogrammed. :param method: The distance measure being used for clustering. This is a parameter that is passed to `scipy.hierarchy`. :param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default). :param n: The cap on the number of columns to include in the filtered DataFrame. :param p: The cap on the percentage fill of the columns in the filtered DataFrame. :param sort: The sort to apply to the heatmap. Should be one of "ascending", "descending", or None. :param figsize: The size of the figure to display. This is a `matplotlib` parameter which defaults to `(25, 10)`. :param fontsize: The figure's font size. :param orientation: The way the dendrogram is oriented. Defaults to top-down if there are less than or equal to 50 columns and left-right if there are more. :param inline: Whether or not the figure is inline. If it's not then instead of getting plotted, this method will return its figure. :return: If `inline` is False, the underlying `matplotlib.figure` object. Else, nothing. """ if not figsize: if len(df.columns) <= 50 or orientation == 'top' or orientation == 'bottom': figsize = (25, 10) else: figsize = (25, (25 + len(df.columns) - 50)*0.5) plt.figure(figsize=figsize) gs = gridspec.GridSpec(1, 1) ax0 = plt.subplot(gs[0]) df = nullity_filter(df, filter=filter, n=n, p=p) df = nullity_sort(df, sort=sort) # Link the hierarchical output matrix, figure out orientation, construct base dendrogram. x = np.transpose(df.isnull().astype(int).values) z = hierarchy.linkage(x, method) if not orientation: if len(df.columns) > 50: orientation = 'left' else: orientation = 'bottom' hierarchy.dendrogram(z, orientation=orientation, labels=df.columns.tolist(), distance_sort='descending', link_color_func=lambda c: 'black', leaf_font_size=fontsize, ax=ax0 ) # Remove extraneous default visual elements. ax0.set_aspect('auto') ax0.grid(b=False) if orientation == 'bottom': ax0.xaxis.tick_top() ax0.xaxis.set_ticks_position('none') ax0.yaxis.set_ticks_position('none') ax0.spines['top'].set_visible(False) ax0.spines['right'].set_visible(False) ax0.spines['bottom'].set_visible(False) ax0.spines['left'].set_visible(False) ax0.patch.set_visible(False) # Set up the categorical axis labels and draw. if orientation == 'bottom': ax0.set_xticklabels(ax0.xaxis.get_majorticklabels(), rotation=45, ha='left') elif orientation == 'top': ax0.set_xticklabels(ax0.xaxis.get_majorticklabels(), rotation=45, ha='right') if orientation == 'bottom' or orientation == 'top': ax0.tick_params(axis='y', labelsize=int(fontsize / 16 * 20)) else: ax0.tick_params(axis='x', labelsize=int(fontsize / 16 * 20)) if inline: plt.show() else: return ax0
python
def dendrogram(df, method='average', filter=None, n=0, p=0, sort=None, orientation=None, figsize=None, fontsize=16, inline=False ): if not figsize: if len(df.columns) <= 50 or orientation == 'top' or orientation == 'bottom': figsize = (25, 10) else: figsize = (25, (25 + len(df.columns) - 50)*0.5) plt.figure(figsize=figsize) gs = gridspec.GridSpec(1, 1) ax0 = plt.subplot(gs[0]) df = nullity_filter(df, filter=filter, n=n, p=p) df = nullity_sort(df, sort=sort) # Link the hierarchical output matrix, figure out orientation, construct base dendrogram. x = np.transpose(df.isnull().astype(int).values) z = hierarchy.linkage(x, method) if not orientation: if len(df.columns) > 50: orientation = 'left' else: orientation = 'bottom' hierarchy.dendrogram(z, orientation=orientation, labels=df.columns.tolist(), distance_sort='descending', link_color_func=lambda c: 'black', leaf_font_size=fontsize, ax=ax0 ) # Remove extraneous default visual elements. ax0.set_aspect('auto') ax0.grid(b=False) if orientation == 'bottom': ax0.xaxis.tick_top() ax0.xaxis.set_ticks_position('none') ax0.yaxis.set_ticks_position('none') ax0.spines['top'].set_visible(False) ax0.spines['right'].set_visible(False) ax0.spines['bottom'].set_visible(False) ax0.spines['left'].set_visible(False) ax0.patch.set_visible(False) # Set up the categorical axis labels and draw. if orientation == 'bottom': ax0.set_xticklabels(ax0.xaxis.get_majorticklabels(), rotation=45, ha='left') elif orientation == 'top': ax0.set_xticklabels(ax0.xaxis.get_majorticklabels(), rotation=45, ha='right') if orientation == 'bottom' or orientation == 'top': ax0.tick_params(axis='y', labelsize=int(fontsize / 16 * 20)) else: ax0.tick_params(axis='x', labelsize=int(fontsize / 16 * 20)) if inline: plt.show() else: return ax0
[ "def", "dendrogram", "(", "df", ",", "method", "=", "'average'", ",", "filter", "=", "None", ",", "n", "=", "0", ",", "p", "=", "0", ",", "sort", "=", "None", ",", "orientation", "=", "None", ",", "figsize", "=", "None", ",", "fontsize", "=", "16...
Fits a `scipy` hierarchical clustering algorithm to the given DataFrame's variables and visualizes the results as a `scipy` dendrogram. The default vertical display will fit up to 50 columns. If more than 50 columns are specified and orientation is left unspecified the dendrogram will automatically swap to a horizontal display to fit the additional variables. :param df: The DataFrame whose completeness is being dendrogrammed. :param method: The distance measure being used for clustering. This is a parameter that is passed to `scipy.hierarchy`. :param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default). :param n: The cap on the number of columns to include in the filtered DataFrame. :param p: The cap on the percentage fill of the columns in the filtered DataFrame. :param sort: The sort to apply to the heatmap. Should be one of "ascending", "descending", or None. :param figsize: The size of the figure to display. This is a `matplotlib` parameter which defaults to `(25, 10)`. :param fontsize: The figure's font size. :param orientation: The way the dendrogram is oriented. Defaults to top-down if there are less than or equal to 50 columns and left-right if there are more. :param inline: Whether or not the figure is inline. If it's not then instead of getting plotted, this method will return its figure. :return: If `inline` is False, the underlying `matplotlib.figure` object. Else, nothing.
[ "Fits", "a", "scipy", "hierarchical", "clustering", "algorithm", "to", "the", "given", "DataFrame", "s", "variables", "and", "visualizes", "the", "results", "as", "a", "scipy", "dendrogram", ".", "The", "default", "vertical", "display", "will", "fit", "up", "t...
1d67f91fbab0695a919c6bb72c796db57024e0ca
https://github.com/ResidentMario/missingno/blob/1d67f91fbab0695a919c6bb72c796db57024e0ca/missingno/missingno.py#L349-L434
238,358
ResidentMario/missingno
missingno/utils.py
nullity_sort
def nullity_sort(df, sort=None): """ Sorts a DataFrame according to its nullity, in either ascending or descending order. :param df: The DataFrame object being sorted. :param sort: The sorting method: either "ascending", "descending", or None (default). :return: The nullity-sorted DataFrame. """ if sort == 'ascending': return df.iloc[np.argsort(df.count(axis='columns').values), :] elif sort == 'descending': return df.iloc[np.flipud(np.argsort(df.count(axis='columns').values)), :] else: return df
python
def nullity_sort(df, sort=None): if sort == 'ascending': return df.iloc[np.argsort(df.count(axis='columns').values), :] elif sort == 'descending': return df.iloc[np.flipud(np.argsort(df.count(axis='columns').values)), :] else: return df
[ "def", "nullity_sort", "(", "df", ",", "sort", "=", "None", ")", ":", "if", "sort", "==", "'ascending'", ":", "return", "df", ".", "iloc", "[", "np", ".", "argsort", "(", "df", ".", "count", "(", "axis", "=", "'columns'", ")", ".", "values", ")", ...
Sorts a DataFrame according to its nullity, in either ascending or descending order. :param df: The DataFrame object being sorted. :param sort: The sorting method: either "ascending", "descending", or None (default). :return: The nullity-sorted DataFrame.
[ "Sorts", "a", "DataFrame", "according", "to", "its", "nullity", "in", "either", "ascending", "or", "descending", "order", "." ]
1d67f91fbab0695a919c6bb72c796db57024e0ca
https://github.com/ResidentMario/missingno/blob/1d67f91fbab0695a919c6bb72c796db57024e0ca/missingno/utils.py#L5-L18
238,359
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/session_entity_types_client.py
SessionEntityTypesClient.from_service_account_file
def from_service_account_file(cls, filename, *args, **kwargs): """Creates an instance of this client using the provided credentials file. Args: filename (str): The path to the service account private key json file. args: Additional arguments to pass to the constructor. kwargs: Additional arguments to pass to the constructor. Returns: dialogflow_v2.SessionEntityTypesClient: The constructed client. """ credentials = service_account.Credentials.from_service_account_file( filename) kwargs['credentials'] = credentials return cls(*args, **kwargs)
python
def from_service_account_file(cls, filename, *args, **kwargs): credentials = service_account.Credentials.from_service_account_file( filename) kwargs['credentials'] = credentials return cls(*args, **kwargs)
[ "def", "from_service_account_file", "(", "cls", ",", "filename", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "credentials", "=", "service_account", ".", "Credentials", ".", "from_service_account_file", "(", "filename", ")", "kwargs", "[", "'credentials'...
Creates an instance of this client using the provided credentials file. Args: filename (str): The path to the service account private key json file. args: Additional arguments to pass to the constructor. kwargs: Additional arguments to pass to the constructor. Returns: dialogflow_v2.SessionEntityTypesClient: The constructed client.
[ "Creates", "an", "instance", "of", "this", "client", "using", "the", "provided", "credentials", "file", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/session_entity_types_client.py#L75-L91
238,360
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/session_entity_types_client.py
SessionEntityTypesClient.session_entity_type_path
def session_entity_type_path(cls, project, session, entity_type): """Return a fully-qualified session_entity_type string.""" return google.api_core.path_template.expand( 'projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}', project=project, session=session, entity_type=entity_type, )
python
def session_entity_type_path(cls, project, session, entity_type): return google.api_core.path_template.expand( 'projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}', project=project, session=session, entity_type=entity_type, )
[ "def", "session_entity_type_path", "(", "cls", ",", "project", ",", "session", ",", "entity_type", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "'projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}'", ",", "p...
Return a fully-qualified session_entity_type string.
[ "Return", "a", "fully", "-", "qualified", "session_entity_type", "string", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/session_entity_types_client.py#L105-L112
238,361
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/session_entity_types_client.py
SessionEntityTypesClient.create_session_entity_type
def create_session_entity_type( self, parent, session_entity_type, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Creates a session entity type. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.SessionEntityTypesClient() >>> >>> parent = client.session_path('[PROJECT]', '[SESSION]') >>> >>> # TODO: Initialize ``session_entity_type``: >>> session_entity_type = {} >>> >>> response = client.create_session_entity_type(parent, session_entity_type) Args: parent (str): Required. The session to create a session entity type for. Format: ``projects/<Project ID>/agent/sessions/<Session ID>``. session_entity_type (Union[dict, ~google.cloud.dialogflow_v2.types.SessionEntityType]): Required. The session entity type to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.SessionEntityType` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.SessionEntityType` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'create_session_entity_type' not in self._inner_api_calls: self._inner_api_calls[ 'create_session_entity_type'] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_session_entity_type, default_retry=self._method_configs[ 'CreateSessionEntityType'].retry, default_timeout=self._method_configs[ 'CreateSessionEntityType'].timeout, client_info=self._client_info, ) request = session_entity_type_pb2.CreateSessionEntityTypeRequest( parent=parent, session_entity_type=session_entity_type, ) return self._inner_api_calls['create_session_entity_type']( request, retry=retry, timeout=timeout, metadata=metadata)
python
def create_session_entity_type( self, parent, session_entity_type, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): # Wrap the transport method to add retry and timeout logic. if 'create_session_entity_type' not in self._inner_api_calls: self._inner_api_calls[ 'create_session_entity_type'] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_session_entity_type, default_retry=self._method_configs[ 'CreateSessionEntityType'].retry, default_timeout=self._method_configs[ 'CreateSessionEntityType'].timeout, client_info=self._client_info, ) request = session_entity_type_pb2.CreateSessionEntityTypeRequest( parent=parent, session_entity_type=session_entity_type, ) return self._inner_api_calls['create_session_entity_type']( request, retry=retry, timeout=timeout, metadata=metadata)
[ "def", "create_session_entity_type", "(", "self", ",", "parent", ",", "session_entity_type", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "...
Creates a session entity type. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.SessionEntityTypesClient() >>> >>> parent = client.session_path('[PROJECT]', '[SESSION]') >>> >>> # TODO: Initialize ``session_entity_type``: >>> session_entity_type = {} >>> >>> response = client.create_session_entity_type(parent, session_entity_type) Args: parent (str): Required. The session to create a session entity type for. Format: ``projects/<Project ID>/agent/sessions/<Session ID>``. session_entity_type (Union[dict, ~google.cloud.dialogflow_v2.types.SessionEntityType]): Required. The session entity type to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.SessionEntityType` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.SessionEntityType` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Creates", "a", "session", "entity", "type", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/session_entity_types_client.py#L351-L415
238,362
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/session_entity_types_client.py
SessionEntityTypesClient.update_session_entity_type
def update_session_entity_type( self, session_entity_type, update_mask=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Updates the specified session entity type. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.SessionEntityTypesClient() >>> >>> # TODO: Initialize ``session_entity_type``: >>> session_entity_type = {} >>> >>> response = client.update_session_entity_type(session_entity_type) Args: session_entity_type (Union[dict, ~google.cloud.dialogflow_v2.types.SessionEntityType]): Required. The entity type to update. Format: ``projects/<Project ID>/agent/sessions/<Session ID>/entityTypes/<Entity Type Display Name>``. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.SessionEntityType` update_mask (Union[dict, ~google.cloud.dialogflow_v2.types.FieldMask]): Optional. The mask to control which fields get updated. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.FieldMask` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.SessionEntityType` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'update_session_entity_type' not in self._inner_api_calls: self._inner_api_calls[ 'update_session_entity_type'] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_session_entity_type, default_retry=self._method_configs[ 'UpdateSessionEntityType'].retry, default_timeout=self._method_configs[ 'UpdateSessionEntityType'].timeout, client_info=self._client_info, ) request = session_entity_type_pb2.UpdateSessionEntityTypeRequest( session_entity_type=session_entity_type, update_mask=update_mask, ) return self._inner_api_calls['update_session_entity_type']( request, retry=retry, timeout=timeout, metadata=metadata)
python
def update_session_entity_type( self, session_entity_type, update_mask=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): # Wrap the transport method to add retry and timeout logic. if 'update_session_entity_type' not in self._inner_api_calls: self._inner_api_calls[ 'update_session_entity_type'] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_session_entity_type, default_retry=self._method_configs[ 'UpdateSessionEntityType'].retry, default_timeout=self._method_configs[ 'UpdateSessionEntityType'].timeout, client_info=self._client_info, ) request = session_entity_type_pb2.UpdateSessionEntityTypeRequest( session_entity_type=session_entity_type, update_mask=update_mask, ) return self._inner_api_calls['update_session_entity_type']( request, retry=retry, timeout=timeout, metadata=metadata)
[ "def", "update_session_entity_type", "(", "self", ",", "session_entity_type", ",", "update_mask", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", ...
Updates the specified session entity type. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.SessionEntityTypesClient() >>> >>> # TODO: Initialize ``session_entity_type``: >>> session_entity_type = {} >>> >>> response = client.update_session_entity_type(session_entity_type) Args: session_entity_type (Union[dict, ~google.cloud.dialogflow_v2.types.SessionEntityType]): Required. The entity type to update. Format: ``projects/<Project ID>/agent/sessions/<Session ID>/entityTypes/<Entity Type Display Name>``. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.SessionEntityType` update_mask (Union[dict, ~google.cloud.dialogflow_v2.types.FieldMask]): Optional. The mask to control which fields get updated. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.FieldMask` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.SessionEntityType` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Updates", "the", "specified", "session", "entity", "type", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/session_entity_types_client.py#L417-L482
238,363
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/session_entity_types_client.py
SessionEntityTypesClient.delete_session_entity_type
def delete_session_entity_type( self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Deletes the specified session entity type. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.SessionEntityTypesClient() >>> >>> name = client.session_entity_type_path('[PROJECT]', '[SESSION]', '[ENTITY_TYPE]') >>> >>> client.delete_session_entity_type(name) Args: name (str): Required. The name of the entity type to delete. Format: ``projects/<Project ID>/agent/sessions/<Session ID>/entityTypes/<Entity Type Display Name>``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'delete_session_entity_type' not in self._inner_api_calls: self._inner_api_calls[ 'delete_session_entity_type'] = google.api_core.gapic_v1.method.wrap_method( self.transport.delete_session_entity_type, default_retry=self._method_configs[ 'DeleteSessionEntityType'].retry, default_timeout=self._method_configs[ 'DeleteSessionEntityType'].timeout, client_info=self._client_info, ) request = session_entity_type_pb2.DeleteSessionEntityTypeRequest( name=name, ) self._inner_api_calls['delete_session_entity_type']( request, retry=retry, timeout=timeout, metadata=metadata)
python
def delete_session_entity_type( self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): # Wrap the transport method to add retry and timeout logic. if 'delete_session_entity_type' not in self._inner_api_calls: self._inner_api_calls[ 'delete_session_entity_type'] = google.api_core.gapic_v1.method.wrap_method( self.transport.delete_session_entity_type, default_retry=self._method_configs[ 'DeleteSessionEntityType'].retry, default_timeout=self._method_configs[ 'DeleteSessionEntityType'].timeout, client_info=self._client_info, ) request = session_entity_type_pb2.DeleteSessionEntityTypeRequest( name=name, ) self._inner_api_calls['delete_session_entity_type']( request, retry=retry, timeout=timeout, metadata=metadata)
[ "def", "delete_session_entity_type", "(", "self", ",", "name", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ","...
Deletes the specified session entity type. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.SessionEntityTypesClient() >>> >>> name = client.session_entity_type_path('[PROJECT]', '[SESSION]', '[ENTITY_TYPE]') >>> >>> client.delete_session_entity_type(name) Args: name (str): Required. The name of the entity type to delete. Format: ``projects/<Project ID>/agent/sessions/<Session ID>/entityTypes/<Entity Type Display Name>``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Deletes", "the", "specified", "session", "entity", "type", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/session_entity_types_client.py#L484-L537
238,364
googleapis/dialogflow-python-client-v2
samples/knowledge_base_management.py
list_knowledge_bases
def list_knowledge_bases(project_id): """Lists the Knowledge bases belonging to a project. Args: project_id: The GCP project linked with the agent.""" import dialogflow_v2beta1 as dialogflow client = dialogflow.KnowledgeBasesClient() project_path = client.project_path(project_id) print('Knowledge Bases for: {}'.format(project_id)) for knowledge_base in client.list_knowledge_bases(project_path): print(' - Display Name: {}'.format(knowledge_base.display_name)) print(' - Knowledge ID: {}\n'.format(knowledge_base.name))
python
def list_knowledge_bases(project_id): import dialogflow_v2beta1 as dialogflow client = dialogflow.KnowledgeBasesClient() project_path = client.project_path(project_id) print('Knowledge Bases for: {}'.format(project_id)) for knowledge_base in client.list_knowledge_bases(project_path): print(' - Display Name: {}'.format(knowledge_base.display_name)) print(' - Knowledge ID: {}\n'.format(knowledge_base.name))
[ "def", "list_knowledge_bases", "(", "project_id", ")", ":", "import", "dialogflow_v2beta1", "as", "dialogflow", "client", "=", "dialogflow", ".", "KnowledgeBasesClient", "(", ")", "project_path", "=", "client", ".", "project_path", "(", "project_id", ")", "print", ...
Lists the Knowledge bases belonging to a project. Args: project_id: The GCP project linked with the agent.
[ "Lists", "the", "Knowledge", "bases", "belonging", "to", "a", "project", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/knowledge_base_management.py#L35-L47
238,365
googleapis/dialogflow-python-client-v2
samples/knowledge_base_management.py
create_knowledge_base
def create_knowledge_base(project_id, display_name): """Creates a Knowledge base. Args: project_id: The GCP project linked with the agent. display_name: The display name of the Knowledge base.""" import dialogflow_v2beta1 as dialogflow client = dialogflow.KnowledgeBasesClient() project_path = client.project_path(project_id) knowledge_base = dialogflow.types.KnowledgeBase( display_name=display_name) response = client.create_knowledge_base(project_path, knowledge_base) print('Knowledge Base created:\n') print('Display Name: {}\n'.format(response.display_name)) print('Knowledge ID: {}\n'.format(response.name))
python
def create_knowledge_base(project_id, display_name): import dialogflow_v2beta1 as dialogflow client = dialogflow.KnowledgeBasesClient() project_path = client.project_path(project_id) knowledge_base = dialogflow.types.KnowledgeBase( display_name=display_name) response = client.create_knowledge_base(project_path, knowledge_base) print('Knowledge Base created:\n') print('Display Name: {}\n'.format(response.display_name)) print('Knowledge ID: {}\n'.format(response.name))
[ "def", "create_knowledge_base", "(", "project_id", ",", "display_name", ")", ":", "import", "dialogflow_v2beta1", "as", "dialogflow", "client", "=", "dialogflow", ".", "KnowledgeBasesClient", "(", ")", "project_path", "=", "client", ".", "project_path", "(", "projec...
Creates a Knowledge base. Args: project_id: The GCP project linked with the agent. display_name: The display name of the Knowledge base.
[ "Creates", "a", "Knowledge", "base", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/knowledge_base_management.py#L52-L69
238,366
googleapis/dialogflow-python-client-v2
samples/knowledge_base_management.py
get_knowledge_base
def get_knowledge_base(project_id, knowledge_base_id): """Gets a specific Knowledge base. Args: project_id: The GCP project linked with the agent. knowledge_base_id: Id of the Knowledge base.""" import dialogflow_v2beta1 as dialogflow client = dialogflow.KnowledgeBasesClient() knowledge_base_path = client.knowledge_base_path( project_id, knowledge_base_id) response = client.get_knowledge_base(knowledge_base_path) print('Got Knowledge Base:') print(' - Display Name: {}'.format(response.display_name)) print(' - Knowledge ID: {}'.format(response.name))
python
def get_knowledge_base(project_id, knowledge_base_id): import dialogflow_v2beta1 as dialogflow client = dialogflow.KnowledgeBasesClient() knowledge_base_path = client.knowledge_base_path( project_id, knowledge_base_id) response = client.get_knowledge_base(knowledge_base_path) print('Got Knowledge Base:') print(' - Display Name: {}'.format(response.display_name)) print(' - Knowledge ID: {}'.format(response.name))
[ "def", "get_knowledge_base", "(", "project_id", ",", "knowledge_base_id", ")", ":", "import", "dialogflow_v2beta1", "as", "dialogflow", "client", "=", "dialogflow", ".", "KnowledgeBasesClient", "(", ")", "knowledge_base_path", "=", "client", ".", "knowledge_base_path", ...
Gets a specific Knowledge base. Args: project_id: The GCP project linked with the agent. knowledge_base_id: Id of the Knowledge base.
[ "Gets", "a", "specific", "Knowledge", "base", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/knowledge_base_management.py#L74-L89
238,367
googleapis/dialogflow-python-client-v2
samples/knowledge_base_management.py
delete_knowledge_base
def delete_knowledge_base(project_id, knowledge_base_id): """Deletes a specific Knowledge base. Args: project_id: The GCP project linked with the agent. knowledge_base_id: Id of the Knowledge base.""" import dialogflow_v2beta1 as dialogflow client = dialogflow.KnowledgeBasesClient() knowledge_base_path = client.knowledge_base_path( project_id, knowledge_base_id) response = client.delete_knowledge_base(knowledge_base_path) print('Knowledge Base deleted.'.format(response))
python
def delete_knowledge_base(project_id, knowledge_base_id): import dialogflow_v2beta1 as dialogflow client = dialogflow.KnowledgeBasesClient() knowledge_base_path = client.knowledge_base_path( project_id, knowledge_base_id) response = client.delete_knowledge_base(knowledge_base_path) print('Knowledge Base deleted.'.format(response))
[ "def", "delete_knowledge_base", "(", "project_id", ",", "knowledge_base_id", ")", ":", "import", "dialogflow_v2beta1", "as", "dialogflow", "client", "=", "dialogflow", ".", "KnowledgeBasesClient", "(", ")", "knowledge_base_path", "=", "client", ".", "knowledge_base_path...
Deletes a specific Knowledge base. Args: project_id: The GCP project linked with the agent. knowledge_base_id: Id of the Knowledge base.
[ "Deletes", "a", "specific", "Knowledge", "base", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/knowledge_base_management.py#L94-L107
238,368
googleapis/dialogflow-python-client-v2
samples/detect_intent_with_texttospeech_response.py
detect_intent_with_texttospeech_response
def detect_intent_with_texttospeech_response(project_id, session_id, texts, language_code): """Returns the result of detect intent with texts as inputs and includes the response in an audio format. Using the same `session_id` between requests allows continuation of the conversaion.""" import dialogflow_v2beta1 as dialogflow session_client = dialogflow.SessionsClient() session_path = session_client.session_path(project_id, session_id) print('Session path: {}\n'.format(session_path)) for text in texts: text_input = dialogflow.types.TextInput( text=text, language_code=language_code) query_input = dialogflow.types.QueryInput(text=text_input) # Set the query parameters with sentiment analysis output_audio_config = dialogflow.types.OutputAudioConfig( audio_encoding=dialogflow.enums.OutputAudioEncoding .OUTPUT_AUDIO_ENCODING_LINEAR_16) response = session_client.detect_intent( session=session_path, query_input=query_input, output_audio_config=output_audio_config) print('=' * 20) print('Query text: {}'.format(response.query_result.query_text)) print('Detected intent: {} (confidence: {})\n'.format( response.query_result.intent.display_name, response.query_result.intent_detection_confidence)) print('Fulfillment text: {}\n'.format( response.query_result.fulfillment_text)) # The response's audio_content is binary. with open('output.wav', 'wb') as out: out.write(response.output_audio) print('Audio content written to file "output.wav"')
python
def detect_intent_with_texttospeech_response(project_id, session_id, texts, language_code): import dialogflow_v2beta1 as dialogflow session_client = dialogflow.SessionsClient() session_path = session_client.session_path(project_id, session_id) print('Session path: {}\n'.format(session_path)) for text in texts: text_input = dialogflow.types.TextInput( text=text, language_code=language_code) query_input = dialogflow.types.QueryInput(text=text_input) # Set the query parameters with sentiment analysis output_audio_config = dialogflow.types.OutputAudioConfig( audio_encoding=dialogflow.enums.OutputAudioEncoding .OUTPUT_AUDIO_ENCODING_LINEAR_16) response = session_client.detect_intent( session=session_path, query_input=query_input, output_audio_config=output_audio_config) print('=' * 20) print('Query text: {}'.format(response.query_result.query_text)) print('Detected intent: {} (confidence: {})\n'.format( response.query_result.intent.display_name, response.query_result.intent_detection_confidence)) print('Fulfillment text: {}\n'.format( response.query_result.fulfillment_text)) # The response's audio_content is binary. with open('output.wav', 'wb') as out: out.write(response.output_audio) print('Audio content written to file "output.wav"')
[ "def", "detect_intent_with_texttospeech_response", "(", "project_id", ",", "session_id", ",", "texts", ",", "language_code", ")", ":", "import", "dialogflow_v2beta1", "as", "dialogflow", "session_client", "=", "dialogflow", ".", "SessionsClient", "(", ")", "session_path...
Returns the result of detect intent with texts as inputs and includes the response in an audio format. Using the same `session_id` between requests allows continuation of the conversaion.
[ "Returns", "the", "result", "of", "detect", "intent", "with", "texts", "as", "inputs", "and", "includes", "the", "response", "in", "an", "audio", "format", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/detect_intent_with_texttospeech_response.py#L30-L68
238,369
googleapis/dialogflow-python-client-v2
samples/detect_intent_with_model_selection.py
detect_intent_with_model_selection
def detect_intent_with_model_selection(project_id, session_id, audio_file_path, language_code): """Returns the result of detect intent with model selection on an audio file as input Using the same `session_id` between requests allows continuation of the conversaion.""" import dialogflow_v2beta1 as dialogflow session_client = dialogflow.SessionsClient() # Note: hard coding audio_encoding and sample_rate_hertz for simplicity. audio_encoding = dialogflow.enums.AudioEncoding.AUDIO_ENCODING_LINEAR_16 sample_rate_hertz = 16000 session_path = session_client.session_path(project_id, session_id) print('Session path: {}\n'.format(session_path)) with open(audio_file_path, 'rb') as audio_file: input_audio = audio_file.read() # Which Speech model to select for the given request. # Possible models: video, phone_call, command_and_search, default model = 'phone_call' audio_config = dialogflow.types.InputAudioConfig( audio_encoding=audio_encoding, language_code=language_code, sample_rate_hertz=sample_rate_hertz, model=model) query_input = dialogflow.types.QueryInput(audio_config=audio_config) response = session_client.detect_intent( session=session_path, query_input=query_input, input_audio=input_audio) print('=' * 20) print('Query text: {}'.format(response.query_result.query_text)) print('Detected intent: {} (confidence: {})\n'.format( response.query_result.intent.display_name, response.query_result.intent_detection_confidence)) print('Fulfillment text: {}\n'.format( response.query_result.fulfillment_text))
python
def detect_intent_with_model_selection(project_id, session_id, audio_file_path, language_code): import dialogflow_v2beta1 as dialogflow session_client = dialogflow.SessionsClient() # Note: hard coding audio_encoding and sample_rate_hertz for simplicity. audio_encoding = dialogflow.enums.AudioEncoding.AUDIO_ENCODING_LINEAR_16 sample_rate_hertz = 16000 session_path = session_client.session_path(project_id, session_id) print('Session path: {}\n'.format(session_path)) with open(audio_file_path, 'rb') as audio_file: input_audio = audio_file.read() # Which Speech model to select for the given request. # Possible models: video, phone_call, command_and_search, default model = 'phone_call' audio_config = dialogflow.types.InputAudioConfig( audio_encoding=audio_encoding, language_code=language_code, sample_rate_hertz=sample_rate_hertz, model=model) query_input = dialogflow.types.QueryInput(audio_config=audio_config) response = session_client.detect_intent( session=session_path, query_input=query_input, input_audio=input_audio) print('=' * 20) print('Query text: {}'.format(response.query_result.query_text)) print('Detected intent: {} (confidence: {})\n'.format( response.query_result.intent.display_name, response.query_result.intent_detection_confidence)) print('Fulfillment text: {}\n'.format( response.query_result.fulfillment_text))
[ "def", "detect_intent_with_model_selection", "(", "project_id", ",", "session_id", ",", "audio_file_path", ",", "language_code", ")", ":", "import", "dialogflow_v2beta1", "as", "dialogflow", "session_client", "=", "dialogflow", ".", "SessionsClient", "(", ")", "# Note: ...
Returns the result of detect intent with model selection on an audio file as input Using the same `session_id` between requests allows continuation of the conversaion.
[ "Returns", "the", "result", "of", "detect", "intent", "with", "model", "selection", "on", "an", "audio", "file", "as", "input" ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/detect_intent_with_model_selection.py#L30-L70
238,370
googleapis/dialogflow-python-client-v2
dialogflow_v2beta1/gapic/knowledge_bases_client.py
KnowledgeBasesClient.knowledge_base_path
def knowledge_base_path(cls, project, knowledge_base): """Return a fully-qualified knowledge_base string.""" return google.api_core.path_template.expand( 'projects/{project}/knowledgeBases/{knowledge_base}', project=project, knowledge_base=knowledge_base, )
python
def knowledge_base_path(cls, project, knowledge_base): return google.api_core.path_template.expand( 'projects/{project}/knowledgeBases/{knowledge_base}', project=project, knowledge_base=knowledge_base, )
[ "def", "knowledge_base_path", "(", "cls", ",", "project", ",", "knowledge_base", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "'projects/{project}/knowledgeBases/{knowledge_base}'", ",", "project", "=", "project", ",", "kn...
Return a fully-qualified knowledge_base string.
[ "Return", "a", "fully", "-", "qualified", "knowledge_base", "string", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2beta1/gapic/knowledge_bases_client.py#L97-L103
238,371
googleapis/dialogflow-python-client-v2
dialogflow_v2beta1/gapic/knowledge_bases_client.py
KnowledgeBasesClient.get_knowledge_base
def get_knowledge_base(self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Retrieves the specified knowledge base. Example: >>> import dialogflow_v2beta1 >>> >>> client = dialogflow_v2beta1.KnowledgeBasesClient() >>> >>> name = client.knowledge_base_path('[PROJECT]', '[KNOWLEDGE_BASE]') >>> >>> response = client.get_knowledge_base(name) Args: name (str): Required. The name of the knowledge base to retrieve. Format ``projects/<Project ID>/knowledgeBases/<Knowledge Base ID>``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2beta1.types.KnowledgeBase` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'get_knowledge_base' not in self._inner_api_calls: self._inner_api_calls[ 'get_knowledge_base'] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_knowledge_base, default_retry=self._method_configs[ 'GetKnowledgeBase'].retry, default_timeout=self._method_configs['GetKnowledgeBase'] .timeout, client_info=self._client_info, ) request = knowledge_base_pb2.GetKnowledgeBaseRequest(name=name, ) return self._inner_api_calls['get_knowledge_base']( request, retry=retry, timeout=timeout, metadata=metadata)
python
def get_knowledge_base(self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): # Wrap the transport method to add retry and timeout logic. if 'get_knowledge_base' not in self._inner_api_calls: self._inner_api_calls[ 'get_knowledge_base'] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_knowledge_base, default_retry=self._method_configs[ 'GetKnowledgeBase'].retry, default_timeout=self._method_configs['GetKnowledgeBase'] .timeout, client_info=self._client_info, ) request = knowledge_base_pb2.GetKnowledgeBaseRequest(name=name, ) return self._inner_api_calls['get_knowledge_base']( request, retry=retry, timeout=timeout, metadata=metadata)
[ "def", "get_knowledge_base", "(", "self", ",", "name", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "met...
Retrieves the specified knowledge base. Example: >>> import dialogflow_v2beta1 >>> >>> client = dialogflow_v2beta1.KnowledgeBasesClient() >>> >>> name = client.knowledge_base_path('[PROJECT]', '[KNOWLEDGE_BASE]') >>> >>> response = client.get_knowledge_base(name) Args: name (str): Required. The name of the knowledge base to retrieve. Format ``projects/<Project ID>/knowledgeBases/<Knowledge Base ID>``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2beta1.types.KnowledgeBase` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Retrieves", "the", "specified", "knowledge", "base", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2beta1/gapic/knowledge_bases_client.py#L283-L336
238,372
googleapis/dialogflow-python-client-v2
dialogflow_v2beta1/gapic/knowledge_bases_client.py
KnowledgeBasesClient.create_knowledge_base
def create_knowledge_base(self, parent, knowledge_base, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Creates a knowledge base. Example: >>> import dialogflow_v2beta1 >>> >>> client = dialogflow_v2beta1.KnowledgeBasesClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize ``knowledge_base``: >>> knowledge_base = {} >>> >>> response = client.create_knowledge_base(parent, knowledge_base) Args: parent (str): Required. The agent to create a knowledge base for. Format: ``projects/<Project ID>/agent``. knowledge_base (Union[dict, ~google.cloud.dialogflow_v2beta1.types.KnowledgeBase]): Required. The knowledge base to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2beta1.types.KnowledgeBase` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2beta1.types.KnowledgeBase` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'create_knowledge_base' not in self._inner_api_calls: self._inner_api_calls[ 'create_knowledge_base'] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_knowledge_base, default_retry=self._method_configs[ 'CreateKnowledgeBase'].retry, default_timeout=self._method_configs['CreateKnowledgeBase'] .timeout, client_info=self._client_info, ) request = knowledge_base_pb2.CreateKnowledgeBaseRequest( parent=parent, knowledge_base=knowledge_base, ) return self._inner_api_calls['create_knowledge_base']( request, retry=retry, timeout=timeout, metadata=metadata)
python
def create_knowledge_base(self, parent, knowledge_base, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): # Wrap the transport method to add retry and timeout logic. if 'create_knowledge_base' not in self._inner_api_calls: self._inner_api_calls[ 'create_knowledge_base'] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_knowledge_base, default_retry=self._method_configs[ 'CreateKnowledgeBase'].retry, default_timeout=self._method_configs['CreateKnowledgeBase'] .timeout, client_info=self._client_info, ) request = knowledge_base_pb2.CreateKnowledgeBaseRequest( parent=parent, knowledge_base=knowledge_base, ) return self._inner_api_calls['create_knowledge_base']( request, retry=retry, timeout=timeout, metadata=metadata)
[ "def", "create_knowledge_base", "(", "self", ",", "parent", ",", "knowledge_base", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ...
Creates a knowledge base. Example: >>> import dialogflow_v2beta1 >>> >>> client = dialogflow_v2beta1.KnowledgeBasesClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize ``knowledge_base``: >>> knowledge_base = {} >>> >>> response = client.create_knowledge_base(parent, knowledge_base) Args: parent (str): Required. The agent to create a knowledge base for. Format: ``projects/<Project ID>/agent``. knowledge_base (Union[dict, ~google.cloud.dialogflow_v2beta1.types.KnowledgeBase]): Required. The knowledge base to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2beta1.types.KnowledgeBase` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2beta1.types.KnowledgeBase` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Creates", "a", "knowledge", "base", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2beta1/gapic/knowledge_bases_client.py#L338-L401
238,373
googleapis/dialogflow-python-client-v2
dialogflow_v2beta1/gapic/session_entity_types_client.py
SessionEntityTypesClient.environment_session_path
def environment_session_path(cls, project, environment, user, session): """Return a fully-qualified environment_session string.""" return google.api_core.path_template.expand( 'projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}', project=project, environment=environment, user=user, session=session, )
python
def environment_session_path(cls, project, environment, user, session): return google.api_core.path_template.expand( 'projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}', project=project, environment=environment, user=user, session=session, )
[ "def", "environment_session_path", "(", "cls", ",", "project", ",", "environment", ",", "user", ",", "session", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "'projects/{project}/agent/environments/{environment}/users/{user}/se...
Return a fully-qualified environment_session string.
[ "Return", "a", "fully", "-", "qualified", "environment_session", "string", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2beta1/gapic/session_entity_types_client.py#L109-L117
238,374
googleapis/dialogflow-python-client-v2
dialogflow_v2beta1/gapic/session_entity_types_client.py
SessionEntityTypesClient.environment_session_entity_type_path
def environment_session_entity_type_path(cls, project, environment, user, session, entity_type): """Return a fully-qualified environment_session_entity_type string.""" return google.api_core.path_template.expand( 'projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}/entityTypes/{entity_type}', project=project, environment=environment, user=user, session=session, entity_type=entity_type, )
python
def environment_session_entity_type_path(cls, project, environment, user, session, entity_type): return google.api_core.path_template.expand( 'projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}/entityTypes/{entity_type}', project=project, environment=environment, user=user, session=session, entity_type=entity_type, )
[ "def", "environment_session_entity_type_path", "(", "cls", ",", "project", ",", "environment", ",", "user", ",", "session", ",", "entity_type", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "'projects/{project}/agent/enviro...
Return a fully-qualified environment_session_entity_type string.
[ "Return", "a", "fully", "-", "qualified", "environment_session_entity_type", "string", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2beta1/gapic/session_entity_types_client.py#L130-L140
238,375
googleapis/dialogflow-python-client-v2
dialogflow_v2beta1/gapic/documents_client.py
DocumentsClient.document_path
def document_path(cls, project, knowledge_base, document): """Return a fully-qualified document string.""" return google.api_core.path_template.expand( 'projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}', project=project, knowledge_base=knowledge_base, document=document, )
python
def document_path(cls, project, knowledge_base, document): return google.api_core.path_template.expand( 'projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}', project=project, knowledge_base=knowledge_base, document=document, )
[ "def", "document_path", "(", "cls", ",", "project", ",", "knowledge_base", ",", "document", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "'projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}'", ",", "projec...
Return a fully-qualified document string.
[ "Return", "a", "fully", "-", "qualified", "document", "string", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2beta1/gapic/documents_client.py#L90-L97
238,376
googleapis/dialogflow-python-client-v2
dialogflow_v2beta1/gapic/documents_client.py
DocumentsClient.list_documents
def list_documents(self, parent, page_size=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Returns the list of all documents of the knowledge base. Example: >>> import dialogflow_v2beta1 >>> >>> client = dialogflow_v2beta1.DocumentsClient() >>> >>> parent = client.knowledge_base_path('[PROJECT]', '[KNOWLEDGE_BASE]') >>> >>> # Iterate over all results >>> for element in client.list_documents(parent): ... # process element ... pass >>> >>> >>> # Alternatively: >>> >>> # Iterate over results one page at a time >>> for page in client.list_documents(parent, options=CallOptions(page_token=INITIAL_PAGE)): ... for element in page: ... # process element ... pass Args: parent (str): Required. The knowledge base to list all documents for. Format: ``projects/<Project ID>/knowledgeBases/<Knowledge Base ID>``. page_size (int): The maximum number of resources contained in the underlying API response. If page streaming is performed per- resource, this parameter does not affect the return value. If page streaming is performed per-page, this determines the maximum number of resources in a page. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.gax.PageIterator` instance. By default, this is an iterable of :class:`~google.cloud.dialogflow_v2beta1.types.Document` instances. This object can also be configured to iterate over the pages of the response through the `options` parameter. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'list_documents' not in self._inner_api_calls: self._inner_api_calls[ 'list_documents'] = google.api_core.gapic_v1.method.wrap_method( self.transport.list_documents, default_retry=self._method_configs['ListDocuments'].retry, default_timeout=self._method_configs['ListDocuments'] .timeout, client_info=self._client_info, ) request = document_pb2.ListDocumentsRequest( parent=parent, page_size=page_size, ) iterator = google.api_core.page_iterator.GRPCIterator( client=None, method=functools.partial( self._inner_api_calls['list_documents'], retry=retry, timeout=timeout, metadata=metadata), request=request, items_field='documents', request_token_field='page_token', response_token_field='next_page_token', ) return iterator
python
def list_documents(self, parent, page_size=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): # Wrap the transport method to add retry and timeout logic. if 'list_documents' not in self._inner_api_calls: self._inner_api_calls[ 'list_documents'] = google.api_core.gapic_v1.method.wrap_method( self.transport.list_documents, default_retry=self._method_configs['ListDocuments'].retry, default_timeout=self._method_configs['ListDocuments'] .timeout, client_info=self._client_info, ) request = document_pb2.ListDocumentsRequest( parent=parent, page_size=page_size, ) iterator = google.api_core.page_iterator.GRPCIterator( client=None, method=functools.partial( self._inner_api_calls['list_documents'], retry=retry, timeout=timeout, metadata=metadata), request=request, items_field='documents', request_token_field='page_token', response_token_field='next_page_token', ) return iterator
[ "def", "list_documents", "(", "self", ",", "parent", ",", "page_size", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "metho...
Returns the list of all documents of the knowledge base. Example: >>> import dialogflow_v2beta1 >>> >>> client = dialogflow_v2beta1.DocumentsClient() >>> >>> parent = client.knowledge_base_path('[PROJECT]', '[KNOWLEDGE_BASE]') >>> >>> # Iterate over all results >>> for element in client.list_documents(parent): ... # process element ... pass >>> >>> >>> # Alternatively: >>> >>> # Iterate over results one page at a time >>> for page in client.list_documents(parent, options=CallOptions(page_token=INITIAL_PAGE)): ... for element in page: ... # process element ... pass Args: parent (str): Required. The knowledge base to list all documents for. Format: ``projects/<Project ID>/knowledgeBases/<Knowledge Base ID>``. page_size (int): The maximum number of resources contained in the underlying API response. If page streaming is performed per- resource, this parameter does not affect the return value. If page streaming is performed per-page, this determines the maximum number of resources in a page. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.gax.PageIterator` instance. By default, this is an iterable of :class:`~google.cloud.dialogflow_v2beta1.types.Document` instances. This object can also be configured to iterate over the pages of the response through the `options` parameter. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Returns", "the", "list", "of", "all", "documents", "of", "the", "knowledge", "base", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2beta1/gapic/documents_client.py#L187-L274
238,377
googleapis/dialogflow-python-client-v2
dialogflow_v2beta1/gapic/documents_client.py
DocumentsClient.delete_document
def delete_document(self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Deletes the specified document. Operation <response: ``google.protobuf.Empty``, metadata: [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata]> Example: >>> import dialogflow_v2beta1 >>> >>> client = dialogflow_v2beta1.DocumentsClient() >>> >>> name = client.document_path('[PROJECT]', '[KNOWLEDGE_BASE]', '[DOCUMENT]') >>> >>> response = client.delete_document(name) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: name (str): The name of the document to delete. Format: ``projects/<Project ID>/knowledgeBases/<Knowledge Base ID>/documents/<Document ID>``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2beta1.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'delete_document' not in self._inner_api_calls: self._inner_api_calls[ 'delete_document'] = google.api_core.gapic_v1.method.wrap_method( self.transport.delete_document, default_retry=self._method_configs['DeleteDocument'].retry, default_timeout=self._method_configs['DeleteDocument'] .timeout, client_info=self._client_info, ) request = document_pb2.DeleteDocumentRequest(name=name, ) operation = self._inner_api_calls['delete_document']( request, retry=retry, timeout=timeout, metadata=metadata) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, empty_pb2.Empty, metadata_type=document_pb2.KnowledgeOperationMetadata, )
python
def delete_document(self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): # Wrap the transport method to add retry and timeout logic. if 'delete_document' not in self._inner_api_calls: self._inner_api_calls[ 'delete_document'] = google.api_core.gapic_v1.method.wrap_method( self.transport.delete_document, default_retry=self._method_configs['DeleteDocument'].retry, default_timeout=self._method_configs['DeleteDocument'] .timeout, client_info=self._client_info, ) request = document_pb2.DeleteDocumentRequest(name=name, ) operation = self._inner_api_calls['delete_document']( request, retry=retry, timeout=timeout, metadata=metadata) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, empty_pb2.Empty, metadata_type=document_pb2.KnowledgeOperationMetadata, )
[ "def", "delete_document", "(", "self", ",", "name", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "metada...
Deletes the specified document. Operation <response: ``google.protobuf.Empty``, metadata: [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata]> Example: >>> import dialogflow_v2beta1 >>> >>> client = dialogflow_v2beta1.DocumentsClient() >>> >>> name = client.document_path('[PROJECT]', '[KNOWLEDGE_BASE]', '[DOCUMENT]') >>> >>> response = client.delete_document(name) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: name (str): The name of the document to delete. Format: ``projects/<Project ID>/knowledgeBases/<Knowledge Base ID>/documents/<Document ID>``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2beta1.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Deletes", "the", "specified", "document", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2beta1/gapic/documents_client.py#L413-L484
238,378
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/contexts_client.py
ContextsClient.context_path
def context_path(cls, project, session, context): """Return a fully-qualified context string.""" return google.api_core.path_template.expand( 'projects/{project}/agent/sessions/{session}/contexts/{context}', project=project, session=session, context=context, )
python
def context_path(cls, project, session, context): return google.api_core.path_template.expand( 'projects/{project}/agent/sessions/{session}/contexts/{context}', project=project, session=session, context=context, )
[ "def", "context_path", "(", "cls", ",", "project", ",", "session", ",", "context", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "'projects/{project}/agent/sessions/{session}/contexts/{context}'", ",", "project", "=", "proj...
Return a fully-qualified context string.
[ "Return", "a", "fully", "-", "qualified", "context", "string", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/contexts_client.py#L104-L111
238,379
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/contexts_client.py
ContextsClient.get_context
def get_context(self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Retrieves the specified context. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.ContextsClient() >>> >>> name = client.context_path('[PROJECT]', '[SESSION]', '[CONTEXT]') >>> >>> response = client.get_context(name) Args: name (str): Required. The name of the context. Format: ``projects/<Project ID>/agent/sessions/<Session ID>/contexts/<Context ID>``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.Context` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'get_context' not in self._inner_api_calls: self._inner_api_calls[ 'get_context'] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_context, default_retry=self._method_configs['GetContext'].retry, default_timeout=self._method_configs['GetContext'].timeout, client_info=self._client_info, ) request = context_pb2.GetContextRequest(name=name, ) return self._inner_api_calls['get_context']( request, retry=retry, timeout=timeout, metadata=metadata)
python
def get_context(self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): # Wrap the transport method to add retry and timeout logic. if 'get_context' not in self._inner_api_calls: self._inner_api_calls[ 'get_context'] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_context, default_retry=self._method_configs['GetContext'].retry, default_timeout=self._method_configs['GetContext'].timeout, client_info=self._client_info, ) request = context_pb2.GetContextRequest(name=name, ) return self._inner_api_calls['get_context']( request, retry=retry, timeout=timeout, metadata=metadata)
[ "def", "get_context", "(", "self", ",", "name", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "metadata",...
Retrieves the specified context. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.ContextsClient() >>> >>> name = client.context_path('[PROJECT]', '[SESSION]', '[CONTEXT]') >>> >>> response = client.get_context(name) Args: name (str): Required. The name of the context. Format: ``projects/<Project ID>/agent/sessions/<Session ID>/contexts/<Context ID>``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.Context` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Retrieves", "the", "specified", "context", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/contexts_client.py#L290-L341
238,380
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/contexts_client.py
ContextsClient.update_context
def update_context(self, context, update_mask=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Updates the specified context. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.ContextsClient() >>> >>> # TODO: Initialize ``context``: >>> context = {} >>> >>> response = client.update_context(context) Args: context (Union[dict, ~google.cloud.dialogflow_v2.types.Context]): Required. The context to update. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.Context` update_mask (Union[dict, ~google.cloud.dialogflow_v2.types.FieldMask]): Optional. The mask to control which fields get updated. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.FieldMask` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.Context` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'update_context' not in self._inner_api_calls: self._inner_api_calls[ 'update_context'] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_context, default_retry=self._method_configs['UpdateContext'].retry, default_timeout=self._method_configs['UpdateContext'] .timeout, client_info=self._client_info, ) request = context_pb2.UpdateContextRequest( context=context, update_mask=update_mask, ) return self._inner_api_calls['update_context']( request, retry=retry, timeout=timeout, metadata=metadata)
python
def update_context(self, context, update_mask=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): # Wrap the transport method to add retry and timeout logic. if 'update_context' not in self._inner_api_calls: self._inner_api_calls[ 'update_context'] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_context, default_retry=self._method_configs['UpdateContext'].retry, default_timeout=self._method_configs['UpdateContext'] .timeout, client_info=self._client_info, ) request = context_pb2.UpdateContextRequest( context=context, update_mask=update_mask, ) return self._inner_api_calls['update_context']( request, retry=retry, timeout=timeout, metadata=metadata)
[ "def", "update_context", "(", "self", ",", "context", ",", "update_mask", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "me...
Updates the specified context. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.ContextsClient() >>> >>> # TODO: Initialize ``context``: >>> context = {} >>> >>> response = client.update_context(context) Args: context (Union[dict, ~google.cloud.dialogflow_v2.types.Context]): Required. The context to update. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.Context` update_mask (Union[dict, ~google.cloud.dialogflow_v2.types.FieldMask]): Optional. The mask to control which fields get updated. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.FieldMask` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.Context` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Updates", "the", "specified", "context", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/contexts_client.py#L407-L468
238,381
googleapis/dialogflow-python-client-v2
samples/session_entity_type_management.py
create_session_entity_type
def create_session_entity_type(project_id, session_id, entity_values, entity_type_display_name, entity_override_mode): """Create a session entity type with the given display name.""" import dialogflow_v2 as dialogflow session_entity_types_client = dialogflow.SessionEntityTypesClient() session_path = session_entity_types_client.session_path( project_id, session_id) session_entity_type_name = ( session_entity_types_client.session_entity_type_path( project_id, session_id, entity_type_display_name)) # Here we use the entity value as the only synonym. entities = [ dialogflow.types.EntityType.Entity(value=value, synonyms=[value]) for value in entity_values] session_entity_type = dialogflow.types.SessionEntityType( name=session_entity_type_name, entity_override_mode=entity_override_mode, entities=entities) response = session_entity_types_client.create_session_entity_type( session_path, session_entity_type) print('SessionEntityType created: \n\n{}'.format(response))
python
def create_session_entity_type(project_id, session_id, entity_values, entity_type_display_name, entity_override_mode): import dialogflow_v2 as dialogflow session_entity_types_client = dialogflow.SessionEntityTypesClient() session_path = session_entity_types_client.session_path( project_id, session_id) session_entity_type_name = ( session_entity_types_client.session_entity_type_path( project_id, session_id, entity_type_display_name)) # Here we use the entity value as the only synonym. entities = [ dialogflow.types.EntityType.Entity(value=value, synonyms=[value]) for value in entity_values] session_entity_type = dialogflow.types.SessionEntityType( name=session_entity_type_name, entity_override_mode=entity_override_mode, entities=entities) response = session_entity_types_client.create_session_entity_type( session_path, session_entity_type) print('SessionEntityType created: \n\n{}'.format(response))
[ "def", "create_session_entity_type", "(", "project_id", ",", "session_id", ",", "entity_values", ",", "entity_type_display_name", ",", "entity_override_mode", ")", ":", "import", "dialogflow_v2", "as", "dialogflow", "session_entity_types_client", "=", "dialogflow", ".", "...
Create a session entity type with the given display name.
[ "Create", "a", "session", "entity", "type", "with", "the", "given", "display", "name", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/session_entity_type_management.py#L54-L78
238,382
googleapis/dialogflow-python-client-v2
samples/session_entity_type_management.py
delete_session_entity_type
def delete_session_entity_type(project_id, session_id, entity_type_display_name): """Delete session entity type with the given entity type display name.""" import dialogflow_v2 as dialogflow session_entity_types_client = dialogflow.SessionEntityTypesClient() session_entity_type_name = ( session_entity_types_client.session_entity_type_path( project_id, session_id, entity_type_display_name)) session_entity_types_client.delete_session_entity_type( session_entity_type_name)
python
def delete_session_entity_type(project_id, session_id, entity_type_display_name): import dialogflow_v2 as dialogflow session_entity_types_client = dialogflow.SessionEntityTypesClient() session_entity_type_name = ( session_entity_types_client.session_entity_type_path( project_id, session_id, entity_type_display_name)) session_entity_types_client.delete_session_entity_type( session_entity_type_name)
[ "def", "delete_session_entity_type", "(", "project_id", ",", "session_id", ",", "entity_type_display_name", ")", ":", "import", "dialogflow_v2", "as", "dialogflow", "session_entity_types_client", "=", "dialogflow", ".", "SessionEntityTypesClient", "(", ")", "session_entity_...
Delete session entity type with the given entity type display name.
[ "Delete", "session", "entity", "type", "with", "the", "given", "entity", "type", "display", "name", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/session_entity_type_management.py#L83-L94
238,383
googleapis/dialogflow-python-client-v2
samples/entity_type_management.py
create_entity_type
def create_entity_type(project_id, display_name, kind): """Create an entity type with the given display name.""" import dialogflow_v2 as dialogflow entity_types_client = dialogflow.EntityTypesClient() parent = entity_types_client.project_agent_path(project_id) entity_type = dialogflow.types.EntityType( display_name=display_name, kind=kind) response = entity_types_client.create_entity_type(parent, entity_type) print('Entity type created: \n{}'.format(response))
python
def create_entity_type(project_id, display_name, kind): import dialogflow_v2 as dialogflow entity_types_client = dialogflow.EntityTypesClient() parent = entity_types_client.project_agent_path(project_id) entity_type = dialogflow.types.EntityType( display_name=display_name, kind=kind) response = entity_types_client.create_entity_type(parent, entity_type) print('Entity type created: \n{}'.format(response))
[ "def", "create_entity_type", "(", "project_id", ",", "display_name", ",", "kind", ")", ":", "import", "dialogflow_v2", "as", "dialogflow", "entity_types_client", "=", "dialogflow", ".", "EntityTypesClient", "(", ")", "parent", "=", "entity_types_client", ".", "proje...
Create an entity type with the given display name.
[ "Create", "an", "entity", "type", "with", "the", "given", "display", "name", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/entity_type_management.py#L45-L56
238,384
googleapis/dialogflow-python-client-v2
samples/entity_type_management.py
delete_entity_type
def delete_entity_type(project_id, entity_type_id): """Delete entity type with the given entity type name.""" import dialogflow_v2 as dialogflow entity_types_client = dialogflow.EntityTypesClient() entity_type_path = entity_types_client.entity_type_path( project_id, entity_type_id) entity_types_client.delete_entity_type(entity_type_path)
python
def delete_entity_type(project_id, entity_type_id): import dialogflow_v2 as dialogflow entity_types_client = dialogflow.EntityTypesClient() entity_type_path = entity_types_client.entity_type_path( project_id, entity_type_id) entity_types_client.delete_entity_type(entity_type_path)
[ "def", "delete_entity_type", "(", "project_id", ",", "entity_type_id", ")", ":", "import", "dialogflow_v2", "as", "dialogflow", "entity_types_client", "=", "dialogflow", ".", "EntityTypesClient", "(", ")", "entity_type_path", "=", "entity_types_client", ".", "entity_typ...
Delete entity type with the given entity type name.
[ "Delete", "entity", "type", "with", "the", "given", "entity", "type", "name", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/entity_type_management.py#L61-L69
238,385
googleapis/dialogflow-python-client-v2
samples/detect_intent_texts.py
detect_intent_texts
def detect_intent_texts(project_id, session_id, texts, language_code): """Returns the result of detect intent with texts as inputs. Using the same `session_id` between requests allows continuation of the conversation.""" import dialogflow_v2 as dialogflow session_client = dialogflow.SessionsClient() session = session_client.session_path(project_id, session_id) print('Session path: {}\n'.format(session)) for text in texts: text_input = dialogflow.types.TextInput( text=text, language_code=language_code) query_input = dialogflow.types.QueryInput(text=text_input) response = session_client.detect_intent( session=session, query_input=query_input) print('=' * 20) print('Query text: {}'.format(response.query_result.query_text)) print('Detected intent: {} (confidence: {})\n'.format( response.query_result.intent.display_name, response.query_result.intent_detection_confidence)) print('Fulfillment text: {}\n'.format( response.query_result.fulfillment_text))
python
def detect_intent_texts(project_id, session_id, texts, language_code): import dialogflow_v2 as dialogflow session_client = dialogflow.SessionsClient() session = session_client.session_path(project_id, session_id) print('Session path: {}\n'.format(session)) for text in texts: text_input = dialogflow.types.TextInput( text=text, language_code=language_code) query_input = dialogflow.types.QueryInput(text=text_input) response = session_client.detect_intent( session=session, query_input=query_input) print('=' * 20) print('Query text: {}'.format(response.query_result.query_text)) print('Detected intent: {} (confidence: {})\n'.format( response.query_result.intent.display_name, response.query_result.intent_detection_confidence)) print('Fulfillment text: {}\n'.format( response.query_result.fulfillment_text))
[ "def", "detect_intent_texts", "(", "project_id", ",", "session_id", ",", "texts", ",", "language_code", ")", ":", "import", "dialogflow_v2", "as", "dialogflow", "session_client", "=", "dialogflow", ".", "SessionsClient", "(", ")", "session", "=", "session_client", ...
Returns the result of detect intent with texts as inputs. Using the same `session_id` between requests allows continuation of the conversation.
[ "Returns", "the", "result", "of", "detect", "intent", "with", "texts", "as", "inputs", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/detect_intent_texts.py#L34-L61
238,386
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/entity_types_client.py
EntityTypesClient.entity_type_path
def entity_type_path(cls, project, entity_type): """Return a fully-qualified entity_type string.""" return google.api_core.path_template.expand( 'projects/{project}/agent/entityTypes/{entity_type}', project=project, entity_type=entity_type, )
python
def entity_type_path(cls, project, entity_type): return google.api_core.path_template.expand( 'projects/{project}/agent/entityTypes/{entity_type}', project=project, entity_type=entity_type, )
[ "def", "entity_type_path", "(", "cls", ",", "project", ",", "entity_type", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "'projects/{project}/agent/entityTypes/{entity_type}'", ",", "project", "=", "project", ",", "entity_t...
Return a fully-qualified entity_type string.
[ "Return", "a", "fully", "-", "qualified", "entity_type", "string", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/entity_types_client.py#L118-L124
238,387
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/entity_types_client.py
EntityTypesClient.get_entity_type
def get_entity_type(self, name, language_code=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Retrieves the specified entity type. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.EntityTypesClient() >>> >>> name = client.entity_type_path('[PROJECT]', '[ENTITY_TYPE]') >>> >>> response = client.get_entity_type(name) Args: name (str): Required. The name of the entity type. Format: ``projects/<Project ID>/agent/entityTypes/<EntityType ID>``. language_code (str): Optional. The language to retrieve entity synonyms for. If not specified, the agent's default language is used. [More than a dozen languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must be enabled in the agent, before they can be used. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.EntityType` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'get_entity_type' not in self._inner_api_calls: self._inner_api_calls[ 'get_entity_type'] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_entity_type, default_retry=self._method_configs['GetEntityType'].retry, default_timeout=self._method_configs['GetEntityType'] .timeout, client_info=self._client_info, ) request = entity_type_pb2.GetEntityTypeRequest( name=name, language_code=language_code, ) return self._inner_api_calls['get_entity_type']( request, retry=retry, timeout=timeout, metadata=metadata)
python
def get_entity_type(self, name, language_code=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): # Wrap the transport method to add retry and timeout logic. if 'get_entity_type' not in self._inner_api_calls: self._inner_api_calls[ 'get_entity_type'] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_entity_type, default_retry=self._method_configs['GetEntityType'].retry, default_timeout=self._method_configs['GetEntityType'] .timeout, client_info=self._client_info, ) request = entity_type_pb2.GetEntityTypeRequest( name=name, language_code=language_code, ) return self._inner_api_calls['get_entity_type']( request, retry=retry, timeout=timeout, metadata=metadata)
[ "def", "get_entity_type", "(", "self", ",", "name", ",", "language_code", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "me...
Retrieves the specified entity type. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.EntityTypesClient() >>> >>> name = client.entity_type_path('[PROJECT]', '[ENTITY_TYPE]') >>> >>> response = client.get_entity_type(name) Args: name (str): Required. The name of the entity type. Format: ``projects/<Project ID>/agent/entityTypes/<EntityType ID>``. language_code (str): Optional. The language to retrieve entity synonyms for. If not specified, the agent's default language is used. [More than a dozen languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must be enabled in the agent, before they can be used. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.EntityType` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Retrieves", "the", "specified", "entity", "type", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/entity_types_client.py#L311-L372
238,388
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/entity_types_client.py
EntityTypesClient.create_entity_type
def create_entity_type(self, parent, entity_type, language_code=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Creates an entity type in the specified agent. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.EntityTypesClient() >>> >>> parent = client.project_agent_path('[PROJECT]') >>> >>> # TODO: Initialize ``entity_type``: >>> entity_type = {} >>> >>> response = client.create_entity_type(parent, entity_type) Args: parent (str): Required. The agent to create a entity type for. Format: ``projects/<Project ID>/agent``. entity_type (Union[dict, ~google.cloud.dialogflow_v2.types.EntityType]): Required. The entity type to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.EntityType` language_code (str): Optional. The language of entity synonyms defined in ``entity_type``. If not specified, the agent's default language is used. [More than a dozen languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must be enabled in the agent, before they can be used. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.EntityType` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'create_entity_type' not in self._inner_api_calls: self._inner_api_calls[ 'create_entity_type'] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_entity_type, default_retry=self._method_configs[ 'CreateEntityType'].retry, default_timeout=self._method_configs['CreateEntityType'] .timeout, client_info=self._client_info, ) request = entity_type_pb2.CreateEntityTypeRequest( parent=parent, entity_type=entity_type, language_code=language_code, ) return self._inner_api_calls['create_entity_type']( request, retry=retry, timeout=timeout, metadata=metadata)
python
def create_entity_type(self, parent, entity_type, language_code=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): # Wrap the transport method to add retry and timeout logic. if 'create_entity_type' not in self._inner_api_calls: self._inner_api_calls[ 'create_entity_type'] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_entity_type, default_retry=self._method_configs[ 'CreateEntityType'].retry, default_timeout=self._method_configs['CreateEntityType'] .timeout, client_info=self._client_info, ) request = entity_type_pb2.CreateEntityTypeRequest( parent=parent, entity_type=entity_type, language_code=language_code, ) return self._inner_api_calls['create_entity_type']( request, retry=retry, timeout=timeout, metadata=metadata)
[ "def", "create_entity_type", "(", "self", ",", "parent", ",", "entity_type", ",", "language_code", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", "....
Creates an entity type in the specified agent. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.EntityTypesClient() >>> >>> parent = client.project_agent_path('[PROJECT]') >>> >>> # TODO: Initialize ``entity_type``: >>> entity_type = {} >>> >>> response = client.create_entity_type(parent, entity_type) Args: parent (str): Required. The agent to create a entity type for. Format: ``projects/<Project ID>/agent``. entity_type (Union[dict, ~google.cloud.dialogflow_v2.types.EntityType]): Required. The entity type to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.EntityType` language_code (str): Optional. The language of entity synonyms defined in ``entity_type``. If not specified, the agent's default language is used. [More than a dozen languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must be enabled in the agent, before they can be used. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.EntityType` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Creates", "an", "entity", "type", "in", "the", "specified", "agent", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/entity_types_client.py#L374-L444
238,389
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/entity_types_client.py
EntityTypesClient.update_entity_type
def update_entity_type(self, entity_type, language_code=None, update_mask=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Updates the specified entity type. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.EntityTypesClient() >>> >>> # TODO: Initialize ``entity_type``: >>> entity_type = {} >>> >>> response = client.update_entity_type(entity_type) Args: entity_type (Union[dict, ~google.cloud.dialogflow_v2.types.EntityType]): Required. The entity type to update. Format: ``projects/<Project ID>/agent/entityTypes/<EntityType ID>``. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.EntityType` language_code (str): Optional. The language of entity synonyms defined in ``entity_type``. If not specified, the agent's default language is used. [More than a dozen languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must be enabled in the agent, before they can be used. update_mask (Union[dict, ~google.cloud.dialogflow_v2.types.FieldMask]): Optional. The mask to control which fields get updated. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.FieldMask` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.EntityType` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'update_entity_type' not in self._inner_api_calls: self._inner_api_calls[ 'update_entity_type'] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_entity_type, default_retry=self._method_configs[ 'UpdateEntityType'].retry, default_timeout=self._method_configs['UpdateEntityType'] .timeout, client_info=self._client_info, ) request = entity_type_pb2.UpdateEntityTypeRequest( entity_type=entity_type, language_code=language_code, update_mask=update_mask, ) return self._inner_api_calls['update_entity_type']( request, retry=retry, timeout=timeout, metadata=metadata)
python
def update_entity_type(self, entity_type, language_code=None, update_mask=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): # Wrap the transport method to add retry and timeout logic. if 'update_entity_type' not in self._inner_api_calls: self._inner_api_calls[ 'update_entity_type'] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_entity_type, default_retry=self._method_configs[ 'UpdateEntityType'].retry, default_timeout=self._method_configs['UpdateEntityType'] .timeout, client_info=self._client_info, ) request = entity_type_pb2.UpdateEntityTypeRequest( entity_type=entity_type, language_code=language_code, update_mask=update_mask, ) return self._inner_api_calls['update_entity_type']( request, retry=retry, timeout=timeout, metadata=metadata)
[ "def", "update_entity_type", "(", "self", ",", "entity_type", ",", "language_code", "=", "None", ",", "update_mask", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", "...
Updates the specified entity type. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.EntityTypesClient() >>> >>> # TODO: Initialize ``entity_type``: >>> entity_type = {} >>> >>> response = client.update_entity_type(entity_type) Args: entity_type (Union[dict, ~google.cloud.dialogflow_v2.types.EntityType]): Required. The entity type to update. Format: ``projects/<Project ID>/agent/entityTypes/<EntityType ID>``. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.EntityType` language_code (str): Optional. The language of entity synonyms defined in ``entity_type``. If not specified, the agent's default language is used. [More than a dozen languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must be enabled in the agent, before they can be used. update_mask (Union[dict, ~google.cloud.dialogflow_v2.types.FieldMask]): Optional. The mask to control which fields get updated. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.FieldMask` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.EntityType` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Updates", "the", "specified", "entity", "type", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/entity_types_client.py#L446-L516
238,390
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/entity_types_client.py
EntityTypesClient.batch_delete_entities
def batch_delete_entities(self, parent, entity_values, language_code=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Deletes entities in the specified entity type. Operation <response: ``google.protobuf.Empty``, metadata: [google.protobuf.Struct][google.protobuf.Struct]> Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.EntityTypesClient() >>> >>> parent = client.entity_type_path('[PROJECT]', '[ENTITY_TYPE]') >>> >>> # TODO: Initialize ``entity_values``: >>> entity_values = [] >>> >>> response = client.batch_delete_entities(parent, entity_values) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. The name of the entity type to delete entries for. Format: ``projects/<Project ID>/agent/entityTypes/<Entity Type ID>``. entity_values (list[str]): Required. The canonical ``values`` of the entities to delete. Note that these are not fully-qualified names, i.e. they don't start with ``projects/<Project ID>``. language_code (str): Optional. The language of entity synonyms defined in ``entities``. If not specified, the agent's default language is used. [More than a dozen languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must be enabled in the agent, before they can be used. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'batch_delete_entities' not in self._inner_api_calls: self._inner_api_calls[ 'batch_delete_entities'] = google.api_core.gapic_v1.method.wrap_method( self.transport.batch_delete_entities, default_retry=self._method_configs[ 'BatchDeleteEntities'].retry, default_timeout=self._method_configs['BatchDeleteEntities'] .timeout, client_info=self._client_info, ) request = entity_type_pb2.BatchDeleteEntitiesRequest( parent=parent, entity_values=entity_values, language_code=language_code, ) operation = self._inner_api_calls['batch_delete_entities']( request, retry=retry, timeout=timeout, metadata=metadata) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, empty_pb2.Empty, metadata_type=struct_pb2.Struct, )
python
def batch_delete_entities(self, parent, entity_values, language_code=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): # Wrap the transport method to add retry and timeout logic. if 'batch_delete_entities' not in self._inner_api_calls: self._inner_api_calls[ 'batch_delete_entities'] = google.api_core.gapic_v1.method.wrap_method( self.transport.batch_delete_entities, default_retry=self._method_configs[ 'BatchDeleteEntities'].retry, default_timeout=self._method_configs['BatchDeleteEntities'] .timeout, client_info=self._client_info, ) request = entity_type_pb2.BatchDeleteEntitiesRequest( parent=parent, entity_values=entity_values, language_code=language_code, ) operation = self._inner_api_calls['batch_delete_entities']( request, retry=retry, timeout=timeout, metadata=metadata) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, empty_pb2.Empty, metadata_type=struct_pb2.Struct, )
[ "def", "batch_delete_entities", "(", "self", ",", "parent", ",", "entity_values", ",", "language_code", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core",...
Deletes entities in the specified entity type. Operation <response: ``google.protobuf.Empty``, metadata: [google.protobuf.Struct][google.protobuf.Struct]> Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.EntityTypesClient() >>> >>> parent = client.entity_type_path('[PROJECT]', '[ENTITY_TYPE]') >>> >>> # TODO: Initialize ``entity_values``: >>> entity_values = [] >>> >>> response = client.batch_delete_entities(parent, entity_values) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. The name of the entity type to delete entries for. Format: ``projects/<Project ID>/agent/entityTypes/<Entity Type ID>``. entity_values (list[str]): Required. The canonical ``values`` of the entities to delete. Note that these are not fully-qualified names, i.e. they don't start with ``projects/<Project ID>``. language_code (str): Optional. The language of entity synonyms defined in ``entities``. If not specified, the agent's default language is used. [More than a dozen languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must be enabled in the agent, before they can be used. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Deletes", "entities", "in", "the", "specified", "entity", "type", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/entity_types_client.py#L945-L1033
238,391
googleapis/dialogflow-python-client-v2
samples/detect_intent_knowledge.py
detect_intent_knowledge
def detect_intent_knowledge(project_id, session_id, language_code, knowledge_base_id, texts): """Returns the result of detect intent with querying Knowledge Connector. Args: project_id: The GCP project linked with the agent you are going to query. session_id: Id of the session, using the same `session_id` between requests allows continuation of the conversation. language_code: Language of the queries. knowledge_base_id: The Knowledge base's id to query against. texts: A list of text queries to send. """ import dialogflow_v2beta1 as dialogflow session_client = dialogflow.SessionsClient() session_path = session_client.session_path(project_id, session_id) print('Session path: {}\n'.format(session_path)) for text in texts: text_input = dialogflow.types.TextInput( text=text, language_code=language_code) query_input = dialogflow.types.QueryInput(text=text_input) knowledge_base_path = dialogflow.knowledge_bases_client \ .KnowledgeBasesClient \ .knowledge_base_path(project_id, knowledge_base_id) query_params = dialogflow.types.QueryParameters( knowledge_base_names=[knowledge_base_path]) response = session_client.detect_intent( session=session_path, query_input=query_input, query_params=query_params) print('=' * 20) print('Query text: {}'.format(response.query_result.query_text)) print('Detected intent: {} (confidence: {})\n'.format( response.query_result.intent.display_name, response.query_result.intent_detection_confidence)) print('Fulfillment text: {}\n'.format( response.query_result.fulfillment_text)) print('Knowledge results:') knowledge_answers = response.query_result.knowledge_answers for answers in knowledge_answers.answers: print(' - Answer: {}'.format(answers.answer)) print(' - Confidence: {}'.format( answers.match_confidence))
python
def detect_intent_knowledge(project_id, session_id, language_code, knowledge_base_id, texts): import dialogflow_v2beta1 as dialogflow session_client = dialogflow.SessionsClient() session_path = session_client.session_path(project_id, session_id) print('Session path: {}\n'.format(session_path)) for text in texts: text_input = dialogflow.types.TextInput( text=text, language_code=language_code) query_input = dialogflow.types.QueryInput(text=text_input) knowledge_base_path = dialogflow.knowledge_bases_client \ .KnowledgeBasesClient \ .knowledge_base_path(project_id, knowledge_base_id) query_params = dialogflow.types.QueryParameters( knowledge_base_names=[knowledge_base_path]) response = session_client.detect_intent( session=session_path, query_input=query_input, query_params=query_params) print('=' * 20) print('Query text: {}'.format(response.query_result.query_text)) print('Detected intent: {} (confidence: {})\n'.format( response.query_result.intent.display_name, response.query_result.intent_detection_confidence)) print('Fulfillment text: {}\n'.format( response.query_result.fulfillment_text)) print('Knowledge results:') knowledge_answers = response.query_result.knowledge_answers for answers in knowledge_answers.answers: print(' - Answer: {}'.format(answers.answer)) print(' - Confidence: {}'.format( answers.match_confidence))
[ "def", "detect_intent_knowledge", "(", "project_id", ",", "session_id", ",", "language_code", ",", "knowledge_base_id", ",", "texts", ")", ":", "import", "dialogflow_v2beta1", "as", "dialogflow", "session_client", "=", "dialogflow", ".", "SessionsClient", "(", ")", ...
Returns the result of detect intent with querying Knowledge Connector. Args: project_id: The GCP project linked with the agent you are going to query. session_id: Id of the session, using the same `session_id` between requests allows continuation of the conversation. language_code: Language of the queries. knowledge_base_id: The Knowledge base's id to query against. texts: A list of text queries to send.
[ "Returns", "the", "result", "of", "detect", "intent", "with", "querying", "Knowledge", "Connector", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/detect_intent_knowledge.py#L31-L78
238,392
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/intents_client.py
IntentsClient.intent_path
def intent_path(cls, project, intent): """Return a fully-qualified intent string.""" return google.api_core.path_template.expand( 'projects/{project}/agent/intents/{intent}', project=project, intent=intent, )
python
def intent_path(cls, project, intent): return google.api_core.path_template.expand( 'projects/{project}/agent/intents/{intent}', project=project, intent=intent, )
[ "def", "intent_path", "(", "cls", ",", "project", ",", "intent", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "'projects/{project}/agent/intents/{intent}'", ",", "project", "=", "project", ",", "intent", "=", "intent",...
Return a fully-qualified intent string.
[ "Return", "a", "fully", "-", "qualified", "intent", "string", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/intents_client.py#L125-L131
238,393
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/intents_client.py
IntentsClient.agent_path
def agent_path(cls, project, agent): """Return a fully-qualified agent string.""" return google.api_core.path_template.expand( 'projects/{project}/agents/{agent}', project=project, agent=agent, )
python
def agent_path(cls, project, agent): return google.api_core.path_template.expand( 'projects/{project}/agents/{agent}', project=project, agent=agent, )
[ "def", "agent_path", "(", "cls", ",", "project", ",", "agent", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "'projects/{project}/agents/{agent}'", ",", "project", "=", "project", ",", "agent", "=", "agent", ",", ")...
Return a fully-qualified agent string.
[ "Return", "a", "fully", "-", "qualified", "agent", "string", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/intents_client.py#L134-L140
238,394
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/intents_client.py
IntentsClient.get_intent
def get_intent(self, name, language_code=None, intent_view=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Retrieves the specified intent. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.IntentsClient() >>> >>> name = client.intent_path('[PROJECT]', '[INTENT]') >>> >>> response = client.get_intent(name) Args: name (str): Required. The name of the intent. Format: ``projects/<Project ID>/agent/intents/<Intent ID>``. language_code (str): Optional. The language to retrieve training phrases, parameters and rich messages for. If not specified, the agent's default language is used. [More than a dozen languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must be enabled in the agent, before they can be used. intent_view (~google.cloud.dialogflow_v2.types.IntentView): Optional. The resource view to apply to the returned intent. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.Intent` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'get_intent' not in self._inner_api_calls: self._inner_api_calls[ 'get_intent'] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_intent, default_retry=self._method_configs['GetIntent'].retry, default_timeout=self._method_configs['GetIntent'].timeout, client_info=self._client_info, ) request = intent_pb2.GetIntentRequest( name=name, language_code=language_code, intent_view=intent_view, ) return self._inner_api_calls['get_intent']( request, retry=retry, timeout=timeout, metadata=metadata)
python
def get_intent(self, name, language_code=None, intent_view=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): # Wrap the transport method to add retry and timeout logic. if 'get_intent' not in self._inner_api_calls: self._inner_api_calls[ 'get_intent'] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_intent, default_retry=self._method_configs['GetIntent'].retry, default_timeout=self._method_configs['GetIntent'].timeout, client_info=self._client_info, ) request = intent_pb2.GetIntentRequest( name=name, language_code=language_code, intent_view=intent_view, ) return self._inner_api_calls['get_intent']( request, retry=retry, timeout=timeout, metadata=metadata)
[ "def", "get_intent", "(", "self", ",", "name", ",", "language_code", "=", "None", ",", "intent_view", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core...
Retrieves the specified intent. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.IntentsClient() >>> >>> name = client.intent_path('[PROJECT]', '[INTENT]') >>> >>> response = client.get_intent(name) Args: name (str): Required. The name of the intent. Format: ``projects/<Project ID>/agent/intents/<Intent ID>``. language_code (str): Optional. The language to retrieve training phrases, parameters and rich messages for. If not specified, the agent's default language is used. [More than a dozen languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must be enabled in the agent, before they can be used. intent_view (~google.cloud.dialogflow_v2.types.IntentView): Optional. The resource view to apply to the returned intent. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.Intent` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Retrieves", "the", "specified", "intent", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/intents_client.py#L328-L391
238,395
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/intents_client.py
IntentsClient.create_intent
def create_intent(self, parent, intent, language_code=None, intent_view=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Creates an intent in the specified agent. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.IntentsClient() >>> >>> parent = client.project_agent_path('[PROJECT]') >>> >>> # TODO: Initialize ``intent``: >>> intent = {} >>> >>> response = client.create_intent(parent, intent) Args: parent (str): Required. The agent to create a intent for. Format: ``projects/<Project ID>/agent``. intent (Union[dict, ~google.cloud.dialogflow_v2.types.Intent]): Required. The intent to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.Intent` language_code (str): Optional. The language of training phrases, parameters and rich messages defined in ``intent``. If not specified, the agent's default language is used. [More than a dozen languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must be enabled in the agent, before they can be used. intent_view (~google.cloud.dialogflow_v2.types.IntentView): Optional. The resource view to apply to the returned intent. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.Intent` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'create_intent' not in self._inner_api_calls: self._inner_api_calls[ 'create_intent'] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_intent, default_retry=self._method_configs['CreateIntent'].retry, default_timeout=self._method_configs['CreateIntent'] .timeout, client_info=self._client_info, ) request = intent_pb2.CreateIntentRequest( parent=parent, intent=intent, language_code=language_code, intent_view=intent_view, ) return self._inner_api_calls['create_intent']( request, retry=retry, timeout=timeout, metadata=metadata)
python
def create_intent(self, parent, intent, language_code=None, intent_view=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): # Wrap the transport method to add retry and timeout logic. if 'create_intent' not in self._inner_api_calls: self._inner_api_calls[ 'create_intent'] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_intent, default_retry=self._method_configs['CreateIntent'].retry, default_timeout=self._method_configs['CreateIntent'] .timeout, client_info=self._client_info, ) request = intent_pb2.CreateIntentRequest( parent=parent, intent=intent, language_code=language_code, intent_view=intent_view, ) return self._inner_api_calls['create_intent']( request, retry=retry, timeout=timeout, metadata=metadata)
[ "def", "create_intent", "(", "self", ",", "parent", ",", "intent", ",", "language_code", "=", "None", ",", "intent_view", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "goo...
Creates an intent in the specified agent. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.IntentsClient() >>> >>> parent = client.project_agent_path('[PROJECT]') >>> >>> # TODO: Initialize ``intent``: >>> intent = {} >>> >>> response = client.create_intent(parent, intent) Args: parent (str): Required. The agent to create a intent for. Format: ``projects/<Project ID>/agent``. intent (Union[dict, ~google.cloud.dialogflow_v2.types.Intent]): Required. The intent to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.Intent` language_code (str): Optional. The language of training phrases, parameters and rich messages defined in ``intent``. If not specified, the agent's default language is used. [More than a dozen languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must be enabled in the agent, before they can be used. intent_view (~google.cloud.dialogflow_v2.types.IntentView): Optional. The resource view to apply to the returned intent. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.Intent` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Creates", "an", "intent", "in", "the", "specified", "agent", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/intents_client.py#L393-L465
238,396
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/intents_client.py
IntentsClient.update_intent
def update_intent(self, intent, language_code, update_mask=None, intent_view=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Updates the specified intent. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.IntentsClient() >>> >>> # TODO: Initialize ``intent``: >>> intent = {} >>> >>> # TODO: Initialize ``language_code``: >>> language_code = '' >>> >>> response = client.update_intent(intent, language_code) Args: intent (Union[dict, ~google.cloud.dialogflow_v2.types.Intent]): Required. The intent to update. Format: ``projects/<Project ID>/agent/intents/<Intent ID>``. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.Intent` language_code (str): Optional. The language of training phrases, parameters and rich messages defined in ``intent``. If not specified, the agent's default language is used. [More than a dozen languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must be enabled in the agent, before they can be used. update_mask (Union[dict, ~google.cloud.dialogflow_v2.types.FieldMask]): Optional. The mask to control which fields get updated. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.FieldMask` intent_view (~google.cloud.dialogflow_v2.types.IntentView): Optional. The resource view to apply to the returned intent. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.Intent` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'update_intent' not in self._inner_api_calls: self._inner_api_calls[ 'update_intent'] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_intent, default_retry=self._method_configs['UpdateIntent'].retry, default_timeout=self._method_configs['UpdateIntent'] .timeout, client_info=self._client_info, ) request = intent_pb2.UpdateIntentRequest( intent=intent, language_code=language_code, update_mask=update_mask, intent_view=intent_view, ) return self._inner_api_calls['update_intent']( request, retry=retry, timeout=timeout, metadata=metadata)
python
def update_intent(self, intent, language_code, update_mask=None, intent_view=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): # Wrap the transport method to add retry and timeout logic. if 'update_intent' not in self._inner_api_calls: self._inner_api_calls[ 'update_intent'] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_intent, default_retry=self._method_configs['UpdateIntent'].retry, default_timeout=self._method_configs['UpdateIntent'] .timeout, client_info=self._client_info, ) request = intent_pb2.UpdateIntentRequest( intent=intent, language_code=language_code, update_mask=update_mask, intent_view=intent_view, ) return self._inner_api_calls['update_intent']( request, retry=retry, timeout=timeout, metadata=metadata)
[ "def", "update_intent", "(", "self", ",", "intent", ",", "language_code", ",", "update_mask", "=", "None", ",", "intent_view", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", ...
Updates the specified intent. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.IntentsClient() >>> >>> # TODO: Initialize ``intent``: >>> intent = {} >>> >>> # TODO: Initialize ``language_code``: >>> language_code = '' >>> >>> response = client.update_intent(intent, language_code) Args: intent (Union[dict, ~google.cloud.dialogflow_v2.types.Intent]): Required. The intent to update. Format: ``projects/<Project ID>/agent/intents/<Intent ID>``. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.Intent` language_code (str): Optional. The language of training phrases, parameters and rich messages defined in ``intent``. If not specified, the agent's default language is used. [More than a dozen languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must be enabled in the agent, before they can be used. update_mask (Union[dict, ~google.cloud.dialogflow_v2.types.FieldMask]): Optional. The mask to control which fields get updated. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.FieldMask` intent_view (~google.cloud.dialogflow_v2.types.IntentView): Optional. The resource view to apply to the returned intent. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types.Intent` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Updates", "the", "specified", "intent", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/intents_client.py#L467-L542
238,397
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/intents_client.py
IntentsClient.delete_intent
def delete_intent(self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Deletes the specified intent. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.IntentsClient() >>> >>> name = client.intent_path('[PROJECT]', '[INTENT]') >>> >>> client.delete_intent(name) Args: name (str): Required. The name of the intent to delete. Format: ``projects/<Project ID>/agent/intents/<Intent ID>``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'delete_intent' not in self._inner_api_calls: self._inner_api_calls[ 'delete_intent'] = google.api_core.gapic_v1.method.wrap_method( self.transport.delete_intent, default_retry=self._method_configs['DeleteIntent'].retry, default_timeout=self._method_configs['DeleteIntent'] .timeout, client_info=self._client_info, ) request = intent_pb2.DeleteIntentRequest(name=name, ) self._inner_api_calls['delete_intent']( request, retry=retry, timeout=timeout, metadata=metadata)
python
def delete_intent(self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): # Wrap the transport method to add retry and timeout logic. if 'delete_intent' not in self._inner_api_calls: self._inner_api_calls[ 'delete_intent'] = google.api_core.gapic_v1.method.wrap_method( self.transport.delete_intent, default_retry=self._method_configs['DeleteIntent'].retry, default_timeout=self._method_configs['DeleteIntent'] .timeout, client_info=self._client_info, ) request = intent_pb2.DeleteIntentRequest(name=name, ) self._inner_api_calls['delete_intent']( request, retry=retry, timeout=timeout, metadata=metadata)
[ "def", "delete_intent", "(", "self", ",", "name", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "metadata...
Deletes the specified intent. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.IntentsClient() >>> >>> name = client.intent_path('[PROJECT]', '[INTENT]') >>> >>> client.delete_intent(name) Args: name (str): Required. The name of the intent to delete. Format: ``projects/<Project ID>/agent/intents/<Intent ID>``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Deletes", "the", "specified", "intent", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/intents_client.py#L544-L593
238,398
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/intents_client.py
IntentsClient.batch_delete_intents
def batch_delete_intents(self, parent, intents, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Deletes intents in the specified agent. Operation <response: ``google.protobuf.Empty``> Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.IntentsClient() >>> >>> parent = client.project_agent_path('[PROJECT]') >>> >>> # TODO: Initialize ``intents``: >>> intents = [] >>> >>> response = client.batch_delete_intents(parent, intents) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. The name of the agent to delete all entities types for. Format: ``projects/<Project ID>/agent``. intents (list[Union[dict, ~google.cloud.dialogflow_v2.types.Intent]]): Required. The collection of intents to delete. Only intent ``name`` must be filled in. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.Intent` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'batch_delete_intents' not in self._inner_api_calls: self._inner_api_calls[ 'batch_delete_intents'] = google.api_core.gapic_v1.method.wrap_method( self.transport.batch_delete_intents, default_retry=self._method_configs[ 'BatchDeleteIntents'].retry, default_timeout=self._method_configs['BatchDeleteIntents'] .timeout, client_info=self._client_info, ) request = intent_pb2.BatchDeleteIntentsRequest( parent=parent, intents=intents, ) operation = self._inner_api_calls['batch_delete_intents']( request, retry=retry, timeout=timeout, metadata=metadata) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, empty_pb2.Empty, metadata_type=struct_pb2.Struct, )
python
def batch_delete_intents(self, parent, intents, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): # Wrap the transport method to add retry and timeout logic. if 'batch_delete_intents' not in self._inner_api_calls: self._inner_api_calls[ 'batch_delete_intents'] = google.api_core.gapic_v1.method.wrap_method( self.transport.batch_delete_intents, default_retry=self._method_configs[ 'BatchDeleteIntents'].retry, default_timeout=self._method_configs['BatchDeleteIntents'] .timeout, client_info=self._client_info, ) request = intent_pb2.BatchDeleteIntentsRequest( parent=parent, intents=intents, ) operation = self._inner_api_calls['batch_delete_intents']( request, retry=retry, timeout=timeout, metadata=metadata) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, empty_pb2.Empty, metadata_type=struct_pb2.Struct, )
[ "def", "batch_delete_intents", "(", "self", ",", "parent", ",", "intents", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", ...
Deletes intents in the specified agent. Operation <response: ``google.protobuf.Empty``> Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.IntentsClient() >>> >>> parent = client.project_agent_path('[PROJECT]') >>> >>> # TODO: Initialize ``intents``: >>> intents = [] >>> >>> response = client.batch_delete_intents(parent, intents) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. The name of the agent to delete all entities types for. Format: ``projects/<Project ID>/agent``. intents (list[Union[dict, ~google.cloud.dialogflow_v2.types.Intent]]): Required. The collection of intents to delete. Only intent ``name`` must be filled in. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dialogflow_v2.types.Intent` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dialogflow_v2.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Deletes", "intents", "in", "the", "specified", "agent", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/intents_client.py#L704-L785
238,399
googleapis/dialogflow-python-client-v2
dialogflow_v2beta1/gapic/contexts_client.py
ContextsClient.environment_context_path
def environment_context_path(cls, project, environment, user, session, context): """Return a fully-qualified environment_context string.""" return google.api_core.path_template.expand( 'projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}/contexts/{context}', project=project, environment=environment, user=user, session=session, context=context, )
python
def environment_context_path(cls, project, environment, user, session, context): return google.api_core.path_template.expand( 'projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}/contexts/{context}', project=project, environment=environment, user=user, session=session, context=context, )
[ "def", "environment_context_path", "(", "cls", ",", "project", ",", "environment", ",", "user", ",", "session", ",", "context", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "'projects/{project}/agent/environments/{environm...
Return a fully-qualified environment_context string.
[ "Return", "a", "fully", "-", "qualified", "environment_context", "string", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2beta1/gapic/contexts_client.py#L125-L135