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
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | 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 = params.get("username")
message = params.get("message")
uservars = params.get("vars", dict())
# Make sure the required params are present.
if username is None or message is None:
return jsonify({
"status": "error",
"error": "username and message are required keys",
})
# Copy and user vars from the post into RiveScript.
if type(uservars) is dict:
for key, value in uservars.items():
bot.set_uservar(username, key, value)
# Get a reply from the bot.
reply = bot.reply(username, message)
# Get all the user's vars back out of the bot to include in the response.
uservars = bot.get_uservars(username)
# Send the response.
return jsonify({
"status": "ok",
"reply": reply,
"vars": uservars,
}) | 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())
# Make sure the required params are present.
if username is None or message is None:
return jsonify({
"status": "error",
"error": "username and message are required keys",
})
# Copy and user vars from the post into RiveScript.
if type(uservars) is dict:
for key, value in uservars.items():
bot.set_uservar(username, key, value)
# Get a reply from the bot.
reply = bot.reply(username, message)
# Get all the user's vars back out of the bot to include in the response.
uservars = bot.get_uservars(username)
# Send the response.
return jsonify({
"status": "ok",
"reply": reply,
"vars": uservars,
}) | [
"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",
"(",
")",
")",
"# Make sure the required params are present.",
"if",
"username",
"is",
"None",
"or",
"message",
"is",
"None",
":",
"return",
"jsonify",
"(",
"{",
"\"status\"",
":",
"\"error\"",
",",
"\"error\"",
":",
"\"username and message are required keys\"",
",",
"}",
")",
"# Copy and user vars from the post into RiveScript.",
"if",
"type",
"(",
"uservars",
")",
"is",
"dict",
":",
"for",
"key",
",",
"value",
"in",
"uservars",
".",
"items",
"(",
")",
":",
"bot",
".",
"set_uservar",
"(",
"username",
",",
"key",
",",
"value",
")",
"# Get a reply from the bot.",
"reply",
"=",
"bot",
".",
"reply",
"(",
"username",
",",
"message",
")",
"# Get all the user's vars back out of the bot to include in the response.",
"uservars",
"=",
"bot",
".",
"get_uservars",
"(",
"username",
")",
"# Send the response.",
"return",
"jsonify",
"(",
"{",
"\"status\"",
":",
"\"ok\"",
",",
"\"reply\"",
":",
"reply",
",",
"\"vars\"",
":",
"uservars",
",",
"}",
")"
] | 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" \
-X POST -d '{}' \
http://localhost:5000/reply""".format(json.dumps(payload)),
mimetype="text/plain") | 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.dumps(payload)),
mimetype="text/plain") | [
"def",
"index",
"(",
"path",
"=",
"None",
")",
":",
"payload",
"=",
"{",
"\"username\"",
":",
"\"soandso\"",
",",
"\"message\"",
":",
"\"Hello bot\"",
",",
"\"vars\"",
":",
"{",
"\"name\"",
":",
"\"Soandso\"",
",",
"}",
"}",
"return",
"Response",
"(",
"r\"\"\"Usage: curl -i \\\n -H \"Content-Type: application/json\" \\\n -X POST -d '{}' \\\n http://localhost:5000/reply\"\"\"",
".",
"format",
"(",
"json",
".",
"dumps",
"(",
"payload",
")",
")",
",",
"mimetype",
"=",
"\"text/plain\"",
")"
] | 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",
"(",
"data",
".",
"decode",
"(",
")",
")"
] | 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
first. Triggers with equal word counts are sorted by length, and then
alphabetically if they have the same length.
* Triggers containing optionals are sorted next, by word count like
atomic triggers.
* Triggers containing wildcards are next, with ``_`` (alphabetic)
wildcards on top, then ``#`` (numeric) and finally ``*``.
* At the bottom of the sorted list are triggers consisting of only a
single wildcard, in the order: ``_``, ``#``, ``*``.
Triggers that have ``{weight}`` tags are grouped together by weight
value and sorted amongst themselves. Higher weighted groups are then
ordered before lower weighted groups regardless of the normal sorting
algorithm.
Triggers that come from topics which inherit other topics are also
sorted with higher priority than triggers from the inherited topics.
Arguments:
triggers ([]str): Array of triggers to sort.
exclude_previous (bool): Create a sort buffer for 'previous' triggers.
say (function): A reference to ``RiveScript._say()`` or provide your
own function.
"""
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.
# Create a list of trigger objects map.
trigger_object_list = []
for index, trig in enumerate(triggers):
if exclude_previous and trig[1]["previous"]:
continue
pattern = trig[0] # Extract only the text of the trigger, with possible tag of inherit
# See if it has a weight tag
match, weight = re.search(RE.weight, trig[0]), 0
if match: # Value of math is not None if there is a match.
weight = int(match.group(1)) # Get the weight from the tag ``{weight}``
# See if it has an inherits tag.
match = re.search(RE.inherit, pattern)
if match:
inherit = int(match.group(1)) # Get inherit value from the tag ``{inherit}``
say("\t\t\tTrigger belongs to a topic which inherits other topics: level=" + str(inherit))
triggers[index][0] = pattern = re.sub(RE.inherit, "", pattern) # Remove the inherit tag if any
else:
inherit = sys.maxsize # If not found any inherit, set it to the maximum value, to place it last in the sort
trigger_object_list.append(TriggerObj(pattern, index, weight, inherit))
# Priority order of sorting criteria:
# weight, inherit, is_empty, star, pound, under, option, wordcount, len, alphabet
sorted_list = sorted(trigger_object_list,
key=attrgetter('weight', 'inherit', 'is_empty', 'star', 'pound',
'under', 'option', 'wordcount', 'len', 'alphabet'))
return [triggers[item.index] for item in sorted_list] | 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.
# Create a list of trigger objects map.
trigger_object_list = []
for index, trig in enumerate(triggers):
if exclude_previous and trig[1]["previous"]:
continue
pattern = trig[0] # Extract only the text of the trigger, with possible tag of inherit
# See if it has a weight tag
match, weight = re.search(RE.weight, trig[0]), 0
if match: # Value of math is not None if there is a match.
weight = int(match.group(1)) # Get the weight from the tag ``{weight}``
# See if it has an inherits tag.
match = re.search(RE.inherit, pattern)
if match:
inherit = int(match.group(1)) # Get inherit value from the tag ``{inherit}``
say("\t\t\tTrigger belongs to a topic which inherits other topics: level=" + str(inherit))
triggers[index][0] = pattern = re.sub(RE.inherit, "", pattern) # Remove the inherit tag if any
else:
inherit = sys.maxsize # If not found any inherit, set it to the maximum value, to place it last in the sort
trigger_object_list.append(TriggerObj(pattern, index, weight, inherit))
# Priority order of sorting criteria:
# weight, inherit, is_empty, star, pound, under, option, wordcount, len, alphabet
sorted_list = sorted(trigger_object_list,
key=attrgetter('weight', 'inherit', 'is_empty', 'star', 'pound',
'under', 'option', 'wordcount', 'len', 'alphabet'))
return [triggers[item.index] for item in sorted_list] | [
"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.",
"# Create a list of trigger objects map.",
"trigger_object_list",
"=",
"[",
"]",
"for",
"index",
",",
"trig",
"in",
"enumerate",
"(",
"triggers",
")",
":",
"if",
"exclude_previous",
"and",
"trig",
"[",
"1",
"]",
"[",
"\"previous\"",
"]",
":",
"continue",
"pattern",
"=",
"trig",
"[",
"0",
"]",
"# Extract only the text of the trigger, with possible tag of inherit",
"# See if it has a weight tag",
"match",
",",
"weight",
"=",
"re",
".",
"search",
"(",
"RE",
".",
"weight",
",",
"trig",
"[",
"0",
"]",
")",
",",
"0",
"if",
"match",
":",
"# Value of math is not None if there is a match.",
"weight",
"=",
"int",
"(",
"match",
".",
"group",
"(",
"1",
")",
")",
"# Get the weight from the tag ``{weight}``",
"# See if it has an inherits tag.",
"match",
"=",
"re",
".",
"search",
"(",
"RE",
".",
"inherit",
",",
"pattern",
")",
"if",
"match",
":",
"inherit",
"=",
"int",
"(",
"match",
".",
"group",
"(",
"1",
")",
")",
"# Get inherit value from the tag ``{inherit}``",
"say",
"(",
"\"\\t\\t\\tTrigger belongs to a topic which inherits other topics: level=\"",
"+",
"str",
"(",
"inherit",
")",
")",
"triggers",
"[",
"index",
"]",
"[",
"0",
"]",
"=",
"pattern",
"=",
"re",
".",
"sub",
"(",
"RE",
".",
"inherit",
",",
"\"\"",
",",
"pattern",
")",
"# Remove the inherit tag if any",
"else",
":",
"inherit",
"=",
"sys",
".",
"maxsize",
"# If not found any inherit, set it to the maximum value, to place it last in the sort",
"trigger_object_list",
".",
"append",
"(",
"TriggerObj",
"(",
"pattern",
",",
"index",
",",
"weight",
",",
"inherit",
")",
")",
"# Priority order of sorting criteria:",
"# weight, inherit, is_empty, star, pound, under, option, wordcount, len, alphabet",
"sorted_list",
"=",
"sorted",
"(",
"trigger_object_list",
",",
"key",
"=",
"attrgetter",
"(",
"'weight'",
",",
"'inherit'",
",",
"'is_empty'",
",",
"'star'",
",",
"'pound'",
",",
"'under'",
",",
"'option'",
",",
"'wordcount'",
",",
"'len'",
",",
"'alphabet'",
")",
")",
"return",
"[",
"triggers",
"[",
"item",
".",
"index",
"]",
"for",
"item",
"in",
"sorted_list",
"]"
] | 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
alphabetically if they have the same length.
* Triggers containing optionals are sorted next, by word count like
atomic triggers.
* Triggers containing wildcards are next, with ``_`` (alphabetic)
wildcards on top, then ``#`` (numeric) and finally ``*``.
* At the bottom of the sorted list are triggers consisting of only a
single wildcard, in the order: ``_``, ``#``, ``*``.
Triggers that have ``{weight}`` tags are grouped together by weight
value and sorted amongst themselves. Higher weighted groups are then
ordered before lower weighted groups regardless of the normal sorting
algorithm.
Triggers that come from topics which inherit other topics are also
sorted with higher priority than triggers from the inherited topics.
Arguments:
triggers ([]str): Array of triggers to sort.
exclude_previous (bool): Create a sort buffer for 'previous' triggers.
say (function): A reference to ``RiveScript._say()`` or provide your
own function. | [
"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(item, all=True)
if cword not in track:
track[cword] = []
track[cword].append(item)
# Sort them.
output = []
for count in sorted(track.keys(), reverse=True):
sort = sorted(track[count], key=len, reverse=True)
output.extend(sort)
return output | 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[cword] = []
track[cword].append(item)
# Sort them.
output = []
for count in sorted(track.keys(), reverse=True):
sort = sorted(track[count], key=len, reverse=True)
output.extend(sort)
return output | [
"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",
"[",
"cword",
"]",
"=",
"[",
"]",
"track",
"[",
"cword",
"]",
".",
"append",
"(",
"item",
")",
"# Sort them.",
"output",
"=",
"[",
"]",
"for",
"count",
"in",
"sorted",
"(",
"track",
".",
"keys",
"(",
")",
",",
"reverse",
"=",
"True",
")",
":",
"sort",
"=",
"sorted",
"(",
"track",
"[",
"count",
"]",
",",
"key",
"=",
"len",
",",
"reverse",
"=",
"True",
")",
"output",
".",
"extend",
"(",
"sort",
")",
"return",
"output"
] | 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 ``[".rive", ".rs"]``.
"""
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 value.
ext = [ext]
if not os.path.isdir(directory):
self._warn("Error: " + directory + " is not a directory.")
return
for root, subdirs, files in os.walk(directory):
for file in files:
for extension in ext:
if file.lower().endswith(extension):
# Load this file.
self.load_file(os.path.join(root, file))
break | 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 value.
ext = [ext]
if not os.path.isdir(directory):
self._warn("Error: " + directory + " is not a directory.")
return
for root, subdirs, files in os.walk(directory):
for file in files:
for extension in ext:
if file.lower().endswith(extension):
# Load this file.
self.load_file(os.path.join(root, file))
break | [
"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 value.",
"ext",
"=",
"[",
"ext",
"]",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"directory",
")",
":",
"self",
".",
"_warn",
"(",
"\"Error: \"",
"+",
"directory",
"+",
"\" is not a directory.\"",
")",
"return",
"for",
"root",
",",
"subdirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"directory",
")",
":",
"for",
"file",
"in",
"files",
":",
"for",
"extension",
"in",
"ext",
":",
"if",
"file",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"extension",
")",
":",
"# Load this file.",
"self",
".",
"load_file",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"file",
")",
")",
"break"
] | 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._say("Parsing " + str(len(lines)) + " lines of code from " + filename)
self._parse(filename, lines) | 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",
"(",
")",
"fh",
".",
"close",
"(",
")",
"self",
".",
"_say",
"(",
"\"Parsing \"",
"+",
"str",
"(",
"len",
"(",
"lines",
")",
")",
"+",
"\" lines of code from \"",
"+",
"filename",
")",
"self",
".",
"_parse",
"(",
"filename",
",",
"lines",
")"
] | 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("\n")
self._parse("stream()", code) | 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",
".",
"_parse",
"(",
"\"stream()\"",
",",
"code",
")"
] | 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, 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 this attribute
for name, value in data.items():
if value == "<undef>":
del internal[name]
else:
internal[name] = value
# Precompile substitutions.
if kind in ["sub", "person"]:
self._precompile_substitution(kind, name)
# Let the scripts set the debug mode and other special globals.
if self._global.get("debug"):
self._debug = str(self._global["debug"]).lower() == "true"
if self._global.get("depth"):
self._depth = int(self._global["depth"])
# Consume all the parsed triggers.
for topic, data in ast["topics"].items():
# Keep a map of the topics that are included/inherited under this topic.
if not topic in self._includes:
self._includes[topic] = {}
if not topic in self._lineage:
self._lineage[topic] = {}
self._includes[topic].update(data["includes"])
self._lineage[topic].update(data["inherits"])
# Consume the triggers.
if not topic in self._topics:
self._topics[topic] = []
for trigger in data["triggers"]:
self._topics[topic].append(trigger)
# Precompile the regexp for this trigger.
self._precompile_regexp(trigger["trigger"])
# Does this trigger have a %Previous? If so, make a pointer to
# this exact trigger in _thats.
if trigger["previous"] is not None:
if not topic in self._thats:
self._thats[topic] = {}
if not trigger["trigger"] in self._thats[topic]:
self._thats[topic][trigger["trigger"]] = {}
self._thats[topic][trigger["trigger"]][trigger["previous"]] = trigger
# Load all the parsed objects.
for obj in ast["objects"]:
# Have a handler for it?
if obj["language"] in self._handlers:
self._objlangs[obj["name"]] = obj["language"]
self._handlers[obj["language"]].load(obj["name"], obj["code"]) | 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 this attribute
for name, value in data.items():
if value == "<undef>":
del internal[name]
else:
internal[name] = value
# Precompile substitutions.
if kind in ["sub", "person"]:
self._precompile_substitution(kind, name)
# Let the scripts set the debug mode and other special globals.
if self._global.get("debug"):
self._debug = str(self._global["debug"]).lower() == "true"
if self._global.get("depth"):
self._depth = int(self._global["depth"])
# Consume all the parsed triggers.
for topic, data in ast["topics"].items():
# Keep a map of the topics that are included/inherited under this topic.
if not topic in self._includes:
self._includes[topic] = {}
if not topic in self._lineage:
self._lineage[topic] = {}
self._includes[topic].update(data["includes"])
self._lineage[topic].update(data["inherits"])
# Consume the triggers.
if not topic in self._topics:
self._topics[topic] = []
for trigger in data["triggers"]:
self._topics[topic].append(trigger)
# Precompile the regexp for this trigger.
self._precompile_regexp(trigger["trigger"])
# Does this trigger have a %Previous? If so, make a pointer to
# this exact trigger in _thats.
if trigger["previous"] is not None:
if not topic in self._thats:
self._thats[topic] = {}
if not trigger["trigger"] in self._thats[topic]:
self._thats[topic][trigger["trigger"]] = {}
self._thats[topic][trigger["trigger"]][trigger["previous"]] = trigger
# Load all the parsed objects.
for obj in ast["objects"]:
# Have a handler for it?
if obj["language"] in self._handlers:
self._objlangs[obj["name"]] = obj["language"]
self._handlers[obj["language"]].load(obj["name"], obj["code"]) | [
"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 this attribute",
"for",
"name",
",",
"value",
"in",
"data",
".",
"items",
"(",
")",
":",
"if",
"value",
"==",
"\"<undef>\"",
":",
"del",
"internal",
"[",
"name",
"]",
"else",
":",
"internal",
"[",
"name",
"]",
"=",
"value",
"# Precompile substitutions.",
"if",
"kind",
"in",
"[",
"\"sub\"",
",",
"\"person\"",
"]",
":",
"self",
".",
"_precompile_substitution",
"(",
"kind",
",",
"name",
")",
"# Let the scripts set the debug mode and other special globals.",
"if",
"self",
".",
"_global",
".",
"get",
"(",
"\"debug\"",
")",
":",
"self",
".",
"_debug",
"=",
"str",
"(",
"self",
".",
"_global",
"[",
"\"debug\"",
"]",
")",
".",
"lower",
"(",
")",
"==",
"\"true\"",
"if",
"self",
".",
"_global",
".",
"get",
"(",
"\"depth\"",
")",
":",
"self",
".",
"_depth",
"=",
"int",
"(",
"self",
".",
"_global",
"[",
"\"depth\"",
"]",
")",
"# Consume all the parsed triggers.",
"for",
"topic",
",",
"data",
"in",
"ast",
"[",
"\"topics\"",
"]",
".",
"items",
"(",
")",
":",
"# Keep a map of the topics that are included/inherited under this topic.",
"if",
"not",
"topic",
"in",
"self",
".",
"_includes",
":",
"self",
".",
"_includes",
"[",
"topic",
"]",
"=",
"{",
"}",
"if",
"not",
"topic",
"in",
"self",
".",
"_lineage",
":",
"self",
".",
"_lineage",
"[",
"topic",
"]",
"=",
"{",
"}",
"self",
".",
"_includes",
"[",
"topic",
"]",
".",
"update",
"(",
"data",
"[",
"\"includes\"",
"]",
")",
"self",
".",
"_lineage",
"[",
"topic",
"]",
".",
"update",
"(",
"data",
"[",
"\"inherits\"",
"]",
")",
"# Consume the triggers.",
"if",
"not",
"topic",
"in",
"self",
".",
"_topics",
":",
"self",
".",
"_topics",
"[",
"topic",
"]",
"=",
"[",
"]",
"for",
"trigger",
"in",
"data",
"[",
"\"triggers\"",
"]",
":",
"self",
".",
"_topics",
"[",
"topic",
"]",
".",
"append",
"(",
"trigger",
")",
"# Precompile the regexp for this trigger.",
"self",
".",
"_precompile_regexp",
"(",
"trigger",
"[",
"\"trigger\"",
"]",
")",
"# Does this trigger have a %Previous? If so, make a pointer to",
"# this exact trigger in _thats.",
"if",
"trigger",
"[",
"\"previous\"",
"]",
"is",
"not",
"None",
":",
"if",
"not",
"topic",
"in",
"self",
".",
"_thats",
":",
"self",
".",
"_thats",
"[",
"topic",
"]",
"=",
"{",
"}",
"if",
"not",
"trigger",
"[",
"\"trigger\"",
"]",
"in",
"self",
".",
"_thats",
"[",
"topic",
"]",
":",
"self",
".",
"_thats",
"[",
"topic",
"]",
"[",
"trigger",
"[",
"\"trigger\"",
"]",
"]",
"=",
"{",
"}",
"self",
".",
"_thats",
"[",
"topic",
"]",
"[",
"trigger",
"[",
"\"trigger\"",
"]",
"]",
"[",
"trigger",
"[",
"\"previous\"",
"]",
"]",
"=",
"trigger",
"# Load all the parsed objects.",
"for",
"obj",
"in",
"ast",
"[",
"\"objects\"",
"]",
":",
"# Have a handler for it?",
"if",
"obj",
"[",
"\"language\"",
"]",
"in",
"self",
".",
"_handlers",
":",
"self",
".",
"_objlangs",
"[",
"obj",
"[",
"\"name\"",
"]",
"]",
"=",
"obj",
"[",
"\"language\"",
"]",
"self",
".",
"_handlers",
"[",
"obj",
"[",
"\"language\"",
"]",
"]",
".",
"load",
"(",
"obj",
"[",
"\"name\"",
"]",
",",
"obj",
"[",
"\"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. | [
"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 data structure containing the
contents of all RiveScript replies currently loaded in memory.
"""
# Data to return.
result = {
"begin": {
"global": {},
"var": {},
"sub": {},
"person": {},
"array": {},
"triggers": [],
},
"topics": {},
}
# Populate the config fields.
if self._debug:
result["begin"]["global"]["debug"] = self._debug
if self._depth != 50:
result["begin"]["global"]["depth"] = 50
# Definitions
result["begin"]["var"] = self._var.copy()
result["begin"]["sub"] = self._sub.copy()
result["begin"]["person"] = self._person.copy()
result["begin"]["array"] = self._array.copy()
result["begin"]["global"].update(self._global.copy())
# Topic Triggers.
for topic in self._topics:
dest = None # Where to place the topic info
if topic == "__begin__":
# Begin block.
dest = result["begin"]
else:
# Normal topic.
if topic not in result["topics"]:
result["topics"][topic] = {
"triggers": [],
"includes": {},
"inherits": {},
}
dest = result["topics"][topic]
# Copy the triggers.
for trig in self._topics[topic]:
dest["triggers"].append(copy.deepcopy(trig))
# Inherits/Includes.
for label, mapping in {"inherits": self._lineage, "includes": self._includes}.items():
if topic in mapping and len(mapping[topic]):
dest[label] = mapping[topic].copy()
return result | python | def deparse(self):
# Data to return.
result = {
"begin": {
"global": {},
"var": {},
"sub": {},
"person": {},
"array": {},
"triggers": [],
},
"topics": {},
}
# Populate the config fields.
if self._debug:
result["begin"]["global"]["debug"] = self._debug
if self._depth != 50:
result["begin"]["global"]["depth"] = 50
# Definitions
result["begin"]["var"] = self._var.copy()
result["begin"]["sub"] = self._sub.copy()
result["begin"]["person"] = self._person.copy()
result["begin"]["array"] = self._array.copy()
result["begin"]["global"].update(self._global.copy())
# Topic Triggers.
for topic in self._topics:
dest = None # Where to place the topic info
if topic == "__begin__":
# Begin block.
dest = result["begin"]
else:
# Normal topic.
if topic not in result["topics"]:
result["topics"][topic] = {
"triggers": [],
"includes": {},
"inherits": {},
}
dest = result["topics"][topic]
# Copy the triggers.
for trig in self._topics[topic]:
dest["triggers"].append(copy.deepcopy(trig))
# Inherits/Includes.
for label, mapping in {"inherits": self._lineage, "includes": self._includes}.items():
if topic in mapping and len(mapping[topic]):
dest[label] = mapping[topic].copy()
return result | [
"def",
"deparse",
"(",
"self",
")",
":",
"# Data to return.",
"result",
"=",
"{",
"\"begin\"",
":",
"{",
"\"global\"",
":",
"{",
"}",
",",
"\"var\"",
":",
"{",
"}",
",",
"\"sub\"",
":",
"{",
"}",
",",
"\"person\"",
":",
"{",
"}",
",",
"\"array\"",
":",
"{",
"}",
",",
"\"triggers\"",
":",
"[",
"]",
",",
"}",
",",
"\"topics\"",
":",
"{",
"}",
",",
"}",
"# Populate the config fields.",
"if",
"self",
".",
"_debug",
":",
"result",
"[",
"\"begin\"",
"]",
"[",
"\"global\"",
"]",
"[",
"\"debug\"",
"]",
"=",
"self",
".",
"_debug",
"if",
"self",
".",
"_depth",
"!=",
"50",
":",
"result",
"[",
"\"begin\"",
"]",
"[",
"\"global\"",
"]",
"[",
"\"depth\"",
"]",
"=",
"50",
"# Definitions",
"result",
"[",
"\"begin\"",
"]",
"[",
"\"var\"",
"]",
"=",
"self",
".",
"_var",
".",
"copy",
"(",
")",
"result",
"[",
"\"begin\"",
"]",
"[",
"\"sub\"",
"]",
"=",
"self",
".",
"_sub",
".",
"copy",
"(",
")",
"result",
"[",
"\"begin\"",
"]",
"[",
"\"person\"",
"]",
"=",
"self",
".",
"_person",
".",
"copy",
"(",
")",
"result",
"[",
"\"begin\"",
"]",
"[",
"\"array\"",
"]",
"=",
"self",
".",
"_array",
".",
"copy",
"(",
")",
"result",
"[",
"\"begin\"",
"]",
"[",
"\"global\"",
"]",
".",
"update",
"(",
"self",
".",
"_global",
".",
"copy",
"(",
")",
")",
"# Topic Triggers.",
"for",
"topic",
"in",
"self",
".",
"_topics",
":",
"dest",
"=",
"None",
"# Where to place the topic info",
"if",
"topic",
"==",
"\"__begin__\"",
":",
"# Begin block.",
"dest",
"=",
"result",
"[",
"\"begin\"",
"]",
"else",
":",
"# Normal topic.",
"if",
"topic",
"not",
"in",
"result",
"[",
"\"topics\"",
"]",
":",
"result",
"[",
"\"topics\"",
"]",
"[",
"topic",
"]",
"=",
"{",
"\"triggers\"",
":",
"[",
"]",
",",
"\"includes\"",
":",
"{",
"}",
",",
"\"inherits\"",
":",
"{",
"}",
",",
"}",
"dest",
"=",
"result",
"[",
"\"topics\"",
"]",
"[",
"topic",
"]",
"# Copy the triggers.",
"for",
"trig",
"in",
"self",
".",
"_topics",
"[",
"topic",
"]",
":",
"dest",
"[",
"\"triggers\"",
"]",
".",
"append",
"(",
"copy",
".",
"deepcopy",
"(",
"trig",
")",
")",
"# Inherits/Includes.",
"for",
"label",
",",
"mapping",
"in",
"{",
"\"inherits\"",
":",
"self",
".",
"_lineage",
",",
"\"includes\"",
":",
"self",
".",
"_includes",
"}",
".",
"items",
"(",
")",
":",
"if",
"topic",
"in",
"mapping",
"and",
"len",
"(",
"mapping",
"[",
"topic",
"]",
")",
":",
"dest",
"[",
"label",
"]",
"=",
"mapping",
"[",
"topic",
"]",
".",
"copy",
"(",
")",
"return",
"result"
] | 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
contents of all RiveScript replies currently loaded in memory. | [
"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 data as the
``deparsed`` argument, it will use that data instead of calling
``deparse()`` itself. This way you can use ``deparse()``, edit the data,
and use that to write the RiveScript document (for example, to be used
by a user interface for editing RiveScript without writing the code
directly).
Parameters:
fh (str or file): a string or a file-like object.
deparsed (dict): a data structure in the same format as what
``deparse()`` returns. If not passed, this value will come from
the current in-memory data from ``deparse()``.
"""
# 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("// Written by rivescript.deparse()\n")
fh.write("! version = 2.0\n\n")
# Variables of all sorts!
for kind in ["global", "var", "sub", "person", "array"]:
if len(deparsed["begin"][kind].keys()) == 0:
continue
for var in sorted(deparsed["begin"][kind].keys()):
# Array types need to be separated by either spaces or pipes.
data = deparsed["begin"][kind][var]
if type(data) not in [str, text_type]:
needs_pipes = False
for test in data:
if " " in test:
needs_pipes = True
break
# Word-wrap the result, target width is 78 chars minus the
# kind, var, and spaces and equals sign.
# TODO: not implemented yet.
# width = 78 - len(kind) - len(var) - 4
if needs_pipes:
data = self._write_wrapped("|".join(data), sep="|")
else:
data = " ".join(data)
fh.write("! {kind} {var} = {data}\n".format(
kind=kind,
var=var,
data=data,
))
fh.write("\n")
# Begin block.
if len(deparsed["begin"]["triggers"]):
fh.write("> begin\n\n")
self._write_triggers(fh, deparsed["begin"]["triggers"], indent="\t")
fh.write("< begin\n\n")
# The topics. Random first!
topics = ["random"]
topics.extend(sorted(deparsed["topics"].keys()))
done_random = False
for topic in topics:
if topic not in deparsed["topics"]: continue
if topic == "random" and done_random: continue
if topic == "random": done_random = True
tagged = False # Used > topic tag
data = deparsed["topics"][topic]
if topic != "random" or len(data["includes"]) or len(data["inherits"]):
tagged = True
fh.write("> topic " + topic)
if data["inherits"]:
fh.write(" inherits " + " ".join(sorted(data["inherits"].keys())))
if data["includes"]:
fh.write(" includes " + " ".join(sorted(data["includes"].keys())))
fh.write("\n\n")
indent = "\t" if tagged else ""
self._write_triggers(fh, data["triggers"], indent=indent)
if tagged:
fh.write("< topic\n\n")
return True | 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("// Written by rivescript.deparse()\n")
fh.write("! version = 2.0\n\n")
# Variables of all sorts!
for kind in ["global", "var", "sub", "person", "array"]:
if len(deparsed["begin"][kind].keys()) == 0:
continue
for var in sorted(deparsed["begin"][kind].keys()):
# Array types need to be separated by either spaces or pipes.
data = deparsed["begin"][kind][var]
if type(data) not in [str, text_type]:
needs_pipes = False
for test in data:
if " " in test:
needs_pipes = True
break
# Word-wrap the result, target width is 78 chars minus the
# kind, var, and spaces and equals sign.
# TODO: not implemented yet.
# width = 78 - len(kind) - len(var) - 4
if needs_pipes:
data = self._write_wrapped("|".join(data), sep="|")
else:
data = " ".join(data)
fh.write("! {kind} {var} = {data}\n".format(
kind=kind,
var=var,
data=data,
))
fh.write("\n")
# Begin block.
if len(deparsed["begin"]["triggers"]):
fh.write("> begin\n\n")
self._write_triggers(fh, deparsed["begin"]["triggers"], indent="\t")
fh.write("< begin\n\n")
# The topics. Random first!
topics = ["random"]
topics.extend(sorted(deparsed["topics"].keys()))
done_random = False
for topic in topics:
if topic not in deparsed["topics"]: continue
if topic == "random" and done_random: continue
if topic == "random": done_random = True
tagged = False # Used > topic tag
data = deparsed["topics"][topic]
if topic != "random" or len(data["includes"]) or len(data["inherits"]):
tagged = True
fh.write("> topic " + topic)
if data["inherits"]:
fh.write(" inherits " + " ".join(sorted(data["inherits"].keys())))
if data["includes"]:
fh.write(" includes " + " ".join(sorted(data["includes"].keys())))
fh.write("\n\n")
indent = "\t" if tagged else ""
self._write_triggers(fh, data["triggers"], indent=indent)
if tagged:
fh.write("< topic\n\n")
return True | [
"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",
"(",
"\"// Written by rivescript.deparse()\\n\"",
")",
"fh",
".",
"write",
"(",
"\"! version = 2.0\\n\\n\"",
")",
"# Variables of all sorts!",
"for",
"kind",
"in",
"[",
"\"global\"",
",",
"\"var\"",
",",
"\"sub\"",
",",
"\"person\"",
",",
"\"array\"",
"]",
":",
"if",
"len",
"(",
"deparsed",
"[",
"\"begin\"",
"]",
"[",
"kind",
"]",
".",
"keys",
"(",
")",
")",
"==",
"0",
":",
"continue",
"for",
"var",
"in",
"sorted",
"(",
"deparsed",
"[",
"\"begin\"",
"]",
"[",
"kind",
"]",
".",
"keys",
"(",
")",
")",
":",
"# Array types need to be separated by either spaces or pipes.",
"data",
"=",
"deparsed",
"[",
"\"begin\"",
"]",
"[",
"kind",
"]",
"[",
"var",
"]",
"if",
"type",
"(",
"data",
")",
"not",
"in",
"[",
"str",
",",
"text_type",
"]",
":",
"needs_pipes",
"=",
"False",
"for",
"test",
"in",
"data",
":",
"if",
"\" \"",
"in",
"test",
":",
"needs_pipes",
"=",
"True",
"break",
"# Word-wrap the result, target width is 78 chars minus the",
"# kind, var, and spaces and equals sign.",
"# TODO: not implemented yet.",
"# width = 78 - len(kind) - len(var) - 4",
"if",
"needs_pipes",
":",
"data",
"=",
"self",
".",
"_write_wrapped",
"(",
"\"|\"",
".",
"join",
"(",
"data",
")",
",",
"sep",
"=",
"\"|\"",
")",
"else",
":",
"data",
"=",
"\" \"",
".",
"join",
"(",
"data",
")",
"fh",
".",
"write",
"(",
"\"! {kind} {var} = {data}\\n\"",
".",
"format",
"(",
"kind",
"=",
"kind",
",",
"var",
"=",
"var",
",",
"data",
"=",
"data",
",",
")",
")",
"fh",
".",
"write",
"(",
"\"\\n\"",
")",
"# Begin block.",
"if",
"len",
"(",
"deparsed",
"[",
"\"begin\"",
"]",
"[",
"\"triggers\"",
"]",
")",
":",
"fh",
".",
"write",
"(",
"\"> begin\\n\\n\"",
")",
"self",
".",
"_write_triggers",
"(",
"fh",
",",
"deparsed",
"[",
"\"begin\"",
"]",
"[",
"\"triggers\"",
"]",
",",
"indent",
"=",
"\"\\t\"",
")",
"fh",
".",
"write",
"(",
"\"< begin\\n\\n\"",
")",
"# The topics. Random first!",
"topics",
"=",
"[",
"\"random\"",
"]",
"topics",
".",
"extend",
"(",
"sorted",
"(",
"deparsed",
"[",
"\"topics\"",
"]",
".",
"keys",
"(",
")",
")",
")",
"done_random",
"=",
"False",
"for",
"topic",
"in",
"topics",
":",
"if",
"topic",
"not",
"in",
"deparsed",
"[",
"\"topics\"",
"]",
":",
"continue",
"if",
"topic",
"==",
"\"random\"",
"and",
"done_random",
":",
"continue",
"if",
"topic",
"==",
"\"random\"",
":",
"done_random",
"=",
"True",
"tagged",
"=",
"False",
"# Used > topic tag",
"data",
"=",
"deparsed",
"[",
"\"topics\"",
"]",
"[",
"topic",
"]",
"if",
"topic",
"!=",
"\"random\"",
"or",
"len",
"(",
"data",
"[",
"\"includes\"",
"]",
")",
"or",
"len",
"(",
"data",
"[",
"\"inherits\"",
"]",
")",
":",
"tagged",
"=",
"True",
"fh",
".",
"write",
"(",
"\"> topic \"",
"+",
"topic",
")",
"if",
"data",
"[",
"\"inherits\"",
"]",
":",
"fh",
".",
"write",
"(",
"\" inherits \"",
"+",
"\" \"",
".",
"join",
"(",
"sorted",
"(",
"data",
"[",
"\"inherits\"",
"]",
".",
"keys",
"(",
")",
")",
")",
")",
"if",
"data",
"[",
"\"includes\"",
"]",
":",
"fh",
".",
"write",
"(",
"\" includes \"",
"+",
"\" \"",
".",
"join",
"(",
"sorted",
"(",
"data",
"[",
"\"includes\"",
"]",
".",
"keys",
"(",
")",
")",
")",
")",
"fh",
".",
"write",
"(",
"\"\\n\\n\"",
")",
"indent",
"=",
"\"\\t\"",
"if",
"tagged",
"else",
"\"\"",
"self",
".",
"_write_triggers",
"(",
"fh",
",",
"data",
"[",
"\"triggers\"",
"]",
",",
"indent",
"=",
"indent",
")",
"if",
"tagged",
":",
"fh",
".",
"write",
"(",
"\"< topic\\n\\n\"",
")",
"return",
"True"
] | 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 will use that data instead of calling
``deparse()`` itself. This way you can use ``deparse()``, edit the data,
and use that to write the RiveScript document (for example, to be used
by a user interface for editing RiveScript without writing the code
directly).
Parameters:
fh (str or file): a string or a file-like object.
deparsed (dict): a data structure in the same format as what
``deparse()`` returns. If not passed, this value will come from
the current in-memory data from ``deparse()``. | [
"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.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=indent) + "\n")
for cond in d["condition"]:
fh.write(indent + "* " + self._write_wrapped(cond, indent=indent) + "\n")
if d.get("redirect"):
fh.write(indent + "@ " + self._write_wrapped(d["redirect"], indent=indent) + "\n")
for reply in d["reply"]:
fh.write(indent + "- " + self._write_wrapped(reply, indent=indent) + "\n")
fh.write("\n") | 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=indent) + "\n")
for cond in d["condition"]:
fh.write(indent + "* " + self._write_wrapped(cond, indent=indent) + "\n")
if d.get("redirect"):
fh.write(indent + "@ " + self._write_wrapped(d["redirect"], indent=indent) + "\n")
for reply in d["reply"]:
fh.write(indent + "- " + self._write_wrapped(reply, indent=indent) + "\n")
fh.write("\n") | [
"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",
"=",
"indent",
")",
"+",
"\"\\n\"",
")",
"for",
"cond",
"in",
"d",
"[",
"\"condition\"",
"]",
":",
"fh",
".",
"write",
"(",
"indent",
"+",
"\"* \"",
"+",
"self",
".",
"_write_wrapped",
"(",
"cond",
",",
"indent",
"=",
"indent",
")",
"+",
"\"\\n\"",
")",
"if",
"d",
".",
"get",
"(",
"\"redirect\"",
")",
":",
"fh",
".",
"write",
"(",
"indent",
"+",
"\"@ \"",
"+",
"self",
".",
"_write_wrapped",
"(",
"d",
"[",
"\"redirect\"",
"]",
",",
"indent",
"=",
"indent",
")",
"+",
"\"\\n\"",
")",
"for",
"reply",
"in",
"d",
"[",
"\"reply\"",
"]",
":",
"fh",
".",
"write",
"(",
"indent",
"+",
"\"- \"",
"+",
"self",
".",
"_write_wrapped",
"(",
"reply",
",",
"indent",
"=",
"indent",
")",
"+",
"\"\\n\"",
")",
"fh",
".",
"write",
"(",
"\"\\n\"",
")"
] | 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).
:param int width: The character width to constrain each line to.
:return str: The reformatted line(s)."""
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!
words.insert(0, buf.pop()) # Undo
lines.append(sep.join(buf))
buf = []
line = ""
# Straggler?
if line:
lines.append(line)
# Returned output
result = lines.pop(0)
if len(lines):
eol = ""
if sep == " ":
eol = "\s"
for item in lines:
result += eol + "\n" + indent + "^ " + item
return result | 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!
words.insert(0, buf.pop()) # Undo
lines.append(sep.join(buf))
buf = []
line = ""
# Straggler?
if line:
lines.append(line)
# Returned output
result = lines.pop(0)
if len(lines):
eol = ""
if sep == " ":
eol = "\s"
for item in lines:
result += eol + "\n" + indent + "^ " + item
return result | [
"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!",
"words",
".",
"insert",
"(",
"0",
",",
"buf",
".",
"pop",
"(",
")",
")",
"# Undo",
"lines",
".",
"append",
"(",
"sep",
".",
"join",
"(",
"buf",
")",
")",
"buf",
"=",
"[",
"]",
"line",
"=",
"\"\"",
"# Straggler?",
"if",
"line",
":",
"lines",
".",
"append",
"(",
"line",
")",
"# Returned output",
"result",
"=",
"lines",
".",
"pop",
"(",
"0",
")",
"if",
"len",
"(",
"lines",
")",
":",
"eol",
"=",
"\"\"",
"if",
"sep",
"==",
"\" \"",
":",
"eol",
"=",
"\"\\s\"",
"for",
"item",
"in",
"lines",
":",
"result",
"+=",
"eol",
"+",
"\"\\n\"",
"+",
"indent",
"+",
"\"^ \"",
"+",
"item",
"return",
"result"
] | 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.
:return str: The reformatted line(s). | [
"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!
"""
# (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 " + topic)
# Collect a list of all the triggers we're going to worry about.
# If this topic inherits another topic, we need to recursively add
# those to the list as well.
alltrig = inherit_utils.get_topic_triggers(self, topic, False)
# Sort them.
self._sorted["topics"][topic] = sorting.sort_trigger_set(alltrig, True, self._say)
# Get all of the %Previous triggers for this topic.
that_triggers = inherit_utils.get_topic_triggers(self, topic, True)
# And sort them, too.
self._sorted["thats"][topic] = sorting.sort_trigger_set(that_triggers, False, self._say)
# And sort the substitution lists.
if not "lists" in self._sorted:
self._sorted["lists"] = {}
self._sorted["lists"]["sub"] = sorting.sort_list(self._sub.keys())
self._sorted["lists"]["person"] = sorting.sort_list(self._person.keys()) | 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 " + topic)
# Collect a list of all the triggers we're going to worry about.
# If this topic inherits another topic, we need to recursively add
# those to the list as well.
alltrig = inherit_utils.get_topic_triggers(self, topic, False)
# Sort them.
self._sorted["topics"][topic] = sorting.sort_trigger_set(alltrig, True, self._say)
# Get all of the %Previous triggers for this topic.
that_triggers = inherit_utils.get_topic_triggers(self, topic, True)
# And sort them, too.
self._sorted["thats"][topic] = sorting.sort_trigger_set(that_triggers, False, self._say)
# And sort the substitution lists.
if not "lists" in self._sorted:
self._sorted["lists"] = {}
self._sorted["lists"]["sub"] = sorting.sort_list(self._sub.keys())
self._sorted["lists"]["person"] = sorting.sort_list(self._person.keys()) | [
"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 \"",
"+",
"topic",
")",
"# Collect a list of all the triggers we're going to worry about.",
"# If this topic inherits another topic, we need to recursively add",
"# those to the list as well.",
"alltrig",
"=",
"inherit_utils",
".",
"get_topic_triggers",
"(",
"self",
",",
"topic",
",",
"False",
")",
"# Sort them.",
"self",
".",
"_sorted",
"[",
"\"topics\"",
"]",
"[",
"topic",
"]",
"=",
"sorting",
".",
"sort_trigger_set",
"(",
"alltrig",
",",
"True",
",",
"self",
".",
"_say",
")",
"# Get all of the %Previous triggers for this topic.",
"that_triggers",
"=",
"inherit_utils",
".",
"get_topic_triggers",
"(",
"self",
",",
"topic",
",",
"True",
")",
"# And sort them, too.",
"self",
".",
"_sorted",
"[",
"\"thats\"",
"]",
"[",
"topic",
"]",
"=",
"sorting",
".",
"sort_trigger_set",
"(",
"that_triggers",
",",
"False",
",",
"self",
".",
"_say",
")",
"# And sort the substitution lists.",
"if",
"not",
"\"lists\"",
"in",
"self",
".",
"_sorted",
":",
"self",
".",
"_sorted",
"[",
"\"lists\"",
"]",
"=",
"{",
"}",
"self",
".",
"_sorted",
"[",
"\"lists\"",
"]",
"[",
"\"sub\"",
"]",
"=",
"sorting",
".",
"sort_list",
"(",
"self",
".",
"_sub",
".",
"keys",
"(",
")",
")",
"self",
".",
"_sorted",
"[",
"\"lists\"",
"]",
"[",
"\"person\"",
"]",
"=",
"sorting",
".",
"sort_list",
"(",
"self",
".",
"_person",
".",
"keys",
"(",
")",
")"
] | 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 rivescript-python distribution for
an example script that sets up a JavaScript language handler.
:param str language: The lowercased name of the programming language.
Examples: python, javascript, perl
:param class obj: An instance of an implementation class object.
It should provide the following interface::
class MyObjectHandler:
def __init__(self):
pass
def load(self, name, code):
# name = the name of the object from the RiveScript code
# code = the source code of the object
def call(self, rs, name, fields):
# rs = the current RiveScript interpreter object
# name = the name of the object being called
# fields = array of arguments passed to the object
return reply
"""
# 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 | 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",
"]",
"else",
":",
"self",
".",
"_handlers",
"[",
"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 rivescript-python distribution for
an example script that sets up a JavaScript language handler.
:param str language: The lowercased name of the programming language.
Examples: python, javascript, perl
:param class obj: An instance of an implementation class object.
It should provide the following interface::
class MyObjectHandler:
def __init__(self):
pass
def load(self, name, code):
# name = the name of the object from the RiveScript code
# code = the source code of the object
def call(self, rs, name, fields):
# rs = the current RiveScript interpreter object
# name = the name of the object being called
# fields = array of arguments passed to the object
return reply | [
"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 function with a method signature of
``(rs, args)``
This method is only available if there is a Python handler set up
(which there is by default, unless you've called
``set_handler("python", None)``).
"""
# 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!") | 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",
"self",
".",
"_objlangs",
"[",
"name",
"]",
"=",
"'python'",
"else",
":",
"self",
".",
"_warn",
"(",
"\"Can't set_subroutine: no Python object handler!\"",
")"
] | 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
``(rs, args)``
This method is only available if there is a Python handler set up
(which there is by default, unless you've called
``set_handler("python", None)``). | [
"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 value is None:
# Unset the variable.
if name in self._global:
del self._global[name]
self._global[name] = value | 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",
"[",
"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. | [
"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 is None:
# Unset the variable.
if name in self._var:
del self._var[name]
self._var[name] = value | 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",
"[",
"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. | [
"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 is None:
# Unset the variable.
if what in self._subs:
del self._subs[what]
self._subs[what] = 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",
"[",
"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. | [
"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 rep is None:
# Unset the variable.
if what in self._person:
del self._person[what]
self._person[what] = rep | 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",
"[",
"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. | [
"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.
"""
self._session.set(user, {name: value}) | 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 for many users.
rs.set_uservars(many_vars)
In the first syntax, ``vars`` is a simple dict of key/value string
pairs. In the second syntax, ``many_vars`` is a structure like this::
{
"username1": {
"key": "value",
},
"username2": {
"key": "value",
},
}
This way you can export *all* user variables via ``get_uservars()``
and then re-import them all at once, instead of setting them once per
user.
:param optional str user: The user ID to set many variables for.
Skip this parameter to set many variables for many users instead.
:param dict data: The dictionary of key/value pairs for user variables,
or else a dict of dicts mapping usernames to key/value pairs.
This may raise a ``TypeError`` exception if you pass it invalid data
types. Note that only the standard ``dict`` type is accepted, but not
variants like ``OrderedDict``, so if you have a dict-like type you
should cast it to ``dict`` first.
"""
# 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:
raise TypeError(
"In set_uservars(many_vars) syntax, the many_vars dict "
"must be in the format of `many_vars['username'] = "
"dict(key=value)`, but the contents of many_vars['{}']"
" is not a dict.".format(uid)
)
self._session.set(uid, uservars)
elif type(user) in [text_type, str] and type(data) is dict:
# Setting variables for a single user.
self._session.set(user, data)
else:
raise TypeError(
"set_uservars() may only be called with types ({str}, dict) or "
"(dict<{str}, dict>) but you called it with types ({a}, {b})"
.format(
str="unicode" if sys.version_info[0] < 3 else "str",
a=type(user),
b=type(data),
),
) | 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:
raise TypeError(
"In set_uservars(many_vars) syntax, the many_vars dict "
"must be in the format of `many_vars['username'] = "
"dict(key=value)`, but the contents of many_vars['{}']"
" is not a dict.".format(uid)
)
self._session.set(uid, uservars)
elif type(user) in [text_type, str] and type(data) is dict:
# Setting variables for a single user.
self._session.set(user, data)
else:
raise TypeError(
"set_uservars() may only be called with types ({str}, dict) or "
"(dict<{str}, dict>) but you called it with types ({a}, {b})"
.format(
str="unicode" if sys.version_info[0] < 3 else "str",
a=type(user),
b=type(data),
),
) | [
"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",
":",
"raise",
"TypeError",
"(",
"\"In set_uservars(many_vars) syntax, the many_vars dict \"",
"\"must be in the format of `many_vars['username'] = \"",
"\"dict(key=value)`, but the contents of many_vars['{}']\"",
"\" is not a dict.\"",
".",
"format",
"(",
"uid",
")",
")",
"self",
".",
"_session",
".",
"set",
"(",
"uid",
",",
"uservars",
")",
"elif",
"type",
"(",
"user",
")",
"in",
"[",
"text_type",
",",
"str",
"]",
"and",
"type",
"(",
"data",
")",
"is",
"dict",
":",
"# Setting variables for a single user.",
"self",
".",
"_session",
".",
"set",
"(",
"user",
",",
"data",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"set_uservars() may only be called with types ({str}, dict) or \"",
"\"(dict<{str}, dict>) but you called it with types ({a}, {b})\"",
".",
"format",
"(",
"str",
"=",
"\"unicode\"",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"<",
"3",
"else",
"\"str\"",
",",
"a",
"=",
"type",
"(",
"user",
")",
",",
"b",
"=",
"type",
"(",
"data",
")",
",",
")",
",",
")"
] | 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_vars)
In the first syntax, ``vars`` is a simple dict of key/value string
pairs. In the second syntax, ``many_vars`` is a structure like this::
{
"username1": {
"key": "value",
},
"username2": {
"key": "value",
},
}
This way you can export *all* user variables via ``get_uservars()``
and then re-import them all at once, instead of setting them once per
user.
:param optional str user: The user ID to set many variables for.
Skip this parameter to set many variables for many users instead.
:param dict data: The dictionary of key/value pairs for user variables,
or else a dict of dicts mapping usernames to key/value pairs.
This may raise a ``TypeError`` exception if you pass it invalid data
types. Note that only the standard ``dict`` type is accepted, but not
variants like ``OrderedDict``, so if you have a dict-like type you
should cast it to ``dict`` first. | [
"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 returns ``None``.
* If the user doesn't have this variable set, this returns the
string ``"undefined"``.
* Otherwise this returns the string value of the variable.
"""
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) | 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",
"self",
".",
"_session",
".",
"get",
"(",
"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 returns ``None``.
* If the user doesn't have this variable set, this returns the
string ``"undefined"``.
* Otherwise this returns the string value of the variable. | [
"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 a list
of matching triggers, containing their topics, filenames and line
numbers. Returns ``None`` if there weren't any matches found.
The keys in the trigger info is as follows:
* ``category``: Either 'topic' (for normal) or 'thats'
(for %Previous triggers)
* ``topic``: The topic name
* ``trigger``: The raw trigger text
* ``filename``: The filename the trigger was found in.
* ``lineno``: The line number the trigger was found on.
Pass in a true value for ``dump``, and the entire syntax tracking
tree is returned.
:param str trigger: The raw trigger text to look up.
:param bool dump: Whether to dump the entire syntax tracking tree.
:return: A list of matching triggers or ``None`` if no matches.
"""
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]:
# We got a match!
if response is None:
response = list()
fname, lineno = self._syntax[category][topic][trigger]['trigger']
response.append(dict(
category=category,
topic=topic,
trigger=trigger,
filename=fname,
line=lineno,
))
return response | 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]:
# We got a match!
if response is None:
response = list()
fname, lineno = self._syntax[category][topic][trigger]['trigger']
response.append(dict(
category=category,
topic=topic,
trigger=trigger,
filename=fname,
line=lineno,
))
return response | [
"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",
"]",
":",
"# We got a match!",
"if",
"response",
"is",
"None",
":",
"response",
"=",
"list",
"(",
")",
"fname",
",",
"lineno",
"=",
"self",
".",
"_syntax",
"[",
"category",
"]",
"[",
"topic",
"]",
"[",
"trigger",
"]",
"[",
"'trigger'",
"]",
"response",
".",
"append",
"(",
"dict",
"(",
"category",
"=",
"category",
",",
"topic",
"=",
"topic",
",",
"trigger",
"=",
"trigger",
",",
"filename",
"=",
"fname",
",",
"line",
"=",
"lineno",
",",
")",
")",
"return",
"response"
] | 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, filenames and line
numbers. Returns ``None`` if there weren't any matches found.
The keys in the trigger info is as follows:
* ``category``: Either 'topic' (for normal) or 'thats'
(for %Previous triggers)
* ``topic``: The topic name
* ``trigger``: The raw trigger text
* ``filename``: The filename the trigger was found in.
* ``lineno``: The line number the trigger was found on.
Pass in a true value for ``dump``, and the entire syntax tracking
tree is returned.
:param str trigger: The raw trigger text to look up.
:param bool dump: Whether to dump the entire syntax tracking tree.
:return: A list of matching triggers or ``None`` if no matches. | [
"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).
This will return ``None`` if used outside of the context of getting a
reply (the value is unset at the end of the ``reply()`` method).
"""
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 | 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",
".",
"_brain",
".",
"_current_user"
] | 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 used outside of the context of getting a
reply (the value is unset at the end of the ``reply()`` method). | [
"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 variables (including topic and history), so if your
bot has multiple users each one should have a unique ID.
msg (str): The user's message. This is allowed to contain
punctuation and such, but any extraneous data such as HTML tags
should be removed in advance.
errors_as_replies (bool): When errors are encountered (such as a
deep recursion error, no reply matched, etc.) this will make the
reply be a text representation of the error message. If you set
this to ``False``, errors will instead raise an exception, such as
a ``DeepRecursionError`` or ``NoReplyError``. By default, no
exceptions are raised and errors are set in the reply instead.
Returns:
str: The reply output.
"""
return self._brain.reply(user, msg, errors_as_replies) | 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
bot has multiple users each one should have a unique ID.
msg (str): The user's message. This is allowed to contain
punctuation and such, but any extraneous data such as HTML tags
should be removed in advance.
errors_as_replies (bool): When errors are encountered (such as a
deep recursion error, no reply matched, etc.) this will make the
reply be a text representation of the error message. If you set
this to ``False``, errors will instead raise an exception, such as
a ``DeepRecursionError`` or ``NoReplyError``. By default, no
exceptions are raised and errors are set in the reply instead.
Returns:
str: The reply output. | [
"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
:param str kind: One of ``sub``, ``person``.
:param str pattern: The substitution 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+)'),
"sub3": re.compile(r'(\W+)' + qm + r'(\W+)'),
"sub4": re.compile(r'(\W+)' + qm + r'$'),
} | 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+)'),
"sub3": re.compile(r'(\W+)' + qm + r'(\W+)'),
"sub4": re.compile(r'(\W+)' + qm + r'$'),
} | [
"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+)'",
")",
",",
"\"sub3\"",
":",
"re",
".",
"compile",
"(",
"r'(\\W+)'",
"+",
"qm",
"+",
"r'(\\W+)'",
")",
",",
"\"sub4\"",
":",
"re",
".",
"compile",
"(",
"r'(\\W+)'",
"+",
"qm",
"+",
"r'$'",
")",
",",
"}"
] | 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``.
:param str pattern: The substitution pattern. | [
"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 trigger text to attempt to precompile.
"""
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 trigger.
self._regexc["trigger"][trigger] = self._brain.reply_regexp(None, trigger) | 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 trigger.
self._regexc["trigger"][trigger] = self._brain.reply_regexp(None, trigger) | [
"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 trigger.",
"self",
".",
"_regexc",
"[",
"\"trigger\"",
"]",
"[",
"trigger",
"]",
"=",
"self",
".",
"_brain",
".",
"reply_regexp",
"(",
"None",
",",
"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 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 --")
pp.pprint(self._sub)
print("-- Person Substitutions --")
pp.pprint(self._person)
print("-- Arrays --")
pp.pprint(self._array)
print("=== Topic Structure ===")
pp.pprint(self._topics)
print("=== %Previous Structure ===")
pp.pprint(self._thats)
print("=== Includes ===")
pp.pprint(self._includes)
print("=== Inherits ===")
pp.pprint(self._lineage)
print("=== Sort Buffer ===")
pp.pprint(self._sorted)
print("=== Syntax Tree ===")
pp.pprint(self._syntax) | 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 Substitutions --")
pp.pprint(self._person)
print("-- Arrays --")
pp.pprint(self._array)
print("=== Topic Structure ===")
pp.pprint(self._topics)
print("=== %Previous Structure ===")
pp.pprint(self._thats)
print("=== Includes ===")
pp.pprint(self._includes)
print("=== Inherits ===")
pp.pprint(self._lineage)
print("=== Sort Buffer ===")
pp.pprint(self._sorted)
print("=== Syntax Tree ===")
pp.pprint(self._syntax) | [
"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 Substitutions --\"",
")",
"pp",
".",
"pprint",
"(",
"self",
".",
"_person",
")",
"print",
"(",
"\"-- Arrays --\"",
")",
"pp",
".",
"pprint",
"(",
"self",
".",
"_array",
")",
"print",
"(",
"\"=== Topic Structure ===\"",
")",
"pp",
".",
"pprint",
"(",
"self",
".",
"_topics",
")",
"print",
"(",
"\"=== %Previous Structure ===\"",
")",
"pp",
".",
"pprint",
"(",
"self",
".",
"_thats",
")",
"print",
"(",
"\"=== Includes ===\"",
")",
"pp",
".",
"pprint",
"(",
"self",
".",
"_includes",
")",
"print",
"(",
"\"=== Inherits ===\"",
")",
"pp",
".",
"pprint",
"(",
"self",
".",
"_lineage",
")",
"print",
"(",
"\"=== Sort Buffer ===\"",
")",
"pp",
".",
"pprint",
"(",
"self",
".",
"_sorted",
")",
"print",
"(",
"\"=== Syntax Tree ===\"",
")",
"pp",
".",
"pprint",
"(",
"self",
".",
"_syntax",
")"
] | 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.SMUGGLER_EXCLUDE_LIST) | 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",
"(",
"','",
")",
"return",
"dump_to_response",
"(",
"request",
",",
"app_label",
"=",
"app_label",
",",
"exclude",
"=",
"settings",
".",
"SMUGGLER_EXCLUDE_LIST",
")"
] | 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_label",
",",
"model_label",
")",
")",
")"
] | 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, months, weeks, days, hours, and minutes.
Seconds and microseconds are ignored. Up to two adjacent units will be
displayed. For example, "2 weeks, 3 days" and "1 year, 3 months" are
possible outputs, but "2 weeks, 3 hours" and "1 year, 5 days" are not.
Adapted from
http://web.archive.org/web/20060617175230/\
http://blog.natbat.co.uk/archive/2003/Jun/14/time_since
"""
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, pluralize('%d month', '%d months')),
(60 * 60 * 24 * 7, pluralize('%d week', '%d weeks')),
(60 * 60 * 24, pluralize('%d day', '%d days')),
(60 * 60, pluralize('%d hour', '%d hours')),
(60, pluralize('%d minute', '%d minutes')),
(0, pluralize('%d second', '%d seconds'))
)
# Convert datetime.date to datetime.datetime for comparison.
if not isinstance(d, datetime.datetime):
d = datetime.datetime(d.year, d.month, d.day)
if now and not isinstance(now, datetime.datetime):
now = datetime.datetime(now.year, now.month, now.day)
delta = now - d
# ignore microseconds
since = delta.days * 24 * 60 * 60 + delta.seconds
if since <= 0:
# d is in the future compared to now, stop processing.
# We'll use the last chunk (highest granularity)
_, name = chunks[-1]
return name(0)
for i, (seconds, name) in enumerate(chunks):
if seconds > 0:
count = since // seconds
if count != 0:
break
else:
count = since
result = name(count)
if i + 1 < len(chunks):
# Now get the second item
seconds2, name2 = chunks[i + 1]
if seconds2 > 0:
count2 = (since - (seconds * count)) // seconds2
else:
count2 = since - (seconds * count)
if count2 != 0:
result += ugettext(', ') + name2(count2)
return result | 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, pluralize('%d month', '%d months')),
(60 * 60 * 24 * 7, pluralize('%d week', '%d weeks')),
(60 * 60 * 24, pluralize('%d day', '%d days')),
(60 * 60, pluralize('%d hour', '%d hours')),
(60, pluralize('%d minute', '%d minutes')),
(0, pluralize('%d second', '%d seconds'))
)
# Convert datetime.date to datetime.datetime for comparison.
if not isinstance(d, datetime.datetime):
d = datetime.datetime(d.year, d.month, d.day)
if now and not isinstance(now, datetime.datetime):
now = datetime.datetime(now.year, now.month, now.day)
delta = now - d
# ignore microseconds
since = delta.days * 24 * 60 * 60 + delta.seconds
if since <= 0:
# d is in the future compared to now, stop processing.
# We'll use the last chunk (highest granularity)
_, name = chunks[-1]
return name(0)
for i, (seconds, name) in enumerate(chunks):
if seconds > 0:
count = since // seconds
if count != 0:
break
else:
count = since
result = name(count)
if i + 1 < len(chunks):
# Now get the second item
seconds2, name2 = chunks[i + 1]
if seconds2 > 0:
count2 = (since - (seconds * count)) // seconds2
else:
count2 = since - (seconds * count)
if count2 != 0:
result += ugettext(', ') + name2(count2)
return result | [
"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",
",",
"pluralize",
"(",
"'%d month'",
",",
"'%d months'",
")",
")",
",",
"(",
"60",
"*",
"60",
"*",
"24",
"*",
"7",
",",
"pluralize",
"(",
"'%d week'",
",",
"'%d weeks'",
")",
")",
",",
"(",
"60",
"*",
"60",
"*",
"24",
",",
"pluralize",
"(",
"'%d day'",
",",
"'%d days'",
")",
")",
",",
"(",
"60",
"*",
"60",
",",
"pluralize",
"(",
"'%d hour'",
",",
"'%d hours'",
")",
")",
",",
"(",
"60",
",",
"pluralize",
"(",
"'%d minute'",
",",
"'%d minutes'",
")",
")",
",",
"(",
"0",
",",
"pluralize",
"(",
"'%d second'",
",",
"'%d seconds'",
")",
")",
")",
"# Convert datetime.date to datetime.datetime for comparison.",
"if",
"not",
"isinstance",
"(",
"d",
",",
"datetime",
".",
"datetime",
")",
":",
"d",
"=",
"datetime",
".",
"datetime",
"(",
"d",
".",
"year",
",",
"d",
".",
"month",
",",
"d",
".",
"day",
")",
"if",
"now",
"and",
"not",
"isinstance",
"(",
"now",
",",
"datetime",
".",
"datetime",
")",
":",
"now",
"=",
"datetime",
".",
"datetime",
"(",
"now",
".",
"year",
",",
"now",
".",
"month",
",",
"now",
".",
"day",
")",
"delta",
"=",
"now",
"-",
"d",
"# ignore microseconds",
"since",
"=",
"delta",
".",
"days",
"*",
"24",
"*",
"60",
"*",
"60",
"+",
"delta",
".",
"seconds",
"if",
"since",
"<=",
"0",
":",
"# d is in the future compared to now, stop processing.",
"# We'll use the last chunk (highest granularity)",
"_",
",",
"name",
"=",
"chunks",
"[",
"-",
"1",
"]",
"return",
"name",
"(",
"0",
")",
"for",
"i",
",",
"(",
"seconds",
",",
"name",
")",
"in",
"enumerate",
"(",
"chunks",
")",
":",
"if",
"seconds",
">",
"0",
":",
"count",
"=",
"since",
"//",
"seconds",
"if",
"count",
"!=",
"0",
":",
"break",
"else",
":",
"count",
"=",
"since",
"result",
"=",
"name",
"(",
"count",
")",
"if",
"i",
"+",
"1",
"<",
"len",
"(",
"chunks",
")",
":",
"# Now get the second item",
"seconds2",
",",
"name2",
"=",
"chunks",
"[",
"i",
"+",
"1",
"]",
"if",
"seconds2",
">",
"0",
":",
"count2",
"=",
"(",
"since",
"-",
"(",
"seconds",
"*",
"count",
")",
")",
"//",
"seconds2",
"else",
":",
"count2",
"=",
"since",
"-",
"(",
"seconds",
"*",
"count",
")",
"if",
"count2",
"!=",
"0",
":",
"result",
"+=",
"ugettext",
"(",
"', '",
")",
"+",
"name2",
"(",
"count2",
")",
"return",
"result"
] | 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.
Seconds and microseconds are ignored. Up to two adjacent units will be
displayed. For example, "2 weeks, 3 days" and "1 year, 3 months" are
possible outputs, but "2 weeks, 3 hours" and "1 year, 5 days" are not.
Adapted from
http://web.archive.org/web/20060617175230/\
http://blog.natbat.co.uk/archive/2003/Jun/14/time_since | [
"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 resources and start running again"""
global restart
restart = True
if logger:
logger.info('detected SIGHUP')
raise KeyboardInterrupt | 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",
"configuration",
"information",
"rebuild",
"all",
"of",
"its",
"structures",
"and",
"resources",
"and",
"start",
"running",
"again"
] | 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.config.backoff_delays:
yield x
while True:
yield self.config.backoff_delays[-1] | 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",
".",
"This",
"generator",
"will",
"never",
"raise",
"the",
"StopIteration",
"exception",
"."
] | 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.
"""
#----------------------------------------------------------------------
def main(self, function=None):
return super(cls, self).main(
function=function,
once=False,
)
cls.main = main
cls._is_backfill_app = True
return cls | 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",
"(",
"function",
"=",
"function",
",",
"once",
"=",
"False",
",",
")",
"cls",
".",
"main",
"=",
"main",
"cls",
".",
"_is_backfill_app",
"=",
"True",
"return",
"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. | [
"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",
"."
] | 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 method ends.
In order for this dectorator to function properly, it must be used in
conjunction with previous dectorator, "with_transactional_resource" or
equivalent. This decorator depends on the mechanims added by that
decorator.
"""
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:
try:
self.run(connection, *args, **kwargs)
finally:
factory.close_connection(connection, force=True)
cls._run_proxy = _run_proxy
return cls
return class_decorator | 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:
try:
self.run(connection, *args, **kwargs)
finally:
factory.close_connection(connection, force=True)
cls._run_proxy = _run_proxy
return cls
return class_decorator | [
"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",
":",
"try",
":",
"self",
".",
"run",
"(",
"connection",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"finally",
":",
"factory",
".",
"close_connection",
"(",
"connection",
",",
"force",
"=",
"True",
")",
"cls",
".",
"_run_proxy",
"=",
"_run_proxy",
"return",
"cls",
"return",
"class_decorator"
] | 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 properly, it must be used in
conjunction with previous dectorator, "with_transactional_resource" or
equivalent. This decorator depends on the mechanims added by that
decorator. | [
"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",
"."
] | 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 'run' exits normally, the
connection will automatically be commited. Any abnormal exit from 'run'
will result in the connnection being rolledback.
In order for this dectorator to function properly, it must be used in
conjunction with previous dectorator, "with_transactional_resource" or
equivalent. This decorator depends on the mechanims added by that
decorator.
"""
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,
**kwargs
)
cls._run_proxy = _run_proxy
return cls
return class_decorator | 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,
**kwargs
)
cls._run_proxy = _run_proxy
return cls
return class_decorator | [
"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",
",",
"*",
"*",
"kwargs",
")",
"cls",
".",
"_run_proxy",
"=",
"_run_proxy",
"return",
"cls",
"return",
"class_decorator"
] | 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 automatically be commited. Any abnormal exit from 'run'
will result in the connnection being rolledback.
In order for this dectorator to function properly, it must be used in
conjunction with previous dectorator, "with_transactional_resource" or
equivalent. This decorator depends on the mechanims added by that
decorator. | [
"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",
"automatically",
"be",
"commited",
".",
"Any",
"abnormal",
"exit",
"from",
"run",
"will",
"result",
"in",
"the",
"connnection",
"being",
"rolledback",
"."
] | 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 short so that
the transaction is not held open too long.
"""
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 isinstance(command, (tuple, list)):
command = ' '.join('"%s"' % x for x in command)
proc = subprocess.Popen(
command,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
out, err = proc.communicate(input=input)
return proc.returncode, out.strip(), err.strip()
cls.run_process = run_process
return cls | 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 isinstance(command, (tuple, list)):
command = ' '.join('"%s"' % x for x in command)
proc = subprocess.Popen(
command,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
out, err = proc.communicate(input=input)
return proc.returncode, out.strip(), err.strip()
cls.run_process = run_process
return cls | [
"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 that was sent to stdout\n 2. stderr - all output that was sent to stderr\n \"\"\"",
"if",
"isinstance",
"(",
"command",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"command",
"=",
"' '",
".",
"join",
"(",
"'\"%s\"'",
"%",
"x",
"for",
"x",
"in",
"command",
")",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"command",
",",
"shell",
"=",
"True",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
"out",
",",
"err",
"=",
"proc",
".",
"communicate",
"(",
"input",
"=",
"input",
")",
"return",
"proc",
".",
"returncode",
",",
"out",
".",
"strip",
"(",
")",
",",
"err",
".",
"strip",
"(",
")",
"cls",
".",
"run_process",
"=",
"run_process",
"return",
"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 short so that
the transaction is not held open too long. | [
"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",
"is",
"not",
"held",
"open",
"too",
"long",
"."
] | 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,
last_error
FROM crontabber"""
columns = (
'app_name',
'next_run', 'first_run', 'last_run', 'last_success',
'depends_on', 'error_count', 'last_error'
)
items = []
for record in self.transaction_executor(execute_query_fetchall, sql):
row = dict(zip(columns, record))
items.append((row.pop('app_name'), row))
return items | 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 = (
'app_name',
'next_run', 'first_run', 'last_run', 'last_success',
'depends_on', 'error_count', 'last_error'
)
items = []
for record in self.transaction_executor(execute_query_fetchall, sql):
row = dict(zip(columns, record))
items.append((row.pop('app_name'), row))
return items | [
"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_error\n FROM crontabber\"\"\"",
"columns",
"=",
"(",
"'app_name'",
",",
"'next_run'",
",",
"'first_run'",
",",
"'last_run'",
",",
"'last_success'",
",",
"'depends_on'",
",",
"'error_count'",
",",
"'last_error'",
")",
"items",
"=",
"[",
"]",
"for",
"record",
"in",
"self",
".",
"transaction_executor",
"(",
"execute_query_fetchall",
",",
"sql",
")",
":",
"row",
"=",
"dict",
"(",
"zip",
"(",
"columns",
",",
"record",
")",
")",
"items",
".",
"append",
"(",
"(",
"row",
".",
"pop",
"(",
"'app_name'",
")",
",",
"row",
")",
")",
"return",
"items"
] | 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]
return popped
except KeyError:
if default == _marker:
raise
return default | 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",
":",
"raise",
"return",
"default"
] | 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 in class_list:
if (
job_class.app_name == description or
description == job_class.__module__ + '.' + job_class.__name__
):
if job_class.app_name in self.job_state_database:
self.config.logger.info('App reset')
self.job_state_database.pop(job_class.app_name)
else:
self.config.logger.warning('App already reset')
return
raise JobNotFoundError(description) | 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__ + '.' + job_class.__name__
):
if job_class.app_name in self.job_state_database:
self.config.logger.info('App reset')
self.job_state_database.pop(job_class.app_name)
else:
self.config.logger.warning('App already reset')
return
raise JobNotFoundError(description) | [
"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__",
"+",
"'.'",
"+",
"job_class",
".",
"__name__",
")",
":",
"if",
"job_class",
".",
"app_name",
"in",
"self",
".",
"job_state_database",
":",
"self",
".",
"config",
".",
"logger",
".",
"info",
"(",
"'App reset'",
")",
"self",
".",
"job_state_database",
".",
"pop",
"(",
"job_class",
".",
"app_name",
")",
"else",
":",
"self",
".",
"config",
".",
"logger",
".",
"warning",
"(",
"'App already reset'",
")",
"return",
"raise",
"JobNotFoundError",
"(",
"description",
")"
] | 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:
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
now = utc_now()
if now.hour > h:
return True
elif now.hour == h and now.minute >= m:
return True
return False
else:
# no past information, run now
return True
next_run = info['next_run']
if not next_run:
# It has never run before.
# If it has an active ongoing status it means two
# independent threads tried to start it. The second one
# (by a tiny time margin) will have a job_class whose
# `ongoing` value has already been set.
# If that's the case, let it through because it will
# commence and break due to RowLevelLockError in the
# state's __setitem__ method.
return bool(info['ongoing'])
if next_run < utc_now():
return True
return False | 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
now = utc_now()
if now.hour > h:
return True
elif now.hour == h and now.minute >= m:
return True
return False
else:
# no past information, run now
return True
next_run = info['next_run']
if not next_run:
# It has never run before.
# If it has an active ongoing status it means two
# independent threads tried to start it. The second one
# (by a tiny time margin) will have a job_class whose
# `ongoing` value has already been set.
# If that's the case, let it through because it will
# commence and break due to RowLevelLockError in the
# state's __setitem__ method.
return bool(info['ongoing'])
if next_run < utc_now():
return True
return False | [
"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",
"now",
"=",
"utc_now",
"(",
")",
"if",
"now",
".",
"hour",
">",
"h",
":",
"return",
"True",
"elif",
"now",
".",
"hour",
"==",
"h",
"and",
"now",
".",
"minute",
">=",
"m",
":",
"return",
"True",
"return",
"False",
"else",
":",
"# no past information, run now",
"return",
"True",
"next_run",
"=",
"info",
"[",
"'next_run'",
"]",
"if",
"not",
"next_run",
":",
"# It has never run before.",
"# If it has an active ongoing status it means two",
"# independent threads tried to start it. The second one",
"# (by a tiny time margin) will have a job_class whose",
"# `ongoing` value has already been set.",
"# If that's the case, let it through because it will",
"# commence and break due to RowLevelLockError in the",
"# state's __setitem__ method.",
"return",
"bool",
"(",
"info",
"[",
"'ongoing'",
"]",
")",
"if",
"next_run",
"<",
"utc_now",
"(",
")",
":",
"return",
"True",
"return",
"False"
] | 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",
"next_run",
"to",
"a",
"date",
"that",
"is",
"now",
"past",
"."
] | 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 database but not "
"available as a configured job:"
)
print "\t%s" % (app_name,) | 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:"
)
print "\t%s" % (app_name,) | [
"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:\"",
")",
"print",
"\"\\t%s\"",
"%",
"(",
"app_name",
",",
")"
] | 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:
Grammar.JS_WINDOW_TEMPLATE
Grammar.JS_ES6_IMPORT_EXPORT_TEMPLATE (default)
'''
language = []
refs = []
classes = {'Grammar'}
indent = 0
cname = self.__class__.__name__ if 'import ' in js_template else None
for name in self._order:
elem = getattr(self, name, None)
if not isinstance(elem, Element):
continue
if not hasattr(elem, '_export_js'):
continue
language.append('{indent}{var} {name} = {value};'.format(
indent=js_indent,
name=name,
var='static' if cname else 'var',
value=elem._export_js(js_indent, indent, classes, cname)))
for name, ref in self._refs.items():
refs.append(
'{pre}{name}.set({value});'
.format(
pre='{}.'.format(cname) if cname else js_indent,
name=name,
value=ref._element._export_js(
js_indent,
-1 if cname else indent,
classes,
cname)))
if 'Rule' in classes:
classes.remove('Rule')
return js_template.format(
name=self.__class__.__name__,
indent=js_indent,
js_module=js_module_name,
datetime=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()),
language='\n'.join(language),
refs='\n{}'.format('\n'.join(refs)),
arguments=',\n'.join(map(lambda s:
js_indent * 3 + s, classes)),
re_keywords=self.RE_KEYWORDS.pattern.replace('\\', '\\\\'),
classes=', '.join(classes),
constructors=',\n'.join(
map(lambda s: js_indent + s,
['.'.join([
'window',
js_module_name, n]) for n in classes]))) | 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:
Grammar.JS_WINDOW_TEMPLATE
Grammar.JS_ES6_IMPORT_EXPORT_TEMPLATE (default)
'''
language = []
refs = []
classes = {'Grammar'}
indent = 0
cname = self.__class__.__name__ if 'import ' in js_template else None
for name in self._order:
elem = getattr(self, name, None)
if not isinstance(elem, Element):
continue
if not hasattr(elem, '_export_js'):
continue
language.append('{indent}{var} {name} = {value};'.format(
indent=js_indent,
name=name,
var='static' if cname else 'var',
value=elem._export_js(js_indent, indent, classes, cname)))
for name, ref in self._refs.items():
refs.append(
'{pre}{name}.set({value});'
.format(
pre='{}.'.format(cname) if cname else js_indent,
name=name,
value=ref._element._export_js(
js_indent,
-1 if cname else indent,
classes,
cname)))
if 'Rule' in classes:
classes.remove('Rule')
return js_template.format(
name=self.__class__.__name__,
indent=js_indent,
js_module=js_module_name,
datetime=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()),
language='\n'.join(language),
refs='\n{}'.format('\n'.join(refs)),
arguments=',\n'.join(map(lambda s:
js_indent * 3 + s, classes)),
re_keywords=self.RE_KEYWORDS.pattern.replace('\\', '\\\\'),
classes=', '.join(classes),
constructors=',\n'.join(
map(lambda s: js_indent + s,
['.'.join([
'window',
js_module_name, n]) for n in classes]))) | [
"def",
"export_js",
"(",
"self",
",",
"js_module_name",
"=",
"JS_MODULE_NAME",
",",
"js_template",
"=",
"JS_ES6_IMPORT_EXPORT_TEMPLATE",
",",
"js_indent",
"=",
"JS_INDENTATION",
")",
":",
"language",
"=",
"[",
"]",
"refs",
"=",
"[",
"]",
"classes",
"=",
"{",
"'Grammar'",
"}",
"indent",
"=",
"0",
"cname",
"=",
"self",
".",
"__class__",
".",
"__name__",
"if",
"'import '",
"in",
"js_template",
"else",
"None",
"for",
"name",
"in",
"self",
".",
"_order",
":",
"elem",
"=",
"getattr",
"(",
"self",
",",
"name",
",",
"None",
")",
"if",
"not",
"isinstance",
"(",
"elem",
",",
"Element",
")",
":",
"continue",
"if",
"not",
"hasattr",
"(",
"elem",
",",
"'_export_js'",
")",
":",
"continue",
"language",
".",
"append",
"(",
"'{indent}{var} {name} = {value};'",
".",
"format",
"(",
"indent",
"=",
"js_indent",
",",
"name",
"=",
"name",
",",
"var",
"=",
"'static'",
"if",
"cname",
"else",
"'var'",
",",
"value",
"=",
"elem",
".",
"_export_js",
"(",
"js_indent",
",",
"indent",
",",
"classes",
",",
"cname",
")",
")",
")",
"for",
"name",
",",
"ref",
"in",
"self",
".",
"_refs",
".",
"items",
"(",
")",
":",
"refs",
".",
"append",
"(",
"'{pre}{name}.set({value});'",
".",
"format",
"(",
"pre",
"=",
"'{}.'",
".",
"format",
"(",
"cname",
")",
"if",
"cname",
"else",
"js_indent",
",",
"name",
"=",
"name",
",",
"value",
"=",
"ref",
".",
"_element",
".",
"_export_js",
"(",
"js_indent",
",",
"-",
"1",
"if",
"cname",
"else",
"indent",
",",
"classes",
",",
"cname",
")",
")",
")",
"if",
"'Rule'",
"in",
"classes",
":",
"classes",
".",
"remove",
"(",
"'Rule'",
")",
"return",
"js_template",
".",
"format",
"(",
"name",
"=",
"self",
".",
"__class__",
".",
"__name__",
",",
"indent",
"=",
"js_indent",
",",
"js_module",
"=",
"js_module_name",
",",
"datetime",
"=",
"time",
".",
"strftime",
"(",
"'%Y-%m-%d %H:%M:%S'",
",",
"time",
".",
"localtime",
"(",
")",
")",
",",
"language",
"=",
"'\\n'",
".",
"join",
"(",
"language",
")",
",",
"refs",
"=",
"'\\n{}'",
".",
"format",
"(",
"'\\n'",
".",
"join",
"(",
"refs",
")",
")",
",",
"arguments",
"=",
"',\\n'",
".",
"join",
"(",
"map",
"(",
"lambda",
"s",
":",
"js_indent",
"*",
"3",
"+",
"s",
",",
"classes",
")",
")",
",",
"re_keywords",
"=",
"self",
".",
"RE_KEYWORDS",
".",
"pattern",
".",
"replace",
"(",
"'\\\\'",
",",
"'\\\\\\\\'",
")",
",",
"classes",
"=",
"', '",
".",
"join",
"(",
"classes",
")",
",",
"constructors",
"=",
"',\\n'",
".",
"join",
"(",
"map",
"(",
"lambda",
"s",
":",
"js_indent",
"+",
"s",
",",
"[",
"'.'",
".",
"join",
"(",
"[",
"'window'",
",",
"js_module_name",
",",
"n",
"]",
")",
"for",
"n",
"in",
"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 grammar and an export of the final result is
required.'''
language = []
classes = {'Grammar'}
indent = 0
for name in self._order:
elem = getattr(self, name, None)
if not isinstance(elem, Element):
continue
if not hasattr(elem, '_export_py'):
continue
language.append('{indent}{name} = {value}'.format(
indent=py_indent,
name=name,
value=elem._export_py(py_indent, indent, classes)))
for name, ref in self._refs.items():
language.append(
'{indent}{name} = {value}'
.format(
indent=py_indent,
name=name,
value=ref._element._export_py(
py_indent,
indent,
classes)))
return py_template.format(
name=self.__class__.__name__,
indent=py_indent,
py_module=py_module_name,
datetime=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()),
language='\n'.join(language),
re_keywords=self.RE_KEYWORDS.pattern.replace('\\', '\\\\'),
imports='\n'.join(
map(lambda s: s, [
' '.join(['from', py_module_name, 'import', n])
for n in classes if n != 'Rule']))) | 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 grammar and an export of the final result is
required.'''
language = []
classes = {'Grammar'}
indent = 0
for name in self._order:
elem = getattr(self, name, None)
if not isinstance(elem, Element):
continue
if not hasattr(elem, '_export_py'):
continue
language.append('{indent}{name} = {value}'.format(
indent=py_indent,
name=name,
value=elem._export_py(py_indent, indent, classes)))
for name, ref in self._refs.items():
language.append(
'{indent}{name} = {value}'
.format(
indent=py_indent,
name=name,
value=ref._element._export_py(
py_indent,
indent,
classes)))
return py_template.format(
name=self.__class__.__name__,
indent=py_indent,
py_module=py_module_name,
datetime=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()),
language='\n'.join(language),
re_keywords=self.RE_KEYWORDS.pattern.replace('\\', '\\\\'),
imports='\n'.join(
map(lambda s: s, [
' '.join(['from', py_module_name, 'import', n])
for n in classes if n != 'Rule']))) | [
"def",
"export_py",
"(",
"self",
",",
"py_module_name",
"=",
"PY_MODULE_NAME",
",",
"py_template",
"=",
"PY_TEMPLATE",
",",
"py_indent",
"=",
"PY_INDENTATION",
")",
":",
"language",
"=",
"[",
"]",
"classes",
"=",
"{",
"'Grammar'",
"}",
"indent",
"=",
"0",
"for",
"name",
"in",
"self",
".",
"_order",
":",
"elem",
"=",
"getattr",
"(",
"self",
",",
"name",
",",
"None",
")",
"if",
"not",
"isinstance",
"(",
"elem",
",",
"Element",
")",
":",
"continue",
"if",
"not",
"hasattr",
"(",
"elem",
",",
"'_export_py'",
")",
":",
"continue",
"language",
".",
"append",
"(",
"'{indent}{name} = {value}'",
".",
"format",
"(",
"indent",
"=",
"py_indent",
",",
"name",
"=",
"name",
",",
"value",
"=",
"elem",
".",
"_export_py",
"(",
"py_indent",
",",
"indent",
",",
"classes",
")",
")",
")",
"for",
"name",
",",
"ref",
"in",
"self",
".",
"_refs",
".",
"items",
"(",
")",
":",
"language",
".",
"append",
"(",
"'{indent}{name} = {value}'",
".",
"format",
"(",
"indent",
"=",
"py_indent",
",",
"name",
"=",
"name",
",",
"value",
"=",
"ref",
".",
"_element",
".",
"_export_py",
"(",
"py_indent",
",",
"indent",
",",
"classes",
")",
")",
")",
"return",
"py_template",
".",
"format",
"(",
"name",
"=",
"self",
".",
"__class__",
".",
"__name__",
",",
"indent",
"=",
"py_indent",
",",
"py_module",
"=",
"py_module_name",
",",
"datetime",
"=",
"time",
".",
"strftime",
"(",
"'%Y-%m-%d %H:%M:%S'",
",",
"time",
".",
"localtime",
"(",
")",
")",
",",
"language",
"=",
"'\\n'",
".",
"join",
"(",
"language",
")",
",",
"re_keywords",
"=",
"self",
".",
"RE_KEYWORDS",
".",
"pattern",
".",
"replace",
"(",
"'\\\\'",
",",
"'\\\\\\\\'",
")",
",",
"imports",
"=",
"'\\n'",
".",
"join",
"(",
"map",
"(",
"lambda",
"s",
":",
"s",
",",
"[",
"' '",
".",
"join",
"(",
"[",
"'from'",
",",
"py_module_name",
",",
"'import'",
",",
"n",
"]",
")",
"for",
"n",
"in",
"classes",
"if",
"n",
"!=",
"'Rule'",
"]",
")",
")",
")"
] | 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",
"an",
"export",
"of",
"the",
"final",
"result",
"is",
"required",
"."
] | 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 = self.RE_KEYWORDS.pattern.replace('`', '` + "`" + `')
if not pattern.startswith('^'):
pattern = '^' + pattern
for name in self._order:
elem = getattr(self, name, None)
if not isinstance(elem, Element):
continue
if not hasattr(elem, '_export_go'):
continue
language.append('{indent}{name} := {value}'.format(
indent=go_indent,
name=camel_case(name),
value=elem._export_go(go_indent, indent, enums)))
for name, ref in self._refs.items():
language.append(
'{indent}{name}.Set({value})'
.format(
indent=go_indent,
name=camel_case(name),
value=ref._element._export_go(
go_indent,
indent,
enums)))
enums = ' = iota\n'.join([
'{}{}'.format(go_indent, gid)
for gid in sorted(enums)]) + ' = iota'
return go_template.format(
name=self.__class__.__name__,
indent=go_indent,
package=go_package,
datetime=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()),
language='\n'.join(language),
re_keywords=pattern,
enums=enums) | 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 = self.RE_KEYWORDS.pattern.replace('`', '` + "`" + `')
if not pattern.startswith('^'):
pattern = '^' + pattern
for name in self._order:
elem = getattr(self, name, None)
if not isinstance(elem, Element):
continue
if not hasattr(elem, '_export_go'):
continue
language.append('{indent}{name} := {value}'.format(
indent=go_indent,
name=camel_case(name),
value=elem._export_go(go_indent, indent, enums)))
for name, ref in self._refs.items():
language.append(
'{indent}{name}.Set({value})'
.format(
indent=go_indent,
name=camel_case(name),
value=ref._element._export_go(
go_indent,
indent,
enums)))
enums = ' = iota\n'.join([
'{}{}'.format(go_indent, gid)
for gid in sorted(enums)]) + ' = iota'
return go_template.format(
name=self.__class__.__name__,
indent=go_indent,
package=go_package,
datetime=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()),
language='\n'.join(language),
re_keywords=pattern,
enums=enums) | [
"def",
"export_go",
"(",
"self",
",",
"go_template",
"=",
"GO_TEMPLATE",
",",
"go_indent",
"=",
"GO_INDENTATION",
",",
"go_package",
"=",
"GO_PACKAGE",
")",
":",
"language",
"=",
"[",
"]",
"enums",
"=",
"set",
"(",
")",
"indent",
"=",
"0",
"pattern",
"=",
"self",
".",
"RE_KEYWORDS",
".",
"pattern",
".",
"replace",
"(",
"'`'",
",",
"'` + \"`\" + `'",
")",
"if",
"not",
"pattern",
".",
"startswith",
"(",
"'^'",
")",
":",
"pattern",
"=",
"'^'",
"+",
"pattern",
"for",
"name",
"in",
"self",
".",
"_order",
":",
"elem",
"=",
"getattr",
"(",
"self",
",",
"name",
",",
"None",
")",
"if",
"not",
"isinstance",
"(",
"elem",
",",
"Element",
")",
":",
"continue",
"if",
"not",
"hasattr",
"(",
"elem",
",",
"'_export_go'",
")",
":",
"continue",
"language",
".",
"append",
"(",
"'{indent}{name} := {value}'",
".",
"format",
"(",
"indent",
"=",
"go_indent",
",",
"name",
"=",
"camel_case",
"(",
"name",
")",
",",
"value",
"=",
"elem",
".",
"_export_go",
"(",
"go_indent",
",",
"indent",
",",
"enums",
")",
")",
")",
"for",
"name",
",",
"ref",
"in",
"self",
".",
"_refs",
".",
"items",
"(",
")",
":",
"language",
".",
"append",
"(",
"'{indent}{name}.Set({value})'",
".",
"format",
"(",
"indent",
"=",
"go_indent",
",",
"name",
"=",
"camel_case",
"(",
"name",
")",
",",
"value",
"=",
"ref",
".",
"_element",
".",
"_export_go",
"(",
"go_indent",
",",
"indent",
",",
"enums",
")",
")",
")",
"enums",
"=",
"' = iota\\n'",
".",
"join",
"(",
"[",
"'{}{}'",
".",
"format",
"(",
"go_indent",
",",
"gid",
")",
"for",
"gid",
"in",
"sorted",
"(",
"enums",
")",
"]",
")",
"+",
"' = iota'",
"return",
"go_template",
".",
"format",
"(",
"name",
"=",
"self",
".",
"__class__",
".",
"__name__",
",",
"indent",
"=",
"go_indent",
",",
"package",
"=",
"go_package",
",",
"datetime",
"=",
"time",
".",
"strftime",
"(",
"'%Y-%m-%d %H:%M:%S'",
",",
"time",
".",
"localtime",
"(",
")",
")",
",",
"language",
"=",
"'\\n'",
".",
"join",
"(",
"language",
")",
",",
"re_keywords",
"=",
"pattern",
",",
"enums",
"=",
"enums",
")"
] | 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 = set()
classes = {'jleri.Grammar', 'jleri.Element'}
refs = []
indent = 0
pattern = self.RE_KEYWORDS.pattern.replace('\\', '\\\\')
if not pattern.startswith('^'):
pattern = '^' + pattern
for name in self._order:
elem = getattr(self, name, None)
if not isinstance(elem, Element):
continue
if not hasattr(elem, '_export_java'):
continue
language.append(
'{indent}private static final Element {name} = {value};'
.format(
indent=java_indent,
name=name.upper(),
value=elem._export_java(
java_indent, indent, enums, classes)))
enum_str = ',\n'.join([
'{indent}{indent}{gid}'.format(
indent=java_indent,
gid=gid)
for gid in sorted(enums)])
for name, ref in self._refs.items():
refs.append(
'{indent}{indent}((Ref) {name}).set({value});'
.format(
indent=java_indent,
name=name.upper(),
value=ref._element._export_java(
java_indent,
-2,
enums,
classes)))
return java_template.format(
name=self.__class__.__name__,
imports='\n'.join(
map(lambda s: s, [
'import {};'.format(c)
for c in sorted(classes) if c != 'Rule'])),
indent=java_indent,
package='' if java_package is None
else 'package {};\n'.format(java_package),
datetime=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()),
language='\n'.join(language),
re_keywords=pattern,
refs='' if not refs else '{}\n'.format('\n'.join(refs)),
enums=enum_str,
public='public ' if is_public else '') | 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 = set()
classes = {'jleri.Grammar', 'jleri.Element'}
refs = []
indent = 0
pattern = self.RE_KEYWORDS.pattern.replace('\\', '\\\\')
if not pattern.startswith('^'):
pattern = '^' + pattern
for name in self._order:
elem = getattr(self, name, None)
if not isinstance(elem, Element):
continue
if not hasattr(elem, '_export_java'):
continue
language.append(
'{indent}private static final Element {name} = {value};'
.format(
indent=java_indent,
name=name.upper(),
value=elem._export_java(
java_indent, indent, enums, classes)))
enum_str = ',\n'.join([
'{indent}{indent}{gid}'.format(
indent=java_indent,
gid=gid)
for gid in sorted(enums)])
for name, ref in self._refs.items():
refs.append(
'{indent}{indent}((Ref) {name}).set({value});'
.format(
indent=java_indent,
name=name.upper(),
value=ref._element._export_java(
java_indent,
-2,
enums,
classes)))
return java_template.format(
name=self.__class__.__name__,
imports='\n'.join(
map(lambda s: s, [
'import {};'.format(c)
for c in sorted(classes) if c != 'Rule'])),
indent=java_indent,
package='' if java_package is None
else 'package {};\n'.format(java_package),
datetime=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()),
language='\n'.join(language),
re_keywords=pattern,
refs='' if not refs else '{}\n'.format('\n'.join(refs)),
enums=enum_str,
public='public ' if is_public else '') | [
"def",
"export_java",
"(",
"self",
",",
"java_template",
"=",
"JAVA_TEMPLATE",
",",
"java_indent",
"=",
"JAVA_INDENTATION",
",",
"java_package",
"=",
"JAVA_PACKAGE",
",",
"is_public",
"=",
"True",
")",
":",
"language",
"=",
"[",
"]",
"enums",
"=",
"set",
"(",
")",
"classes",
"=",
"{",
"'jleri.Grammar'",
",",
"'jleri.Element'",
"}",
"refs",
"=",
"[",
"]",
"indent",
"=",
"0",
"pattern",
"=",
"self",
".",
"RE_KEYWORDS",
".",
"pattern",
".",
"replace",
"(",
"'\\\\'",
",",
"'\\\\\\\\'",
")",
"if",
"not",
"pattern",
".",
"startswith",
"(",
"'^'",
")",
":",
"pattern",
"=",
"'^'",
"+",
"pattern",
"for",
"name",
"in",
"self",
".",
"_order",
":",
"elem",
"=",
"getattr",
"(",
"self",
",",
"name",
",",
"None",
")",
"if",
"not",
"isinstance",
"(",
"elem",
",",
"Element",
")",
":",
"continue",
"if",
"not",
"hasattr",
"(",
"elem",
",",
"'_export_java'",
")",
":",
"continue",
"language",
".",
"append",
"(",
"'{indent}private static final Element {name} = {value};'",
".",
"format",
"(",
"indent",
"=",
"java_indent",
",",
"name",
"=",
"name",
".",
"upper",
"(",
")",
",",
"value",
"=",
"elem",
".",
"_export_java",
"(",
"java_indent",
",",
"indent",
",",
"enums",
",",
"classes",
")",
")",
")",
"enum_str",
"=",
"',\\n'",
".",
"join",
"(",
"[",
"'{indent}{indent}{gid}'",
".",
"format",
"(",
"indent",
"=",
"java_indent",
",",
"gid",
"=",
"gid",
")",
"for",
"gid",
"in",
"sorted",
"(",
"enums",
")",
"]",
")",
"for",
"name",
",",
"ref",
"in",
"self",
".",
"_refs",
".",
"items",
"(",
")",
":",
"refs",
".",
"append",
"(",
"'{indent}{indent}((Ref) {name}).set({value});'",
".",
"format",
"(",
"indent",
"=",
"java_indent",
",",
"name",
"=",
"name",
".",
"upper",
"(",
")",
",",
"value",
"=",
"ref",
".",
"_element",
".",
"_export_java",
"(",
"java_indent",
",",
"-",
"2",
",",
"enums",
",",
"classes",
")",
")",
")",
"return",
"java_template",
".",
"format",
"(",
"name",
"=",
"self",
".",
"__class__",
".",
"__name__",
",",
"imports",
"=",
"'\\n'",
".",
"join",
"(",
"map",
"(",
"lambda",
"s",
":",
"s",
",",
"[",
"'import {};'",
".",
"format",
"(",
"c",
")",
"for",
"c",
"in",
"sorted",
"(",
"classes",
")",
"if",
"c",
"!=",
"'Rule'",
"]",
")",
")",
",",
"indent",
"=",
"java_indent",
",",
"package",
"=",
"''",
"if",
"java_package",
"is",
"None",
"else",
"'package {};\\n'",
".",
"format",
"(",
"java_package",
")",
",",
"datetime",
"=",
"time",
".",
"strftime",
"(",
"'%Y-%m-%d %H:%M:%S'",
",",
"time",
".",
"localtime",
"(",
")",
")",
",",
"language",
"=",
"'\\n'",
".",
"join",
"(",
"language",
")",
",",
"re_keywords",
"=",
"pattern",
",",
"refs",
"=",
"''",
"if",
"not",
"refs",
"else",
"'{}\\n'",
".",
"format",
"(",
"'\\n'",
".",
"join",
"(",
"refs",
")",
")",
",",
"enums",
"=",
"enum_str",
",",
"public",
"=",
"'public '",
"if",
"is_public",
"else",
"''",
")"
] | 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 the end of the string when is_valid is True)
- expecting: a list containing possible elements at position
'pos' in the string.
- tree: the parse_tree containing a structured
result for the given string.
'''
self._string = string
self._expecting = Expecting()
self._cached_kw_match.clear()
self._len_string = len(string)
self._pos = None
tree = Node(self._element, string, 0, self._len_string)
node_res = Result(*self._walk(
self._element,
0,
tree.children,
self._element,
True))
# get rest if anything
rest = self._string[node_res.pos:].lstrip()
# set is_valid to False if we have 'rest' left.
if node_res.is_valid and rest:
node_res.is_valid = False
# add end_of_statement to expecting if this is possible
if not self._expecting.required and rest:
self._expecting.set_mode_required(node_res.pos, True)
self._expecting.update(end_of_statement, node_res.pos)
node_res.expecting = self._expecting.get_expecting()
# add expecting and correct pos to node_res if node_res is not valid
if not node_res.is_valid:
node_res.pos = self._expecting.pos
node_res.tree = tree
return node_res | 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 the end of the string when is_valid is True)
- expecting: a list containing possible elements at position
'pos' in the string.
- tree: the parse_tree containing a structured
result for the given string.
'''
self._string = string
self._expecting = Expecting()
self._cached_kw_match.clear()
self._len_string = len(string)
self._pos = None
tree = Node(self._element, string, 0, self._len_string)
node_res = Result(*self._walk(
self._element,
0,
tree.children,
self._element,
True))
# get rest if anything
rest = self._string[node_res.pos:].lstrip()
# set is_valid to False if we have 'rest' left.
if node_res.is_valid and rest:
node_res.is_valid = False
# add end_of_statement to expecting if this is possible
if not self._expecting.required and rest:
self._expecting.set_mode_required(node_res.pos, True)
self._expecting.update(end_of_statement, node_res.pos)
node_res.expecting = self._expecting.get_expecting()
# add expecting and correct pos to node_res if node_res is not valid
if not node_res.is_valid:
node_res.pos = self._expecting.pos
node_res.tree = tree
return node_res | [
"def",
"parse",
"(",
"self",
",",
"string",
")",
":",
"self",
".",
"_string",
"=",
"string",
"self",
".",
"_expecting",
"=",
"Expecting",
"(",
")",
"self",
".",
"_cached_kw_match",
".",
"clear",
"(",
")",
"self",
".",
"_len_string",
"=",
"len",
"(",
"string",
")",
"self",
".",
"_pos",
"=",
"None",
"tree",
"=",
"Node",
"(",
"self",
".",
"_element",
",",
"string",
",",
"0",
",",
"self",
".",
"_len_string",
")",
"node_res",
"=",
"Result",
"(",
"*",
"self",
".",
"_walk",
"(",
"self",
".",
"_element",
",",
"0",
",",
"tree",
".",
"children",
",",
"self",
".",
"_element",
",",
"True",
")",
")",
"# get rest if anything",
"rest",
"=",
"self",
".",
"_string",
"[",
"node_res",
".",
"pos",
":",
"]",
".",
"lstrip",
"(",
")",
"# set is_valid to False if we have 'rest' left.",
"if",
"node_res",
".",
"is_valid",
"and",
"rest",
":",
"node_res",
".",
"is_valid",
"=",
"False",
"# add end_of_statement to expecting if this is possible",
"if",
"not",
"self",
".",
"_expecting",
".",
"required",
"and",
"rest",
":",
"self",
".",
"_expecting",
".",
"set_mode_required",
"(",
"node_res",
".",
"pos",
",",
"True",
")",
"self",
".",
"_expecting",
".",
"update",
"(",
"end_of_statement",
",",
"node_res",
".",
"pos",
")",
"node_res",
".",
"expecting",
"=",
"self",
".",
"_expecting",
".",
"get_expecting",
"(",
")",
"# add expecting and correct pos to node_res if node_res is not valid",
"if",
"not",
"node_res",
".",
"is_valid",
":",
"node_res",
".",
"pos",
"=",
"self",
".",
"_expecting",
".",
"pos",
"node_res",
".",
"tree",
"=",
"tree",
"return",
"node_res"
] | 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 True)
- expecting: a list containing possible elements at position
'pos' in the string.
- tree: the parse_tree containing a structured
result for the given string. | [
"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()
assert wf == w and hf == h, 'All canvas objects need to have same size'
buffers.append(np.fromstring(f.canvas.tostring_rgb(), dtype=np.uint8).reshape(h, w, 3))
return np.stack(buffers) | 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()
assert wf == w and hf == h, 'All canvas objects need to have same size'
buffers.append(np.fromstring(f.canvas.tostring_rgb(), dtype=np.uint8).reshape(h, w, 3))
return np.stack(buffers) | [
"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_width_height",
"(",
")",
"for",
"f",
"in",
"figs",
":",
"wf",
",",
"hf",
"=",
"f",
".",
"canvas",
".",
"get_width_height",
"(",
")",
"assert",
"wf",
"==",
"w",
"and",
"hf",
"==",
"h",
",",
"'All canvas objects need to have same size'",
"buffers",
".",
"append",
"(",
"np",
".",
"fromstring",
"(",
"f",
".",
"canvas",
".",
"tostring_rgb",
"(",
")",
",",
"dtype",
"=",
"np",
".",
"uint8",
")",
".",
"reshape",
"(",
"h",
",",
"w",
",",
"3",
")",
")",
"return",
"np",
".",
"stack",
"(",
"buffers",
")"
] | 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
where `*args` can be any positional argument and `**kwargs` are any
keyword arguments. The decorated function returns a tensor of shape
`[NumFigures, Height, Width, 3]` of type `tf.uint8`.
The drawing code is invoked during running of TensorFlow sessions,
at a time when all positional tensor arguments have been evaluated
by the session. The decorated function is then passed the tensor values.
All non tensor arguments remain unchanged.
'''
name = tf_pyfunc_kwargs.pop('name', func.__name__)
@wraps(func)
def wrapper(*func_args, **func_kwargs):
tf_args = PositionalTensorArgs(func_args)
def pyfnc_callee(*tensor_values, **unused):
try:
figs = as_list(func(*tf_args.mix_args(tensor_values), **func_kwargs))
for f in figs:
f.canvas.draw()
return figure_buffer(figs)
except Exception:
print('-'*5 + 'tfmpl catched exception' + '-'*5)
print(traceback.format_exc())
print('-'*20)
raise
return tf.py_func(pyfnc_callee, tf_args.tensor_args, tf.uint8, name=name, **tf_pyfunc_kwargs)
return wrapper | 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
where `*args` can be any positional argument and `**kwargs` are any
keyword arguments. The decorated function returns a tensor of shape
`[NumFigures, Height, Width, 3]` of type `tf.uint8`.
The drawing code is invoked during running of TensorFlow sessions,
at a time when all positional tensor arguments have been evaluated
by the session. The decorated function is then passed the tensor values.
All non tensor arguments remain unchanged.
'''
name = tf_pyfunc_kwargs.pop('name', func.__name__)
@wraps(func)
def wrapper(*func_args, **func_kwargs):
tf_args = PositionalTensorArgs(func_args)
def pyfnc_callee(*tensor_values, **unused):
try:
figs = as_list(func(*tf_args.mix_args(tensor_values), **func_kwargs))
for f in figs:
f.canvas.draw()
return figure_buffer(figs)
except Exception:
print('-'*5 + 'tfmpl catched exception' + '-'*5)
print(traceback.format_exc())
print('-'*20)
raise
return tf.py_func(pyfnc_callee, tf_args.tensor_args, tf.uint8, name=name, **tf_pyfunc_kwargs)
return wrapper | [
"def",
"figure_tensor",
"(",
"func",
",",
"*",
"*",
"tf_pyfunc_kwargs",
")",
":",
"name",
"=",
"tf_pyfunc_kwargs",
".",
"pop",
"(",
"'name'",
",",
"func",
".",
"__name__",
")",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"func_args",
",",
"*",
"*",
"func_kwargs",
")",
":",
"tf_args",
"=",
"PositionalTensorArgs",
"(",
"func_args",
")",
"def",
"pyfnc_callee",
"(",
"*",
"tensor_values",
",",
"*",
"*",
"unused",
")",
":",
"try",
":",
"figs",
"=",
"as_list",
"(",
"func",
"(",
"*",
"tf_args",
".",
"mix_args",
"(",
"tensor_values",
")",
",",
"*",
"*",
"func_kwargs",
")",
")",
"for",
"f",
"in",
"figs",
":",
"f",
".",
"canvas",
".",
"draw",
"(",
")",
"return",
"figure_buffer",
"(",
"figs",
")",
"except",
"Exception",
":",
"print",
"(",
"'-'",
"*",
"5",
"+",
"'tfmpl catched exception'",
"+",
"'-'",
"*",
"5",
")",
"print",
"(",
"traceback",
".",
"format_exc",
"(",
")",
")",
"print",
"(",
"'-'",
"*",
"20",
")",
"raise",
"return",
"tf",
".",
"py_func",
"(",
"pyfnc_callee",
",",
"tf_args",
".",
"tensor_args",
",",
"tf",
".",
"uint8",
",",
"name",
"=",
"name",
",",
"*",
"*",
"tf_pyfunc_kwargs",
")",
"return",
"wrapper"
] | 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 `**kwargs` are any
keyword arguments. The decorated function returns a tensor of shape
`[NumFigures, Height, Width, 3]` of type `tf.uint8`.
The drawing code is invoked during running of TensorFlow sessions,
at a time when all positional tensor arguments have been evaluated
by the session. The decorated function is then passed the tensor values.
All non tensor arguments remain unchanged. | [
"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) -> iterable of artists
where `*args` can be any positional argument and `**kwargs` are any
keyword arguments. The decorated function returns a tensor of shape
`[NumFigures, Height, Width, 3]` of type `tf.uint8`.
Besides the actual drawing function, `blittable_figure_tensor` requires
a `init_func` argument with the following signature
def init(*args, **kwargs) -> iterable of figures, iterable of artists
The init function is meant to create and initialize figures, as well as to
perform drawing that is meant to be done only once. Any set of artits to be
updated in later drawing calls should also be allocated in init. The
initialize function must have the same positional and keyword arguments
as the decorated function. It is called once before the decorated function
is called.
The drawing code / init function is invoked during running of TensorFlow
sessions, at a time when all positional tensor arguments have been
evaluated by the session. The decorated / init function is then passed the
tensor values. All non tensor arguments remain unchanged.
'''
name = tf_pyfunc_kwargs.pop('name', func.__name__)
assert callable(init_func), 'Init function not callable'
@wraps(func)
def wrapper(*func_args, **func_kwargs):
figs = None
bgs = None
tf_args = PositionalTensorArgs(func_args)
def pyfnc_callee(*tensor_values, **unused):
try:
nonlocal figs, bgs
pos_args = tf_args.mix_args(tensor_values)
if figs is None:
figs, artists = init_func(*pos_args, **func_kwargs)
figs = as_list(figs)
artists = as_list(artists)
for f in figs:
f.canvas.draw()
for a in artists:
a.set_animated(True)
bgs = [f.canvas.copy_from_bbox(f.bbox) for f in figs]
artists = as_list(func(*pos_args, **func_kwargs))
for f, bg in zip(figs, bgs):
f.canvas.restore_region(bg)
for a in artists:
a.axes.draw_artist(a)
for f in figs:
f.canvas.blit(f.bbox)
return figure_buffer(figs)
except Exception:
print('-'*5 + 'tfmpl catched exception' + '-'*5)
print(traceback.format_exc())
print('-'*20)
raise
return tf.py_func(pyfnc_callee, tf_args.tensor_args, tf.uint8, name=name, **tf_pyfunc_kwargs)
return wrapper | 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) -> iterable of artists
where `*args` can be any positional argument and `**kwargs` are any
keyword arguments. The decorated function returns a tensor of shape
`[NumFigures, Height, Width, 3]` of type `tf.uint8`.
Besides the actual drawing function, `blittable_figure_tensor` requires
a `init_func` argument with the following signature
def init(*args, **kwargs) -> iterable of figures, iterable of artists
The init function is meant to create and initialize figures, as well as to
perform drawing that is meant to be done only once. Any set of artits to be
updated in later drawing calls should also be allocated in init. The
initialize function must have the same positional and keyword arguments
as the decorated function. It is called once before the decorated function
is called.
The drawing code / init function is invoked during running of TensorFlow
sessions, at a time when all positional tensor arguments have been
evaluated by the session. The decorated / init function is then passed the
tensor values. All non tensor arguments remain unchanged.
'''
name = tf_pyfunc_kwargs.pop('name', func.__name__)
assert callable(init_func), 'Init function not callable'
@wraps(func)
def wrapper(*func_args, **func_kwargs):
figs = None
bgs = None
tf_args = PositionalTensorArgs(func_args)
def pyfnc_callee(*tensor_values, **unused):
try:
nonlocal figs, bgs
pos_args = tf_args.mix_args(tensor_values)
if figs is None:
figs, artists = init_func(*pos_args, **func_kwargs)
figs = as_list(figs)
artists = as_list(artists)
for f in figs:
f.canvas.draw()
for a in artists:
a.set_animated(True)
bgs = [f.canvas.copy_from_bbox(f.bbox) for f in figs]
artists = as_list(func(*pos_args, **func_kwargs))
for f, bg in zip(figs, bgs):
f.canvas.restore_region(bg)
for a in artists:
a.axes.draw_artist(a)
for f in figs:
f.canvas.blit(f.bbox)
return figure_buffer(figs)
except Exception:
print('-'*5 + 'tfmpl catched exception' + '-'*5)
print(traceback.format_exc())
print('-'*20)
raise
return tf.py_func(pyfnc_callee, tf_args.tensor_args, tf.uint8, name=name, **tf_pyfunc_kwargs)
return wrapper | [
"def",
"blittable_figure_tensor",
"(",
"func",
",",
"init_func",
",",
"*",
"*",
"tf_pyfunc_kwargs",
")",
":",
"name",
"=",
"tf_pyfunc_kwargs",
".",
"pop",
"(",
"'name'",
",",
"func",
".",
"__name__",
")",
"assert",
"callable",
"(",
"init_func",
")",
",",
"'Init function not callable'",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"func_args",
",",
"*",
"*",
"func_kwargs",
")",
":",
"figs",
"=",
"None",
"bgs",
"=",
"None",
"tf_args",
"=",
"PositionalTensorArgs",
"(",
"func_args",
")",
"def",
"pyfnc_callee",
"(",
"*",
"tensor_values",
",",
"*",
"*",
"unused",
")",
":",
"try",
":",
"nonlocal",
"figs",
",",
"bgs",
"pos_args",
"=",
"tf_args",
".",
"mix_args",
"(",
"tensor_values",
")",
"if",
"figs",
"is",
"None",
":",
"figs",
",",
"artists",
"=",
"init_func",
"(",
"*",
"pos_args",
",",
"*",
"*",
"func_kwargs",
")",
"figs",
"=",
"as_list",
"(",
"figs",
")",
"artists",
"=",
"as_list",
"(",
"artists",
")",
"for",
"f",
"in",
"figs",
":",
"f",
".",
"canvas",
".",
"draw",
"(",
")",
"for",
"a",
"in",
"artists",
":",
"a",
".",
"set_animated",
"(",
"True",
")",
"bgs",
"=",
"[",
"f",
".",
"canvas",
".",
"copy_from_bbox",
"(",
"f",
".",
"bbox",
")",
"for",
"f",
"in",
"figs",
"]",
"artists",
"=",
"as_list",
"(",
"func",
"(",
"*",
"pos_args",
",",
"*",
"*",
"func_kwargs",
")",
")",
"for",
"f",
",",
"bg",
"in",
"zip",
"(",
"figs",
",",
"bgs",
")",
":",
"f",
".",
"canvas",
".",
"restore_region",
"(",
"bg",
")",
"for",
"a",
"in",
"artists",
":",
"a",
".",
"axes",
".",
"draw_artist",
"(",
"a",
")",
"for",
"f",
"in",
"figs",
":",
"f",
".",
"canvas",
".",
"blit",
"(",
"f",
".",
"bbox",
")",
"return",
"figure_buffer",
"(",
"figs",
")",
"except",
"Exception",
":",
"print",
"(",
"'-'",
"*",
"5",
"+",
"'tfmpl catched exception'",
"+",
"'-'",
"*",
"5",
")",
"print",
"(",
"traceback",
".",
"format_exc",
"(",
")",
")",
"print",
"(",
"'-'",
"*",
"20",
")",
"raise",
"return",
"tf",
".",
"py_func",
"(",
"pyfnc_callee",
",",
"tf_args",
".",
"tensor_args",
",",
"tf",
".",
"uint8",
",",
"name",
"=",
"name",
",",
"*",
"*",
"tf_pyfunc_kwargs",
")",
"return",
"wrapper"
] | 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 argument and `**kwargs` are any
keyword arguments. The decorated function returns a tensor of shape
`[NumFigures, Height, Width, 3]` of type `tf.uint8`.
Besides the actual drawing function, `blittable_figure_tensor` requires
a `init_func` argument with the following signature
def init(*args, **kwargs) -> iterable of figures, iterable of artists
The init function is meant to create and initialize figures, as well as to
perform drawing that is meant to be done only once. Any set of artits to be
updated in later drawing calls should also be allocated in init. The
initialize function must have the same positional and keyword arguments
as the decorated function. It is called once before the decorated function
is called.
The drawing code / init function is invoked during running of TensorFlow
sessions, at a time when all positional tensor arguments have been
evaluated by the session. The decorated / init function is then passed the
tensor values. All non tensor arguments remain unchanged. | [
"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) for x in range(10)],
normalize=True
)
return fig | 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) for x in range(10)],
normalize=True
)
return fig | [
"def",
"draw_confusion_matrix",
"(",
"matrix",
")",
":",
"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",
")",
"for",
"x",
"in",
"range",
"(",
"10",
")",
"]",
",",
"normalize",
"=",
"True",
")",
"return",
"fig"
] | 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 classification
predicitions: array-like
1-D array of predicted label classes
num_classes: scalar
Total number of classes
Returns
-------
matrix : NxN array
Array of shape [num_classes, num_classes] containing the confusion values.
'''
assert len(labels) == len(predictions)
cm = np.zeros((num_classes, num_classes), dtype=np.int32)
for i in range(len(labels)):
cm[labels[i], predictions[i]] += 1
return cm | 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 classification
predicitions: array-like
1-D array of predicted label classes
num_classes: scalar
Total number of classes
Returns
-------
matrix : NxN array
Array of shape [num_classes, num_classes] containing the confusion values.
'''
assert len(labels) == len(predictions)
cm = np.zeros((num_classes, num_classes), dtype=np.int32)
for i in range(len(labels)):
cm[labels[i], predictions[i]] += 1
return cm | [
"def",
"from_labels_and_predictions",
"(",
"labels",
",",
"predictions",
",",
"num_classes",
")",
":",
"assert",
"len",
"(",
"labels",
")",
"==",
"len",
"(",
"predictions",
")",
"cm",
"=",
"np",
".",
"zeros",
"(",
"(",
"num_classes",
",",
"num_classes",
")",
",",
"dtype",
"=",
"np",
".",
"int32",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"labels",
")",
")",
":",
"cm",
"[",
"labels",
"[",
"i",
"]",
",",
"predictions",
"[",
"i",
"]",
"]",
"+=",
"1",
"return",
"cm"
] | 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 classes
num_classes: scalar
Total number of classes
Returns
-------
matrix : NxN array
Array of shape [num_classes, num_classes] containing the confusion values. | [
"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
------
axis_labels : array-like
Array of size N containing axis labels
normalize : bool
Whether to plot counts or ratios.
'''
cm = np.asarray(cm)
num_classes = cm.shape[0]
if normalize:
with np.errstate(invalid='ignore', divide='ignore'):
cm = cm / cm.sum(1, keepdims=True)
cm = np.nan_to_num(cm, copy=True)
po = np.get_printoptions()
np.set_printoptions(precision=2)
ax.imshow(cm, cmap='Oranges')
ticks = np.arange(num_classes)
ax.set_xlabel('Predicted')
ax.set_xticks(ticks)
ax.xaxis.set_label_position('bottom')
ax.xaxis.tick_bottom()
ax.set_ylabel('Actual')
ax.set_yticks(ticks)
ax.yaxis.set_label_position('left')
ax.yaxis.tick_left()
if axis_labels is not None:
ticklabels = [re.sub(r'([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))', r'\1 ', x) for x in axis_labels]
ticklabels = ['\n'.join(wrap(l, 20)) for l in ticklabels]
ax.set_xticklabels(ticklabels, rotation=-90, ha='center')
ax.set_yticklabels(ticklabels, va ='center')
for i, j in product(range(num_classes), range(num_classes)):
if cm[i,j] == 0:
txt = '.'
elif normalize:
txt = '{:.2f}'.format(cm[i,j])
else:
txt = '{}'.format(cm[i,j])
ax.text(j, i, txt, horizontalalignment="center", verticalalignment='center', color= "black", fontsize=7)
np.set_printoptions(**po) | 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
------
axis_labels : array-like
Array of size N containing axis labels
normalize : bool
Whether to plot counts or ratios.
'''
cm = np.asarray(cm)
num_classes = cm.shape[0]
if normalize:
with np.errstate(invalid='ignore', divide='ignore'):
cm = cm / cm.sum(1, keepdims=True)
cm = np.nan_to_num(cm, copy=True)
po = np.get_printoptions()
np.set_printoptions(precision=2)
ax.imshow(cm, cmap='Oranges')
ticks = np.arange(num_classes)
ax.set_xlabel('Predicted')
ax.set_xticks(ticks)
ax.xaxis.set_label_position('bottom')
ax.xaxis.tick_bottom()
ax.set_ylabel('Actual')
ax.set_yticks(ticks)
ax.yaxis.set_label_position('left')
ax.yaxis.tick_left()
if axis_labels is not None:
ticklabels = [re.sub(r'([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))', r'\1 ', x) for x in axis_labels]
ticklabels = ['\n'.join(wrap(l, 20)) for l in ticklabels]
ax.set_xticklabels(ticklabels, rotation=-90, ha='center')
ax.set_yticklabels(ticklabels, va ='center')
for i, j in product(range(num_classes), range(num_classes)):
if cm[i,j] == 0:
txt = '.'
elif normalize:
txt = '{:.2f}'.format(cm[i,j])
else:
txt = '{}'.format(cm[i,j])
ax.text(j, i, txt, horizontalalignment="center", verticalalignment='center', color= "black", fontsize=7)
np.set_printoptions(**po) | [
"def",
"draw",
"(",
"ax",
",",
"cm",
",",
"axis_labels",
"=",
"None",
",",
"normalize",
"=",
"False",
")",
":",
"cm",
"=",
"np",
".",
"asarray",
"(",
"cm",
")",
"num_classes",
"=",
"cm",
".",
"shape",
"[",
"0",
"]",
"if",
"normalize",
":",
"with",
"np",
".",
"errstate",
"(",
"invalid",
"=",
"'ignore'",
",",
"divide",
"=",
"'ignore'",
")",
":",
"cm",
"=",
"cm",
"/",
"cm",
".",
"sum",
"(",
"1",
",",
"keepdims",
"=",
"True",
")",
"cm",
"=",
"np",
".",
"nan_to_num",
"(",
"cm",
",",
"copy",
"=",
"True",
")",
"po",
"=",
"np",
".",
"get_printoptions",
"(",
")",
"np",
".",
"set_printoptions",
"(",
"precision",
"=",
"2",
")",
"ax",
".",
"imshow",
"(",
"cm",
",",
"cmap",
"=",
"'Oranges'",
")",
"ticks",
"=",
"np",
".",
"arange",
"(",
"num_classes",
")",
"ax",
".",
"set_xlabel",
"(",
"'Predicted'",
")",
"ax",
".",
"set_xticks",
"(",
"ticks",
")",
"ax",
".",
"xaxis",
".",
"set_label_position",
"(",
"'bottom'",
")",
"ax",
".",
"xaxis",
".",
"tick_bottom",
"(",
")",
"ax",
".",
"set_ylabel",
"(",
"'Actual'",
")",
"ax",
".",
"set_yticks",
"(",
"ticks",
")",
"ax",
".",
"yaxis",
".",
"set_label_position",
"(",
"'left'",
")",
"ax",
".",
"yaxis",
".",
"tick_left",
"(",
")",
"if",
"axis_labels",
"is",
"not",
"None",
":",
"ticklabels",
"=",
"[",
"re",
".",
"sub",
"(",
"r'([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))'",
",",
"r'\\1 '",
",",
"x",
")",
"for",
"x",
"in",
"axis_labels",
"]",
"ticklabels",
"=",
"[",
"'\\n'",
".",
"join",
"(",
"wrap",
"(",
"l",
",",
"20",
")",
")",
"for",
"l",
"in",
"ticklabels",
"]",
"ax",
".",
"set_xticklabels",
"(",
"ticklabels",
",",
"rotation",
"=",
"-",
"90",
",",
"ha",
"=",
"'center'",
")",
"ax",
".",
"set_yticklabels",
"(",
"ticklabels",
",",
"va",
"=",
"'center'",
")",
"for",
"i",
",",
"j",
"in",
"product",
"(",
"range",
"(",
"num_classes",
")",
",",
"range",
"(",
"num_classes",
")",
")",
":",
"if",
"cm",
"[",
"i",
",",
"j",
"]",
"==",
"0",
":",
"txt",
"=",
"'.'",
"elif",
"normalize",
":",
"txt",
"=",
"'{:.2f}'",
".",
"format",
"(",
"cm",
"[",
"i",
",",
"j",
"]",
")",
"else",
":",
"txt",
"=",
"'{}'",
".",
"format",
"(",
"cm",
"[",
"i",
",",
"j",
"]",
")",
"ax",
".",
"text",
"(",
"j",
",",
"i",
",",
"txt",
",",
"horizontalalignment",
"=",
"\"center\"",
",",
"verticalalignment",
"=",
"'center'",
",",
"color",
"=",
"\"black\"",
",",
"fontsize",
"=",
"7",
")",
"np",
".",
"set_printoptions",
"(",
"*",
"*",
"po",
")"
] | 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 containing axis labels
normalize : bool
Whether to plot counts or ratios. | [
"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 their respective thread, avoid usage
of pyplot where possible.
'''
fig = Figure(*fig_args, **fig_kwargs)
# Attach canvas
FigureCanvas(fig)
return fig | 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 their respective thread, avoid usage
of pyplot where possible.
'''
fig = Figure(*fig_args, **fig_kwargs)
# Attach canvas
FigureCanvas(fig)
return fig | [
"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 where possible. | [
"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 in their respective thread, avoid usage
of pyplot where possible.
'''
return [create_figure(*fig_args, **fig_kwargs) for _ in range(n)] | 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 in their respective thread, avoid usage
of pyplot where possible.
'''
return [create_figure(*fig_args, **fig_kwargs) for _ in range(n)] | [
"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 where possible. | [
"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 decorator | 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 decorator | [
"def",
"vararg_decorator",
"(",
"f",
")",
":",
"@",
"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",
"decorator"
] | 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]: How to sort the photos. Optional.
(Valid values: latest, oldest, popular; default: latest)
:return: [Array]: A single page of the Photo list.
"""
return self._all("/photos", page=page, per_page=per_page, order_by=order_by) | 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",
"=",
"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, popular; default: latest)
:return: [Array]: A single page of the Photo list. | [
"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 width [integer]: Image width in pixels.
:param height [integer]: Image height in pixels.
:param rect [string]: 4 comma-separated integers representing x, y, width, height of the cropped rectangle.
:return: [Photo]: The Unsplash Photo.
"""
url = "/photos/%s" % photo_id
params = {
"w": width,
"h": height,
"rect": rect
}
result = self._get(url, params=params)
return PhotoModel.parse(result) | 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\"",
":",
"height",
",",
"\"rect\"",
":",
"rect",
"}",
"result",
"=",
"self",
".",
"_get",
"(",
"url",
",",
"params",
"=",
"params",
")",
"return",
"PhotoModel",
".",
"parse",
"(",
"result",
")"
] | 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 in pixels.
:param rect [string]: 4 comma-separated integers representing x, y, width, height of the cropped rectangle.
:return: [Photo]: The Unsplash Photo. | [
"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 the collections and query parameters in the same request
Note: When supplying a count parameter
- and only then - the response will be an array of photos,
even if the value of count is 1.
All parameters are optional, and can be combined to narrow
the pool of photos from which a random one will be chosen.
:param count [integer]: The number of photos to return. (Default: 1; max: 30)
:param category: Category ID(‘s) to filter selection. If multiple, comma-separated. (deprecated)
:param collections: Public collection ID(‘s) to filter selection. If multiple, comma-separated
:param featured: Limit selection to featured photos.
:param username: Limit selection to a single user.
:param query: Limit selection to photos matching a search term.
:param w: Image width in pixels.
:param h: Image height in pixels.
:param orientation: Filter search results by photo orientation.
Valid values are landscape, portrait, and squarish.
:return: [Array] or [Photo]: A single page of the curated Photo list or The Unsplash Photo. .
:raise UnsplashError: If the given orientation is not in the default orientation values.
"""
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)
return PhotoModel.parse_list(result) | 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)
return PhotoModel.parse_list(result) | [
"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",
")",
"return",
"PhotoModel",
".",
"parse_list",
"(",
"result",
")"
] | 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
Note: When supplying a count parameter
- and only then - the response will be an array of photos,
even if the value of count is 1.
All parameters are optional, and can be combined to narrow
the pool of photos from which a random one will be chosen.
:param count [integer]: The number of photos to return. (Default: 1; max: 30)
:param category: Category ID(‘s) to filter selection. If multiple, comma-separated. (deprecated)
:param collections: Public collection ID(‘s) to filter selection. If multiple, comma-separated
:param featured: Limit selection to featured photos.
:param username: Limit selection to a single user.
:param query: Limit selection to photos matching a search term.
:param w: Image width in pixels.
:param h: Image height in pixels.
:param orientation: Filter search results by photo orientation.
Valid values are landscape, portrait, and squarish.
:return: [Array] or [Photo]: A single page of the curated Photo list or The Unsplash Photo. .
:raise UnsplashError: If the given orientation is not in the default orientation values. | [
"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 ID. Required.
:return: [Photo]: The Unsplash Photo.
"""
url = "/photos/%s/like" % photo_id
result = self._post(url)
return PhotoModel.parse(result) | 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 Unsplash Photo. | [
"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: 10)
:return: [dict]: {u'total': 0, u'total_pages': 0, u'results': [Photo]}
"""
url = "/search/photos"
data = self._search(url, query, page=page, per_page=per_page)
data["results"] = PhotoModel.parse_list(data.get("results"))
return data | 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",
"=",
"per_page",
")",
"data",
"[",
"\"results\"",
"]",
"=",
"PhotoModel",
".",
"parse_list",
"(",
"data",
".",
"get",
"(",
"\"results\"",
")",
")",
"return",
"data"
] | 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'results': [Photo]} | [
"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; default: 10)
:return: [dict]: {u'total': 0, u'total_pages': 0, u'results': [Collection]}
"""
url = "/search/collections"
data = self._search(url, query, page=page, per_page=per_page)
data["results"] = CollectionModel.parse_list(data.get("results"))
return data | 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_page",
"=",
"per_page",
")",
"data",
"[",
"\"results\"",
"]",
"=",
"CollectionModel",
".",
"parse_list",
"(",
"data",
".",
"get",
"(",
"\"results\"",
")",
")",
"return",
"data"
] | 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, u'results': [Collection]} | [
"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)
:return: [dict]: {u'total': 0, u'total_pages': 0, u'results': [User]}
"""
url = "/search/users"
data = self._search(url, query, page=page, per_page=per_page)
data["results"] = UserModel.parse_list(data.get("results"))
return data | 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",
"=",
"per_page",
")",
"data",
"[",
"\"results\"",
"]",
"=",
"UserModel",
".",
"parse_list",
"(",
"data",
".",
"get",
"(",
"\"results\"",
")",
")",
"return",
"data"
] | 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'results': [User]} | [
"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 Collection list.
"""
url = "/collections"
result = self._all(url, page=page, per_page=per_page)
return CollectionModel.parse_list(result) | 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",
"CollectionModel",
".",
"parse_list",
"(",
"result",
")"
] | 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
result = self._get(url)
return CollectionModel.parse_list(result) | 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.)
:param private [boolean]: Whether to make this collection private. (Optional; default false).
:return: [Collection]: The Unsplash Collection.
"""
url = "/collections"
data = {
"title": title,
"description": description,
"private": private
}
result = self._post(url, data=data)
return CollectionModel.parse(result) | 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\"",
":",
"private",
"}",
"result",
"=",
"self",
".",
"_post",
"(",
"url",
",",
"data",
"=",
"data",
")",
"return",
"CollectionModel",
".",
"parse",
"(",
"result",
")"
] | 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; default false).
:return: [Collection]: The Unsplash Collection. | [
"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 title of the collection. (Required.)
:param description [string]: The collection’s description. (Optional.)
:param private [boolean]: Whether to make this collection private. (Optional; default false).
:return: [Collection]: The Unsplash Collection.
"""
url = "/collections/%s" % collection_id
data = {
"title": title,
"description": description,
"private": private
}
result = self._put(url, data=data)
return CollectionModel.parse(result) | 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 CollectionModel.parse(result) | [
"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",
"CollectionModel",
".",
"parse",
"(",
"result",
")"
] | 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 description. (Optional.)
:param private [boolean]: Whether to make this collection private. (Optional; default false).
:return: [Collection]: The Unsplash Collection. | [
"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_token",
"=",
"self",
".",
"token",
".",
"get",
"(",
"\"access_token\"",
")"
] | 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 {"Authorization": "Client-ID %s" % self.api.client_id} | 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\"",
":",
"\"Client-ID %s\"",
"%",
"self",
".",
"api",
".",
"client_id",
"}"
] | 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 token)
this request will return a '401 Unauthorized' response.
:return: [User]: The Unsplash User.
"""
url = "/me"
result = self._get(url)
return UserModel.parse(result) | 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 return a '401 Unauthorized' response.
:return: [User]: The Unsplash User. | [
"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]: First name.
:param last_name [string]: Last name.
:param email [string]: Email.
:param url [string]: Portfolio/personal URL.
:param location [string]: Location.
:param bio [string]: About/bio.
:param instagram_username [string]: Instagram username.
:return: [User]: The Unsplash User.
"""
url = "/me"
result = self._put(url, data=kwargs)
return UserModel.parse(result) | 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]: Last name.
:param email [string]: Email.
:param url [string]: Portfolio/personal URL.
:param location [string]: Location.
:param bio [string]: About/bio.
:param instagram_username [string]: Instagram username.
:return: [User]: The Unsplash User. | [
"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.
:param width [integer]: Profile image width in pixels.
:param height [integer]: Profile image height in pixels.
:return: [User]: The Unsplash User.
"""
url = "/users/{username}".format(username=username)
params = {
"w": width,
"h": height
}
result = self._get(url, params=params)
return UserModel.parse(result) | 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",
",",
"\"h\"",
":",
"height",
"}",
"result",
"=",
"self",
".",
"_get",
"(",
"url",
",",
"params",
"=",
"params",
")",
"return",
"UserModel",
".",
"parse",
"(",
"result",
")"
] | 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.
:param height [integer]: Profile image height in pixels.
:return: [User]: The Unsplash User. | [
"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 items per page. (Optional; default: 10)
:param order_by [string]: How to sort the photos. Optional.
(Valid values: latest, oldest, popular; default: latest)
:return: [Array]: A single page of the Photo list.
"""
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) | 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",
"=",
"self",
".",
"_photos",
"(",
"url",
",",
"username",
",",
"page",
"=",
"page",
",",
"per_page",
"=",
"per_page",
",",
"order_by",
"=",
"order_by",
")",
"return",
"PhotoModel",
".",
"parse_list",
"(",
"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 photos. Optional.
(Valid values: latest, oldest, popular; default: latest)
:return: [Array]: A single page of the Photo list. | [
"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 page. (Optional; default: 10)
:return: [Array]: A single page of the Collection list.
"""
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) | 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\"",
":",
"page",
",",
"\"per_page\"",
":",
"per_page",
"}",
"result",
"=",
"self",
".",
"_get",
"(",
"url",
",",
"params",
"=",
"params",
")",
"return",
"CollectionModel",
".",
"parse_list",
"(",
"result",
")"
] | 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 the Collection list. | [
"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:
part.append(self.ANSI_RESET)
res.append("".join(part))
prev_state = set()
part = []
cwidth = 0
cwidth += _width
if prev_state == state:
pass
elif prev_state <= state:
part.extend(state - prev_state)
else:
part.append(self.ANSI_RESET)
part.extend(state)
prev_state = state
part.append(char)
if prev_state:
part.append(self.ANSI_RESET)
if part:
res.append("".join(part))
return res | 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)
res.append("".join(part))
prev_state = set()
part = []
cwidth = 0
cwidth += _width
if prev_state == state:
pass
elif prev_state <= state:
part.extend(state - prev_state)
else:
part.append(self.ANSI_RESET)
part.extend(state)
prev_state = state
part.append(char)
if prev_state:
part.append(self.ANSI_RESET)
if part:
res.append("".join(part))
return res | [
"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",
")",
"res",
".",
"append",
"(",
"\"\"",
".",
"join",
"(",
"part",
")",
")",
"prev_state",
"=",
"set",
"(",
")",
"part",
"=",
"[",
"]",
"cwidth",
"=",
"0",
"cwidth",
"+=",
"_width",
"if",
"prev_state",
"==",
"state",
":",
"pass",
"elif",
"prev_state",
"<=",
"state",
":",
"part",
".",
"extend",
"(",
"state",
"-",
"prev_state",
")",
"else",
":",
"part",
".",
"append",
"(",
"self",
".",
"ANSI_RESET",
")",
"part",
".",
"extend",
"(",
"state",
")",
"prev_state",
"=",
"state",
"part",
".",
"append",
"(",
"char",
")",
"if",
"prev_state",
":",
"part",
".",
"append",
"(",
"self",
".",
"ANSI_RESET",
")",
"if",
"part",
":",
"res",
".",
"append",
"(",
"\"\"",
".",
"join",
"(",
"part",
")",
")",
"return",
"res"
] | 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 = [''] * 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, header)
self._column_alignments = AlignmentMetaData(self, alignment)
self._column_widths = PositiveIntegerMetaData(self, width)
self._left_padding_widths = PositiveIntegerMetaData(self, padding)
self._right_padding_widths = PositiveIntegerMetaData(self, padding) | 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, header)
self._column_alignments = AlignmentMetaData(self, alignment)
self._column_widths = PositiveIntegerMetaData(self, width)
self._left_padding_widths = PositiveIntegerMetaData(self, padding)
self._right_padding_widths = PositiveIntegerMetaData(self, padding) | [
"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",
",",
"header",
")",
"self",
".",
"_column_alignments",
"=",
"AlignmentMetaData",
"(",
"self",
",",
"alignment",
")",
"self",
".",
"_column_widths",
"=",
"PositiveIntegerMetaData",
"(",
"self",
",",
"width",
")",
"self",
".",
"_left_padding_widths",
"=",
"PositiveIntegerMetaData",
"(",
"self",
",",
"padding",
")",
"self",
".",
"_right_padding_widths",
"=",
"PositiveIntegerMetaData",
"(",
"self",
",",
"padding",
")"
] | 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.STYLE_DOTTED
* beautifulTable.STYLE_MYSQL
* beautifulTable.STYLE_SEPARATED
* beautifulTable.STYLE_COMPACT
* beautifulTable.STYLE_MARKDOWN
* beautifulTable.STYLE_RESTRUCTURED_TEXT
* beautifultable.STYLE_BOX
* beautifultable.STYLE_BOX_DOUBLED
* beautifultable.STYLE_BOX_ROUNDED
* beautifultable.STYLE_GRID
"""
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(error_msg)
style_template = style.value
self.left_border_char = style_template.left_border_char
self.right_border_char = style_template.right_border_char
self.top_border_char = style_template.top_border_char
self.bottom_border_char = style_template.bottom_border_char
self.header_separator_char = style_template.header_separator_char
self.column_separator_char = style_template.column_separator_char
self.row_separator_char = style_template.row_separator_char
self.intersect_top_left = style_template.intersect_top_left
self.intersect_top_mid = style_template.intersect_top_mid
self.intersect_top_right = style_template.intersect_top_right
self.intersect_header_left = style_template.intersect_header_left
self.intersect_header_mid = style_template.intersect_header_mid
self.intersect_header_right = style_template.intersect_header_right
self.intersect_row_left = style_template.intersect_row_left
self.intersect_row_mid = style_template.intersect_row_mid
self.intersect_row_right = style_template.intersect_row_right
self.intersect_bottom_left = style_template.intersect_bottom_left
self.intersect_bottom_mid = style_template.intersect_bottom_mid
self.intersect_bottom_right = style_template.intersect_bottom_right | 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(error_msg)
style_template = style.value
self.left_border_char = style_template.left_border_char
self.right_border_char = style_template.right_border_char
self.top_border_char = style_template.top_border_char
self.bottom_border_char = style_template.bottom_border_char
self.header_separator_char = style_template.header_separator_char
self.column_separator_char = style_template.column_separator_char
self.row_separator_char = style_template.row_separator_char
self.intersect_top_left = style_template.intersect_top_left
self.intersect_top_mid = style_template.intersect_top_mid
self.intersect_top_right = style_template.intersect_top_right
self.intersect_header_left = style_template.intersect_header_left
self.intersect_header_mid = style_template.intersect_header_mid
self.intersect_header_right = style_template.intersect_header_right
self.intersect_row_left = style_template.intersect_row_left
self.intersect_row_mid = style_template.intersect_row_mid
self.intersect_row_right = style_template.intersect_row_right
self.intersect_bottom_left = style_template.intersect_bottom_left
self.intersect_bottom_mid = style_template.intersect_bottom_mid
self.intersect_bottom_right = style_template.intersect_bottom_right | [
"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",
"(",
"error_msg",
")",
"style_template",
"=",
"style",
".",
"value",
"self",
".",
"left_border_char",
"=",
"style_template",
".",
"left_border_char",
"self",
".",
"right_border_char",
"=",
"style_template",
".",
"right_border_char",
"self",
".",
"top_border_char",
"=",
"style_template",
".",
"top_border_char",
"self",
".",
"bottom_border_char",
"=",
"style_template",
".",
"bottom_border_char",
"self",
".",
"header_separator_char",
"=",
"style_template",
".",
"header_separator_char",
"self",
".",
"column_separator_char",
"=",
"style_template",
".",
"column_separator_char",
"self",
".",
"row_separator_char",
"=",
"style_template",
".",
"row_separator_char",
"self",
".",
"intersect_top_left",
"=",
"style_template",
".",
"intersect_top_left",
"self",
".",
"intersect_top_mid",
"=",
"style_template",
".",
"intersect_top_mid",
"self",
".",
"intersect_top_right",
"=",
"style_template",
".",
"intersect_top_right",
"self",
".",
"intersect_header_left",
"=",
"style_template",
".",
"intersect_header_left",
"self",
".",
"intersect_header_mid",
"=",
"style_template",
".",
"intersect_header_mid",
"self",
".",
"intersect_header_right",
"=",
"style_template",
".",
"intersect_header_right",
"self",
".",
"intersect_row_left",
"=",
"style_template",
".",
"intersect_row_left",
"self",
".",
"intersect_row_mid",
"=",
"style_template",
".",
"intersect_row_mid",
"self",
".",
"intersect_row_right",
"=",
"style_template",
".",
"intersect_row_right",
"self",
".",
"intersect_bottom_left",
"=",
"style_template",
".",
"intersect_bottom_left",
"self",
".",
"intersect_bottom_mid",
"=",
"style_template",
".",
"intersect_bottom_mid",
"self",
".",
"intersect_bottom_right",
"=",
"style_template",
".",
"intersect_bottom_right"
] | 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.STYLE_MYSQL
* beautifulTable.STYLE_SEPARATED
* beautifulTable.STYLE_COMPACT
* beautifulTable.STYLE_MARKDOWN
* beautifulTable.STYLE_RESTRUCTURED_TEXT
* beautifultable.STYLE_BOX
* beautifultable.STYLE_BOX_DOUBLED
* beautifultable.STYLE_BOX_ROUNDED
* beautifultable.STYLE_GRID | [
"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 = [0 for index in range(self._column_count)]
offset = table_width - sum(self._column_widths) + sum(pad_widths)
self._max_table_width = max(self._max_table_width,
offset + self._column_count)
for index, column in enumerate(zip(*self._table)):
max_length = 0
for i in column:
for j in to_unicode(i).split('\n'):
output_str = get_output_str(j, self.detect_numerics,
self.numeric_precision,
self.sign_mode.value)
max_length = max(max_length, termwidth(output_str))
for i in to_unicode(self._column_headers[index]).split('\n'):
output_str = get_output_str(i, self.detect_numerics,
self.numeric_precision,
self.sign_mode.value)
max_length = max(max_length, termwidth(output_str))
max_widths[index] += max_length
sum_ = sum(max_widths)
desired_sum = self._max_table_width - offset
# Set flag for columns who are within their fair share
temp_sum = 0
flag = [0] * len(max_widths)
for i, width in enumerate(max_widths):
if width <= int(desired_sum / self._column_count):
temp_sum += width
flag[i] = 1
else:
# Allocate atleast 1 character width to the column
temp_sum += 1
avail_space = desired_sum - temp_sum
actual_space = sum_ - temp_sum
shrinked_columns = {}
# Columns which exceed their fair share should be shrinked based on
# how much space is left for the table
for i, width in enumerate(max_widths):
self.column_widths[i] = width
if not flag[i]:
new_width = 1 + int((width-1) * avail_space / actual_space)
if new_width < width:
self.column_widths[i] = new_width
shrinked_columns[new_width] = i
# Divide any remaining space among shrinked columns
if shrinked_columns:
extra = (self._max_table_width
- offset
- sum(self.column_widths))
actual_space = sum(shrinked_columns)
if extra > 0:
for i, width in enumerate(sorted(shrinked_columns)):
index = shrinked_columns[width]
extra_width = int(width * extra / actual_space)
self.column_widths[i] += extra_width
if i == (len(shrinked_columns) - 1):
extra = (self._max_table_width
- offset
- sum(self.column_widths))
self.column_widths[index] += extra
for i in range(self.column_count):
self.column_widths[i] += pad_widths[i] | 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_width - sum(self._column_widths) + sum(pad_widths)
self._max_table_width = max(self._max_table_width,
offset + self._column_count)
for index, column in enumerate(zip(*self._table)):
max_length = 0
for i in column:
for j in to_unicode(i).split('\n'):
output_str = get_output_str(j, self.detect_numerics,
self.numeric_precision,
self.sign_mode.value)
max_length = max(max_length, termwidth(output_str))
for i in to_unicode(self._column_headers[index]).split('\n'):
output_str = get_output_str(i, self.detect_numerics,
self.numeric_precision,
self.sign_mode.value)
max_length = max(max_length, termwidth(output_str))
max_widths[index] += max_length
sum_ = sum(max_widths)
desired_sum = self._max_table_width - offset
# Set flag for columns who are within their fair share
temp_sum = 0
flag = [0] * len(max_widths)
for i, width in enumerate(max_widths):
if width <= int(desired_sum / self._column_count):
temp_sum += width
flag[i] = 1
else:
# Allocate atleast 1 character width to the column
temp_sum += 1
avail_space = desired_sum - temp_sum
actual_space = sum_ - temp_sum
shrinked_columns = {}
# Columns which exceed their fair share should be shrinked based on
# how much space is left for the table
for i, width in enumerate(max_widths):
self.column_widths[i] = width
if not flag[i]:
new_width = 1 + int((width-1) * avail_space / actual_space)
if new_width < width:
self.column_widths[i] = new_width
shrinked_columns[new_width] = i
# Divide any remaining space among shrinked columns
if shrinked_columns:
extra = (self._max_table_width
- offset
- sum(self.column_widths))
actual_space = sum(shrinked_columns)
if extra > 0:
for i, width in enumerate(sorted(shrinked_columns)):
index = shrinked_columns[width]
extra_width = int(width * extra / actual_space)
self.column_widths[i] += extra_width
if i == (len(shrinked_columns) - 1):
extra = (self._max_table_width
- offset
- sum(self.column_widths))
self.column_widths[index] += extra
for i in range(self.column_count):
self.column_widths[i] += pad_widths[i] | [
"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_width",
"-",
"sum",
"(",
"self",
".",
"_column_widths",
")",
"+",
"sum",
"(",
"pad_widths",
")",
"self",
".",
"_max_table_width",
"=",
"max",
"(",
"self",
".",
"_max_table_width",
",",
"offset",
"+",
"self",
".",
"_column_count",
")",
"for",
"index",
",",
"column",
"in",
"enumerate",
"(",
"zip",
"(",
"*",
"self",
".",
"_table",
")",
")",
":",
"max_length",
"=",
"0",
"for",
"i",
"in",
"column",
":",
"for",
"j",
"in",
"to_unicode",
"(",
"i",
")",
".",
"split",
"(",
"'\\n'",
")",
":",
"output_str",
"=",
"get_output_str",
"(",
"j",
",",
"self",
".",
"detect_numerics",
",",
"self",
".",
"numeric_precision",
",",
"self",
".",
"sign_mode",
".",
"value",
")",
"max_length",
"=",
"max",
"(",
"max_length",
",",
"termwidth",
"(",
"output_str",
")",
")",
"for",
"i",
"in",
"to_unicode",
"(",
"self",
".",
"_column_headers",
"[",
"index",
"]",
")",
".",
"split",
"(",
"'\\n'",
")",
":",
"output_str",
"=",
"get_output_str",
"(",
"i",
",",
"self",
".",
"detect_numerics",
",",
"self",
".",
"numeric_precision",
",",
"self",
".",
"sign_mode",
".",
"value",
")",
"max_length",
"=",
"max",
"(",
"max_length",
",",
"termwidth",
"(",
"output_str",
")",
")",
"max_widths",
"[",
"index",
"]",
"+=",
"max_length",
"sum_",
"=",
"sum",
"(",
"max_widths",
")",
"desired_sum",
"=",
"self",
".",
"_max_table_width",
"-",
"offset",
"# Set flag for columns who are within their fair share",
"temp_sum",
"=",
"0",
"flag",
"=",
"[",
"0",
"]",
"*",
"len",
"(",
"max_widths",
")",
"for",
"i",
",",
"width",
"in",
"enumerate",
"(",
"max_widths",
")",
":",
"if",
"width",
"<=",
"int",
"(",
"desired_sum",
"/",
"self",
".",
"_column_count",
")",
":",
"temp_sum",
"+=",
"width",
"flag",
"[",
"i",
"]",
"=",
"1",
"else",
":",
"# Allocate atleast 1 character width to the column",
"temp_sum",
"+=",
"1",
"avail_space",
"=",
"desired_sum",
"-",
"temp_sum",
"actual_space",
"=",
"sum_",
"-",
"temp_sum",
"shrinked_columns",
"=",
"{",
"}",
"# Columns which exceed their fair share should be shrinked based on",
"# how much space is left for the table",
"for",
"i",
",",
"width",
"in",
"enumerate",
"(",
"max_widths",
")",
":",
"self",
".",
"column_widths",
"[",
"i",
"]",
"=",
"width",
"if",
"not",
"flag",
"[",
"i",
"]",
":",
"new_width",
"=",
"1",
"+",
"int",
"(",
"(",
"width",
"-",
"1",
")",
"*",
"avail_space",
"/",
"actual_space",
")",
"if",
"new_width",
"<",
"width",
":",
"self",
".",
"column_widths",
"[",
"i",
"]",
"=",
"new_width",
"shrinked_columns",
"[",
"new_width",
"]",
"=",
"i",
"# Divide any remaining space among shrinked columns",
"if",
"shrinked_columns",
":",
"extra",
"=",
"(",
"self",
".",
"_max_table_width",
"-",
"offset",
"-",
"sum",
"(",
"self",
".",
"column_widths",
")",
")",
"actual_space",
"=",
"sum",
"(",
"shrinked_columns",
")",
"if",
"extra",
">",
"0",
":",
"for",
"i",
",",
"width",
"in",
"enumerate",
"(",
"sorted",
"(",
"shrinked_columns",
")",
")",
":",
"index",
"=",
"shrinked_columns",
"[",
"width",
"]",
"extra_width",
"=",
"int",
"(",
"width",
"*",
"extra",
"/",
"actual_space",
")",
"self",
".",
"column_widths",
"[",
"i",
"]",
"+=",
"extra_width",
"if",
"i",
"==",
"(",
"len",
"(",
"shrinked_columns",
")",
"-",
"1",
")",
":",
"extra",
"=",
"(",
"self",
".",
"_max_table_width",
"-",
"offset",
"-",
"sum",
"(",
"self",
".",
"column_widths",
")",
")",
"self",
".",
"column_widths",
"[",
"index",
"]",
"+=",
"extra",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"column_count",
")",
":",
"self",
".",
"column_widths",
"[",
"i",
"]",
"+=",
"pad_widths",
"[",
"i",
"]"
] | 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`.
"""
try:
index = self._column_headers.index(header)
return index
except ValueError:
raise_suppressed(KeyError(("'{}' is not a header for any "
"column").format(header))) | 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",
"(",
"(",
"\"'{}' is not a header for any \"",
"\"column\"",
")",
".",
"format",
"(",
"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`. | [
"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:
If key is not of type `int`, or `str`.
Returns
-------
iter:
Iterator to the specified column.
"""
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__))
return iter(map(operator.itemgetter(index), self._table)) | 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__))
return iter(map(operator.itemgetter(index), self._table)) | [
"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__",
")",
")",
"return",
"iter",
"(",
"map",
"(",
"operator",
".",
"itemgetter",
"(",
"index",
")",
",",
"self",
".",
"_table",
")",
")"
] | 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`.
Returns
-------
iter:
Iterator to the specified column. | [
"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` is not an iterable.
ValueError:
If size of `row` is inconsistent with the current number
of columns.
"""
row = self._validate_row(row)
row_obj = RowData(self, row)
self._table.insert(index, row_obj) | 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_obj",
")"
] | 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:
If size of `row` is inconsistent with the current number
of columns. | [
"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 Table remains in consistent state even if column
is too short. Any changes made by this method is rolled back
before raising the exception.
Parameters
----------
index : int
List index rules apply.
header : str
Title of the column.
column : iterable
Any iterable of appropriate length.
Raises
------
TypeError:
If `header` is not of type `str`.
ValueError:
If length of `column` is shorter than number of rows.
"""
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 of type str")
column_length = 0
for i, (row, new_item) in enumerate(zip(self._table, column)):
row._insert(index, new_item)
column_length = i
if column_length == len(self._table) - 1:
self._column_count += 1
self._column_headers._insert(index, header)
self._column_alignments._insert(index, self.default_alignment)
self._column_widths._insert(index, 0)
self._left_padding_widths._insert(index, self.default_padding)
self._right_padding_widths._insert(index, self.default_padding)
else:
# Roll back changes so that table remains in consistent state
for j in range(column_length, -1, -1):
self._table[j]._pop(index)
raise ValueError(("length of 'column' should be atleast {}, "
"got {}").format(len(self._table),
column_length + 1)) | 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 of type str")
column_length = 0
for i, (row, new_item) in enumerate(zip(self._table, column)):
row._insert(index, new_item)
column_length = i
if column_length == len(self._table) - 1:
self._column_count += 1
self._column_headers._insert(index, header)
self._column_alignments._insert(index, self.default_alignment)
self._column_widths._insert(index, 0)
self._left_padding_widths._insert(index, self.default_padding)
self._right_padding_widths._insert(index, self.default_padding)
else:
# Roll back changes so that table remains in consistent state
for j in range(column_length, -1, -1):
self._table[j]._pop(index)
raise ValueError(("length of 'column' should be atleast {}, "
"got {}").format(len(self._table),
column_length + 1)) | [
"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 of type str\"",
")",
"column_length",
"=",
"0",
"for",
"i",
",",
"(",
"row",
",",
"new_item",
")",
"in",
"enumerate",
"(",
"zip",
"(",
"self",
".",
"_table",
",",
"column",
")",
")",
":",
"row",
".",
"_insert",
"(",
"index",
",",
"new_item",
")",
"column_length",
"=",
"i",
"if",
"column_length",
"==",
"len",
"(",
"self",
".",
"_table",
")",
"-",
"1",
":",
"self",
".",
"_column_count",
"+=",
"1",
"self",
".",
"_column_headers",
".",
"_insert",
"(",
"index",
",",
"header",
")",
"self",
".",
"_column_alignments",
".",
"_insert",
"(",
"index",
",",
"self",
".",
"default_alignment",
")",
"self",
".",
"_column_widths",
".",
"_insert",
"(",
"index",
",",
"0",
")",
"self",
".",
"_left_padding_widths",
".",
"_insert",
"(",
"index",
",",
"self",
".",
"default_padding",
")",
"self",
".",
"_right_padding_widths",
".",
"_insert",
"(",
"index",
",",
"self",
".",
"default_padding",
")",
"else",
":",
"# Roll back changes so that table remains in consistent state",
"for",
"j",
"in",
"range",
"(",
"column_length",
",",
"-",
"1",
",",
"-",
"1",
")",
":",
"self",
".",
"_table",
"[",
"j",
"]",
".",
"_pop",
"(",
"index",
")",
"raise",
"ValueError",
"(",
"(",
"\"length of 'column' should be atleast {}, \"",
"\"got {}\"",
")",
".",
"format",
"(",
"len",
"(",
"self",
".",
"_table",
")",
",",
"column_length",
"+",
"1",
")",
")"
] | 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 too short. Any changes made by this method is rolled back
before raising the exception.
Parameters
----------
index : int
List index rules apply.
header : str
Title of the column.
column : iterable
Any iterable of appropriate length.
Raises
------
TypeError:
If `header` is not of type `str`.
ValueError:
If length of `column` is shorter than number of rows. | [
"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, header, column) | 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
detects intersection and handles it according to the values of
`intersect_*_*` attributes.
Parameters
----------
char : str
Character used to draw the line.
Returns
-------
str
String which will be printed as the Top border of the table.
"""
width = self.get_table_width()
try:
line = list(char * (int(width/termwidth(char)) + 1))[:width]
except ZeroDivisionError:
line = [' '] * width
if len(line) == 0:
return ''
# Only if Special Intersection is enabled and horizontal line is
# visible
if not char.isspace():
# If left border is enabled and it is visible
visible_junc = not intersect_left.isspace()
if termwidth(self.left_border_char) > 0:
if not (self.left_border_char.isspace() and visible_junc):
length = min(termwidth(self.left_border_char),
termwidth(intersect_left))
for i in range(length):
line[i] = intersect_left[i]
visible_junc = not intersect_right.isspace()
# If right border is enabled and it is visible
if termwidth(self.right_border_char) > 0:
if not (self.right_border_char.isspace() and visible_junc):
length = min(termwidth(self.right_border_char),
termwidth(intersect_right))
for i in range(length):
line[-i-1] = intersect_right[-i-1]
visible_junc = not intersect_mid.isspace()
# If column separator is enabled and it is visible
if termwidth(self.column_separator_char):
if not (self.column_separator_char.isspace() and visible_junc):
index = termwidth(self.left_border_char)
for i in range(self._column_count-1):
index += (self._column_widths[i])
length = min(termwidth(self.column_separator_char),
termwidth(intersect_mid))
for i in range(length):
line[index+i] = intersect_mid[i]
index += termwidth(self.column_separator_char)
return ''.join(line) | 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 len(line) == 0:
return ''
# Only if Special Intersection is enabled and horizontal line is
# visible
if not char.isspace():
# If left border is enabled and it is visible
visible_junc = not intersect_left.isspace()
if termwidth(self.left_border_char) > 0:
if not (self.left_border_char.isspace() and visible_junc):
length = min(termwidth(self.left_border_char),
termwidth(intersect_left))
for i in range(length):
line[i] = intersect_left[i]
visible_junc = not intersect_right.isspace()
# If right border is enabled and it is visible
if termwidth(self.right_border_char) > 0:
if not (self.right_border_char.isspace() and visible_junc):
length = min(termwidth(self.right_border_char),
termwidth(intersect_right))
for i in range(length):
line[-i-1] = intersect_right[-i-1]
visible_junc = not intersect_mid.isspace()
# If column separator is enabled and it is visible
if termwidth(self.column_separator_char):
if not (self.column_separator_char.isspace() and visible_junc):
index = termwidth(self.left_border_char)
for i in range(self._column_count-1):
index += (self._column_widths[i])
length = min(termwidth(self.column_separator_char),
termwidth(intersect_mid))
for i in range(length):
line[index+i] = intersect_mid[i]
index += termwidth(self.column_separator_char)
return ''.join(line) | [
"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",
"len",
"(",
"line",
")",
"==",
"0",
":",
"return",
"''",
"# Only if Special Intersection is enabled and horizontal line is",
"# visible",
"if",
"not",
"char",
".",
"isspace",
"(",
")",
":",
"# If left border is enabled and it is visible",
"visible_junc",
"=",
"not",
"intersect_left",
".",
"isspace",
"(",
")",
"if",
"termwidth",
"(",
"self",
".",
"left_border_char",
")",
">",
"0",
":",
"if",
"not",
"(",
"self",
".",
"left_border_char",
".",
"isspace",
"(",
")",
"and",
"visible_junc",
")",
":",
"length",
"=",
"min",
"(",
"termwidth",
"(",
"self",
".",
"left_border_char",
")",
",",
"termwidth",
"(",
"intersect_left",
")",
")",
"for",
"i",
"in",
"range",
"(",
"length",
")",
":",
"line",
"[",
"i",
"]",
"=",
"intersect_left",
"[",
"i",
"]",
"visible_junc",
"=",
"not",
"intersect_right",
".",
"isspace",
"(",
")",
"# If right border is enabled and it is visible",
"if",
"termwidth",
"(",
"self",
".",
"right_border_char",
")",
">",
"0",
":",
"if",
"not",
"(",
"self",
".",
"right_border_char",
".",
"isspace",
"(",
")",
"and",
"visible_junc",
")",
":",
"length",
"=",
"min",
"(",
"termwidth",
"(",
"self",
".",
"right_border_char",
")",
",",
"termwidth",
"(",
"intersect_right",
")",
")",
"for",
"i",
"in",
"range",
"(",
"length",
")",
":",
"line",
"[",
"-",
"i",
"-",
"1",
"]",
"=",
"intersect_right",
"[",
"-",
"i",
"-",
"1",
"]",
"visible_junc",
"=",
"not",
"intersect_mid",
".",
"isspace",
"(",
")",
"# If column separator is enabled and it is visible",
"if",
"termwidth",
"(",
"self",
".",
"column_separator_char",
")",
":",
"if",
"not",
"(",
"self",
".",
"column_separator_char",
".",
"isspace",
"(",
")",
"and",
"visible_junc",
")",
":",
"index",
"=",
"termwidth",
"(",
"self",
".",
"left_border_char",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"_column_count",
"-",
"1",
")",
":",
"index",
"+=",
"(",
"self",
".",
"_column_widths",
"[",
"i",
"]",
")",
"length",
"=",
"min",
"(",
"termwidth",
"(",
"self",
".",
"column_separator_char",
")",
",",
"termwidth",
"(",
"intersect_mid",
")",
")",
"for",
"i",
"in",
"range",
"(",
"length",
")",
":",
"line",
"[",
"index",
"+",
"i",
"]",
"=",
"intersect_mid",
"[",
"i",
"]",
"index",
"+=",
"termwidth",
"(",
"self",
".",
"column_separator_char",
")",
"return",
"''",
".",
"join",
"(",
"line",
")"
] | 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.
Parameters
----------
char : str
Character used to draw the line.
Returns
-------
str
String which will be printed as the Top border of the table. | [
"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:
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_char)
return width | 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_char)
return width | [
"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_char",
")",
"return",
"width"
] | 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
explicitly when this method is called for the first time ,
regardless of the value of `recalculate_width`.
Returns
-------
str:
Table as a string.
"""
# 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))
# Should widths of column be recalculated
if recalculate_width or sum(self._column_widths) == 0:
self._calculate_column_widths()
string_ = []
# Drawing the top border
if self.top_border_char:
string_.append(
self._get_top_border())
# Print headers if not empty or only spaces
if ''.join(self._column_headers).strip():
headers = to_unicode(self._column_headers)
string_.append(headers)
if self.header_separator_char:
string_.append(
self._get_header_separator())
# Printing rows
first_row_encountered = False
for row in self._table:
if first_row_encountered and self.row_separator_char:
string_.append(
self._get_row_separator())
first_row_encountered = True
content = to_unicode(row)
string_.append(content)
# Drawing the bottom border
if self.bottom_border_char:
string_.append(
self._get_bottom_border())
if self.serialno and self.column_count > 0:
self.pop_column(0)
return '\n'.join(string_) | 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))
# Should widths of column be recalculated
if recalculate_width or sum(self._column_widths) == 0:
self._calculate_column_widths()
string_ = []
# Drawing the top border
if self.top_border_char:
string_.append(
self._get_top_border())
# Print headers if not empty or only spaces
if ''.join(self._column_headers).strip():
headers = to_unicode(self._column_headers)
string_.append(headers)
if self.header_separator_char:
string_.append(
self._get_header_separator())
# Printing rows
first_row_encountered = False
for row in self._table:
if first_row_encountered and self.row_separator_char:
string_.append(
self._get_row_separator())
first_row_encountered = True
content = to_unicode(row)
string_.append(content)
# Drawing the bottom border
if self.bottom_border_char:
string_.append(
self._get_bottom_border())
if self.serialno and self.column_count > 0:
self.pop_column(0)
return '\n'.join(string_) | [
"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",
")",
")",
"# Should widths of column be recalculated",
"if",
"recalculate_width",
"or",
"sum",
"(",
"self",
".",
"_column_widths",
")",
"==",
"0",
":",
"self",
".",
"_calculate_column_widths",
"(",
")",
"string_",
"=",
"[",
"]",
"# Drawing the top border",
"if",
"self",
".",
"top_border_char",
":",
"string_",
".",
"append",
"(",
"self",
".",
"_get_top_border",
"(",
")",
")",
"# Print headers if not empty or only spaces",
"if",
"''",
".",
"join",
"(",
"self",
".",
"_column_headers",
")",
".",
"strip",
"(",
")",
":",
"headers",
"=",
"to_unicode",
"(",
"self",
".",
"_column_headers",
")",
"string_",
".",
"append",
"(",
"headers",
")",
"if",
"self",
".",
"header_separator_char",
":",
"string_",
".",
"append",
"(",
"self",
".",
"_get_header_separator",
"(",
")",
")",
"# Printing rows",
"first_row_encountered",
"=",
"False",
"for",
"row",
"in",
"self",
".",
"_table",
":",
"if",
"first_row_encountered",
"and",
"self",
".",
"row_separator_char",
":",
"string_",
".",
"append",
"(",
"self",
".",
"_get_row_separator",
"(",
")",
")",
"first_row_encountered",
"=",
"True",
"content",
"=",
"to_unicode",
"(",
"row",
")",
"string_",
".",
"append",
"(",
"content",
")",
"# Drawing the bottom border",
"if",
"self",
".",
"bottom_border_char",
":",
"string_",
".",
"append",
"(",
"self",
".",
"_get_bottom_border",
"(",
")",
")",
"if",
"self",
".",
"serialno",
"and",
"self",
".",
"column_count",
">",
"0",
":",
"self",
".",
"pop_column",
"(",
"0",
")",
"return",
"'\\n'",
".",
"join",
"(",
"string_",
")"
] | 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 ,
regardless of the value of `recalculate_width`.
Returns
-------
str:
Table as a string. | [
"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, float) # noqa: F821
# We don't wan't to perform any conversions if item is already a number
if isinstance(item, num_types):
return item
# First try for an int conversion so that strings like "5" are converted
# to 5 instead of 5.0 . This is safe as a direct int cast for a non integer
# string raises a ValueError.
try:
num = int(to_unicode(item))
except ValueError:
try:
num = float(to_unicode(item))
except ValueError:
return item
else:
return num
except TypeError:
return item
else:
return num | 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 item
# First try for an int conversion so that strings like "5" are converted
# to 5 instead of 5.0 . This is safe as a direct int cast for a non integer
# string raises a ValueError.
try:
num = int(to_unicode(item))
except ValueError:
try:
num = float(to_unicode(item))
except ValueError:
return item
else:
return num
except TypeError:
return item
else:
return num | [
"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",
"item",
"# First try for an int conversion so that strings like \"5\" are converted",
"# to 5 instead of 5.0 . This is safe as a direct int cast for a non integer",
"# string raises a ValueError.",
"try",
":",
"num",
"=",
"int",
"(",
"to_unicode",
"(",
"item",
")",
")",
"except",
"ValueError",
":",
"try",
":",
"num",
"=",
"float",
"(",
"to_unicode",
"(",
"item",
")",
")",
"except",
"ValueError",
":",
"return",
"item",
"else",
":",
"return",
"num",
"except",
"TypeError",
":",
"return",
"item",
"else",
":",
"return",
"num"
] | 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_value)
except (ValueError, TypeError):
pass
return to_unicode(item) | 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
return to_unicode(item) | [
"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",
"return",
"to_unicode",
"(",
"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
according to width exceed policy.
"""
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):
# Let's strip the row
delimiter = '' if wep is WidthExceedPolicy.WEP_STRIP else '...'
row_item_list = []
for index, row_item in enumerate(row):
left_pad = table._column_pad * lpw[index]
right_pad = table._column_pad * rpw[index]
clmp_str = (left_pad
+ self._clamp_string(row_item, index, delimiter)
+ right_pad)
row_item_list.append(clmp_str)
list_of_rows.append(row_item_list)
elif wep is WidthExceedPolicy.WEP_WRAP:
# Let's wrap the row
string_partition = []
for index, row_item in enumerate(row):
width = table.column_widths[index] - lpw[index] - rpw[index]
string_partition.append(textwrap(row_item, width))
for row_items in zip_longest(*string_partition, fillvalue=''):
row_item_list = []
for index, row_item in enumerate(row_items):
left_pad = table._column_pad * lpw[index]
right_pad = table._column_pad * rpw[index]
row_item_list.append(left_pad + row_item + right_pad)
list_of_rows.append(row_item_list)
if len(list_of_rows) == 0:
return [[''] * table.column_count]
else:
return list_of_rows | 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):
# Let's strip the row
delimiter = '' if wep is WidthExceedPolicy.WEP_STRIP else '...'
row_item_list = []
for index, row_item in enumerate(row):
left_pad = table._column_pad * lpw[index]
right_pad = table._column_pad * rpw[index]
clmp_str = (left_pad
+ self._clamp_string(row_item, index, delimiter)
+ right_pad)
row_item_list.append(clmp_str)
list_of_rows.append(row_item_list)
elif wep is WidthExceedPolicy.WEP_WRAP:
# Let's wrap the row
string_partition = []
for index, row_item in enumerate(row):
width = table.column_widths[index] - lpw[index] - rpw[index]
string_partition.append(textwrap(row_item, width))
for row_items in zip_longest(*string_partition, fillvalue=''):
row_item_list = []
for index, row_item in enumerate(row_items):
left_pad = table._column_pad * lpw[index]
right_pad = table._column_pad * rpw[index]
row_item_list.append(left_pad + row_item + right_pad)
list_of_rows.append(row_item_list)
if len(list_of_rows) == 0:
return [[''] * table.column_count]
else:
return list_of_rows | [
"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",
")",
":",
"# Let's strip the row",
"delimiter",
"=",
"''",
"if",
"wep",
"is",
"WidthExceedPolicy",
".",
"WEP_STRIP",
"else",
"'...'",
"row_item_list",
"=",
"[",
"]",
"for",
"index",
",",
"row_item",
"in",
"enumerate",
"(",
"row",
")",
":",
"left_pad",
"=",
"table",
".",
"_column_pad",
"*",
"lpw",
"[",
"index",
"]",
"right_pad",
"=",
"table",
".",
"_column_pad",
"*",
"rpw",
"[",
"index",
"]",
"clmp_str",
"=",
"(",
"left_pad",
"+",
"self",
".",
"_clamp_string",
"(",
"row_item",
",",
"index",
",",
"delimiter",
")",
"+",
"right_pad",
")",
"row_item_list",
".",
"append",
"(",
"clmp_str",
")",
"list_of_rows",
".",
"append",
"(",
"row_item_list",
")",
"elif",
"wep",
"is",
"WidthExceedPolicy",
".",
"WEP_WRAP",
":",
"# Let's wrap the row",
"string_partition",
"=",
"[",
"]",
"for",
"index",
",",
"row_item",
"in",
"enumerate",
"(",
"row",
")",
":",
"width",
"=",
"table",
".",
"column_widths",
"[",
"index",
"]",
"-",
"lpw",
"[",
"index",
"]",
"-",
"rpw",
"[",
"index",
"]",
"string_partition",
".",
"append",
"(",
"textwrap",
"(",
"row_item",
",",
"width",
")",
")",
"for",
"row_items",
"in",
"zip_longest",
"(",
"*",
"string_partition",
",",
"fillvalue",
"=",
"''",
")",
":",
"row_item_list",
"=",
"[",
"]",
"for",
"index",
",",
"row_item",
"in",
"enumerate",
"(",
"row_items",
")",
":",
"left_pad",
"=",
"table",
".",
"_column_pad",
"*",
"lpw",
"[",
"index",
"]",
"right_pad",
"=",
"table",
".",
"_column_pad",
"*",
"rpw",
"[",
"index",
"]",
"row_item_list",
".",
"append",
"(",
"left_pad",
"+",
"row_item",
"+",
"right_pad",
")",
"list_of_rows",
".",
"append",
"(",
"row_item_list",
")",
"if",
"len",
"(",
"list_of_rows",
")",
"==",
"0",
":",
"return",
"[",
"[",
"''",
"]",
"*",
"table",
".",
"column_count",
"]",
"else",
":",
"return",
"list_of_rows"
] | 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
String which should be clamped.
column_index: int
Index of the column `row_item` belongs to.
delimiter: str
String which is to be appended to the clamped string.
Returns
-------
str
The modified string which fits in it's column.
"""
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_item
else:
if width - len(delimiter) >= 0:
clamped_string = (textwrap(row_item, width-len(delimiter))[0]
+ delimiter)
else:
clamped_string = delimiter[:width]
return clamped_string | 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_item
else:
if width - len(delimiter) >= 0:
clamped_string = (textwrap(row_item, width-len(delimiter))[0]
+ delimiter)
else:
clamped_string = delimiter[:width]
return clamped_string | [
"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_item",
"else",
":",
"if",
"width",
"-",
"len",
"(",
"delimiter",
")",
">=",
"0",
":",
"clamped_string",
"=",
"(",
"textwrap",
"(",
"row_item",
",",
"width",
"-",
"len",
"(",
"delimiter",
")",
")",
"[",
"0",
"]",
"+",
"delimiter",
")",
"else",
":",
"clamped_string",
"=",
"delimiter",
"[",
":",
"width",
"]",
"return",
"clamped_string"
] | 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 of the column `row_item` belongs to.
delimiter: str
String which is to be appended to the clamped string.
Returns
-------
str
The modified string which fits in it's column. | [
"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: Iterable with several values from :class:`icq.constant.MessageParseType` specifying which message
items should be parsed by target client (making preview, snippets, etc.). Specify empty iterable to avoid
parsing message at target client. By default all types are included.
:param update_msg_id: Message ID to update.
:param wrap_length: Maximum length of symbols in one message. Text exceeding this length will be sent in several
messages.
:return: Tuple of HTTP responses.
"""
try:
responses = set()
for text in wrap(string=str(message), length=wrap_length):
response = self.http_session.post(
url="{}/im/sendIM".format(self.api_base_url),
data={
"r": uuid.uuid4(),
"aimsid": self.token,
"t": target,
"message": text,
"mentions": (
mentions if isinstance(mentions, six.string_types) or not hasattr(mentions, "__iter__")
else ",".join(mentions)
),
"parse": json.dumps([p.value for p in parse]) if parse is not None else None,
"updateMsgId": update_msg_id
},
timeout=self.timeout_s
)
try:
self.__sent_im_cache[response.json()["response"]["data"]["msgId"]] = text
except (LookupError, TypeError):
self.log.exception("Error while getting 'msgId'!")
responses.add(response)
return tuple(responses)
except ReadTimeout:
self.log.exception("Timeout while sending request!") | 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_base_url),
data={
"r": uuid.uuid4(),
"aimsid": self.token,
"t": target,
"message": text,
"mentions": (
mentions if isinstance(mentions, six.string_types) or not hasattr(mentions, "__iter__")
else ",".join(mentions)
),
"parse": json.dumps([p.value for p in parse]) if parse is not None else None,
"updateMsgId": update_msg_id
},
timeout=self.timeout_s
)
try:
self.__sent_im_cache[response.json()["response"]["data"]["msgId"]] = text
except (LookupError, TypeError):
self.log.exception("Error while getting 'msgId'!")
responses.add(response)
return tuple(responses)
except ReadTimeout:
self.log.exception("Timeout while sending request!") | [
"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_base_url",
")",
",",
"data",
"=",
"{",
"\"r\"",
":",
"uuid",
".",
"uuid4",
"(",
")",
",",
"\"aimsid\"",
":",
"self",
".",
"token",
",",
"\"t\"",
":",
"target",
",",
"\"message\"",
":",
"text",
",",
"\"mentions\"",
":",
"(",
"mentions",
"if",
"isinstance",
"(",
"mentions",
",",
"six",
".",
"string_types",
")",
"or",
"not",
"hasattr",
"(",
"mentions",
",",
"\"__iter__\"",
")",
"else",
"\",\"",
".",
"join",
"(",
"mentions",
")",
")",
",",
"\"parse\"",
":",
"json",
".",
"dumps",
"(",
"[",
"p",
".",
"value",
"for",
"p",
"in",
"parse",
"]",
")",
"if",
"parse",
"is",
"not",
"None",
"else",
"None",
",",
"\"updateMsgId\"",
":",
"update_msg_id",
"}",
",",
"timeout",
"=",
"self",
".",
"timeout_s",
")",
"try",
":",
"self",
".",
"__sent_im_cache",
"[",
"response",
".",
"json",
"(",
")",
"[",
"\"response\"",
"]",
"[",
"\"data\"",
"]",
"[",
"\"msgId\"",
"]",
"]",
"=",
"text",
"except",
"(",
"LookupError",
",",
"TypeError",
")",
":",
"self",
".",
"log",
".",
"exception",
"(",
"\"Error while getting 'msgId'!\"",
")",
"responses",
".",
"add",
"(",
"response",
")",
"return",
"tuple",
"(",
"responses",
")",
"except",
"ReadTimeout",
":",
"self",
".",
"log",
".",
"exception",
"(",
"\"Timeout while sending request!\"",
")"
] | 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 be parsed by target client (making preview, snippets, etc.). Specify empty iterable to avoid
parsing message at target client. By default all types are included.
:param update_msg_id: Message ID to update.
:param wrap_length: Maximum length of symbols in one message. Text exceeding this length will be sent in several
messages.
:return: Tuple of HTTP responses. | [
"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_markdown_html) | 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",
"(",
"text",
")",
"sanitised_markdown_html",
"=",
"_sanitise_markdown_html",
"(",
"markdown_html",
")",
"return",
"mark_safe",
"(",
"sanitised_markdown_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 header.startswith('|'):
border = True
# Get alignment of columns
align = []
for c in self._split_row(seperator, border):
if c.startswith(':') and c.endswith(':'):
align.append('center')
elif c.startswith(':'):
align.append('left')
elif c.endswith(':'):
align.append('right')
else:
align.append(None)
# Build table
table = etree.SubElement(parent, 'table')
table.set('class', 'wftable')
thead = etree.SubElement(table, 'thead')
self._build_row(header, thead, align, border)
tbody = etree.SubElement(table, 'tbody')
for row in rows:
self._build_row(row.strip(), tbody, align, border) | 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
# Get alignment of columns
align = []
for c in self._split_row(seperator, border):
if c.startswith(':') and c.endswith(':'):
align.append('center')
elif c.startswith(':'):
align.append('left')
elif c.endswith(':'):
align.append('right')
else:
align.append(None)
# Build table
table = etree.SubElement(parent, 'table')
table.set('class', 'wftable')
thead = etree.SubElement(table, 'thead')
self._build_row(header, thead, align, border)
tbody = etree.SubElement(table, 'tbody')
for row in rows:
self._build_row(row.strip(), tbody, align, border) | [
"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)\r",
"border",
"=",
"False",
"if",
"header",
".",
"startswith",
"(",
"'|'",
")",
":",
"border",
"=",
"True",
"# Get alignment of columns\r",
"align",
"=",
"[",
"]",
"for",
"c",
"in",
"self",
".",
"_split_row",
"(",
"seperator",
",",
"border",
")",
":",
"if",
"c",
".",
"startswith",
"(",
"':'",
")",
"and",
"c",
".",
"endswith",
"(",
"':'",
")",
":",
"align",
".",
"append",
"(",
"'center'",
")",
"elif",
"c",
".",
"startswith",
"(",
"':'",
")",
":",
"align",
".",
"append",
"(",
"'left'",
")",
"elif",
"c",
".",
"endswith",
"(",
"':'",
")",
":",
"align",
".",
"append",
"(",
"'right'",
")",
"else",
":",
"align",
".",
"append",
"(",
"None",
")",
"# Build table\r",
"table",
"=",
"etree",
".",
"SubElement",
"(",
"parent",
",",
"'table'",
")",
"table",
".",
"set",
"(",
"'class'",
",",
"'wftable'",
")",
"thead",
"=",
"etree",
".",
"SubElement",
"(",
"table",
",",
"'thead'",
")",
"self",
".",
"_build_row",
"(",
"header",
",",
"thead",
",",
"align",
",",
"border",
")",
"tbody",
"=",
"etree",
".",
"SubElement",
"(",
"table",
",",
"'tbody'",
")",
"for",
"row",
"in",
"rows",
":",
"self",
".",
"_build_row",
"(",
"row",
".",
"strip",
"(",
")",
",",
"tbody",
",",
"align",
",",
"border",
")"
] | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.