repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
jelmer/python-fastimport
fastimport/parser.py
ImportParser.iter_commands
def iter_commands(self): """Iterator returning ImportCommand objects.""" while True: line = self.next_line() if line is None: if b'done' in self.features: raise errors.PrematureEndOfStream(self.lineno) break elif len...
python
def iter_commands(self): """Iterator returning ImportCommand objects.""" while True: line = self.next_line() if line is None: if b'done' in self.features: raise errors.PrematureEndOfStream(self.lineno) break elif len...
[ "def", "iter_commands", "(", "self", ")", ":", "while", "True", ":", "line", "=", "self", ".", "next_line", "(", ")", "if", "line", "is", "None", ":", "if", "b'done'", "in", "self", ".", "features", ":", "raise", "errors", ".", "PrematureEndOfStream", ...
Iterator returning ImportCommand objects.
[ "Iterator", "returning", "ImportCommand", "objects", "." ]
train
https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/parser.py#L290-L318
jelmer/python-fastimport
fastimport/parser.py
ImportParser.iter_file_commands
def iter_file_commands(self): """Iterator returning FileCommand objects. If an invalid file command is found, the line is silently pushed back and iteration ends. """ while True: line = self.next_line() if line is None: break e...
python
def iter_file_commands(self): """Iterator returning FileCommand objects. If an invalid file command is found, the line is silently pushed back and iteration ends. """ while True: line = self.next_line() if line is None: break e...
[ "def", "iter_file_commands", "(", "self", ")", ":", "while", "True", ":", "line", "=", "self", ".", "next_line", "(", ")", "if", "line", "is", "None", ":", "break", "elif", "len", "(", "line", ")", "==", "0", "or", "line", ".", "startswith", "(", "...
Iterator returning FileCommand objects. If an invalid file command is found, the line is silently pushed back and iteration ends.
[ "Iterator", "returning", "FileCommand", "objects", "." ]
train
https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/parser.py#L320-L348
jelmer/python-fastimport
fastimport/parser.py
ImportParser._parse_blob
def _parse_blob(self): """Parse a blob command.""" lineno = self.lineno mark = self._get_mark_if_any() data = self._get_data(b'blob') return commands.BlobCommand(mark, data, lineno)
python
def _parse_blob(self): """Parse a blob command.""" lineno = self.lineno mark = self._get_mark_if_any() data = self._get_data(b'blob') return commands.BlobCommand(mark, data, lineno)
[ "def", "_parse_blob", "(", "self", ")", ":", "lineno", "=", "self", ".", "lineno", "mark", "=", "self", ".", "_get_mark_if_any", "(", ")", "data", "=", "self", ".", "_get_data", "(", "b'blob'", ")", "return", "commands", ".", "BlobCommand", "(", "mark", ...
Parse a blob command.
[ "Parse", "a", "blob", "command", "." ]
train
https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/parser.py#L350-L355
jelmer/python-fastimport
fastimport/parser.py
ImportParser._parse_commit
def _parse_commit(self, ref): """Parse a commit command.""" lineno = self.lineno mark = self._get_mark_if_any() author = self._get_user_info(b'commit', b'author', False) more_authors = [] while True: another_author = self._get_user_info(b'commit', b'author', ...
python
def _parse_commit(self, ref): """Parse a commit command.""" lineno = self.lineno mark = self._get_mark_if_any() author = self._get_user_info(b'commit', b'author', False) more_authors = [] while True: another_author = self._get_user_info(b'commit', b'author', ...
[ "def", "_parse_commit", "(", "self", ",", "ref", ")", ":", "lineno", "=", "self", ".", "lineno", "mark", "=", "self", ".", "_get_mark_if_any", "(", ")", "author", "=", "self", ".", "_get_user_info", "(", "b'commit'", ",", "b'author'", ",", "False", ")", ...
Parse a commit command.
[ "Parse", "a", "commit", "command", "." ]
train
https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/parser.py#L357-L393
jelmer/python-fastimport
fastimport/parser.py
ImportParser._parse_feature
def _parse_feature(self, info): """Parse a feature command.""" parts = info.split(b'=', 1) name = parts[0] if len(parts) > 1: value = self._path(parts[1]) else: value = None self.features[name] = value return commands.FeatureCommand(name, v...
python
def _parse_feature(self, info): """Parse a feature command.""" parts = info.split(b'=', 1) name = parts[0] if len(parts) > 1: value = self._path(parts[1]) else: value = None self.features[name] = value return commands.FeatureCommand(name, v...
[ "def", "_parse_feature", "(", "self", ",", "info", ")", ":", "parts", "=", "info", ".", "split", "(", "b'='", ",", "1", ")", "name", "=", "parts", "[", "0", "]", "if", "len", "(", "parts", ")", ">", "1", ":", "value", "=", "self", ".", "_path",...
Parse a feature command.
[ "Parse", "a", "feature", "command", "." ]
train
https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/parser.py#L395-L404
jelmer/python-fastimport
fastimport/parser.py
ImportParser._parse_file_modify
def _parse_file_modify(self, info): """Parse a filemodify command within a commit. :param info: a string in the format "mode dataref path" (where dataref might be the hard-coded literal 'inline'). """ params = info.split(b' ', 2) path = self._path(params[2]) mo...
python
def _parse_file_modify(self, info): """Parse a filemodify command within a commit. :param info: a string in the format "mode dataref path" (where dataref might be the hard-coded literal 'inline'). """ params = info.split(b' ', 2) path = self._path(params[2]) mo...
[ "def", "_parse_file_modify", "(", "self", ",", "info", ")", ":", "params", "=", "info", ".", "split", "(", "b' '", ",", "2", ")", "path", "=", "self", ".", "_path", "(", "params", "[", "2", "]", ")", "mode", "=", "self", ".", "_mode", "(", "param...
Parse a filemodify command within a commit. :param info: a string in the format "mode dataref path" (where dataref might be the hard-coded literal 'inline').
[ "Parse", "a", "filemodify", "command", "within", "a", "commit", "." ]
train
https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/parser.py#L406-L422
jelmer/python-fastimport
fastimport/parser.py
ImportParser._parse_reset
def _parse_reset(self, ref): """Parse a reset command.""" from_ = self._get_from() return commands.ResetCommand(ref, from_)
python
def _parse_reset(self, ref): """Parse a reset command.""" from_ = self._get_from() return commands.ResetCommand(ref, from_)
[ "def", "_parse_reset", "(", "self", ",", "ref", ")", ":", "from_", "=", "self", ".", "_get_from", "(", ")", "return", "commands", ".", "ResetCommand", "(", "ref", ",", "from_", ")" ]
Parse a reset command.
[ "Parse", "a", "reset", "command", "." ]
train
https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/parser.py#L424-L427
jelmer/python-fastimport
fastimport/parser.py
ImportParser._parse_tag
def _parse_tag(self, name): """Parse a tag command.""" from_ = self._get_from(b'tag') tagger = self._get_user_info(b'tag', b'tagger', accept_just_who=True) message = self._get_data(b'tag', b'message') return commands.TagCommand(name, from_, tagger, message)
python
def _parse_tag(self, name): """Parse a tag command.""" from_ = self._get_from(b'tag') tagger = self._get_user_info(b'tag', b'tagger', accept_just_who=True) message = self._get_data(b'tag', b'message') return commands.TagCommand(name, from_, tagger, message)
[ "def", "_parse_tag", "(", "self", ",", "name", ")", ":", "from_", "=", "self", ".", "_get_from", "(", "b'tag'", ")", "tagger", "=", "self", ".", "_get_user_info", "(", "b'tag'", ",", "b'tagger'", ",", "accept_just_who", "=", "True", ")", "message", "=", ...
Parse a tag command.
[ "Parse", "a", "tag", "command", "." ]
train
https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/parser.py#L429-L435
jelmer/python-fastimport
fastimport/parser.py
ImportParser._get_mark_if_any
def _get_mark_if_any(self): """Parse a mark section.""" line = self.next_line() if line.startswith(b'mark :'): return line[len(b'mark :'):] else: self.push_line(line) return None
python
def _get_mark_if_any(self): """Parse a mark section.""" line = self.next_line() if line.startswith(b'mark :'): return line[len(b'mark :'):] else: self.push_line(line) return None
[ "def", "_get_mark_if_any", "(", "self", ")", ":", "line", "=", "self", ".", "next_line", "(", ")", "if", "line", ".", "startswith", "(", "b'mark :'", ")", ":", "return", "line", "[", "len", "(", "b'mark :'", ")", ":", "]", "else", ":", "self", ".", ...
Parse a mark section.
[ "Parse", "a", "mark", "section", "." ]
train
https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/parser.py#L437-L444
jelmer/python-fastimport
fastimport/parser.py
ImportParser._get_from
def _get_from(self, required_for=None): """Parse a from section.""" line = self.next_line() if line is None: return None elif line.startswith(b'from '): return line[len(b'from '):] elif required_for: self.abort(errors.MissingSection, required_f...
python
def _get_from(self, required_for=None): """Parse a from section.""" line = self.next_line() if line is None: return None elif line.startswith(b'from '): return line[len(b'from '):] elif required_for: self.abort(errors.MissingSection, required_f...
[ "def", "_get_from", "(", "self", ",", "required_for", "=", "None", ")", ":", "line", "=", "self", ".", "next_line", "(", ")", "if", "line", "is", "None", ":", "return", "None", "elif", "line", ".", "startswith", "(", "b'from '", ")", ":", "return", "...
Parse a from section.
[ "Parse", "a", "from", "section", "." ]
train
https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/parser.py#L446-L457
jelmer/python-fastimport
fastimport/parser.py
ImportParser._get_merge
def _get_merge(self): """Parse a merge section.""" line = self.next_line() if line is None: return None elif line.startswith(b'merge '): return line[len(b'merge '):] else: self.push_line(line) return None
python
def _get_merge(self): """Parse a merge section.""" line = self.next_line() if line is None: return None elif line.startswith(b'merge '): return line[len(b'merge '):] else: self.push_line(line) return None
[ "def", "_get_merge", "(", "self", ")", ":", "line", "=", "self", ".", "next_line", "(", ")", "if", "line", "is", "None", ":", "return", "None", "elif", "line", ".", "startswith", "(", "b'merge '", ")", ":", "return", "line", "[", "len", "(", "b'merge...
Parse a merge section.
[ "Parse", "a", "merge", "section", "." ]
train
https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/parser.py#L459-L468
jelmer/python-fastimport
fastimport/parser.py
ImportParser._get_property
def _get_property(self): """Parse a property section.""" line = self.next_line() if line is None: return None elif line.startswith(b'property '): return self._name_value(line[len(b'property '):]) else: self.push_line(line) return No...
python
def _get_property(self): """Parse a property section.""" line = self.next_line() if line is None: return None elif line.startswith(b'property '): return self._name_value(line[len(b'property '):]) else: self.push_line(line) return No...
[ "def", "_get_property", "(", "self", ")", ":", "line", "=", "self", ".", "next_line", "(", ")", "if", "line", "is", "None", ":", "return", "None", "elif", "line", ".", "startswith", "(", "b'property '", ")", ":", "return", "self", ".", "_name_value", "...
Parse a property section.
[ "Parse", "a", "property", "section", "." ]
train
https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/parser.py#L470-L479
jelmer/python-fastimport
fastimport/parser.py
ImportParser._get_user_info
def _get_user_info(self, cmd, section, required=True, accept_just_who=False): """Parse a user section.""" line = self.next_line() if line.startswith(section + b' '): return self._who_when(line[len(section + b' '):], cmd, section, accept_just_who=accept_just_wh...
python
def _get_user_info(self, cmd, section, required=True, accept_just_who=False): """Parse a user section.""" line = self.next_line() if line.startswith(section + b' '): return self._who_when(line[len(section + b' '):], cmd, section, accept_just_who=accept_just_wh...
[ "def", "_get_user_info", "(", "self", ",", "cmd", ",", "section", ",", "required", "=", "True", ",", "accept_just_who", "=", "False", ")", ":", "line", "=", "self", ".", "next_line", "(", ")", "if", "line", ".", "startswith", "(", "section", "+", "b' '...
Parse a user section.
[ "Parse", "a", "user", "section", "." ]
train
https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/parser.py#L481-L492
jelmer/python-fastimport
fastimport/parser.py
ImportParser._get_data
def _get_data(self, required_for, section=b'data'): """Parse a data section.""" line = self.next_line() if line.startswith(b'data '): rest = line[len(b'data '):] if rest.startswith(b'<<'): return self.read_until(rest[2:]) else: ...
python
def _get_data(self, required_for, section=b'data'): """Parse a data section.""" line = self.next_line() if line.startswith(b'data '): rest = line[len(b'data '):] if rest.startswith(b'<<'): return self.read_until(rest[2:]) else: ...
[ "def", "_get_data", "(", "self", ",", "required_for", ",", "section", "=", "b'data'", ")", ":", "line", "=", "self", ".", "next_line", "(", ")", "if", "line", ".", "startswith", "(", "b'data '", ")", ":", "rest", "=", "line", "[", "len", "(", "b'data...
Parse a data section.
[ "Parse", "a", "data", "section", "." ]
train
https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/parser.py#L494-L511
jelmer/python-fastimport
fastimport/parser.py
ImportParser._who_when
def _who_when(self, s, cmd, section, accept_just_who=False): """Parse who and when information from a string. :return: a tuple of (name,email,timestamp,timezone). name may be the empty string if only an email address was given. """ match = _WHO_AND_WHEN_RE.search(s) ...
python
def _who_when(self, s, cmd, section, accept_just_who=False): """Parse who and when information from a string. :return: a tuple of (name,email,timestamp,timezone). name may be the empty string if only an email address was given. """ match = _WHO_AND_WHEN_RE.search(s) ...
[ "def", "_who_when", "(", "self", ",", "s", ",", "cmd", ",", "section", ",", "accept_just_who", "=", "False", ")", ":", "match", "=", "_WHO_AND_WHEN_RE", ".", "search", "(", "s", ")", "if", "match", ":", "datestr", "=", "match", ".", "group", "(", "3"...
Parse who and when information from a string. :return: a tuple of (name,email,timestamp,timezone). name may be the empty string if only an email address was given.
[ "Parse", "who", "and", "when", "information", "from", "a", "string", "." ]
train
https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/parser.py#L513-L561
jelmer/python-fastimport
fastimport/parser.py
ImportParser._name_value
def _name_value(self, s): """Parse a (name,value) tuple from 'name value-length value'.""" parts = s.split(b' ', 2) name = parts[0] if len(parts) == 1: value = None else: size = int(parts[1]) value = parts[2] still_to_read = size - ...
python
def _name_value(self, s): """Parse a (name,value) tuple from 'name value-length value'.""" parts = s.split(b' ', 2) name = parts[0] if len(parts) == 1: value = None else: size = int(parts[1]) value = parts[2] still_to_read = size - ...
[ "def", "_name_value", "(", "self", ",", "s", ")", ":", "parts", "=", "s", ".", "split", "(", "b' '", ",", "2", ")", "name", "=", "parts", "[", "0", "]", "if", "len", "(", "parts", ")", "==", "1", ":", "value", "=", "None", "else", ":", "size"...
Parse a (name,value) tuple from 'name value-length value'.
[ "Parse", "a", "(", "name", "value", ")", "tuple", "from", "name", "value", "-", "length", "value", "." ]
train
https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/parser.py#L563-L576
jelmer/python-fastimport
fastimport/parser.py
ImportParser._path
def _path(self, s): """Parse a path.""" if s.startswith(b'"'): if not s.endswith(b'"'): self.abort(errors.BadFormat, '?', '?', s) else: return _unquote_c_string(s[1:-1]) return s
python
def _path(self, s): """Parse a path.""" if s.startswith(b'"'): if not s.endswith(b'"'): self.abort(errors.BadFormat, '?', '?', s) else: return _unquote_c_string(s[1:-1]) return s
[ "def", "_path", "(", "self", ",", "s", ")", ":", "if", "s", ".", "startswith", "(", "b'\"'", ")", ":", "if", "not", "s", ".", "endswith", "(", "b'\"'", ")", ":", "self", ".", "abort", "(", "errors", ".", "BadFormat", ",", "'?'", ",", "'?'", ","...
Parse a path.
[ "Parse", "a", "path", "." ]
train
https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/parser.py#L578-L585
jelmer/python-fastimport
fastimport/parser.py
ImportParser._path_pair
def _path_pair(self, s): """Parse two paths separated by a space.""" # TODO: handle a space in the first path if s.startswith(b'"'): parts = s[1:].split(b'" ', 1) else: parts = s.split(b' ', 1) if len(parts) != 2: self.abort(errors.BadFormat, '...
python
def _path_pair(self, s): """Parse two paths separated by a space.""" # TODO: handle a space in the first path if s.startswith(b'"'): parts = s[1:].split(b'" ', 1) else: parts = s.split(b' ', 1) if len(parts) != 2: self.abort(errors.BadFormat, '...
[ "def", "_path_pair", "(", "self", ",", "s", ")", ":", "# TODO: handle a space in the first path", "if", "s", ".", "startswith", "(", "b'\"'", ")", ":", "parts", "=", "s", "[", "1", ":", "]", ".", "split", "(", "b'\" '", ",", "1", ")", "else", ":", "p...
Parse two paths separated by a space.
[ "Parse", "two", "paths", "separated", "by", "a", "space", "." ]
train
https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/parser.py#L587-L600
jelmer/python-fastimport
fastimport/parser.py
ImportParser._mode
def _mode(self, s): """Check file mode format and parse into an int. :return: mode as integer """ # Note: Output from git-fast-export slightly different to spec if s in [b'644', b'100644', b'0100644']: return 0o100644 elif s in [b'755', b'100755', b'0100755']...
python
def _mode(self, s): """Check file mode format and parse into an int. :return: mode as integer """ # Note: Output from git-fast-export slightly different to spec if s in [b'644', b'100644', b'0100644']: return 0o100644 elif s in [b'755', b'100755', b'0100755']...
[ "def", "_mode", "(", "self", ",", "s", ")", ":", "# Note: Output from git-fast-export slightly different to spec", "if", "s", "in", "[", "b'644'", ",", "b'100644'", ",", "b'0100644'", "]", ":", "return", "0o100644", "elif", "s", "in", "[", "b'755'", ",", "b'10...
Check file mode format and parse into an int. :return: mode as integer
[ "Check", "file", "mode", "format", "and", "parse", "into", "an", "int", "." ]
train
https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/parser.py#L602-L619
jelmer/python-fastimport
fastimport/helpers.py
common_directory
def common_directory(paths): """Find the deepest common directory of a list of paths. :return: if no paths are provided, None is returned; if there is no common directory, '' is returned; otherwise the common directory with a trailing / is returned. """ import posixpath def get_dir_with...
python
def common_directory(paths): """Find the deepest common directory of a list of paths. :return: if no paths are provided, None is returned; if there is no common directory, '' is returned; otherwise the common directory with a trailing / is returned. """ import posixpath def get_dir_with...
[ "def", "common_directory", "(", "paths", ")", ":", "import", "posixpath", "def", "get_dir_with_slash", "(", "path", ")", ":", "if", "path", "==", "b''", "or", "path", ".", "endswith", "(", "b'/'", ")", ":", "return", "path", "else", ":", "dirname", ",", ...
Find the deepest common directory of a list of paths. :return: if no paths are provided, None is returned; if there is no common directory, '' is returned; otherwise the common directory with a trailing / is returned.
[ "Find", "the", "deepest", "common", "directory", "of", "a", "list", "of", "paths", "." ]
train
https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/helpers.py#L40-L66
jelmer/python-fastimport
fastimport/helpers.py
is_inside
def is_inside(directory, fname): """True if fname is inside directory. The parameters should typically be passed to osutils.normpath first, so that . and .. and repeated slashes are eliminated, and the separators are canonical for the platform. The empty string as a dir name is taken as top-of-tre...
python
def is_inside(directory, fname): """True if fname is inside directory. The parameters should typically be passed to osutils.normpath first, so that . and .. and repeated slashes are eliminated, and the separators are canonical for the platform. The empty string as a dir name is taken as top-of-tre...
[ "def", "is_inside", "(", "directory", ",", "fname", ")", ":", "# XXX: Most callers of this can actually do something smarter by", "# looking at the inventory", "if", "directory", "==", "fname", ":", "return", "True", "if", "directory", "==", "b''", ":", "return", "True"...
True if fname is inside directory. The parameters should typically be passed to osutils.normpath first, so that . and .. and repeated slashes are eliminated, and the separators are canonical for the platform. The empty string as a dir name is taken as top-of-tree and matches everything.
[ "True", "if", "fname", "is", "inside", "directory", "." ]
train
https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/helpers.py#L69-L90
jelmer/python-fastimport
fastimport/helpers.py
is_inside_any
def is_inside_any(dir_list, fname): """True if fname is inside any of given dirs.""" for dirname in dir_list: if is_inside(dirname, fname): return True return False
python
def is_inside_any(dir_list, fname): """True if fname is inside any of given dirs.""" for dirname in dir_list: if is_inside(dirname, fname): return True return False
[ "def", "is_inside_any", "(", "dir_list", ",", "fname", ")", ":", "for", "dirname", "in", "dir_list", ":", "if", "is_inside", "(", "dirname", ",", "fname", ")", ":", "return", "True", "return", "False" ]
True if fname is inside any of given dirs.
[ "True", "if", "fname", "is", "inside", "any", "of", "given", "dirs", "." ]
train
https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/helpers.py#L93-L98
jelmer/python-fastimport
fastimport/helpers.py
utf8_bytes_string
def utf8_bytes_string(s): """Convert a string to a bytes string (if necessary, encode in utf8)""" if sys.version_info[0] == 2: if isinstance(s, str): return s else: return s.encode('utf8') else: if isinstance(s, str): return bytes(s, encoding='utf8...
python
def utf8_bytes_string(s): """Convert a string to a bytes string (if necessary, encode in utf8)""" if sys.version_info[0] == 2: if isinstance(s, str): return s else: return s.encode('utf8') else: if isinstance(s, str): return bytes(s, encoding='utf8...
[ "def", "utf8_bytes_string", "(", "s", ")", ":", "if", "sys", ".", "version_info", "[", "0", "]", "==", "2", ":", "if", "isinstance", "(", "s", ",", "str", ")", ":", "return", "s", "else", ":", "return", "s", ".", "encode", "(", "'utf8'", ")", "el...
Convert a string to a bytes string (if necessary, encode in utf8)
[ "Convert", "a", "string", "to", "a", "bytes", "string", "(", "if", "necessary", "encode", "in", "utf8", ")" ]
train
https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/helpers.py#L101-L112
jelmer/python-fastimport
fastimport/helpers.py
binary_stream
def binary_stream(stream): """Ensure a stream is binary on Windows. :return: the stream """ try: import os if os.name == 'nt': fileno = getattr(stream, 'fileno', None) if fileno: no = fileno() if no >= 0: # -1 means we're worki...
python
def binary_stream(stream): """Ensure a stream is binary on Windows. :return: the stream """ try: import os if os.name == 'nt': fileno = getattr(stream, 'fileno', None) if fileno: no = fileno() if no >= 0: # -1 means we're worki...
[ "def", "binary_stream", "(", "stream", ")", ":", "try", ":", "import", "os", "if", "os", ".", "name", "==", "'nt'", ":", "fileno", "=", "getattr", "(", "stream", ",", "'fileno'", ",", "None", ")", "if", "fileno", ":", "no", "=", "fileno", "(", ")",...
Ensure a stream is binary on Windows. :return: the stream
[ "Ensure", "a", "stream", "is", "binary", "on", "Windows", "." ]
train
https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/helpers.py#L199-L215
jelmer/python-fastimport
fastimport/helpers.py
invert_dictset
def invert_dictset(d): """Invert a dictionary with keys matching a set of values, turned into lists.""" # Based on recipe from ASPN result = {} for k, c in d.items(): for v in c: keys = result.setdefault(v, []) keys.append(k) return result
python
def invert_dictset(d): """Invert a dictionary with keys matching a set of values, turned into lists.""" # Based on recipe from ASPN result = {} for k, c in d.items(): for v in c: keys = result.setdefault(v, []) keys.append(k) return result
[ "def", "invert_dictset", "(", "d", ")", ":", "# Based on recipe from ASPN", "result", "=", "{", "}", "for", "k", ",", "c", "in", "d", ".", "items", "(", ")", ":", "for", "v", "in", "c", ":", "keys", "=", "result", ".", "setdefault", "(", "v", ",", ...
Invert a dictionary with keys matching a set of values, turned into lists.
[ "Invert", "a", "dictionary", "with", "keys", "matching", "a", "set", "of", "values", "turned", "into", "lists", "." ]
train
https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/helpers.py#L218-L226
jelmer/python-fastimport
fastimport/helpers.py
invert_dict
def invert_dict(d): """Invert a dictionary with keys matching each value turned into a list.""" # Based on recipe from ASPN result = {} for k, v in d.items(): keys = result.setdefault(v, []) keys.append(k) return result
python
def invert_dict(d): """Invert a dictionary with keys matching each value turned into a list.""" # Based on recipe from ASPN result = {} for k, v in d.items(): keys = result.setdefault(v, []) keys.append(k) return result
[ "def", "invert_dict", "(", "d", ")", ":", "# Based on recipe from ASPN", "result", "=", "{", "}", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", ":", "keys", "=", "result", ".", "setdefault", "(", "v", ",", "[", "]", ")", "keys", ".", "...
Invert a dictionary with keys matching each value turned into a list.
[ "Invert", "a", "dictionary", "with", "keys", "matching", "each", "value", "turned", "into", "a", "list", "." ]
train
https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/helpers.py#L229-L236
jelmer/python-fastimport
fastimport/helpers.py
defines_to_dict
def defines_to_dict(defines): """Convert a list of definition strings to a dictionary.""" if defines is None: return None result = {} for define in defines: kv = define.split('=', 1) if len(kv) == 1: result[define.strip()] = 1 else: result[kv[0].st...
python
def defines_to_dict(defines): """Convert a list of definition strings to a dictionary.""" if defines is None: return None result = {} for define in defines: kv = define.split('=', 1) if len(kv) == 1: result[define.strip()] = 1 else: result[kv[0].st...
[ "def", "defines_to_dict", "(", "defines", ")", ":", "if", "defines", "is", "None", ":", "return", "None", "result", "=", "{", "}", "for", "define", "in", "defines", ":", "kv", "=", "define", ".", "split", "(", "'='", ",", "1", ")", "if", "len", "("...
Convert a list of definition strings to a dictionary.
[ "Convert", "a", "list", "of", "definition", "strings", "to", "a", "dictionary", "." ]
train
https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/helpers.py#L239-L250
galaxyproject/gravity
gravity/process_manager/__init__.py
BaseProcessManager.start
def start(self, instance_names): """ If start is called from the root of a Galaxy source directory with no args, automatically add this instance. """ if not instance_names: configs = (os.path.join('config', 'galaxy.ini'), os.path.join('config', 'galaxy.ini...
python
def start(self, instance_names): """ If start is called from the root of a Galaxy source directory with no args, automatically add this instance. """ if not instance_names: configs = (os.path.join('config', 'galaxy.ini'), os.path.join('config', 'galaxy.ini...
[ "def", "start", "(", "self", ",", "instance_names", ")", ":", "if", "not", "instance_names", ":", "configs", "=", "(", "os", ".", "path", ".", "join", "(", "'config'", ",", "'galaxy.ini'", ")", ",", "os", ".", "path", ".", "join", "(", "'config'", ",...
If start is called from the root of a Galaxy source directory with no args, automatically add this instance.
[ "If", "start", "is", "called", "from", "the", "root", "of", "a", "Galaxy", "source", "directory", "with", "no", "args", "automatically", "add", "this", "instance", "." ]
train
https://github.com/galaxyproject/gravity/blob/2f792497fc60874f881c9ef74a5905a286a9ce3e/gravity/process_manager/__init__.py#L32-L43
theiviaxx/photoshopConnection
pyps/_des.py
des.crypt
def crypt(self, data, crypt_type): """Crypt the data in blocks, running it through des_crypt()""" # Error check the data if not data: return '' if len(data) % self.block_size != 0: if crypt_type == des.DECRYPT: # Decryption must work on 8 byte blocks ...
python
def crypt(self, data, crypt_type): """Crypt the data in blocks, running it through des_crypt()""" # Error check the data if not data: return '' if len(data) % self.block_size != 0: if crypt_type == des.DECRYPT: # Decryption must work on 8 byte blocks ...
[ "def", "crypt", "(", "self", ",", "data", ",", "crypt_type", ")", ":", "# Error check the data", "if", "not", "data", ":", "return", "''", "if", "len", "(", "data", ")", "%", "self", ".", "block_size", "!=", "0", ":", "if", "crypt_type", "==", "des", ...
Crypt the data in blocks, running it through des_crypt()
[ "Crypt", "the", "data", "in", "blocks", "running", "it", "through", "des_crypt", "()" ]
train
https://github.com/theiviaxx/photoshopConnection/blob/ab5e3715d3bdc69601bc6dd0f29348f59fa3d612/pyps/_des.py#L566-L617
lawlesst/vivo-rdflib-sparqlstore
vstore/vstore.py
VIVOWrapper.setQuery
def setQuery(self, query): """ Set the SPARQL query text and set the VIVO custom authentication parameters. Set here because this is called immediately before any query is sent to the triple store. """ self.queryType = self._parseQueryType(query) self.que...
python
def setQuery(self, query): """ Set the SPARQL query text and set the VIVO custom authentication parameters. Set here because this is called immediately before any query is sent to the triple store. """ self.queryType = self._parseQueryType(query) self.que...
[ "def", "setQuery", "(", "self", ",", "query", ")", ":", "self", ".", "queryType", "=", "self", ".", "_parseQueryType", "(", "query", ")", "self", ".", "queryString", "=", "self", ".", "injectPrefixes", "(", "query", ")", "self", ".", "addParameter", "(",...
Set the SPARQL query text and set the VIVO custom authentication parameters. Set here because this is called immediately before any query is sent to the triple store.
[ "Set", "the", "SPARQL", "query", "text", "and", "set", "the", "VIVO", "custom", "authentication", "parameters", "." ]
train
https://github.com/lawlesst/vivo-rdflib-sparqlstore/blob/9e3a3d8efb8ab3a247c49cb64af639e2bdc2425b/vstore/vstore.py#L17-L28
sveetch/boussole
boussole/conf/post_processor.py
SettingsPostProcessor.post_process
def post_process(self, settings): """ Perform post processing methods on settings according to their definition in manifest. Post process methods are implemented in their own method that have the same signature: * Get arguments: Current settings, item name and item valu...
python
def post_process(self, settings): """ Perform post processing methods on settings according to their definition in manifest. Post process methods are implemented in their own method that have the same signature: * Get arguments: Current settings, item name and item valu...
[ "def", "post_process", "(", "self", ",", "settings", ")", ":", "for", "k", "in", "settings", ":", "# Search for post process rules for setting in manifest", "if", "k", "in", "self", ".", "settings_manifesto", "and", "self", ".", "settings_manifesto", "[", "k", "]"...
Perform post processing methods on settings according to their definition in manifest. Post process methods are implemented in their own method that have the same signature: * Get arguments: Current settings, item name and item value; * Return item value possibly patched; ...
[ "Perform", "post", "processing", "methods", "on", "settings", "according", "to", "their", "definition", "in", "manifest", "." ]
train
https://github.com/sveetch/boussole/blob/22cc644e9d633f41ebfc167d427a71c1726cee21/boussole/conf/post_processor.py#L25-L58
sveetch/boussole
boussole/conf/post_processor.py
SettingsPostProcessor._patch_expand_path
def _patch_expand_path(self, settings, name, value): """ Patch a path to expand home directory and make absolute path. Args: settings (dict): Current settings. name (str): Setting name. value (str): Path to patch. Returns: str: Patched pa...
python
def _patch_expand_path(self, settings, name, value): """ Patch a path to expand home directory and make absolute path. Args: settings (dict): Current settings. name (str): Setting name. value (str): Path to patch. Returns: str: Patched pa...
[ "def", "_patch_expand_path", "(", "self", ",", "settings", ",", "name", ",", "value", ")", ":", "if", "os", ".", "path", ".", "isabs", "(", "value", ")", ":", "return", "os", ".", "path", ".", "normpath", "(", "value", ")", "# Expand home directory if an...
Patch a path to expand home directory and make absolute path. Args: settings (dict): Current settings. name (str): Setting name. value (str): Path to patch. Returns: str: Patched path to an absolute path.
[ "Patch", "a", "path", "to", "expand", "home", "directory", "and", "make", "absolute", "path", "." ]
train
https://github.com/sveetch/boussole/blob/22cc644e9d633f41ebfc167d427a71c1726cee21/boussole/conf/post_processor.py#L60-L84
sveetch/boussole
boussole/conf/post_processor.py
SettingsPostProcessor._patch_expand_paths
def _patch_expand_paths(self, settings, name, value): """ Apply ``SettingsPostProcessor._patch_expand_path`` to each element in list. Args: settings (dict): Current settings. name (str): Setting name. value (list): List of paths to patch. Ret...
python
def _patch_expand_paths(self, settings, name, value): """ Apply ``SettingsPostProcessor._patch_expand_path`` to each element in list. Args: settings (dict): Current settings. name (str): Setting name. value (list): List of paths to patch. Ret...
[ "def", "_patch_expand_paths", "(", "self", ",", "settings", ",", "name", ",", "value", ")", ":", "return", "[", "self", ".", "_patch_expand_path", "(", "settings", ",", "name", ",", "item", ")", "for", "item", "in", "value", "]" ]
Apply ``SettingsPostProcessor._patch_expand_path`` to each element in list. Args: settings (dict): Current settings. name (str): Setting name. value (list): List of paths to patch. Returns: list: Patched path list to an absolute path.
[ "Apply", "SettingsPostProcessor", ".", "_patch_expand_path", "to", "each", "element", "in", "list", "." ]
train
https://github.com/sveetch/boussole/blob/22cc644e9d633f41ebfc167d427a71c1726cee21/boussole/conf/post_processor.py#L86-L101
sveetch/boussole
boussole/conf/post_processor.py
SettingsPostProcessor._validate_path
def _validate_path(self, settings, name, value): """ Validate path exists Args: settings (dict): Current settings. name (str): Setting name. value (str): Path to validate. Raises: boussole.exceptions.SettingsInvalidError: If path does not...
python
def _validate_path(self, settings, name, value): """ Validate path exists Args: settings (dict): Current settings. name (str): Setting name. value (str): Path to validate. Raises: boussole.exceptions.SettingsInvalidError: If path does not...
[ "def", "_validate_path", "(", "self", ",", "settings", ",", "name", ",", "value", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "value", ")", ":", "raise", "SettingsInvalidError", "(", "\"Path from setting '{name}' does not \"", "\"exists: {value...
Validate path exists Args: settings (dict): Current settings. name (str): Setting name. value (str): Path to validate. Raises: boussole.exceptions.SettingsInvalidError: If path does not exists. Returns: str: Validated path.
[ "Validate", "path", "exists" ]
train
https://github.com/sveetch/boussole/blob/22cc644e9d633f41ebfc167d427a71c1726cee21/boussole/conf/post_processor.py#L103-L126
sveetch/boussole
boussole/conf/post_processor.py
SettingsPostProcessor._validate_paths
def _validate_paths(self, settings, name, value): """ Apply ``SettingsPostProcessor._validate_path`` to each element in list. Args: settings (dict): Current settings. name (str): Setting name. value (list): List of paths to patch. Raises: ...
python
def _validate_paths(self, settings, name, value): """ Apply ``SettingsPostProcessor._validate_path`` to each element in list. Args: settings (dict): Current settings. name (str): Setting name. value (list): List of paths to patch. Raises: ...
[ "def", "_validate_paths", "(", "self", ",", "settings", ",", "name", ",", "value", ")", ":", "return", "[", "self", ".", "_validate_path", "(", "settings", ",", "name", ",", "item", ")", "for", "item", "in", "value", "]" ]
Apply ``SettingsPostProcessor._validate_path`` to each element in list. Args: settings (dict): Current settings. name (str): Setting name. value (list): List of paths to patch. Raises: boussole.exceptions.SettingsInvalidError: Once a path does no...
[ "Apply", "SettingsPostProcessor", ".", "_validate_path", "to", "each", "element", "in", "list", "." ]
train
https://github.com/sveetch/boussole/blob/22cc644e9d633f41ebfc167d427a71c1726cee21/boussole/conf/post_processor.py#L128-L147
sveetch/boussole
boussole/conf/post_processor.py
SettingsPostProcessor._validate_required
def _validate_required(self, settings, name, value): """ Validate a required setting (value can not be empty) Args: settings (dict): Current settings. name (str): Setting name. value (str): Required value to validate. Raises: boussole.exc...
python
def _validate_required(self, settings, name, value): """ Validate a required setting (value can not be empty) Args: settings (dict): Current settings. name (str): Setting name. value (str): Required value to validate. Raises: boussole.exc...
[ "def", "_validate_required", "(", "self", ",", "settings", ",", "name", ",", "value", ")", ":", "if", "not", "value", ":", "raise", "SettingsInvalidError", "(", "(", "\"Required value from setting '{name}' \"", "\"must not be \"", "\"empty.\"", ")", ".", "format", ...
Validate a required setting (value can not be empty) Args: settings (dict): Current settings. name (str): Setting name. value (str): Required value to validate. Raises: boussole.exceptions.SettingsInvalidError: If value is empty. Returns: ...
[ "Validate", "a", "required", "setting", "(", "value", "can", "not", "be", "empty", ")" ]
train
https://github.com/sveetch/boussole/blob/22cc644e9d633f41ebfc167d427a71c1726cee21/boussole/conf/post_processor.py#L149-L170
svven/summary
summarize.py
render
def render(template, **kwargs): """ Renders the HTML containing provided summaries. The summary has to be an instance of summary.Summary, or at least contain similar properties: title, image, url, description and collections: titles, images, descriptions. """ import jinja2 imp...
python
def render(template, **kwargs): """ Renders the HTML containing provided summaries. The summary has to be an instance of summary.Summary, or at least contain similar properties: title, image, url, description and collections: titles, images, descriptions. """ import jinja2 imp...
[ "def", "render", "(", "template", ",", "*", "*", "kwargs", ")", ":", "import", "jinja2", "import", "os", ".", "path", "as", "path", "searchpath", "=", "path", ".", "join", "(", "path", ".", "dirname", "(", "__file__", ")", ",", "\"templates\"", ")", ...
Renders the HTML containing provided summaries. The summary has to be an instance of summary.Summary, or at least contain similar properties: title, image, url, description and collections: titles, images, descriptions.
[ "Renders", "the", "HTML", "containing", "provided", "summaries", ".", "The", "summary", "has", "to", "be", "an", "instance", "of", "summary", ".", "Summary", "or", "at", "least", "contain", "similar", "properties", ":", "title", "image", "url", "description", ...
train
https://github.com/svven/summary/blob/3a6c43d2da08a7452f6b76d1813aa70ba36b8a54/summarize.py#L6-L23
svven/summary
summarize.py
summarize
def summarize(urls): """ Calls extract for each of the URLs, Returns the list of Extracted instances as summaries, the result of the process, and the speed. """ import time from summary import Summary fails = 0 err = lambda e: e.__class__.__name__ summaries = [] ...
python
def summarize(urls): """ Calls extract for each of the URLs, Returns the list of Extracted instances as summaries, the result of the process, and the speed. """ import time from summary import Summary fails = 0 err = lambda e: e.__class__.__name__ summaries = [] ...
[ "def", "summarize", "(", "urls", ")", ":", "import", "time", "from", "summary", "import", "Summary", "fails", "=", "0", "err", "=", "lambda", "e", ":", "e", ".", "__class__", ".", "__name__", "summaries", "=", "[", "]", "start", "=", "time", ".", "ti...
Calls extract for each of the URLs, Returns the list of Extracted instances as summaries, the result of the process, and the speed.
[ "Calls", "extract", "for", "each", "of", "the", "URLs", "Returns", "the", "list", "of", "Extracted", "instances", "as", "summaries", "the", "result", "of", "the", "process", "and", "the", "speed", "." ]
train
https://github.com/svven/summary/blob/3a6c43d2da08a7452f6b76d1813aa70ba36b8a54/summarize.py#L26-L67
samisalkosuo/mazepy
mazepy/mazepy.py
initMazeFromJSON
def initMazeFromJSON(jsonString, cellClass=Cell, gridClass=Grid): '''Init a maze from JSON string.''' jsonObj = json.loads(jsonString) rows=jsonObj["rows"] columns=jsonObj["columns"] grid=gridClass(rows,columns,cellClass) grid.algorithm=jsonObj["algorithm"] grid.algorithm_key=jsonObj["a...
python
def initMazeFromJSON(jsonString, cellClass=Cell, gridClass=Grid): '''Init a maze from JSON string.''' jsonObj = json.loads(jsonString) rows=jsonObj["rows"] columns=jsonObj["columns"] grid=gridClass(rows,columns,cellClass) grid.algorithm=jsonObj["algorithm"] grid.algorithm_key=jsonObj["a...
[ "def", "initMazeFromJSON", "(", "jsonString", ",", "cellClass", "=", "Cell", ",", "gridClass", "=", "Grid", ")", ":", "jsonObj", "=", "json", ".", "loads", "(", "jsonString", ")", "rows", "=", "jsonObj", "[", "\"rows\"", "]", "columns", "=", "jsonObj", "...
Init a maze from JSON string.
[ "Init", "a", "maze", "from", "JSON", "string", "." ]
train
https://github.com/samisalkosuo/mazepy/blob/b14184da0095adaa026577d695f9c4b4b10a858c/mazepy/mazepy.py#L438-L468
jantman/webhook2lambda2sqs
webhook2lambda2sqs/utils.py
read_json_file
def read_json_file(fpath): """ Read a JSON file from ``fpath``; raise an exception if it doesn't exist. :param fpath: path to file to read :type fpath: str :return: deserialized JSON :rtype: dict """ if not os.path.exists(fpath): raise Exception('ERROR: file %s does not exist.' ...
python
def read_json_file(fpath): """ Read a JSON file from ``fpath``; raise an exception if it doesn't exist. :param fpath: path to file to read :type fpath: str :return: deserialized JSON :rtype: dict """ if not os.path.exists(fpath): raise Exception('ERROR: file %s does not exist.' ...
[ "def", "read_json_file", "(", "fpath", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "fpath", ")", ":", "raise", "Exception", "(", "'ERROR: file %s does not exist.'", "%", "fpath", ")", "with", "open", "(", "fpath", ",", "'r'", ")", "as",...
Read a JSON file from ``fpath``; raise an exception if it doesn't exist. :param fpath: path to file to read :type fpath: str :return: deserialized JSON :rtype: dict
[ "Read", "a", "JSON", "file", "from", "fpath", ";", "raise", "an", "exception", "if", "it", "doesn", "t", "exist", "." ]
train
https://github.com/jantman/webhook2lambda2sqs/blob/c80c18d5a908ba8b8ee624dc3a977c633fba2b7c/webhook2lambda2sqs/utils.py#L47-L61
jantman/webhook2lambda2sqs
webhook2lambda2sqs/utils.py
run_cmd
def run_cmd(args, stream=False, shell=True): """ Execute a command via :py:class:`subprocess.Popen`; return its output (string, combined STDOUT and STDERR) and exit code (int). If stream is True, also stream the output to STDOUT in realtime. :param args: the command to run and arguments, as a list ...
python
def run_cmd(args, stream=False, shell=True): """ Execute a command via :py:class:`subprocess.Popen`; return its output (string, combined STDOUT and STDERR) and exit code (int). If stream is True, also stream the output to STDOUT in realtime. :param args: the command to run and arguments, as a list ...
[ "def", "run_cmd", "(", "args", ",", "stream", "=", "False", ",", "shell", "=", "True", ")", ":", "s", "=", "''", "if", "stream", ":", "s", "=", "' and streaming output'", "logger", ".", "info", "(", "'Running command%s: %s'", ",", "s", ",", "args", ")"...
Execute a command via :py:class:`subprocess.Popen`; return its output (string, combined STDOUT and STDERR) and exit code (int). If stream is True, also stream the output to STDOUT in realtime. :param args: the command to run and arguments, as a list or string :param stream: whether or not to stream com...
[ "Execute", "a", "command", "via", ":", "py", ":", "class", ":", "subprocess", ".", "Popen", ";", "return", "its", "output", "(", "string", "combined", "STDOUT", "and", "STDERR", ")", "and", "exit", "code", "(", "int", ")", ".", "If", "stream", "is", ...
train
https://github.com/jantman/webhook2lambda2sqs/blob/c80c18d5a908ba8b8ee624dc3a977c633fba2b7c/webhook2lambda2sqs/utils.py#L76-L105
svven/summary
summary/__init__.py
Summary._load
def _load(self, titles=[], descriptions=[], images=[], urls=[], **kwargs): """ Loads extracted data into Summary. Performs validation and filtering on-the-fly, and sets the non-plural fields to the best specific item so far. If GET_ALL_DATA is False, it gets only the first valid ...
python
def _load(self, titles=[], descriptions=[], images=[], urls=[], **kwargs): """ Loads extracted data into Summary. Performs validation and filtering on-the-fly, and sets the non-plural fields to the best specific item so far. If GET_ALL_DATA is False, it gets only the first valid ...
[ "def", "_load", "(", "self", ",", "titles", "=", "[", "]", ",", "descriptions", "=", "[", "]", ",", "images", "=", "[", "]", ",", "urls", "=", "[", "]", ",", "*", "*", "kwargs", ")", ":", "enough", "=", "lambda", "items", ":", "items", "# len(i...
Loads extracted data into Summary. Performs validation and filtering on-the-fly, and sets the non-plural fields to the best specific item so far. If GET_ALL_DATA is False, it gets only the first valid item.
[ "Loads", "extracted", "data", "into", "Summary", ".", "Performs", "validation", "and", "filtering", "on", "-", "the", "-", "fly", "and", "sets", "the", "non", "-", "plural", "fields", "to", "the", "best", "specific", "item", "so", "far", ".", "If", "GET_...
train
https://github.com/svven/summary/blob/3a6c43d2da08a7452f6b76d1813aa70ba36b8a54/summary/__init__.py#L103-L136
svven/summary
summary/__init__.py
Summary._clean_url
def _clean_url(self, url): """ Canonicalizes the url, as it is done in Scrapy. And keeps only USEFUL_QUERY_KEYS. It also strips the trailing slash to help identifying dupes. """ # TODO: Turn this into regex if not url.startswith('http') or url.endswith('}}') or '...
python
def _clean_url(self, url): """ Canonicalizes the url, as it is done in Scrapy. And keeps only USEFUL_QUERY_KEYS. It also strips the trailing slash to help identifying dupes. """ # TODO: Turn this into regex if not url.startswith('http') or url.endswith('}}') or '...
[ "def", "_clean_url", "(", "self", ",", "url", ")", ":", "# TODO: Turn this into regex", "if", "not", "url", ".", "startswith", "(", "'http'", ")", "or", "url", ".", "endswith", "(", "'}}'", ")", "or", "'nojs_router'", "in", "url", ":", "return", "None", ...
Canonicalizes the url, as it is done in Scrapy. And keeps only USEFUL_QUERY_KEYS. It also strips the trailing slash to help identifying dupes.
[ "Canonicalizes", "the", "url", "as", "it", "is", "done", "in", "Scrapy", ".", "And", "keeps", "only", "USEFUL_QUERY_KEYS", ".", "It", "also", "strips", "the", "trailing", "slash", "to", "help", "identifying", "dupes", "." ]
train
https://github.com/svven/summary/blob/3a6c43d2da08a7452f6b76d1813aa70ba36b8a54/summary/__init__.py#L151-L164
svven/summary
summary/__init__.py
Summary._filter_image
def _filter_image(self, url): "The param is the image URL, which is returned if it passes all the filters." return reduce(lambda f, g: f and g(f), [ filters.AdblockURLFilter()(url), filters.NoImageFilter(), filters.SizeImageFilter(), filters.MonoI...
python
def _filter_image(self, url): "The param is the image URL, which is returned if it passes all the filters." return reduce(lambda f, g: f and g(f), [ filters.AdblockURLFilter()(url), filters.NoImageFilter(), filters.SizeImageFilter(), filters.MonoI...
[ "def", "_filter_image", "(", "self", ",", "url", ")", ":", "return", "reduce", "(", "lambda", "f", ",", "g", ":", "f", "and", "g", "(", "f", ")", ",", "[", "filters", ".", "AdblockURLFilter", "(", ")", "(", "url", ")", ",", "filters", ".", "NoIma...
The param is the image URL, which is returned if it passes all the filters.
[ "The", "param", "is", "the", "image", "URL", "which", "is", "returned", "if", "it", "passes", "all", "the", "filters", "." ]
train
https://github.com/svven/summary/blob/3a6c43d2da08a7452f6b76d1813aa70ba36b8a54/summary/__init__.py#L166-L175
svven/summary
summary/__init__.py
Summary._get_tag
def _get_tag(self, response, tag_name="html", encoding="utf-8"): """ Iterates response content and returns the tag if found. If not found, the response content is fully consumed so self._html equals response.content, and it returns None. """ def find_tag(tag_name): ...
python
def _get_tag(self, response, tag_name="html", encoding="utf-8"): """ Iterates response content and returns the tag if found. If not found, the response content is fully consumed so self._html equals response.content, and it returns None. """ def find_tag(tag_name): ...
[ "def", "_get_tag", "(", "self", ",", "response", ",", "tag_name", "=", "\"html\"", ",", "encoding", "=", "\"utf-8\"", ")", ":", "def", "find_tag", "(", "tag_name", ")", ":", "tag_start", "=", "tag_end", "=", "None", "found", "=", "lambda", ":", "tag_star...
Iterates response content and returns the tag if found. If not found, the response content is fully consumed so self._html equals response.content, and it returns None.
[ "Iterates", "response", "content", "and", "returns", "the", "tag", "if", "found", ".", "If", "not", "found", "the", "response", "content", "is", "fully", "consumed", "so", "self", ".", "_html", "equals", "response", ".", "content", "and", "it", "returns", ...
train
https://github.com/svven/summary/blob/3a6c43d2da08a7452f6b76d1813aa70ba36b8a54/summary/__init__.py#L177-L219
svven/summary
summary/__init__.py
Summary.extract
def extract(self, check_url=None, http_equiv_refresh=True): """ Downloads HTML <head> tag first, extracts data from it using specific head techniques, loads it and checks if is complete. Otherwise downloads the HTML <body> tag as well and loads data extracted by using appropria...
python
def extract(self, check_url=None, http_equiv_refresh=True): """ Downloads HTML <head> tag first, extracts data from it using specific head techniques, loads it and checks if is complete. Otherwise downloads the HTML <body> tag as well and loads data extracted by using appropria...
[ "def", "extract", "(", "self", ",", "check_url", "=", "None", ",", "http_equiv_refresh", "=", "True", ")", ":", "# assert self._is_clear()", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "info", "(", "\"Extract: %s\"", ",", ...
Downloads HTML <head> tag first, extracts data from it using specific head techniques, loads it and checks if is complete. Otherwise downloads the HTML <body> tag as well and loads data extracted by using appropriate semantic techniques. Eagerly calls check_url(url) if any, before par...
[ "Downloads", "HTML", "<head", ">", "tag", "first", "extracts", "data", "from", "it", "using", "specific", "head", "techniques", "loads", "it", "and", "checks", "if", "is", "complete", ".", "Otherwise", "downloads", "the", "HTML", "<body", ">", "tag", "as", ...
train
https://github.com/svven/summary/blob/3a6c43d2da08a7452f6b76d1813aa70ba36b8a54/summary/__init__.py#L227-L300
transmogrifier/pidigits
pidigits/pidigits_gosper.py
piGenGosper
def piGenGosper(): """A generator function that yields the digits of Pi """ z = ((1,0,0,1),1) while True: lft = __lfts(z[1]) n = int(__next(z)) if __safe(z,n): z = __prod(z,n) yield n else: z = __cons(z,lft)
python
def piGenGosper(): """A generator function that yields the digits of Pi """ z = ((1,0,0,1),1) while True: lft = __lfts(z[1]) n = int(__next(z)) if __safe(z,n): z = __prod(z,n) yield n else: z = __cons(z,lft)
[ "def", "piGenGosper", "(", ")", ":", "z", "=", "(", "(", "1", ",", "0", ",", "0", ",", "1", ")", ",", "1", ")", "while", "True", ":", "lft", "=", "__lfts", "(", "z", "[", "1", "]", ")", "n", "=", "int", "(", "__next", "(", "z", ")", ")"...
A generator function that yields the digits of Pi
[ "A", "generator", "function", "that", "yields", "the", "digits", "of", "Pi" ]
train
https://github.com/transmogrifier/pidigits/blob/b12081126a76d30fb69839aa586420c5bb04feb8/pidigits/pidigits_gosper.py#L62-L73
transmogrifier/pidigits
pidigits/pidigits_gosper.py
getPiGosper
def getPiGosper(n): """Returns a list containing first n digits of Pi """ mypi = piGenGosper() result = [] if n > 0: result += [next(mypi) for i in range(n)] mypi.close() return result
python
def getPiGosper(n): """Returns a list containing first n digits of Pi """ mypi = piGenGosper() result = [] if n > 0: result += [next(mypi) for i in range(n)] mypi.close() return result
[ "def", "getPiGosper", "(", "n", ")", ":", "mypi", "=", "piGenGosper", "(", ")", "result", "=", "[", "]", "if", "n", ">", "0", ":", "result", "+=", "[", "next", "(", "mypi", ")", "for", "i", "in", "range", "(", "n", ")", "]", "mypi", ".", "clo...
Returns a list containing first n digits of Pi
[ "Returns", "a", "list", "containing", "first", "n", "digits", "of", "Pi" ]
train
https://github.com/transmogrifier/pidigits/blob/b12081126a76d30fb69839aa586420c5bb04feb8/pidigits/pidigits_gosper.py#L75-L83
fchauvel/MAD
mad/evaluation.py
Evaluation.of_think
def of_think(self, think): """ Simulate the worker processing the task for the specified amount of time. The worker is not released and the task is not paused. """ return self._compute( duration=think.duration, after=self.continuation)
python
def of_think(self, think): """ Simulate the worker processing the task for the specified amount of time. The worker is not released and the task is not paused. """ return self._compute( duration=think.duration, after=self.continuation)
[ "def", "of_think", "(", "self", ",", "think", ")", ":", "return", "self", ".", "_compute", "(", "duration", "=", "think", ".", "duration", ",", "after", "=", "self", ".", "continuation", ")" ]
Simulate the worker processing the task for the specified amount of time. The worker is not released and the task is not paused.
[ "Simulate", "the", "worker", "processing", "the", "task", "for", "the", "specified", "amount", "of", "time", ".", "The", "worker", "is", "not", "released", "and", "the", "task", "is", "not", "paused", "." ]
train
https://github.com/fchauvel/MAD/blob/806d5174848b1a502e5c683894995602478c448b/mad/evaluation.py#L209-L216
Robin8Put/pmes
balance/handler.py
Balance.freeze
async def freeze(self, *args, **kwargs): """ Freeze users balance Accepts: - uid [integer] (users id from main server) - coinid [string] (blockchain type in uppercase) - amount [integer] (amount for freezing) Returns: - uid [integer] (users id from main server) - coinid [string] (blockchain typ...
python
async def freeze(self, *args, **kwargs): """ Freeze users balance Accepts: - uid [integer] (users id from main server) - coinid [string] (blockchain type in uppercase) - amount [integer] (amount for freezing) Returns: - uid [integer] (users id from main server) - coinid [string] (blockchain typ...
[ "async", "def", "freeze", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Get data from request", "uid", "=", "kwargs", ".", "get", "(", "\"uid\"", ",", "0", ")", "coinid", "=", "kwargs", ".", "get", "(", "\"coinid\"", ")", "amou...
Freeze users balance Accepts: - uid [integer] (users id from main server) - coinid [string] (blockchain type in uppercase) - amount [integer] (amount for freezing) Returns: - uid [integer] (users id from main server) - coinid [string] (blockchain type in uppercase) - amount_active [integer] (act...
[ "Freeze", "users", "balance" ]
train
https://github.com/Robin8Put/pmes/blob/338bec94162098f05b75bad035417317e1252fd2/balance/handler.py#L103-L178
Robin8Put/pmes
balance/handler.py
Balance.get_active
async def get_active(self, *args, **kwargs): """ Get active users balance Accepts: - uid [integer] (users id) - types [list | string] (array with needed types or "all") Returns: { type [string] (blockchain type): amount } """ # Get daya from request coinids = kwargs.get("coinids") uid...
python
async def get_active(self, *args, **kwargs): """ Get active users balance Accepts: - uid [integer] (users id) - types [list | string] (array with needed types or "all") Returns: { type [string] (blockchain type): amount } """ # Get daya from request coinids = kwargs.get("coinids") uid...
[ "async", "def", "get_active", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Get daya from request", "coinids", "=", "kwargs", ".", "get", "(", "\"coinids\"", ")", "uid", "=", "kwargs", ".", "get", "(", "\"uid\"", ",", "0", ")", ...
Get active users balance Accepts: - uid [integer] (users id) - types [list | string] (array with needed types or "all") Returns: { type [string] (blockchain type): amount }
[ "Get", "active", "users", "balance" ]
train
https://github.com/Robin8Put/pmes/blob/338bec94162098f05b75bad035417317e1252fd2/balance/handler.py#L635-L697
Robin8Put/pmes
balance/handler.py
Balance.get_frozen
async def get_frozen(self, *args, **kwargs): """ Get frozen users balance Accepts: - uid [integer] (users id) - types [list | string] (array with needed types or "all") Returns: { type [string] (blockchain type): amount } """ super().validate(*args, **kwargs) if kwargs.get("message"): ...
python
async def get_frozen(self, *args, **kwargs): """ Get frozen users balance Accepts: - uid [integer] (users id) - types [list | string] (array with needed types or "all") Returns: { type [string] (blockchain type): amount } """ super().validate(*args, **kwargs) if kwargs.get("message"): ...
[ "async", "def", "get_frozen", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "super", "(", ")", ".", "validate", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "kwargs", ".", "get", "(", "\"message\"", ")", ":", "kwargs"...
Get frozen users balance Accepts: - uid [integer] (users id) - types [list | string] (array with needed types or "all") Returns: { type [string] (blockchain type): amount }
[ "Get", "frozen", "users", "balance" ]
train
https://github.com/Robin8Put/pmes/blob/338bec94162098f05b75bad035417317e1252fd2/balance/handler.py#L700-L766
Robin8Put/pmes
balance/handler.py
Balance.collect_wallets
async def collect_wallets(self, uid): """ Asynchronous generator """ logging.debug(self.types) logging.debug(uid) for coinid in self.types: logging.debug(coinid) await asyncio.sleep(0.5) # Connect to appropriate database database = self.client[self.collection] logging.debug(database) colle...
python
async def collect_wallets(self, uid): """ Asynchronous generator """ logging.debug(self.types) logging.debug(uid) for coinid in self.types: logging.debug(coinid) await asyncio.sleep(0.5) # Connect to appropriate database database = self.client[self.collection] logging.debug(database) colle...
[ "async", "def", "collect_wallets", "(", "self", ",", "uid", ")", ":", "logging", ".", "debug", "(", "self", ".", "types", ")", "logging", ".", "debug", "(", "uid", ")", "for", "coinid", "in", "self", ".", "types", ":", "logging", ".", "debug", "(", ...
Asynchronous generator
[ "Asynchronous", "generator" ]
train
https://github.com/Robin8Put/pmes/blob/338bec94162098f05b75bad035417317e1252fd2/balance/handler.py#L769-L790
Robin8Put/pmes
balance/handler.py
Balance.get_wallets
async def get_wallets(self, *args, **kwargs): """ Get users wallets by uid Accepts: - uid [integer] (users id) Returns a list: - [ { "address": [string], "uid": [integer], "amount_active": [integer], "amount_frozen": [integer] }, ] """ logging.debug("\n [+] -- G...
python
async def get_wallets(self, *args, **kwargs): """ Get users wallets by uid Accepts: - uid [integer] (users id) Returns a list: - [ { "address": [string], "uid": [integer], "amount_active": [integer], "amount_frozen": [integer] }, ] """ logging.debug("\n [+] -- G...
[ "async", "def", "get_wallets", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "logging", ".", "debug", "(", "\"\\n [+] -- Get wallets debugging.\"", ")", "if", "kwargs", ".", "get", "(", "\"message\"", ")", ":", "kwargs", "=", "json", ...
Get users wallets by uid Accepts: - uid [integer] (users id) Returns a list: - [ { "address": [string], "uid": [integer], "amount_active": [integer], "amount_frozen": [integer] }, ]
[ "Get", "users", "wallets", "by", "uid" ]
train
https://github.com/Robin8Put/pmes/blob/338bec94162098f05b75bad035417317e1252fd2/balance/handler.py#L794-L836
Robin8Put/pmes
balance/handler.py
Balance.confirmbalance
async def confirmbalance(self, *args, **kwargs): """ Confirm balance after trading Accepts: - message (signed dictionary): - "txid" - str - "coinid" - str - "amount" - int Returns: - "address" - str - "coinid" - str - "amount" - int - "...
python
async def confirmbalance(self, *args, **kwargs): """ Confirm balance after trading Accepts: - message (signed dictionary): - "txid" - str - "coinid" - str - "amount" - int Returns: - "address" - str - "coinid" - str - "amount" - int - "...
[ "async", "def", "confirmbalance", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Get data from request", "if", "kwargs", ".", "get", "(", "\"message\"", ")", ":", "kwargs", "=", "json", ".", "loads", "(", "kwargs", ".", "get", "("...
Confirm balance after trading Accepts: - message (signed dictionary): - "txid" - str - "coinid" - str - "amount" - int Returns: - "address" - str - "coinid" - str - "amount" - int - "uid" - int - "unconfirmed" - int (0 by defaul...
[ "Confirm", "balance", "after", "trading" ]
train
https://github.com/Robin8Put/pmes/blob/338bec94162098f05b75bad035417317e1252fd2/balance/handler.py#L840-L931
jantman/webhook2lambda2sqs
webhook2lambda2sqs/config.py
Config._validate_config
def _validate_config(self): """ Validate configuration file. :raises: RuntimeError """ # while set().issubset() is easier, we want to tell the user the names # of any invalid keys bad_keys = [] for k in self._config.keys(): if k not in self._ex...
python
def _validate_config(self): """ Validate configuration file. :raises: RuntimeError """ # while set().issubset() is easier, we want to tell the user the names # of any invalid keys bad_keys = [] for k in self._config.keys(): if k not in self._ex...
[ "def", "_validate_config", "(", "self", ")", ":", "# while set().issubset() is easier, we want to tell the user the names", "# of any invalid keys", "bad_keys", "=", "[", "]", "for", "k", "in", "self", ".", "_config", ".", "keys", "(", ")", ":", "if", "k", "not", ...
Validate configuration file. :raises: RuntimeError
[ "Validate", "configuration", "file", ".", ":", "raises", ":", "RuntimeError" ]
train
https://github.com/jantman/webhook2lambda2sqs/blob/c80c18d5a908ba8b8ee624dc3a977c633fba2b7c/webhook2lambda2sqs/config.py#L166-L250
jantman/webhook2lambda2sqs
webhook2lambda2sqs/config.py
Config._load_config
def _load_config(self, path): """ Load configuration from JSON :param path: path to the JSON config file :type path: str :return: config dictionary :rtype: dict """ p = os.path.abspath(os.path.expanduser(path)) logger.debug('Loading configuration ...
python
def _load_config(self, path): """ Load configuration from JSON :param path: path to the JSON config file :type path: str :return: config dictionary :rtype: dict """ p = os.path.abspath(os.path.expanduser(path)) logger.debug('Loading configuration ...
[ "def", "_load_config", "(", "self", ",", "path", ")", ":", "p", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "expanduser", "(", "path", ")", ")", "logger", ".", "debug", "(", "'Loading configuration from: %s'", ",", "p", ")", ...
Load configuration from JSON :param path: path to the JSON config file :type path: str :return: config dictionary :rtype: dict
[ "Load", "configuration", "from", "JSON" ]
train
https://github.com/jantman/webhook2lambda2sqs/blob/c80c18d5a908ba8b8ee624dc3a977c633fba2b7c/webhook2lambda2sqs/config.py#L264-L275
DC23/scriptabit
scriptabit/configuration.py
__add_min_max_value
def __add_min_max_value( parser, basename, default_min, default_max, initial, help_template): """ Generates parser entries for options with a min, max, and default value. Args: parser: the parser to use. basename: the base option name. Gen...
python
def __add_min_max_value( parser, basename, default_min, default_max, initial, help_template): """ Generates parser entries for options with a min, max, and default value. Args: parser: the parser to use. basename: the base option name. Gen...
[ "def", "__add_min_max_value", "(", "parser", ",", "basename", ",", "default_min", ",", "default_max", ",", "initial", ",", "help_template", ")", ":", "help_template", "=", "Template", "(", "help_template", ")", "parser", ".", "add", "(", "'--{0}-min'", ".", "f...
Generates parser entries for options with a min, max, and default value. Args: parser: the parser to use. basename: the base option name. Generated options will have flags --basename-min, --basename-max, and --basename. default_min: the default min value default_max:...
[ "Generates", "parser", "entries", "for", "options", "with", "a", "min", "max", "and", "default", "value", "." ]
train
https://github.com/DC23/scriptabit/blob/0d0cf71814e98954850891fa0887bdcffcf7147d/scriptabit/configuration.py#L21-L64
DC23/scriptabit
scriptabit/configuration.py
get_config_file
def get_config_file(basename): """ Looks for a configuration file in 3 locations: - the current directory - the user config directory (~/.config/scriptabit) - the version installed with the package (using setuptools resource API) Args: basename (str): The base filename. Re...
python
def get_config_file(basename): """ Looks for a configuration file in 3 locations: - the current directory - the user config directory (~/.config/scriptabit) - the version installed with the package (using setuptools resource API) Args: basename (str): The base filename. Re...
[ "def", "get_config_file", "(", "basename", ")", ":", "locations", "=", "[", "os", ".", "path", ".", "join", "(", "os", ".", "curdir", ",", "basename", ")", ",", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "expanduser", "(", "\"~\""...
Looks for a configuration file in 3 locations: - the current directory - the user config directory (~/.config/scriptabit) - the version installed with the package (using setuptools resource API) Args: basename (str): The base filename. Returns: str: The full path to th...
[ "Looks", "for", "a", "configuration", "file", "in", "3", "locations", ":" ]
train
https://github.com/DC23/scriptabit/blob/0d0cf71814e98954850891fa0887bdcffcf7147d/scriptabit/configuration.py#L66-L93
DC23/scriptabit
scriptabit/configuration.py
copy_default_config_to_user_directory
def copy_default_config_to_user_directory( basename, clobber=False, dst_dir='~/.config/scriptabit'): """ Copies the default configuration file into the user config directory. Args: basename (str): The base filename. clobber (bool): If True, the default will be written ev...
python
def copy_default_config_to_user_directory( basename, clobber=False, dst_dir='~/.config/scriptabit'): """ Copies the default configuration file into the user config directory. Args: basename (str): The base filename. clobber (bool): If True, the default will be written ev...
[ "def", "copy_default_config_to_user_directory", "(", "basename", ",", "clobber", "=", "False", ",", "dst_dir", "=", "'~/.config/scriptabit'", ")", ":", "dst_dir", "=", "os", ".", "path", ".", "expanduser", "(", "dst_dir", ")", "dst", "=", "os", ".", "path", ...
Copies the default configuration file into the user config directory. Args: basename (str): The base filename. clobber (bool): If True, the default will be written even if a user config already exists. dst_dir (str): The destination directory.
[ "Copies", "the", "default", "configuration", "file", "into", "the", "user", "config", "directory", "." ]
train
https://github.com/DC23/scriptabit/blob/0d0cf71814e98954850891fa0887bdcffcf7147d/scriptabit/configuration.py#L95-L117
DC23/scriptabit
scriptabit/configuration.py
get_configuration
def get_configuration(basename='scriptabit.cfg', parents=None): """Parses and returns the program configuration options, taken from a combination of ini-style config file, and command line arguments. Args: basename (str): The base filename. parents (list): A list of ArgumentParser objec...
python
def get_configuration(basename='scriptabit.cfg', parents=None): """Parses and returns the program configuration options, taken from a combination of ini-style config file, and command line arguments. Args: basename (str): The base filename. parents (list): A list of ArgumentParser objec...
[ "def", "get_configuration", "(", "basename", "=", "'scriptabit.cfg'", ",", "parents", "=", "None", ")", ":", "copy_default_config_to_user_directory", "(", "basename", ")", "parser", "=", "configargparse", ".", "ArgParser", "(", "formatter_class", "=", "configargparse"...
Parses and returns the program configuration options, taken from a combination of ini-style config file, and command line arguments. Args: basename (str): The base filename. parents (list): A list of ArgumentParser objects whose arguments should also be included in the configura...
[ "Parses", "and", "returns", "the", "program", "configuration", "options", "taken", "from", "a", "combination", "of", "ini", "-", "style", "config", "file", "and", "command", "line", "arguments", "." ]
train
https://github.com/DC23/scriptabit/blob/0d0cf71814e98954850891fa0887bdcffcf7147d/scriptabit/configuration.py#L119-L235
al4/flask-tokenauth
flask_tokenauth.py
TokenAuth.authenticate
def authenticate(self, token): """ Authenticate a token :param token: """ if self.verify_token_callback: # Specified verify function overrides below return self.verify_token_callback(token) if not token: return False name = self.toke...
python
def authenticate(self, token): """ Authenticate a token :param token: """ if self.verify_token_callback: # Specified verify function overrides below return self.verify_token_callback(token) if not token: return False name = self.toke...
[ "def", "authenticate", "(", "self", ",", "token", ")", ":", "if", "self", ".", "verify_token_callback", ":", "# Specified verify function overrides below", "return", "self", ".", "verify_token_callback", "(", "token", ")", "if", "not", "token", ":", "return", "Fal...
Authenticate a token :param token:
[ "Authenticate", "a", "token" ]
train
https://github.com/al4/flask-tokenauth/blob/71da088e79bbc01c4e047fc5c6b2719a24af026b/flask_tokenauth.py#L119-L135
jelmer/python-fastimport
fastimport/dates.py
parse_raw
def parse_raw(s, lineno=0): """Parse a date from a raw string. The format must be exactly "seconds-since-epoch offset-utc". See the spec for details. """ timestamp_str, timezone_str = s.split(b' ', 1) timestamp = float(timestamp_str) try: timezone = parse_tz(timezone_str) except...
python
def parse_raw(s, lineno=0): """Parse a date from a raw string. The format must be exactly "seconds-since-epoch offset-utc". See the spec for details. """ timestamp_str, timezone_str = s.split(b' ', 1) timestamp = float(timestamp_str) try: timezone = parse_tz(timezone_str) except...
[ "def", "parse_raw", "(", "s", ",", "lineno", "=", "0", ")", ":", "timestamp_str", ",", "timezone_str", "=", "s", ".", "split", "(", "b' '", ",", "1", ")", "timestamp", "=", "float", "(", "timestamp_str", ")", "try", ":", "timezone", "=", "parse_tz", ...
Parse a date from a raw string. The format must be exactly "seconds-since-epoch offset-utc". See the spec for details.
[ "Parse", "a", "date", "from", "a", "raw", "string", "." ]
train
https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/dates.py#L30-L42
jelmer/python-fastimport
fastimport/dates.py
parse_tz
def parse_tz(tz): """Parse a timezone specification in the [+|-]HHMM format. :return: the timezone offset in seconds. """ # from git_repository.py in bzr-git sign_byte = tz[0:1] # in python 3 b'+006'[0] would return an integer, # but b'+006'[0:1] return a new bytes string. if sign_byte ...
python
def parse_tz(tz): """Parse a timezone specification in the [+|-]HHMM format. :return: the timezone offset in seconds. """ # from git_repository.py in bzr-git sign_byte = tz[0:1] # in python 3 b'+006'[0] would return an integer, # but b'+006'[0:1] return a new bytes string. if sign_byte ...
[ "def", "parse_tz", "(", "tz", ")", ":", "# from git_repository.py in bzr-git", "sign_byte", "=", "tz", "[", "0", ":", "1", "]", "# in python 3 b'+006'[0] would return an integer,", "# but b'+006'[0:1] return a new bytes string.", "if", "sign_byte", "not", "in", "(", "b'+'...
Parse a timezone specification in the [+|-]HHMM format. :return: the timezone offset in seconds.
[ "Parse", "a", "timezone", "specification", "in", "the", "[", "+", "|", "-", "]", "HHMM", "format", "." ]
train
https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/dates.py#L45-L61
fchauvel/MAD
mad/parsing.py
p_definition_list
def p_definition_list(p): """ definition_list : definition definition_list | definition """ if len(p) == 3: p[0] = p[1] + p[2] elif len(p) == 2: p[0] = p[1] else: raise RuntimeError("Invalid production rules 'p_action_list'")
python
def p_definition_list(p): """ definition_list : definition definition_list | definition """ if len(p) == 3: p[0] = p[1] + p[2] elif len(p) == 2: p[0] = p[1] else: raise RuntimeError("Invalid production rules 'p_action_list'")
[ "def", "p_definition_list", "(", "p", ")", ":", "if", "len", "(", "p", ")", "==", "3", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "+", "p", "[", "2", "]", "elif", "len", "(", "p", ")", "==", "2", ":", "p", "[", "0", "]", "=", "...
definition_list : definition definition_list | definition
[ "definition_list", ":", "definition", "definition_list", "|", "definition" ]
train
https://github.com/fchauvel/MAD/blob/806d5174848b1a502e5c683894995602478c448b/mad/parsing.py#L122-L132
fchauvel/MAD
mad/parsing.py
p_define_service
def p_define_service(p): """ define_service : SERVICE IDENTIFIER OPEN_CURLY_BRACKET settings operation_list CLOSE_CURLY_BRACKET | SERVICE IDENTIFIER OPEN_CURLY_BRACKET operation_list CLOSE_CURLY_BRACKET """ if len(p) == 7: body = p[4] + p[5] else: body = p[4] p...
python
def p_define_service(p): """ define_service : SERVICE IDENTIFIER OPEN_CURLY_BRACKET settings operation_list CLOSE_CURLY_BRACKET | SERVICE IDENTIFIER OPEN_CURLY_BRACKET operation_list CLOSE_CURLY_BRACKET """ if len(p) == 7: body = p[4] + p[5] else: body = p[4] p...
[ "def", "p_define_service", "(", "p", ")", ":", "if", "len", "(", "p", ")", "==", "7", ":", "body", "=", "p", "[", "4", "]", "+", "p", "[", "5", "]", "else", ":", "body", "=", "p", "[", "4", "]", "p", "[", "0", "]", "=", "DefineService", "...
define_service : SERVICE IDENTIFIER OPEN_CURLY_BRACKET settings operation_list CLOSE_CURLY_BRACKET | SERVICE IDENTIFIER OPEN_CURLY_BRACKET operation_list CLOSE_CURLY_BRACKET
[ "define_service", ":", "SERVICE", "IDENTIFIER", "OPEN_CURLY_BRACKET", "settings", "operation_list", "CLOSE_CURLY_BRACKET", "|", "SERVICE", "IDENTIFIER", "OPEN_CURLY_BRACKET", "operation_list", "CLOSE_CURLY_BRACKET" ]
train
https://github.com/fchauvel/MAD/blob/806d5174848b1a502e5c683894995602478c448b/mad/parsing.py#L143-L152
fchauvel/MAD
mad/parsing.py
p_setting_list
def p_setting_list(p): """ setting_list : setting setting_list | setting """ if len(p) == 3: p[0] = merge_map(p[1], p[2]) elif len(p) == 2: p[0] = p[1] else: raise RuntimeError("Invalid production rules 'p_setting_list'")
python
def p_setting_list(p): """ setting_list : setting setting_list | setting """ if len(p) == 3: p[0] = merge_map(p[1], p[2]) elif len(p) == 2: p[0] = p[1] else: raise RuntimeError("Invalid production rules 'p_setting_list'")
[ "def", "p_setting_list", "(", "p", ")", ":", "if", "len", "(", "p", ")", "==", "3", ":", "p", "[", "0", "]", "=", "merge_map", "(", "p", "[", "1", "]", ",", "p", "[", "2", "]", ")", "elif", "len", "(", "p", ")", "==", "2", ":", "p", "["...
setting_list : setting setting_list | setting
[ "setting_list", ":", "setting", "setting_list", "|", "setting" ]
train
https://github.com/fchauvel/MAD/blob/806d5174848b1a502e5c683894995602478c448b/mad/parsing.py#L162-L172
fchauvel/MAD
mad/parsing.py
p_queue
def p_queue(p): """ queue : QUEUE COLON LIFO | QUEUE COLON FIFO """ if p[3] == "LIFO": p[0] = {"queue": LIFO()} elif p[3] == "FIFO": p[0] = {"queue": FIFO()} else: raise RuntimeError("Queue discipline '%s' is not supported!" % p[1])
python
def p_queue(p): """ queue : QUEUE COLON LIFO | QUEUE COLON FIFO """ if p[3] == "LIFO": p[0] = {"queue": LIFO()} elif p[3] == "FIFO": p[0] = {"queue": FIFO()} else: raise RuntimeError("Queue discipline '%s' is not supported!" % p[1])
[ "def", "p_queue", "(", "p", ")", ":", "if", "p", "[", "3", "]", "==", "\"LIFO\"", ":", "p", "[", "0", "]", "=", "{", "\"queue\"", ":", "LIFO", "(", ")", "}", "elif", "p", "[", "3", "]", "==", "\"FIFO\"", ":", "p", "[", "0", "]", "=", "{",...
queue : QUEUE COLON LIFO | QUEUE COLON FIFO
[ "queue", ":", "QUEUE", "COLON", "LIFO", "|", "QUEUE", "COLON", "FIFO" ]
train
https://github.com/fchauvel/MAD/blob/806d5174848b1a502e5c683894995602478c448b/mad/parsing.py#L184-L196
fchauvel/MAD
mad/parsing.py
p_throttling
def p_throttling(p): """ throttling : THROTTLING COLON NONE | THROTTLING COLON TAIL_DROP OPEN_BRACKET NUMBER CLOSE_BRACKET """ throttling = NoThrottlingSettings() if len(p) == 7: throttling = TailDropSettings(int(p[5])) p[0] = {"throttling": throttling}
python
def p_throttling(p): """ throttling : THROTTLING COLON NONE | THROTTLING COLON TAIL_DROP OPEN_BRACKET NUMBER CLOSE_BRACKET """ throttling = NoThrottlingSettings() if len(p) == 7: throttling = TailDropSettings(int(p[5])) p[0] = {"throttling": throttling}
[ "def", "p_throttling", "(", "p", ")", ":", "throttling", "=", "NoThrottlingSettings", "(", ")", "if", "len", "(", "p", ")", "==", "7", ":", "throttling", "=", "TailDropSettings", "(", "int", "(", "p", "[", "5", "]", ")", ")", "p", "[", "0", "]", ...
throttling : THROTTLING COLON NONE | THROTTLING COLON TAIL_DROP OPEN_BRACKET NUMBER CLOSE_BRACKET
[ "throttling", ":", "THROTTLING", "COLON", "NONE", "|", "THROTTLING", "COLON", "TAIL_DROP", "OPEN_BRACKET", "NUMBER", "CLOSE_BRACKET" ]
train
https://github.com/fchauvel/MAD/blob/806d5174848b1a502e5c683894995602478c448b/mad/parsing.py#L199-L207
fchauvel/MAD
mad/parsing.py
p_autoscaling_setting_list
def p_autoscaling_setting_list(p): """ autoscaling_setting_list : autoscaling_setting autoscaling_setting_list | autoscaling_setting """ if len(p) == 3: p[0] = merge_map(p[1], p[2]) elif len(p) == 2: p[0] = p[1] else: raise RuntimeError("Inval...
python
def p_autoscaling_setting_list(p): """ autoscaling_setting_list : autoscaling_setting autoscaling_setting_list | autoscaling_setting """ if len(p) == 3: p[0] = merge_map(p[1], p[2]) elif len(p) == 2: p[0] = p[1] else: raise RuntimeError("Inval...
[ "def", "p_autoscaling_setting_list", "(", "p", ")", ":", "if", "len", "(", "p", ")", "==", "3", ":", "p", "[", "0", "]", "=", "merge_map", "(", "p", "[", "1", "]", ",", "p", "[", "2", "]", ")", "elif", "len", "(", "p", ")", "==", "2", ":", ...
autoscaling_setting_list : autoscaling_setting autoscaling_setting_list | autoscaling_setting
[ "autoscaling_setting_list", ":", "autoscaling_setting", "autoscaling_setting_list", "|", "autoscaling_setting" ]
train
https://github.com/fchauvel/MAD/blob/806d5174848b1a502e5c683894995602478c448b/mad/parsing.py#L217-L227
fchauvel/MAD
mad/parsing.py
p_autoscaling_setting
def p_autoscaling_setting(p): """ autoscaling_setting : PERIOD COLON NUMBER | LIMITS COLON OPEN_SQUARE_BRACKET NUMBER COMMA NUMBER CLOSE_SQUARE_BRACKET """ if len(p) == 8: p[0] = {"limits": (int(p[4]), int(p[6]))} elif len(p) == 4: p[0] = {"period": int(p[3])}...
python
def p_autoscaling_setting(p): """ autoscaling_setting : PERIOD COLON NUMBER | LIMITS COLON OPEN_SQUARE_BRACKET NUMBER COMMA NUMBER CLOSE_SQUARE_BRACKET """ if len(p) == 8: p[0] = {"limits": (int(p[4]), int(p[6]))} elif len(p) == 4: p[0] = {"period": int(p[3])}...
[ "def", "p_autoscaling_setting", "(", "p", ")", ":", "if", "len", "(", "p", ")", "==", "8", ":", "p", "[", "0", "]", "=", "{", "\"limits\"", ":", "(", "int", "(", "p", "[", "4", "]", ")", ",", "int", "(", "p", "[", "6", "]", ")", ")", "}",...
autoscaling_setting : PERIOD COLON NUMBER | LIMITS COLON OPEN_SQUARE_BRACKET NUMBER COMMA NUMBER CLOSE_SQUARE_BRACKET
[ "autoscaling_setting", ":", "PERIOD", "COLON", "NUMBER", "|", "LIMITS", "COLON", "OPEN_SQUARE_BRACKET", "NUMBER", "COMMA", "NUMBER", "CLOSE_SQUARE_BRACKET" ]
train
https://github.com/fchauvel/MAD/blob/806d5174848b1a502e5c683894995602478c448b/mad/parsing.py#L230-L240
fchauvel/MAD
mad/parsing.py
p_operation_list
def p_operation_list(p): """ operation_list : define_operation operation_list | define_operation """ if len(p) == 3: p[0] = p[1] + p[2] elif len(p) == 2: p[0] = p[1] else: raise RuntimeError("Invalid production rules 'p_operation_list'")
python
def p_operation_list(p): """ operation_list : define_operation operation_list | define_operation """ if len(p) == 3: p[0] = p[1] + p[2] elif len(p) == 2: p[0] = p[1] else: raise RuntimeError("Invalid production rules 'p_operation_list'")
[ "def", "p_operation_list", "(", "p", ")", ":", "if", "len", "(", "p", ")", "==", "3", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "+", "p", "[", "2", "]", "elif", "len", "(", "p", ")", "==", "2", ":", "p", "[", "0", "]", "=", "p...
operation_list : define_operation operation_list | define_operation
[ "operation_list", ":", "define_operation", "operation_list", "|", "define_operation" ]
train
https://github.com/fchauvel/MAD/blob/806d5174848b1a502e5c683894995602478c448b/mad/parsing.py#L243-L253
fchauvel/MAD
mad/parsing.py
p_action_list
def p_action_list(p): """ action_list : action action_list | action """ if len(p) == 3: p[0] = p[1] + p[2] elif len(p) == 2: p[0] = p[1] else: raise RuntimeError("Invalid production rules 'p_action_list'")
python
def p_action_list(p): """ action_list : action action_list | action """ if len(p) == 3: p[0] = p[1] + p[2] elif len(p) == 2: p[0] = p[1] else: raise RuntimeError("Invalid production rules 'p_action_list'")
[ "def", "p_action_list", "(", "p", ")", ":", "if", "len", "(", "p", ")", "==", "3", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "+", "p", "[", "2", "]", "elif", "len", "(", "p", ")", "==", "2", ":", "p", "[", "0", "]", "=", "p", ...
action_list : action action_list | action
[ "action_list", ":", "action", "action_list", "|", "action" ]
train
https://github.com/fchauvel/MAD/blob/806d5174848b1a502e5c683894995602478c448b/mad/parsing.py#L270-L280
fchauvel/MAD
mad/parsing.py
p_fail
def p_fail(p): """ fail : FAIL NUMBER | FAIL """ if len(p) > 2: p[0] = Fail(float(p[2])) else: p[0] = Fail()
python
def p_fail(p): """ fail : FAIL NUMBER | FAIL """ if len(p) > 2: p[0] = Fail(float(p[2])) else: p[0] = Fail()
[ "def", "p_fail", "(", "p", ")", ":", "if", "len", "(", "p", ")", ">", "2", ":", "p", "[", "0", "]", "=", "Fail", "(", "float", "(", "p", "[", "2", "]", ")", ")", "else", ":", "p", "[", "0", "]", "=", "Fail", "(", ")" ]
fail : FAIL NUMBER | FAIL
[ "fail", ":", "FAIL", "NUMBER", "|", "FAIL" ]
train
https://github.com/fchauvel/MAD/blob/806d5174848b1a502e5c683894995602478c448b/mad/parsing.py#L302-L310
fchauvel/MAD
mad/parsing.py
p_query
def p_query(p): """ query : QUERY IDENTIFIER SLASH IDENTIFIER | QUERY IDENTIFIER SLASH IDENTIFIER OPEN_CURLY_BRACKET query_option_list CLOSE_CURLY_BRACKET """ parameters = {"service": p[2], "operation": p[4]} if len(p) > 5: parameters = merge_map(parameters, p[6]) p[0] = Query(...
python
def p_query(p): """ query : QUERY IDENTIFIER SLASH IDENTIFIER | QUERY IDENTIFIER SLASH IDENTIFIER OPEN_CURLY_BRACKET query_option_list CLOSE_CURLY_BRACKET """ parameters = {"service": p[2], "operation": p[4]} if len(p) > 5: parameters = merge_map(parameters, p[6]) p[0] = Query(...
[ "def", "p_query", "(", "p", ")", ":", "parameters", "=", "{", "\"service\"", ":", "p", "[", "2", "]", ",", "\"operation\"", ":", "p", "[", "4", "]", "}", "if", "len", "(", "p", ")", ">", "5", ":", "parameters", "=", "merge_map", "(", "parameters"...
query : QUERY IDENTIFIER SLASH IDENTIFIER | QUERY IDENTIFIER SLASH IDENTIFIER OPEN_CURLY_BRACKET query_option_list CLOSE_CURLY_BRACKET
[ "query", ":", "QUERY", "IDENTIFIER", "SLASH", "IDENTIFIER", "|", "QUERY", "IDENTIFIER", "SLASH", "IDENTIFIER", "OPEN_CURLY_BRACKET", "query_option_list", "CLOSE_CURLY_BRACKET" ]
train
https://github.com/fchauvel/MAD/blob/806d5174848b1a502e5c683894995602478c448b/mad/parsing.py#L312-L320
fchauvel/MAD
mad/parsing.py
p_query_option_list
def p_query_option_list(p): """ query_option_list : query_option COMMA query_option_list | query_option """ if len(p) == 2: p[0] = p[1] elif len(p) == 4: p[0] = merge_map(p[1], p[3]) else: raise RuntimeError("Invalid product rules for 'query_option_l...
python
def p_query_option_list(p): """ query_option_list : query_option COMMA query_option_list | query_option """ if len(p) == 2: p[0] = p[1] elif len(p) == 4: p[0] = merge_map(p[1], p[3]) else: raise RuntimeError("Invalid product rules for 'query_option_l...
[ "def", "p_query_option_list", "(", "p", ")", ":", "if", "len", "(", "p", ")", "==", "2", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "elif", "len", "(", "p", ")", "==", "4", ":", "p", "[", "0", "]", "=", "merge_map", "(", "p", "[", ...
query_option_list : query_option COMMA query_option_list | query_option
[ "query_option_list", ":", "query_option", "COMMA", "query_option_list", "|", "query_option" ]
train
https://github.com/fchauvel/MAD/blob/806d5174848b1a502e5c683894995602478c448b/mad/parsing.py#L323-L333
fchauvel/MAD
mad/parsing.py
p_invoke
def p_invoke(p): """ invoke : INVOKE IDENTIFIER SLASH IDENTIFIER | INVOKE IDENTIFIER SLASH IDENTIFIER OPEN_CURLY_BRACKET PRIORITY COLON NUMBER CLOSE_CURLY_BRACKET """ priority = None if len(p) > 5: priority = int(p[8]) p[0] = Trigger(p[2], p[4], priority)
python
def p_invoke(p): """ invoke : INVOKE IDENTIFIER SLASH IDENTIFIER | INVOKE IDENTIFIER SLASH IDENTIFIER OPEN_CURLY_BRACKET PRIORITY COLON NUMBER CLOSE_CURLY_BRACKET """ priority = None if len(p) > 5: priority = int(p[8]) p[0] = Trigger(p[2], p[4], priority)
[ "def", "p_invoke", "(", "p", ")", ":", "priority", "=", "None", "if", "len", "(", "p", ")", ">", "5", ":", "priority", "=", "int", "(", "p", "[", "8", "]", ")", "p", "[", "0", "]", "=", "Trigger", "(", "p", "[", "2", "]", ",", "p", "[", ...
invoke : INVOKE IDENTIFIER SLASH IDENTIFIER | INVOKE IDENTIFIER SLASH IDENTIFIER OPEN_CURLY_BRACKET PRIORITY COLON NUMBER CLOSE_CURLY_BRACKET
[ "invoke", ":", "INVOKE", "IDENTIFIER", "SLASH", "IDENTIFIER", "|", "INVOKE", "IDENTIFIER", "SLASH", "IDENTIFIER", "OPEN_CURLY_BRACKET", "PRIORITY", "COLON", "NUMBER", "CLOSE_CURLY_BRACKET" ]
train
https://github.com/fchauvel/MAD/blob/806d5174848b1a502e5c683894995602478c448b/mad/parsing.py#L358-L366
fchauvel/MAD
mad/parsing.py
p_retry
def p_retry(p): """ retry : RETRY OPEN_CURLY_BRACKET action_list CLOSE_CURLY_BRACKET | RETRY OPEN_BRACKET retry_option_list CLOSE_BRACKET OPEN_CURLY_BRACKET action_list CLOSE_CURLY_BRACKET """ if len(p) == 5: p[0] = Retry(p[3]) elif len(p) == 8: p[0] = Retry(p[6], **p[3]) ...
python
def p_retry(p): """ retry : RETRY OPEN_CURLY_BRACKET action_list CLOSE_CURLY_BRACKET | RETRY OPEN_BRACKET retry_option_list CLOSE_BRACKET OPEN_CURLY_BRACKET action_list CLOSE_CURLY_BRACKET """ if len(p) == 5: p[0] = Retry(p[3]) elif len(p) == 8: p[0] = Retry(p[6], **p[3]) ...
[ "def", "p_retry", "(", "p", ")", ":", "if", "len", "(", "p", ")", "==", "5", ":", "p", "[", "0", "]", "=", "Retry", "(", "p", "[", "3", "]", ")", "elif", "len", "(", "p", ")", "==", "8", ":", "p", "[", "0", "]", "=", "Retry", "(", "p"...
retry : RETRY OPEN_CURLY_BRACKET action_list CLOSE_CURLY_BRACKET | RETRY OPEN_BRACKET retry_option_list CLOSE_BRACKET OPEN_CURLY_BRACKET action_list CLOSE_CURLY_BRACKET
[ "retry", ":", "RETRY", "OPEN_CURLY_BRACKET", "action_list", "CLOSE_CURLY_BRACKET", "|", "RETRY", "OPEN_BRACKET", "retry_option_list", "CLOSE_BRACKET", "OPEN_CURLY_BRACKET", "action_list", "CLOSE_CURLY_BRACKET" ]
train
https://github.com/fchauvel/MAD/blob/806d5174848b1a502e5c683894995602478c448b/mad/parsing.py#L369-L379
fchauvel/MAD
mad/parsing.py
p_retry_option_list
def p_retry_option_list(p): """ retry_option_list : retry_option COMMA retry_option_list | retry_option """ if len(p) == 4: p[0] = merge_map(p[1], p[3]) elif len(p) == 2: p[0] = p[1] else: raise RuntimeError("Invalid production in 'retry_option_list'...
python
def p_retry_option_list(p): """ retry_option_list : retry_option COMMA retry_option_list | retry_option """ if len(p) == 4: p[0] = merge_map(p[1], p[3]) elif len(p) == 2: p[0] = p[1] else: raise RuntimeError("Invalid production in 'retry_option_list'...
[ "def", "p_retry_option_list", "(", "p", ")", ":", "if", "len", "(", "p", ")", "==", "4", ":", "p", "[", "0", "]", "=", "merge_map", "(", "p", "[", "1", "]", ",", "p", "[", "3", "]", ")", "elif", "len", "(", "p", ")", "==", "2", ":", "p", ...
retry_option_list : retry_option COMMA retry_option_list | retry_option
[ "retry_option_list", ":", "retry_option", "COMMA", "retry_option_list", "|", "retry_option" ]
train
https://github.com/fchauvel/MAD/blob/806d5174848b1a502e5c683894995602478c448b/mad/parsing.py#L382-L392
fchauvel/MAD
mad/parsing.py
p_retry_option
def p_retry_option(p): """ retry_option : LIMIT COLON NUMBER | DELAY COLON IDENTIFIER OPEN_BRACKET NUMBER CLOSE_BRACKET """ if len(p) == 4: p[0] = {"limit": int(p[3]) } elif len(p) == 7: p[0] = {"delay": Delay(int(p[5]), p[3])} else: raise RuntimeError("I...
python
def p_retry_option(p): """ retry_option : LIMIT COLON NUMBER | DELAY COLON IDENTIFIER OPEN_BRACKET NUMBER CLOSE_BRACKET """ if len(p) == 4: p[0] = {"limit": int(p[3]) } elif len(p) == 7: p[0] = {"delay": Delay(int(p[5]), p[3])} else: raise RuntimeError("I...
[ "def", "p_retry_option", "(", "p", ")", ":", "if", "len", "(", "p", ")", "==", "4", ":", "p", "[", "0", "]", "=", "{", "\"limit\"", ":", "int", "(", "p", "[", "3", "]", ")", "}", "elif", "len", "(", "p", ")", "==", "7", ":", "p", "[", "...
retry_option : LIMIT COLON NUMBER | DELAY COLON IDENTIFIER OPEN_BRACKET NUMBER CLOSE_BRACKET
[ "retry_option", ":", "LIMIT", "COLON", "NUMBER", "|", "DELAY", "COLON", "IDENTIFIER", "OPEN_BRACKET", "NUMBER", "CLOSE_BRACKET" ]
train
https://github.com/fchauvel/MAD/blob/806d5174848b1a502e5c683894995602478c448b/mad/parsing.py#L395-L405
Robin8Put/pmes
wallet_manager/withdraw_client/withdraw_cli.py
WithdrawClient.is_valid_address
def is_valid_address(self, *args, **kwargs): """ check address Accepts: - address [hex string] (withdrawal address in hex form) - coinid [string] (blockchain id (example: BTCTEST, LTCTEST)) Returns dictionary with following fields: - bool [Bool] ...
python
def is_valid_address(self, *args, **kwargs): """ check address Accepts: - address [hex string] (withdrawal address in hex form) - coinid [string] (blockchain id (example: BTCTEST, LTCTEST)) Returns dictionary with following fields: - bool [Bool] ...
[ "def", "is_valid_address", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "client", "=", "HTTPClient", "(", "self", ".", "withdraw_server_address", "+", "self", ".", "withdraw_endpoint", ")", "return", "client", ".", "request", "(", "'is...
check address Accepts: - address [hex string] (withdrawal address in hex form) - coinid [string] (blockchain id (example: BTCTEST, LTCTEST)) Returns dictionary with following fields: - bool [Bool]
[ "check", "address" ]
train
https://github.com/Robin8Put/pmes/blob/338bec94162098f05b75bad035417317e1252fd2/wallet_manager/withdraw_client/withdraw_cli.py#L92-L105
Robin8Put/pmes
wallet_manager/withdraw_client/withdraw_cli.py
WithdrawClient.register_token
def register_token(self, *args, **kwargs): """ Register token Accepts: - token_name [string] - contract_address [hex string] - blockchain [string] token's blockchain (QTUMTEST, ETH) Returns dictionary with following fields: - success [Boo...
python
def register_token(self, *args, **kwargs): """ Register token Accepts: - token_name [string] - contract_address [hex string] - blockchain [string] token's blockchain (QTUMTEST, ETH) Returns dictionary with following fields: - success [Boo...
[ "def", "register_token", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "client", "=", "HTTPClient", "(", "self", ".", "withdraw_server_address", "+", "self", ".", "withdraw_endpoint", ")", "if", "check_sig", ":", "return", "client", "."...
Register token Accepts: - token_name [string] - contract_address [hex string] - blockchain [string] token's blockchain (QTUMTEST, ETH) Returns dictionary with following fields: - success [Bool]
[ "Register", "token" ]
train
https://github.com/Robin8Put/pmes/blob/338bec94162098f05b75bad035417317e1252fd2/wallet_manager/withdraw_client/withdraw_cli.py#L107-L122
grahame/sedge
sedge/engine.py
Section.get_lines
def get_lines(self, config_access, visited_set): """ get the lines for this section visited_set is used to avoid visiting same section twice, if we've got a diamond in the @is setup """ if self in visited_set: return [] lines = self.lines.copy() ...
python
def get_lines(self, config_access, visited_set): """ get the lines for this section visited_set is used to avoid visiting same section twice, if we've got a diamond in the @is setup """ if self in visited_set: return [] lines = self.lines.copy() ...
[ "def", "get_lines", "(", "self", ",", "config_access", ",", "visited_set", ")", ":", "if", "self", "in", "visited_set", ":", "return", "[", "]", "lines", "=", "self", ".", "lines", ".", "copy", "(", ")", "visited_set", ".", "add", "(", "self", ")", "...
get the lines for this section visited_set is used to avoid visiting same section twice, if we've got a diamond in the @is setup
[ "get", "the", "lines", "for", "this", "section", "visited_set", "is", "used", "to", "avoid", "visiting", "same", "section", "twice", "if", "we", "ve", "got", "a", "diamond", "in", "the" ]
train
https://github.com/grahame/sedge/blob/60dc6a0c5ef3bf802fe48a2571a8524a6ea33878/sedge/engine.py#L49-L66
grahame/sedge
sedge/engine.py
Host.variable_iter
def variable_iter(self, base): """ returns iterator over the cross product of the variables for this stanza """ base_substs = dict(('<' + t + '>', u) for (t, u) in base.items()) substs = [] vals = [] for with_defn in self.with_exprs: substs.app...
python
def variable_iter(self, base): """ returns iterator over the cross product of the variables for this stanza """ base_substs = dict(('<' + t + '>', u) for (t, u) in base.items()) substs = [] vals = [] for with_defn in self.with_exprs: substs.app...
[ "def", "variable_iter", "(", "self", ",", "base", ")", ":", "base_substs", "=", "dict", "(", "(", "'<'", "+", "t", "+", "'>'", ",", "u", ")", "for", "(", "t", ",", "u", ")", "in", "base", ".", "items", "(", ")", ")", "substs", "=", "[", "]", ...
returns iterator over the cross product of the variables for this stanza
[ "returns", "iterator", "over", "the", "cross", "product", "of", "the", "variables", "for", "this", "stanza" ]
train
https://github.com/grahame/sedge/blob/60dc6a0c5ef3bf802fe48a2571a8524a6ea33878/sedge/engine.py#L159-L173
grahame/sedge
sedge/engine.py
Host.host_stanzas
def host_stanzas(self, config_access): """ returns a list of host definitions """ defn_lines = self.resolve_defn(config_access) for val_dict in self.variable_iter(config_access.get_variables()): subst = list(self.apply_substitutions(defn_lines, val_dict)) ...
python
def host_stanzas(self, config_access): """ returns a list of host definitions """ defn_lines = self.resolve_defn(config_access) for val_dict in self.variable_iter(config_access.get_variables()): subst = list(self.apply_substitutions(defn_lines, val_dict)) ...
[ "def", "host_stanzas", "(", "self", ",", "config_access", ")", ":", "defn_lines", "=", "self", ".", "resolve_defn", "(", "config_access", ")", "for", "val_dict", "in", "self", ".", "variable_iter", "(", "config_access", ".", "get_variables", "(", ")", ")", "...
returns a list of host definitions
[ "returns", "a", "list", "of", "host", "definitions" ]
train
https://github.com/grahame/sedge/blob/60dc6a0c5ef3bf802fe48a2571a8524a6ea33878/sedge/engine.py#L175-L184
grahame/sedge
sedge/engine.py
SedgeEngine.parse
def parse(self, fd): """very simple parser - but why would we want it to be complex?""" def resolve_args(args): # FIXME break this out, it's in common with the templating stuff elsewhere root = self.sections[0] val_dict = dict(('<' + t + '>', u) for (t, u) in root.ge...
python
def parse(self, fd): """very simple parser - but why would we want it to be complex?""" def resolve_args(args): # FIXME break this out, it's in common with the templating stuff elsewhere root = self.sections[0] val_dict = dict(('<' + t + '>', u) for (t, u) in root.ge...
[ "def", "parse", "(", "self", ",", "fd", ")", ":", "def", "resolve_args", "(", "args", ")", ":", "# FIXME break this out, it's in common with the templating stuff elsewhere", "root", "=", "self", ".", "sections", "[", "0", "]", "val_dict", "=", "dict", "(", "(", ...
very simple parser - but why would we want it to be complex?
[ "very", "simple", "parser", "-", "but", "why", "would", "we", "want", "it", "to", "be", "complex?" ]
train
https://github.com/grahame/sedge/blob/60dc6a0c5ef3bf802fe48a2571a8524a6ea33878/sedge/engine.py#L328-L464
Clinical-Genomics/housekeeper
housekeeper/cli/core.py
base
def base(context, config, database, root, log_level): """Housekeeper - Access your files!""" coloredlogs.install(level=log_level) context.obj = ruamel.yaml.safe_load(config) if config else {} context.obj['database'] = database if database else context.obj['database'] context.obj['root'] = root if ro...
python
def base(context, config, database, root, log_level): """Housekeeper - Access your files!""" coloredlogs.install(level=log_level) context.obj = ruamel.yaml.safe_load(config) if config else {} context.obj['database'] = database if database else context.obj['database'] context.obj['root'] = root if ro...
[ "def", "base", "(", "context", ",", "config", ",", "database", ",", "root", ",", "log_level", ")", ":", "coloredlogs", ".", "install", "(", "level", "=", "log_level", ")", "context", ".", "obj", "=", "ruamel", ".", "yaml", ".", "safe_load", "(", "confi...
Housekeeper - Access your files!
[ "Housekeeper", "-", "Access", "your", "files!" ]
train
https://github.com/Clinical-Genomics/housekeeper/blob/a7d10d327dc9f06274bdef5504ed1b9413f2c8c1/housekeeper/cli/core.py#L17-L22
dmgass/baseline
baseline/_script.py
Script.showpath
def showpath(path): """Return path in form most convenient for user to read. Return relative path when input path is within the current working directory, otherwise return same (absolute) path passed in. :param path: file system path :type path: str or unicode :returns:...
python
def showpath(path): """Return path in form most convenient for user to read. Return relative path when input path is within the current working directory, otherwise return same (absolute) path passed in. :param path: file system path :type path: str or unicode :returns:...
[ "def", "showpath", "(", "path", ")", ":", "try", ":", "retval", "=", "os", ".", "path", ".", "relpath", "(", "path", ",", "os", ".", "getcwd", "(", ")", ")", "except", "ValueError", ":", "retval", "=", "path", "else", ":", "if", "retval", ".", "s...
Return path in form most convenient for user to read. Return relative path when input path is within the current working directory, otherwise return same (absolute) path passed in. :param path: file system path :type path: str or unicode :returns: file system path :rtyp...
[ "Return", "path", "in", "form", "most", "convenient", "for", "user", "to", "read", "." ]
train
https://github.com/dmgass/baseline/blob/1f7988e8c9fafa83eb3a1ce73b1601d2afdbb2cd/baseline/_script.py#L58-L77
dmgass/baseline
baseline/_script.py
Script.lines
def lines(self): """List of file lines.""" if self._lines is None: with io.open(self.path, 'r', encoding='utf-8') as fh: self._lines = fh.read().split('\n') return self._lines
python
def lines(self): """List of file lines.""" if self._lines is None: with io.open(self.path, 'r', encoding='utf-8') as fh: self._lines = fh.read().split('\n') return self._lines
[ "def", "lines", "(", "self", ")", ":", "if", "self", ".", "_lines", "is", "None", ":", "with", "io", ".", "open", "(", "self", ".", "path", ",", "'r'", ",", "encoding", "=", "'utf-8'", ")", "as", "fh", ":", "self", ".", "_lines", "=", "fh", "."...
List of file lines.
[ "List", "of", "file", "lines", "." ]
train
https://github.com/dmgass/baseline/blob/1f7988e8c9fafa83eb3a1ce73b1601d2afdbb2cd/baseline/_script.py#L89-L95
dmgass/baseline
baseline/_script.py
Script.replace_baseline_repr
def replace_baseline_repr(self, linenum, update): """Replace individual baseline representation. :param int linenum: location of baseline representation :param str update: new baseline representation text (with delimiters) """ # use property to access lines to read them from fi...
python
def replace_baseline_repr(self, linenum, update): """Replace individual baseline representation. :param int linenum: location of baseline representation :param str update: new baseline representation text (with delimiters) """ # use property to access lines to read them from fi...
[ "def", "replace_baseline_repr", "(", "self", ",", "linenum", ",", "update", ")", ":", "# use property to access lines to read them from file if necessary", "lines", "=", "self", ".", "lines", "count", "=", "0", "delimiter", "=", "None", "for", "index", "in", "range"...
Replace individual baseline representation. :param int linenum: location of baseline representation :param str update: new baseline representation text (with delimiters)
[ "Replace", "individual", "baseline", "representation", "." ]
train
https://github.com/dmgass/baseline/blob/1f7988e8c9fafa83eb3a1ce73b1601d2afdbb2cd/baseline/_script.py#L106-L153
dmgass/baseline
baseline/_script.py
Script.update
def update(self): """Replace baseline representations previously registered for update.""" for linenum in reversed(sorted(self.updates)): self.replace_baseline_repr(linenum, self.updates[linenum]) if not self.TEST_MODE: path = '{}.update{}'.format(*os.path.splitext(self....
python
def update(self): """Replace baseline representations previously registered for update.""" for linenum in reversed(sorted(self.updates)): self.replace_baseline_repr(linenum, self.updates[linenum]) if not self.TEST_MODE: path = '{}.update{}'.format(*os.path.splitext(self....
[ "def", "update", "(", "self", ")", ":", "for", "linenum", "in", "reversed", "(", "sorted", "(", "self", ".", "updates", ")", ")", ":", "self", ".", "replace_baseline_repr", "(", "linenum", ",", "self", ".", "updates", "[", "linenum", "]", ")", "if", ...
Replace baseline representations previously registered for update.
[ "Replace", "baseline", "representations", "previously", "registered", "for", "update", "." ]
train
https://github.com/dmgass/baseline/blob/1f7988e8c9fafa83eb3a1ce73b1601d2afdbb2cd/baseline/_script.py#L155-L164
datalib/StatsCounter
statscounter/_stats.py
_sum
def _sum(data): """_sum(data [, start]) -> value Return a high-precision sum of the given numeric data. If optional argument ``start`` is given, it is added to the total. If ``data`` is empty, ``start`` (defaulting to 0) is returned. Examples -------- >>> _sum([3, 2.25, 4.5, -0.5, 1.0], 0.75...
python
def _sum(data): """_sum(data [, start]) -> value Return a high-precision sum of the given numeric data. If optional argument ``start`` is given, it is added to the total. If ``data`` is empty, ``start`` (defaulting to 0) is returned. Examples -------- >>> _sum([3, 2.25, 4.5, -0.5, 1.0], 0.75...
[ "def", "_sum", "(", "data", ")", ":", "data", "=", "iter", "(", "data", ")", "n", "=", "_first", "(", "data", ")", "if", "n", "is", "not", "None", ":", "data", "=", "chain", "(", "[", "n", "]", ",", "data", ")", "if", "isinstance", "(", "n", ...
_sum(data [, start]) -> value Return a high-precision sum of the given numeric data. If optional argument ``start`` is given, it is added to the total. If ``data`` is empty, ``start`` (defaulting to 0) is returned. Examples -------- >>> _sum([3, 2.25, 4.5, -0.5, 1.0], 0.75) 11.0 Some sou...
[ "_sum", "(", "data", "[", "start", "]", ")", "-", ">", "value", "Return", "a", "high", "-", "precision", "sum", "of", "the", "given", "numeric", "data", ".", "If", "optional", "argument", "start", "is", "given", "it", "is", "added", "to", "the", "tot...
train
https://github.com/datalib/StatsCounter/blob/5386c967808bbe451025af1d550f060cd7f86669/statscounter/_stats.py#L28-L59
datalib/StatsCounter
statscounter/_stats.py
mean
def mean(data): """Return the sample arithmetic mean of data. >>> mean([1, 2, 3, 4, 4]) 2.8 >>> from fractions import Fraction as F >>> mean([F(3, 7), F(1, 21), F(5, 3), F(1, 3)]) Fraction(13, 21) >>> from decimal import Decimal as D >>> mean([D("0.5"), D("0.75"), D("0.625"), D("0.375...
python
def mean(data): """Return the sample arithmetic mean of data. >>> mean([1, 2, 3, 4, 4]) 2.8 >>> from fractions import Fraction as F >>> mean([F(3, 7), F(1, 21), F(5, 3), F(1, 3)]) Fraction(13, 21) >>> from decimal import Decimal as D >>> mean([D("0.5"), D("0.75"), D("0.625"), D("0.375...
[ "def", "mean", "(", "data", ")", ":", "if", "iter", "(", "data", ")", "is", "data", ":", "data", "=", "list", "(", "data", ")", "n", "=", "len", "(", "data", ")", "if", "n", "<", "1", ":", "raise", "StatisticsError", "(", "'mean requires at least o...
Return the sample arithmetic mean of data. >>> mean([1, 2, 3, 4, 4]) 2.8 >>> from fractions import Fraction as F >>> mean([F(3, 7), F(1, 21), F(5, 3), F(1, 3)]) Fraction(13, 21) >>> from decimal import Decimal as D >>> mean([D("0.5"), D("0.75"), D("0.625"), D("0.375")]) Decimal('0.562...
[ "Return", "the", "sample", "arithmetic", "mean", "of", "data", "." ]
train
https://github.com/datalib/StatsCounter/blob/5386c967808bbe451025af1d550f060cd7f86669/statscounter/_stats.py#L64-L85
datalib/StatsCounter
statscounter/_stats.py
median_grouped
def median_grouped(data, interval=1): """"Return the 50th percentile (median) of grouped continuous data. >>> median_grouped([1, 2, 2, 3, 4, 4, 4, 4, 4, 5]) 3.7 >>> median_grouped([52, 52, 53, 54]) 52.5 This calculates the median as the 50th percentile, and should be used when your data is...
python
def median_grouped(data, interval=1): """"Return the 50th percentile (median) of grouped continuous data. >>> median_grouped([1, 2, 2, 3, 4, 4, 4, 4, 4, 5]) 3.7 >>> median_grouped([52, 52, 53, 54]) 52.5 This calculates the median as the 50th percentile, and should be used when your data is...
[ "def", "median_grouped", "(", "data", ",", "interval", "=", "1", ")", ":", "data", "=", "sorted", "(", "data", ")", "n", "=", "len", "(", "data", ")", "if", "n", "==", "0", ":", "raise", "StatisticsError", "(", "\"no median for empty data\"", ")", "eli...
Return the 50th percentile (median) of grouped continuous data. >>> median_grouped([1, 2, 2, 3, 4, 4, 4, 4, 4, 5]) 3.7 >>> median_grouped([52, 52, 53, 54]) 52.5 This calculates the median as the 50th percentile, and should be used when your data is continuous and grouped. In the above example,...
[ "Return", "the", "50th", "percentile", "(", "median", ")", "of", "grouped", "continuous", "data", "." ]
train
https://github.com/datalib/StatsCounter/blob/5386c967808bbe451025af1d550f060cd7f86669/statscounter/_stats.py#L154-L200
datalib/StatsCounter
statscounter/_stats.py
mode
def mode(data): """Return the most common data point from discrete or nominal data. ``mode`` assumes discrete data, and returns a single value. This is the standard treatment of the mode as commonly taught in schools: >>> mode([1, 1, 2, 3, 3, 3, 3, 4]) 3 This also works with nominal (non-nume...
python
def mode(data): """Return the most common data point from discrete or nominal data. ``mode`` assumes discrete data, and returns a single value. This is the standard treatment of the mode as commonly taught in schools: >>> mode([1, 1, 2, 3, 3, 3, 3, 4]) 3 This also works with nominal (non-nume...
[ "def", "mode", "(", "data", ")", ":", "# Generate a table of sorted (value, frequency) pairs.", "hist", "=", "collections", ".", "Counter", "(", "data", ")", "top", "=", "hist", ".", "most_common", "(", "2", ")", "if", "len", "(", "top", ")", "==", "1", ":...
Return the most common data point from discrete or nominal data. ``mode`` assumes discrete data, and returns a single value. This is the standard treatment of the mode as commonly taught in schools: >>> mode([1, 1, 2, 3, 3, 3, 3, 4]) 3 This also works with nominal (non-numeric) data: >>> mod...
[ "Return", "the", "most", "common", "data", "point", "from", "discrete", "or", "nominal", "data", "." ]
train
https://github.com/datalib/StatsCounter/blob/5386c967808bbe451025af1d550f060cd7f86669/statscounter/_stats.py#L203-L231
datalib/StatsCounter
statscounter/_stats.py
_ss
def _ss(data, c=None): """Return sum of square deviations of sequence data. If ``c`` is None, the mean is calculated in one pass, and the deviations from the mean are calculated in a second pass. Otherwise, deviations are calculated from ``c`` as given. Use the second case with care, as it can lead...
python
def _ss(data, c=None): """Return sum of square deviations of sequence data. If ``c`` is None, the mean is calculated in one pass, and the deviations from the mean are calculated in a second pass. Otherwise, deviations are calculated from ``c`` as given. Use the second case with care, as it can lead...
[ "def", "_ss", "(", "data", ",", "c", "=", "None", ")", ":", "if", "c", "is", "None", ":", "c", "=", "mean", "(", "data", ")", "#print(data)", "ss", "=", "_sum", "(", "(", "x", "-", "c", ")", "**", "2", "for", "x", "in", "data", ")", "# The ...
Return sum of square deviations of sequence data. If ``c`` is None, the mean is calculated in one pass, and the deviations from the mean are calculated in a second pass. Otherwise, deviations are calculated from ``c`` as given. Use the second case with care, as it can lead to garbage results.
[ "Return", "sum", "of", "square", "deviations", "of", "sequence", "data", "." ]
train
https://github.com/datalib/StatsCounter/blob/5386c967808bbe451025af1d550f060cd7f86669/statscounter/_stats.py#L247-L263
svven/summary
summary/url.py
unicode_to_str
def unicode_to_str(text, encoding=None, errors='strict'): """Return the str representation of text in the given encoding. Unlike .encode(encoding) this function can be applied directly to a str object without the risk of double-decoding problems (which can happen if you don't use the default 'ascii' enc...
python
def unicode_to_str(text, encoding=None, errors='strict'): """Return the str representation of text in the given encoding. Unlike .encode(encoding) this function can be applied directly to a str object without the risk of double-decoding problems (which can happen if you don't use the default 'ascii' enc...
[ "def", "unicode_to_str", "(", "text", ",", "encoding", "=", "None", ",", "errors", "=", "'strict'", ")", ":", "if", "encoding", "is", "None", ":", "encoding", "=", "'utf-8'", "if", "isinstance", "(", "text", ",", "unicode", ")", ":", "return", "text", ...
Return the str representation of text in the given encoding. Unlike .encode(encoding) this function can be applied directly to a str object without the risk of double-decoding problems (which can happen if you don't use the default 'ascii' encoding) This function has been copied from here: https://...
[ "Return", "the", "str", "representation", "of", "text", "in", "the", "given", "encoding", ".", "Unlike", ".", "encode", "(", "encoding", ")", "this", "function", "can", "be", "applied", "directly", "to", "a", "str", "object", "without", "the", "risk", "of"...
train
https://github.com/svven/summary/blob/3a6c43d2da08a7452f6b76d1813aa70ba36b8a54/summary/url.py#L55-L72
svven/summary
summary/url.py
url_is_from_any_domain
def url_is_from_any_domain(url, domains): """Return True if the url belongs to any of the given domains""" host = parse_url(url).netloc.lower() if host: return any(((host == d.lower()) or (host.endswith('.%s' % d.lower())) for d in domains)) else: return False
python
def url_is_from_any_domain(url, domains): """Return True if the url belongs to any of the given domains""" host = parse_url(url).netloc.lower() if host: return any(((host == d.lower()) or (host.endswith('.%s' % d.lower())) for d in domains)) else: return False
[ "def", "url_is_from_any_domain", "(", "url", ",", "domains", ")", ":", "host", "=", "parse_url", "(", "url", ")", ".", "netloc", ".", "lower", "(", ")", "if", "host", ":", "return", "any", "(", "(", "(", "host", "==", "d", ".", "lower", "(", ")", ...
Return True if the url belongs to any of the given domains
[ "Return", "True", "if", "the", "url", "belongs", "to", "any", "of", "the", "given", "domains" ]
train
https://github.com/svven/summary/blob/3a6c43d2da08a7452f6b76d1813aa70ba36b8a54/summary/url.py#L75-L82
svven/summary
summary/url.py
canonicalize_url
def canonicalize_url(url, keep_params=False, keep_fragments=False): """Canonicalize the given url by applying the following procedures: # a sort query arguments, first by key, then by value # b percent encode paths and query arguments. non-ASCII characters are # c percent-encoded using UTF-8 (RFC-3986)...
python
def canonicalize_url(url, keep_params=False, keep_fragments=False): """Canonicalize the given url by applying the following procedures: # a sort query arguments, first by key, then by value # b percent encode paths and query arguments. non-ASCII characters are # c percent-encoded using UTF-8 (RFC-3986)...
[ "def", "canonicalize_url", "(", "url", ",", "keep_params", "=", "False", ",", "keep_fragments", "=", "False", ")", ":", "if", "keep_params", ":", "# Preserve all query params", "parsed", "=", "extract", "(", "norm", "(", "url", ")", ")", "else", ":", "# Remo...
Canonicalize the given url by applying the following procedures: # a sort query arguments, first by key, then by value # b percent encode paths and query arguments. non-ASCII characters are # c percent-encoded using UTF-8 (RFC-3986) # d normalize all spaces (in query arguments) '+' (plus symbol) # ...
[ "Canonicalize", "the", "given", "url", "by", "applying", "the", "following", "procedures", ":" ]
train
https://github.com/svven/summary/blob/3a6c43d2da08a7452f6b76d1813aa70ba36b8a54/summary/url.py#L94-L130
svven/summary
summary/url.py
parse_url
def parse_url(url, encoding=None): """Return urlparsed url from the given argument (which could be an already parsed url) """ return url if isinstance(url, urlparse.ParseResult) else \ urlparse.urlparse(unicode_to_str(url, encoding))
python
def parse_url(url, encoding=None): """Return urlparsed url from the given argument (which could be an already parsed url) """ return url if isinstance(url, urlparse.ParseResult) else \ urlparse.urlparse(unicode_to_str(url, encoding))
[ "def", "parse_url", "(", "url", ",", "encoding", "=", "None", ")", ":", "return", "url", "if", "isinstance", "(", "url", ",", "urlparse", ".", "ParseResult", ")", "else", "urlparse", ".", "urlparse", "(", "unicode_to_str", "(", "url", ",", "encoding", ")...
Return urlparsed url from the given argument (which could be an already parsed url)
[ "Return", "urlparsed", "url", "from", "the", "given", "argument", "(", "which", "could", "be", "an", "already", "parsed", "url", ")" ]
train
https://github.com/svven/summary/blob/3a6c43d2da08a7452f6b76d1813aa70ba36b8a54/summary/url.py#L141-L146