id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
1,800
aichaos/rivescript-python
eg/json-server/server.py
reply
def reply(): """Fetch a reply from RiveScript. Parameters (JSON): * username * message * vars """ params = request.json if not params: return jsonify({ "status": "error", "error": "Request must be of the application/json type!", }) username =...
python
def reply(): params = request.json if not params: return jsonify({ "status": "error", "error": "Request must be of the application/json type!", }) username = params.get("username") message = params.get("message") uservars = params.get("vars", dict()) # ...
[ "def", "reply", "(", ")", ":", "params", "=", "request", ".", "json", "if", "not", "params", ":", "return", "jsonify", "(", "{", "\"status\"", ":", "\"error\"", ",", "\"error\"", ":", "\"Request must be of the application/json type!\"", ",", "}", ")", "usernam...
Fetch a reply from RiveScript. Parameters (JSON): * username * message * vars
[ "Fetch", "a", "reply", "from", "RiveScript", "." ]
b55c820cf02a194605fd66af1f070e239f84ed31
https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/eg/json-server/server.py#L24-L66
1,801
aichaos/rivescript-python
eg/json-server/server.py
index
def index(path=None): """On all other routes, just return an example `curl` command.""" payload = { "username": "soandso", "message": "Hello bot", "vars": { "name": "Soandso", } } return Response(r"""Usage: curl -i \ -H "Content-Type: application/json" \ ...
python
def index(path=None): payload = { "username": "soandso", "message": "Hello bot", "vars": { "name": "Soandso", } } return Response(r"""Usage: curl -i \ -H "Content-Type: application/json" \ -X POST -d '{}' \ http://localhost:5000/reply""".format(json.du...
[ "def", "index", "(", "path", "=", "None", ")", ":", "payload", "=", "{", "\"username\"", ":", "\"soandso\"", ",", "\"message\"", ":", "\"Hello bot\"", ",", "\"vars\"", ":", "{", "\"name\"", ":", "\"Soandso\"", ",", "}", "}", "return", "Response", "(", "r...
On all other routes, just return an example `curl` command.
[ "On", "all", "other", "routes", "just", "return", "an", "example", "curl", "command", "." ]
b55c820cf02a194605fd66af1f070e239f84ed31
https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/eg/json-server/server.py#L70-L83
1,802
aichaos/rivescript-python
contrib/redis/rivescript_redis.py
RedisSessionManager._key
def _key(self, username, frozen=False): """Translate a username into a key for Redis.""" if frozen: return self.frozen + username return self.prefix + username
python
def _key(self, username, frozen=False): if frozen: return self.frozen + username return self.prefix + username
[ "def", "_key", "(", "self", ",", "username", ",", "frozen", "=", "False", ")", ":", "if", "frozen", ":", "return", "self", ".", "frozen", "+", "username", "return", "self", ".", "prefix", "+", "username" ]
Translate a username into a key for Redis.
[ "Translate", "a", "username", "into", "a", "key", "for", "Redis", "." ]
b55c820cf02a194605fd66af1f070e239f84ed31
https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/contrib/redis/rivescript_redis.py#L42-L46
1,803
aichaos/rivescript-python
contrib/redis/rivescript_redis.py
RedisSessionManager._get_user
def _get_user(self, username): """Custom helper method to retrieve a user's data from Redis.""" data = self.client.get(self._key(username)) if data is None: return None return json.loads(data.decode())
python
def _get_user(self, username): data = self.client.get(self._key(username)) if data is None: return None return json.loads(data.decode())
[ "def", "_get_user", "(", "self", ",", "username", ")", ":", "data", "=", "self", ".", "client", ".", "get", "(", "self", ".", "_key", "(", "username", ")", ")", "if", "data", "is", "None", ":", "return", "None", "return", "json", ".", "loads", "(",...
Custom helper method to retrieve a user's data from Redis.
[ "Custom", "helper", "method", "to", "retrieve", "a", "user", "s", "data", "from", "Redis", "." ]
b55c820cf02a194605fd66af1f070e239f84ed31
https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/contrib/redis/rivescript_redis.py#L48-L53
1,804
aichaos/rivescript-python
rivescript/sorting.py
sort_trigger_set
def sort_trigger_set(triggers, exclude_previous=True, say=None): """Sort a group of triggers in optimal sorting order. The optimal sorting order is, briefly: * Atomic triggers (containing nothing but plain words and alternation groups) are on top, with triggers containing the most words coming ...
python
def sort_trigger_set(triggers, exclude_previous=True, say=None): if say is None: say = lambda x: x # KEEP IN MIND: the `triggers` array is composed of array elements of the form # ["trigger text", pointer to trigger data] # So this code will use e.g. `trig[0]` when referring to the trigger text...
[ "def", "sort_trigger_set", "(", "triggers", ",", "exclude_previous", "=", "True", ",", "say", "=", "None", ")", ":", "if", "say", "is", "None", ":", "say", "=", "lambda", "x", ":", "x", "# KEEP IN MIND: the `triggers` array is composed of array elements of the form"...
Sort a group of triggers in optimal sorting order. The optimal sorting order is, briefly: * Atomic triggers (containing nothing but plain words and alternation groups) are on top, with triggers containing the most words coming first. Triggers with equal word counts are sorted by length, and then ...
[ "Sort", "a", "group", "of", "triggers", "in", "optimal", "sorting", "order", "." ]
b55c820cf02a194605fd66af1f070e239f84ed31
https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/sorting.py#L52-L118
1,805
aichaos/rivescript-python
rivescript/sorting.py
sort_list
def sort_list(items): """Sort a simple list by number of words and length.""" # Track by number of words. track = {} def by_length(word1, word2): return len(word2) - len(word1) # Loop through each item. for item in items: # Count the words. cword = utils.word_count(ite...
python
def sort_list(items): # Track by number of words. track = {} def by_length(word1, word2): return len(word2) - len(word1) # Loop through each item. for item in items: # Count the words. cword = utils.word_count(item, all=True) if cword not in track: track...
[ "def", "sort_list", "(", "items", ")", ":", "# Track by number of words.", "track", "=", "{", "}", "def", "by_length", "(", "word1", ",", "word2", ")", ":", "return", "len", "(", "word2", ")", "-", "len", "(", "word1", ")", "# Loop through each item.", "fo...
Sort a simple list by number of words and length.
[ "Sort", "a", "simple", "list", "by", "number", "of", "words", "and", "length", "." ]
b55c820cf02a194605fd66af1f070e239f84ed31
https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/sorting.py#L120-L143
1,806
aichaos/rivescript-python
rivescript/rivescript.py
RiveScript.load_directory
def load_directory(self, directory, ext=None): """Load RiveScript documents from a directory. :param str directory: The directory of RiveScript documents to load replies from. :param []str ext: List of file extensions to consider as RiveScript documents. The default is `...
python
def load_directory(self, directory, ext=None): self._say("Loading from directory: " + directory) if ext is None: # Use the default extensions - .rive is preferable. ext = ['.rive', '.rs'] elif type(ext) == str: # Backwards compatibility for ext being a string...
[ "def", "load_directory", "(", "self", ",", "directory", ",", "ext", "=", "None", ")", ":", "self", ".", "_say", "(", "\"Loading from directory: \"", "+", "directory", ")", "if", "ext", "is", "None", ":", "# Use the default extensions - .rive is preferable.", "ext"...
Load RiveScript documents from a directory. :param str directory: The directory of RiveScript documents to load replies from. :param []str ext: List of file extensions to consider as RiveScript documents. The default is ``[".rive", ".rs"]``.
[ "Load", "RiveScript", "documents", "from", "a", "directory", "." ]
b55c820cf02a194605fd66af1f070e239f84ed31
https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L165-L192
1,807
aichaos/rivescript-python
rivescript/rivescript.py
RiveScript.load_file
def load_file(self, filename): """Load and parse a RiveScript document. :param str filename: The path to a RiveScript file. """ self._say("Loading file: " + filename) fh = codecs.open(filename, 'r', 'utf-8') lines = fh.readlines() fh.close() self._sa...
python
def load_file(self, filename): self._say("Loading file: " + filename) fh = codecs.open(filename, 'r', 'utf-8') lines = fh.readlines() fh.close() self._say("Parsing " + str(len(lines)) + " lines of code from " + filename) self._parse(filename, lines)
[ "def", "load_file", "(", "self", ",", "filename", ")", ":", "self", ".", "_say", "(", "\"Loading file: \"", "+", "filename", ")", "fh", "=", "codecs", ".", "open", "(", "filename", ",", "'r'", ",", "'utf-8'", ")", "lines", "=", "fh", ".", "readlines", ...
Load and parse a RiveScript document. :param str filename: The path to a RiveScript file.
[ "Load", "and", "parse", "a", "RiveScript", "document", "." ]
b55c820cf02a194605fd66af1f070e239f84ed31
https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L194-L206
1,808
aichaos/rivescript-python
rivescript/rivescript.py
RiveScript.stream
def stream(self, code): """Stream in RiveScript source code dynamically. :param code: Either a string containing RiveScript code or an array of lines of RiveScript code. """ self._say("Streaming code.") if type(code) in [str, text_type]: code = code.split...
python
def stream(self, code): self._say("Streaming code.") if type(code) in [str, text_type]: code = code.split("\n") self._parse("stream()", code)
[ "def", "stream", "(", "self", ",", "code", ")", ":", "self", ".", "_say", "(", "\"Streaming code.\"", ")", "if", "type", "(", "code", ")", "in", "[", "str", ",", "text_type", "]", ":", "code", "=", "code", ".", "split", "(", "\"\\n\"", ")", "self",...
Stream in RiveScript source code dynamically. :param code: Either a string containing RiveScript code or an array of lines of RiveScript code.
[ "Stream", "in", "RiveScript", "source", "code", "dynamically", "." ]
b55c820cf02a194605fd66af1f070e239f84ed31
https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L208-L217
1,809
aichaos/rivescript-python
rivescript/rivescript.py
RiveScript._parse
def _parse(self, fname, code): """Parse RiveScript code into memory. :param str fname: The arbitrary file name used for syntax reporting. :param []str code: Lines of RiveScript source code to parse. """ # Get the "abstract syntax tree" ast = self._parser.parse(fname, co...
python
def _parse(self, fname, code): # Get the "abstract syntax tree" ast = self._parser.parse(fname, code) # Get all of the "begin" type variables: global, var, sub, person, ... for kind, data in ast["begin"].items(): internal = getattr(self, "_" + kind) # The internal name for ...
[ "def", "_parse", "(", "self", ",", "fname", ",", "code", ")", ":", "# Get the \"abstract syntax tree\"", "ast", "=", "self", ".", "_parser", ".", "parse", "(", "fname", ",", "code", ")", "# Get all of the \"begin\" type variables: global, var, sub, person, ...", "for"...
Parse RiveScript code into memory. :param str fname: The arbitrary file name used for syntax reporting. :param []str code: Lines of RiveScript source code to parse.
[ "Parse", "RiveScript", "code", "into", "memory", "." ]
b55c820cf02a194605fd66af1f070e239f84ed31
https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L219-L281
1,810
aichaos/rivescript-python
rivescript/rivescript.py
RiveScript.deparse
def deparse(self): """Dump the in-memory RiveScript brain as a Python data structure. This would be useful, for example, to develop a user interface for editing RiveScript replies without having to edit the RiveScript source code directly. :return dict: JSON-serializable Python...
python
def deparse(self): # Data to return. result = { "begin": { "global": {}, "var": {}, "sub": {}, "person": {}, "array": {}, "triggers": [], }, "topics": {},...
[ "def", "deparse", "(", "self", ")", ":", "# Data to return.", "result", "=", "{", "\"begin\"", ":", "{", "\"global\"", ":", "{", "}", ",", "\"var\"", ":", "{", "}", ",", "\"sub\"", ":", "{", "}", ",", "\"person\"", ":", "{", "}", ",", "\"array\"", ...
Dump the in-memory RiveScript brain as a Python data structure. This would be useful, for example, to develop a user interface for editing RiveScript replies without having to edit the RiveScript source code directly. :return dict: JSON-serializable Python data structure containing the...
[ "Dump", "the", "in", "-", "memory", "RiveScript", "brain", "as", "a", "Python", "data", "structure", "." ]
b55c820cf02a194605fd66af1f070e239f84ed31
https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L283-L346
1,811
aichaos/rivescript-python
rivescript/rivescript.py
RiveScript.write
def write(self, fh, deparsed=None): """Write the currently parsed RiveScript data into a file. Pass either a file name (string) or a file handle object. This uses ``deparse()`` to dump a representation of the loaded data and writes it to the destination file. If you provide your own da...
python
def write(self, fh, deparsed=None): # Passed a string instead of a file handle? if type(fh) is str: fh = codecs.open(fh, "w", "utf-8") # Deparse the loaded data. if deparsed is None: deparsed = self.deparse() # Start at the beginning. fh.write("/...
[ "def", "write", "(", "self", ",", "fh", ",", "deparsed", "=", "None", ")", ":", "# Passed a string instead of a file handle?", "if", "type", "(", "fh", ")", "is", "str", ":", "fh", "=", "codecs", ".", "open", "(", "fh", ",", "\"w\"", ",", "\"utf-8\"", ...
Write the currently parsed RiveScript data into a file. Pass either a file name (string) or a file handle object. This uses ``deparse()`` to dump a representation of the loaded data and writes it to the destination file. If you provide your own data as the ``deparsed`` argument, it wil...
[ "Write", "the", "currently", "parsed", "RiveScript", "data", "into", "a", "file", "." ]
b55c820cf02a194605fd66af1f070e239f84ed31
https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L348-L448
1,812
aichaos/rivescript-python
rivescript/rivescript.py
RiveScript._write_triggers
def _write_triggers(self, fh, triggers, indent=""): """Write triggers to a file handle. Parameters: fh (file): file object. triggers (list): list of triggers to write. indent (str): indentation for each line. """ for trig in triggers: fh....
python
def _write_triggers(self, fh, triggers, indent=""): for trig in triggers: fh.write(indent + "+ " + self._write_wrapped(trig["trigger"], indent=indent) + "\n") d = trig if d.get("previous"): fh.write(indent + "% " + self._write_wrapped(d["previous"], indent=in...
[ "def", "_write_triggers", "(", "self", ",", "fh", ",", "triggers", ",", "indent", "=", "\"\"", ")", ":", "for", "trig", "in", "triggers", ":", "fh", ".", "write", "(", "indent", "+", "\"+ \"", "+", "self", ".", "_write_wrapped", "(", "trig", "[", "\"...
Write triggers to a file handle. Parameters: fh (file): file object. triggers (list): list of triggers to write. indent (str): indentation for each line.
[ "Write", "triggers", "to", "a", "file", "handle", "." ]
b55c820cf02a194605fd66af1f070e239f84ed31
https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L450-L475
1,813
aichaos/rivescript-python
rivescript/rivescript.py
RiveScript._write_wrapped
def _write_wrapped(self, line, sep=" ", indent="", width=78): """Word-wrap a line of RiveScript code for being written to a file. :param str line: The original line of text to word-wrap. :param str sep: The word separator. :param str indent: The indentation to use (as a set of spaces). ...
python
def _write_wrapped(self, line, sep=" ", indent="", width=78): words = line.split(sep) lines = [] line = "" buf = [] while len(words): buf.append(words.pop(0)) line = sep.join(buf) if len(line) > width: # Need to word wrap! ...
[ "def", "_write_wrapped", "(", "self", ",", "line", ",", "sep", "=", "\" \"", ",", "indent", "=", "\"\"", ",", "width", "=", "78", ")", ":", "words", "=", "line", ".", "split", "(", "sep", ")", "lines", "=", "[", "]", "line", "=", "\"\"", "buf", ...
Word-wrap a line of RiveScript code for being written to a file. :param str line: The original line of text to word-wrap. :param str sep: The word separator. :param str indent: The indentation to use (as a set of spaces). :param int width: The character width to constrain each line to. ...
[ "Word", "-", "wrap", "a", "line", "of", "RiveScript", "code", "for", "being", "written", "to", "a", "file", "." ]
b55c820cf02a194605fd66af1f070e239f84ed31
https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L477-L515
1,814
aichaos/rivescript-python
rivescript/rivescript.py
RiveScript.sort_replies
def sort_replies(self, thats=False): """Sort the loaded triggers in memory. After you have finished loading your RiveScript code, call this method to populate the various internal sort buffers. This is absolutely necessary for reply matching to work efficiently! """ # (R...
python
def sort_replies(self, thats=False): # (Re)initialize the sort cache. self._sorted["topics"] = {} self._sorted["thats"] = {} self._say("Sorting triggers...") # Loop through all the topics. for topic in self._topics.keys(): self._say("Analyzing topic " + topi...
[ "def", "sort_replies", "(", "self", ",", "thats", "=", "False", ")", ":", "# (Re)initialize the sort cache.", "self", ".", "_sorted", "[", "\"topics\"", "]", "=", "{", "}", "self", ".", "_sorted", "[", "\"thats\"", "]", "=", "{", "}", "self", ".", "_say"...
Sort the loaded triggers in memory. After you have finished loading your RiveScript code, call this method to populate the various internal sort buffers. This is absolutely necessary for reply matching to work efficiently!
[ "Sort", "the", "loaded", "triggers", "in", "memory", "." ]
b55c820cf02a194605fd66af1f070e239f84ed31
https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L521-L555
1,815
aichaos/rivescript-python
rivescript/rivescript.py
RiveScript.set_handler
def set_handler(self, language, obj): """Define a custom language handler for RiveScript objects. Pass in a ``None`` value for the object to delete an existing handler (for example, to prevent Python code from being able to be run by default). Look in the ``eg`` folder of the rivescrip...
python
def set_handler(self, language, obj): # Allow them to delete a handler too. if obj is None: if language in self._handlers: del self._handlers[language] else: self._handlers[language] = obj
[ "def", "set_handler", "(", "self", ",", "language", ",", "obj", ")", ":", "# Allow them to delete a handler too.", "if", "obj", "is", "None", ":", "if", "language", "in", "self", ".", "_handlers", ":", "del", "self", ".", "_handlers", "[", "language", "]", ...
Define a custom language handler for RiveScript objects. Pass in a ``None`` value for the object to delete an existing handler (for example, to prevent Python code from being able to be run by default). Look in the ``eg`` folder of the rivescript-python distribution for an example scri...
[ "Define", "a", "custom", "language", "handler", "for", "RiveScript", "objects", "." ]
b55c820cf02a194605fd66af1f070e239f84ed31
https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L561-L593
1,816
aichaos/rivescript-python
rivescript/rivescript.py
RiveScript.set_subroutine
def set_subroutine(self, name, code): """Define a Python object from your program. This is equivalent to having an object defined in the RiveScript code, except your Python code is defining it instead. :param str name: The name of the object macro. :param def code: A Python fun...
python
def set_subroutine(self, name, code): # Do we have a Python handler? if 'python' in self._handlers: self._handlers['python']._objects[name] = code self._objlangs[name] = 'python' else: self._warn("Can't set_subroutine: no Python object handler!")
[ "def", "set_subroutine", "(", "self", ",", "name", ",", "code", ")", ":", "# Do we have a Python handler?", "if", "'python'", "in", "self", ".", "_handlers", ":", "self", ".", "_handlers", "[", "'python'", "]", ".", "_objects", "[", "name", "]", "=", "code...
Define a Python object from your program. This is equivalent to having an object defined in the RiveScript code, except your Python code is defining it instead. :param str name: The name of the object macro. :param def code: A Python function with a method signature of ``(r...
[ "Define", "a", "Python", "object", "from", "your", "program", "." ]
b55c820cf02a194605fd66af1f070e239f84ed31
https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L595-L615
1,817
aichaos/rivescript-python
rivescript/rivescript.py
RiveScript.set_global
def set_global(self, name, value): """Set a global variable. Equivalent to ``! global`` in RiveScript code. :param str name: The name of the variable to set. :param str value: The value of the variable. Set this to ``None`` to delete the variable. """ if val...
python
def set_global(self, name, value): if value is None: # Unset the variable. if name in self._global: del self._global[name] self._global[name] = value
[ "def", "set_global", "(", "self", ",", "name", ",", "value", ")", ":", "if", "value", "is", "None", ":", "# Unset the variable.", "if", "name", "in", "self", ".", "_global", ":", "del", "self", ".", "_global", "[", "name", "]", "self", ".", "_global", ...
Set a global variable. Equivalent to ``! global`` in RiveScript code. :param str name: The name of the variable to set. :param str value: The value of the variable. Set this to ``None`` to delete the variable.
[ "Set", "a", "global", "variable", "." ]
b55c820cf02a194605fd66af1f070e239f84ed31
https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L617-L630
1,818
aichaos/rivescript-python
rivescript/rivescript.py
RiveScript.set_variable
def set_variable(self, name, value): """Set a bot variable. Equivalent to ``! var`` in RiveScript code. :param str name: The name of the variable to set. :param str value: The value of the variable. Set this to ``None`` to delete the variable. """ if value i...
python
def set_variable(self, name, value): if value is None: # Unset the variable. if name in self._var: del self._var[name] self._var[name] = value
[ "def", "set_variable", "(", "self", ",", "name", ",", "value", ")", ":", "if", "value", "is", "None", ":", "# Unset the variable.", "if", "name", "in", "self", ".", "_var", ":", "del", "self", ".", "_var", "[", "name", "]", "self", ".", "_var", "[", ...
Set a bot variable. Equivalent to ``! var`` in RiveScript code. :param str name: The name of the variable to set. :param str value: The value of the variable. Set this to ``None`` to delete the variable.
[ "Set", "a", "bot", "variable", "." ]
b55c820cf02a194605fd66af1f070e239f84ed31
https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L640-L653
1,819
aichaos/rivescript-python
rivescript/rivescript.py
RiveScript.set_substitution
def set_substitution(self, what, rep): """Set a substitution. Equivalent to ``! sub`` in RiveScript code. :param str what: The original text to replace. :param str rep: The text to replace it with. Set this to ``None`` to delete the substitution. """ if rep ...
python
def set_substitution(self, what, rep): if rep is None: # Unset the variable. if what in self._subs: del self._subs[what] self._subs[what] = rep
[ "def", "set_substitution", "(", "self", ",", "what", ",", "rep", ")", ":", "if", "rep", "is", "None", ":", "# Unset the variable.", "if", "what", "in", "self", ".", "_subs", ":", "del", "self", ".", "_subs", "[", "what", "]", "self", ".", "_subs", "[...
Set a substitution. Equivalent to ``! sub`` in RiveScript code. :param str what: The original text to replace. :param str rep: The text to replace it with. Set this to ``None`` to delete the substitution.
[ "Set", "a", "substitution", "." ]
b55c820cf02a194605fd66af1f070e239f84ed31
https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L663-L676
1,820
aichaos/rivescript-python
rivescript/rivescript.py
RiveScript.set_person
def set_person(self, what, rep): """Set a person substitution. Equivalent to ``! person`` in RiveScript code. :param str what: The original text to replace. :param str rep: The text to replace it with. Set this to ``None`` to delete the substitution. """ if ...
python
def set_person(self, what, rep): if rep is None: # Unset the variable. if what in self._person: del self._person[what] self._person[what] = rep
[ "def", "set_person", "(", "self", ",", "what", ",", "rep", ")", ":", "if", "rep", "is", "None", ":", "# Unset the variable.", "if", "what", "in", "self", ".", "_person", ":", "del", "self", ".", "_person", "[", "what", "]", "self", ".", "_person", "[...
Set a person substitution. Equivalent to ``! person`` in RiveScript code. :param str what: The original text to replace. :param str rep: The text to replace it with. Set this to ``None`` to delete the substitution.
[ "Set", "a", "person", "substitution", "." ]
b55c820cf02a194605fd66af1f070e239f84ed31
https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L678-L691
1,821
aichaos/rivescript-python
rivescript/rivescript.py
RiveScript.set_uservar
def set_uservar(self, user, name, value): """Set a variable for a user. This is like the ``<set>`` tag in RiveScript code. :param str user: The user ID to set a variable for. :param str name: The name of the variable to set. :param str value: The value to set there. """...
python
def set_uservar(self, user, name, value): self._session.set(user, {name: value})
[ "def", "set_uservar", "(", "self", ",", "user", ",", "name", ",", "value", ")", ":", "self", ".", "_session", ".", "set", "(", "user", ",", "{", "name", ":", "value", "}", ")" ]
Set a variable for a user. This is like the ``<set>`` tag in RiveScript code. :param str user: The user ID to set a variable for. :param str name: The name of the variable to set. :param str value: The value to set there.
[ "Set", "a", "variable", "for", "a", "user", "." ]
b55c820cf02a194605fd66af1f070e239f84ed31
https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L693-L702
1,822
aichaos/rivescript-python
rivescript/rivescript.py
RiveScript.set_uservars
def set_uservars(self, user, data=None): """Set many variables for a user, or set many variables for many users. This function can be called in two ways:: # Set a dict of variables for a single user. rs.set_uservars(username, vars) # Set a nested dict of variables ...
python
def set_uservars(self, user, data=None): # Check the parameters to see how we're being used. if type(user) is dict and data is None: # Setting many variables for many users. for uid, uservars in user.items(): if type(uservars) is not dict: rais...
[ "def", "set_uservars", "(", "self", ",", "user", ",", "data", "=", "None", ")", ":", "# Check the parameters to see how we're being used.", "if", "type", "(", "user", ")", "is", "dict", "and", "data", "is", "None", ":", "# Setting many variables for many users.", ...
Set many variables for a user, or set many variables for many users. This function can be called in two ways:: # Set a dict of variables for a single user. rs.set_uservars(username, vars) # Set a nested dict of variables for many users. rs.set_uservars(many_var...
[ "Set", "many", "variables", "for", "a", "user", "or", "set", "many", "variables", "for", "many", "users", "." ]
b55c820cf02a194605fd66af1f070e239f84ed31
https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L704-L769
1,823
aichaos/rivescript-python
rivescript/rivescript.py
RiveScript.get_uservar
def get_uservar(self, user, name): """Get a variable about a user. :param str user: The user ID to look up a variable for. :param str name: The name of the variable to get. :return: The user variable, or ``None`` or ``"undefined"``: * If the user has no data at all, this r...
python
def get_uservar(self, user, name): if name == '__lastmatch__': # Treat var `__lastmatch__` since it can't receive "undefined" value return self.last_match(user) else: return self._session.get(user, name)
[ "def", "get_uservar", "(", "self", ",", "user", ",", "name", ")", ":", "if", "name", "==", "'__lastmatch__'", ":", "# Treat var `__lastmatch__` since it can't receive \"undefined\" value", "return", "self", ".", "last_match", "(", "user", ")", "else", ":", "return",...
Get a variable about a user. :param str user: The user ID to look up a variable for. :param str name: The name of the variable to get. :return: The user variable, or ``None`` or ``"undefined"``: * If the user has no data at all, this returns ``None``. * If the user doe...
[ "Get", "a", "variable", "about", "a", "user", "." ]
b55c820cf02a194605fd66af1f070e239f84ed31
https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L771-L787
1,824
aichaos/rivescript-python
rivescript/rivescript.py
RiveScript.trigger_info
def trigger_info(self, trigger=None, dump=False): """Get information about a trigger. Pass in a raw trigger to find out what file name and line number it appeared at. This is useful for e.g. tracking down the location of the trigger last matched by the user via ``last_match()``. Returns...
python
def trigger_info(self, trigger=None, dump=False): if dump: return self._syntax response = None # Search the syntax tree for the trigger. for category in self._syntax: for topic in self._syntax[category]: if trigger in self._syntax[category][topic...
[ "def", "trigger_info", "(", "self", ",", "trigger", "=", "None", ",", "dump", "=", "False", ")", ":", "if", "dump", ":", "return", "self", ".", "_syntax", "response", "=", "None", "# Search the syntax tree for the trigger.", "for", "category", "in", "self", ...
Get information about a trigger. Pass in a raw trigger to find out what file name and line number it appeared at. This is useful for e.g. tracking down the location of the trigger last matched by the user via ``last_match()``. Returns a list of matching triggers, containing their topics...
[ "Get", "information", "about", "a", "trigger", "." ]
b55c820cf02a194605fd66af1f070e239f84ed31
https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L858-L905
1,825
aichaos/rivescript-python
rivescript/rivescript.py
RiveScript.current_user
def current_user(self): """Retrieve the user ID of the current user talking to your bot. This is mostly useful inside of a Python object macro to get the user ID of the person who caused the object macro to be invoked (i.e. to set a variable for that user from within the object). ...
python
def current_user(self): if self._brain._current_user is None: # They're doing it wrong. self._warn("current_user() is meant to be used from within a Python object macro!") return self._brain._current_user
[ "def", "current_user", "(", "self", ")", ":", "if", "self", ".", "_brain", ".", "_current_user", "is", "None", ":", "# They're doing it wrong.", "self", ".", "_warn", "(", "\"current_user() is meant to be used from within a Python object macro!\"", ")", "return", "self"...
Retrieve the user ID of the current user talking to your bot. This is mostly useful inside of a Python object macro to get the user ID of the person who caused the object macro to be invoked (i.e. to set a variable for that user from within the object). This will return ``None`` if use...
[ "Retrieve", "the", "user", "ID", "of", "the", "current", "user", "talking", "to", "your", "bot", "." ]
b55c820cf02a194605fd66af1f070e239f84ed31
https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L907-L920
1,826
aichaos/rivescript-python
rivescript/rivescript.py
RiveScript.reply
def reply(self, user, msg, errors_as_replies=True): """Fetch a reply from the RiveScript brain. Arguments: user (str): A unique user ID for the person requesting a reply. This could be e.g. a screen name or nickname. It's used internally to store user variabl...
python
def reply(self, user, msg, errors_as_replies=True): return self._brain.reply(user, msg, errors_as_replies)
[ "def", "reply", "(", "self", ",", "user", ",", "msg", ",", "errors_as_replies", "=", "True", ")", ":", "return", "self", ".", "_brain", ".", "reply", "(", "user", ",", "msg", ",", "errors_as_replies", ")" ]
Fetch a reply from the RiveScript brain. Arguments: user (str): A unique user ID for the person requesting a reply. This could be e.g. a screen name or nickname. It's used internally to store user variables (including topic and history), so if your bo...
[ "Fetch", "a", "reply", "from", "the", "RiveScript", "brain", "." ]
b55c820cf02a194605fd66af1f070e239f84ed31
https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L926-L947
1,827
aichaos/rivescript-python
rivescript/rivescript.py
RiveScript._precompile_substitution
def _precompile_substitution(self, kind, pattern): """Pre-compile the regexp for a substitution pattern. This will speed up the substitutions that happen at the beginning of the reply fetching process. With the default brain, this took the time for _substitute down from 0.08s to 0.02s ...
python
def _precompile_substitution(self, kind, pattern): if pattern not in self._regexc[kind]: qm = re.escape(pattern) self._regexc[kind][pattern] = { "qm": qm, "sub1": re.compile(r'^' + qm + r'$'), "sub2": re.compile(r'^' + qm + r'(\W+)'), ...
[ "def", "_precompile_substitution", "(", "self", ",", "kind", ",", "pattern", ")", ":", "if", "pattern", "not", "in", "self", ".", "_regexc", "[", "kind", "]", ":", "qm", "=", "re", ".", "escape", "(", "pattern", ")", "self", ".", "_regexc", "[", "kin...
Pre-compile the regexp for a substitution pattern. This will speed up the substitutions that happen at the beginning of the reply fetching process. With the default brain, this took the time for _substitute down from 0.08s to 0.02s :param str kind: One of ``sub``, ``person``. :...
[ "Pre", "-", "compile", "the", "regexp", "for", "a", "substitution", "pattern", "." ]
b55c820cf02a194605fd66af1f070e239f84ed31
https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L949-L967
1,828
aichaos/rivescript-python
rivescript/rivescript.py
RiveScript._precompile_regexp
def _precompile_regexp(self, trigger): """Precompile the regex for most triggers. If the trigger is non-atomic, and doesn't include dynamic tags like ``<bot>``, ``<get>``, ``<input>/<reply>`` or arrays, it can be precompiled and save time when matching. :param str trigger: The ...
python
def _precompile_regexp(self, trigger): if utils.is_atomic(trigger): return # Don't need a regexp for atomic triggers. # Check for dynamic tags. for tag in ["@", "<bot", "<get", "<input", "<reply"]: if tag in trigger: return # Can't precompile this trigg...
[ "def", "_precompile_regexp", "(", "self", ",", "trigger", ")", ":", "if", "utils", ".", "is_atomic", "(", "trigger", ")", ":", "return", "# Don't need a regexp for atomic triggers.", "# Check for dynamic tags.", "for", "tag", "in", "[", "\"@\"", ",", "\"<bot\"", "...
Precompile the regex for most triggers. If the trigger is non-atomic, and doesn't include dynamic tags like ``<bot>``, ``<get>``, ``<input>/<reply>`` or arrays, it can be precompiled and save time when matching. :param str trigger: The trigger text to attempt to precompile.
[ "Precompile", "the", "regex", "for", "most", "triggers", "." ]
b55c820cf02a194605fd66af1f070e239f84ed31
https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L969-L986
1,829
aichaos/rivescript-python
rivescript/rivescript.py
RiveScript._dump
def _dump(self): """For debugging, dump the entire data structure.""" pp = pprint.PrettyPrinter(indent=4) print("=== Variables ===") print("-- Globals --") pp.pprint(self._global) print("-- Bot vars --") pp.pprint(self._var) print("-- Substitutions --") ...
python
def _dump(self): pp = pprint.PrettyPrinter(indent=4) print("=== Variables ===") print("-- Globals --") pp.pprint(self._global) print("-- Bot vars --") pp.pprint(self._var) print("-- Substitutions --") pp.pprint(self._sub) print("-- Person Substitu...
[ "def", "_dump", "(", "self", ")", ":", "pp", "=", "pprint", ".", "PrettyPrinter", "(", "indent", "=", "4", ")", "print", "(", "\"=== Variables ===\"", ")", "print", "(", "\"-- Globals --\"", ")", "pp", ".", "pprint", "(", "self", ".", "_global", ")", "...
For debugging, dump the entire data structure.
[ "For", "debugging", "dump", "the", "entire", "data", "structure", "." ]
b55c820cf02a194605fd66af1f070e239f84ed31
https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L992-L1023
1,830
semente/django-smuggler
smuggler/views.py
dump_data
def dump_data(request): """Exports data from whole project. """ # Try to grab app_label data app_label = request.GET.get('app_label', []) if app_label: app_label = app_label.split(',') return dump_to_response(request, app_label=app_label, exclude=settings.SMUG...
python
def dump_data(request): # Try to grab app_label data app_label = request.GET.get('app_label', []) if app_label: app_label = app_label.split(',') return dump_to_response(request, app_label=app_label, exclude=settings.SMUGGLER_EXCLUDE_LIST)
[ "def", "dump_data", "(", "request", ")", ":", "# Try to grab app_label data", "app_label", "=", "request", ".", "GET", ".", "get", "(", "'app_label'", ",", "[", "]", ")", "if", "app_label", ":", "app_label", "=", "app_label", ".", "split", "(", "','", ")",...
Exports data from whole project.
[ "Exports", "data", "from", "whole", "project", "." ]
3be76f4e94e50e927a55a60741fac1a793df83de
https://github.com/semente/django-smuggler/blob/3be76f4e94e50e927a55a60741fac1a793df83de/smuggler/views.py#L63-L71
1,831
semente/django-smuggler
smuggler/views.py
dump_model_data
def dump_model_data(request, app_label, model_label): """Exports data from a model. """ return dump_to_response(request, '%s.%s' % (app_label, model_label), [], '-'.join((app_label, model_label)))
python
def dump_model_data(request, app_label, model_label): return dump_to_response(request, '%s.%s' % (app_label, model_label), [], '-'.join((app_label, model_label)))
[ "def", "dump_model_data", "(", "request", ",", "app_label", ",", "model_label", ")", ":", "return", "dump_to_response", "(", "request", ",", "'%s.%s'", "%", "(", "app_label", ",", "model_label", ")", ",", "[", "]", ",", "'-'", ".", "join", "(", "(", "app...
Exports data from a model.
[ "Exports", "data", "from", "a", "model", "." ]
3be76f4e94e50e927a55a60741fac1a793df83de
https://github.com/semente/django-smuggler/blob/3be76f4e94e50e927a55a60741fac1a793df83de/smuggler/views.py#L83-L87
1,832
mozilla/crontabber
crontabber/datetimeutil.py
timesince
def timesince(d, now): """ Taken from django.utils.timesince and modified to simpler requirements. Takes two datetime objects and returns the time between d and now as a nicely formatted string, e.g. "10 minutes". If d occurs after now, then "0 minutes" is returned. Units used are years, month...
python
def timesince(d, now): def pluralize(a, b): def inner(n): if n == 1: return a % n return b % n return inner def ugettext(s): return s chunks = ( (60 * 60 * 24 * 365, pluralize('%d year', '%d years')), (60 * 60 * 24 * 30, plura...
[ "def", "timesince", "(", "d", ",", "now", ")", ":", "def", "pluralize", "(", "a", ",", "b", ")", ":", "def", "inner", "(", "n", ")", ":", "if", "n", "==", "1", ":", "return", "a", "%", "n", "return", "b", "%", "n", "return", "inner", "def", ...
Taken from django.utils.timesince and modified to simpler requirements. Takes two datetime objects and returns the time between d and now as a nicely formatted string, e.g. "10 minutes". If d occurs after now, then "0 minutes" is returned. Units used are years, months, weeks, days, hours, and minutes....
[ "Taken", "from", "django", ".", "utils", ".", "timesince", "and", "modified", "to", "simpler", "requirements", "." ]
b510be349e71f165c1a9506db95bda0b88728f8b
https://github.com/mozilla/crontabber/blob/b510be349e71f165c1a9506db95bda0b88728f8b/crontabber/datetimeutil.py#L48-L117
1,833
mozilla/crontabber
crontabber/generic_app.py
respond_to_SIGHUP
def respond_to_SIGHUP(signal_number, frame, logger=None): """raise the KeyboardInterrupt which will cause the app to effectively shutdown, closing all it resources. Then, because it sets 'restart' to True, the app will reread all the configuration information, rebuild all of its structures and resource...
python
def respond_to_SIGHUP(signal_number, frame, logger=None): global restart restart = True if logger: logger.info('detected SIGHUP') raise KeyboardInterrupt
[ "def", "respond_to_SIGHUP", "(", "signal_number", ",", "frame", ",", "logger", "=", "None", ")", ":", "global", "restart", "restart", "=", "True", "if", "logger", ":", "logger", ".", "info", "(", "'detected SIGHUP'", ")", "raise", "KeyboardInterrupt" ]
raise the KeyboardInterrupt which will cause the app to effectively shutdown, closing all it resources. Then, because it sets 'restart' to True, the app will reread all the configuration information, rebuild all of its structures and resources and start running again
[ "raise", "the", "KeyboardInterrupt", "which", "will", "cause", "the", "app", "to", "effectively", "shutdown", "closing", "all", "it", "resources", ".", "Then", "because", "it", "sets", "restart", "to", "True", "the", "app", "will", "reread", "all", "the", "c...
b510be349e71f165c1a9506db95bda0b88728f8b
https://github.com/mozilla/crontabber/blob/b510be349e71f165c1a9506db95bda0b88728f8b/crontabber/generic_app.py#L195-L204
1,834
mozilla/crontabber
crontabber/transaction_executor.py
TransactionExecutorWithInfiniteBackoff.backoff_generator
def backoff_generator(self): """Generate a series of integers used for the length of the sleep between retries. It produces after exhausting the list, it repeats the last value from the list forever. This generator will never raise the StopIteration exception.""" for x in self....
python
def backoff_generator(self): for x in self.config.backoff_delays: yield x while True: yield self.config.backoff_delays[-1]
[ "def", "backoff_generator", "(", "self", ")", ":", "for", "x", "in", "self", ".", "config", ".", "backoff_delays", ":", "yield", "x", "while", "True", ":", "yield", "self", ".", "config", ".", "backoff_delays", "[", "-", "1", "]" ]
Generate a series of integers used for the length of the sleep between retries. It produces after exhausting the list, it repeats the last value from the list forever. This generator will never raise the StopIteration exception.
[ "Generate", "a", "series", "of", "integers", "used", "for", "the", "length", "of", "the", "sleep", "between", "retries", ".", "It", "produces", "after", "exhausting", "the", "list", "it", "repeats", "the", "last", "value", "from", "the", "list", "forever", ...
b510be349e71f165c1a9506db95bda0b88728f8b
https://github.com/mozilla/crontabber/blob/b510be349e71f165c1a9506db95bda0b88728f8b/crontabber/transaction_executor.py#L76-L84
1,835
mozilla/crontabber
crontabber/mixins.py
as_backfill_cron_app
def as_backfill_cron_app(cls): """a class decorator for Crontabber Apps. This decorator embues a CronApp with the parts necessary to be a backfill CronApp. It adds a main method that forces the base class to use a value of False for 'once'. That means it will do the work of a backfilling app. """...
python
def as_backfill_cron_app(cls): #---------------------------------------------------------------------- def main(self, function=None): return super(cls, self).main( function=function, once=False, ) cls.main = main cls._is_backfill_app = True return cls
[ "def", "as_backfill_cron_app", "(", "cls", ")", ":", "#----------------------------------------------------------------------", "def", "main", "(", "self", ",", "function", "=", "None", ")", ":", "return", "super", "(", "cls", ",", "self", ")", ".", "main", "(", ...
a class decorator for Crontabber Apps. This decorator embues a CronApp with the parts necessary to be a backfill CronApp. It adds a main method that forces the base class to use a value of False for 'once'. That means it will do the work of a backfilling app.
[ "a", "class", "decorator", "for", "Crontabber", "Apps", ".", "This", "decorator", "embues", "a", "CronApp", "with", "the", "parts", "necessary", "to", "be", "a", "backfill", "CronApp", ".", "It", "adds", "a", "main", "method", "that", "forces", "the", "bas...
b510be349e71f165c1a9506db95bda0b88728f8b
https://github.com/mozilla/crontabber/blob/b510be349e71f165c1a9506db95bda0b88728f8b/crontabber/mixins.py#L14-L28
1,836
mozilla/crontabber
crontabber/mixins.py
with_resource_connection_as_argument
def with_resource_connection_as_argument(resource_name): """a class decorator for Crontabber Apps. This decorator will a class a _run_proxy method that passes a databsase connection as a context manager into the CronApp's run method. The connection will automatically be closed when the ConApp's run me...
python
def with_resource_connection_as_argument(resource_name): connection_factory_attr_name = '%s_connection_factory' % resource_name def class_decorator(cls): def _run_proxy(self, *args, **kwargs): factory = getattr(self, connection_factory_attr_name) with factory() as connection: ...
[ "def", "with_resource_connection_as_argument", "(", "resource_name", ")", ":", "connection_factory_attr_name", "=", "'%s_connection_factory'", "%", "resource_name", "def", "class_decorator", "(", "cls", ")", ":", "def", "_run_proxy", "(", "self", ",", "*", "args", ","...
a class decorator for Crontabber Apps. This decorator will a class a _run_proxy method that passes a databsase connection as a context manager into the CronApp's run method. The connection will automatically be closed when the ConApp's run method ends. In order for this dectorator to function properl...
[ "a", "class", "decorator", "for", "Crontabber", "Apps", ".", "This", "decorator", "will", "a", "class", "a", "_run_proxy", "method", "that", "passes", "a", "databsase", "connection", "as", "a", "context", "manager", "into", "the", "CronApp", "s", "run", "met...
b510be349e71f165c1a9506db95bda0b88728f8b
https://github.com/mozilla/crontabber/blob/b510be349e71f165c1a9506db95bda0b88728f8b/crontabber/mixins.py#L118-L141
1,837
mozilla/crontabber
crontabber/mixins.py
with_single_transaction
def with_single_transaction(resource_name): """a class decorator for Crontabber Apps. This decorator will give a class a _run_proxy method that passes a databsase connection as a context manager into the CronApp's 'run' method. The run method may then use the connection at will knowing that after if '...
python
def with_single_transaction(resource_name): transaction_executor_attr_name = "%s_transaction_executor" % resource_name def class_decorator(cls): def _run_proxy(self, *args, **kwargs): getattr(self, transaction_executor_attr_name)( self.run, *args, ...
[ "def", "with_single_transaction", "(", "resource_name", ")", ":", "transaction_executor_attr_name", "=", "\"%s_transaction_executor\"", "%", "resource_name", "def", "class_decorator", "(", "cls", ")", ":", "def", "_run_proxy", "(", "self", ",", "*", "args", ",", "*"...
a class decorator for Crontabber Apps. This decorator will give a class a _run_proxy method that passes a databsase connection as a context manager into the CronApp's 'run' method. The run method may then use the connection at will knowing that after if 'run' exits normally, the connection will automa...
[ "a", "class", "decorator", "for", "Crontabber", "Apps", ".", "This", "decorator", "will", "give", "a", "class", "a", "_run_proxy", "method", "that", "passes", "a", "databsase", "connection", "as", "a", "context", "manager", "into", "the", "CronApp", "s", "ru...
b510be349e71f165c1a9506db95bda0b88728f8b
https://github.com/mozilla/crontabber/blob/b510be349e71f165c1a9506db95bda0b88728f8b/crontabber/mixins.py#L145-L169
1,838
mozilla/crontabber
crontabber/mixins.py
with_subprocess
def with_subprocess(cls): """a class decorator for Crontabber Apps. This decorator gives the CronApp a _run_proxy method that will execute the cron app as a single PG transaction. Commit and Rollback are automatic. The cron app should do no transaction management of its own. The cron app should be s...
python
def with_subprocess(cls): def run_process(self, command, input=None): """ Run the command and return a tuple of three things. 1. exit code - an integer number 2. stdout - all output that was sent to stdout 2. stderr - all output that was sent to stderr """ if...
[ "def", "with_subprocess", "(", "cls", ")", ":", "def", "run_process", "(", "self", ",", "command", ",", "input", "=", "None", ")", ":", "\"\"\"\n Run the command and return a tuple of three things.\n\n 1. exit code - an integer number\n 2. stdout - all output...
a class decorator for Crontabber Apps. This decorator gives the CronApp a _run_proxy method that will execute the cron app as a single PG transaction. Commit and Rollback are automatic. The cron app should do no transaction management of its own. The cron app should be short so that the transaction ...
[ "a", "class", "decorator", "for", "Crontabber", "Apps", ".", "This", "decorator", "gives", "the", "CronApp", "a", "_run_proxy", "method", "that", "will", "execute", "the", "cron", "app", "as", "a", "single", "PG", "transaction", ".", "Commit", "and", "Rollba...
b510be349e71f165c1a9506db95bda0b88728f8b
https://github.com/mozilla/crontabber/blob/b510be349e71f165c1a9506db95bda0b88728f8b/crontabber/mixins.py#L173-L201
1,839
mozilla/crontabber
crontabber/app.py
JobStateDatabase.keys
def keys(self): """return a list of all app_names""" keys = [] for app_name, __ in self.items(): keys.append(app_name) return keys
python
def keys(self): keys = [] for app_name, __ in self.items(): keys.append(app_name) return keys
[ "def", "keys", "(", "self", ")", ":", "keys", "=", "[", "]", "for", "app_name", ",", "__", "in", "self", ".", "items", "(", ")", ":", "keys", ".", "append", "(", "app_name", ")", "return", "keys" ]
return a list of all app_names
[ "return", "a", "list", "of", "all", "app_names" ]
b510be349e71f165c1a9506db95bda0b88728f8b
https://github.com/mozilla/crontabber/blob/b510be349e71f165c1a9506db95bda0b88728f8b/crontabber/app.py#L257-L262
1,840
mozilla/crontabber
crontabber/app.py
JobStateDatabase.items
def items(self): """return all the app_names and their values as tuples""" sql = """ SELECT app_name, next_run, first_run, last_run, last_success, depends_on, error_count, ...
python
def items(self): sql = """ SELECT app_name, next_run, first_run, last_run, last_success, depends_on, error_count, last_error FROM crontabber""" columns ...
[ "def", "items", "(", "self", ")", ":", "sql", "=", "\"\"\"\n SELECT\n app_name,\n next_run,\n first_run,\n last_run,\n last_success,\n depends_on,\n error_count,\n last_...
return all the app_names and their values as tuples
[ "return", "all", "the", "app_names", "and", "their", "values", "as", "tuples" ]
b510be349e71f165c1a9506db95bda0b88728f8b
https://github.com/mozilla/crontabber/blob/b510be349e71f165c1a9506db95bda0b88728f8b/crontabber/app.py#L264-L286
1,841
mozilla/crontabber
crontabber/app.py
JobStateDatabase.values
def values(self): """return a list of all state values""" values = [] for __, data in self.items(): values.append(data) return values
python
def values(self): values = [] for __, data in self.items(): values.append(data) return values
[ "def", "values", "(", "self", ")", ":", "values", "=", "[", "]", "for", "__", ",", "data", "in", "self", ".", "items", "(", ")", ":", "values", ".", "append", "(", "data", ")", "return", "values" ]
return a list of all state values
[ "return", "a", "list", "of", "all", "state", "values" ]
b510be349e71f165c1a9506db95bda0b88728f8b
https://github.com/mozilla/crontabber/blob/b510be349e71f165c1a9506db95bda0b88728f8b/crontabber/app.py#L288-L293
1,842
mozilla/crontabber
crontabber/app.py
JobStateDatabase.pop
def pop(self, key, default=_marker): """remove the item by key If not default is specified, raise KeyError if nothing could be removed. Return 'default' if specified and nothing could be removed """ try: popped = self[key] del self[key] ...
python
def pop(self, key, default=_marker): try: popped = self[key] del self[key] return popped except KeyError: if default == _marker: raise return default
[ "def", "pop", "(", "self", ",", "key", ",", "default", "=", "_marker", ")", ":", "try", ":", "popped", "=", "self", "[", "key", "]", "del", "self", "[", "key", "]", "return", "popped", "except", "KeyError", ":", "if", "default", "==", "_marker", ":...
remove the item by key If not default is specified, raise KeyError if nothing could be removed. Return 'default' if specified and nothing could be removed
[ "remove", "the", "item", "by", "key", "If", "not", "default", "is", "specified", "raise", "KeyError", "if", "nothing", "could", "be", "removed", ".", "Return", "default", "if", "specified", "and", "nothing", "could", "be", "removed" ]
b510be349e71f165c1a9506db95bda0b88728f8b
https://github.com/mozilla/crontabber/blob/b510be349e71f165c1a9506db95bda0b88728f8b/crontabber/app.py#L451-L464
1,843
mozilla/crontabber
crontabber/app.py
CronTabberBase.reset_job
def reset_job(self, description): """remove the job from the state. if means that next time we run, this job will start over from scratch. """ class_list = self.config.crontabber.jobs.class_list class_list = self._reorder_class_list(class_list) for class_name, job_class i...
python
def reset_job(self, description): class_list = self.config.crontabber.jobs.class_list class_list = self._reorder_class_list(class_list) for class_name, job_class in class_list: if ( job_class.app_name == description or description == job_class.__module...
[ "def", "reset_job", "(", "self", ",", "description", ")", ":", "class_list", "=", "self", ".", "config", ".", "crontabber", ".", "jobs", ".", "class_list", "class_list", "=", "self", ".", "_reorder_class_list", "(", "class_list", ")", "for", "class_name", ",...
remove the job from the state. if means that next time we run, this job will start over from scratch.
[ "remove", "the", "job", "from", "the", "state", ".", "if", "means", "that", "next", "time", "we", "run", "this", "job", "will", "start", "over", "from", "scratch", "." ]
b510be349e71f165c1a9506db95bda0b88728f8b
https://github.com/mozilla/crontabber/blob/b510be349e71f165c1a9506db95bda0b88728f8b/crontabber/app.py#L987-L1004
1,844
mozilla/crontabber
crontabber/app.py
CronTabberBase.time_to_run
def time_to_run(self, class_, time_): """return true if it's time to run the job. This is true if there is no previous information about its last run or if the last time it ran and set its next_run to a date that is now past. """ app_name = class_.app_name try: ...
python
def time_to_run(self, class_, time_): app_name = class_.app_name try: info = self.job_state_database[app_name] except KeyError: if time_: h, m = [int(x) for x in time_.split(':')] # only run if this hour and minute is < now ...
[ "def", "time_to_run", "(", "self", ",", "class_", ",", "time_", ")", ":", "app_name", "=", "class_", ".", "app_name", "try", ":", "info", "=", "self", ".", "job_state_database", "[", "app_name", "]", "except", "KeyError", ":", "if", "time_", ":", "h", ...
return true if it's time to run the job. This is true if there is no previous information about its last run or if the last time it ran and set its next_run to a date that is now past.
[ "return", "true", "if", "it", "s", "time", "to", "run", "the", "job", ".", "This", "is", "true", "if", "there", "is", "no", "previous", "information", "about", "its", "last", "run", "or", "if", "the", "last", "time", "it", "ran", "and", "set", "its",...
b510be349e71f165c1a9506db95bda0b88728f8b
https://github.com/mozilla/crontabber/blob/b510be349e71f165c1a9506db95bda0b88728f8b/crontabber/app.py#L1195-L1232
1,845
mozilla/crontabber
crontabber/app.py
CronTabberBase.audit_ghosts
def audit_ghosts(self): """compare the list of configured jobs with the jobs in the state""" print_header = True for app_name in self._get_ghosts(): if print_header: print_header = False print ( "Found the following in the state dat...
python
def audit_ghosts(self): print_header = True for app_name in self._get_ghosts(): if print_header: print_header = False print ( "Found the following in the state database but not " "available as a configured job:" ...
[ "def", "audit_ghosts", "(", "self", ")", ":", "print_header", "=", "True", "for", "app_name", "in", "self", ".", "_get_ghosts", "(", ")", ":", "if", "print_header", ":", "print_header", "=", "False", "print", "(", "\"Found the following in the state database but n...
compare the list of configured jobs with the jobs in the state
[ "compare", "the", "list", "of", "configured", "jobs", "with", "the", "jobs", "in", "the", "state" ]
b510be349e71f165c1a9506db95bda0b88728f8b
https://github.com/mozilla/crontabber/blob/b510be349e71f165c1a9506db95bda0b88728f8b/crontabber/app.py#L1385-L1395
1,846
transceptor-technology/pyleri
pyleri/grammar.py
Grammar.export_js
def export_js( self, js_module_name=JS_MODULE_NAME, js_template=JS_ES6_IMPORT_EXPORT_TEMPLATE, js_indent=JS_INDENTATION): '''Export the grammar to a JavaScript file which can be used with the js-lrparsing module. Two templates are available: ...
python
def export_js( self, js_module_name=JS_MODULE_NAME, js_template=JS_ES6_IMPORT_EXPORT_TEMPLATE, js_indent=JS_INDENTATION): '''Export the grammar to a JavaScript file which can be used with the js-lrparsing module. Two templates are available: ...
[ "def", "export_js", "(", "self", ",", "js_module_name", "=", "JS_MODULE_NAME", ",", "js_template", "=", "JS_ES6_IMPORT_EXPORT_TEMPLATE", ",", "js_indent", "=", "JS_INDENTATION", ")", ":", "language", "=", "[", "]", "refs", "=", "[", "]", "classes", "=", "{", ...
Export the grammar to a JavaScript file which can be used with the js-lrparsing module. Two templates are available: Grammar.JS_WINDOW_TEMPLATE Grammar.JS_ES6_IMPORT_EXPORT_TEMPLATE (default)
[ "Export", "the", "grammar", "to", "a", "JavaScript", "file", "which", "can", "be", "used", "with", "the", "js", "-", "lrparsing", "module", "." ]
af754300d42a5a79bcdfc7852ee4cc75ce245f39
https://github.com/transceptor-technology/pyleri/blob/af754300d42a5a79bcdfc7852ee4cc75ce245f39/pyleri/grammar.py#L341-L402
1,847
transceptor-technology/pyleri
pyleri/grammar.py
Grammar.export_py
def export_py( self, py_module_name=PY_MODULE_NAME, py_template=PY_TEMPLATE, py_indent=PY_INDENTATION): '''Export the grammar to a python file which can be used with the pyleri module. This can be useful when python code if used to auto-create a gr...
python
def export_py( self, py_module_name=PY_MODULE_NAME, py_template=PY_TEMPLATE, py_indent=PY_INDENTATION): '''Export the grammar to a python file which can be used with the pyleri module. This can be useful when python code if used to auto-create a gr...
[ "def", "export_py", "(", "self", ",", "py_module_name", "=", "PY_MODULE_NAME", ",", "py_template", "=", "PY_TEMPLATE", ",", "py_indent", "=", "PY_INDENTATION", ")", ":", "language", "=", "[", "]", "classes", "=", "{", "'Grammar'", "}", "indent", "=", "0", ...
Export the grammar to a python file which can be used with the pyleri module. This can be useful when python code if used to auto-create a grammar and an export of the final result is required.
[ "Export", "the", "grammar", "to", "a", "python", "file", "which", "can", "be", "used", "with", "the", "pyleri", "module", ".", "This", "can", "be", "useful", "when", "python", "code", "if", "used", "to", "auto", "-", "create", "a", "grammar", "and", "a...
af754300d42a5a79bcdfc7852ee4cc75ce245f39
https://github.com/transceptor-technology/pyleri/blob/af754300d42a5a79bcdfc7852ee4cc75ce245f39/pyleri/grammar.py#L404-L450
1,848
transceptor-technology/pyleri
pyleri/grammar.py
Grammar.export_go
def export_go( self, go_template=GO_TEMPLATE, go_indent=GO_INDENTATION, go_package=GO_PACKAGE): '''Export the grammar to a Go file which can be used with the goleri module.''' language = [] enums = set() indent = 0 pattern ...
python
def export_go( self, go_template=GO_TEMPLATE, go_indent=GO_INDENTATION, go_package=GO_PACKAGE): '''Export the grammar to a Go file which can be used with the goleri module.''' language = [] enums = set() indent = 0 pattern ...
[ "def", "export_go", "(", "self", ",", "go_template", "=", "GO_TEMPLATE", ",", "go_indent", "=", "GO_INDENTATION", ",", "go_package", "=", "GO_PACKAGE", ")", ":", "language", "=", "[", "]", "enums", "=", "set", "(", ")", "indent", "=", "0", "pattern", "="...
Export the grammar to a Go file which can be used with the goleri module.
[ "Export", "the", "grammar", "to", "a", "Go", "file", "which", "can", "be", "used", "with", "the", "goleri", "module", "." ]
af754300d42a5a79bcdfc7852ee4cc75ce245f39
https://github.com/transceptor-technology/pyleri/blob/af754300d42a5a79bcdfc7852ee4cc75ce245f39/pyleri/grammar.py#L516-L564
1,849
transceptor-technology/pyleri
pyleri/grammar.py
Grammar.export_java
def export_java( self, java_template=JAVA_TEMPLATE, java_indent=JAVA_INDENTATION, java_package=JAVA_PACKAGE, is_public=True): '''Export the grammar to a Java file which can be used with the jleri module.''' language = [] enums ...
python
def export_java( self, java_template=JAVA_TEMPLATE, java_indent=JAVA_INDENTATION, java_package=JAVA_PACKAGE, is_public=True): '''Export the grammar to a Java file which can be used with the jleri module.''' language = [] enums ...
[ "def", "export_java", "(", "self", ",", "java_template", "=", "JAVA_TEMPLATE", ",", "java_indent", "=", "JAVA_INDENTATION", ",", "java_package", "=", "JAVA_PACKAGE", ",", "is_public", "=", "True", ")", ":", "language", "=", "[", "]", "enums", "=", "set", "("...
Export the grammar to a Java file which can be used with the jleri module.
[ "Export", "the", "grammar", "to", "a", "Java", "file", "which", "can", "be", "used", "with", "the", "jleri", "module", "." ]
af754300d42a5a79bcdfc7852ee4cc75ce245f39
https://github.com/transceptor-technology/pyleri/blob/af754300d42a5a79bcdfc7852ee4cc75ce245f39/pyleri/grammar.py#L566-L630
1,850
transceptor-technology/pyleri
pyleri/grammar.py
Grammar.parse
def parse(self, string): '''Parse some string to the Grammar. Returns a nodeResult with the following attributes: - is_valid: True when the string is successfully parsed by the Grammar. - pos: position in the string where parsing ended. (this is th...
python
def parse(self, string): '''Parse some string to the Grammar. Returns a nodeResult with the following attributes: - is_valid: True when the string is successfully parsed by the Grammar. - pos: position in the string where parsing ended. (this is th...
[ "def", "parse", "(", "self", ",", "string", ")", ":", "self", ".", "_string", "=", "string", "self", ".", "_expecting", "=", "Expecting", "(", ")", "self", ".", "_cached_kw_match", ".", "clear", "(", ")", "self", ".", "_len_string", "=", "len", "(", ...
Parse some string to the Grammar. Returns a nodeResult with the following attributes: - is_valid: True when the string is successfully parsed by the Grammar. - pos: position in the string where parsing ended. (this is the end of the string when is_valid is...
[ "Parse", "some", "string", "to", "the", "Grammar", "." ]
af754300d42a5a79bcdfc7852ee4cc75ce245f39
https://github.com/transceptor-technology/pyleri/blob/af754300d42a5a79bcdfc7852ee4cc75ce245f39/pyleri/grammar.py#L632-L678
1,851
cheind/tf-matplotlib
tfmpl/figure.py
figure_buffer
def figure_buffer(figs): '''Extract raw image buffer from matplotlib figure shaped as 1xHxWx3.''' assert len(figs) > 0, 'No figure buffers given. Forgot to return from draw call?' buffers = [] w, h = figs[0].canvas.get_width_height() for f in figs: wf, hf = f.canvas.get_width_height() ...
python
def figure_buffer(figs): '''Extract raw image buffer from matplotlib figure shaped as 1xHxWx3.''' assert len(figs) > 0, 'No figure buffers given. Forgot to return from draw call?' buffers = [] w, h = figs[0].canvas.get_width_height() for f in figs: wf, hf = f.canvas.get_width_height() ...
[ "def", "figure_buffer", "(", "figs", ")", ":", "assert", "len", "(", "figs", ")", ">", "0", ",", "'No figure buffers given. Forgot to return from draw call?'", "buffers", "=", "[", "]", "w", ",", "h", "=", "figs", "[", "0", "]", ".", "canvas", ".", "get_wi...
Extract raw image buffer from matplotlib figure shaped as 1xHxWx3.
[ "Extract", "raw", "image", "buffer", "from", "matplotlib", "figure", "shaped", "as", "1xHxWx3", "." ]
c6904d3d2d306d9a479c24fbcb1f674a57dafd0e
https://github.com/cheind/tf-matplotlib/blob/c6904d3d2d306d9a479c24fbcb1f674a57dafd0e/tfmpl/figure.py#L14-L24
1,852
cheind/tf-matplotlib
tfmpl/figure.py
figure_tensor
def figure_tensor(func, **tf_pyfunc_kwargs): '''Decorate matplotlib drawing routines. This dectorator is meant to decorate functions that return matplotlib figures. The decorated function has to have the following signature def decorated(*args, **kwargs) -> figure or iterable of figures w...
python
def figure_tensor(func, **tf_pyfunc_kwargs): '''Decorate matplotlib drawing routines. This dectorator is meant to decorate functions that return matplotlib figures. The decorated function has to have the following signature def decorated(*args, **kwargs) -> figure or iterable of figures w...
[ "def", "figure_tensor", "(", "func", ",", "*", "*", "tf_pyfunc_kwargs", ")", ":", "name", "=", "tf_pyfunc_kwargs", ".", "pop", "(", "'name'", ",", "func", ".", "__name__", ")", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "func_args", ",...
Decorate matplotlib drawing routines. This dectorator is meant to decorate functions that return matplotlib figures. The decorated function has to have the following signature def decorated(*args, **kwargs) -> figure or iterable of figures where `*args` can be any positional argument and `**k...
[ "Decorate", "matplotlib", "drawing", "routines", "." ]
c6904d3d2d306d9a479c24fbcb1f674a57dafd0e
https://github.com/cheind/tf-matplotlib/blob/c6904d3d2d306d9a479c24fbcb1f674a57dafd0e/tfmpl/figure.py#L27-L64
1,853
cheind/tf-matplotlib
tfmpl/figure.py
blittable_figure_tensor
def blittable_figure_tensor(func, init_func, **tf_pyfunc_kwargs): '''Decorate matplotlib drawing routines with blitting support. This dectorator is meant to decorate functions that return matplotlib figures. The decorated function has to have the following signature def decorated(*args, **kwargs) ...
python
def blittable_figure_tensor(func, init_func, **tf_pyfunc_kwargs): '''Decorate matplotlib drawing routines with blitting support. This dectorator is meant to decorate functions that return matplotlib figures. The decorated function has to have the following signature def decorated(*args, **kwargs) ...
[ "def", "blittable_figure_tensor", "(", "func", ",", "init_func", ",", "*", "*", "tf_pyfunc_kwargs", ")", ":", "name", "=", "tf_pyfunc_kwargs", ".", "pop", "(", "'name'", ",", "func", ".", "__name__", ")", "assert", "callable", "(", "init_func", ")", ",", "...
Decorate matplotlib drawing routines with blitting support. This dectorator is meant to decorate functions that return matplotlib figures. The decorated function has to have the following signature def decorated(*args, **kwargs) -> iterable of artists where `*args` can be any positional argum...
[ "Decorate", "matplotlib", "drawing", "routines", "with", "blitting", "support", "." ]
c6904d3d2d306d9a479c24fbcb1f674a57dafd0e
https://github.com/cheind/tf-matplotlib/blob/c6904d3d2d306d9a479c24fbcb1f674a57dafd0e/tfmpl/figure.py#L67-L139
1,854
cheind/tf-matplotlib
tfmpl/samples/mnist.py
draw_confusion_matrix
def draw_confusion_matrix(matrix): '''Draw confusion matrix for MNIST.''' fig = tfmpl.create_figure(figsize=(7,7)) ax = fig.add_subplot(111) ax.set_title('Confusion matrix for MNIST classification') tfmpl.plots.confusion_matrix.draw( ax, matrix, axis_labels=['Digit ' + str(x) fo...
python
def draw_confusion_matrix(matrix): '''Draw confusion matrix for MNIST.''' fig = tfmpl.create_figure(figsize=(7,7)) ax = fig.add_subplot(111) ax.set_title('Confusion matrix for MNIST classification') tfmpl.plots.confusion_matrix.draw( ax, matrix, axis_labels=['Digit ' + str(x) fo...
[ "def", "draw_confusion_matrix", "(", "matrix", ")", ":", "fig", "=", "tfmpl", ".", "create_figure", "(", "figsize", "=", "(", "7", ",", "7", ")", ")", "ax", "=", "fig", ".", "add_subplot", "(", "111", ")", "ax", ".", "set_title", "(", "'Confusion matri...
Draw confusion matrix for MNIST.
[ "Draw", "confusion", "matrix", "for", "MNIST", "." ]
c6904d3d2d306d9a479c24fbcb1f674a57dafd0e
https://github.com/cheind/tf-matplotlib/blob/c6904d3d2d306d9a479c24fbcb1f674a57dafd0e/tfmpl/samples/mnist.py#L24-L36
1,855
cheind/tf-matplotlib
tfmpl/plots/confusion_matrix.py
from_labels_and_predictions
def from_labels_and_predictions(labels, predictions, num_classes): '''Compute a confusion matrix from labels and predictions. A drop-in replacement for tf.confusion_matrix that works on CPU data and not tensors. Params ------ labels : array-like 1-D array of real labels for classi...
python
def from_labels_and_predictions(labels, predictions, num_classes): '''Compute a confusion matrix from labels and predictions. A drop-in replacement for tf.confusion_matrix that works on CPU data and not tensors. Params ------ labels : array-like 1-D array of real labels for classi...
[ "def", "from_labels_and_predictions", "(", "labels", ",", "predictions", ",", "num_classes", ")", ":", "assert", "len", "(", "labels", ")", "==", "len", "(", "predictions", ")", "cm", "=", "np", ".", "zeros", "(", "(", "num_classes", ",", "num_classes", ")...
Compute a confusion matrix from labels and predictions. A drop-in replacement for tf.confusion_matrix that works on CPU data and not tensors. Params ------ labels : array-like 1-D array of real labels for classification predicitions: array-like 1-D array of predicted label...
[ "Compute", "a", "confusion", "matrix", "from", "labels", "and", "predictions", ".", "A", "drop", "-", "in", "replacement", "for", "tf", ".", "confusion_matrix", "that", "works", "on", "CPU", "data", "and", "not", "tensors", "." ]
c6904d3d2d306d9a479c24fbcb1f674a57dafd0e
https://github.com/cheind/tf-matplotlib/blob/c6904d3d2d306d9a479c24fbcb1f674a57dafd0e/tfmpl/plots/confusion_matrix.py#L11-L35
1,856
cheind/tf-matplotlib
tfmpl/plots/confusion_matrix.py
draw
def draw(ax, cm, axis_labels=None, normalize=False): '''Plot a confusion matrix. Inspired by https://stackoverflow.com/questions/41617463/tensorflow-confusion-matrix-in-tensorboard Params ------ ax : axis Axis to plot on cm : NxN array Confusion matrix Kwargs -...
python
def draw(ax, cm, axis_labels=None, normalize=False): '''Plot a confusion matrix. Inspired by https://stackoverflow.com/questions/41617463/tensorflow-confusion-matrix-in-tensorboard Params ------ ax : axis Axis to plot on cm : NxN array Confusion matrix Kwargs -...
[ "def", "draw", "(", "ax", ",", "cm", ",", "axis_labels", "=", "None", ",", "normalize", "=", "False", ")", ":", "cm", "=", "np", ".", "asarray", "(", "cm", ")", "num_classes", "=", "cm", ".", "shape", "[", "0", "]", "if", "normalize", ":", "with"...
Plot a confusion matrix. Inspired by https://stackoverflow.com/questions/41617463/tensorflow-confusion-matrix-in-tensorboard Params ------ ax : axis Axis to plot on cm : NxN array Confusion matrix Kwargs ------ axis_labels : array-like Array of size N c...
[ "Plot", "a", "confusion", "matrix", "." ]
c6904d3d2d306d9a479c24fbcb1f674a57dafd0e
https://github.com/cheind/tf-matplotlib/blob/c6904d3d2d306d9a479c24fbcb1f674a57dafd0e/tfmpl/plots/confusion_matrix.py#L37-L98
1,857
cheind/tf-matplotlib
tfmpl/create.py
create_figure
def create_figure(*fig_args, **fig_kwargs): '''Create a single figure. Args and Kwargs are passed to `matplotlib.figure.Figure`. This routine is provided in order to avoid usage of pyplot which is stateful and not thread safe. As drawing routines in tf-matplotlib are called from py-funcs in th...
python
def create_figure(*fig_args, **fig_kwargs): '''Create a single figure. Args and Kwargs are passed to `matplotlib.figure.Figure`. This routine is provided in order to avoid usage of pyplot which is stateful and not thread safe. As drawing routines in tf-matplotlib are called from py-funcs in th...
[ "def", "create_figure", "(", "*", "fig_args", ",", "*", "*", "fig_kwargs", ")", ":", "fig", "=", "Figure", "(", "*", "fig_args", ",", "*", "*", "fig_kwargs", ")", "# Attach canvas", "FigureCanvas", "(", "fig", ")", "return", "fig" ]
Create a single figure. Args and Kwargs are passed to `matplotlib.figure.Figure`. This routine is provided in order to avoid usage of pyplot which is stateful and not thread safe. As drawing routines in tf-matplotlib are called from py-funcs in their respective thread, avoid usage of pyplot wh...
[ "Create", "a", "single", "figure", "." ]
c6904d3d2d306d9a479c24fbcb1f674a57dafd0e
https://github.com/cheind/tf-matplotlib/blob/c6904d3d2d306d9a479c24fbcb1f674a57dafd0e/tfmpl/create.py#L9-L23
1,858
cheind/tf-matplotlib
tfmpl/create.py
create_figures
def create_figures(n, *fig_args, **fig_kwargs): '''Create multiple figures. Args and Kwargs are passed to `matplotlib.figure.Figure`. This routine is provided in order to avoid usage of pyplot which is stateful and not thread safe. As drawing routines in tf-matplotlib are called from py-funcs ...
python
def create_figures(n, *fig_args, **fig_kwargs): '''Create multiple figures. Args and Kwargs are passed to `matplotlib.figure.Figure`. This routine is provided in order to avoid usage of pyplot which is stateful and not thread safe. As drawing routines in tf-matplotlib are called from py-funcs ...
[ "def", "create_figures", "(", "n", ",", "*", "fig_args", ",", "*", "*", "fig_kwargs", ")", ":", "return", "[", "create_figure", "(", "*", "fig_args", ",", "*", "*", "fig_kwargs", ")", "for", "_", "in", "range", "(", "n", ")", "]" ]
Create multiple figures. Args and Kwargs are passed to `matplotlib.figure.Figure`. This routine is provided in order to avoid usage of pyplot which is stateful and not thread safe. As drawing routines in tf-matplotlib are called from py-funcs in their respective thread, avoid usage of pyplot w...
[ "Create", "multiple", "figures", "." ]
c6904d3d2d306d9a479c24fbcb1f674a57dafd0e
https://github.com/cheind/tf-matplotlib/blob/c6904d3d2d306d9a479c24fbcb1f674a57dafd0e/tfmpl/create.py#L25-L35
1,859
cheind/tf-matplotlib
tfmpl/meta.py
vararg_decorator
def vararg_decorator(f): '''Decorator to handle variable argument decorators.''' @wraps(f) def decorator(*args, **kwargs): if len(args) == 1 and len(kwargs) == 0 and callable(args[0]): return f(args[0]) else: return lambda realf: f(realf, *args, **kwargs) return...
python
def vararg_decorator(f): '''Decorator to handle variable argument decorators.''' @wraps(f) def decorator(*args, **kwargs): if len(args) == 1 and len(kwargs) == 0 and callable(args[0]): return f(args[0]) else: return lambda realf: f(realf, *args, **kwargs) return...
[ "def", "vararg_decorator", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "decorator", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "args", ")", "==", "1", "and", "len", "(", "kwargs", ")", "==", "0", "and", ...
Decorator to handle variable argument decorators.
[ "Decorator", "to", "handle", "variable", "argument", "decorators", "." ]
c6904d3d2d306d9a479c24fbcb1f674a57dafd0e
https://github.com/cheind/tf-matplotlib/blob/c6904d3d2d306d9a479c24fbcb1f674a57dafd0e/tfmpl/meta.py#L11-L21
1,860
cheind/tf-matplotlib
tfmpl/meta.py
as_list
def as_list(x): '''Ensure `x` is of list type.''' if x is None: x = [] elif not isinstance(x, Sequence): x = [x] return list(x)
python
def as_list(x): '''Ensure `x` is of list type.''' if x is None: x = [] elif not isinstance(x, Sequence): x = [x] return list(x)
[ "def", "as_list", "(", "x", ")", ":", "if", "x", "is", "None", ":", "x", "=", "[", "]", "elif", "not", "isinstance", "(", "x", ",", "Sequence", ")", ":", "x", "=", "[", "x", "]", "return", "list", "(", "x", ")" ]
Ensure `x` is of list type.
[ "Ensure", "x", "is", "of", "list", "type", "." ]
c6904d3d2d306d9a479c24fbcb1f674a57dafd0e
https://github.com/cheind/tf-matplotlib/blob/c6904d3d2d306d9a479c24fbcb1f674a57dafd0e/tfmpl/meta.py#L40-L47
1,861
yakupadakli/python-unsplash
unsplash/photo.py
Photo.all
def all(self, page=1, per_page=10, order_by="latest"): """ Get a single page from the list of all photos. :param page [integer]: Page number to retrieve. (Optional; default: 1) :param per_page [integer]: Number of items per page. (Optional; default: 10) :param order_by [string]:...
python
def all(self, page=1, per_page=10, order_by="latest"): return self._all("/photos", page=page, per_page=per_page, order_by=order_by)
[ "def", "all", "(", "self", ",", "page", "=", "1", ",", "per_page", "=", "10", ",", "order_by", "=", "\"latest\"", ")", ":", "return", "self", ".", "_all", "(", "\"/photos\"", ",", "page", "=", "page", ",", "per_page", "=", "per_page", ",", "order_by"...
Get a single page from the list of all photos. :param page [integer]: Page number to retrieve. (Optional; default: 1) :param per_page [integer]: Number of items per page. (Optional; default: 10) :param order_by [string]: How to sort the photos. Optional. (Valid values: latest, oldest, p...
[ "Get", "a", "single", "page", "from", "the", "list", "of", "all", "photos", "." ]
6e43dce3225237e1b8111fd475fb98b1ea33972c
https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/photo.py#L34-L44
1,862
yakupadakli/python-unsplash
unsplash/photo.py
Photo.get
def get(self, photo_id, width=None, height=None, rect=None): """ Retrieve a single photo. Note: Supplying the optional w or h parameters will result in the custom photo URL being added to the 'urls' object: :param photo_id [string]: The photo’s ID. Required. :param widt...
python
def get(self, photo_id, width=None, height=None, rect=None): url = "/photos/%s" % photo_id params = { "w": width, "h": height, "rect": rect } result = self._get(url, params=params) return PhotoModel.parse(result)
[ "def", "get", "(", "self", ",", "photo_id", ",", "width", "=", "None", ",", "height", "=", "None", ",", "rect", "=", "None", ")", ":", "url", "=", "\"/photos/%s\"", "%", "photo_id", "params", "=", "{", "\"w\"", ":", "width", ",", "\"h\"", ":", "hei...
Retrieve a single photo. Note: Supplying the optional w or h parameters will result in the custom photo URL being added to the 'urls' object: :param photo_id [string]: The photo’s ID. Required. :param width [integer]: Image width in pixels. :param height [integer]: Image height...
[ "Retrieve", "a", "single", "photo", "." ]
6e43dce3225237e1b8111fd475fb98b1ea33972c
https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/photo.py#L58-L78
1,863
yakupadakli/python-unsplash
unsplash/photo.py
Photo.random
def random(self, count=1, **kwargs): """ Retrieve a single random photo, given optional filters. Note: If supplying multiple category ID’s, the resulting photos will be those that match all of the given categories, not ones that match any category. Note: You can’t use t...
python
def random(self, count=1, **kwargs): kwargs.update({"count": count}) orientation = kwargs.get("orientation", None) if orientation and orientation not in self.orientation_values: raise Exception() url = "/photos/random" result = self._get(url, params=kwargs) re...
[ "def", "random", "(", "self", ",", "count", "=", "1", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "{", "\"count\"", ":", "count", "}", ")", "orientation", "=", "kwargs", ".", "get", "(", "\"orientation\"", ",", "None", ")", "if...
Retrieve a single random photo, given optional filters. Note: If supplying multiple category ID’s, the resulting photos will be those that match all of the given categories, not ones that match any category. Note: You can’t use the collections and query parameters in the same request ...
[ "Retrieve", "a", "single", "random", "photo", "given", "optional", "filters", "." ]
6e43dce3225237e1b8111fd475fb98b1ea33972c
https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/photo.py#L111-L147
1,864
yakupadakli/python-unsplash
unsplash/photo.py
Photo.like
def like(self, photo_id): """ Like a photo on behalf of the logged-in user. This requires the 'write_likes' scope. Note: This action is idempotent; sending the POST request to a single photo multiple times has no additional effect. :param photo_id [string]: The photo’s ...
python
def like(self, photo_id): url = "/photos/%s/like" % photo_id result = self._post(url) return PhotoModel.parse(result)
[ "def", "like", "(", "self", ",", "photo_id", ")", ":", "url", "=", "\"/photos/%s/like\"", "%", "photo_id", "result", "=", "self", ".", "_post", "(", "url", ")", "return", "PhotoModel", ".", "parse", "(", "result", ")" ]
Like a photo on behalf of the logged-in user. This requires the 'write_likes' scope. Note: This action is idempotent; sending the POST request to a single photo multiple times has no additional effect. :param photo_id [string]: The photo’s ID. Required. :return: [Photo]: The Un...
[ "Like", "a", "photo", "on", "behalf", "of", "the", "logged", "-", "in", "user", ".", "This", "requires", "the", "write_likes", "scope", "." ]
6e43dce3225237e1b8111fd475fb98b1ea33972c
https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/photo.py#L179-L192
1,865
yakupadakli/python-unsplash
unsplash/search.py
Search.photos
def photos(self, query, page=1, per_page=10): """ Get a single page of photo results for a query. :param query [string]: Search terms. :param page [integer]: Page number to retrieve. (Optional; default: 1) :param per_page [integer]: Number of items per page. (Optional; default: ...
python
def photos(self, query, page=1, per_page=10): url = "/search/photos" data = self._search(url, query, page=page, per_page=per_page) data["results"] = PhotoModel.parse_list(data.get("results")) return data
[ "def", "photos", "(", "self", ",", "query", ",", "page", "=", "1", ",", "per_page", "=", "10", ")", ":", "url", "=", "\"/search/photos\"", "data", "=", "self", ".", "_search", "(", "url", ",", "query", ",", "page", "=", "page", ",", "per_page", "="...
Get a single page of photo results for a query. :param query [string]: Search terms. :param page [integer]: Page number to retrieve. (Optional; default: 1) :param per_page [integer]: Number of items per page. (Optional; default: 10) :return: [dict]: {u'total': 0, u'total_pages': 0, u're...
[ "Get", "a", "single", "page", "of", "photo", "results", "for", "a", "query", "." ]
6e43dce3225237e1b8111fd475fb98b1ea33972c
https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/search.py#L19-L31
1,866
yakupadakli/python-unsplash
unsplash/search.py
Search.collections
def collections(self, query, page=1, per_page=10): """ Get a single page of collection results for a query. :param query [string]: Search terms. :param page [integer]: Page number to retrieve. (Optional; default: 1) :param per_page [integer]: Number of items per page. (Optional;...
python
def collections(self, query, page=1, per_page=10): url = "/search/collections" data = self._search(url, query, page=page, per_page=per_page) data["results"] = CollectionModel.parse_list(data.get("results")) return data
[ "def", "collections", "(", "self", ",", "query", ",", "page", "=", "1", ",", "per_page", "=", "10", ")", ":", "url", "=", "\"/search/collections\"", "data", "=", "self", ".", "_search", "(", "url", ",", "query", ",", "page", "=", "page", ",", "per_pa...
Get a single page of collection results for a query. :param query [string]: Search terms. :param page [integer]: Page number to retrieve. (Optional; default: 1) :param per_page [integer]: Number of items per page. (Optional; default: 10) :return: [dict]: {u'total': 0, u'total_pages': 0,...
[ "Get", "a", "single", "page", "of", "collection", "results", "for", "a", "query", "." ]
6e43dce3225237e1b8111fd475fb98b1ea33972c
https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/search.py#L33-L45
1,867
yakupadakli/python-unsplash
unsplash/search.py
Search.users
def users(self, query, page=1, per_page=10): """ Get a single page of user results for a query. :param query [string]: Search terms. :param page [integer]: Page number to retrieve. (Optional; default: 1) :param per_page [integer]: Number of items per page. (Optional; default: 10...
python
def users(self, query, page=1, per_page=10): url = "/search/users" data = self._search(url, query, page=page, per_page=per_page) data["results"] = UserModel.parse_list(data.get("results")) return data
[ "def", "users", "(", "self", ",", "query", ",", "page", "=", "1", ",", "per_page", "=", "10", ")", ":", "url", "=", "\"/search/users\"", "data", "=", "self", ".", "_search", "(", "url", ",", "query", ",", "page", "=", "page", ",", "per_page", "=", ...
Get a single page of user results for a query. :param query [string]: Search terms. :param page [integer]: Page number to retrieve. (Optional; default: 1) :param per_page [integer]: Number of items per page. (Optional; default: 10) :return: [dict]: {u'total': 0, u'total_pages': 0, u'res...
[ "Get", "a", "single", "page", "of", "user", "results", "for", "a", "query", "." ]
6e43dce3225237e1b8111fd475fb98b1ea33972c
https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/search.py#L47-L59
1,868
yakupadakli/python-unsplash
unsplash/collection.py
Collection.all
def all(self, page=1, per_page=10): """ Get a single page from the list of all collections. :param page [integer]: Page number to retrieve. (Optional; default: 1) :param per_page [integer]: Number of items per page. (Optional; default: 10) :return: [Array]: A single page of the ...
python
def all(self, page=1, per_page=10): url = "/collections" result = self._all(url, page=page, per_page=per_page) return CollectionModel.parse_list(result)
[ "def", "all", "(", "self", ",", "page", "=", "1", ",", "per_page", "=", "10", ")", ":", "url", "=", "\"/collections\"", "result", "=", "self", ".", "_all", "(", "url", ",", "page", "=", "page", ",", "per_page", "=", "per_page", ")", "return", "Coll...
Get a single page from the list of all collections. :param page [integer]: Page number to retrieve. (Optional; default: 1) :param per_page [integer]: Number of items per page. (Optional; default: 10) :return: [Array]: A single page of the Collection list.
[ "Get", "a", "single", "page", "from", "the", "list", "of", "all", "collections", "." ]
6e43dce3225237e1b8111fd475fb98b1ea33972c
https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/collection.py#L29-L39
1,869
yakupadakli/python-unsplash
unsplash/collection.py
Collection.related
def related(self, collection_id): """ Retrieve a list of collections related to this one. :param collection_id [string]: The collection’s ID. Required. :return: [Array]: A single page of the Collection list. """ url = "/collections/%s/related" % collection_id res...
python
def related(self, collection_id): url = "/collections/%s/related" % collection_id result = self._get(url) return CollectionModel.parse_list(result)
[ "def", "related", "(", "self", ",", "collection_id", ")", ":", "url", "=", "\"/collections/%s/related\"", "%", "collection_id", "result", "=", "self", ".", "_get", "(", "url", ")", "return", "CollectionModel", ".", "parse_list", "(", "result", ")" ]
Retrieve a list of collections related to this one. :param collection_id [string]: The collection’s ID. Required. :return: [Array]: A single page of the Collection list.
[ "Retrieve", "a", "list", "of", "collections", "related", "to", "this", "one", "." ]
6e43dce3225237e1b8111fd475fb98b1ea33972c
https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/collection.py#L115-L124
1,870
yakupadakli/python-unsplash
unsplash/collection.py
Collection.create
def create(self, title, description=None, private=False): """ Create a new collection. This requires the 'write_collections' scope. :param title [string]: The title of the collection. (Required.) :param description [string]: The collection’s description. (Optional.) :par...
python
def create(self, title, description=None, private=False): url = "/collections" data = { "title": title, "description": description, "private": private } result = self._post(url, data=data) return CollectionModel.parse(result)
[ "def", "create", "(", "self", ",", "title", ",", "description", "=", "None", ",", "private", "=", "False", ")", ":", "url", "=", "\"/collections\"", "data", "=", "{", "\"title\"", ":", "title", ",", "\"description\"", ":", "description", ",", "\"private\""...
Create a new collection. This requires the 'write_collections' scope. :param title [string]: The title of the collection. (Required.) :param description [string]: The collection’s description. (Optional.) :param private [boolean]: Whether to make this collection private. (Optional; defa...
[ "Create", "a", "new", "collection", ".", "This", "requires", "the", "write_collections", "scope", "." ]
6e43dce3225237e1b8111fd475fb98b1ea33972c
https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/collection.py#L126-L143
1,871
yakupadakli/python-unsplash
unsplash/collection.py
Collection.update
def update(self, collection_id, title=None, description=None, private=False): """ Update an existing collection belonging to the logged-in user. This requires the 'write_collections' scope. :param collection_id [string]: The collection’s ID. Required. :param title [string]: The ...
python
def update(self, collection_id, title=None, description=None, private=False): url = "/collections/%s" % collection_id data = { "title": title, "description": description, "private": private } result = self._put(url, data=data) return Collection...
[ "def", "update", "(", "self", ",", "collection_id", ",", "title", "=", "None", ",", "description", "=", "None", ",", "private", "=", "False", ")", ":", "url", "=", "\"/collections/%s\"", "%", "collection_id", "data", "=", "{", "\"title\"", ":", "title", ...
Update an existing collection belonging to the logged-in user. This requires the 'write_collections' scope. :param collection_id [string]: The collection’s ID. Required. :param title [string]: The title of the collection. (Required.) :param description [string]: The collection’s descrip...
[ "Update", "an", "existing", "collection", "belonging", "to", "the", "logged", "-", "in", "user", ".", "This", "requires", "the", "write_collections", "scope", "." ]
6e43dce3225237e1b8111fd475fb98b1ea33972c
https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/collection.py#L145-L163
1,872
yakupadakli/python-unsplash
unsplash/stat.py
Stat.total
def total(self): """ Get a list of counts for all of Unsplash :return [Stat]: The Unsplash Stat. """ url = "/stats/total" result = self._get(url) return StatModel.parse(result)
python
def total(self): url = "/stats/total" result = self._get(url) return StatModel.parse(result)
[ "def", "total", "(", "self", ")", ":", "url", "=", "\"/stats/total\"", "result", "=", "self", ".", "_get", "(", "url", ")", "return", "StatModel", ".", "parse", "(", "result", ")" ]
Get a list of counts for all of Unsplash :return [Stat]: The Unsplash Stat.
[ "Get", "a", "list", "of", "counts", "for", "all", "of", "Unsplash" ]
6e43dce3225237e1b8111fd475fb98b1ea33972c
https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/stat.py#L11-L19
1,873
yakupadakli/python-unsplash
unsplash/stat.py
Stat.month
def month(self): """ Get the overall Unsplash stats for the past 30 days. :return [Stat]: The Unsplash Stat. """ url = "/stats/month" result = self._get(url) return StatModel.parse(result)
python
def month(self): url = "/stats/month" result = self._get(url) return StatModel.parse(result)
[ "def", "month", "(", "self", ")", ":", "url", "=", "\"/stats/month\"", "result", "=", "self", ".", "_get", "(", "url", ")", "return", "StatModel", ".", "parse", "(", "result", ")" ]
Get the overall Unsplash stats for the past 30 days. :return [Stat]: The Unsplash Stat.
[ "Get", "the", "overall", "Unsplash", "stats", "for", "the", "past", "30", "days", "." ]
6e43dce3225237e1b8111fd475fb98b1ea33972c
https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/stat.py#L21-L29
1,874
yakupadakli/python-unsplash
unsplash/auth.py
Auth.refresh_token
def refresh_token(self): """ Refreshing the current expired access token """ self.token = self.oauth.refresh_token(self.access_token_url, refresh_token=self.get_refresh_token()) self.access_token = self.token.get("access_token")
python
def refresh_token(self): self.token = self.oauth.refresh_token(self.access_token_url, refresh_token=self.get_refresh_token()) self.access_token = self.token.get("access_token")
[ "def", "refresh_token", "(", "self", ")", ":", "self", ".", "token", "=", "self", ".", "oauth", ".", "refresh_token", "(", "self", ".", "access_token_url", ",", "refresh_token", "=", "self", ".", "get_refresh_token", "(", ")", ")", "self", ".", "access_tok...
Refreshing the current expired access token
[ "Refreshing", "the", "current", "expired", "access", "token" ]
6e43dce3225237e1b8111fd475fb98b1ea33972c
https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/auth.py#L83-L88
1,875
yakupadakli/python-unsplash
unsplash/client.py
Client.get_auth_header
def get_auth_header(self): """ Getting the authorization header according to the authentication procedure :return [dict]: Authorization header """ if self.api.is_authenticated: return {"Authorization": "Bearer %s" % self.api.access_token} return {"Authorizati...
python
def get_auth_header(self): if self.api.is_authenticated: return {"Authorization": "Bearer %s" % self.api.access_token} return {"Authorization": "Client-ID %s" % self.api.client_id}
[ "def", "get_auth_header", "(", "self", ")", ":", "if", "self", ".", "api", ".", "is_authenticated", ":", "return", "{", "\"Authorization\"", ":", "\"Bearer %s\"", "%", "self", ".", "api", ".", "access_token", "}", "return", "{", "\"Authorization\"", ":", "\"...
Getting the authorization header according to the authentication procedure :return [dict]: Authorization header
[ "Getting", "the", "authorization", "header", "according", "to", "the", "authentication", "procedure" ]
6e43dce3225237e1b8111fd475fb98b1ea33972c
https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/client.py#L52-L60
1,876
yakupadakli/python-unsplash
unsplash/user.py
User.me
def me(self): """ Get the currently-logged in user. Note: To access a user’s private data, the user is required to authorize the 'read_user' scope. Without it, this request will return a '403 Forbidden' response. Note: Without a Bearer token (i.e. using a Client-ID toke...
python
def me(self): url = "/me" result = self._get(url) return UserModel.parse(result)
[ "def", "me", "(", "self", ")", ":", "url", "=", "\"/me\"", "result", "=", "self", ".", "_get", "(", "url", ")", "return", "UserModel", ".", "parse", "(", "result", ")" ]
Get the currently-logged in user. Note: To access a user’s private data, the user is required to authorize the 'read_user' scope. Without it, this request will return a '403 Forbidden' response. Note: Without a Bearer token (i.e. using a Client-ID token) this request will retur...
[ "Get", "the", "currently", "-", "logged", "in", "user", "." ]
6e43dce3225237e1b8111fd475fb98b1ea33972c
https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/user.py#L25-L40
1,877
yakupadakli/python-unsplash
unsplash/user.py
User.update
def update(self, **kwargs): """ Update the currently-logged in user. Note: This action requires the write_user scope. Without it, it will return a 403 Forbidden response. All parameters are optional. :param username [string]: Username. :param first_name [string]...
python
def update(self, **kwargs): url = "/me" result = self._put(url, data=kwargs) return UserModel.parse(result)
[ "def", "update", "(", "self", ",", "*", "*", "kwargs", ")", ":", "url", "=", "\"/me\"", "result", "=", "self", ".", "_put", "(", "url", ",", "data", "=", "kwargs", ")", "return", "UserModel", ".", "parse", "(", "result", ")" ]
Update the currently-logged in user. Note: This action requires the write_user scope. Without it, it will return a 403 Forbidden response. All parameters are optional. :param username [string]: Username. :param first_name [string]: First name. :param last_name [string]:...
[ "Update", "the", "currently", "-", "logged", "in", "user", "." ]
6e43dce3225237e1b8111fd475fb98b1ea33972c
https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/user.py#L42-L62
1,878
yakupadakli/python-unsplash
unsplash/user.py
User.get
def get(self, username, width=None, height=None): """ Retrieve public details on a given user. Note: Supplying the optional w or h parameters will result in the 'custom' photo URL being added to the 'profile_image' object: :param username [string]: The user’s username. Required...
python
def get(self, username, width=None, height=None): url = "/users/{username}".format(username=username) params = { "w": width, "h": height } result = self._get(url, params=params) return UserModel.parse(result)
[ "def", "get", "(", "self", ",", "username", ",", "width", "=", "None", ",", "height", "=", "None", ")", ":", "url", "=", "\"/users/{username}\"", ".", "format", "(", "username", "=", "username", ")", "params", "=", "{", "\"w\"", ":", "width", ",", "\...
Retrieve public details on a given user. Note: Supplying the optional w or h parameters will result in the 'custom' photo URL being added to the 'profile_image' object: :param username [string]: The user’s username. Required. :param width [integer]: Profile image width in pixels. ...
[ "Retrieve", "public", "details", "on", "a", "given", "user", "." ]
6e43dce3225237e1b8111fd475fb98b1ea33972c
https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/user.py#L64-L82
1,879
yakupadakli/python-unsplash
unsplash/user.py
User.photos
def photos(self, username, page=1, per_page=10, order_by="latest"): """ Get a list of photos uploaded by a user. :param username [string]: The user’s username. Required. :param page [integer]: Page number to retrieve. (Optional; default: 1) :param per_page [integer]: Number of i...
python
def photos(self, username, page=1, per_page=10, order_by="latest"): url = "/users/{username}/photos".format(username=username) result = self._photos(url, username, page=page, per_page=per_page, order_by=order_by) return PhotoModel.parse_list(result)
[ "def", "photos", "(", "self", ",", "username", ",", "page", "=", "1", ",", "per_page", "=", "10", ",", "order_by", "=", "\"latest\"", ")", ":", "url", "=", "\"/users/{username}/photos\"", ".", "format", "(", "username", "=", "username", ")", "result", "=...
Get a list of photos uploaded by a user. :param username [string]: The user’s username. Required. :param page [integer]: Page number to retrieve. (Optional; default: 1) :param per_page [integer]: Number of items per page. (Optional; default: 10) :param order_by [string]: How to sort the...
[ "Get", "a", "list", "of", "photos", "uploaded", "by", "a", "user", "." ]
6e43dce3225237e1b8111fd475fb98b1ea33972c
https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/user.py#L105-L118
1,880
yakupadakli/python-unsplash
unsplash/user.py
User.collections
def collections(self, username, page=1, per_page=10): """ Get a list of collections created by the user. :param username [string]: The user’s username. Required. :param page [integer]: Page number to retrieve. (Optional; default: 1) :param per_page [integer]: Number of items per...
python
def collections(self, username, page=1, per_page=10): url = "/users/{username}/collections".format(username=username) params = { "page": page, "per_page": per_page } result = self._get(url, params=params) return CollectionModel.parse_list(result)
[ "def", "collections", "(", "self", ",", "username", ",", "page", "=", "1", ",", "per_page", "=", "10", ")", ":", "url", "=", "\"/users/{username}/collections\"", ".", "format", "(", "username", "=", "username", ")", "params", "=", "{", "\"page\"", ":", "...
Get a list of collections created by the user. :param username [string]: The user’s username. Required. :param page [integer]: Page number to retrieve. (Optional; default: 1) :param per_page [integer]: Number of items per page. (Optional; default: 10) :return: [Array]: A single page of ...
[ "Get", "a", "list", "of", "collections", "created", "by", "the", "user", "." ]
6e43dce3225237e1b8111fd475fb98b1ea33972c
https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/user.py#L135-L150
1,881
pri22296/beautifultable
beautifultable/ansi.py
ANSIMultiByteString.wrap
def wrap(self, width): """Returns a partition of the string based on `width`""" res = [] prev_state = set() part = [] cwidth = 0 for char, _width, state in zip(self._string, self._width, self._state): if cwidth + _width > width: if prev_state: ...
python
def wrap(self, width): res = [] prev_state = set() part = [] cwidth = 0 for char, _width, state in zip(self._string, self._width, self._state): if cwidth + _width > width: if prev_state: part.append(self.ANSI_RESET) ...
[ "def", "wrap", "(", "self", ",", "width", ")", ":", "res", "=", "[", "]", "prev_state", "=", "set", "(", ")", "part", "=", "[", "]", "cwidth", "=", "0", "for", "char", ",", "_width", ",", "state", "in", "zip", "(", "self", ".", "_string", ",", ...
Returns a partition of the string based on `width`
[ "Returns", "a", "partition", "of", "the", "string", "based", "on", "width" ]
c9638f73dff4bb1f341c9ee783e4e47f26efba0b
https://github.com/pri22296/beautifultable/blob/c9638f73dff4bb1f341c9ee783e4e47f26efba0b/beautifultable/ansi.py#L87-L115
1,882
pri22296/beautifultable
beautifultable/beautifultable.py
BeautifulTable._initialize_table
def _initialize_table(self, column_count): """Sets the column count of the table. This method is called to set the number of columns for the first time. Parameters ---------- column_count : int number of columns in the table """ header = [''] * colum...
python
def _initialize_table(self, column_count): header = [''] * column_count alignment = [self.default_alignment] * column_count width = [0] * column_count padding = [self.default_padding] * column_count self._column_count = column_count self._column_headers = HeaderData(self...
[ "def", "_initialize_table", "(", "self", ",", "column_count", ")", ":", "header", "=", "[", "''", "]", "*", "column_count", "alignment", "=", "[", "self", ".", "default_alignment", "]", "*", "column_count", "width", "=", "[", "0", "]", "*", "column_count",...
Sets the column count of the table. This method is called to set the number of columns for the first time. Parameters ---------- column_count : int number of columns in the table
[ "Sets", "the", "column", "count", "of", "the", "table", "." ]
c9638f73dff4bb1f341c9ee783e4e47f26efba0b
https://github.com/pri22296/beautifultable/blob/c9638f73dff4bb1f341c9ee783e4e47f26efba0b/beautifultable/beautifultable.py#L422-L442
1,883
pri22296/beautifultable
beautifultable/beautifultable.py
BeautifulTable.set_style
def set_style(self, style): """Set the style of the table from a predefined set of styles. Parameters ---------- style: Style It can be one of the following: * beautifulTable.STYLE_DEFAULT * beautifultable.STYLE_NONE * beautifulTable.STY...
python
def set_style(self, style): if not isinstance(style, enums.Style): allowed = ("{}.{}".format(type(self).__name__, i.name) for i in enums.Style) error_msg = ("allowed values for style are: " + ', '.join(allowed)) raise ValueError...
[ "def", "set_style", "(", "self", ",", "style", ")", ":", "if", "not", "isinstance", "(", "style", ",", "enums", ".", "Style", ")", ":", "allowed", "=", "(", "\"{}.{}\"", ".", "format", "(", "type", "(", "self", ")", ".", "__name__", ",", "i", ".", ...
Set the style of the table from a predefined set of styles. Parameters ---------- style: Style It can be one of the following: * beautifulTable.STYLE_DEFAULT * beautifultable.STYLE_NONE * beautifulTable.STYLE_DOTTED * beautifulTable....
[ "Set", "the", "style", "of", "the", "table", "from", "a", "predefined", "set", "of", "styles", "." ]
c9638f73dff4bb1f341c9ee783e4e47f26efba0b
https://github.com/pri22296/beautifultable/blob/c9638f73dff4bb1f341c9ee783e4e47f26efba0b/beautifultable/beautifultable.py#L580-L627
1,884
pri22296/beautifultable
beautifultable/beautifultable.py
BeautifulTable._calculate_column_widths
def _calculate_column_widths(self): """Calculate width of column automatically based on data.""" table_width = self.get_table_width() lpw, rpw = self._left_padding_widths, self._right_padding_widths pad_widths = [(lpw[i] + rpw[i]) for i in range(self._column_count)] max_widths = ...
python
def _calculate_column_widths(self): table_width = self.get_table_width() lpw, rpw = self._left_padding_widths, self._right_padding_widths pad_widths = [(lpw[i] + rpw[i]) for i in range(self._column_count)] max_widths = [0 for index in range(self._column_count)] offset = table_wid...
[ "def", "_calculate_column_widths", "(", "self", ")", ":", "table_width", "=", "self", ".", "get_table_width", "(", ")", "lpw", ",", "rpw", "=", "self", ".", "_left_padding_widths", ",", "self", ".", "_right_padding_widths", "pad_widths", "=", "[", "(", "lpw", ...
Calculate width of column automatically based on data.
[ "Calculate", "width", "of", "column", "automatically", "based", "on", "data", "." ]
c9638f73dff4bb1f341c9ee783e4e47f26efba0b
https://github.com/pri22296/beautifultable/blob/c9638f73dff4bb1f341c9ee783e4e47f26efba0b/beautifultable/beautifultable.py#L629-L701
1,885
pri22296/beautifultable
beautifultable/beautifultable.py
BeautifulTable.get_column_index
def get_column_index(self, header): """Get index of a column from it's header. Parameters ---------- header: str header of the column. Raises ------ ValueError: If no column could be found corresponding to `header`. """ tr...
python
def get_column_index(self, header): try: index = self._column_headers.index(header) return index except ValueError: raise_suppressed(KeyError(("'{}' is not a header for any " "column").format(header)))
[ "def", "get_column_index", "(", "self", ",", "header", ")", ":", "try", ":", "index", "=", "self", ".", "_column_headers", ".", "index", "(", "header", ")", "return", "index", "except", "ValueError", ":", "raise_suppressed", "(", "KeyError", "(", "(", "\"'...
Get index of a column from it's header. Parameters ---------- header: str header of the column. Raises ------ ValueError: If no column could be found corresponding to `header`.
[ "Get", "index", "of", "a", "column", "from", "it", "s", "header", "." ]
c9638f73dff4bb1f341c9ee783e4e47f26efba0b
https://github.com/pri22296/beautifultable/blob/c9638f73dff4bb1f341c9ee783e4e47f26efba0b/beautifultable/beautifultable.py#L756-L774
1,886
pri22296/beautifultable
beautifultable/beautifultable.py
BeautifulTable.get_column
def get_column(self, key): """Return an iterator to a column. Parameters ---------- key : int, str index of the column, or the header of the column. If index is specified, then normal list rules apply. Raises ------ TypeError: ...
python
def get_column(self, key): if isinstance(key, int): index = key elif isinstance(key, basestring): index = self.get_column_index(key) else: raise TypeError(("key must be an int or str, " "not {}").format(type(key).__name__)) ...
[ "def", "get_column", "(", "self", ",", "key", ")", ":", "if", "isinstance", "(", "key", ",", "int", ")", ":", "index", "=", "key", "elif", "isinstance", "(", "key", ",", "basestring", ")", ":", "index", "=", "self", ".", "get_column_index", "(", "key...
Return an iterator to a column. Parameters ---------- key : int, str index of the column, or the header of the column. If index is specified, then normal list rules apply. Raises ------ TypeError: If key is not of type `int`, or `str`...
[ "Return", "an", "iterator", "to", "a", "column", "." ]
c9638f73dff4bb1f341c9ee783e4e47f26efba0b
https://github.com/pri22296/beautifultable/blob/c9638f73dff4bb1f341c9ee783e4e47f26efba0b/beautifultable/beautifultable.py#L776-L802
1,887
pri22296/beautifultable
beautifultable/beautifultable.py
BeautifulTable.insert_row
def insert_row(self, index, row): """Insert a row before index in the table. Parameters ---------- index : int List index rules apply row : iterable Any iterable of appropriate length. Raises ------ TypeError: If `row...
python
def insert_row(self, index, row): row = self._validate_row(row) row_obj = RowData(self, row) self._table.insert(index, row_obj)
[ "def", "insert_row", "(", "self", ",", "index", ",", "row", ")", ":", "row", "=", "self", ".", "_validate_row", "(", "row", ")", "row_obj", "=", "RowData", "(", "self", ",", "row", ")", "self", ".", "_table", ".", "insert", "(", "index", ",", "row_...
Insert a row before index in the table. Parameters ---------- index : int List index rules apply row : iterable Any iterable of appropriate length. Raises ------ TypeError: If `row` is not an iterable. ValueError: ...
[ "Insert", "a", "row", "before", "index", "in", "the", "table", "." ]
c9638f73dff4bb1f341c9ee783e4e47f26efba0b
https://github.com/pri22296/beautifultable/blob/c9638f73dff4bb1f341c9ee783e4e47f26efba0b/beautifultable/beautifultable.py#L860-L882
1,888
pri22296/beautifultable
beautifultable/beautifultable.py
BeautifulTable.insert_column
def insert_column(self, index, header, column): """Insert a column before `index` in the table. If length of column is bigger than number of rows, lets say `k`, only the first `k` values of `column` is considered. If column is shorter than 'k', ValueError is raised. Note that T...
python
def insert_column(self, index, header, column): if self._column_count == 0: self.column_headers = HeaderData(self, [header]) self._table = [RowData(self, [i]) for i in column] else: if not isinstance(header, basestring): raise TypeError("header must be...
[ "def", "insert_column", "(", "self", ",", "index", ",", "header", ",", "column", ")", ":", "if", "self", ".", "_column_count", "==", "0", ":", "self", ".", "column_headers", "=", "HeaderData", "(", "self", ",", "[", "header", "]", ")", "self", ".", "...
Insert a column before `index` in the table. If length of column is bigger than number of rows, lets say `k`, only the first `k` values of `column` is considered. If column is shorter than 'k', ValueError is raised. Note that Table remains in consistent state even if column is ...
[ "Insert", "a", "column", "before", "index", "in", "the", "table", "." ]
c9638f73dff4bb1f341c9ee783e4e47f26efba0b
https://github.com/pri22296/beautifultable/blob/c9638f73dff4bb1f341c9ee783e4e47f26efba0b/beautifultable/beautifultable.py#L963-L1016
1,889
pri22296/beautifultable
beautifultable/beautifultable.py
BeautifulTable.append_column
def append_column(self, header, column): """Append a column to end of the table. Parameters ---------- header : str Title of the column column : iterable Any iterable of appropriate length. """ self.insert_column(self._column_count, heade...
python
def append_column(self, header, column): self.insert_column(self._column_count, header, column)
[ "def", "append_column", "(", "self", ",", "header", ",", "column", ")", ":", "self", ".", "insert_column", "(", "self", ".", "_column_count", ",", "header", ",", "column", ")" ]
Append a column to end of the table. Parameters ---------- header : str Title of the column column : iterable Any iterable of appropriate length.
[ "Append", "a", "column", "to", "end", "of", "the", "table", "." ]
c9638f73dff4bb1f341c9ee783e4e47f26efba0b
https://github.com/pri22296/beautifultable/blob/c9638f73dff4bb1f341c9ee783e4e47f26efba0b/beautifultable/beautifultable.py#L1018-L1029
1,890
pri22296/beautifultable
beautifultable/beautifultable.py
BeautifulTable._get_horizontal_line
def _get_horizontal_line(self, char, intersect_left, intersect_mid, intersect_right): """Get a horizontal line for the table. Internal method used to actually get all horizontal lines in the table. Column width should be set prior to calling this method. This method...
python
def _get_horizontal_line(self, char, intersect_left, intersect_mid, intersect_right): width = self.get_table_width() try: line = list(char * (int(width/termwidth(char)) + 1))[:width] except ZeroDivisionError: line = [' '] * width if ...
[ "def", "_get_horizontal_line", "(", "self", ",", "char", ",", "intersect_left", ",", "intersect_mid", ",", "intersect_right", ")", ":", "width", "=", "self", ".", "get_table_width", "(", ")", "try", ":", "line", "=", "list", "(", "char", "*", "(", "int", ...
Get a horizontal line for the table. Internal method used to actually get all horizontal lines in the table. Column width should be set prior to calling this method. This method detects intersection and handles it according to the values of `intersect_*_*` attributes. Parameter...
[ "Get", "a", "horizontal", "line", "for", "the", "table", "." ]
c9638f73dff4bb1f341c9ee783e4e47f26efba0b
https://github.com/pri22296/beautifultable/blob/c9638f73dff4bb1f341c9ee783e4e47f26efba0b/beautifultable/beautifultable.py#L1049-L1110
1,891
pri22296/beautifultable
beautifultable/beautifultable.py
BeautifulTable.get_table_width
def get_table_width(self): """Get the width of the table as number of characters. Column width should be set prior to calling this method. Returns ------- int Width of the table as number of characters. """ if self.column_count == 0: retu...
python
def get_table_width(self): if self.column_count == 0: return 0 width = sum(self._column_widths) width += ((self._column_count - 1) * termwidth(self.column_separator_char)) width += termwidth(self.left_border_char) width += termwidth(self.right_border...
[ "def", "get_table_width", "(", "self", ")", ":", "if", "self", ".", "column_count", "==", "0", ":", "return", "0", "width", "=", "sum", "(", "self", ".", "_column_widths", ")", "width", "+=", "(", "(", "self", ".", "_column_count", "-", "1", ")", "*"...
Get the width of the table as number of characters. Column width should be set prior to calling this method. Returns ------- int Width of the table as number of characters.
[ "Get", "the", "width", "of", "the", "table", "as", "number", "of", "characters", "." ]
c9638f73dff4bb1f341c9ee783e4e47f26efba0b
https://github.com/pri22296/beautifultable/blob/c9638f73dff4bb1f341c9ee783e4e47f26efba0b/beautifultable/beautifultable.py#L1188-L1205
1,892
pri22296/beautifultable
beautifultable/beautifultable.py
BeautifulTable.get_string
def get_string(self, recalculate_width=True): """Get the table as a String. Parameters ---------- recalculate_width : bool, optional If width for each column should be recalculated(default True). Note that width is always calculated if it wasn't set e...
python
def get_string(self, recalculate_width=True): # Empty table. returning empty string. if len(self._table) == 0: return '' if self.serialno and self.column_count > 0: self.insert_column(0, self.serialno_header, range(1, len(self) + 1)) ...
[ "def", "get_string", "(", "self", ",", "recalculate_width", "=", "True", ")", ":", "# Empty table. returning empty string.", "if", "len", "(", "self", ".", "_table", ")", "==", "0", ":", "return", "''", "if", "self", ".", "serialno", "and", "self", ".", "c...
Get the table as a String. Parameters ---------- recalculate_width : bool, optional If width for each column should be recalculated(default True). Note that width is always calculated if it wasn't set explicitly when this method is called for the first time ,...
[ "Get", "the", "table", "as", "a", "String", "." ]
c9638f73dff4bb1f341c9ee783e4e47f26efba0b
https://github.com/pri22296/beautifultable/blob/c9638f73dff4bb1f341c9ee783e4e47f26efba0b/beautifultable/beautifultable.py#L1207-L1269
1,893
pri22296/beautifultable
beautifultable/utils.py
_convert_to_numeric
def _convert_to_numeric(item): """ Helper method to convert a string to float or int if possible. If the conversion is not possible, it simply returns the string. """ if PY3: num_types = (int, float) else: # pragma: no cover num_types = (int, long...
python
def _convert_to_numeric(item): if PY3: num_types = (int, float) else: # pragma: no cover num_types = (int, long, float) # noqa: F821 # We don't wan't to perform any conversions if item is already a number if isinstance(item, num_types): return i...
[ "def", "_convert_to_numeric", "(", "item", ")", ":", "if", "PY3", ":", "num_types", "=", "(", "int", ",", "float", ")", "else", ":", "# pragma: no cover", "num_types", "=", "(", "int", ",", "long", ",", "float", ")", "# noqa: F821", "# We don't wan't to perf...
Helper method to convert a string to float or int if possible. If the conversion is not possible, it simply returns the string.
[ "Helper", "method", "to", "convert", "a", "string", "to", "float", "or", "int", "if", "possible", "." ]
c9638f73dff4bb1f341c9ee783e4e47f26efba0b
https://github.com/pri22296/beautifultable/blob/c9638f73dff4bb1f341c9ee783e4e47f26efba0b/beautifultable/utils.py#L11-L40
1,894
pri22296/beautifultable
beautifultable/utils.py
get_output_str
def get_output_str(item, detect_numerics, precision, sign_value): """Returns the final string which should be displayed""" if detect_numerics: item = _convert_to_numeric(item) if isinstance(item, float): item = round(item, precision) try: item = '{:{sign}}'.format(item, sign=sign...
python
def get_output_str(item, detect_numerics, precision, sign_value): if detect_numerics: item = _convert_to_numeric(item) if isinstance(item, float): item = round(item, precision) try: item = '{:{sign}}'.format(item, sign=sign_value) except (ValueError, TypeError): pass ...
[ "def", "get_output_str", "(", "item", ",", "detect_numerics", ",", "precision", ",", "sign_value", ")", ":", "if", "detect_numerics", ":", "item", "=", "_convert_to_numeric", "(", "item", ")", "if", "isinstance", "(", "item", ",", "float", ")", ":", "item", ...
Returns the final string which should be displayed
[ "Returns", "the", "final", "string", "which", "should", "be", "displayed" ]
c9638f73dff4bb1f341c9ee783e4e47f26efba0b
https://github.com/pri22296/beautifultable/blob/c9638f73dff4bb1f341c9ee783e4e47f26efba0b/beautifultable/utils.py#L43-L53
1,895
pri22296/beautifultable
beautifultable/rows.py
RowData._get_row_within_width
def _get_row_within_width(self, row): """Process a row so that it is clamped by column_width. Parameters ---------- row : array_like A single row. Returns ------- list of list: List representation of the `row` after it has been processed...
python
def _get_row_within_width(self, row): table = self._table lpw, rpw = table.left_padding_widths, table.right_padding_widths wep = table.width_exceed_policy list_of_rows = [] if (wep is WidthExceedPolicy.WEP_STRIP or wep is WidthExceedPolicy.WEP_ELLIPSIS): ...
[ "def", "_get_row_within_width", "(", "self", ",", "row", ")", ":", "table", "=", "self", ".", "_table", "lpw", ",", "rpw", "=", "table", ".", "left_padding_widths", ",", "table", ".", "right_padding_widths", "wep", "=", "table", ".", "width_exceed_policy", "...
Process a row so that it is clamped by column_width. Parameters ---------- row : array_like A single row. Returns ------- list of list: List representation of the `row` after it has been processed according to width exceed policy.
[ "Process", "a", "row", "so", "that", "it", "is", "clamped", "by", "column_width", "." ]
c9638f73dff4bb1f341c9ee783e4e47f26efba0b
https://github.com/pri22296/beautifultable/blob/c9638f73dff4bb1f341c9ee783e4e47f26efba0b/beautifultable/rows.py#L9-L63
1,896
pri22296/beautifultable
beautifultable/rows.py
RowData._clamp_string
def _clamp_string(self, row_item, column_index, delimiter=''): """Clamp `row_item` to fit in column referred by column_index. This method considers padding and appends the delimiter if `row_item` needs to be truncated. Parameters ---------- row_item: str Str...
python
def _clamp_string(self, row_item, column_index, delimiter=''): width = (self._table.column_widths[column_index] - self._table.left_padding_widths[column_index] - self._table.right_padding_widths[column_index]) if termwidth(row_item) <= width: return row_ite...
[ "def", "_clamp_string", "(", "self", ",", "row_item", ",", "column_index", ",", "delimiter", "=", "''", ")", ":", "width", "=", "(", "self", ".", "_table", ".", "column_widths", "[", "column_index", "]", "-", "self", ".", "_table", ".", "left_padding_width...
Clamp `row_item` to fit in column referred by column_index. This method considers padding and appends the delimiter if `row_item` needs to be truncated. Parameters ---------- row_item: str String which should be clamped. column_index: int Index ...
[ "Clamp", "row_item", "to", "fit", "in", "column", "referred", "by", "column_index", "." ]
c9638f73dff4bb1f341c9ee783e4e47f26efba0b
https://github.com/pri22296/beautifultable/blob/c9638f73dff4bb1f341c9ee783e4e47f26efba0b/beautifultable/rows.py#L65-L99
1,897
icq-bot/python-icq-bot
icq/bot.py
ICQBot.send_im
def send_im(self, target, message, mentions=None, parse=None, update_msg_id=None, wrap_length=5000): """ Send text message. :param target: Target user UIN or chat ID. :param message: Message text. :param mentions: Iterable with UINs to mention in message. :param parse: I...
python
def send_im(self, target, message, mentions=None, parse=None, update_msg_id=None, wrap_length=5000): try: responses = set() for text in wrap(string=str(message), length=wrap_length): response = self.http_session.post( url="{}/im/sendIM".format(self.api...
[ "def", "send_im", "(", "self", ",", "target", ",", "message", ",", "mentions", "=", "None", ",", "parse", "=", "None", ",", "update_msg_id", "=", "None", ",", "wrap_length", "=", "5000", ")", ":", "try", ":", "responses", "=", "set", "(", ")", "for",...
Send text message. :param target: Target user UIN or chat ID. :param message: Message text. :param mentions: Iterable with UINs to mention in message. :param parse: Iterable with several values from :class:`icq.constant.MessageParseType` specifying which message items should...
[ "Send", "text", "message", "." ]
1d278cc91f8eba5481bb8d70f80fc74160a40c8b
https://github.com/icq-bot/python-icq-bot/blob/1d278cc91f8eba5481bb8d70f80fc74160a40c8b/icq/bot.py#L459-L503
1,898
torchbox/wagtail-markdown
wagtailmarkdown/utils.py
render_markdown
def render_markdown(text, context=None): """ Turn markdown into HTML. """ if context is None or not isinstance(context, dict): context = {} markdown_html = _transform_markdown_into_html(text) sanitised_markdown_html = _sanitise_markdown_html(markdown_html) return mark_safe(sanitised_...
python
def render_markdown(text, context=None): if context is None or not isinstance(context, dict): context = {} markdown_html = _transform_markdown_into_html(text) sanitised_markdown_html = _sanitise_markdown_html(markdown_html) return mark_safe(sanitised_markdown_html)
[ "def", "render_markdown", "(", "text", ",", "context", "=", "None", ")", ":", "if", "context", "is", "None", "or", "not", "isinstance", "(", "context", ",", "dict", ")", ":", "context", "=", "{", "}", "markdown_html", "=", "_transform_markdown_into_html", ...
Turn markdown into HTML.
[ "Turn", "markdown", "into", "HTML", "." ]
6e1c4457049b68e8bc7eb5a3b19830bff58dc6a6
https://github.com/torchbox/wagtail-markdown/blob/6e1c4457049b68e8bc7eb5a3b19830bff58dc6a6/wagtailmarkdown/utils.py#L22-L30
1,899
torchbox/wagtail-markdown
wagtailmarkdown/mdx/tables/__init__.py
TableProcessor.run
def run(self, parent, blocks): """ Parse a table block and build table. """ block = blocks.pop(0).split('\n') header = block[0].strip() seperator = block[1].strip() rows = block[2:] # Get format type (bordered by pipes or not) border = False if hea...
python
def run(self, parent, blocks): block = blocks.pop(0).split('\n') header = block[0].strip() seperator = block[1].strip() rows = block[2:] # Get format type (bordered by pipes or not) border = False if header.startswith('|'): border = True ...
[ "def", "run", "(", "self", ",", "parent", ",", "blocks", ")", ":", "block", "=", "blocks", ".", "pop", "(", "0", ")", ".", "split", "(", "'\\n'", ")", "header", "=", "block", "[", "0", "]", ".", "strip", "(", ")", "seperator", "=", "block", "["...
Parse a table block and build table.
[ "Parse", "a", "table", "block", "and", "build", "table", "." ]
6e1c4457049b68e8bc7eb5a3b19830bff58dc6a6
https://github.com/torchbox/wagtail-markdown/blob/6e1c4457049b68e8bc7eb5a3b19830bff58dc6a6/wagtailmarkdown/mdx/tables/__init__.py#L33-L61