repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
brbsix/subnuker | subnuker.py | AeidonProject.open | def open(self):
"""Open the subtitle file into an Aeidon project."""
try:
self.project.open_main(self.filename)
except UnicodeDecodeError:
with open(self.filename, 'rb') as openfile:
encoding = get_encoding(openfile.read())
try:
... | python | def open(self):
"""Open the subtitle file into an Aeidon project."""
try:
self.project.open_main(self.filename)
except UnicodeDecodeError:
with open(self.filename, 'rb') as openfile:
encoding = get_encoding(openfile.read())
try:
... | [
"def",
"open",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"project",
".",
"open_main",
"(",
"self",
".",
"filename",
")",
"except",
"UnicodeDecodeError",
":",
"with",
"open",
"(",
"self",
".",
"filename",
",",
"'rb'",
")",
"as",
"openfile",
":",
... | Open the subtitle file into an Aeidon project. | [
"Open",
"the",
"subtitle",
"file",
"into",
"an",
"Aeidon",
"project",
"."
] | train | https://github.com/brbsix/subnuker/blob/a94260a6e84b790a9e39e0b1793443ffd4e1f496/subnuker.py#L99-L117 |
brbsix/subnuker | subnuker.py | AeidonProject.save | def save(self):
"""Save subtitle file."""
try:
# ensure file is encoded properly while saving
self.project.main_file.encoding = 'utf_8'
self.project.save_main()
if self.fix:
LOGGER.info("Saved changes to '%s'", self.filename)
except... | python | def save(self):
"""Save subtitle file."""
try:
# ensure file is encoded properly while saving
self.project.main_file.encoding = 'utf_8'
self.project.save_main()
if self.fix:
LOGGER.info("Saved changes to '%s'", self.filename)
except... | [
"def",
"save",
"(",
"self",
")",
":",
"try",
":",
"# ensure file is encoded properly while saving",
"self",
".",
"project",
".",
"main_file",
".",
"encoding",
"=",
"'utf_8'",
"self",
".",
"project",
".",
"save_main",
"(",
")",
"if",
"self",
".",
"fix",
":",
... | Save subtitle file. | [
"Save",
"subtitle",
"file",
"."
] | train | https://github.com/brbsix/subnuker/blob/a94260a6e84b790a9e39e0b1793443ffd4e1f496/subnuker.py#L146-L156 |
brbsix/subnuker | subnuker.py | AeidonProject.search | def search(self):
"""Search srt in project for cells matching list of terms."""
matches = []
for pattern in Config.patterns:
matches += self.termfinder(pattern)
return sorted(set(matches), key=int) | python | def search(self):
"""Search srt in project for cells matching list of terms."""
matches = []
for pattern in Config.patterns:
matches += self.termfinder(pattern)
return sorted(set(matches), key=int) | [
"def",
"search",
"(",
"self",
")",
":",
"matches",
"=",
"[",
"]",
"for",
"pattern",
"in",
"Config",
".",
"patterns",
":",
"matches",
"+=",
"self",
".",
"termfinder",
"(",
"pattern",
")",
"return",
"sorted",
"(",
"set",
"(",
"matches",
")",
",",
"key"... | Search srt in project for cells matching list of terms. | [
"Search",
"srt",
"in",
"project",
"for",
"cells",
"matching",
"list",
"of",
"terms",
"."
] | train | https://github.com/brbsix/subnuker/blob/a94260a6e84b790a9e39e0b1793443ffd4e1f496/subnuker.py#L158-L165 |
brbsix/subnuker | subnuker.py | AeidonProject.termfinder | def termfinder(self, pattern):
"""Search srt in project for cells matching term."""
if Config.options.regex:
flags = re.M | re.S | \
(0 if Config.options.case_sensitive else re.I)
self.project.set_search_regex(
pattern, flags=flags)
else:
... | python | def termfinder(self, pattern):
"""Search srt in project for cells matching term."""
if Config.options.regex:
flags = re.M | re.S | \
(0 if Config.options.case_sensitive else re.I)
self.project.set_search_regex(
pattern, flags=flags)
else:
... | [
"def",
"termfinder",
"(",
"self",
",",
"pattern",
")",
":",
"if",
"Config",
".",
"options",
".",
"regex",
":",
"flags",
"=",
"re",
".",
"M",
"|",
"re",
".",
"S",
"|",
"(",
"0",
"if",
"Config",
".",
"options",
".",
"case_sensitive",
"else",
"re",
... | Search srt in project for cells matching term. | [
"Search",
"srt",
"in",
"project",
"for",
"cells",
"matching",
"term",
"."
] | train | https://github.com/brbsix/subnuker/blob/a94260a6e84b790a9e39e0b1793443ffd4e1f496/subnuker.py#L167-L195 |
brbsix/subnuker | subnuker.py | SrtProject.fixchars | def fixchars(self, text):
"""Find and replace problematic characters."""
keys = ''.join(Config.CHARFIXES.keys())
values = ''.join(Config.CHARFIXES.values())
fixed = text.translate(str.maketrans(keys, values))
if fixed != text:
self.modified = True
return fixed | python | def fixchars(self, text):
"""Find and replace problematic characters."""
keys = ''.join(Config.CHARFIXES.keys())
values = ''.join(Config.CHARFIXES.values())
fixed = text.translate(str.maketrans(keys, values))
if fixed != text:
self.modified = True
return fixed | [
"def",
"fixchars",
"(",
"self",
",",
"text",
")",
":",
"keys",
"=",
"''",
".",
"join",
"(",
"Config",
".",
"CHARFIXES",
".",
"keys",
"(",
")",
")",
"values",
"=",
"''",
".",
"join",
"(",
"Config",
".",
"CHARFIXES",
".",
"values",
"(",
")",
")",
... | Find and replace problematic characters. | [
"Find",
"and",
"replace",
"problematic",
"characters",
"."
] | train | https://github.com/brbsix/subnuker/blob/a94260a6e84b790a9e39e0b1793443ffd4e1f496/subnuker.py#L229-L236 |
brbsix/subnuker | subnuker.py | SrtProject.open | def open(self):
"""Open the subtitle file (detect encoding if necessary)."""
with open(self.filename, 'rb') as file_open:
binary = file_open.read()
try:
return binary.decode()
except UnicodeDecodeError:
encoding = get_encoding(binary)
try:... | python | def open(self):
"""Open the subtitle file (detect encoding if necessary)."""
with open(self.filename, 'rb') as file_open:
binary = file_open.read()
try:
return binary.decode()
except UnicodeDecodeError:
encoding = get_encoding(binary)
try:... | [
"def",
"open",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"filename",
",",
"'rb'",
")",
"as",
"file_open",
":",
"binary",
"=",
"file_open",
".",
"read",
"(",
")",
"try",
":",
"return",
"binary",
".",
"decode",
"(",
")",
"except",
"Uni... | Open the subtitle file (detect encoding if necessary). | [
"Open",
"the",
"subtitle",
"file",
"(",
"detect",
"encoding",
"if",
"necessary",
")",
"."
] | train | https://github.com/brbsix/subnuker/blob/a94260a6e84b790a9e39e0b1793443ffd4e1f496/subnuker.py#L238-L254 |
brbsix/subnuker | subnuker.py | SrtProject.prompt | def prompt(self, matches):
"""Prompt user to remove cells from subtitle file."""
if Config.options.autoyes:
return matches
deletions = []
for match in matches:
os.system('clear')
print(self.cells[match])
print('--------------------------... | python | def prompt(self, matches):
"""Prompt user to remove cells from subtitle file."""
if Config.options.autoyes:
return matches
deletions = []
for match in matches:
os.system('clear')
print(self.cells[match])
print('--------------------------... | [
"def",
"prompt",
"(",
"self",
",",
"matches",
")",
":",
"if",
"Config",
".",
"options",
".",
"autoyes",
":",
"return",
"matches",
"deletions",
"=",
"[",
"]",
"for",
"match",
"in",
"matches",
":",
"os",
".",
"system",
"(",
"'clear'",
")",
"print",
"("... | Prompt user to remove cells from subtitle file. | [
"Prompt",
"user",
"to",
"remove",
"cells",
"from",
"subtitle",
"file",
"."
] | train | https://github.com/brbsix/subnuker/blob/a94260a6e84b790a9e39e0b1793443ffd4e1f496/subnuker.py#L256-L281 |
brbsix/subnuker | subnuker.py | SrtProject.renumber | def renumber(self):
"""Re-number cells."""
num = 0
for cell in self.cells:
cell_split = cell.splitlines()
if len(cell_split) >= 2:
num += 1
cell_split[0] = str(num)
yield '\n'.join(cell_split) | python | def renumber(self):
"""Re-number cells."""
num = 0
for cell in self.cells:
cell_split = cell.splitlines()
if len(cell_split) >= 2:
num += 1
cell_split[0] = str(num)
yield '\n'.join(cell_split) | [
"def",
"renumber",
"(",
"self",
")",
":",
"num",
"=",
"0",
"for",
"cell",
"in",
"self",
".",
"cells",
":",
"cell_split",
"=",
"cell",
".",
"splitlines",
"(",
")",
"if",
"len",
"(",
"cell_split",
")",
">=",
"2",
":",
"num",
"+=",
"1",
"cell_split",
... | Re-number cells. | [
"Re",
"-",
"number",
"cells",
"."
] | train | https://github.com/brbsix/subnuker/blob/a94260a6e84b790a9e39e0b1793443ffd4e1f496/subnuker.py#L283-L292 |
brbsix/subnuker | subnuker.py | SrtProject.save | def save(self):
"""Format and save cells."""
# re-number cells
self.cells = list(self.renumber())
# add a newline to the last line if necessary
if not self.cells[-1].endswith('\n'):
self.cells[-1] += '\n'
# save the rejoined the list of cells
with o... | python | def save(self):
"""Format and save cells."""
# re-number cells
self.cells = list(self.renumber())
# add a newline to the last line if necessary
if not self.cells[-1].endswith('\n'):
self.cells[-1] += '\n'
# save the rejoined the list of cells
with o... | [
"def",
"save",
"(",
"self",
")",
":",
"# re-number cells",
"self",
".",
"cells",
"=",
"list",
"(",
"self",
".",
"renumber",
"(",
")",
")",
"# add a newline to the last line if necessary",
"if",
"not",
"self",
".",
"cells",
"[",
"-",
"1",
"]",
".",
"endswit... | Format and save cells. | [
"Format",
"and",
"save",
"cells",
"."
] | train | https://github.com/brbsix/subnuker/blob/a94260a6e84b790a9e39e0b1793443ffd4e1f496/subnuker.py#L294-L306 |
brbsix/subnuker | subnuker.py | SrtProject.search | def search(self):
"""Return list of cells to be removed."""
matches = []
for index, cell in enumerate(self.cells):
for pattern in Config.patterns:
if ismatch(cell, pattern):
matches.append(index)
break
return matches | python | def search(self):
"""Return list of cells to be removed."""
matches = []
for index, cell in enumerate(self.cells):
for pattern in Config.patterns:
if ismatch(cell, pattern):
matches.append(index)
break
return matches | [
"def",
"search",
"(",
"self",
")",
":",
"matches",
"=",
"[",
"]",
"for",
"index",
",",
"cell",
"in",
"enumerate",
"(",
"self",
".",
"cells",
")",
":",
"for",
"pattern",
"in",
"Config",
".",
"patterns",
":",
"if",
"ismatch",
"(",
"cell",
",",
"patte... | Return list of cells to be removed. | [
"Return",
"list",
"of",
"cells",
"to",
"be",
"removed",
"."
] | train | https://github.com/brbsix/subnuker/blob/a94260a6e84b790a9e39e0b1793443ffd4e1f496/subnuker.py#L308-L318 |
brbsix/subnuker | subnuker.py | SrtProject.split | def split(self, text):
"""Split text into a list of cells."""
import re
if re.search('\n\n', text):
return text.split('\n\n')
elif re.search('\r\n\r\n', text):
return text.split('\r\n\r\n')
else:
LOGGER.error("'%s' does not appear to be a 'srt... | python | def split(self, text):
"""Split text into a list of cells."""
import re
if re.search('\n\n', text):
return text.split('\n\n')
elif re.search('\r\n\r\n', text):
return text.split('\r\n\r\n')
else:
LOGGER.error("'%s' does not appear to be a 'srt... | [
"def",
"split",
"(",
"self",
",",
"text",
")",
":",
"import",
"re",
"if",
"re",
".",
"search",
"(",
"'\\n\\n'",
",",
"text",
")",
":",
"return",
"text",
".",
"split",
"(",
"'\\n\\n'",
")",
"elif",
"re",
".",
"search",
"(",
"'\\r\\n\\r\\n'",
",",
"t... | Split text into a list of cells. | [
"Split",
"text",
"into",
"a",
"list",
"of",
"cells",
"."
] | train | https://github.com/brbsix/subnuker/blob/a94260a6e84b790a9e39e0b1793443ffd4e1f496/subnuker.py#L320-L331 |
rsalmaso/django-fluo | fluo/utils/json.py | dumps | def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, **kw): # NOQA
"""Serialize ``obj`` to a JSON formatted ``str``.
If ``skipkeys`` is false then ``dict`` keys that are not basic types
(``str``, ``uni... | python | def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, **kw): # NOQA
"""Serialize ``obj`` to a JSON formatted ``str``.
If ``skipkeys`` is false then ``dict`` keys that are not basic types
(``str``, ``uni... | [
"def",
"dumps",
"(",
"obj",
",",
"skipkeys",
"=",
"False",
",",
"ensure_ascii",
"=",
"True",
",",
"check_circular",
"=",
"True",
",",
"allow_nan",
"=",
"True",
",",
"cls",
"=",
"None",
",",
"indent",
"=",
"None",
",",
"separators",
"=",
"None",
",",
... | Serialize ``obj`` to a JSON formatted ``str``.
If ``skipkeys`` is false then ``dict`` keys that are not basic types
(``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
will be skipped instead of raising a ``TypeError``.
If ``ensure_ascii`` is false, then the return value will be a... | [
"Serialize",
"obj",
"to",
"a",
"JSON",
"formatted",
"str",
"."
] | train | https://github.com/rsalmaso/django-fluo/blob/1321c1e7d6a912108f79be02a9e7f2108c57f89f/fluo/utils/json.py#L118-L171 |
sunlightlabs/django-locksmith | locksmith/hub/dataviews.py | _active_keys_by_month | def _active_keys_by_month(ignore_internal_keys, monthly_minimum, cached=True):
"""
Returns a dict of (year, month) -> active_keys. The dict will contain a key
for each month observed in the data.
"""
cache_key = '_active_keys_by_month({0!r},{1!r})[{date!s}]'.format(ignore_internal_keys,
... | python | def _active_keys_by_month(ignore_internal_keys, monthly_minimum, cached=True):
"""
Returns a dict of (year, month) -> active_keys. The dict will contain a key
for each month observed in the data.
"""
cache_key = '_active_keys_by_month({0!r},{1!r})[{date!s}]'.format(ignore_internal_keys,
... | [
"def",
"_active_keys_by_month",
"(",
"ignore_internal_keys",
",",
"monthly_minimum",
",",
"cached",
"=",
"True",
")",
":",
"cache_key",
"=",
"'_active_keys_by_month({0!r},{1!r})[{date!s}]'",
".",
"format",
"(",
"ignore_internal_keys",
",",
"monthly_minimum",
",",
"date",
... | Returns a dict of (year, month) -> active_keys. The dict will contain a key
for each month observed in the data. | [
"Returns",
"a",
"dict",
"of",
"(",
"year",
"month",
")",
"-",
">",
"active_keys",
".",
"The",
"dict",
"will",
"contain",
"a",
"key",
"for",
"each",
"month",
"observed",
"in",
"the",
"data",
"."
] | train | https://github.com/sunlightlabs/django-locksmith/blob/eef5b7c25404560aaad50b6e622594f89239b74b/locksmith/hub/dataviews.py#L135-L179 |
sunlightlabs/django-locksmith | locksmith/hub/dataviews.py | keys | def keys(request):
"""Lists API keys. Compatible with jQuery DataTables."""
iDisplayStart = parse_int_param(request, 'iDisplayStart')
iDisplayLength = parse_int_param(request, 'iDisplayLength')
sEcho = parse_int_param(request, 'sEcho')
iSortCol_0 = parse_int_param(request, 'iSortCol_0')
sSortDir... | python | def keys(request):
"""Lists API keys. Compatible with jQuery DataTables."""
iDisplayStart = parse_int_param(request, 'iDisplayStart')
iDisplayLength = parse_int_param(request, 'iDisplayLength')
sEcho = parse_int_param(request, 'sEcho')
iSortCol_0 = parse_int_param(request, 'iSortCol_0')
sSortDir... | [
"def",
"keys",
"(",
"request",
")",
":",
"iDisplayStart",
"=",
"parse_int_param",
"(",
"request",
",",
"'iDisplayStart'",
")",
"iDisplayLength",
"=",
"parse_int_param",
"(",
"request",
",",
"'iDisplayLength'",
")",
"sEcho",
"=",
"parse_int_param",
"(",
"request",
... | Lists API keys. Compatible with jQuery DataTables. | [
"Lists",
"API",
"keys",
".",
"Compatible",
"with",
"jQuery",
"DataTables",
"."
] | train | https://github.com/sunlightlabs/django-locksmith/blob/eef5b7c25404560aaad50b6e622594f89239b74b/locksmith/hub/dataviews.py#L468-L507 |
MacHu-GWU/angora-project | angora/algorithm/iterable.py | flatten_all | def flatten_all(list_of_list):
"""Flatten arbitrary depth of nesting. Good for unknown nesting structure
iterable object.
Usage::
>>> flatten_all([[0, 1], [2, 3, [4, 5], [6, 7, 8]], [9,]])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
"""
for i in list_of_list:
if hasattr(i, "__iter__"):
... | python | def flatten_all(list_of_list):
"""Flatten arbitrary depth of nesting. Good for unknown nesting structure
iterable object.
Usage::
>>> flatten_all([[0, 1], [2, 3, [4, 5], [6, 7, 8]], [9,]])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
"""
for i in list_of_list:
if hasattr(i, "__iter__"):
... | [
"def",
"flatten_all",
"(",
"list_of_list",
")",
":",
"for",
"i",
"in",
"list_of_list",
":",
"if",
"hasattr",
"(",
"i",
",",
"\"__iter__\"",
")",
":",
"for",
"j",
"in",
"flatten_all",
"(",
"i",
")",
":",
"yield",
"j",
"else",
":",
"yield",
"i"
] | Flatten arbitrary depth of nesting. Good for unknown nesting structure
iterable object.
Usage::
>>> flatten_all([[0, 1], [2, 3, [4, 5], [6, 7, 8]], [9,]])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] | [
"Flatten",
"arbitrary",
"depth",
"of",
"nesting",
".",
"Good",
"for",
"unknown",
"nesting",
"structure",
"iterable",
"object",
"."
] | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/algorithm/iterable.py#L83-L97 |
MacHu-GWU/angora-project | angora/algorithm/iterable.py | grouper_dict | def grouper_dict(d, n):
"""Evenly divide dictionary into fixed-length piece, no filled value if
chunk size smaller than fixed-length.
Usage::
>>> list(grouper_dict({1: 'A', 2: 'B', 3: 'C', 4: 'D', 5: 'E',
6: 'F', 7: 'G', 8: 'H', 9: 'I', 10: 'J'}))
[{1: 'A', 2... | python | def grouper_dict(d, n):
"""Evenly divide dictionary into fixed-length piece, no filled value if
chunk size smaller than fixed-length.
Usage::
>>> list(grouper_dict({1: 'A', 2: 'B', 3: 'C', 4: 'D', 5: 'E',
6: 'F', 7: 'G', 8: 'H', 9: 'I', 10: 'J'}))
[{1: 'A', 2... | [
"def",
"grouper_dict",
"(",
"d",
",",
"n",
")",
":",
"chunk",
"=",
"dict",
"(",
")",
"counter",
"=",
"0",
"for",
"k",
",",
"v",
"in",
"d",
".",
"items",
"(",
")",
":",
"counter",
"+=",
"1",
"chunk",
"[",
"k",
"]",
"=",
"v",
"print",
"(",
"c... | Evenly divide dictionary into fixed-length piece, no filled value if
chunk size smaller than fixed-length.
Usage::
>>> list(grouper_dict({1: 'A', 2: 'B', 3: 'C', 4: 'D', 5: 'E',
6: 'F', 7: 'G', 8: 'H', 9: 'I', 10: 'J'}))
[{1: 'A', 2: 'B', 3: 'C'}, {4: 'D', 5: 'E'... | [
"Evenly",
"divide",
"dictionary",
"into",
"fixed",
"-",
"length",
"piece",
"no",
"filled",
"value",
"if",
"chunk",
"size",
"smaller",
"than",
"fixed",
"-",
"length",
"."
] | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/algorithm/iterable.py#L169-L191 |
MacHu-GWU/angora-project | angora/algorithm/iterable.py | running_windows | def running_windows(iterable, size):
"""Generate n-size running windows.
Usage::
>>> for i in running_windows([1, 2, 3, 4, 5], size=3):
... print(i)
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
"""
fifo = collections.deque(maxlen=size)
for i in iterable:
fifo.a... | python | def running_windows(iterable, size):
"""Generate n-size running windows.
Usage::
>>> for i in running_windows([1, 2, 3, 4, 5], size=3):
... print(i)
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
"""
fifo = collections.deque(maxlen=size)
for i in iterable:
fifo.a... | [
"def",
"running_windows",
"(",
"iterable",
",",
"size",
")",
":",
"fifo",
"=",
"collections",
".",
"deque",
"(",
"maxlen",
"=",
"size",
")",
"for",
"i",
"in",
"iterable",
":",
"fifo",
".",
"append",
"(",
"i",
")",
"if",
"len",
"(",
"fifo",
")",
"==... | Generate n-size running windows.
Usage::
>>> for i in running_windows([1, 2, 3, 4, 5], size=3):
... print(i)
[1, 2, 3]
[2, 3, 4]
[3, 4, 5] | [
"Generate",
"n",
"-",
"size",
"running",
"windows",
"."
] | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/algorithm/iterable.py#L194-L209 |
MacHu-GWU/angora-project | angora/algorithm/iterable.py | cycle_slice | def cycle_slice(sliceable, start, end):
"""Given a list, return right hand cycle direction slice from start to end.
Usage::
>>> array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> cycle_slice(array, 4, 7) # from array[4] to array[7]
[4, 5, 6, 7]
>>> cycle_slice(array, 8, 2) # from arra... | python | def cycle_slice(sliceable, start, end):
"""Given a list, return right hand cycle direction slice from start to end.
Usage::
>>> array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> cycle_slice(array, 4, 7) # from array[4] to array[7]
[4, 5, 6, 7]
>>> cycle_slice(array, 8, 2) # from arra... | [
"def",
"cycle_slice",
"(",
"sliceable",
",",
"start",
",",
"end",
")",
":",
"if",
"type",
"(",
"sliceable",
")",
"!=",
"list",
":",
"sliceable",
"=",
"list",
"(",
"sliceable",
")",
"if",
"end",
">=",
"start",
":",
"return",
"sliceable",
"[",
"start",
... | Given a list, return right hand cycle direction slice from start to end.
Usage::
>>> array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> cycle_slice(array, 4, 7) # from array[4] to array[7]
[4, 5, 6, 7]
>>> cycle_slice(array, 8, 2) # from array[8] to array[2]
[8, 9, 0, 1, 2] | [
"Given",
"a",
"list",
"return",
"right",
"hand",
"cycle",
"direction",
"slice",
"from",
"start",
"to",
"end",
"."
] | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/algorithm/iterable.py#L237-L255 |
MacHu-GWU/angora-project | angora/algorithm/iterable.py | cycle_dist | def cycle_dist(x, y, n):
"""Find Distance between x, y by means of a n-length cycle.
Example:
cycle_dist(1, 23, 24) = 2
cycle_dist(5, 13, 24) = 8
cycle_dist(0.0, 2.4, 1.0) = 0.4
cycle_dist(0.0, 2.6, 1.0) = 0.4
"""
dist = abs(x - y) % n
if dist >= 0.5 * n:
di... | python | def cycle_dist(x, y, n):
"""Find Distance between x, y by means of a n-length cycle.
Example:
cycle_dist(1, 23, 24) = 2
cycle_dist(5, 13, 24) = 8
cycle_dist(0.0, 2.4, 1.0) = 0.4
cycle_dist(0.0, 2.6, 1.0) = 0.4
"""
dist = abs(x - y) % n
if dist >= 0.5 * n:
di... | [
"def",
"cycle_dist",
"(",
"x",
",",
"y",
",",
"n",
")",
":",
"dist",
"=",
"abs",
"(",
"x",
"-",
"y",
")",
"%",
"n",
"if",
"dist",
">=",
"0.5",
"*",
"n",
":",
"dist",
"=",
"n",
"-",
"dist",
"return",
"dist"
] | Find Distance between x, y by means of a n-length cycle.
Example:
cycle_dist(1, 23, 24) = 2
cycle_dist(5, 13, 24) = 8
cycle_dist(0.0, 2.4, 1.0) = 0.4
cycle_dist(0.0, 2.6, 1.0) = 0.4 | [
"Find",
"Distance",
"between",
"x",
"y",
"by",
"means",
"of",
"a",
"n",
"-",
"length",
"cycle",
"."
] | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/algorithm/iterable.py#L258-L271 |
MacHu-GWU/angora-project | angora/algorithm/iterable.py | shift_to_the_left | def shift_to_the_left(array, dist, pad=True, trim=True):
"""Shift array to the left.
:param array: An iterable object.
:type array: iterable object
:param dist: how far you want to shift
:type disk: int
:param pad: pad array[-1] to the right.
:type pad: boolean (default True)
:param tri... | python | def shift_to_the_left(array, dist, pad=True, trim=True):
"""Shift array to the left.
:param array: An iterable object.
:type array: iterable object
:param dist: how far you want to shift
:type disk: int
:param pad: pad array[-1] to the right.
:type pad: boolean (default True)
:param tri... | [
"def",
"shift_to_the_left",
"(",
"array",
",",
"dist",
",",
"pad",
"=",
"True",
",",
"trim",
"=",
"True",
")",
":",
"if",
"dist",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"Shift distance has to greater or equal than 0.\"",
")",
"if",
"pad",
":",
"if",
... | Shift array to the left.
:param array: An iterable object.
:type array: iterable object
:param dist: how far you want to shift
:type disk: int
:param pad: pad array[-1] to the right.
:type pad: boolean (default True)
:param trim: trim the first ``#dist`` items.
:type trim: boolean (defa... | [
"Shift",
"array",
"to",
"the",
"left",
"."
] | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/algorithm/iterable.py#L274-L316 |
MacHu-GWU/angora-project | angora/algorithm/iterable.py | count_generator | def count_generator(generator, memory_efficient=True):
"""Count number of item in generator.
memory_efficient=True, 3 times slower, but memory_efficient.
memory_efficient=False, faster, but cost more memory.
"""
if memory_efficient:
counter = 0
for _ in generator:
counte... | python | def count_generator(generator, memory_efficient=True):
"""Count number of item in generator.
memory_efficient=True, 3 times slower, but memory_efficient.
memory_efficient=False, faster, but cost more memory.
"""
if memory_efficient:
counter = 0
for _ in generator:
counte... | [
"def",
"count_generator",
"(",
"generator",
",",
"memory_efficient",
"=",
"True",
")",
":",
"if",
"memory_efficient",
":",
"counter",
"=",
"0",
"for",
"_",
"in",
"generator",
":",
"counter",
"+=",
"1",
"return",
"counter",
"else",
":",
"return",
"len",
"("... | Count number of item in generator.
memory_efficient=True, 3 times slower, but memory_efficient.
memory_efficient=False, faster, but cost more memory. | [
"Count",
"number",
"of",
"item",
"in",
"generator",
"."
] | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/algorithm/iterable.py#L364-L376 |
MacHu-GWU/pyknackhq-project | pyknackhq/schema.py | Object.get_field_key | def get_field_key(self, key, using_name=True):
"""Given a field key or name, return it's field key.
"""
try:
if using_name:
return self.f_name[key].key
else:
return self.f[key].key
except KeyError:
raise ValueError("'%s'... | python | def get_field_key(self, key, using_name=True):
"""Given a field key or name, return it's field key.
"""
try:
if using_name:
return self.f_name[key].key
else:
return self.f[key].key
except KeyError:
raise ValueError("'%s'... | [
"def",
"get_field_key",
"(",
"self",
",",
"key",
",",
"using_name",
"=",
"True",
")",
":",
"try",
":",
"if",
"using_name",
":",
"return",
"self",
".",
"f_name",
"[",
"key",
"]",
".",
"key",
"else",
":",
"return",
"self",
".",
"f",
"[",
"key",
"]",
... | Given a field key or name, return it's field key. | [
"Given",
"a",
"field",
"key",
"or",
"name",
"return",
"it",
"s",
"field",
"key",
"."
] | train | https://github.com/MacHu-GWU/pyknackhq-project/blob/dd937f24d7b0a351ba3818eb746c31b29a8cc341/pyknackhq/schema.py#L80-L89 |
MacHu-GWU/pyknackhq-project | pyknackhq/schema.py | Application.get_object_key | def get_object_key(self, key, using_name=True):
"""Given a object key or name, return it's object key.
"""
try:
if using_name:
return self.o_name[key].key
else:
return self.o[key].key
except KeyError:
raise ValueError("'... | python | def get_object_key(self, key, using_name=True):
"""Given a object key or name, return it's object key.
"""
try:
if using_name:
return self.o_name[key].key
else:
return self.o[key].key
except KeyError:
raise ValueError("'... | [
"def",
"get_object_key",
"(",
"self",
",",
"key",
",",
"using_name",
"=",
"True",
")",
":",
"try",
":",
"if",
"using_name",
":",
"return",
"self",
".",
"o_name",
"[",
"key",
"]",
".",
"key",
"else",
":",
"return",
"self",
".",
"o",
"[",
"key",
"]",... | Given a object key or name, return it's object key. | [
"Given",
"a",
"object",
"key",
"or",
"name",
"return",
"it",
"s",
"object",
"key",
"."
] | train | https://github.com/MacHu-GWU/pyknackhq-project/blob/dd937f24d7b0a351ba3818eb746c31b29a8cc341/pyknackhq/schema.py#L149-L158 |
MacHu-GWU/angora-project | angora/filesystem/winzip.py | zip_a_folder | def zip_a_folder(src, dst):
"""Add a folder and everything inside to zip archive.
Example::
|---paper
|--- algorithm.pdf
|--- images
|--- 1.jpg
zip_a_folder("paper", "paper.zip")
paper.zip
|---paper
|--- algorithm.pd... | python | def zip_a_folder(src, dst):
"""Add a folder and everything inside to zip archive.
Example::
|---paper
|--- algorithm.pdf
|--- images
|--- 1.jpg
zip_a_folder("paper", "paper.zip")
paper.zip
|---paper
|--- algorithm.pd... | [
"def",
"zip_a_folder",
"(",
"src",
",",
"dst",
")",
":",
"src",
",",
"dst",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"src",
")",
",",
"os",
".",
"path",
".",
"abspath",
"(",
"dst",
")",
"cwd",
"=",
"os",
".",
"getcwd",
"(",
")",
"todo",
"... | Add a folder and everything inside to zip archive.
Example::
|---paper
|--- algorithm.pdf
|--- images
|--- 1.jpg
zip_a_folder("paper", "paper.zip")
paper.zip
|---paper
|--- algorithm.pdf
|--- images
... | [
"Add",
"a",
"folder",
"and",
"everything",
"inside",
"to",
"zip",
"archive",
"."
] | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/filesystem/winzip.py#L67-L104 |
MacHu-GWU/angora-project | angora/filesystem/winzip.py | zip_many_files | def zip_many_files(list_of_abspath, dst):
"""Add many files to a zip archive.
**中文文档**
将一系列的文件压缩到一个压缩包中, 若有重复的文件名, 在zip中保留所有的副本。
"""
base_dir = os.getcwd()
with ZipFile(dst, "w") as f:
for abspath in list_of_abspath:
dirname, basename = os.path.split(abspath)
o... | python | def zip_many_files(list_of_abspath, dst):
"""Add many files to a zip archive.
**中文文档**
将一系列的文件压缩到一个压缩包中, 若有重复的文件名, 在zip中保留所有的副本。
"""
base_dir = os.getcwd()
with ZipFile(dst, "w") as f:
for abspath in list_of_abspath:
dirname, basename = os.path.split(abspath)
o... | [
"def",
"zip_many_files",
"(",
"list_of_abspath",
",",
"dst",
")",
":",
"base_dir",
"=",
"os",
".",
"getcwd",
"(",
")",
"with",
"ZipFile",
"(",
"dst",
",",
"\"w\"",
")",
"as",
"f",
":",
"for",
"abspath",
"in",
"list_of_abspath",
":",
"dirname",
",",
"ba... | Add many files to a zip archive.
**中文文档**
将一系列的文件压缩到一个压缩包中, 若有重复的文件名, 在zip中保留所有的副本。 | [
"Add",
"many",
"files",
"to",
"a",
"zip",
"archive",
"."
] | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/filesystem/winzip.py#L145-L160 |
MacHu-GWU/angora-project | angora/filesystem/winzip.py | write_gzip | def write_gzip(content, abspath):
"""Write binary content to gzip file.
**中文文档**
将二进制内容压缩后编码写入gzip压缩文件。
"""
with gzip.open(abspath, "wb") as f:
f.write(content) | python | def write_gzip(content, abspath):
"""Write binary content to gzip file.
**中文文档**
将二进制内容压缩后编码写入gzip压缩文件。
"""
with gzip.open(abspath, "wb") as f:
f.write(content) | [
"def",
"write_gzip",
"(",
"content",
",",
"abspath",
")",
":",
"with",
"gzip",
".",
"open",
"(",
"abspath",
",",
"\"wb\"",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"content",
")"
] | Write binary content to gzip file.
**中文文档**
将二进制内容压缩后编码写入gzip压缩文件。 | [
"Write",
"binary",
"content",
"to",
"gzip",
"file",
"."
] | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/filesystem/winzip.py#L163-L171 |
klmitch/metatools | metatools.py | MetaMeta.iter_bases | def iter_bases(bases):
"""
Performs MRO linearization of a set of base classes. Yields
each base class in turn.
"""
sequences = ([list(inspect.getmro(base)) for base in bases] +
[list(bases)])
# Loop over sequences
while True:
s... | python | def iter_bases(bases):
"""
Performs MRO linearization of a set of base classes. Yields
each base class in turn.
"""
sequences = ([list(inspect.getmro(base)) for base in bases] +
[list(bases)])
# Loop over sequences
while True:
s... | [
"def",
"iter_bases",
"(",
"bases",
")",
":",
"sequences",
"=",
"(",
"[",
"list",
"(",
"inspect",
".",
"getmro",
"(",
"base",
")",
")",
"for",
"base",
"in",
"bases",
"]",
"+",
"[",
"list",
"(",
"bases",
")",
"]",
")",
"# Loop over sequences",
"while",... | Performs MRO linearization of a set of base classes. Yields
each base class in turn. | [
"Performs",
"MRO",
"linearization",
"of",
"a",
"set",
"of",
"base",
"classes",
".",
"Yields",
"each",
"base",
"class",
"in",
"turn",
"."
] | train | https://github.com/klmitch/metatools/blob/7161cf22ef2b194cfd4406e85b81e39a49104d9d/metatools.py#L53-L86 |
klmitch/metatools | metatools.py | MetaMeta.inherit_dict | def inherit_dict(base, namespace, attr_name,
inherit=lambda k, v: True):
"""
Perform inheritance of dictionaries. Returns a list of key
and value pairs for values that were inherited, for
post-processing.
:param base: The base class being considered; see
... | python | def inherit_dict(base, namespace, attr_name,
inherit=lambda k, v: True):
"""
Perform inheritance of dictionaries. Returns a list of key
and value pairs for values that were inherited, for
post-processing.
:param base: The base class being considered; see
... | [
"def",
"inherit_dict",
"(",
"base",
",",
"namespace",
",",
"attr_name",
",",
"inherit",
"=",
"lambda",
"k",
",",
"v",
":",
"True",
")",
":",
"items",
"=",
"[",
"]",
"# Get the dicts to compare",
"base_dict",
"=",
"getattr",
"(",
"base",
",",
"attr_name",
... | Perform inheritance of dictionaries. Returns a list of key
and value pairs for values that were inherited, for
post-processing.
:param base: The base class being considered; see
``iter_bases()``.
:param namespace: The dictionary of the new class being built.
... | [
"Perform",
"inheritance",
"of",
"dictionaries",
".",
"Returns",
"a",
"list",
"of",
"key",
"and",
"value",
"pairs",
"for",
"values",
"that",
"were",
"inherited",
"for",
"post",
"-",
"processing",
"."
] | train | https://github.com/klmitch/metatools/blob/7161cf22ef2b194cfd4406e85b81e39a49104d9d/metatools.py#L89-L131 |
klmitch/metatools | metatools.py | MetaMeta.inherit_set | def inherit_set(base, namespace, attr_name,
inherit=lambda i: True):
"""
Perform inheritance of sets. Returns a list of items that
were inherited, for post-processing.
:param base: The base class being considered; see
``iter_bases()``.
:... | python | def inherit_set(base, namespace, attr_name,
inherit=lambda i: True):
"""
Perform inheritance of sets. Returns a list of items that
were inherited, for post-processing.
:param base: The base class being considered; see
``iter_bases()``.
:... | [
"def",
"inherit_set",
"(",
"base",
",",
"namespace",
",",
"attr_name",
",",
"inherit",
"=",
"lambda",
"i",
":",
"True",
")",
":",
"items",
"=",
"[",
"]",
"# Get the sets to compare",
"base_set",
"=",
"getattr",
"(",
"base",
",",
"attr_name",
",",
"set",
... | Perform inheritance of sets. Returns a list of items that
were inherited, for post-processing.
:param base: The base class being considered; see
``iter_bases()``.
:param namespace: The dictionary of the new class being built.
:param attr_name: The name of the attri... | [
"Perform",
"inheritance",
"of",
"sets",
".",
"Returns",
"a",
"list",
"of",
"items",
"that",
"were",
"inherited",
"for",
"post",
"-",
"processing",
"."
] | train | https://github.com/klmitch/metatools/blob/7161cf22ef2b194cfd4406e85b81e39a49104d9d/metatools.py#L134-L173 |
EnigmaBridge/client.py | ebclient/process_data.py | ProcessData.call | def call(self, input_data=None, *args, **kwargs):
"""
Calls the request with input data using given configuration (retry, timeout, ...).
:param input_data:
:param args:
:param kwargs:
:return:
"""
self.build_request(input_data)
self.caller = Reques... | python | def call(self, input_data=None, *args, **kwargs):
"""
Calls the request with input data using given configuration (retry, timeout, ...).
:param input_data:
:param args:
:param kwargs:
:return:
"""
self.build_request(input_data)
self.caller = Reques... | [
"def",
"call",
"(",
"self",
",",
"input_data",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"build_request",
"(",
"input_data",
")",
"self",
".",
"caller",
"=",
"RequestCall",
"(",
"self",
".",
"request",
")",
"self"... | Calls the request with input data using given configuration (retry, timeout, ...).
:param input_data:
:param args:
:param kwargs:
:return: | [
"Calls",
"the",
"request",
"with",
"input",
"data",
"using",
"given",
"configuration",
"(",
"retry",
"timeout",
"...",
")",
".",
":",
"param",
"input_data",
":",
":",
"param",
"args",
":",
":",
"param",
"kwargs",
":",
":",
"return",
":"
] | train | https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/process_data.py#L32-L53 |
EnigmaBridge/client.py | ebclient/process_data.py | ProcessData.build_request | def build_request(self, input_data=None, *args, **kwargs):
"""
Builds request
:param input_data:
:param args:
:param kwargs:
:return:
"""
if input_data is not None:
self.input_data = input_data
if self.input_data is None:
r... | python | def build_request(self, input_data=None, *args, **kwargs):
"""
Builds request
:param input_data:
:param args:
:param kwargs:
:return:
"""
if input_data is not None:
self.input_data = input_data
if self.input_data is None:
r... | [
"def",
"build_request",
"(",
"self",
",",
"input_data",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"input_data",
"is",
"not",
"None",
":",
"self",
".",
"input_data",
"=",
"input_data",
"if",
"self",
".",
"input_data",
"is",... | Builds request
:param input_data:
:param args:
:param kwargs:
:return: | [
"Builds",
"request"
] | train | https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/process_data.py#L55-L92 |
EnigmaBridge/client.py | ebclient/process_data.py | ProcessData.decrypt_result | def decrypt_result(self, *args, **kwargs):
"""
Decrypts ProcessData result with comm keys
:param args:
:param kwargs:
:return:
"""
if self.response is None:
raise ValueError('Empty response')
if self.response.response is None \
... | python | def decrypt_result(self, *args, **kwargs):
"""
Decrypts ProcessData result with comm keys
:param args:
:param kwargs:
:return:
"""
if self.response is None:
raise ValueError('Empty response')
if self.response.response is None \
... | [
"def",
"decrypt_result",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"response",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Empty response'",
")",
"if",
"self",
".",
"response",
".",
"response",
"is",
"Non... | Decrypts ProcessData result with comm keys
:param args:
:param kwargs:
:return: | [
"Decrypts",
"ProcessData",
"result",
"with",
"comm",
"keys"
] | train | https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/process_data.py#L94-L147 |
langloisjp/tstore | tstore/tstore.py | TStore.db | def db(self):
"""Lazy init the DB (fork friendly)"""
if not self._db:
self._db = pgtablestorage.DB(dburl=self.dburl)
return self._db | python | def db(self):
"""Lazy init the DB (fork friendly)"""
if not self._db:
self._db = pgtablestorage.DB(dburl=self.dburl)
return self._db | [
"def",
"db",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_db",
":",
"self",
".",
"_db",
"=",
"pgtablestorage",
".",
"DB",
"(",
"dburl",
"=",
"self",
".",
"dburl",
")",
"return",
"self",
".",
"_db"
] | Lazy init the DB (fork friendly) | [
"Lazy",
"init",
"the",
"DB",
"(",
"fork",
"friendly",
")"
] | train | https://github.com/langloisjp/tstore/blob/b438f8aaf09117bf6f922ba06ae5cf46b7b97a57/tstore/tstore.py#L102-L106 |
langloisjp/tstore | tstore/tstore.py | TStore.get | def get(self, cls, rid):
"""Return record of given type with key `rid`
>>> s = teststore()
>>> s.create('tstoretest', {'id': '1', 'name': 'Toto'})
>>> r = s.get('tstoretest', '1')
>>> r['name']
'Toto'
>>> s.get('badcls', '1')
Traceback (most recent call l... | python | def get(self, cls, rid):
"""Return record of given type with key `rid`
>>> s = teststore()
>>> s.create('tstoretest', {'id': '1', 'name': 'Toto'})
>>> r = s.get('tstoretest', '1')
>>> r['name']
'Toto'
>>> s.get('badcls', '1')
Traceback (most recent call l... | [
"def",
"get",
"(",
"self",
",",
"cls",
",",
"rid",
")",
":",
"self",
".",
"validate_record_type",
"(",
"cls",
")",
"rows",
"=",
"self",
".",
"db",
".",
"select",
"(",
"cls",
",",
"where",
"=",
"{",
"ID",
":",
"rid",
"}",
",",
"limit",
"=",
"1",... | Return record of given type with key `rid`
>>> s = teststore()
>>> s.create('tstoretest', {'id': '1', 'name': 'Toto'})
>>> r = s.get('tstoretest', '1')
>>> r['name']
'Toto'
>>> s.get('badcls', '1')
Traceback (most recent call last):
...
ValueE... | [
"Return",
"record",
"of",
"given",
"type",
"with",
"key",
"rid"
] | train | https://github.com/langloisjp/tstore/blob/b438f8aaf09117bf6f922ba06ae5cf46b7b97a57/tstore/tstore.py#L118-L139 |
langloisjp/tstore | tstore/tstore.py | TStore.create | def create(self, cls, record, user='undefined'):
"""Persist new record
>>> s = teststore()
>>> s.create('tstoretest', {'id': '1', 'name': 'Toto'})
>>> s.create('tstoretest', {'id': '2', 'name': 'Tata'}, user='jane')
>>> r = s.get('tstoretest', '2')
>>> r[CREATOR]
... | python | def create(self, cls, record, user='undefined'):
"""Persist new record
>>> s = teststore()
>>> s.create('tstoretest', {'id': '1', 'name': 'Toto'})
>>> s.create('tstoretest', {'id': '2', 'name': 'Tata'}, user='jane')
>>> r = s.get('tstoretest', '2')
>>> r[CREATOR]
... | [
"def",
"create",
"(",
"self",
",",
"cls",
",",
"record",
",",
"user",
"=",
"'undefined'",
")",
":",
"self",
".",
"validate_record",
"(",
"cls",
",",
"record",
")",
"record",
"[",
"CREATION_DATE",
"]",
"=",
"record",
"[",
"UPDATE_DATE",
"]",
"=",
"self"... | Persist new record
>>> s = teststore()
>>> s.create('tstoretest', {'id': '1', 'name': 'Toto'})
>>> s.create('tstoretest', {'id': '2', 'name': 'Tata'}, user='jane')
>>> r = s.get('tstoretest', '2')
>>> r[CREATOR]
'jane'
>>> s.create('badcls', {'id': '1', 'name': '... | [
"Persist",
"new",
"record"
] | train | https://github.com/langloisjp/tstore/blob/b438f8aaf09117bf6f922ba06ae5cf46b7b97a57/tstore/tstore.py#L141-L184 |
langloisjp/tstore | tstore/tstore.py | TStore.update | def update(self, cls, rid, partialrecord, user='undefined'):
"""Update existing record
>>> s = teststore()
>>> s.create('tstoretest', {'id': '1', 'name': 'Toto'})
>>> r = s.get('tstoretest', '1')
>>> r['age']
>>> s.update('tstoretest', '1', {'age': 25})
>>> r = s... | python | def update(self, cls, rid, partialrecord, user='undefined'):
"""Update existing record
>>> s = teststore()
>>> s.create('tstoretest', {'id': '1', 'name': 'Toto'})
>>> r = s.get('tstoretest', '1')
>>> r['age']
>>> s.update('tstoretest', '1', {'age': 25})
>>> r = s... | [
"def",
"update",
"(",
"self",
",",
"cls",
",",
"rid",
",",
"partialrecord",
",",
"user",
"=",
"'undefined'",
")",
":",
"self",
".",
"validate_partial_record",
"(",
"cls",
",",
"partialrecord",
")",
"partialrecord",
"[",
"UPDATE_DATE",
"]",
"=",
"self",
"."... | Update existing record
>>> s = teststore()
>>> s.create('tstoretest', {'id': '1', 'name': 'Toto'})
>>> r = s.get('tstoretest', '1')
>>> r['age']
>>> s.update('tstoretest', '1', {'age': 25})
>>> r = s.get('tstoretest', '1')
>>> r['age']
25
>>> s.up... | [
"Update",
"existing",
"record"
] | train | https://github.com/langloisjp/tstore/blob/b438f8aaf09117bf6f922ba06ae5cf46b7b97a57/tstore/tstore.py#L186-L235 |
langloisjp/tstore | tstore/tstore.py | TStore.list | def list(self, cls, criteria=None):
"""
Return list of matching records. criteria is a dict of {field: value}
>>> s = teststore()
>>> s.list('tstoretest')
[]
"""
self.validate_criteria(cls, criteria)
return self.db.select(cls, where=criteria) | python | def list(self, cls, criteria=None):
"""
Return list of matching records. criteria is a dict of {field: value}
>>> s = teststore()
>>> s.list('tstoretest')
[]
"""
self.validate_criteria(cls, criteria)
return self.db.select(cls, where=criteria) | [
"def",
"list",
"(",
"self",
",",
"cls",
",",
"criteria",
"=",
"None",
")",
":",
"self",
".",
"validate_criteria",
"(",
"cls",
",",
"criteria",
")",
"return",
"self",
".",
"db",
".",
"select",
"(",
"cls",
",",
"where",
"=",
"criteria",
")"
] | Return list of matching records. criteria is a dict of {field: value}
>>> s = teststore()
>>> s.list('tstoretest')
[] | [
"Return",
"list",
"of",
"matching",
"records",
".",
"criteria",
"is",
"a",
"dict",
"of",
"{",
"field",
":",
"value",
"}"
] | train | https://github.com/langloisjp/tstore/blob/b438f8aaf09117bf6f922ba06ae5cf46b7b97a57/tstore/tstore.py#L237-L246 |
langloisjp/tstore | tstore/tstore.py | TStore.delete | def delete(self, cls, rid, user='undefined'):
"""
Delete a record by id.
`user` currently unused. Would be used with soft deletes.
>>> s = teststore()
>>> s.create('tstoretest', {'id': '1', 'name': 'Toto'})
>>> len(s.list('tstoretest'))
1
>>> s.delete('t... | python | def delete(self, cls, rid, user='undefined'):
"""
Delete a record by id.
`user` currently unused. Would be used with soft deletes.
>>> s = teststore()
>>> s.create('tstoretest', {'id': '1', 'name': 'Toto'})
>>> len(s.list('tstoretest'))
1
>>> s.delete('t... | [
"def",
"delete",
"(",
"self",
",",
"cls",
",",
"rid",
",",
"user",
"=",
"'undefined'",
")",
":",
"self",
".",
"validate_record_type",
"(",
"cls",
")",
"deletedcount",
"=",
"self",
".",
"db",
".",
"delete",
"(",
"cls",
",",
"{",
"ID",
":",
"rid",
"}... | Delete a record by id.
`user` currently unused. Would be used with soft deletes.
>>> s = teststore()
>>> s.create('tstoretest', {'id': '1', 'name': 'Toto'})
>>> len(s.list('tstoretest'))
1
>>> s.delete('tstoretest', '1')
>>> len(s.list('tstoretest'))
0
... | [
"Delete",
"a",
"record",
"by",
"id",
"."
] | train | https://github.com/langloisjp/tstore/blob/b438f8aaf09117bf6f922ba06ae5cf46b7b97a57/tstore/tstore.py#L248-L269 |
langloisjp/tstore | tstore/tstore.py | TStore.validate_record_type | def validate_record_type(self, cls):
"""
Validate given record is acceptable.
>>> s = teststore()
>>> s.validate_record_type('tstoretest')
>>> s.validate_record_type('bad')
Traceback (most recent call last):
...
ValueError: Unsupported record type "ba... | python | def validate_record_type(self, cls):
"""
Validate given record is acceptable.
>>> s = teststore()
>>> s.validate_record_type('tstoretest')
>>> s.validate_record_type('bad')
Traceback (most recent call last):
...
ValueError: Unsupported record type "ba... | [
"def",
"validate_record_type",
"(",
"self",
",",
"cls",
")",
":",
"if",
"self",
".",
"record_types",
"and",
"cls",
"not",
"in",
"self",
".",
"record_types",
":",
"raise",
"ValueError",
"(",
"'Unsupported record type \"'",
"+",
"cls",
"+",
"'\"'",
")"
] | Validate given record is acceptable.
>>> s = teststore()
>>> s.validate_record_type('tstoretest')
>>> s.validate_record_type('bad')
Traceback (most recent call last):
...
ValueError: Unsupported record type "bad" | [
"Validate",
"given",
"record",
"is",
"acceptable",
"."
] | train | https://github.com/langloisjp/tstore/blob/b438f8aaf09117bf6f922ba06ae5cf46b7b97a57/tstore/tstore.py#L271-L283 |
langloisjp/tstore | tstore/tstore.py | TStore.as_record | def as_record(self, cls, content_type, strdata):
"""
Returns a record from serialized string representation.
>>> s = teststore()
>>> s.as_record('tstoretest', 'application/json',
... '{"id": "1", "name": "Toto"}')
{u'id': u'1', u'name': u'Toto'}
"""
self.... | python | def as_record(self, cls, content_type, strdata):
"""
Returns a record from serialized string representation.
>>> s = teststore()
>>> s.as_record('tstoretest', 'application/json',
... '{"id": "1", "name": "Toto"}')
{u'id': u'1', u'name': u'Toto'}
"""
self.... | [
"def",
"as_record",
"(",
"self",
",",
"cls",
",",
"content_type",
",",
"strdata",
")",
":",
"self",
".",
"validate_record_type",
"(",
"cls",
")",
"parsedrecord",
"=",
"self",
".",
"deserialize",
"(",
"content_type",
",",
"strdata",
")",
"return",
"self",
"... | Returns a record from serialized string representation.
>>> s = teststore()
>>> s.as_record('tstoretest', 'application/json',
... '{"id": "1", "name": "Toto"}')
{u'id': u'1', u'name': u'Toto'} | [
"Returns",
"a",
"record",
"from",
"serialized",
"string",
"representation",
"."
] | train | https://github.com/langloisjp/tstore/blob/b438f8aaf09117bf6f922ba06ae5cf46b7b97a57/tstore/tstore.py#L285-L296 |
langloisjp/tstore | tstore/tstore.py | TStore.serialize | def serialize(self, cls, record):
"""
Serialize the record to JSON. cls unused in this implementation.
>>> s = teststore()
>>> s.serialize('tstoretest', {'id': '1', 'name': 'Toto'})
'{"id": "1", "name": "Toto"}'
"""
return json.dumps(record, cls=self.encoder) | python | def serialize(self, cls, record):
"""
Serialize the record to JSON. cls unused in this implementation.
>>> s = teststore()
>>> s.serialize('tstoretest', {'id': '1', 'name': 'Toto'})
'{"id": "1", "name": "Toto"}'
"""
return json.dumps(record, cls=self.encoder) | [
"def",
"serialize",
"(",
"self",
",",
"cls",
",",
"record",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"record",
",",
"cls",
"=",
"self",
".",
"encoder",
")"
] | Serialize the record to JSON. cls unused in this implementation.
>>> s = teststore()
>>> s.serialize('tstoretest', {'id': '1', 'name': 'Toto'})
'{"id": "1", "name": "Toto"}' | [
"Serialize",
"the",
"record",
"to",
"JSON",
".",
"cls",
"unused",
"in",
"this",
"implementation",
"."
] | train | https://github.com/langloisjp/tstore/blob/b438f8aaf09117bf6f922ba06ae5cf46b7b97a57/tstore/tstore.py#L298-L306 |
langloisjp/tstore | tstore/tstore.py | TStore.deserialize | def deserialize(self, content_type, strdata):
"""Deserialize string of given content type.
`self` unused in this implementation.
>>> s = teststore()
>>> s.deserialize('application/json', '{"id": "1", "name": "Toto"}')
{u'id': u'1', u'name': u'Toto'}
>>> s.deserialize('t... | python | def deserialize(self, content_type, strdata):
"""Deserialize string of given content type.
`self` unused in this implementation.
>>> s = teststore()
>>> s.deserialize('application/json', '{"id": "1", "name": "Toto"}')
{u'id': u'1', u'name': u'Toto'}
>>> s.deserialize('t... | [
"def",
"deserialize",
"(",
"self",
",",
"content_type",
",",
"strdata",
")",
":",
"if",
"content_type",
"!=",
"'application/json'",
":",
"raise",
"ValueError",
"(",
"'Unsupported content type \"'",
"+",
"content_type",
"+",
"'\"'",
")",
"return",
"json",
".",
"l... | Deserialize string of given content type.
`self` unused in this implementation.
>>> s = teststore()
>>> s.deserialize('application/json', '{"id": "1", "name": "Toto"}')
{u'id': u'1', u'name': u'Toto'}
>>> s.deserialize('text/plain', 'id: 1, name: Toto')
Traceback (most ... | [
"Deserialize",
"string",
"of",
"given",
"content",
"type",
"."
] | train | https://github.com/langloisjp/tstore/blob/b438f8aaf09117bf6f922ba06ae5cf46b7b97a57/tstore/tstore.py#L308-L323 |
Exanis/django-rest-generators | django_rest_generators/steps/http.py | when_i_send_the_request | def when_i_send_the_request(context, method):
"""
:type method: str
:type context: behave.runner.Context
"""
data = context.apiRequestData
context.apiRequest = context.apiClient.generic(
method,
data['url'],
data=json.dumps(data['params']),
content_type=... | python | def when_i_send_the_request(context, method):
"""
:type method: str
:type context: behave.runner.Context
"""
data = context.apiRequestData
context.apiRequest = context.apiClient.generic(
method,
data['url'],
data=json.dumps(data['params']),
content_type=... | [
"def",
"when_i_send_the_request",
"(",
"context",
",",
"method",
")",
":",
"data",
"=",
"context",
".",
"apiRequestData",
"context",
".",
"apiRequest",
"=",
"context",
".",
"apiClient",
".",
"generic",
"(",
"method",
",",
"data",
"[",
"'url'",
"]",
",",
"d... | :type method: str
:type context: behave.runner.Context | [
":",
"type",
"method",
":",
"str",
":",
"type",
"context",
":",
"behave",
".",
"runner",
".",
"Context"
] | train | https://github.com/Exanis/django-rest-generators/blob/fb14ccbba8cb029dc056d852bc13d9216dc924e4/django_rest_generators/steps/http.py#L33-L45 |
Exanis/django-rest-generators | django_rest_generators/steps/http.py | then_the_return_value_for_is | def then_the_return_value_for_is(context, key, value):
"""
:type key: str
:type value: str
:type context: behave.runner.Context
"""
assert key in context.apiRequest.data
assert str(context.apiRequest.data[key]) == str(value) | python | def then_the_return_value_for_is(context, key, value):
"""
:type key: str
:type value: str
:type context: behave.runner.Context
"""
assert key in context.apiRequest.data
assert str(context.apiRequest.data[key]) == str(value) | [
"def",
"then_the_return_value_for_is",
"(",
"context",
",",
"key",
",",
"value",
")",
":",
"assert",
"key",
"in",
"context",
".",
"apiRequest",
".",
"data",
"assert",
"str",
"(",
"context",
".",
"apiRequest",
".",
"data",
"[",
"key",
"]",
")",
"==",
"str... | :type key: str
:type value: str
:type context: behave.runner.Context | [
":",
"type",
"key",
":",
"str",
":",
"type",
"value",
":",
"str",
":",
"type",
"context",
":",
"behave",
".",
"runner",
".",
"Context"
] | train | https://github.com/Exanis/django-rest-generators/blob/fb14ccbba8cb029dc056d852bc13d9216dc924e4/django_rest_generators/steps/http.py#L58-L65 |
Exanis/django-rest-generators | django_rest_generators/steps/http.py | then_then_returned_element_have_a_key | def then_then_returned_element_have_a_key(context, line, key, value):
"""
:type line: str
:type key: str
:type value: str
:type context: behave.runner.Context
"""
line = int(line)
data = context.apiRequest.data
assert 0 <= line < len(data)
row = data[line]
assert k... | python | def then_then_returned_element_have_a_key(context, line, key, value):
"""
:type line: str
:type key: str
:type value: str
:type context: behave.runner.Context
"""
line = int(line)
data = context.apiRequest.data
assert 0 <= line < len(data)
row = data[line]
assert k... | [
"def",
"then_then_returned_element_have_a_key",
"(",
"context",
",",
"line",
",",
"key",
",",
"value",
")",
":",
"line",
"=",
"int",
"(",
"line",
")",
"data",
"=",
"context",
".",
"apiRequest",
".",
"data",
"assert",
"0",
"<=",
"line",
"<",
"len",
"(",
... | :type line: str
:type key: str
:type value: str
:type context: behave.runner.Context | [
":",
"type",
"line",
":",
"str",
":",
"type",
"key",
":",
"str",
":",
"type",
"value",
":",
"str",
":",
"type",
"context",
":",
"behave",
".",
"runner",
".",
"Context"
] | train | https://github.com/Exanis/django-rest-generators/blob/fb14ccbba8cb029dc056d852bc13d9216dc924e4/django_rest_generators/steps/http.py#L79-L91 |
Exanis/django-rest-generators | django_rest_generators/steps/http.py | then_the_return_element_have_no_key | def then_the_return_element_have_no_key(context, line, key):
"""
:param context: behave.runner.Context
:param line: str
:param key: str
"""
line = int(line)
data = context.apiRequest.data
assert 0 <= line < len(data)
assert key not in data[line] | python | def then_the_return_element_have_no_key(context, line, key):
"""
:param context: behave.runner.Context
:param line: str
:param key: str
"""
line = int(line)
data = context.apiRequest.data
assert 0 <= line < len(data)
assert key not in data[line] | [
"def",
"then_the_return_element_have_no_key",
"(",
"context",
",",
"line",
",",
"key",
")",
":",
"line",
"=",
"int",
"(",
"line",
")",
"data",
"=",
"context",
".",
"apiRequest",
".",
"data",
"assert",
"0",
"<=",
"line",
"<",
"len",
"(",
"data",
")",
"a... | :param context: behave.runner.Context
:param line: str
:param key: str | [
":",
"param",
"context",
":",
"behave",
".",
"runner",
".",
"Context",
":",
"param",
"line",
":",
"str",
":",
"param",
"key",
":",
"str"
] | train | https://github.com/Exanis/django-rest-generators/blob/fb14ccbba8cb029dc056d852bc13d9216dc924e4/django_rest_generators/steps/http.py#L107-L116 |
klmitch/tendril | tendril/framers.py | FrameState._reset | def _reset(self, framer):
"""
Reset the state for the framer. It is safe to call this
method multiple times with the same framer; the ID of the
framer object will be saved and the state only reset if the
IDs are different. After resetting the state, the framer's
``init_... | python | def _reset(self, framer):
"""
Reset the state for the framer. It is safe to call this
method multiple times with the same framer; the ID of the
framer object will be saved and the state only reset if the
IDs are different. After resetting the state, the framer's
``init_... | [
"def",
"_reset",
"(",
"self",
",",
"framer",
")",
":",
"# Do nothing if we're already properly initialized",
"if",
"id",
"(",
"framer",
")",
"==",
"self",
".",
"_framer_id",
":",
"return",
"# Reset the state",
"self",
".",
"_other",
"=",
"{",
"}",
"# Initialize ... | Reset the state for the framer. It is safe to call this
method multiple times with the same framer; the ID of the
framer object will be saved and the state only reset if the
IDs are different. After resetting the state, the framer's
``init_state()`` method will be called. | [
"Reset",
"the",
"state",
"for",
"the",
"framer",
".",
"It",
"is",
"safe",
"to",
"call",
"this",
"method",
"multiple",
"times",
"with",
"the",
"same",
"framer",
";",
"the",
"ID",
"of",
"the",
"framer",
"object",
"will",
"be",
"saved",
"and",
"the",
"sta... | train | https://github.com/klmitch/tendril/blob/207102c83e88f8f1fa7ba605ef0aab2ae9078b36/tendril/framers.py#L101-L119 |
klmitch/tendril | tendril/framers.py | IdentityFramer.frameify | def frameify(self, state, data):
"""Yield the data as a single frame."""
try:
yield state.recv_buf + data
except FrameSwitch:
pass
finally:
state.recv_buf = '' | python | def frameify(self, state, data):
"""Yield the data as a single frame."""
try:
yield state.recv_buf + data
except FrameSwitch:
pass
finally:
state.recv_buf = '' | [
"def",
"frameify",
"(",
"self",
",",
"state",
",",
"data",
")",
":",
"try",
":",
"yield",
"state",
".",
"recv_buf",
"+",
"data",
"except",
"FrameSwitch",
":",
"pass",
"finally",
":",
"state",
".",
"recv_buf",
"=",
"''"
] | Yield the data as a single frame. | [
"Yield",
"the",
"data",
"as",
"a",
"single",
"frame",
"."
] | train | https://github.com/klmitch/tendril/blob/207102c83e88f8f1fa7ba605ef0aab2ae9078b36/tendril/framers.py#L167-L175 |
klmitch/tendril | tendril/framers.py | ChunkFramer.frameify | def frameify(self, state, data):
"""Yield chunk data as a single frame, and buffer the rest."""
# If we've pulled in all the chunk data, buffer the data
if state.chunk_remaining <= 0:
state.recv_buf += data
return
# Pull in any partially-processed data
d... | python | def frameify(self, state, data):
"""Yield chunk data as a single frame, and buffer the rest."""
# If we've pulled in all the chunk data, buffer the data
if state.chunk_remaining <= 0:
state.recv_buf += data
return
# Pull in any partially-processed data
d... | [
"def",
"frameify",
"(",
"self",
",",
"state",
",",
"data",
")",
":",
"# If we've pulled in all the chunk data, buffer the data",
"if",
"state",
".",
"chunk_remaining",
"<=",
"0",
":",
"state",
".",
"recv_buf",
"+=",
"data",
"return",
"# Pull in any partially-processed... | Yield chunk data as a single frame, and buffer the rest. | [
"Yield",
"chunk",
"data",
"as",
"a",
"single",
"frame",
"and",
"buffer",
"the",
"rest",
"."
] | train | https://github.com/klmitch/tendril/blob/207102c83e88f8f1fa7ba605ef0aab2ae9078b36/tendril/framers.py#L207-L235 |
klmitch/tendril | tendril/framers.py | LineFramer.frameify | def frameify(self, state, data):
"""Split data into a sequence of lines."""
# Pull in any partially-processed data
data = state.recv_buf + data
# Loop over the data
while data:
line, sep, rest = data.partition('\n')
# Did we have a whole line?
... | python | def frameify(self, state, data):
"""Split data into a sequence of lines."""
# Pull in any partially-processed data
data = state.recv_buf + data
# Loop over the data
while data:
line, sep, rest = data.partition('\n')
# Did we have a whole line?
... | [
"def",
"frameify",
"(",
"self",
",",
"state",
",",
"data",
")",
":",
"# Pull in any partially-processed data",
"data",
"=",
"state",
".",
"recv_buf",
"+",
"data",
"# Loop over the data",
"while",
"data",
":",
"line",
",",
"sep",
",",
"rest",
"=",
"data",
"."... | Split data into a sequence of lines. | [
"Split",
"data",
"into",
"a",
"sequence",
"of",
"lines",
"."
] | train | https://github.com/klmitch/tendril/blob/207102c83e88f8f1fa7ba605ef0aab2ae9078b36/tendril/framers.py#L261-L289 |
klmitch/tendril | tendril/framers.py | StructFramer.frameify | def frameify(self, state, data):
"""Split data into a sequence of frames."""
# Pull in any partially-processed data
data = state.recv_buf + data
# Loop over the data
while data:
if state.frame_len is None:
# Try to grab a frame length from the data
... | python | def frameify(self, state, data):
"""Split data into a sequence of frames."""
# Pull in any partially-processed data
data = state.recv_buf + data
# Loop over the data
while data:
if state.frame_len is None:
# Try to grab a frame length from the data
... | [
"def",
"frameify",
"(",
"self",
",",
"state",
",",
"data",
")",
":",
"# Pull in any partially-processed data",
"data",
"=",
"state",
".",
"recv_buf",
"+",
"data",
"# Loop over the data",
"while",
"data",
":",
"if",
"state",
".",
"frame_len",
"is",
"None",
":",... | Split data into a sequence of frames. | [
"Split",
"data",
"into",
"a",
"sequence",
"of",
"frames",
"."
] | train | https://github.com/klmitch/tendril/blob/207102c83e88f8f1fa7ba605ef0aab2ae9078b36/tendril/framers.py#L343-L378 |
klmitch/tendril | tendril/framers.py | StructFramer.streamify | def streamify(self, state, frame):
"""Prepare frame for output as a length/frame stream."""
return '%s%s' % (self.fmt.pack(len(frame)), frame) | python | def streamify(self, state, frame):
"""Prepare frame for output as a length/frame stream."""
return '%s%s' % (self.fmt.pack(len(frame)), frame) | [
"def",
"streamify",
"(",
"self",
",",
"state",
",",
"frame",
")",
":",
"return",
"'%s%s'",
"%",
"(",
"self",
".",
"fmt",
".",
"pack",
"(",
"len",
"(",
"frame",
")",
")",
",",
"frame",
")"
] | Prepare frame for output as a length/frame stream. | [
"Prepare",
"frame",
"for",
"output",
"as",
"a",
"length",
"/",
"frame",
"stream",
"."
] | train | https://github.com/klmitch/tendril/blob/207102c83e88f8f1fa7ba605ef0aab2ae9078b36/tendril/framers.py#L380-L383 |
klmitch/tendril | tendril/framers.py | StuffingFramer.frameify | def frameify(self, state, data):
"""Split data into a sequence of frames."""
# Pull in any partially-processed data
data = state.recv_buf + data
# Loop over the data
while data:
if not state.frame_start:
try:
idx = data.index(self... | python | def frameify(self, state, data):
"""Split data into a sequence of frames."""
# Pull in any partially-processed data
data = state.recv_buf + data
# Loop over the data
while data:
if not state.frame_start:
try:
idx = data.index(self... | [
"def",
"frameify",
"(",
"self",
",",
"state",
",",
"data",
")",
":",
"# Pull in any partially-processed data",
"data",
"=",
"state",
".",
"recv_buf",
"+",
"data",
"# Loop over the data",
"while",
"data",
":",
"if",
"not",
"state",
".",
"frame_start",
":",
"try... | Split data into a sequence of frames. | [
"Split",
"data",
"into",
"a",
"sequence",
"of",
"frames",
"."
] | train | https://github.com/klmitch/tendril/blob/207102c83e88f8f1fa7ba605ef0aab2ae9078b36/tendril/framers.py#L436-L479 |
klmitch/tendril | tendril/framers.py | StuffingFramer.streamify | def streamify(self, state, frame):
"""Prepare frame for output as a byte-stuffed stream."""
# Split the frame apart for stuffing...
pieces = frame.split(self.prefix)
return '%s%s%s%s%s' % (self.prefix, self.begin,
(self.prefix + self.nop).join(pieces),
... | python | def streamify(self, state, frame):
"""Prepare frame for output as a byte-stuffed stream."""
# Split the frame apart for stuffing...
pieces = frame.split(self.prefix)
return '%s%s%s%s%s' % (self.prefix, self.begin,
(self.prefix + self.nop).join(pieces),
... | [
"def",
"streamify",
"(",
"self",
",",
"state",
",",
"frame",
")",
":",
"# Split the frame apart for stuffing...",
"pieces",
"=",
"frame",
".",
"split",
"(",
"self",
".",
"prefix",
")",
"return",
"'%s%s%s%s%s'",
"%",
"(",
"self",
".",
"prefix",
",",
"self",
... | Prepare frame for output as a byte-stuffed stream. | [
"Prepare",
"frame",
"for",
"output",
"as",
"a",
"byte",
"-",
"stuffed",
"stream",
"."
] | train | https://github.com/klmitch/tendril/blob/207102c83e88f8f1fa7ba605ef0aab2ae9078b36/tendril/framers.py#L481-L489 |
klmitch/tendril | tendril/framers.py | COBSFramer._get_tab | def _get_tab(cls):
"""Generate and return the COBS table."""
if not cls._tabs['dec_cobs']:
# Compute the COBS table for decoding
cls._tabs['dec_cobs']['\xff'] = (255, '')
cls._tabs['dec_cobs'].update(dict((chr(l), (l, '\0'))
... | python | def _get_tab(cls):
"""Generate and return the COBS table."""
if not cls._tabs['dec_cobs']:
# Compute the COBS table for decoding
cls._tabs['dec_cobs']['\xff'] = (255, '')
cls._tabs['dec_cobs'].update(dict((chr(l), (l, '\0'))
... | [
"def",
"_get_tab",
"(",
"cls",
")",
":",
"if",
"not",
"cls",
".",
"_tabs",
"[",
"'dec_cobs'",
"]",
":",
"# Compute the COBS table for decoding",
"cls",
".",
"_tabs",
"[",
"'dec_cobs'",
"]",
"[",
"'\\xff'",
"]",
"=",
"(",
"255",
",",
"''",
")",
"cls",
"... | Generate and return the COBS table. | [
"Generate",
"and",
"return",
"the",
"COBS",
"table",
"."
] | train | https://github.com/klmitch/tendril/blob/207102c83e88f8f1fa7ba605ef0aab2ae9078b36/tendril/framers.py#L507-L522 |
klmitch/tendril | tendril/framers.py | COBSFramer._get_tab_zpe | def _get_tab_zpe(cls):
"""Generate and return the COBS ZPE table."""
if not cls._tabs['dec_cobs_zpe']:
# Compute the COBS ZPE table for decoding
cls._tabs['dec_cobs_zpe']['\xe0'] = (224, '')
cls._tabs['dec_cobs_zpe'].update(dict((chr(l), (l, '\0'))
... | python | def _get_tab_zpe(cls):
"""Generate and return the COBS ZPE table."""
if not cls._tabs['dec_cobs_zpe']:
# Compute the COBS ZPE table for decoding
cls._tabs['dec_cobs_zpe']['\xe0'] = (224, '')
cls._tabs['dec_cobs_zpe'].update(dict((chr(l), (l, '\0'))
... | [
"def",
"_get_tab_zpe",
"(",
"cls",
")",
":",
"if",
"not",
"cls",
".",
"_tabs",
"[",
"'dec_cobs_zpe'",
"]",
":",
"# Compute the COBS ZPE table for decoding",
"cls",
".",
"_tabs",
"[",
"'dec_cobs_zpe'",
"]",
"[",
"'\\xe0'",
"]",
"=",
"(",
"224",
",",
"''",
"... | Generate and return the COBS ZPE table. | [
"Generate",
"and",
"return",
"the",
"COBS",
"ZPE",
"table",
"."
] | train | https://github.com/klmitch/tendril/blob/207102c83e88f8f1fa7ba605ef0aab2ae9078b36/tendril/framers.py#L525-L544 |
klmitch/tendril | tendril/framers.py | COBSFramer._decode | def _decode(frame, tab):
"""Decode a frame with the help of the table."""
blocks = []
# Decode each block
while frame:
length, endseq = tab[frame[0]]
blocks.extend([frame[1:length], endseq])
frame = frame[length:]
# Remove one (and only one)... | python | def _decode(frame, tab):
"""Decode a frame with the help of the table."""
blocks = []
# Decode each block
while frame:
length, endseq = tab[frame[0]]
blocks.extend([frame[1:length], endseq])
frame = frame[length:]
# Remove one (and only one)... | [
"def",
"_decode",
"(",
"frame",
",",
"tab",
")",
":",
"blocks",
"=",
"[",
"]",
"# Decode each block",
"while",
"frame",
":",
"length",
",",
"endseq",
"=",
"tab",
"[",
"frame",
"[",
"0",
"]",
"]",
"blocks",
".",
"extend",
"(",
"[",
"frame",
"[",
"1"... | Decode a frame with the help of the table. | [
"Decode",
"a",
"frame",
"with",
"the",
"help",
"of",
"the",
"table",
"."
] | train | https://github.com/klmitch/tendril/blob/207102c83e88f8f1fa7ba605ef0aab2ae9078b36/tendril/framers.py#L547-L563 |
klmitch/tendril | tendril/framers.py | COBSFramer.frameify | def frameify(self, state, data):
"""Split data into a sequence of frames."""
# Pull in any partially-processed data
data = state.recv_buf + data
# Loop over the data
while data:
frame, sep, rest = data.partition('\0')
# Did we have a whole frame?
... | python | def frameify(self, state, data):
"""Split data into a sequence of frames."""
# Pull in any partially-processed data
data = state.recv_buf + data
# Loop over the data
while data:
frame, sep, rest = data.partition('\0')
# Did we have a whole frame?
... | [
"def",
"frameify",
"(",
"self",
",",
"state",
",",
"data",
")",
":",
"# Pull in any partially-processed data",
"data",
"=",
"state",
".",
"recv_buf",
"+",
"data",
"# Loop over the data",
"while",
"data",
":",
"frame",
",",
"sep",
",",
"rest",
"=",
"data",
".... | Split data into a sequence of frames. | [
"Split",
"data",
"into",
"a",
"sequence",
"of",
"frames",
"."
] | train | https://github.com/klmitch/tendril/blob/207102c83e88f8f1fa7ba605ef0aab2ae9078b36/tendril/framers.py#L577-L601 |
klmitch/tendril | tendril/framers.py | COBSFramer.streamify | def streamify(self, state, frame):
"""Prepare frame for output as a COBS-encoded stream."""
# Get the encoding table
enc_tab = self._tables[1][:]
# Need the special un-trailed block length and code
untrail_len, untrail_code = enc_tab.pop(0)
# Set up a repository to rec... | python | def streamify(self, state, frame):
"""Prepare frame for output as a COBS-encoded stream."""
# Get the encoding table
enc_tab = self._tables[1][:]
# Need the special un-trailed block length and code
untrail_len, untrail_code = enc_tab.pop(0)
# Set up a repository to rec... | [
"def",
"streamify",
"(",
"self",
",",
"state",
",",
"frame",
")",
":",
"# Get the encoding table",
"enc_tab",
"=",
"self",
".",
"_tables",
"[",
"1",
"]",
"[",
":",
"]",
"# Need the special un-trailed block length and code",
"untrail_len",
",",
"untrail_code",
"=",... | Prepare frame for output as a COBS-encoded stream. | [
"Prepare",
"frame",
"for",
"output",
"as",
"a",
"COBS",
"-",
"encoded",
"stream",
"."
] | train | https://github.com/klmitch/tendril/blob/207102c83e88f8f1fa7ba605ef0aab2ae9078b36/tendril/framers.py#L603-L650 |
rmed/flask-waffleconf | flask_waffleconf/core.py | _WaffleState.parse_conf | def parse_conf(self, keys=[]):
"""Parse configuration values from the database.
The extension must have been previously initialized.
If a key is not found in the database, it will be created with the
default value specified.
Arguments:
keys (list[str]): list of key... | python | def parse_conf(self, keys=[]):
"""Parse configuration values from the database.
The extension must have been previously initialized.
If a key is not found in the database, it will be created with the
default value specified.
Arguments:
keys (list[str]): list of key... | [
"def",
"parse_conf",
"(",
"self",
",",
"keys",
"=",
"[",
"]",
")",
":",
"confs",
"=",
"self",
".",
"app",
".",
"config",
".",
"get",
"(",
"'WAFFLE_CONFS'",
",",
"{",
"}",
")",
"if",
"not",
"keys",
":",
"keys",
"=",
"confs",
".",
"keys",
"(",
")... | Parse configuration values from the database.
The extension must have been previously initialized.
If a key is not found in the database, it will be created with the
default value specified.
Arguments:
keys (list[str]): list of keys to parse. If the list is empty, then
... | [
"Parse",
"configuration",
"values",
"from",
"the",
"database",
"."
] | train | https://github.com/rmed/flask-waffleconf/blob/a75ed69101796c9f3f42eff9f91e91dc6dd13869/flask_waffleconf/core.py#L58-L102 |
rmed/flask-waffleconf | flask_waffleconf/core.py | _WaffleState.update_db | def update_db(self, new_values):
"""Update database values and application configuration.
The provided keys must be defined in the ``WAFFLE_CONFS`` setting.
Arguments:
new_values (dict): dict of configuration variables and their values
The dict has the following str... | python | def update_db(self, new_values):
"""Update database values and application configuration.
The provided keys must be defined in the ``WAFFLE_CONFS`` setting.
Arguments:
new_values (dict): dict of configuration variables and their values
The dict has the following str... | [
"def",
"update_db",
"(",
"self",
",",
"new_values",
")",
":",
"confs",
"=",
"self",
".",
"app",
".",
"config",
".",
"get",
"(",
"'WAFFLE_CONFS'",
",",
"{",
"}",
")",
"to_update",
"=",
"{",
"}",
"for",
"key",
"in",
"new_values",
".",
"keys",
"(",
")... | Update database values and application configuration.
The provided keys must be defined in the ``WAFFLE_CONFS`` setting.
Arguments:
new_values (dict): dict of configuration variables and their values
The dict has the following structure:
{
... | [
"Update",
"database",
"values",
"and",
"application",
"configuration",
"."
] | train | https://github.com/rmed/flask-waffleconf/blob/a75ed69101796c9f3f42eff9f91e91dc6dd13869/flask_waffleconf/core.py#L104-L144 |
rmed/flask-waffleconf | flask_waffleconf/core.py | _WaffleState.update_conf | def update_conf(self):
"""Update configuration values from database.
This method should be called when there is an update notification.
"""
parsed = self.parse_conf()
if not parsed:
return None
# Update app config
self.app.config.update(parsed) | python | def update_conf(self):
"""Update configuration values from database.
This method should be called when there is an update notification.
"""
parsed = self.parse_conf()
if not parsed:
return None
# Update app config
self.app.config.update(parsed) | [
"def",
"update_conf",
"(",
"self",
")",
":",
"parsed",
"=",
"self",
".",
"parse_conf",
"(",
")",
"if",
"not",
"parsed",
":",
"return",
"None",
"# Update app config",
"self",
".",
"app",
".",
"config",
".",
"update",
"(",
"parsed",
")"
] | Update configuration values from database.
This method should be called when there is an update notification. | [
"Update",
"configuration",
"values",
"from",
"database",
"."
] | train | https://github.com/rmed/flask-waffleconf/blob/a75ed69101796c9f3f42eff9f91e91dc6dd13869/flask_waffleconf/core.py#L146-L157 |
rmed/flask-waffleconf | flask_waffleconf/core.py | WaffleConf.init_app | def init_app(self, app, configstore):
"""Initialize the extension for the given application and store.
Parse the configuration values stored in the database obtained from
the ``WAFFLE_CONFS`` value of the configuration.
Arguments:
app: Flask application instance
... | python | def init_app(self, app, configstore):
"""Initialize the extension for the given application and store.
Parse the configuration values stored in the database obtained from
the ``WAFFLE_CONFS`` value of the configuration.
Arguments:
app: Flask application instance
... | [
"def",
"init_app",
"(",
"self",
",",
"app",
",",
"configstore",
")",
":",
"if",
"not",
"hasattr",
"(",
"app",
",",
"'extensions'",
")",
":",
"app",
".",
"extensions",
"=",
"{",
"}",
"self",
".",
"state",
"=",
"_WaffleState",
"(",
"app",
",",
"configs... | Initialize the extension for the given application and store.
Parse the configuration values stored in the database obtained from
the ``WAFFLE_CONFS`` value of the configuration.
Arguments:
app: Flask application instance
configstore (WaffleStore): database store. | [
"Initialize",
"the",
"extension",
"for",
"the",
"given",
"application",
"and",
"store",
"."
] | train | https://github.com/rmed/flask-waffleconf/blob/a75ed69101796c9f3f42eff9f91e91dc6dd13869/flask_waffleconf/core.py#L177-L192 |
smbapps/isolcss | isolcss/main.py | isolcss | def isolcss(prefix, css):
"""
Returns `css` with all selectors prefixed by `prefix`, or replacing "&"
as SASS and LESS both do.
Tries to parse strictly then falls back, with a warning, to forgiving
parse if necessary.
"""
try:
# Attempt full strict parse, raise exception on failure.... | python | def isolcss(prefix, css):
"""
Returns `css` with all selectors prefixed by `prefix`, or replacing "&"
as SASS and LESS both do.
Tries to parse strictly then falls back, with a warning, to forgiving
parse if necessary.
"""
try:
# Attempt full strict parse, raise exception on failure.... | [
"def",
"isolcss",
"(",
"prefix",
",",
"css",
")",
":",
"try",
":",
"# Attempt full strict parse, raise exception on failure.",
"all",
"(",
"True",
"for",
"m",
"in",
"matchiter",
"(",
"selrule_or_atom_re",
",",
"css",
")",
")",
"except",
"ValueError",
"as",
"e",
... | Returns `css` with all selectors prefixed by `prefix`, or replacing "&"
as SASS and LESS both do.
Tries to parse strictly then falls back, with a warning, to forgiving
parse if necessary. | [
"Returns",
"css",
"with",
"all",
"selectors",
"prefixed",
"by",
"prefix",
"or",
"replacing",
"&",
"as",
"SASS",
"and",
"LESS",
"both",
"do",
"."
] | train | https://github.com/smbapps/isolcss/blob/1613dfd297f64292af1216855b6d096f2bed82fe/isolcss/main.py#L11-L50 |
lewisjared/credkeep | credkeep/decrypt.py | decrypt_file | def decrypt_file(filename, set_env=True, override_env=False):
"""
Decrypts a JSON file containing encrypted secrets. This file should contain an object mapping the key names to
encrypted secrets. This encrypted file can be created using `credkeep.encrypt_file` or the commandline utility.
:param filenam... | python | def decrypt_file(filename, set_env=True, override_env=False):
"""
Decrypts a JSON file containing encrypted secrets. This file should contain an object mapping the key names to
encrypted secrets. This encrypted file can be created using `credkeep.encrypt_file` or the commandline utility.
:param filenam... | [
"def",
"decrypt_file",
"(",
"filename",
",",
"set_env",
"=",
"True",
",",
"override_env",
"=",
"False",
")",
":",
"data",
"=",
"json",
".",
"load",
"(",
"open",
"(",
"filename",
")",
")",
"results",
"=",
"{",
"}",
"for",
"key",
",",
"v",
"in",
"dat... | Decrypts a JSON file containing encrypted secrets. This file should contain an object mapping the key names to
encrypted secrets. This encrypted file can be created using `credkeep.encrypt_file` or the commandline utility.
:param filename: filename of the JSON file
:param set_env: If True, an environment ... | [
"Decrypts",
"a",
"JSON",
"file",
"containing",
"encrypted",
"secrets",
".",
"This",
"file",
"should",
"contain",
"an",
"object",
"mapping",
"the",
"key",
"names",
"to",
"encrypted",
"secrets",
".",
"This",
"encrypted",
"file",
"can",
"be",
"created",
"using",
... | train | https://github.com/lewisjared/credkeep/blob/63638ced094992552a28109b91839bcbbbe9230a/credkeep/decrypt.py#L13-L37 |
lewisjared/credkeep | credkeep/decrypt.py | decrypt_or_cache | def decrypt_or_cache(filename, **kwargs):
"""
Attempts to load a local version of decrypted secrets before making external api calls.
This is useful as it allows credkeep secrets to be used offline. Options for decrypt_filename can be passed to this
function.
:param filename: filename of encrypted ... | python | def decrypt_or_cache(filename, **kwargs):
"""
Attempts to load a local version of decrypted secrets before making external api calls.
This is useful as it allows credkeep secrets to be used offline. Options for decrypt_filename can be passed to this
function.
:param filename: filename of encrypted ... | [
"def",
"decrypt_or_cache",
"(",
"filename",
",",
"*",
"*",
"kwargs",
")",
":",
"clear_fname",
"=",
"enc_to_clear_filename",
"(",
"filename",
")",
"if",
"clear_fname",
":",
"return",
"json",
".",
"load",
"(",
"open",
"(",
"clear_fname",
")",
")",
"return",
... | Attempts to load a local version of decrypted secrets before making external api calls.
This is useful as it allows credkeep secrets to be used offline. Options for decrypt_filename can be passed to this
function.
:param filename: filename of encrypted JSON file
:return: Dict containing decrypted keys | [
"Attempts",
"to",
"load",
"a",
"local",
"version",
"of",
"decrypted",
"secrets",
"before",
"making",
"external",
"api",
"calls",
"."
] | train | https://github.com/lewisjared/credkeep/blob/63638ced094992552a28109b91839bcbbbe9230a/credkeep/decrypt.py#L40-L53 |
datakortet/dkfileutils | dkfileutils/path.py | Path.touch | def touch(self, mode=0o666, exist_ok=True):
"""Create this file with the given access mode, if it doesn't exist.
Based on:
https://github.com/python/cpython/blob/master/Lib/pathlib.py)
"""
if exist_ok:
# First try to bump modificat... | python | def touch(self, mode=0o666, exist_ok=True):
"""Create this file with the given access mode, if it doesn't exist.
Based on:
https://github.com/python/cpython/blob/master/Lib/pathlib.py)
"""
if exist_ok:
# First try to bump modificat... | [
"def",
"touch",
"(",
"self",
",",
"mode",
"=",
"0o666",
",",
"exist_ok",
"=",
"True",
")",
":",
"if",
"exist_ok",
":",
"# First try to bump modification time",
"# Implementation note: GNU touch uses the UTIME_NOW option of",
"# the utimensat() / futimens() functions.",
"try",... | Create this file with the given access mode, if it doesn't exist.
Based on:
https://github.com/python/cpython/blob/master/Lib/pathlib.py) | [
"Create",
"this",
"file",
"with",
"the",
"given",
"access",
"mode",
"if",
"it",
"doesn",
"t",
"exist",
".",
"Based",
"on",
":",
"https",
":",
"//",
"github",
".",
"com",
"/",
"python",
"/",
"cpython",
"/",
"blob",
"/",
"master",
"/",
"Lib",
"/",
"p... | train | https://github.com/datakortet/dkfileutils/blob/924098d6e2edf88ad9b3ffdec9c74530f80a7d77/dkfileutils/path.py#L99-L121 |
datakortet/dkfileutils | dkfileutils/path.py | Path.glob | def glob(self, pat):
"""`pat` can be an extended glob pattern, e.g. `'**/*.less'`
This code handles negations similarly to node.js' minimatch, i.e.
a leading `!` will negate the entire pattern.
"""
r = ""
negate = int(pat.startswith('!'))
i = negate
... | python | def glob(self, pat):
"""`pat` can be an extended glob pattern, e.g. `'**/*.less'`
This code handles negations similarly to node.js' minimatch, i.e.
a leading `!` will negate the entire pattern.
"""
r = ""
negate = int(pat.startswith('!'))
i = negate
... | [
"def",
"glob",
"(",
"self",
",",
"pat",
")",
":",
"r",
"=",
"\"\"",
"negate",
"=",
"int",
"(",
"pat",
".",
"startswith",
"(",
"'!'",
")",
")",
"i",
"=",
"negate",
"while",
"i",
"<",
"len",
"(",
"pat",
")",
":",
"if",
"pat",
"[",
"i",
":",
"... | `pat` can be an extended glob pattern, e.g. `'**/*.less'`
This code handles negations similarly to node.js' minimatch, i.e.
a leading `!` will negate the entire pattern. | [
"pat",
"can",
"be",
"an",
"extended",
"glob",
"pattern",
"e",
".",
"g",
".",
"**",
"/",
"*",
".",
"less",
"This",
"code",
"handles",
"negations",
"similarly",
"to",
"node",
".",
"js",
"minimatch",
"i",
".",
"e",
".",
"a",
"leading",
"!",
"will",
"n... | train | https://github.com/datakortet/dkfileutils/blob/924098d6e2edf88ad9b3ffdec9c74530f80a7d77/dkfileutils/path.py#L123-L158 |
datakortet/dkfileutils | dkfileutils/path.py | Path.list | def list(self, filterfn=lambda x: True):
"""Return all direct descendands of directory `self` for which
`filterfn` returns True.
"""
return [self / p for p in self.listdir() if filterfn(self / p)] | python | def list(self, filterfn=lambda x: True):
"""Return all direct descendands of directory `self` for which
`filterfn` returns True.
"""
return [self / p for p in self.listdir() if filterfn(self / p)] | [
"def",
"list",
"(",
"self",
",",
"filterfn",
"=",
"lambda",
"x",
":",
"True",
")",
":",
"return",
"[",
"self",
"/",
"p",
"for",
"p",
"in",
"self",
".",
"listdir",
"(",
")",
"if",
"filterfn",
"(",
"self",
"/",
"p",
")",
"]"
] | Return all direct descendands of directory `self` for which
`filterfn` returns True. | [
"Return",
"all",
"direct",
"descendands",
"of",
"directory",
"self",
"for",
"which",
"filterfn",
"returns",
"True",
"."
] | train | https://github.com/datakortet/dkfileutils/blob/924098d6e2edf88ad9b3ffdec9c74530f80a7d77/dkfileutils/path.py#L329-L333 |
datakortet/dkfileutils | dkfileutils/path.py | Path.rm | def rm(self, fname=None):
"""Remove a file, don't raise exception if file does not exist.
"""
if fname is not None:
return (self / fname).rm()
try:
self.remove()
except OSError:
pass | python | def rm(self, fname=None):
"""Remove a file, don't raise exception if file does not exist.
"""
if fname is not None:
return (self / fname).rm()
try:
self.remove()
except OSError:
pass | [
"def",
"rm",
"(",
"self",
",",
"fname",
"=",
"None",
")",
":",
"if",
"fname",
"is",
"not",
"None",
":",
"return",
"(",
"self",
"/",
"fname",
")",
".",
"rm",
"(",
")",
"try",
":",
"self",
".",
"remove",
"(",
")",
"except",
"OSError",
":",
"pass"... | Remove a file, don't raise exception if file does not exist. | [
"Remove",
"a",
"file",
"don",
"t",
"raise",
"exception",
"if",
"file",
"does",
"not",
"exist",
"."
] | train | https://github.com/datakortet/dkfileutils/blob/924098d6e2edf88ad9b3ffdec9c74530f80a7d77/dkfileutils/path.py#L372-L380 |
oczkers/pyllegro | pyllegro/core.py | chunked | def chunked(l, n):
"""Chunk one big list into few small lists."""
return [l[i:i + n] for i in range(0, len(l), n)] | python | def chunked(l, n):
"""Chunk one big list into few small lists."""
return [l[i:i + n] for i in range(0, len(l), n)] | [
"def",
"chunked",
"(",
"l",
",",
"n",
")",
":",
"return",
"[",
"l",
"[",
"i",
":",
"i",
"+",
"n",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"l",
")",
",",
"n",
")",
"]"
] | Chunk one big list into few small lists. | [
"Chunk",
"one",
"big",
"list",
"into",
"few",
"small",
"lists",
"."
] | train | https://github.com/oczkers/pyllegro/blob/c6d7090560cb9e579f7f769a9eec131a3db2c258/pyllegro/core.py#L40-L42 |
oczkers/pyllegro | pyllegro/core.py | Allegro.login | def login(self, username, passwd_hash, webapi_key, country_code=1):
"""Log in (sets self.token). Returns token (session_handle)."""
self.client = Client(self.webapi_url)
self.ArrayOfLong = self.client.get_type('ns0:ArrayOfLong') # this should be done by zeep...
ver_key = self.client.ser... | python | def login(self, username, passwd_hash, webapi_key, country_code=1):
"""Log in (sets self.token). Returns token (session_handle)."""
self.client = Client(self.webapi_url)
self.ArrayOfLong = self.client.get_type('ns0:ArrayOfLong') # this should be done by zeep...
ver_key = self.client.ser... | [
"def",
"login",
"(",
"self",
",",
"username",
",",
"passwd_hash",
",",
"webapi_key",
",",
"country_code",
"=",
"1",
")",
":",
"self",
".",
"client",
"=",
"Client",
"(",
"self",
".",
"webapi_url",
")",
"self",
".",
"ArrayOfLong",
"=",
"self",
".",
"clie... | Log in (sets self.token). Returns token (session_handle). | [
"Log",
"in",
"(",
"sets",
"self",
".",
"token",
")",
".",
"Returns",
"token",
"(",
"session_handle",
")",
"."
] | train | https://github.com/oczkers/pyllegro/blob/c6d7090560cb9e579f7f769a9eec131a3db2c258/pyllegro/core.py#L130-L137 |
oczkers/pyllegro | pyllegro/core.py | Allegro.getBids | def getBids(self, auction_id):
"""Retrieve all bids in given auction."""
bids = {}
rc = self.__ask__('doGetBidItem2', itemId=auction_id)
if rc:
for i in rc:
i = i['bidsArray']
bids[long(i['item'][1])] = {
'price': Decimal(i[... | python | def getBids(self, auction_id):
"""Retrieve all bids in given auction."""
bids = {}
rc = self.__ask__('doGetBidItem2', itemId=auction_id)
if rc:
for i in rc:
i = i['bidsArray']
bids[long(i['item'][1])] = {
'price': Decimal(i[... | [
"def",
"getBids",
"(",
"self",
",",
"auction_id",
")",
":",
"bids",
"=",
"{",
"}",
"rc",
"=",
"self",
".",
"__ask__",
"(",
"'doGetBidItem2'",
",",
"itemId",
"=",
"auction_id",
")",
"if",
"rc",
":",
"for",
"i",
"in",
"rc",
":",
"i",
"=",
"i",
"[",... | Retrieve all bids in given auction. | [
"Retrieve",
"all",
"bids",
"in",
"given",
"auction",
"."
] | train | https://github.com/oczkers/pyllegro/blob/c6d7090560cb9e579f7f769a9eec131a3db2c258/pyllegro/core.py#L150-L162 |
oczkers/pyllegro | pyllegro/core.py | Allegro.getBuyerInfo | def getBuyerInfo(self, auction_id, buyer_id):
"""Return buyer info."""
# TODO: add price from getBids
rc = self.__ask__('doGetPostBuyData', itemsArray=self.ArrayOfLong([auction_id]), buyerFilterArray=self.ArrayOfLong([buyer_id]))
rc = rc[0]['usersPostBuyData']['item'][0]['userData']
... | python | def getBuyerInfo(self, auction_id, buyer_id):
"""Return buyer info."""
# TODO: add price from getBids
rc = self.__ask__('doGetPostBuyData', itemsArray=self.ArrayOfLong([auction_id]), buyerFilterArray=self.ArrayOfLong([buyer_id]))
rc = rc[0]['usersPostBuyData']['item'][0]['userData']
... | [
"def",
"getBuyerInfo",
"(",
"self",
",",
"auction_id",
",",
"buyer_id",
")",
":",
"# TODO: add price from getBids",
"rc",
"=",
"self",
".",
"__ask__",
"(",
"'doGetPostBuyData'",
",",
"itemsArray",
"=",
"self",
".",
"ArrayOfLong",
"(",
"[",
"auction_id",
"]",
"... | Return buyer info. | [
"Return",
"buyer",
"info",
"."
] | train | https://github.com/oczkers/pyllegro/blob/c6d7090560cb9e579f7f769a9eec131a3db2c258/pyllegro/core.py#L164-L179 |
oczkers/pyllegro | pyllegro/core.py | Allegro.getOrders | def getOrders(self, auction_ids):
"""Return orders details."""
orders = {}
# chunk list (only 25 auction_ids per request)
for chunk in chunked(auction_ids, 25):
# auctions = [{'item': auction_id} for auction_id in chunk] # TODO?: is it needed?
auctions = self.Arr... | python | def getOrders(self, auction_ids):
"""Return orders details."""
orders = {}
# chunk list (only 25 auction_ids per request)
for chunk in chunked(auction_ids, 25):
# auctions = [{'item': auction_id} for auction_id in chunk] # TODO?: is it needed?
auctions = self.Arr... | [
"def",
"getOrders",
"(",
"self",
",",
"auction_ids",
")",
":",
"orders",
"=",
"{",
"}",
"# chunk list (only 25 auction_ids per request)",
"for",
"chunk",
"in",
"chunked",
"(",
"auction_ids",
",",
"25",
")",
":",
"# auctions = [{'item': auction_id} for auction_id in chun... | Return orders details. | [
"Return",
"orders",
"details",
"."
] | train | https://github.com/oczkers/pyllegro/blob/c6d7090560cb9e579f7f769a9eec131a3db2c258/pyllegro/core.py#L181-L217 |
oczkers/pyllegro | pyllegro/core.py | Allegro.getTotalPaid | def getTotalPaid(self, auction_id, buyer_id):
"""Return total paid from buyer on single auction."""
# TODO: it has to be better way to check payments.
date_end = long(time.time())
date_start = date_end - 60 * 60 * 24 * 90
rc = self.__ask__('doGetMyIncomingPayments',
... | python | def getTotalPaid(self, auction_id, buyer_id):
"""Return total paid from buyer on single auction."""
# TODO: it has to be better way to check payments.
date_end = long(time.time())
date_start = date_end - 60 * 60 * 24 * 90
rc = self.__ask__('doGetMyIncomingPayments',
... | [
"def",
"getTotalPaid",
"(",
"self",
",",
"auction_id",
",",
"buyer_id",
")",
":",
"# TODO: it has to be better way to check payments.",
"date_end",
"=",
"long",
"(",
"time",
".",
"time",
"(",
")",
")",
"date_start",
"=",
"date_end",
"-",
"60",
"*",
"60",
"*",
... | Return total paid from buyer on single auction. | [
"Return",
"total",
"paid",
"from",
"buyer",
"on",
"single",
"auction",
"."
] | train | https://github.com/oczkers/pyllegro/blob/c6d7090560cb9e579f7f769a9eec131a3db2c258/pyllegro/core.py#L219-L241 |
oczkers/pyllegro | pyllegro/core.py | Allegro.getJournalDeals | def getJournalDeals(self, start=None):
"""Return all journal events from start."""
# 1 - utworzenie aktu zakupowego (deala), 2 - utworzenie formularza pozakupowego (karta platnosci), 3 - anulowanie formularza pozakupowego (karta platnosci), 4 - zakończenie (opłacenie) transakcji przez PzA
if sta... | python | def getJournalDeals(self, start=None):
"""Return all journal events from start."""
# 1 - utworzenie aktu zakupowego (deala), 2 - utworzenie formularza pozakupowego (karta platnosci), 3 - anulowanie formularza pozakupowego (karta platnosci), 4 - zakończenie (opłacenie) transakcji przez PzA
if sta... | [
"def",
"getJournalDeals",
"(",
"self",
",",
"start",
"=",
"None",
")",
":",
"# 1 - utworzenie aktu zakupowego (deala), 2 - utworzenie formularza pozakupowego (karta platnosci), 3 - anulowanie formularza pozakupowego (karta platnosci), 4 - zakończenie (opłacenie) transakcji przez PzA",
"if",
... | Return all journal events from start. | [
"Return",
"all",
"journal",
"events",
"from",
"start",
"."
] | train | https://github.com/oczkers/pyllegro/blob/c6d7090560cb9e579f7f769a9eec131a3db2c258/pyllegro/core.py#L254-L275 |
oczkers/pyllegro | pyllegro/core.py | Allegro.getWaitingFeedbacks | def getWaitingFeedbacks(self):
"""Return all waiting feedbacks from buyers."""
# TODO: return sorted dictionary (negative/positive/neutral)
feedbacks = []
offset = 0
amount = self.__ask__('doGetWaitingFeedbacksCount')
while amount > 0:
rc = self.__ask__('doGet... | python | def getWaitingFeedbacks(self):
"""Return all waiting feedbacks from buyers."""
# TODO: return sorted dictionary (negative/positive/neutral)
feedbacks = []
offset = 0
amount = self.__ask__('doGetWaitingFeedbacksCount')
while amount > 0:
rc = self.__ask__('doGet... | [
"def",
"getWaitingFeedbacks",
"(",
"self",
")",
":",
"# TODO: return sorted dictionary (negative/positive/neutral)",
"feedbacks",
"=",
"[",
"]",
"offset",
"=",
"0",
"amount",
"=",
"self",
".",
"__ask__",
"(",
"'doGetWaitingFeedbacksCount'",
")",
"while",
"amount",
">"... | Return all waiting feedbacks from buyers. | [
"Return",
"all",
"waiting",
"feedbacks",
"from",
"buyers",
"."
] | train | https://github.com/oczkers/pyllegro/blob/c6d7090560cb9e579f7f769a9eec131a3db2c258/pyllegro/core.py#L278-L290 |
oczkers/pyllegro | pyllegro/core.py | Allegro.doFeedback | def doFeedback(self, item_id, use_comment_template, buyer_id, comment, comment_type, op):
"""http://allegro.pl/webapi/documentation.php/show/id,42"""
return self.__ask__('doFeedback',
feItemId=item_id,
feUseCommentTemplate=use_comment_template,
... | python | def doFeedback(self, item_id, use_comment_template, buyer_id, comment, comment_type, op):
"""http://allegro.pl/webapi/documentation.php/show/id,42"""
return self.__ask__('doFeedback',
feItemId=item_id,
feUseCommentTemplate=use_comment_template,
... | [
"def",
"doFeedback",
"(",
"self",
",",
"item_id",
",",
"use_comment_template",
",",
"buyer_id",
",",
"comment",
",",
"comment_type",
",",
"op",
")",
":",
"return",
"self",
".",
"__ask__",
"(",
"'doFeedback'",
",",
"feItemId",
"=",
"item_id",
",",
"feUseComme... | http://allegro.pl/webapi/documentation.php/show/id,42 | [
"http",
":",
"//",
"allegro",
".",
"pl",
"/",
"webapi",
"/",
"documentation",
".",
"php",
"/",
"show",
"/",
"id",
"42"
] | train | https://github.com/oczkers/pyllegro/blob/c6d7090560cb9e579f7f769a9eec131a3db2c258/pyllegro/core.py#L292-L300 |
oczkers/pyllegro | pyllegro/core.py | Allegro.doSendRefundForms | def doSendRefundForms(self, item_id, buyer_id, reason, quantity_sold):
"""http://allegro.pl/webapi/documentation.php/show/id,201"""
# TODO: deprecated
return self.__ask__('doSendRefundForms',
sendRefundFormsDataArr={
'item': {
... | python | def doSendRefundForms(self, item_id, buyer_id, reason, quantity_sold):
"""http://allegro.pl/webapi/documentation.php/show/id,201"""
# TODO: deprecated
return self.__ask__('doSendRefundForms',
sendRefundFormsDataArr={
'item': {
... | [
"def",
"doSendRefundForms",
"(",
"self",
",",
"item_id",
",",
"buyer_id",
",",
"reason",
",",
"quantity_sold",
")",
":",
"# TODO: deprecated",
"return",
"self",
".",
"__ask__",
"(",
"'doSendRefundForms'",
",",
"sendRefundFormsDataArr",
"=",
"{",
"'item'",
":",
"... | http://allegro.pl/webapi/documentation.php/show/id,201 | [
"http",
":",
"//",
"allegro",
".",
"pl",
"/",
"webapi",
"/",
"documentation",
".",
"php",
"/",
"show",
"/",
"id",
"201"
] | train | https://github.com/oczkers/pyllegro/blob/c6d7090560cb9e579f7f769a9eec131a3db2c258/pyllegro/core.py#L303-L312 |
lukaszb/monolith | monolith/utils/imports.py | import_class | def import_class(class_path):
"""
Returns class from the given path.
For example, in order to get class located at
``mypackage.subpackage.MyClass``:
try:
hgrepo = import_class('mypackage.subpackage.MyClass')
except ImportError:
# hadle error
"""
splitted... | python | def import_class(class_path):
"""
Returns class from the given path.
For example, in order to get class located at
``mypackage.subpackage.MyClass``:
try:
hgrepo = import_class('mypackage.subpackage.MyClass')
except ImportError:
# hadle error
"""
splitted... | [
"def",
"import_class",
"(",
"class_path",
")",
":",
"splitted",
"=",
"class_path",
".",
"split",
"(",
"'.'",
")",
"mod_path",
"=",
"'.'",
".",
"join",
"(",
"splitted",
"[",
":",
"-",
"1",
"]",
")",
"class_name",
"=",
"splitted",
"[",
"-",
"1",
"]",
... | Returns class from the given path.
For example, in order to get class located at
``mypackage.subpackage.MyClass``:
try:
hgrepo = import_class('mypackage.subpackage.MyClass')
except ImportError:
# hadle error | [
"Returns",
"class",
"from",
"the",
"given",
"path",
"."
] | train | https://github.com/lukaszb/monolith/blob/cd8ab0483829ed4be6439c4f787ea59d48ad35b8/monolith/utils/imports.py#L3-L24 |
jeffrimko/Auxly | lib/auxly/shell.py | silent | def silent(cmd, **kwargs):
"""Calls the given shell command. Output will not be displayed. Returns the
status code.
**Examples**:
::
auxly.shell.silent("ls")
"""
return call(cmd, shell=True, stdout=NULL, stderr=NULL, **kwargs) | python | def silent(cmd, **kwargs):
"""Calls the given shell command. Output will not be displayed. Returns the
status code.
**Examples**:
::
auxly.shell.silent("ls")
"""
return call(cmd, shell=True, stdout=NULL, stderr=NULL, **kwargs) | [
"def",
"silent",
"(",
"cmd",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"call",
"(",
"cmd",
",",
"shell",
"=",
"True",
",",
"stdout",
"=",
"NULL",
",",
"stderr",
"=",
"NULL",
",",
"*",
"*",
"kwargs",
")"
] | Calls the given shell command. Output will not be displayed. Returns the
status code.
**Examples**:
::
auxly.shell.silent("ls") | [
"Calls",
"the",
"given",
"shell",
"command",
".",
"Output",
"will",
"not",
"be",
"displayed",
".",
"Returns",
"the",
"status",
"code",
"."
] | train | https://github.com/jeffrimko/Auxly/blob/5aae876bcb6ca117c81d904f9455764cdc78cd48/lib/auxly/shell.py#L32-L40 |
jeffrimko/Auxly | lib/auxly/shell.py | has | def has(cmd):
"""Returns true if the give shell command is available.
**Examples**:
::
auxly.shell.has("ls") # True
"""
helps = ["--help", "-h", "--version"]
if "nt" == os.name:
helps.insert(0, "/?")
fakecmd = "fakecmd"
cmderr = strerr(fakecmd).replace(fakecmd, cmd)
... | python | def has(cmd):
"""Returns true if the give shell command is available.
**Examples**:
::
auxly.shell.has("ls") # True
"""
helps = ["--help", "-h", "--version"]
if "nt" == os.name:
helps.insert(0, "/?")
fakecmd = "fakecmd"
cmderr = strerr(fakecmd).replace(fakecmd, cmd)
... | [
"def",
"has",
"(",
"cmd",
")",
":",
"helps",
"=",
"[",
"\"--help\"",
",",
"\"-h\"",
",",
"\"--version\"",
"]",
"if",
"\"nt\"",
"==",
"os",
".",
"name",
":",
"helps",
".",
"insert",
"(",
"0",
",",
"\"/?\"",
")",
"fakecmd",
"=",
"\"fakecmd\"",
"cmderr"... | Returns true if the give shell command is available.
**Examples**:
::
auxly.shell.has("ls") # True | [
"Returns",
"true",
"if",
"the",
"give",
"shell",
"command",
"is",
"available",
"."
] | train | https://github.com/jeffrimko/Auxly/blob/5aae876bcb6ca117c81d904f9455764cdc78cd48/lib/auxly/shell.py#L42-L62 |
jeffrimko/Auxly | lib/auxly/shell.py | iterstd | def iterstd(cmd, std="out", **kwargs):
"""Iterates through the lines of a stderr/stdout stream for the given shell
command."""
def _readline():
while True:
line = getattr(proc, "std"+std).readline()
if line != b"":
yield line.rstrip().decode("UTF-8", "replace"... | python | def iterstd(cmd, std="out", **kwargs):
"""Iterates through the lines of a stderr/stdout stream for the given shell
command."""
def _readline():
while True:
line = getattr(proc, "std"+std).readline()
if line != b"":
yield line.rstrip().decode("UTF-8", "replace"... | [
"def",
"iterstd",
"(",
"cmd",
",",
"std",
"=",
"\"out\"",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"_readline",
"(",
")",
":",
"while",
"True",
":",
"line",
"=",
"getattr",
"(",
"proc",
",",
"\"std\"",
"+",
"std",
")",
".",
"readline",
"(",
")",... | Iterates through the lines of a stderr/stdout stream for the given shell
command. | [
"Iterates",
"through",
"the",
"lines",
"of",
"a",
"stderr",
"/",
"stdout",
"stream",
"for",
"the",
"given",
"shell",
"command",
"."
] | train | https://github.com/jeffrimko/Auxly/blob/5aae876bcb6ca117c81d904f9455764cdc78cd48/lib/auxly/shell.py#L64-L83 |
vilmibm/done | parsedatetime/parsedatetime.py | _parse_date_rfc822 | def _parse_date_rfc822(dateString):
'''Parse an RFC822, RFC1123, RFC2822, or asctime-style date'''
data = dateString.split()
if data[0][-1] in (',', '.') or data[0].lower() in rfc822._daynames:
del data[0]
if len(data) == 4:
s = data[3]
i = s.find('+')
if i > 0:
... | python | def _parse_date_rfc822(dateString):
'''Parse an RFC822, RFC1123, RFC2822, or asctime-style date'''
data = dateString.split()
if data[0][-1] in (',', '.') or data[0].lower() in rfc822._daynames:
del data[0]
if len(data) == 4:
s = data[3]
i = s.find('+')
if i > 0:
... | [
"def",
"_parse_date_rfc822",
"(",
"dateString",
")",
":",
"data",
"=",
"dateString",
".",
"split",
"(",
")",
"if",
"data",
"[",
"0",
"]",
"[",
"-",
"1",
"]",
"in",
"(",
"','",
",",
"'.'",
")",
"or",
"data",
"[",
"0",
"]",
".",
"lower",
"(",
")"... | Parse an RFC822, RFC1123, RFC2822, or asctime-style date | [
"Parse",
"an",
"RFC822",
"RFC1123",
"RFC2822",
"or",
"asctime",
"-",
"style",
"date"
] | train | https://github.com/vilmibm/done/blob/7e5b60d2900ceddefa49de352a19b794199b51a8/parsedatetime/parsedatetime.py#L154-L169 |
vilmibm/done | parsedatetime/parsedatetime.py | Calendar._buildTime | def _buildTime(self, source, quantity, modifier, units):
"""
Take C{quantity}, C{modifier} and C{unit} strings and convert them into values.
After converting, calcuate the time and return the adjusted sourceTime.
@type source: time
@param source: time to use as the ba... | python | def _buildTime(self, source, quantity, modifier, units):
"""
Take C{quantity}, C{modifier} and C{unit} strings and convert them into values.
After converting, calcuate the time and return the adjusted sourceTime.
@type source: time
@param source: time to use as the ba... | [
"def",
"_buildTime",
"(",
"self",
",",
"source",
",",
"quantity",
",",
"modifier",
",",
"units",
")",
":",
"if",
"_debug",
":",
"print",
"'_buildTime: [%s][%s][%s]'",
"%",
"(",
"quantity",
",",
"modifier",
",",
"units",
")",
"if",
"source",
"is",
"None",
... | Take C{quantity}, C{modifier} and C{unit} strings and convert them into values.
After converting, calcuate the time and return the adjusted sourceTime.
@type source: time
@param source: time to use as the base (or source)
@type quantity: string
@param quantity: quant... | [
"Take",
"C",
"{",
"quantity",
"}",
"C",
"{",
"modifier",
"}",
"and",
"C",
"{",
"unit",
"}",
"strings",
"and",
"convert",
"them",
"into",
"values",
".",
"After",
"converting",
"calcuate",
"the",
"time",
"and",
"return",
"the",
"adjusted",
"sourceTime",
".... | train | https://github.com/vilmibm/done/blob/7e5b60d2900ceddefa49de352a19b794199b51a8/parsedatetime/parsedatetime.py#L237-L309 |
vilmibm/done | parsedatetime/parsedatetime.py | Calendar.parseDate | def parseDate(self, dateString):
"""
Parse short-form date strings::
'05/28/2006' or '04.21'
@type dateString: string
@param dateString: text to convert to a C{datetime}
@rtype: struct_time
@return: calculated C{struct_time} value of dateString
... | python | def parseDate(self, dateString):
"""
Parse short-form date strings::
'05/28/2006' or '04.21'
@type dateString: string
@param dateString: text to convert to a C{datetime}
@rtype: struct_time
@return: calculated C{struct_time} value of dateString
... | [
"def",
"parseDate",
"(",
"self",
",",
"dateString",
")",
":",
"yr",
",",
"mth",
",",
"dy",
",",
"hr",
",",
"mn",
",",
"sec",
",",
"wd",
",",
"yd",
",",
"isdst",
"=",
"time",
".",
"localtime",
"(",
")",
"# values pulled from regex's will be stored here an... | Parse short-form date strings::
'05/28/2006' or '04.21'
@type dateString: string
@param dateString: text to convert to a C{datetime}
@rtype: struct_time
@return: calculated C{struct_time} value of dateString | [
"Parse",
"short",
"-",
"form",
"date",
"strings",
"::",
"05",
"/",
"28",
"/",
"2006",
"or",
"04",
".",
"21"
] | train | https://github.com/vilmibm/done/blob/7e5b60d2900ceddefa49de352a19b794199b51a8/parsedatetime/parsedatetime.py#L312-L386 |
vilmibm/done | parsedatetime/parsedatetime.py | Calendar.parseDateText | def parseDateText(self, dateString):
"""
Parse long-form date strings::
'May 31st, 2006'
'Jan 1st'
'July 2006'
@type dateString: string
@param dateString: text to convert to a datetime
@rtype: struct_time
@return: calcu... | python | def parseDateText(self, dateString):
"""
Parse long-form date strings::
'May 31st, 2006'
'Jan 1st'
'July 2006'
@type dateString: string
@param dateString: text to convert to a datetime
@rtype: struct_time
@return: calcu... | [
"def",
"parseDateText",
"(",
"self",
",",
"dateString",
")",
":",
"yr",
",",
"mth",
",",
"dy",
",",
"hr",
",",
"mn",
",",
"sec",
",",
"wd",
",",
"yd",
",",
"isdst",
"=",
"time",
".",
"localtime",
"(",
")",
"currentMth",
"=",
"mth",
"currentDy",
"... | Parse long-form date strings::
'May 31st, 2006'
'Jan 1st'
'July 2006'
@type dateString: string
@param dateString: text to convert to a datetime
@rtype: struct_time
@return: calculated C{struct_time} value of dateString | [
"Parse",
"long",
"-",
"form",
"date",
"strings",
"::",
"May",
"31st",
"2006",
"Jan",
"1st",
"July",
"2006"
] | train | https://github.com/vilmibm/done/blob/7e5b60d2900ceddefa49de352a19b794199b51a8/parsedatetime/parsedatetime.py#L389-L440 |
vilmibm/done | parsedatetime/parsedatetime.py | Calendar.evalRanges | def evalRanges(self, datetimeString, sourceTime=None):
"""
Evaluate the C{datetimeString} text and determine if
it represents a date or time range.
@type datetimeString: string
@param datetimeString: datetime text to evaluate
@type sourceTime: struct_time
... | python | def evalRanges(self, datetimeString, sourceTime=None):
"""
Evaluate the C{datetimeString} text and determine if
it represents a date or time range.
@type datetimeString: string
@param datetimeString: datetime text to evaluate
@type sourceTime: struct_time
... | [
"def",
"evalRanges",
"(",
"self",
",",
"datetimeString",
",",
"sourceTime",
"=",
"None",
")",
":",
"startTime",
"=",
"''",
"endTime",
"=",
"''",
"startDate",
"=",
"''",
"endDate",
"=",
"''",
"rangeFlag",
"=",
"0",
"s",
"=",
"datetimeString",
".",
"strip"... | Evaluate the C{datetimeString} text and determine if
it represents a date or time range.
@type datetimeString: string
@param datetimeString: datetime text to evaluate
@type sourceTime: struct_time
@param sourceTime: C{struct_time} value to use as the base
... | [
"Evaluate",
"the",
"C",
"{",
"datetimeString",
"}",
"text",
"and",
"determine",
"if",
"it",
"represents",
"a",
"date",
"or",
"time",
"range",
"."
] | train | https://github.com/vilmibm/done/blob/7e5b60d2900ceddefa49de352a19b794199b51a8/parsedatetime/parsedatetime.py#L443-L606 |
vilmibm/done | parsedatetime/parsedatetime.py | Calendar._CalculateDOWDelta | def _CalculateDOWDelta(self, wd, wkdy, offset, style, currentDayStyle):
"""
Based on the C{style} and C{currentDayStyle} determine what
day-of-week value is to be returned.
@type wd: integer
@param wd: day-of-week value for the current day
... | python | def _CalculateDOWDelta(self, wd, wkdy, offset, style, currentDayStyle):
"""
Based on the C{style} and C{currentDayStyle} determine what
day-of-week value is to be returned.
@type wd: integer
@param wd: day-of-week value for the current day
... | [
"def",
"_CalculateDOWDelta",
"(",
"self",
",",
"wd",
",",
"wkdy",
",",
"offset",
",",
"style",
",",
"currentDayStyle",
")",
":",
"if",
"offset",
"==",
"1",
":",
"# modifier is indicating future week eg: \"next\".\r",
"# DOW is calculated as DOW of next week\r",
"diff",
... | Based on the C{style} and C{currentDayStyle} determine what
day-of-week value is to be returned.
@type wd: integer
@param wd: day-of-week value for the current day
@type wkdy: integer
@param wkdy: day-of-week value for the ... | [
"Based",
"on",
"the",
"C",
"{",
"style",
"}",
"and",
"C",
"{",
"currentDayStyle",
"}",
"determine",
"what",
"day",
"-",
"of",
"-",
"week",
"value",
"is",
"to",
"be",
"returned",
"."
] | train | https://github.com/vilmibm/done/blob/7e5b60d2900ceddefa49de352a19b794199b51a8/parsedatetime/parsedatetime.py#L609-L678 |
vilmibm/done | parsedatetime/parsedatetime.py | Calendar._evalModifier | def _evalModifier(self, modifier, chunk1, chunk2, sourceTime):
"""
Evaluate the C{modifier} string and following text (passed in
as C{chunk1} and C{chunk2}) and if they match any known modifiers
calculate the delta and apply it to C{sourceTime}.
@type modifier: string
... | python | def _evalModifier(self, modifier, chunk1, chunk2, sourceTime):
"""
Evaluate the C{modifier} string and following text (passed in
as C{chunk1} and C{chunk2}) and if they match any known modifiers
calculate the delta and apply it to C{sourceTime}.
@type modifier: string
... | [
"def",
"_evalModifier",
"(",
"self",
",",
"modifier",
",",
"chunk1",
",",
"chunk2",
",",
"sourceTime",
")",
":",
"offset",
"=",
"self",
".",
"ptc",
".",
"Modifiers",
"[",
"modifier",
"]",
"if",
"sourceTime",
"is",
"not",
"None",
":",
"(",
"yr",
",",
... | Evaluate the C{modifier} string and following text (passed in
as C{chunk1} and C{chunk2}) and if they match any known modifiers
calculate the delta and apply it to C{sourceTime}.
@type modifier: string
@param modifier: modifier text to apply to sourceTime
@type chunk... | [
"Evaluate",
"the",
"C",
"{",
"modifier",
"}",
"string",
"and",
"following",
"text",
"(",
"passed",
"in",
"as",
"C",
"{",
"chunk1",
"}",
"and",
"C",
"{",
"chunk2",
"}",
")",
"and",
"if",
"they",
"match",
"any",
"known",
"modifiers",
"calculate",
"the",
... | train | https://github.com/vilmibm/done/blob/7e5b60d2900ceddefa49de352a19b794199b51a8/parsedatetime/parsedatetime.py#L681-L870 |
vilmibm/done | parsedatetime/parsedatetime.py | Calendar._evalModifier2 | def _evalModifier2(self, modifier, chunk1 , chunk2, sourceTime):
"""
Evaluate the C{modifier} string and following text (passed in
as C{chunk1} and C{chunk2}) and if they match any known modifiers
calculate the delta and apply it to C{sourceTime}.
@type modifier: string... | python | def _evalModifier2(self, modifier, chunk1 , chunk2, sourceTime):
"""
Evaluate the C{modifier} string and following text (passed in
as C{chunk1} and C{chunk2}) and if they match any known modifiers
calculate the delta and apply it to C{sourceTime}.
@type modifier: string... | [
"def",
"_evalModifier2",
"(",
"self",
",",
"modifier",
",",
"chunk1",
",",
"chunk2",
",",
"sourceTime",
")",
":",
"offset",
"=",
"self",
".",
"ptc",
".",
"Modifiers",
"[",
"modifier",
"]",
"digit",
"=",
"r'\\d+'",
"self",
".",
"modifier2Flag",
"=",
"Fals... | Evaluate the C{modifier} string and following text (passed in
as C{chunk1} and C{chunk2}) and if they match any known modifiers
calculate the delta and apply it to C{sourceTime}.
@type modifier: string
@param modifier: modifier text to apply to C{sourceTime}
@type ch... | [
"Evaluate",
"the",
"C",
"{",
"modifier",
"}",
"string",
"and",
"following",
"text",
"(",
"passed",
"in",
"as",
"C",
"{",
"chunk1",
"}",
"and",
"C",
"{",
"chunk2",
"}",
")",
"and",
"if",
"they",
"match",
"any",
"known",
"modifiers",
"calculate",
"the",
... | train | https://github.com/vilmibm/done/blob/7e5b60d2900ceddefa49de352a19b794199b51a8/parsedatetime/parsedatetime.py#L872-L943 |
vilmibm/done | parsedatetime/parsedatetime.py | Calendar._evalString | def _evalString(self, datetimeString, sourceTime=None):
"""
Calculate the datetime based on flags set by the L{parse()} routine
Examples handled::
RFC822, W3CDTF formatted dates
HH:MM[:SS][ am/pm]
MM/DD/YYYY
DD MMMM YYYY
@type ... | python | def _evalString(self, datetimeString, sourceTime=None):
"""
Calculate the datetime based on flags set by the L{parse()} routine
Examples handled::
RFC822, W3CDTF formatted dates
HH:MM[:SS][ am/pm]
MM/DD/YYYY
DD MMMM YYYY
@type ... | [
"def",
"_evalString",
"(",
"self",
",",
"datetimeString",
",",
"sourceTime",
"=",
"None",
")",
":",
"s",
"=",
"datetimeString",
".",
"strip",
"(",
")",
"now",
"=",
"time",
".",
"localtime",
"(",
")",
"# Given string date is a RFC822 date\r",
"if",
"sourceTime"... | Calculate the datetime based on flags set by the L{parse()} routine
Examples handled::
RFC822, W3CDTF formatted dates
HH:MM[:SS][ am/pm]
MM/DD/YYYY
DD MMMM YYYY
@type datetimeString: string
@param datetimeString: text to try and parse a... | [
"Calculate",
"the",
"datetime",
"based",
"on",
"flags",
"set",
"by",
"the",
"L",
"{",
"parse",
"()",
"}",
"routine",
"Examples",
"handled",
"::",
"RFC822",
"W3CDTF",
"formatted",
"dates",
"HH",
":",
"MM",
"[",
":",
"SS",
"]",
"[",
"am",
"/",
"pm",
"]... | train | https://github.com/vilmibm/done/blob/7e5b60d2900ceddefa49de352a19b794199b51a8/parsedatetime/parsedatetime.py#L946-L1158 |
vilmibm/done | parsedatetime/parsedatetime.py | Calendar.parse | def parse(self, datetimeString, sourceTime=None):
"""
Splits the given C{datetimeString} into tokens, finds the regex
patterns that match and then calculates a C{struct_time} value from
the chunks.
If C{sourceTime} is given then the C{struct_time} value will be
ca... | python | def parse(self, datetimeString, sourceTime=None):
"""
Splits the given C{datetimeString} into tokens, finds the regex
patterns that match and then calculates a C{struct_time} value from
the chunks.
If C{sourceTime} is given then the C{struct_time} value will be
ca... | [
"def",
"parse",
"(",
"self",
",",
"datetimeString",
",",
"sourceTime",
"=",
"None",
")",
":",
"if",
"sourceTime",
":",
"if",
"isinstance",
"(",
"sourceTime",
",",
"datetime",
".",
"datetime",
")",
":",
"if",
"_debug",
":",
"print",
"'coercing datetime to tim... | Splits the given C{datetimeString} into tokens, finds the regex
patterns that match and then calculates a C{struct_time} value from
the chunks.
If C{sourceTime} is given then the C{struct_time} value will be
calculated from that value, otherwise from the current date/time.
... | [
"Splits",
"the",
"given",
"C",
"{",
"datetimeString",
"}",
"into",
"tokens",
"finds",
"the",
"regex",
"patterns",
"that",
"match",
"and",
"then",
"calculates",
"a",
"C",
"{",
"struct_time",
"}",
"value",
"from",
"the",
"chunks",
".",
"If",
"C",
"{",
"sou... | train | https://github.com/vilmibm/done/blob/7e5b60d2900ceddefa49de352a19b794199b51a8/parsedatetime/parsedatetime.py#L1161-L1476 |
vilmibm/done | parsedatetime/parsedatetime.py | Calendar.inc | def inc(self, source, month=None, year=None):
"""
Takes the given C{source} date, or current date if none is
passed, and increments it according to the values passed in
by month and/or year.
This routine is needed because Python's C{timedelta()} function
does not ... | python | def inc(self, source, month=None, year=None):
"""
Takes the given C{source} date, or current date if none is
passed, and increments it according to the values passed in
by month and/or year.
This routine is needed because Python's C{timedelta()} function
does not ... | [
"def",
"inc",
"(",
"self",
",",
"source",
",",
"month",
"=",
"None",
",",
"year",
"=",
"None",
")",
":",
"yr",
"=",
"source",
".",
"year",
"mth",
"=",
"source",
".",
"month",
"dy",
"=",
"source",
".",
"day",
"if",
"year",
":",
"try",
":",
"yi",... | Takes the given C{source} date, or current date if none is
passed, and increments it according to the values passed in
by month and/or year.
This routine is needed because Python's C{timedelta()} function
does not allow for month or year increments.
@type source: struct... | [
"Takes",
"the",
"given",
"C",
"{",
"source",
"}",
"date",
"or",
"current",
"date",
"if",
"none",
"is",
"passed",
"and",
"increments",
"it",
"according",
"to",
"the",
"values",
"passed",
"in",
"by",
"month",
"and",
"/",
"or",
"year",
".",
"This",
"routi... | train | https://github.com/vilmibm/done/blob/7e5b60d2900ceddefa49de352a19b794199b51a8/parsedatetime/parsedatetime.py#L1479-L1540 |
mayfield/shellish | shellish/tools/csvpretty.py | csvpretty | def csvpretty(csvfile: csvfile=sys.stdin):
""" Pretty print a CSV file. """
shellish.tabulate(csv.reader(csvfile)) | python | def csvpretty(csvfile: csvfile=sys.stdin):
""" Pretty print a CSV file. """
shellish.tabulate(csv.reader(csvfile)) | [
"def",
"csvpretty",
"(",
"csvfile",
":",
"csvfile",
"=",
"sys",
".",
"stdin",
")",
":",
"shellish",
".",
"tabulate",
"(",
"csv",
".",
"reader",
"(",
"csvfile",
")",
")"
] | Pretty print a CSV file. | [
"Pretty",
"print",
"a",
"CSV",
"file",
"."
] | train | https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/tools/csvpretty.py#L10-L12 |
jpscaletti/moar | moar/storage.py | Storage.get_key | def get_key(self, path, geometry, filters, options):
"""Generates the thumbnail's key from it's arguments.
If the arguments doesn't change the key will not change
"""
seed = u' '.join([
str(path),
str(geometry),
str(filters),
str(options),
... | python | def get_key(self, path, geometry, filters, options):
"""Generates the thumbnail's key from it's arguments.
If the arguments doesn't change the key will not change
"""
seed = u' '.join([
str(path),
str(geometry),
str(filters),
str(options),
... | [
"def",
"get_key",
"(",
"self",
",",
"path",
",",
"geometry",
",",
"filters",
",",
"options",
")",
":",
"seed",
"=",
"u' '",
".",
"join",
"(",
"[",
"str",
"(",
"path",
")",
",",
"str",
"(",
"geometry",
")",
",",
"str",
"(",
"filters",
")",
",",
... | Generates the thumbnail's key from it's arguments.
If the arguments doesn't change the key will not change | [
"Generates",
"the",
"thumbnail",
"s",
"key",
"from",
"it",
"s",
"arguments",
".",
"If",
"the",
"arguments",
"doesn",
"t",
"change",
"the",
"key",
"will",
"not",
"change"
] | train | https://github.com/jpscaletti/moar/blob/22694e5671b6adaccc4c9c87db7bdd701d20e734/moar/storage.py#L33-L43 |
jpscaletti/moar | moar/storage.py | Storage.get_source | def get_source(self, path_or_url):
"""Returns the source image file descriptor.
path_or_url:
Path to the source image as an absolute path, a path relative
to `self.base_path` or a URL beginning with `http[s]`
"""
if path_or_url.startswith(('http://', 'https://')... | python | def get_source(self, path_or_url):
"""Returns the source image file descriptor.
path_or_url:
Path to the source image as an absolute path, a path relative
to `self.base_path` or a URL beginning with `http[s]`
"""
if path_or_url.startswith(('http://', 'https://')... | [
"def",
"get_source",
"(",
"self",
",",
"path_or_url",
")",
":",
"if",
"path_or_url",
".",
"startswith",
"(",
"(",
"'http://'",
",",
"'https://'",
")",
")",
":",
"try",
":",
"return",
"urlopen",
"(",
"path_or_url",
")",
"except",
"IOError",
":",
"return",
... | Returns the source image file descriptor.
path_or_url:
Path to the source image as an absolute path, a path relative
to `self.base_path` or a URL beginning with `http[s]` | [
"Returns",
"the",
"source",
"image",
"file",
"descriptor",
"."
] | train | https://github.com/jpscaletti/moar/blob/22694e5671b6adaccc4c9c87db7bdd701d20e734/moar/storage.py#L45-L65 |
jpscaletti/moar | moar/storage.py | Storage.get_thumb | def get_thumb(self, path, key, format):
"""Get the stored thumbnail if exists.
path:
path of the source image
key:
key of the thumbnail
format:
thumbnail's file extension
"""
thumbpath = self.get_thumbpath(path, key, format)
fu... | python | def get_thumb(self, path, key, format):
"""Get the stored thumbnail if exists.
path:
path of the source image
key:
key of the thumbnail
format:
thumbnail's file extension
"""
thumbpath = self.get_thumbpath(path, key, format)
fu... | [
"def",
"get_thumb",
"(",
"self",
",",
"path",
",",
"key",
",",
"format",
")",
":",
"thumbpath",
"=",
"self",
".",
"get_thumbpath",
"(",
"path",
",",
"key",
",",
"format",
")",
"fullpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"out_... | Get the stored thumbnail if exists.
path:
path of the source image
key:
key of the thumbnail
format:
thumbnail's file extension | [
"Get",
"the",
"stored",
"thumbnail",
"if",
"exists",
"."
] | train | https://github.com/jpscaletti/moar/blob/22694e5671b6adaccc4c9c87db7bdd701d20e734/moar/storage.py#L67-L82 |
jpscaletti/moar | moar/storage.py | Storage.get_thumbpath | def get_thumbpath(self, path, key, format):
"""Return the relative path of the thumbnail.
path:
path of the source image
key:
key of the thumbnail
format:
thumbnail file extension
"""
relpath = os.path.dirname(path)
thumbsdir =... | python | def get_thumbpath(self, path, key, format):
"""Return the relative path of the thumbnail.
path:
path of the source image
key:
key of the thumbnail
format:
thumbnail file extension
"""
relpath = os.path.dirname(path)
thumbsdir =... | [
"def",
"get_thumbpath",
"(",
"self",
",",
"path",
",",
"key",
",",
"format",
")",
":",
"relpath",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
"thumbsdir",
"=",
"self",
".",
"get_thumbsdir",
"(",
"path",
")",
"name",
",",
"_",
"=",
"os... | Return the relative path of the thumbnail.
path:
path of the source image
key:
key of the thumbnail
format:
thumbnail file extension | [
"Return",
"the",
"relative",
"path",
"of",
"the",
"thumbnail",
"."
] | train | https://github.com/jpscaletti/moar/blob/22694e5671b6adaccc4c9c87db7bdd701d20e734/moar/storage.py#L84-L98 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.