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 |
|---|---|---|---|---|---|---|---|---|---|---|
florianpaquet/mease | mease/registry.py | Mease.publish | def publish(self, message_type=ON_SEND, client_id=None, client_storage=None,
*args, **kwargs):
"""
Publishes a message
"""
self.publisher.publish(
message_type, client_id, client_storage, *args, **kwargs) | python | def publish(self, message_type=ON_SEND, client_id=None, client_storage=None,
*args, **kwargs):
"""
Publishes a message
"""
self.publisher.publish(
message_type, client_id, client_storage, *args, **kwargs) | [
"def",
"publish",
"(",
"self",
",",
"message_type",
"=",
"ON_SEND",
",",
"client_id",
"=",
"None",
",",
"client_storage",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"publisher",
".",
"publish",
"(",
"message_type",
"... | Publishes a message | [
"Publishes",
"a",
"message"
] | train | https://github.com/florianpaquet/mease/blob/b9fbd08bbe162c8890c2a2124674371170c319ef/mease/registry.py#L145-L151 |
florianpaquet/mease | mease/registry.py | Mease.run_websocket_server | def run_websocket_server(self, host='localhost', port=9090, debug=False):
"""
Runs websocket server
"""
from .server import MeaseWebSocketServerFactory
websocket_factory = MeaseWebSocketServerFactory(
mease=self, host=host, port=port, debug=debug)
websocket_f... | python | def run_websocket_server(self, host='localhost', port=9090, debug=False):
"""
Runs websocket server
"""
from .server import MeaseWebSocketServerFactory
websocket_factory = MeaseWebSocketServerFactory(
mease=self, host=host, port=port, debug=debug)
websocket_f... | [
"def",
"run_websocket_server",
"(",
"self",
",",
"host",
"=",
"'localhost'",
",",
"port",
"=",
"9090",
",",
"debug",
"=",
"False",
")",
":",
"from",
".",
"server",
"import",
"MeaseWebSocketServerFactory",
"websocket_factory",
"=",
"MeaseWebSocketServerFactory",
"(... | Runs websocket server | [
"Runs",
"websocket",
"server"
] | train | https://github.com/florianpaquet/mease/blob/b9fbd08bbe162c8890c2a2124674371170c319ef/mease/registry.py#L155-L163 |
ulf1/oxyba | oxyba/crossvalidation_loop.py | crossvalidation_loop | def crossvalidation_loop(fitfunc, evalfunc, data,
K=None, idxmat=None, random_state=None):
"""Cross Validation
Parameters:
-----------
fitfunc : function
A function that wraps the model/algorithm, has 1 data
variable as input argument, and returns the estimated
... | python | def crossvalidation_loop(fitfunc, evalfunc, data,
K=None, idxmat=None, random_state=None):
"""Cross Validation
Parameters:
-----------
fitfunc : function
A function that wraps the model/algorithm, has 1 data
variable as input argument, and returns the estimated
... | [
"def",
"crossvalidation_loop",
"(",
"fitfunc",
",",
"evalfunc",
",",
"data",
",",
"K",
"=",
"None",
",",
"idxmat",
"=",
"None",
",",
"random_state",
"=",
"None",
")",
":",
"import",
"oxyba",
"as",
"ox",
"import",
"numpy",
"as",
"np",
"import",
"warnings"... | Cross Validation
Parameters:
-----------
fitfunc : function
A function that wraps the model/algorithm, has 1 data
variable as input argument, and returns the estimated
coefficients, model parameters, weights, etc.
evalfunc : function
A function pointer to an evaluation,... | [
"Cross",
"Validation"
] | train | https://github.com/ulf1/oxyba/blob/b3043116050de275124365cb11e7df91fb40169d/oxyba/crossvalidation_loop.py#L3-L88 |
drcloud/stackclimber | stackclimber.py | stackclimber | def stackclimber(height=0): # http://stackoverflow.com/a/900404/48251
"""
Obtain the name of the caller's module. Uses the inspect module to find
the caller's position in the module hierarchy. With the optional height
argument, finds the caller's caller, and so forth.
"""
caller = insp... | python | def stackclimber(height=0): # http://stackoverflow.com/a/900404/48251
"""
Obtain the name of the caller's module. Uses the inspect module to find
the caller's position in the module hierarchy. With the optional height
argument, finds the caller's caller, and so forth.
"""
caller = insp... | [
"def",
"stackclimber",
"(",
"height",
"=",
"0",
")",
":",
"# http://stackoverflow.com/a/900404/48251",
"caller",
"=",
"inspect",
".",
"stack",
"(",
")",
"[",
"height",
"+",
"1",
"]",
"scope",
"=",
"caller",
"[",
"0",
"]",
".",
"f_globals",
"path",
"=",
"... | Obtain the name of the caller's module. Uses the inspect module to find
the caller's position in the module hierarchy. With the optional height
argument, finds the caller's caller, and so forth. | [
"Obtain",
"the",
"name",
"of",
"the",
"caller",
"s",
"module",
".",
"Uses",
"the",
"inspect",
"module",
"to",
"find",
"the",
"caller",
"s",
"position",
"in",
"the",
"module",
"hierarchy",
".",
"With",
"the",
"optional",
"height",
"argument",
"finds",
"the"... | train | https://github.com/drcloud/stackclimber/blob/595b66474171bc5fe08e7361622953c309d00ae5/stackclimber.py#L6-L20 |
EventTeam/beliefs | src/beliefs/belief_utils.py | flatten_list | def flatten_list(l):
""" Nested lists to single-level list, does not split strings"""
return list(chain.from_iterable(repeat(x,1) if isinstance(x,str) else x for x in l)) | python | def flatten_list(l):
""" Nested lists to single-level list, does not split strings"""
return list(chain.from_iterable(repeat(x,1) if isinstance(x,str) else x for x in l)) | [
"def",
"flatten_list",
"(",
"l",
")",
":",
"return",
"list",
"(",
"chain",
".",
"from_iterable",
"(",
"repeat",
"(",
"x",
",",
"1",
")",
"if",
"isinstance",
"(",
"x",
",",
"str",
")",
"else",
"x",
"for",
"x",
"in",
"l",
")",
")"
] | Nested lists to single-level list, does not split strings | [
"Nested",
"lists",
"to",
"single",
"-",
"level",
"list",
"does",
"not",
"split",
"strings"
] | train | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/belief_utils.py#L55-L57 |
EventTeam/beliefs | src/beliefs/belief_utils.py | list_diff | def list_diff(list1, list2):
""" Ssymetric list difference """
diff_list = []
for item in list1:
if not item in list2:
diff_list.append(item)
for item in list2:
if not item in list1:
diff_list.append(item)
return diff_list | python | def list_diff(list1, list2):
""" Ssymetric list difference """
diff_list = []
for item in list1:
if not item in list2:
diff_list.append(item)
for item in list2:
if not item in list1:
diff_list.append(item)
return diff_list | [
"def",
"list_diff",
"(",
"list1",
",",
"list2",
")",
":",
"diff_list",
"=",
"[",
"]",
"for",
"item",
"in",
"list1",
":",
"if",
"not",
"item",
"in",
"list2",
":",
"diff_list",
".",
"append",
"(",
"item",
")",
"for",
"item",
"in",
"list2",
":",
"if",... | Ssymetric list difference | [
"Ssymetric",
"list",
"difference"
] | train | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/belief_utils.py#L59-L68 |
EventTeam/beliefs | src/beliefs/belief_utils.py | asym_list_diff | def asym_list_diff(list1, list2):
""" Asymmetric list difference """
diff_list = []
for item in list1:
if not item in list2:
diff_list.append(item)
return diff_list | python | def asym_list_diff(list1, list2):
""" Asymmetric list difference """
diff_list = []
for item in list1:
if not item in list2:
diff_list.append(item)
return diff_list | [
"def",
"asym_list_diff",
"(",
"list1",
",",
"list2",
")",
":",
"diff_list",
"=",
"[",
"]",
"for",
"item",
"in",
"list1",
":",
"if",
"not",
"item",
"in",
"list2",
":",
"diff_list",
".",
"append",
"(",
"item",
")",
"return",
"diff_list"
] | Asymmetric list difference | [
"Asymmetric",
"list",
"difference"
] | train | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/belief_utils.py#L70-L76 |
EventTeam/beliefs | src/beliefs/belief_utils.py | si_prefix | def si_prefix(value):
""" By Forrest Green (2010)"""
#standard si prefixes
prefixes = ['y','z','a','f','p','n','u','m','','k','M','G','T','P','E','Z','Y']
from math import log
#closest 1000 exponent
if value == 0: return (value, "")
exp = int(log(value,1000)//1) + 8
if exp < 0: exp = 0
... | python | def si_prefix(value):
""" By Forrest Green (2010)"""
#standard si prefixes
prefixes = ['y','z','a','f','p','n','u','m','','k','M','G','T','P','E','Z','Y']
from math import log
#closest 1000 exponent
if value == 0: return (value, "")
exp = int(log(value,1000)//1) + 8
if exp < 0: exp = 0
... | [
"def",
"si_prefix",
"(",
"value",
")",
":",
"#standard si prefixes",
"prefixes",
"=",
"[",
"'y'",
",",
"'z'",
",",
"'a'",
",",
"'f'",
",",
"'p'",
",",
"'n'",
",",
"'u'",
",",
"'m'",
",",
"''",
",",
"'k'",
",",
"'M'",
",",
"'G'",
",",
"'T'",
",",
... | By Forrest Green (2010) | [
"By",
"Forrest",
"Green",
"(",
"2010",
")"
] | train | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/belief_utils.py#L100-L111 |
EventTeam/beliefs | src/beliefs/belief_utils.py | levenshtein_distance_metric | def levenshtein_distance_metric(a, b):
""" 1 - farthest apart (same number of words, all diff). 0 - same"""
return (levenshtein_distance(a, b) / (2.0 * max(len(a), len(b), 1))) | python | def levenshtein_distance_metric(a, b):
""" 1 - farthest apart (same number of words, all diff). 0 - same"""
return (levenshtein_distance(a, b) / (2.0 * max(len(a), len(b), 1))) | [
"def",
"levenshtein_distance_metric",
"(",
"a",
",",
"b",
")",
":",
"return",
"(",
"levenshtein_distance",
"(",
"a",
",",
"b",
")",
"/",
"(",
"2.0",
"*",
"max",
"(",
"len",
"(",
"a",
")",
",",
"len",
"(",
"b",
")",
",",
"1",
")",
")",
")"
] | 1 - farthest apart (same number of words, all diff). 0 - same | [
"1",
"-",
"farthest",
"apart",
"(",
"same",
"number",
"of",
"words",
"all",
"diff",
")",
".",
"0",
"-",
"same"
] | train | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/belief_utils.py#L143-L145 |
EventTeam/beliefs | src/beliefs/belief_utils.py | next_tokens_in_sequence | def next_tokens_in_sequence(observed, current):
""" Given the observed list of tokens, and the current list,
finds out what should be next next emitted word
"""
idx = 0
for word in current:
if observed[idx:].count(word) != 0:
found_pos = observed.index(word, idx)
idx ... | python | def next_tokens_in_sequence(observed, current):
""" Given the observed list of tokens, and the current list,
finds out what should be next next emitted word
"""
idx = 0
for word in current:
if observed[idx:].count(word) != 0:
found_pos = observed.index(word, idx)
idx ... | [
"def",
"next_tokens_in_sequence",
"(",
"observed",
",",
"current",
")",
":",
"idx",
"=",
"0",
"for",
"word",
"in",
"current",
":",
"if",
"observed",
"[",
"idx",
":",
"]",
".",
"count",
"(",
"word",
")",
"!=",
"0",
":",
"found_pos",
"=",
"observed",
"... | Given the observed list of tokens, and the current list,
finds out what should be next next emitted word | [
"Given",
"the",
"observed",
"list",
"of",
"tokens",
"and",
"the",
"current",
"list",
"finds",
"out",
"what",
"should",
"be",
"next",
"next",
"emitted",
"word"
] | train | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/belief_utils.py#L148-L161 |
EventTeam/beliefs | src/beliefs/belief_utils.py | choose | def choose(n, k):
"""
A fast way to calculate binomial coefficients by Andrew Dalke (contrib).
"""
if 0 <= k <= n:
ntok = 1
ktok = 1
for t in xrange(1, min(k, n - k) + 1):
ntok *= n
ktok *= t
n -= 1
return ntok // ktok
else:
... | python | def choose(n, k):
"""
A fast way to calculate binomial coefficients by Andrew Dalke (contrib).
"""
if 0 <= k <= n:
ntok = 1
ktok = 1
for t in xrange(1, min(k, n - k) + 1):
ntok *= n
ktok *= t
n -= 1
return ntok // ktok
else:
... | [
"def",
"choose",
"(",
"n",
",",
"k",
")",
":",
"if",
"0",
"<=",
"k",
"<=",
"n",
":",
"ntok",
"=",
"1",
"ktok",
"=",
"1",
"for",
"t",
"in",
"xrange",
"(",
"1",
",",
"min",
"(",
"k",
",",
"n",
"-",
"k",
")",
"+",
"1",
")",
":",
"ntok",
... | A fast way to calculate binomial coefficients by Andrew Dalke (contrib). | [
"A",
"fast",
"way",
"to",
"calculate",
"binomial",
"coefficients",
"by",
"Andrew",
"Dalke",
"(",
"contrib",
")",
"."
] | train | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/belief_utils.py#L173-L186 |
EventTeam/beliefs | src/beliefs/cells/numeric.py | IntervalCell.coerce | def coerce(value):
"""
Takes a number (float, int) or a two-valued integer and returns the
[low, high] in the standard interval form
"""
is_number = lambda x: isinstance(x, (int, float, complex)) #is x an instance of those things
if isinstance(value, IntervalCell) or issu... | python | def coerce(value):
"""
Takes a number (float, int) or a two-valued integer and returns the
[low, high] in the standard interval form
"""
is_number = lambda x: isinstance(x, (int, float, complex)) #is x an instance of those things
if isinstance(value, IntervalCell) or issu... | [
"def",
"coerce",
"(",
"value",
")",
":",
"is_number",
"=",
"lambda",
"x",
":",
"isinstance",
"(",
"x",
",",
"(",
"int",
",",
"float",
",",
"complex",
")",
")",
"#is x an instance of those things",
"if",
"isinstance",
"(",
"value",
",",
"IntervalCell",
")",... | Takes a number (float, int) or a two-valued integer and returns the
[low, high] in the standard interval form | [
"Takes",
"a",
"number",
"(",
"float",
"int",
")",
"or",
"a",
"two",
"-",
"valued",
"integer",
"and",
"returns",
"the",
"[",
"low",
"high",
"]",
"in",
"the",
"standard",
"interval",
"form"
] | train | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/numeric.py#L25-L51 |
EventTeam/beliefs | src/beliefs/cells/numeric.py | IntervalCell.is_contradictory | def is_contradictory(self, other):
"""
Whether other and self can coexist
"""
other = IntervalCell.coerce(other)
assert other.low <= other.high, "Low must be <= high"
if max(other.low, self.low) <= min(other.high, self.high):
return False
else:
... | python | def is_contradictory(self, other):
"""
Whether other and self can coexist
"""
other = IntervalCell.coerce(other)
assert other.low <= other.high, "Low must be <= high"
if max(other.low, self.low) <= min(other.high, self.high):
return False
else:
... | [
"def",
"is_contradictory",
"(",
"self",
",",
"other",
")",
":",
"other",
"=",
"IntervalCell",
".",
"coerce",
"(",
"other",
")",
"assert",
"other",
".",
"low",
"<=",
"other",
".",
"high",
",",
"\"Low must be <= high\"",
"if",
"max",
"(",
"other",
".",
"lo... | Whether other and self can coexist | [
"Whether",
"other",
"and",
"self",
"can",
"coexist"
] | train | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/numeric.py#L63-L72 |
EventTeam/beliefs | src/beliefs/cells/numeric.py | IntervalCell.is_entailed_by | def is_entailed_by(self, other):
"""
Other is more specific than self. Other is bounded within self.
"""
other = IntervalCell.coerce(other)
return other.low >= self.low and other.high <= self.high | python | def is_entailed_by(self, other):
"""
Other is more specific than self. Other is bounded within self.
"""
other = IntervalCell.coerce(other)
return other.low >= self.low and other.high <= self.high | [
"def",
"is_entailed_by",
"(",
"self",
",",
"other",
")",
":",
"other",
"=",
"IntervalCell",
".",
"coerce",
"(",
"other",
")",
"return",
"other",
".",
"low",
">=",
"self",
".",
"low",
"and",
"other",
".",
"high",
"<=",
"self",
".",
"high"
] | Other is more specific than self. Other is bounded within self. | [
"Other",
"is",
"more",
"specific",
"than",
"self",
".",
"Other",
"is",
"bounded",
"within",
"self",
"."
] | train | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/numeric.py#L74-L79 |
EventTeam/beliefs | src/beliefs/cells/numeric.py | IntervalCell.is_equal | def is_equal(self, other):
"""
If two intervals are the same
"""
other = IntervalCell.coerce(other)
return other.low == self.low and other.high == self.high | python | def is_equal(self, other):
"""
If two intervals are the same
"""
other = IntervalCell.coerce(other)
return other.low == self.low and other.high == self.high | [
"def",
"is_equal",
"(",
"self",
",",
"other",
")",
":",
"other",
"=",
"IntervalCell",
".",
"coerce",
"(",
"other",
")",
"return",
"other",
".",
"low",
"==",
"self",
".",
"low",
"and",
"other",
".",
"high",
"==",
"self",
".",
"high"
] | If two intervals are the same | [
"If",
"two",
"intervals",
"are",
"the",
"same"
] | train | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/numeric.py#L81-L86 |
EventTeam/beliefs | src/beliefs/cells/numeric.py | IntervalCell.merge | def merge(self, other):
"""
Merges the two values
"""
other = IntervalCell.coerce(other)
if self.is_equal(other):
# pick among dependencies
return self
elif other.is_entailed_by(self):
return self
elif self.is_entailed_by(other)... | python | def merge(self, other):
"""
Merges the two values
"""
other = IntervalCell.coerce(other)
if self.is_equal(other):
# pick among dependencies
return self
elif other.is_entailed_by(self):
return self
elif self.is_entailed_by(other)... | [
"def",
"merge",
"(",
"self",
",",
"other",
")",
":",
"other",
"=",
"IntervalCell",
".",
"coerce",
"(",
"other",
")",
"if",
"self",
".",
"is_equal",
"(",
"other",
")",
":",
"# pick among dependencies",
"return",
"self",
"elif",
"other",
".",
"is_entailed_by... | Merges the two values | [
"Merges",
"the",
"two",
"values"
] | train | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/numeric.py#L88-L110 |
EventTeam/beliefs | src/beliefs/cells/numeric.py | IntervalCell.map | def map(self, other, function):
"""
Applies a mathematic function to the interval arithmetic template:
generate all combinations of low/high values and then take the widest
bounds (min/max) for the result.
"""
other = IntervalCell.coerce(other)
# check the arity o... | python | def map(self, other, function):
"""
Applies a mathematic function to the interval arithmetic template:
generate all combinations of low/high values and then take the widest
bounds (min/max) for the result.
"""
other = IntervalCell.coerce(other)
# check the arity o... | [
"def",
"map",
"(",
"self",
",",
"other",
",",
"function",
")",
":",
"other",
"=",
"IntervalCell",
".",
"coerce",
"(",
"other",
")",
"# check the arity of the function",
"import",
"inspect",
"arity",
"=",
"len",
"(",
"inspect",
".",
"getargspec",
"(",
"functi... | Applies a mathematic function to the interval arithmetic template:
generate all combinations of low/high values and then take the widest
bounds (min/max) for the result. | [
"Applies",
"a",
"mathematic",
"function",
"to",
"the",
"interval",
"arithmetic",
"template",
":",
"generate",
"all",
"combinations",
"of",
"low",
"/",
"high",
"values",
"and",
"then",
"take",
"the",
"widest",
"bounds",
"(",
"min",
"/",
"max",
")",
"for",
"... | train | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/numeric.py#L201-L219 |
EventTeam/beliefs | src/beliefs/cells/numeric.py | IntervalCell.to_latex | def to_latex(self):
""" Returns an interval representation """
if self.low == self.high:
if self.low * 10 % 10 == 0:
return "{0:d}".format(int(self.low))
else:
return "{0:0.2f}".format(self.low)
else:
t = ""
if self.... | python | def to_latex(self):
""" Returns an interval representation """
if self.low == self.high:
if self.low * 10 % 10 == 0:
return "{0:d}".format(int(self.low))
else:
return "{0:0.2f}".format(self.low)
else:
t = ""
if self.... | [
"def",
"to_latex",
"(",
"self",
")",
":",
"if",
"self",
".",
"low",
"==",
"self",
".",
"high",
":",
"if",
"self",
".",
"low",
"*",
"10",
"%",
"10",
"==",
"0",
":",
"return",
"\"{0:d}\"",
".",
"format",
"(",
"int",
"(",
"self",
".",
"low",
")",
... | Returns an interval representation | [
"Returns",
"an",
"interval",
"representation"
] | train | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/numeric.py#L244-L265 |
oubiga/respect | respect/main.py | main | def main():
"""
Main entry point for the `respect` command.
"""
args = parse_respect_args(sys.argv[1:])
if validate_username(args['<username>']):
print("processing...")
else:
print("@"+args['<username>'], "is not a valid username.")
print("Username may only contain alpha... | python | def main():
"""
Main entry point for the `respect` command.
"""
args = parse_respect_args(sys.argv[1:])
if validate_username(args['<username>']):
print("processing...")
else:
print("@"+args['<username>'], "is not a valid username.")
print("Username may only contain alpha... | [
"def",
"main",
"(",
")",
":",
"args",
"=",
"parse_respect_args",
"(",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
")",
"if",
"validate_username",
"(",
"args",
"[",
"'<username>'",
"]",
")",
":",
"print",
"(",
"\"processing...\"",
")",
"else",
":",
"print",... | Main entry point for the `respect` command. | [
"Main",
"entry",
"point",
"for",
"the",
"respect",
"command",
"."
] | train | https://github.com/oubiga/respect/blob/550554ec4d3139379d03cb8f82a8cd2d80c3ad62/respect/main.py#L56-L82 |
polysquare/polysquare-generic-file-linter | polysquarelinter/spelling.py | clear_caches | def clear_caches(): # suppress(unused-function)
"""Clear all caches."""
for _, reader in _spellchecker_cache.values():
reader.close()
_spellchecker_cache.clear()
_valid_words_cache.clear()
_user_dictionary_cache.clear() | python | def clear_caches(): # suppress(unused-function)
"""Clear all caches."""
for _, reader in _spellchecker_cache.values():
reader.close()
_spellchecker_cache.clear()
_valid_words_cache.clear()
_user_dictionary_cache.clear() | [
"def",
"clear_caches",
"(",
")",
":",
"# suppress(unused-function)",
"for",
"_",
",",
"reader",
"in",
"_spellchecker_cache",
".",
"values",
"(",
")",
":",
"reader",
".",
"close",
"(",
")",
"_spellchecker_cache",
".",
"clear",
"(",
")",
"_valid_words_cache",
".... | Clear all caches. | [
"Clear",
"all",
"caches",
"."
] | train | https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/spelling.py#L61-L68 |
polysquare/polysquare-generic-file-linter | polysquarelinter/spelling.py | _comment_system_for_file | def _comment_system_for_file(contents):
"""For file contents, return the comment system."""
if contents[0] == "#":
return FileCommentSystem(begin="#", middle="", end="", single="#")
elif contents[:2] == "/*":
return FileCommentSystem(begin="/*", middle="*", end="*/", single="//")
elif co... | python | def _comment_system_for_file(contents):
"""For file contents, return the comment system."""
if contents[0] == "#":
return FileCommentSystem(begin="#", middle="", end="", single="#")
elif contents[:2] == "/*":
return FileCommentSystem(begin="/*", middle="*", end="*/", single="//")
elif co... | [
"def",
"_comment_system_for_file",
"(",
"contents",
")",
":",
"if",
"contents",
"[",
"0",
"]",
"==",
"\"#\"",
":",
"return",
"FileCommentSystem",
"(",
"begin",
"=",
"\"#\"",
",",
"middle",
"=",
"\"\"",
",",
"end",
"=",
"\"\"",
",",
"single",
"=",
"\"#\""... | For file contents, return the comment system. | [
"For",
"file",
"contents",
"return",
"the",
"comment",
"system",
"."
] | train | https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/spelling.py#L74-L89 |
polysquare/polysquare-generic-file-linter | polysquarelinter/spelling.py | _split_line_with_offsets | def _split_line_with_offsets(line):
"""Split a line by delimiter, but yield tuples of word and offset.
This function works by dropping all the english-like punctuation from
a line (so parenthesis preceded or succeeded by spaces, periods, etc)
and then splitting on spaces.
"""
for delimiter in r... | python | def _split_line_with_offsets(line):
"""Split a line by delimiter, but yield tuples of word and offset.
This function works by dropping all the english-like punctuation from
a line (so parenthesis preceded or succeeded by spaces, periods, etc)
and then splitting on spaces.
"""
for delimiter in r... | [
"def",
"_split_line_with_offsets",
"(",
"line",
")",
":",
"for",
"delimiter",
"in",
"re",
".",
"finditer",
"(",
"r\"[\\.,:\\;](?![^\\s])\"",
",",
"line",
")",
":",
"span",
"=",
"delimiter",
".",
"span",
"(",
")",
"line",
"=",
"line",
"[",
":",
"span",
"[... | Split a line by delimiter, but yield tuples of word and offset.
This function works by dropping all the english-like punctuation from
a line (so parenthesis preceded or succeeded by spaces, periods, etc)
and then splitting on spaces. | [
"Split",
"a",
"line",
"by",
"delimiter",
"but",
"yield",
"tuples",
"of",
"word",
"and",
"offset",
"."
] | train | https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/spelling.py#L129-L159 |
polysquare/polysquare-generic-file-linter | polysquarelinter/spelling.py | read_dictionary_file | def read_dictionary_file(dictionary_path):
"""Return all words in dictionary file as set."""
try:
return _user_dictionary_cache[dictionary_path]
except KeyError:
if dictionary_path and os.path.exists(dictionary_path):
with open(dictionary_path, "rt") as dict_f:
wo... | python | def read_dictionary_file(dictionary_path):
"""Return all words in dictionary file as set."""
try:
return _user_dictionary_cache[dictionary_path]
except KeyError:
if dictionary_path and os.path.exists(dictionary_path):
with open(dictionary_path, "rt") as dict_f:
wo... | [
"def",
"read_dictionary_file",
"(",
"dictionary_path",
")",
":",
"try",
":",
"return",
"_user_dictionary_cache",
"[",
"dictionary_path",
"]",
"except",
"KeyError",
":",
"if",
"dictionary_path",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"dictionary_path",
")",
... | Return all words in dictionary file as set. | [
"Return",
"all",
"words",
"in",
"dictionary",
"file",
"as",
"set",
"."
] | train | https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/spelling.py#L162-L173 |
polysquare/polysquare-generic-file-linter | polysquarelinter/spelling.py | valid_words_set | def valid_words_set(path_to_user_dictionary=None,
user_dictionary_words=None):
"""Get a set of valid words.
If :path_to_user_dictionary: is specified, then the newline-separated
words in that file will be added to the word set.
"""
def read_file(binary_file):
"""Read a b... | python | def valid_words_set(path_to_user_dictionary=None,
user_dictionary_words=None):
"""Get a set of valid words.
If :path_to_user_dictionary: is specified, then the newline-separated
words in that file will be added to the word set.
"""
def read_file(binary_file):
"""Read a b... | [
"def",
"valid_words_set",
"(",
"path_to_user_dictionary",
"=",
"None",
",",
"user_dictionary_words",
"=",
"None",
")",
":",
"def",
"read_file",
"(",
"binary_file",
")",
":",
"\"\"\"Read a binary file for its text lines.\"\"\"",
"return",
"binary_file",
".",
"read",
"(",... | Get a set of valid words.
If :path_to_user_dictionary: is specified, then the newline-separated
words in that file will be added to the word set. | [
"Get",
"a",
"set",
"of",
"valid",
"words",
"."
] | train | https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/spelling.py#L176-L203 |
polysquare/polysquare-generic-file-linter | polysquarelinter/spelling.py | _create_word_graph_file | def _create_word_graph_file(name, file_storage, word_set):
"""Create a word graph file and open it in memory."""
word_graph_file = file_storage.create_file(name)
spelling.wordlist_to_graph_file(sorted(list(word_set)),
word_graph_file)
return copy_to_ram(file_storage).... | python | def _create_word_graph_file(name, file_storage, word_set):
"""Create a word graph file and open it in memory."""
word_graph_file = file_storage.create_file(name)
spelling.wordlist_to_graph_file(sorted(list(word_set)),
word_graph_file)
return copy_to_ram(file_storage).... | [
"def",
"_create_word_graph_file",
"(",
"name",
",",
"file_storage",
",",
"word_set",
")",
":",
"word_graph_file",
"=",
"file_storage",
".",
"create_file",
"(",
"name",
")",
"spelling",
".",
"wordlist_to_graph_file",
"(",
"sorted",
"(",
"list",
"(",
"word_set",
"... | Create a word graph file and open it in memory. | [
"Create",
"a",
"word",
"graph",
"file",
"and",
"open",
"it",
"in",
"memory",
"."
] | train | https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/spelling.py#L211-L216 |
polysquare/polysquare-generic-file-linter | polysquarelinter/spelling.py | _spellchecker_for | def _spellchecker_for(word_set,
name,
spellcheck_cache_path=None,
sources=None):
"""Get a whoosh spellchecker for :word_set:.
The word graph for this spellchecker will be stored on-disk with
the unique-name :name: in :spellcheck_cache_path:,... | python | def _spellchecker_for(word_set,
name,
spellcheck_cache_path=None,
sources=None):
"""Get a whoosh spellchecker for :word_set:.
The word graph for this spellchecker will be stored on-disk with
the unique-name :name: in :spellcheck_cache_path:,... | [
"def",
"_spellchecker_for",
"(",
"word_set",
",",
"name",
",",
"spellcheck_cache_path",
"=",
"None",
",",
"sources",
"=",
"None",
")",
":",
"assert",
"\"/\"",
"not",
"in",
"name",
"and",
"\"\\\\\"",
"not",
"in",
"name",
"if",
"_spellchecker_cache",
".",
"get... | Get a whoosh spellchecker for :word_set:.
The word graph for this spellchecker will be stored on-disk with
the unique-name :name: in :spellcheck_cache_path:, if it exists.
This allows for much faster loading of word graphs after they have been
pre-populated.
:sources: is a list of filenames which ... | [
"Get",
"a",
"whoosh",
"spellchecker",
"for",
":",
"word_set",
":",
"."
] | train | https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/spelling.py#L219-L282 |
polysquare/polysquare-generic-file-linter | polysquarelinter/spelling.py | filter_nonspellcheckable_tokens | def filter_nonspellcheckable_tokens(line, block_out_regexes=None):
"""Return line with paths, urls and emails filtered out.
Block out other strings of text matching :block_out_regexes: if passed in.
"""
all_block_out_regexes = [
r"[^\s]*:[^\s]*[/\\][^\s]*",
r"[^\s]*[/\\][^\s]*",
... | python | def filter_nonspellcheckable_tokens(line, block_out_regexes=None):
"""Return line with paths, urls and emails filtered out.
Block out other strings of text matching :block_out_regexes: if passed in.
"""
all_block_out_regexes = [
r"[^\s]*:[^\s]*[/\\][^\s]*",
r"[^\s]*[/\\][^\s]*",
... | [
"def",
"filter_nonspellcheckable_tokens",
"(",
"line",
",",
"block_out_regexes",
"=",
"None",
")",
":",
"all_block_out_regexes",
"=",
"[",
"r\"[^\\s]*:[^\\s]*[/\\\\][^\\s]*\"",
",",
"r\"[^\\s]*[/\\\\][^\\s]*\"",
",",
"r\"\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]+\\b\"",
"]",... | Return line with paths, urls and emails filtered out.
Block out other strings of text matching :block_out_regexes: if passed in. | [
"Return",
"line",
"with",
"paths",
"urls",
"and",
"emails",
"filtered",
"out",
"."
] | train | https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/spelling.py#L285-L301 |
polysquare/polysquare-generic-file-linter | polysquarelinter/spelling.py | _shadow_contents_from_chunks | def _shadow_contents_from_chunks(contents, chunks, block_out_regexes=None):
"""Remove all contents in spellcheckable :chunks: from contents."""
shadow_contents = [list(l) for l in contents]
for chunk in chunks:
char_offset = chunk.column
line_offset = 0
for index, line in enumerate(... | python | def _shadow_contents_from_chunks(contents, chunks, block_out_regexes=None):
"""Remove all contents in spellcheckable :chunks: from contents."""
shadow_contents = [list(l) for l in contents]
for chunk in chunks:
char_offset = chunk.column
line_offset = 0
for index, line in enumerate(... | [
"def",
"_shadow_contents_from_chunks",
"(",
"contents",
",",
"chunks",
",",
"block_out_regexes",
"=",
"None",
")",
":",
"shadow_contents",
"=",
"[",
"list",
"(",
"l",
")",
"for",
"l",
"in",
"contents",
"]",
"for",
"chunk",
"in",
"chunks",
":",
"char_offset",... | Remove all contents in spellcheckable :chunks: from contents. | [
"Remove",
"all",
"contents",
"in",
"spellcheckable",
":",
"chunks",
":",
"from",
"contents",
"."
] | train | https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/spelling.py#L304-L326 |
polysquare/polysquare-generic-file-linter | polysquarelinter/spelling.py | _chunk_from_ranges | def _chunk_from_ranges(contents_lines,
start_line_index,
start_column_index,
end_line_index,
end_column_index):
"""Create a _ChunkInfo from a range of lines and columns.
:contents_lines: is the raw lines of a file.
... | python | def _chunk_from_ranges(contents_lines,
start_line_index,
start_column_index,
end_line_index,
end_column_index):
"""Create a _ChunkInfo from a range of lines and columns.
:contents_lines: is the raw lines of a file.
... | [
"def",
"_chunk_from_ranges",
"(",
"contents_lines",
",",
"start_line_index",
",",
"start_column_index",
",",
"end_line_index",
",",
"end_column_index",
")",
":",
"# If the start and end line are the same we have to compensate for",
"# that by subtracting start_column_index from end_col... | Create a _ChunkInfo from a range of lines and columns.
:contents_lines: is the raw lines of a file. | [
"Create",
"a",
"_ChunkInfo",
"from",
"a",
"range",
"of",
"lines",
"and",
"columns",
"."
] | train | https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/spelling.py#L334-L354 |
polysquare/polysquare-generic-file-linter | polysquarelinter/spelling.py | _token_at_col_in_line | def _token_at_col_in_line(line, column, token, token_len=None):
"""True if token is at column."""
if not token_len:
token_len = len(token)
remaining_len = len(line) - column
return (remaining_len >= token_len and
line[column:column + token_len] == token) | python | def _token_at_col_in_line(line, column, token, token_len=None):
"""True if token is at column."""
if not token_len:
token_len = len(token)
remaining_len = len(line) - column
return (remaining_len >= token_len and
line[column:column + token_len] == token) | [
"def",
"_token_at_col_in_line",
"(",
"line",
",",
"column",
",",
"token",
",",
"token_len",
"=",
"None",
")",
":",
"if",
"not",
"token_len",
":",
"token_len",
"=",
"len",
"(",
"token",
")",
"remaining_len",
"=",
"len",
"(",
"line",
")",
"-",
"column",
... | True if token is at column. | [
"True",
"if",
"token",
"is",
"at",
"column",
"."
] | train | https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/spelling.py#L357-L365 |
polysquare/polysquare-generic-file-linter | polysquarelinter/spelling.py | _maybe_append_chunk | def _maybe_append_chunk(chunk_info, line_index, column, contents, chunks):
"""Append chunk_info to chunks if it is set."""
if chunk_info:
chunks.append(_chunk_from_ranges(contents,
chunk_info[0],
chunk_info[1],
... | python | def _maybe_append_chunk(chunk_info, line_index, column, contents, chunks):
"""Append chunk_info to chunks if it is set."""
if chunk_info:
chunks.append(_chunk_from_ranges(contents,
chunk_info[0],
chunk_info[1],
... | [
"def",
"_maybe_append_chunk",
"(",
"chunk_info",
",",
"line_index",
",",
"column",
",",
"contents",
",",
"chunks",
")",
":",
"if",
"chunk_info",
":",
"chunks",
".",
"append",
"(",
"_chunk_from_ranges",
"(",
"contents",
",",
"chunk_info",
"[",
"0",
"]",
",",
... | Append chunk_info to chunks if it is set. | [
"Append",
"chunk_info",
"to",
"chunks",
"if",
"it",
"is",
"set",
"."
] | train | https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/spelling.py#L671-L678 |
polysquare/polysquare-generic-file-linter | polysquarelinter/spelling.py | _find_spellcheckable_chunks | def _find_spellcheckable_chunks(contents,
comment_system):
"""Given some contents for a file, find chunks that can be spellchecked.
This applies the following rules:
1. If the comment system comments individual lines, that whole line
can be spellchecked from the poi... | python | def _find_spellcheckable_chunks(contents,
comment_system):
"""Given some contents for a file, find chunks that can be spellchecked.
This applies the following rules:
1. If the comment system comments individual lines, that whole line
can be spellchecked from the poi... | [
"def",
"_find_spellcheckable_chunks",
"(",
"contents",
",",
"comment_system",
")",
":",
"state",
"=",
"InTextParser",
"(",
")",
"comment_system_transitions",
"=",
"CommentSystemTransitions",
"(",
"comment_system",
")",
"chunks",
"=",
"[",
"]",
"for",
"line_index",
"... | Given some contents for a file, find chunks that can be spellchecked.
This applies the following rules:
1. If the comment system comments individual lines, that whole line
can be spellchecked from the point of the comment
2. If a comment-start marker or triple quote is found, keep going
u... | [
"Given",
"some",
"contents",
"for",
"a",
"file",
"find",
"chunks",
"that",
"can",
"be",
"spellchecked",
"."
] | train | https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/spelling.py#L681-L754 |
polysquare/polysquare-generic-file-linter | polysquarelinter/spelling.py | spellcheckable_and_shadow_contents | def spellcheckable_and_shadow_contents(contents, block_out_regexes=None):
"""For contents, split into spellcheckable and shadow parts.
:contents: is a list of lines in a file.
The return value is a tuple of (chunks, shadow_contents).
chunks is a list of _ChunkInfo, each of which contain
a region o... | python | def spellcheckable_and_shadow_contents(contents, block_out_regexes=None):
"""For contents, split into spellcheckable and shadow parts.
:contents: is a list of lines in a file.
The return value is a tuple of (chunks, shadow_contents).
chunks is a list of _ChunkInfo, each of which contain
a region o... | [
"def",
"spellcheckable_and_shadow_contents",
"(",
"contents",
",",
"block_out_regexes",
"=",
"None",
")",
":",
"if",
"not",
"len",
"(",
"contents",
")",
":",
"return",
"(",
"[",
"]",
",",
"[",
"]",
")",
"comment_system",
"=",
"_comment_system_for_file",
"(",
... | For contents, split into spellcheckable and shadow parts.
:contents: is a list of lines in a file.
The return value is a tuple of (chunks, shadow_contents).
chunks is a list of _ChunkInfo, each of which contain
a region of text to be spell-checked. shadow_contents is an array of
characters and int... | [
"For",
"contents",
"split",
"into",
"spellcheckable",
"and",
"shadow",
"parts",
"."
] | train | https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/spelling.py#L763-L786 |
polysquare/polysquare-generic-file-linter | polysquarelinter/spelling.py | _split_into_symbol_words | def _split_into_symbol_words(sym):
"""Split a technical looking word into a set of symbols.
This handles cases where technical words are separated by dots or
arrows, as is the convention in many programming languages.
"""
punc = r"[\s\-\*/\+\.,:\;=\)\(\[\]\{\}<>\|\?&\^\$@]"
words = [w.strip() f... | python | def _split_into_symbol_words(sym):
"""Split a technical looking word into a set of symbols.
This handles cases where technical words are separated by dots or
arrows, as is the convention in many programming languages.
"""
punc = r"[\s\-\*/\+\.,:\;=\)\(\[\]\{\}<>\|\?&\^\$@]"
words = [w.strip() f... | [
"def",
"_split_into_symbol_words",
"(",
"sym",
")",
":",
"punc",
"=",
"r\"[\\s\\-\\*/\\+\\.,:\\;=\\)\\(\\[\\]\\{\\}<>\\|\\?&\\^\\$@]\"",
"words",
"=",
"[",
"w",
".",
"strip",
"(",
")",
"for",
"w",
"in",
"re",
".",
"split",
"(",
"punc",
",",
"sym",
")",
"]",
... | Split a technical looking word into a set of symbols.
This handles cases where technical words are separated by dots or
arrows, as is the convention in many programming languages. | [
"Split",
"a",
"technical",
"looking",
"word",
"into",
"a",
"set",
"of",
"symbols",
"."
] | train | https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/spelling.py#L789-L797 |
polysquare/polysquare-generic-file-linter | polysquarelinter/spelling.py | technical_words_from_shadow_contents | def technical_words_from_shadow_contents(shadow_contents):
"""Get a set of technical words from :shadow_contents:.
:shadow_contents: is an array of shadow contents, as returned by
spellcheckable_and_shadow_contents.
"""
technical_words = set()
for line in shadow_contents:
# "Fix up" the... | python | def technical_words_from_shadow_contents(shadow_contents):
"""Get a set of technical words from :shadow_contents:.
:shadow_contents: is an array of shadow contents, as returned by
spellcheckable_and_shadow_contents.
"""
technical_words = set()
for line in shadow_contents:
# "Fix up" the... | [
"def",
"technical_words_from_shadow_contents",
"(",
"shadow_contents",
")",
":",
"technical_words",
"=",
"set",
"(",
")",
"for",
"line",
"in",
"shadow_contents",
":",
"# \"Fix up\" the shadow line by replacing zeros with spaces.",
"line",
"=",
"\"\"",
".",
"join",
"(",
... | Get a set of technical words from :shadow_contents:.
:shadow_contents: is an array of shadow contents, as returned by
spellcheckable_and_shadow_contents. | [
"Get",
"a",
"set",
"of",
"technical",
"words",
"from",
":",
"shadow_contents",
":",
"."
] | train | https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/spelling.py#L804-L818 |
polysquare/polysquare-generic-file-linter | polysquarelinter/spelling.py | _error_if_word_invalid | def _error_if_word_invalid(word,
valid_words_dictionary,
technical_words_dictionary,
line_offset,
col_offset):
"""Return SpellcheckError if this non-technical word is invalid."""
word_lower = word.lower()... | python | def _error_if_word_invalid(word,
valid_words_dictionary,
technical_words_dictionary,
line_offset,
col_offset):
"""Return SpellcheckError if this non-technical word is invalid."""
word_lower = word.lower()... | [
"def",
"_error_if_word_invalid",
"(",
"word",
",",
"valid_words_dictionary",
",",
"technical_words_dictionary",
",",
"line_offset",
",",
"col_offset",
")",
":",
"word_lower",
"=",
"word",
".",
"lower",
"(",
")",
"valid_words_result",
"=",
"valid_words_dictionary",
"."... | Return SpellcheckError if this non-technical word is invalid. | [
"Return",
"SpellcheckError",
"if",
"this",
"non",
"-",
"technical",
"word",
"is",
"invalid",
"."
] | train | https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/spelling.py#L841-L862 |
polysquare/polysquare-generic-file-linter | polysquarelinter/spelling.py | _error_if_symbol_unused | def _error_if_symbol_unused(symbol_word,
technical_words_dictionary,
line_offset,
col_offset):
"""Return SpellcheckError if this symbol is not used in the code."""
result = technical_words_dictionary.corrections(symbol_word,
... | python | def _error_if_symbol_unused(symbol_word,
technical_words_dictionary,
line_offset,
col_offset):
"""Return SpellcheckError if this symbol is not used in the code."""
result = technical_words_dictionary.corrections(symbol_word,
... | [
"def",
"_error_if_symbol_unused",
"(",
"symbol_word",
",",
"technical_words_dictionary",
",",
"line_offset",
",",
"col_offset",
")",
":",
"result",
"=",
"technical_words_dictionary",
".",
"corrections",
"(",
"symbol_word",
",",
"distance",
"=",
"5",
",",
"prefix",
"... | Return SpellcheckError if this symbol is not used in the code. | [
"Return",
"SpellcheckError",
"if",
"this",
"symbol",
"is",
"not",
"used",
"in",
"the",
"code",
"."
] | train | https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/spelling.py#L865-L878 |
polysquare/polysquare-generic-file-linter | polysquarelinter/spelling.py | spellcheck_region | def spellcheck_region(region_lines,
valid_words_dictionary=None,
technical_words_dictionary=None,
user_dictionary_words=None):
"""Perform spellcheck on each word in :region_lines:.
Each word will be checked for existence in :valid_words_dictiona... | python | def spellcheck_region(region_lines,
valid_words_dictionary=None,
technical_words_dictionary=None,
user_dictionary_words=None):
"""Perform spellcheck on each word in :region_lines:.
Each word will be checked for existence in :valid_words_dictiona... | [
"def",
"spellcheck_region",
"(",
"region_lines",
",",
"valid_words_dictionary",
"=",
"None",
",",
"technical_words_dictionary",
"=",
"None",
",",
"user_dictionary_words",
"=",
"None",
")",
":",
"user_dictionary_words",
"=",
"user_dictionary_words",
"or",
"set",
"(",
"... | Perform spellcheck on each word in :region_lines:.
Each word will be checked for existence in :valid_words_dictionary:.
If it is not in :valid_words_dictionary: then corrections will be
suggested.
If the word isn't one which is an ordinary word, then it will be checked
against the available symbol... | [
"Perform",
"spellcheck",
"on",
"each",
"word",
"in",
":",
"region_lines",
":",
"."
] | train | https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/spelling.py#L937-L992 |
polysquare/polysquare-generic-file-linter | polysquarelinter/spelling.py | CommentSystemTransitions.from_text | def from_text(self, line, line_index, column, is_escaped):
"""Return the new state of the comment parser."""
begin = self._begin
end = self._end
single = self._single
single_len = len(single)
start_len = len(begin)
if _token_at_col_in_line(line, column, single, ... | python | def from_text(self, line, line_index, column, is_escaped):
"""Return the new state of the comment parser."""
begin = self._begin
end = self._end
single = self._single
single_len = len(single)
start_len = len(begin)
if _token_at_col_in_line(line, column, single, ... | [
"def",
"from_text",
"(",
"self",
",",
"line",
",",
"line_index",
",",
"column",
",",
"is_escaped",
")",
":",
"begin",
"=",
"self",
".",
"_begin",
"end",
"=",
"self",
".",
"_end",
"single",
"=",
"self",
".",
"_single",
"single_len",
"=",
"len",
"(",
"... | Return the new state of the comment parser. | [
"Return",
"the",
"new",
"state",
"of",
"the",
"comment",
"parser",
"."
] | train | https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/spelling.py#L395-L429 |
polysquare/polysquare-generic-file-linter | polysquarelinter/spelling.py | CommentSystemTransitions.should_terminate_now | def should_terminate_now(self, line, waiting_for):
"""Whether parsing within a comment should terminate now.
This is used for comment systems where there is no comment-ending
character. We need it for parsing disabled regions where we don't
know where a comment block ends, but we know t... | python | def should_terminate_now(self, line, waiting_for):
"""Whether parsing within a comment should terminate now.
This is used for comment systems where there is no comment-ending
character. We need it for parsing disabled regions where we don't
know where a comment block ends, but we know t... | [
"def",
"should_terminate_now",
"(",
"self",
",",
"line",
",",
"waiting_for",
")",
":",
"if",
"waiting_for",
"not",
"in",
"(",
"ParserState",
".",
"EOL",
",",
"self",
".",
"_end",
")",
":",
"return",
"False",
"if",
"self",
".",
"_continue_regex",
":",
"re... | Whether parsing within a comment should terminate now.
This is used for comment systems where there is no comment-ending
character. We need it for parsing disabled regions where we don't
know where a comment block ends, but we know that a comment block
could end at a line ending. It ret... | [
"Whether",
"parsing",
"within",
"a",
"comment",
"should",
"terminate",
"now",
"."
] | train | https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/spelling.py#L431-L446 |
polysquare/polysquare-generic-file-linter | polysquarelinter/spelling.py | ParserState.get_transition | def get_transition(self, # suppress(too-many-arguments)
line,
line_index,
column,
is_escaped,
comment_system_transitions,
eof=False):
"""Return a parser state, a move-ahead ... | python | def get_transition(self, # suppress(too-many-arguments)
line,
line_index,
column,
is_escaped,
comment_system_transitions,
eof=False):
"""Return a parser state, a move-ahead ... | [
"def",
"get_transition",
"(",
"self",
",",
"# suppress(too-many-arguments)",
"line",
",",
"line_index",
",",
"column",
",",
"is_escaped",
",",
"comment_system_transitions",
",",
"eof",
"=",
"False",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"\"\"Cannot instanti... | Return a parser state, a move-ahead amount, and an append range.
If this parser state should terminate and return back to
the TEXT state, then return that state and also any corresponding
chunk that would have been yielded as a result. | [
"Return",
"a",
"parser",
"state",
"a",
"move",
"-",
"ahead",
"amount",
"and",
"an",
"append",
"range",
"."
] | train | https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/spelling.py#L467-L480 |
polysquare/polysquare-generic-file-linter | polysquarelinter/spelling.py | InTextParser.get_transition | def get_transition(self, # suppress(too-many-arguments)
line,
line_index,
column,
is_escaped,
comment_system_transitions,
eof=False):
"""Get transition from InTextParser."""... | python | def get_transition(self, # suppress(too-many-arguments)
line,
line_index,
column,
is_escaped,
comment_system_transitions,
eof=False):
"""Get transition from InTextParser."""... | [
"def",
"get_transition",
"(",
"self",
",",
"# suppress(too-many-arguments)",
"line",
",",
"line_index",
",",
"column",
",",
"is_escaped",
",",
"comment_system_transitions",
",",
"eof",
"=",
"False",
")",
":",
"parser_transition",
"=",
"{",
"STATE_IN_COMMENT",
":",
... | Get transition from InTextParser. | [
"Get",
"transition",
"from",
"InTextParser",
"."
] | train | https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/spelling.py#L495-L523 |
polysquare/polysquare-generic-file-linter | polysquarelinter/spelling.py | DisabledParser.get_transition | def get_transition(self, # suppress(too-many-arguments)
line,
line_index,
column,
is_escaped,
comment_system_transitions,
eof=False):
"""Get transition from DisabledParser."... | python | def get_transition(self, # suppress(too-many-arguments)
line,
line_index,
column,
is_escaped,
comment_system_transitions,
eof=False):
"""Get transition from DisabledParser."... | [
"def",
"get_transition",
"(",
"self",
",",
"# suppress(too-many-arguments)",
"line",
",",
"line_index",
",",
"column",
",",
"is_escaped",
",",
"comment_system_transitions",
",",
"eof",
"=",
"False",
")",
":",
"# If we are at the beginning of a line, to see if we should",
... | Get transition from DisabledParser. | [
"Get",
"transition",
"from",
"DisabledParser",
"."
] | train | https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/spelling.py#L543-L593 |
polysquare/polysquare-generic-file-linter | polysquarelinter/spelling.py | InCommentParser.get_transition | def get_transition(self, # suppress(too-many-arguments)
line,
line_index,
column,
is_escaped,
comment_system_transitions,
eof=False):
"""Get transition from InCommentParser.... | python | def get_transition(self, # suppress(too-many-arguments)
line,
line_index,
column,
is_escaped,
comment_system_transitions,
eof=False):
"""Get transition from InCommentParser.... | [
"def",
"get_transition",
"(",
"self",
",",
"# suppress(too-many-arguments)",
"line",
",",
"line_index",
",",
"column",
",",
"is_escaped",
",",
"comment_system_transitions",
",",
"eof",
"=",
"False",
")",
":",
"del",
"comment_system_transitions",
"if",
"(",
"_token_a... | Get transition from InCommentParser. | [
"Get",
"transition",
"from",
"InCommentParser",
"."
] | train | https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/spelling.py#L600-L641 |
polysquare/polysquare-generic-file-linter | polysquarelinter/spelling.py | InQuoteParser.get_transition | def get_transition(self, # suppress(too-many-arguments)
line,
line_index,
column,
is_escaped,
*args,
**kwargs):
"""Get transition from InQuoteParser."""
del line_ind... | python | def get_transition(self, # suppress(too-many-arguments)
line,
line_index,
column,
is_escaped,
*args,
**kwargs):
"""Get transition from InQuoteParser."""
del line_ind... | [
"def",
"get_transition",
"(",
"self",
",",
"# suppress(too-many-arguments)",
"line",
",",
"line_index",
",",
"column",
",",
"is_escaped",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"del",
"line_index",
"del",
"args",
"del",
"kwargs",
"wait_until_len"... | Get transition from InQuoteParser. | [
"Get",
"transition",
"from",
"InQuoteParser",
"."
] | train | https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/spelling.py#L648-L668 |
polysquare/polysquare-generic-file-linter | polysquarelinter/spelling.py | Dictionary.corrections | def corrections(self, word, prefix=1, distance=2):
"""Get corrections for word, if word is an invalid word.
:prefix: is the number of characters the prefix of the word must
have in common with the suggested corrections.
:distance: is the character distance the corrections may have betw... | python | def corrections(self, word, prefix=1, distance=2):
"""Get corrections for word, if word is an invalid word.
:prefix: is the number of characters the prefix of the word must
have in common with the suggested corrections.
:distance: is the character distance the corrections may have betw... | [
"def",
"corrections",
"(",
"self",
",",
"word",
",",
"prefix",
"=",
"1",
",",
"distance",
"=",
"2",
")",
":",
"if",
"word",
"not",
"in",
"self",
".",
"_words",
":",
"return",
"Dictionary",
".",
"Result",
"(",
"False",
",",
"self",
".",
"_corrector",
... | Get corrections for word, if word is an invalid word.
:prefix: is the number of characters the prefix of the word must
have in common with the suggested corrections.
:distance: is the character distance the corrections may have between
the input word. This limits the number of availabl... | [
"Get",
"corrections",
"for",
"word",
"if",
"word",
"is",
"an",
"invalid",
"word",
"."
] | train | https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/spelling.py#L910-L930 |
edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/edeposit_autoparser.py | _create_dom | def _create_dom(data):
"""
Creates doublelinked DOM from `data`.
Args:
data (str/HTMLElement): Either string or HTML element.
Returns:
obj: HTMLElement containing double linked DOM.
"""
if not isinstance(data, dhtmlparser.HTMLElement):
data = dhtmlparser.parseString(
... | python | def _create_dom(data):
"""
Creates doublelinked DOM from `data`.
Args:
data (str/HTMLElement): Either string or HTML element.
Returns:
obj: HTMLElement containing double linked DOM.
"""
if not isinstance(data, dhtmlparser.HTMLElement):
data = dhtmlparser.parseString(
... | [
"def",
"_create_dom",
"(",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"dhtmlparser",
".",
"HTMLElement",
")",
":",
"data",
"=",
"dhtmlparser",
".",
"parseString",
"(",
"utils",
".",
"handle_encodnig",
"(",
"data",
")",
")",
"dhtmlparser... | Creates doublelinked DOM from `data`.
Args:
data (str/HTMLElement): Either string or HTML element.
Returns:
obj: HTMLElement containing double linked DOM. | [
"Creates",
"doublelinked",
"DOM",
"from",
"data",
"."
] | train | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/edeposit_autoparser.py#L22-L39 |
edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/edeposit_autoparser.py | _locate_element | def _locate_element(dom, el_content, transformer=None):
"""
Find element containing `el_content` in `dom`. Use `transformer` function
to content of all elements in `dom` in order to correctly transforming them
to match them with `el_content`.
Args:
dom (obj): HTMLElement tree.
el_co... | python | def _locate_element(dom, el_content, transformer=None):
"""
Find element containing `el_content` in `dom`. Use `transformer` function
to content of all elements in `dom` in order to correctly transforming them
to match them with `el_content`.
Args:
dom (obj): HTMLElement tree.
el_co... | [
"def",
"_locate_element",
"(",
"dom",
",",
"el_content",
",",
"transformer",
"=",
"None",
")",
":",
"return",
"dom",
".",
"find",
"(",
"None",
",",
"fn",
"=",
"utils",
".",
"content_matchs",
"(",
"el_content",
",",
"transformer",
")",
")"
] | Find element containing `el_content` in `dom`. Use `transformer` function
to content of all elements in `dom` in order to correctly transforming them
to match them with `el_content`.
Args:
dom (obj): HTMLElement tree.
el_content (str): Content of element will be picked from `dom`.
t... | [
"Find",
"element",
"containing",
"el_content",
"in",
"dom",
".",
"Use",
"transformer",
"function",
"to",
"content",
"of",
"all",
"elements",
"in",
"dom",
"in",
"order",
"to",
"correctly",
"transforming",
"them",
"to",
"match",
"them",
"with",
"el_content",
"."... | train | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/edeposit_autoparser.py#L42-L64 |
edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/edeposit_autoparser.py | _match_elements | def _match_elements(dom, matches):
"""
Find location of elements matching patterns specified in `matches`.
Args:
dom (obj): HTMLElement DOM tree.
matches (dict): Structure: ``{"var": {"data": "match", ..}, ..}``.
Returns:
dict: Structure: ``{"var": {"data": HTMLElement_obj, ..}... | python | def _match_elements(dom, matches):
"""
Find location of elements matching patterns specified in `matches`.
Args:
dom (obj): HTMLElement DOM tree.
matches (dict): Structure: ``{"var": {"data": "match", ..}, ..}``.
Returns:
dict: Structure: ``{"var": {"data": HTMLElement_obj, ..}... | [
"def",
"_match_elements",
"(",
"dom",
",",
"matches",
")",
":",
"out",
"=",
"{",
"}",
"for",
"key",
",",
"content",
"in",
"matches",
".",
"items",
"(",
")",
":",
"pattern",
"=",
"content",
"[",
"\"data\"",
"]",
".",
"strip",
"(",
")",
"if",
"\"\\n\... | Find location of elements matching patterns specified in `matches`.
Args:
dom (obj): HTMLElement DOM tree.
matches (dict): Structure: ``{"var": {"data": "match", ..}, ..}``.
Returns:
dict: Structure: ``{"var": {"data": HTMLElement_obj, ..}, ..}`` | [
"Find",
"location",
"of",
"elements",
"matching",
"patterns",
"specified",
"in",
"matches",
"."
] | train | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/edeposit_autoparser.py#L67-L120 |
edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/edeposit_autoparser.py | _collect_paths | def _collect_paths(element):
"""
Collect all possible path which leads to `element`.
Function returns standard path from root element to this, reverse path,
which uses negative indexes for path, also some pattern matches, like
"this is element, which has neighbour with id 7" and so on.
Args:
... | python | def _collect_paths(element):
"""
Collect all possible path which leads to `element`.
Function returns standard path from root element to this, reverse path,
which uses negative indexes for path, also some pattern matches, like
"this is element, which has neighbour with id 7" and so on.
Args:
... | [
"def",
"_collect_paths",
"(",
"element",
")",
":",
"output",
"=",
"[",
"]",
"# look for element by parameters - sometimes the ID is unique",
"path",
"=",
"vectors",
".",
"el_to_path_vector",
"(",
"element",
")",
"root",
"=",
"path",
"[",
"0",
"]",
"params",
"=",
... | Collect all possible path which leads to `element`.
Function returns standard path from root element to this, reverse path,
which uses negative indexes for path, also some pattern matches, like
"this is element, which has neighbour with id 7" and so on.
Args:
element (obj): HTMLElement instanc... | [
"Collect",
"all",
"possible",
"path",
"which",
"leads",
"to",
"element",
"."
] | train | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/edeposit_autoparser.py#L123-L205 |
edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/edeposit_autoparser.py | _is_working_path | def _is_working_path(dom, path, element):
"""
Check whether the path is working or not.
Aply proper search function interpreting `path` to `dom` and check, if
returned object is `element`. If so, return ``True``, otherwise ``False``.
Args:
dom (obj): HTMLElement DOM.
path (obj): :c... | python | def _is_working_path(dom, path, element):
"""
Check whether the path is working or not.
Aply proper search function interpreting `path` to `dom` and check, if
returned object is `element`. If so, return ``True``, otherwise ``False``.
Args:
dom (obj): HTMLElement DOM.
path (obj): :c... | [
"def",
"_is_working_path",
"(",
"dom",
",",
"path",
",",
"element",
")",
":",
"def",
"i_or_none",
"(",
"el",
",",
"i",
")",
":",
"\"\"\"\n Return ``el[i]`` if the list is not blank, or None otherwise.\n\n Args:\n el (list, tuple): Any indexable object.\n ... | Check whether the path is working or not.
Aply proper search function interpreting `path` to `dom` and check, if
returned object is `element`. If so, return ``True``, otherwise ``False``.
Args:
dom (obj): HTMLElement DOM.
path (obj): :class:`.PathCall` Instance containing informations abou... | [
"Check",
"whether",
"the",
"path",
"is",
"working",
"or",
"not",
"."
] | train | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/edeposit_autoparser.py#L208-L289 |
edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/edeposit_autoparser.py | select_best_paths | def select_best_paths(examples):
"""
Process `examples`, select only paths that works for every example. Select
best paths with highest priority.
Args:
examples (dict): Output from :func:`.read_config`.
Returns:
list: List of :class:`.PathCall` and :class:`.Chained` objects.
""... | python | def select_best_paths(examples):
"""
Process `examples`, select only paths that works for every example. Select
best paths with highest priority.
Args:
examples (dict): Output from :func:`.read_config`.
Returns:
list: List of :class:`.PathCall` and :class:`.Chained` objects.
""... | [
"def",
"select_best_paths",
"(",
"examples",
")",
":",
"possible_paths",
"=",
"{",
"}",
"# {varname: [paths]}",
"# collect list of all possible paths to all existing variables",
"for",
"example",
"in",
"examples",
":",
"dom",
"=",
"_create_dom",
"(",
"example",
"[",
"\"... | Process `examples`, select only paths that works for every example. Select
best paths with highest priority.
Args:
examples (dict): Output from :func:`.read_config`.
Returns:
list: List of :class:`.PathCall` and :class:`.Chained` objects. | [
"Process",
"examples",
"select",
"only",
"paths",
"that",
"works",
"for",
"every",
"example",
".",
"Select",
"best",
"paths",
"with",
"highest",
"priority",
"."
] | train | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/edeposit_autoparser.py#L292-L349 |
edeposit/edeposit.amqp.storage | src/edeposit/amqp/storage/publication_storage.py | _assert_obj_type | def _assert_obj_type(pub, name="pub", obj_type=DBPublication):
"""
Make sure, that `pub` is instance of the `obj_type`.
Args:
pub (obj): Instance which will be checked.
name (str): Name of the instance. Used in exception. Default `pub`.
obj_type (class): Class of which the `pub` sho... | python | def _assert_obj_type(pub, name="pub", obj_type=DBPublication):
"""
Make sure, that `pub` is instance of the `obj_type`.
Args:
pub (obj): Instance which will be checked.
name (str): Name of the instance. Used in exception. Default `pub`.
obj_type (class): Class of which the `pub` sho... | [
"def",
"_assert_obj_type",
"(",
"pub",
",",
"name",
"=",
"\"pub\"",
",",
"obj_type",
"=",
"DBPublication",
")",
":",
"if",
"not",
"isinstance",
"(",
"pub",
",",
"obj_type",
")",
":",
"raise",
"InvalidType",
"(",
"\"`%s` have to be instance of %s, not %s!\"",
"%"... | Make sure, that `pub` is instance of the `obj_type`.
Args:
pub (obj): Instance which will be checked.
name (str): Name of the instance. Used in exception. Default `pub`.
obj_type (class): Class of which the `pub` should be instance. Default
:class:`.DBPublication`.
Rai... | [
"Make",
"sure",
"that",
"pub",
"is",
"instance",
"of",
"the",
"obj_type",
"."
] | train | https://github.com/edeposit/edeposit.amqp.storage/blob/fb6bd326249847de04b17b64e856c878665cea92/src/edeposit/amqp/storage/publication_storage.py#L30-L50 |
edeposit/edeposit.amqp.storage | src/edeposit/amqp/storage/publication_storage.py | save_publication | def save_publication(pub):
"""
Save `pub` into database and into proper indexes.
Attr:
pub (obj): Instance of the :class:`.DBPublication`.
Returns:
obj: :class:`.DBPublication` without data.
Raises:
InvalidType: When the `pub` is not instance of :class:`.DBPublication`.
... | python | def save_publication(pub):
"""
Save `pub` into database and into proper indexes.
Attr:
pub (obj): Instance of the :class:`.DBPublication`.
Returns:
obj: :class:`.DBPublication` without data.
Raises:
InvalidType: When the `pub` is not instance of :class:`.DBPublication`.
... | [
"def",
"save_publication",
"(",
"pub",
")",
":",
"_assert_obj_type",
"(",
"pub",
")",
"_get_handler",
"(",
")",
".",
"store_object",
"(",
"pub",
")",
"return",
"pub",
".",
"to_comm",
"(",
"light_request",
"=",
"True",
")"
] | Save `pub` into database and into proper indexes.
Attr:
pub (obj): Instance of the :class:`.DBPublication`.
Returns:
obj: :class:`.DBPublication` without data.
Raises:
InvalidType: When the `pub` is not instance of :class:`.DBPublication`.
UnindexablePublication: When ther... | [
"Save",
"pub",
"into",
"database",
"and",
"into",
"proper",
"indexes",
"."
] | train | https://github.com/edeposit/edeposit.amqp.storage/blob/fb6bd326249847de04b17b64e856c878665cea92/src/edeposit/amqp/storage/publication_storage.py#L53-L72 |
svetlyak40wt/twiggy-goodies | twiggy_goodies/json.py | prepare_fields | def prepare_fields(fields):
"""Возвращает новый словарь с данными, подготовленными
для сериализации в JSON.
"""
def process_item(value):
if not isinstance(value, NUMERIC_TYPES):
if isinstance(value, six.string_types):
# encode utf-8 to unicode, if necessary
... | python | def prepare_fields(fields):
"""Возвращает новый словарь с данными, подготовленными
для сериализации в JSON.
"""
def process_item(value):
if not isinstance(value, NUMERIC_TYPES):
if isinstance(value, six.string_types):
# encode utf-8 to unicode, if necessary
... | [
"def",
"prepare_fields",
"(",
"fields",
")",
":",
"def",
"process_item",
"(",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"NUMERIC_TYPES",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
":",
"# enco... | Возвращает новый словарь с данными, подготовленными
для сериализации в JSON. | [
"Возвращает",
"новый",
"словарь",
"с",
"данными",
"подготовленными",
"для",
"сериализации",
"в",
"JSON",
"."
] | train | https://github.com/svetlyak40wt/twiggy-goodies/blob/71528d5959fab81eb8d0e4373f20d37a013ac00e/twiggy_goodies/json.py#L20-L40 |
eddiejessup/agaro | agaro/runner.py | Runner.clear_dir | def clear_dir(self):
"""Clear the output directory of all output files."""
for snapshot in output_utils.get_filenames(self.output_dir):
if snapshot.endswith('.pkl'):
os.remove(snapshot) | python | def clear_dir(self):
"""Clear the output directory of all output files."""
for snapshot in output_utils.get_filenames(self.output_dir):
if snapshot.endswith('.pkl'):
os.remove(snapshot) | [
"def",
"clear_dir",
"(",
"self",
")",
":",
"for",
"snapshot",
"in",
"output_utils",
".",
"get_filenames",
"(",
"self",
".",
"output_dir",
")",
":",
"if",
"snapshot",
".",
"endswith",
"(",
"'.pkl'",
")",
":",
"os",
".",
"remove",
"(",
"snapshot",
")"
] | Clear the output directory of all output files. | [
"Clear",
"the",
"output",
"directory",
"of",
"all",
"output",
"files",
"."
] | train | https://github.com/eddiejessup/agaro/blob/b2feb45d6129d749088c70b3e9290af7ca7c7d33/agaro/runner.py#L99-L103 |
eddiejessup/agaro | agaro/runner.py | Runner.is_snapshot_time | def is_snapshot_time(self, output_every=None, t_output_every=None):
"""Determine whether or not the model's iteration number is one
where the runner is expected to make an output snapshot.
"""
if t_output_every is not None:
output_every = int(round(t_output_every // self.mode... | python | def is_snapshot_time(self, output_every=None, t_output_every=None):
"""Determine whether or not the model's iteration number is one
where the runner is expected to make an output snapshot.
"""
if t_output_every is not None:
output_every = int(round(t_output_every // self.mode... | [
"def",
"is_snapshot_time",
"(",
"self",
",",
"output_every",
"=",
"None",
",",
"t_output_every",
"=",
"None",
")",
":",
"if",
"t_output_every",
"is",
"not",
"None",
":",
"output_every",
"=",
"int",
"(",
"round",
"(",
"t_output_every",
"//",
"self",
".",
"m... | Determine whether or not the model's iteration number is one
where the runner is expected to make an output snapshot. | [
"Determine",
"whether",
"or",
"not",
"the",
"model",
"s",
"iteration",
"number",
"is",
"one",
"where",
"the",
"runner",
"is",
"expected",
"to",
"make",
"an",
"output",
"snapshot",
"."
] | train | https://github.com/eddiejessup/agaro/blob/b2feb45d6129d749088c70b3e9290af7ca7c7d33/agaro/runner.py#L105-L111 |
eddiejessup/agaro | agaro/runner.py | Runner.iterate | def iterate(self,
n=None, n_upto=None, t=None, t_upto=None,
output_every=None, t_output_every=None):
"""Run the model for a number of iterations, expressed in a number
of options.
Only one iteration argument should be passed.
Only one output arguments shou... | python | def iterate(self,
n=None, n_upto=None, t=None, t_upto=None,
output_every=None, t_output_every=None):
"""Run the model for a number of iterations, expressed in a number
of options.
Only one iteration argument should be passed.
Only one output arguments shou... | [
"def",
"iterate",
"(",
"self",
",",
"n",
"=",
"None",
",",
"n_upto",
"=",
"None",
",",
"t",
"=",
"None",
",",
"t_upto",
"=",
"None",
",",
"output_every",
"=",
"None",
",",
"t_output_every",
"=",
"None",
")",
":",
"if",
"t",
"is",
"not",
"None",
"... | Run the model for a number of iterations, expressed in a number
of options.
Only one iteration argument should be passed.
Only one output arguments should be passed.
Parameters
----------
n: int
Run the model for `n` iterations from its current point.
... | [
"Run",
"the",
"model",
"for",
"a",
"number",
"of",
"iterations",
"expressed",
"in",
"a",
"number",
"of",
"options",
".",
"Only",
"one",
"iteration",
"argument",
"should",
"be",
"passed",
".",
"Only",
"one",
"output",
"arguments",
"should",
"be",
"passed",
... | train | https://github.com/eddiejessup/agaro/blob/b2feb45d6129d749088c70b3e9290af7ca7c7d33/agaro/runner.py#L113-L149 |
eddiejessup/agaro | agaro/runner.py | Runner.make_snapshot | def make_snapshot(self):
"""Output a snapshot of the current model state, as a pickle of the
`Model` object in a file inside the output directory, with a name
determined by its iteration number.
"""
filename = join(self.output_dir, '{:010d}.pkl'.format(self.model.i))
outp... | python | def make_snapshot(self):
"""Output a snapshot of the current model state, as a pickle of the
`Model` object in a file inside the output directory, with a name
determined by its iteration number.
"""
filename = join(self.output_dir, '{:010d}.pkl'.format(self.model.i))
outp... | [
"def",
"make_snapshot",
"(",
"self",
")",
":",
"filename",
"=",
"join",
"(",
"self",
".",
"output_dir",
",",
"'{:010d}.pkl'",
".",
"format",
"(",
"self",
".",
"model",
".",
"i",
")",
")",
"output_utils",
".",
"model_to_file",
"(",
"self",
".",
"model",
... | Output a snapshot of the current model state, as a pickle of the
`Model` object in a file inside the output directory, with a name
determined by its iteration number. | [
"Output",
"a",
"snapshot",
"of",
"the",
"current",
"model",
"state",
"as",
"a",
"pickle",
"of",
"the",
"Model",
"object",
"in",
"a",
"file",
"inside",
"the",
"output",
"directory",
"with",
"a",
"name",
"determined",
"by",
"its",
"iteration",
"number",
"."
... | train | https://github.com/eddiejessup/agaro/blob/b2feb45d6129d749088c70b3e9290af7ca7c7d33/agaro/runner.py#L151-L157 |
qzmfranklin/easyshell | easyshell/debugging_shell.py | DebuggingShell._do_print | def _do_print(self, cmd, args):
"""\
Display symbols.
p Display names of inspectable objects.
p <id> Display the content of an object.
"""
name = args[0].strip()
if not name:
self.stderr.write('TODO: Display names of insp... | python | def _do_print(self, cmd, args):
"""\
Display symbols.
p Display names of inspectable objects.
p <id> Display the content of an object.
"""
name = args[0].strip()
if not name:
self.stderr.write('TODO: Display names of insp... | [
"def",
"_do_print",
"(",
"self",
",",
"cmd",
",",
"args",
")",
":",
"name",
"=",
"args",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"if",
"not",
"name",
":",
"self",
".",
"stderr",
".",
"write",
"(",
"'TODO: Display names of inspectable objects.\\n'",
")",
... | \
Display symbols.
p Display names of inspectable objects.
p <id> Display the content of an object. | [
"\\",
"Display",
"symbols",
".",
"p",
"Display",
"names",
"of",
"inspectable",
"objects",
".",
"p",
"<id",
">",
"Display",
"the",
"content",
"of",
"an",
"object",
"."
] | train | https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/debugging_shell.py#L36-L53 |
qzmfranklin/easyshell | easyshell/debugging_shell.py | DebuggingShell._do_eval | def _do_eval(self, cmd, args):
"""\
Evaluate python code.
e <expr> Evaluate <expr>.
"""
code = args[0].lstrip()
if not code:
self.stderr.write('e: cannot evalutate empty expression\n')
return
try:
eval(code)
e... | python | def _do_eval(self, cmd, args):
"""\
Evaluate python code.
e <expr> Evaluate <expr>.
"""
code = args[0].lstrip()
if not code:
self.stderr.write('e: cannot evalutate empty expression\n')
return
try:
eval(code)
e... | [
"def",
"_do_eval",
"(",
"self",
",",
"cmd",
",",
"args",
")",
":",
"code",
"=",
"args",
"[",
"0",
"]",
".",
"lstrip",
"(",
")",
"if",
"not",
"code",
":",
"self",
".",
"stderr",
".",
"write",
"(",
"'e: cannot evalutate empty expression\\n'",
")",
"retur... | \
Evaluate python code.
e <expr> Evaluate <expr>. | [
"\\",
"Evaluate",
"python",
"code",
".",
"e",
"<expr",
">",
"Evaluate",
"<expr",
">",
"."
] | train | https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/debugging_shell.py#L59-L72 |
qzmfranklin/easyshell | easyshell/debugging_shell.py | DebuggingShell.parse_line | def parse_line(self, line):
"""Parser for the debugging shell.
Treat everything after the first token as one literal entity. Whitespace
characters between the first token and the next first non-whitespace
character are preserved.
For example, ' foo dicj didiw ' is parsed as... | python | def parse_line(self, line):
"""Parser for the debugging shell.
Treat everything after the first token as one literal entity. Whitespace
characters between the first token and the next first non-whitespace
character are preserved.
For example, ' foo dicj didiw ' is parsed as... | [
"def",
"parse_line",
"(",
"self",
",",
"line",
")",
":",
"line",
"=",
"line",
".",
"lstrip",
"(",
")",
"toks",
"=",
"shlex",
".",
"split",
"(",
"line",
")",
"cmd",
"=",
"toks",
"[",
"0",
"]",
"arg",
"=",
"line",
"[",
"len",
"(",
"cmd",
")",
"... | Parser for the debugging shell.
Treat everything after the first token as one literal entity. Whitespace
characters between the first token and the next first non-whitespace
character are preserved.
For example, ' foo dicj didiw ' is parsed as
( 'foo', ' dicj didiw '... | [
"Parser",
"for",
"the",
"debugging",
"shell",
"."
] | train | https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/debugging_shell.py#L75-L93 |
yv/pathconfig | py_src/pathconfig/factory.py | Factory.bind | def bind(self, **kwargs):
'''
creates a copy of the object without the
cached results and with the given keyword
arguments as properties.
'''
d = dict(self.__dict__)
for k in d.keys():
if k[0] == '_':
del d[k]
elif k.startsw... | python | def bind(self, **kwargs):
'''
creates a copy of the object without the
cached results and with the given keyword
arguments as properties.
'''
d = dict(self.__dict__)
for k in d.keys():
if k[0] == '_':
del d[k]
elif k.startsw... | [
"def",
"bind",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"d",
"=",
"dict",
"(",
"self",
".",
"__dict__",
")",
"for",
"k",
"in",
"d",
".",
"keys",
"(",
")",
":",
"if",
"k",
"[",
"0",
"]",
"==",
"'_'",
":",
"del",
"d",
"[",
"k",
"]",
... | creates a copy of the object without the
cached results and with the given keyword
arguments as properties. | [
"creates",
"a",
"copy",
"of",
"the",
"object",
"without",
"the",
"cached",
"results",
"and",
"with",
"the",
"given",
"keyword",
"arguments",
"as",
"properties",
"."
] | train | https://github.com/yv/pathconfig/blob/ae13901773b8465061e2aa93b2a53fd436ab6c69/py_src/pathconfig/factory.py#L74-L87 |
yv/pathconfig | py_src/pathconfig/factory.py | Factory.get | def get(self, name, *subkey):
"""
retrieves a data item, or loads it if it
is not present.
"""
if subkey == []:
return self.get_atomic(name)
else:
return self.get_subkey(name, tuple(subkey)) | python | def get(self, name, *subkey):
"""
retrieves a data item, or loads it if it
is not present.
"""
if subkey == []:
return self.get_atomic(name)
else:
return self.get_subkey(name, tuple(subkey)) | [
"def",
"get",
"(",
"self",
",",
"name",
",",
"*",
"subkey",
")",
":",
"if",
"subkey",
"==",
"[",
"]",
":",
"return",
"self",
".",
"get_atomic",
"(",
"name",
")",
"else",
":",
"return",
"self",
".",
"get_subkey",
"(",
"name",
",",
"tuple",
"(",
"s... | retrieves a data item, or loads it if it
is not present. | [
"retrieves",
"a",
"data",
"item",
"or",
"loads",
"it",
"if",
"it",
"is",
"not",
"present",
"."
] | train | https://github.com/yv/pathconfig/blob/ae13901773b8465061e2aa93b2a53fd436ab6c69/py_src/pathconfig/factory.py#L89-L97 |
yv/pathconfig | py_src/pathconfig/factory.py | Factory.val | def val(self, name):
"""
retrieves a value, substituting actual
values for ConfigValue templates.
"""
v = getattr(self, name)
if hasattr(v, 'retrieve_value'):
v = v.retrieve_value(self.__dict__)
return v | python | def val(self, name):
"""
retrieves a value, substituting actual
values for ConfigValue templates.
"""
v = getattr(self, name)
if hasattr(v, 'retrieve_value'):
v = v.retrieve_value(self.__dict__)
return v | [
"def",
"val",
"(",
"self",
",",
"name",
")",
":",
"v",
"=",
"getattr",
"(",
"self",
",",
"name",
")",
"if",
"hasattr",
"(",
"v",
",",
"'retrieve_value'",
")",
":",
"v",
"=",
"v",
".",
"retrieve_value",
"(",
"self",
".",
"__dict__",
")",
"return",
... | retrieves a value, substituting actual
values for ConfigValue templates. | [
"retrieves",
"a",
"value",
"substituting",
"actual",
"values",
"for",
"ConfigValue",
"templates",
"."
] | train | https://github.com/yv/pathconfig/blob/ae13901773b8465061e2aa93b2a53fd436ab6c69/py_src/pathconfig/factory.py#L99-L107 |
yv/pathconfig | py_src/pathconfig/factory.py | Factory.open_by_pat | def open_by_pat(self, name, mode='r', **kwargs):
'''
opens the file for the pattern given by *name*,
substituting the object's properties and the
additional keyword arguments given.
'''
fname = self.fname_by_pat(name, **kwargs)
if mode == 'w':
print >>... | python | def open_by_pat(self, name, mode='r', **kwargs):
'''
opens the file for the pattern given by *name*,
substituting the object's properties and the
additional keyword arguments given.
'''
fname = self.fname_by_pat(name, **kwargs)
if mode == 'w':
print >>... | [
"def",
"open_by_pat",
"(",
"self",
",",
"name",
",",
"mode",
"=",
"'r'",
",",
"*",
"*",
"kwargs",
")",
":",
"fname",
"=",
"self",
".",
"fname_by_pat",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
"if",
"mode",
"==",
"'w'",
":",
"print",
">>",
"sys"... | opens the file for the pattern given by *name*,
substituting the object's properties and the
additional keyword arguments given. | [
"opens",
"the",
"file",
"for",
"the",
"pattern",
"given",
"by",
"*",
"name",
"*",
"substituting",
"the",
"object",
"s",
"properties",
"and",
"the",
"additional",
"keyword",
"arguments",
"given",
"."
] | train | https://github.com/yv/pathconfig/blob/ae13901773b8465061e2aa93b2a53fd436ab6c69/py_src/pathconfig/factory.py#L132-L143 |
lsst-sqre/zenodio | zenodio/harvest.py | harvest_collection | def harvest_collection(community_name):
"""Harvest a Zenodo community's record metadata.
Examples
--------
You can harvest record metadata for a Zenodo community via its identifier
name. For example, the identifier for LSST Data Management's Zenodo
collection is ``'lsst-dm'``:
>>> import z... | python | def harvest_collection(community_name):
"""Harvest a Zenodo community's record metadata.
Examples
--------
You can harvest record metadata for a Zenodo community via its identifier
name. For example, the identifier for LSST Data Management's Zenodo
collection is ``'lsst-dm'``:
>>> import z... | [
"def",
"harvest_collection",
"(",
"community_name",
")",
":",
"url",
"=",
"zenodo_harvest_url",
"(",
"community_name",
")",
"r",
"=",
"requests",
".",
"get",
"(",
"url",
")",
"r",
".",
"status_code",
"xml_content",
"=",
"r",
".",
"content",
"return",
"Dataci... | Harvest a Zenodo community's record metadata.
Examples
--------
You can harvest record metadata for a Zenodo community via its identifier
name. For example, the identifier for LSST Data Management's Zenodo
collection is ``'lsst-dm'``:
>>> import zenodio.harvest import harvest_collection
>>... | [
"Harvest",
"a",
"Zenodo",
"community",
"s",
"record",
"metadata",
"."
] | train | https://github.com/lsst-sqre/zenodio/blob/24283e84bee5714450e4f206ec024c4d32f2e761/zenodio/harvest.py#L28-L61 |
lsst-sqre/zenodio | zenodio/harvest.py | zenodo_harvest_url | def zenodo_harvest_url(community_name, format='oai_datacite3'):
"""Build a URL for the Zenodo Community's metadata.
Parameters
----------
community_name : str
Zenodo community identifier.
format : str
OAI-PMH metadata specification name. See https://zenodo.org/dev.
Currently... | python | def zenodo_harvest_url(community_name, format='oai_datacite3'):
"""Build a URL for the Zenodo Community's metadata.
Parameters
----------
community_name : str
Zenodo community identifier.
format : str
OAI-PMH metadata specification name. See https://zenodo.org/dev.
Currently... | [
"def",
"zenodo_harvest_url",
"(",
"community_name",
",",
"format",
"=",
"'oai_datacite3'",
")",
":",
"template",
"=",
"'http://zenodo.org/oai2d?verb=ListRecords&'",
"'metadataPrefix={metadata_format}&set=user-{community}'",
"return",
"template",
".",
"format",
"(",
"metadata_fo... | Build a URL for the Zenodo Community's metadata.
Parameters
----------
community_name : str
Zenodo community identifier.
format : str
OAI-PMH metadata specification name. See https://zenodo.org/dev.
Currently on ``oai_datacite3`` is supported.
Returns
-------
url : ... | [
"Build",
"a",
"URL",
"for",
"the",
"Zenodo",
"Community",
"s",
"metadata",
"."
] | train | https://github.com/lsst-sqre/zenodio/blob/24283e84bee5714450e4f206ec024c4d32f2e761/zenodio/harvest.py#L64-L83 |
lsst-sqre/zenodio | zenodio/harvest.py | _pluralize | def _pluralize(value, item_key):
""""Force the value of a datacite3 key to be a list.
>>> _pluralize(xml_input['authors'], 'author')
['Sick, Jonathan', 'Economou, Frossie']
Background
----------
When `xmltodict` proceses metadata, it turns XML tags into new key-value
pairs whenever possibl... | python | def _pluralize(value, item_key):
""""Force the value of a datacite3 key to be a list.
>>> _pluralize(xml_input['authors'], 'author')
['Sick, Jonathan', 'Economou, Frossie']
Background
----------
When `xmltodict` proceses metadata, it turns XML tags into new key-value
pairs whenever possibl... | [
"def",
"_pluralize",
"(",
"value",
",",
"item_key",
")",
":",
"v",
"=",
"value",
"[",
"item_key",
"]",
"if",
"not",
"isinstance",
"(",
"v",
",",
"list",
")",
":",
"# Force a singular value to be a list",
"return",
"[",
"v",
"]",
"else",
":",
"return",
"v... | Force the value of a datacite3 key to be a list.
>>> _pluralize(xml_input['authors'], 'author')
['Sick, Jonathan', 'Economou, Frossie']
Background
----------
When `xmltodict` proceses metadata, it turns XML tags into new key-value
pairs whenever possible, even if the value should semantically ... | [
"Force",
"the",
"value",
"of",
"a",
"datacite3",
"key",
"to",
"be",
"a",
"list",
"."
] | train | https://github.com/lsst-sqre/zenodio/blob/24283e84bee5714450e4f206ec024c4d32f2e761/zenodio/harvest.py#L258-L317 |
lsst-sqre/zenodio | zenodio/harvest.py | Datacite3Collection.from_collection_xml | def from_collection_xml(cls, xml_content):
"""Build a :class:`~zenodio.harvest.Datacite3Collection` from
Datecite3-formatted XML.
Users should use :func:`zenodio.harvest.harvest_collection` to build a
:class:`~zenodio.harvest.Datacite3Collection` for a Community.
Parameters
... | python | def from_collection_xml(cls, xml_content):
"""Build a :class:`~zenodio.harvest.Datacite3Collection` from
Datecite3-formatted XML.
Users should use :func:`zenodio.harvest.harvest_collection` to build a
:class:`~zenodio.harvest.Datacite3Collection` for a Community.
Parameters
... | [
"def",
"from_collection_xml",
"(",
"cls",
",",
"xml_content",
")",
":",
"xml_dataset",
"=",
"xmltodict",
".",
"parse",
"(",
"xml_content",
",",
"process_namespaces",
"=",
"False",
")",
"# Unwrap the record list when harvesting a collection's datacite 3",
"xml_records",
"=... | Build a :class:`~zenodio.harvest.Datacite3Collection` from
Datecite3-formatted XML.
Users should use :func:`zenodio.harvest.harvest_collection` to build a
:class:`~zenodio.harvest.Datacite3Collection` for a Community.
Parameters
----------
xml_content : str
... | [
"Build",
"a",
":",
"class",
":",
"~zenodio",
".",
"harvest",
".",
"Datacite3Collection",
"from",
"Datecite3",
"-",
"formatted",
"XML",
"."
] | train | https://github.com/lsst-sqre/zenodio/blob/24283e84bee5714450e4f206ec024c4d32f2e761/zenodio/harvest.py#L101-L121 |
lsst-sqre/zenodio | zenodio/harvest.py | Datacite3Record.authors | def authors(self):
"""List of :class:`~zenodio.harvest.Author`\ s
(:class:`zenodio.harvest.Author`).
Authors correspond to `creators` in the Datacite schema.
"""
creators = _pluralize(self._r['creators'], 'creator')
authors = [Author.from_xmldict(c) for c in creators]
... | python | def authors(self):
"""List of :class:`~zenodio.harvest.Author`\ s
(:class:`zenodio.harvest.Author`).
Authors correspond to `creators` in the Datacite schema.
"""
creators = _pluralize(self._r['creators'], 'creator')
authors = [Author.from_xmldict(c) for c in creators]
... | [
"def",
"authors",
"(",
"self",
")",
":",
"creators",
"=",
"_pluralize",
"(",
"self",
".",
"_r",
"[",
"'creators'",
"]",
",",
"'creator'",
")",
"authors",
"=",
"[",
"Author",
".",
"from_xmldict",
"(",
"c",
")",
"for",
"c",
"in",
"creators",
"]",
"retu... | List of :class:`~zenodio.harvest.Author`\ s
(:class:`zenodio.harvest.Author`).
Authors correspond to `creators` in the Datacite schema. | [
"List",
"of",
":",
"class",
":",
"~zenodio",
".",
"harvest",
".",
"Author",
"\\",
"s",
"(",
":",
"class",
":",
"zenodio",
".",
"harvest",
".",
"Author",
")",
"."
] | train | https://github.com/lsst-sqre/zenodio/blob/24283e84bee5714450e4f206ec024c4d32f2e761/zenodio/harvest.py#L156-L164 |
lsst-sqre/zenodio | zenodio/harvest.py | Datacite3Record.abstract_html | def abstract_html(self):
"""Abstract text, marked up with HTML (`str`)."""
descriptions = _pluralize(self._r['descriptions'], 'description')
for desc in descriptions:
if desc['@descriptionType'] == 'Abstract':
return desc['#text'] | python | def abstract_html(self):
"""Abstract text, marked up with HTML (`str`)."""
descriptions = _pluralize(self._r['descriptions'], 'description')
for desc in descriptions:
if desc['@descriptionType'] == 'Abstract':
return desc['#text'] | [
"def",
"abstract_html",
"(",
"self",
")",
":",
"descriptions",
"=",
"_pluralize",
"(",
"self",
".",
"_r",
"[",
"'descriptions'",
"]",
",",
"'description'",
")",
"for",
"desc",
"in",
"descriptions",
":",
"if",
"desc",
"[",
"'@descriptionType'",
"]",
"==",
"... | Abstract text, marked up with HTML (`str`). | [
"Abstract",
"text",
"marked",
"up",
"with",
"HTML",
"(",
"str",
")",
"."
] | train | https://github.com/lsst-sqre/zenodio/blob/24283e84bee5714450e4f206ec024c4d32f2e761/zenodio/harvest.py#L180-L185 |
lsst-sqre/zenodio | zenodio/harvest.py | Datacite3Record.issue_date | def issue_date(self):
"""Date when the DOI was issued (:class:`datetime.datetime.Datetime`).
"""
dates = _pluralize(self._r['dates'], 'date')
for date in dates:
if date['@dateType'] == 'Issued':
return datetime.datetime.strptime(date['#text'], '%Y-%m-%d') | python | def issue_date(self):
"""Date when the DOI was issued (:class:`datetime.datetime.Datetime`).
"""
dates = _pluralize(self._r['dates'], 'date')
for date in dates:
if date['@dateType'] == 'Issued':
return datetime.datetime.strptime(date['#text'], '%Y-%m-%d') | [
"def",
"issue_date",
"(",
"self",
")",
":",
"dates",
"=",
"_pluralize",
"(",
"self",
".",
"_r",
"[",
"'dates'",
"]",
",",
"'date'",
")",
"for",
"date",
"in",
"dates",
":",
"if",
"date",
"[",
"'@dateType'",
"]",
"==",
"'Issued'",
":",
"return",
"datet... | Date when the DOI was issued (:class:`datetime.datetime.Datetime`). | [
"Date",
"when",
"the",
"DOI",
"was",
"issued",
"(",
":",
"class",
":",
"datetime",
".",
"datetime",
".",
"Datetime",
")",
"."
] | train | https://github.com/lsst-sqre/zenodio/blob/24283e84bee5714450e4f206ec024c4d32f2e761/zenodio/harvest.py#L188-L194 |
lsst-sqre/zenodio | zenodio/harvest.py | Author.from_xmldict | def from_xmldict(cls, xml_dict):
"""Create an `Author` from a datacite3 metadata converted by
`xmltodict`.
Parameters
----------
xml_dict : :class:`collections.OrderedDict`
A `dict`-like object mapping XML content for a single record (i.e.,
the contents o... | python | def from_xmldict(cls, xml_dict):
"""Create an `Author` from a datacite3 metadata converted by
`xmltodict`.
Parameters
----------
xml_dict : :class:`collections.OrderedDict`
A `dict`-like object mapping XML content for a single record (i.e.,
the contents o... | [
"def",
"from_xmldict",
"(",
"cls",
",",
"xml_dict",
")",
":",
"name",
"=",
"xml_dict",
"[",
"'creatorName'",
"]",
"kwargs",
"=",
"{",
"}",
"if",
"'affiliation'",
"in",
"xml_dict",
":",
"kwargs",
"[",
"'affiliation'",
"]",
"=",
"xml_dict",
"[",
"'affiliatio... | Create an `Author` from a datacite3 metadata converted by
`xmltodict`.
Parameters
----------
xml_dict : :class:`collections.OrderedDict`
A `dict`-like object mapping XML content for a single record (i.e.,
the contents of the ``record`` tag in OAI-PMH XML). This d... | [
"Create",
"an",
"Author",
"from",
"a",
"datacite3",
"metadata",
"converted",
"by",
"xmltodict",
"."
] | train | https://github.com/lsst-sqre/zenodio/blob/24283e84bee5714450e4f206ec024c4d32f2e761/zenodio/harvest.py#L228-L245 |
lbusoni/plico | plico/utils/zernike_generator.py | ZernikeGenerator.getZernike | def getZernike(self, index):
"""getZernike
Retrieve a map representing the index-th Zernike polynomial
Args:
index (int): The index of Zernike map to be generated,
following Noll 1976 ordering.
Returns:
np.array: A map representing the index-th ... | python | def getZernike(self, index):
"""getZernike
Retrieve a map representing the index-th Zernike polynomial
Args:
index (int): The index of Zernike map to be generated,
following Noll 1976 ordering.
Returns:
np.array: A map representing the index-th ... | [
"def",
"getZernike",
"(",
"self",
",",
"index",
")",
":",
"if",
"index",
"not",
"in",
"list",
"(",
"self",
".",
"_dictCache",
".",
"keys",
"(",
")",
")",
":",
"self",
".",
"_dictCache",
"[",
"index",
"]",
"=",
"self",
".",
"_polar",
"(",
"index",
... | getZernike
Retrieve a map representing the index-th Zernike polynomial
Args:
index (int): The index of Zernike map to be generated,
following Noll 1976 ordering.
Returns:
np.array: A map representing the index-th Zernike polynomial | [
"getZernike"
] | train | https://github.com/lbusoni/plico/blob/08a29da8f06e920470516838878a51ac83bab847/plico/utils/zernike_generator.py#L126-L142 |
minhhoit/yacms | yacms/core/managers.py | search_fields_to_dict | def search_fields_to_dict(fields):
"""
In ``SearchableQuerySet`` and ``SearchableManager``, search fields
can either be a sequence, or a dict of fields mapped to weights.
This function converts sequences to a dict mapped to even weights,
so that we're consistently dealing with a dict of fields mappe... | python | def search_fields_to_dict(fields):
"""
In ``SearchableQuerySet`` and ``SearchableManager``, search fields
can either be a sequence, or a dict of fields mapped to weights.
This function converts sequences to a dict mapped to even weights,
so that we're consistently dealing with a dict of fields mappe... | [
"def",
"search_fields_to_dict",
"(",
"fields",
")",
":",
"if",
"not",
"fields",
":",
"return",
"{",
"}",
"try",
":",
"int",
"(",
"list",
"(",
"dict",
"(",
"fields",
")",
".",
"values",
"(",
")",
")",
"[",
"0",
"]",
")",
"except",
"(",
"TypeError",
... | In ``SearchableQuerySet`` and ``SearchableManager``, search fields
can either be a sequence, or a dict of fields mapped to weights.
This function converts sequences to a dict mapped to even weights,
so that we're consistently dealing with a dict of fields mapped to
weights, eg: ("title", "content") -> {... | [
"In",
"SearchableQuerySet",
"and",
"SearchableManager",
"search",
"fields",
"can",
"either",
"be",
"a",
"sequence",
"or",
"a",
"dict",
"of",
"fields",
"mapped",
"to",
"weights",
".",
"This",
"function",
"converts",
"sequences",
"to",
"a",
"dict",
"mapped",
"to... | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/managers.py#L76-L90 |
minhhoit/yacms | yacms/core/managers.py | PublishedManager.published | def published(self, for_user=None):
"""
For non-staff users, return items with a published status and
whose publish and expiry dates fall before and after the
current date when specified.
"""
from yacms.core.models import CONTENT_STATUS_PUBLISHED
if for_user is no... | python | def published(self, for_user=None):
"""
For non-staff users, return items with a published status and
whose publish and expiry dates fall before and after the
current date when specified.
"""
from yacms.core.models import CONTENT_STATUS_PUBLISHED
if for_user is no... | [
"def",
"published",
"(",
"self",
",",
"for_user",
"=",
"None",
")",
":",
"from",
"yacms",
".",
"core",
".",
"models",
"import",
"CONTENT_STATUS_PUBLISHED",
"if",
"for_user",
"is",
"not",
"None",
"and",
"for_user",
".",
"is_staff",
":",
"return",
"self",
".... | For non-staff users, return items with a published status and
whose publish and expiry dates fall before and after the
current date when specified. | [
"For",
"non",
"-",
"staff",
"users",
"return",
"items",
"with",
"a",
"published",
"status",
"and",
"whose",
"publish",
"and",
"expiry",
"dates",
"fall",
"before",
"and",
"after",
"the",
"current",
"date",
"when",
"specified",
"."
] | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/managers.py#L58-L70 |
minhhoit/yacms | yacms/core/managers.py | SearchableQuerySet.search | def search(self, query, search_fields=None):
"""
Build a queryset matching words in the given search query,
treating quoted terms as exact phrases and taking into
account + and - symbols as modifiers controlling which terms
to require and exclude.
"""
# ### DETER... | python | def search(self, query, search_fields=None):
"""
Build a queryset matching words in the given search query,
treating quoted terms as exact phrases and taking into
account + and - symbols as modifiers controlling which terms
to require and exclude.
"""
# ### DETER... | [
"def",
"search",
"(",
"self",
",",
"query",
",",
"search_fields",
"=",
"None",
")",
":",
"# ### DETERMINE FIELDS TO SEARCH ###",
"# Use search_fields arg if given, otherwise use search_fields",
"# initially configured by the manager class.",
"if",
"search_fields",
":",
"self",
... | Build a queryset matching words in the given search query,
treating quoted terms as exact phrases and taking into
account + and - symbols as modifiers controlling which terms
to require and exclude. | [
"Build",
"a",
"queryset",
"matching",
"words",
"in",
"the",
"given",
"search",
"query",
"treating",
"quoted",
"terms",
"as",
"exact",
"phrases",
"and",
"taking",
"into",
"account",
"+",
"and",
"-",
"symbols",
"as",
"modifiers",
"controlling",
"which",
"terms",... | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/managers.py#L105-L172 |
minhhoit/yacms | yacms/core/managers.py | SearchableQuerySet._clone | def _clone(self, *args, **kwargs):
"""
Ensure attributes are copied to subsequent queries.
"""
for attr in ("_search_terms", "_search_fields", "_search_ordered"):
kwargs[attr] = getattr(self, attr)
return super(SearchableQuerySet, self)._clone(*args, **kwargs) | python | def _clone(self, *args, **kwargs):
"""
Ensure attributes are copied to subsequent queries.
"""
for attr in ("_search_terms", "_search_fields", "_search_ordered"):
kwargs[attr] = getattr(self, attr)
return super(SearchableQuerySet, self)._clone(*args, **kwargs) | [
"def",
"_clone",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"attr",
"in",
"(",
"\"_search_terms\"",
",",
"\"_search_fields\"",
",",
"\"_search_ordered\"",
")",
":",
"kwargs",
"[",
"attr",
"]",
"=",
"getattr",
"(",
"self",
... | Ensure attributes are copied to subsequent queries. | [
"Ensure",
"attributes",
"are",
"copied",
"to",
"subsequent",
"queries",
"."
] | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/managers.py#L174-L180 |
minhhoit/yacms | yacms/core/managers.py | SearchableQuerySet.order_by | def order_by(self, *field_names):
"""
Mark the filter as being ordered if search has occurred.
"""
if not self._search_ordered:
self._search_ordered = len(self._search_terms) > 0
return super(SearchableQuerySet, self).order_by(*field_names) | python | def order_by(self, *field_names):
"""
Mark the filter as being ordered if search has occurred.
"""
if not self._search_ordered:
self._search_ordered = len(self._search_terms) > 0
return super(SearchableQuerySet, self).order_by(*field_names) | [
"def",
"order_by",
"(",
"self",
",",
"*",
"field_names",
")",
":",
"if",
"not",
"self",
".",
"_search_ordered",
":",
"self",
".",
"_search_ordered",
"=",
"len",
"(",
"self",
".",
"_search_terms",
")",
">",
"0",
"return",
"super",
"(",
"SearchableQuerySet",... | Mark the filter as being ordered if search has occurred. | [
"Mark",
"the",
"filter",
"as",
"being",
"ordered",
"if",
"search",
"has",
"occurred",
"."
] | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/managers.py#L182-L188 |
minhhoit/yacms | yacms/core/managers.py | SearchableQuerySet.iterator | def iterator(self):
"""
If search has occurred and no ordering has occurred, decorate
each result with the number of search terms so that it can be
sorted by the number of occurrence of terms.
In the case of search fields that span model relationships, we
cannot accurate... | python | def iterator(self):
"""
If search has occurred and no ordering has occurred, decorate
each result with the number of search terms so that it can be
sorted by the number of occurrence of terms.
In the case of search fields that span model relationships, we
cannot accurate... | [
"def",
"iterator",
"(",
"self",
")",
":",
"results",
"=",
"super",
"(",
"SearchableQuerySet",
",",
"self",
")",
".",
"iterator",
"(",
")",
"if",
"self",
".",
"_search_terms",
"and",
"not",
"self",
".",
"_search_ordered",
":",
"results",
"=",
"list",
"(",... | If search has occurred and no ordering has occurred, decorate
each result with the number of search terms so that it can be
sorted by the number of occurrence of terms.
In the case of search fields that span model relationships, we
cannot accurately match occurrences without some very
... | [
"If",
"search",
"has",
"occurred",
"and",
"no",
"ordering",
"has",
"occurred",
"decorate",
"each",
"result",
"with",
"the",
"number",
"of",
"search",
"terms",
"so",
"that",
"it",
"can",
"be",
"sorted",
"by",
"the",
"number",
"of",
"occurrence",
"of",
"term... | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/managers.py#L190-L221 |
minhhoit/yacms | yacms/core/managers.py | SearchableManager.get_search_fields | def get_search_fields(self):
"""
Returns the search field names mapped to weights as a dict.
Used in ``get_queryset`` below to tell ``SearchableQuerySet``
which search fields to use. Also used by ``DisplayableAdmin``
to populate Django admin's ``search_fields`` attribute.
... | python | def get_search_fields(self):
"""
Returns the search field names mapped to weights as a dict.
Used in ``get_queryset`` below to tell ``SearchableQuerySet``
which search fields to use. Also used by ``DisplayableAdmin``
to populate Django admin's ``search_fields`` attribute.
... | [
"def",
"get_search_fields",
"(",
"self",
")",
":",
"search_fields",
"=",
"self",
".",
"_search_fields",
".",
"copy",
"(",
")",
"if",
"not",
"search_fields",
":",
"for",
"cls",
"in",
"reversed",
"(",
"self",
".",
"model",
".",
"__mro__",
")",
":",
"super_... | Returns the search field names mapped to weights as a dict.
Used in ``get_queryset`` below to tell ``SearchableQuerySet``
which search fields to use. Also used by ``DisplayableAdmin``
to populate Django admin's ``search_fields`` attribute.
Search fields can be populated via
``Se... | [
"Returns",
"the",
"search",
"field",
"names",
"mapped",
"to",
"weights",
"as",
"a",
"dict",
".",
"Used",
"in",
"get_queryset",
"below",
"to",
"tell",
"SearchableQuerySet",
"which",
"search",
"fields",
"to",
"use",
".",
"Also",
"used",
"by",
"DisplayableAdmin",... | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/managers.py#L236-L269 |
minhhoit/yacms | yacms/core/managers.py | SearchableManager.contribute_to_class | def contribute_to_class(self, model, name):
"""
Newer versions of Django explicitly prevent managers being
accessed from abstract classes, which is behaviour the search
API has always relied on. Here we reinstate it.
"""
super(SearchableManager, self).contribute_to_class(... | python | def contribute_to_class(self, model, name):
"""
Newer versions of Django explicitly prevent managers being
accessed from abstract classes, which is behaviour the search
API has always relied on. Here we reinstate it.
"""
super(SearchableManager, self).contribute_to_class(... | [
"def",
"contribute_to_class",
"(",
"self",
",",
"model",
",",
"name",
")",
":",
"super",
"(",
"SearchableManager",
",",
"self",
")",
".",
"contribute_to_class",
"(",
"model",
",",
"name",
")",
"setattr",
"(",
"model",
",",
"name",
",",
"ManagerDescriptor",
... | Newer versions of Django explicitly prevent managers being
accessed from abstract classes, which is behaviour the search
API has always relied on. Here we reinstate it. | [
"Newer",
"versions",
"of",
"Django",
"explicitly",
"prevent",
"managers",
"being",
"accessed",
"from",
"abstract",
"classes",
"which",
"is",
"behaviour",
"the",
"search",
"API",
"has",
"always",
"relied",
"on",
".",
"Here",
"we",
"reinstate",
"it",
"."
] | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/managers.py#L275-L282 |
minhhoit/yacms | yacms/core/managers.py | SearchableManager.search | def search(self, *args, **kwargs):
"""
Proxy to queryset's search method for the manager's model and
any models that subclass from this manager's model if the
model is abstract.
"""
if not settings.SEARCH_MODEL_CHOICES:
# No choices defined - build a list of l... | python | def search(self, *args, **kwargs):
"""
Proxy to queryset's search method for the manager's model and
any models that subclass from this manager's model if the
model is abstract.
"""
if not settings.SEARCH_MODEL_CHOICES:
# No choices defined - build a list of l... | [
"def",
"search",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"settings",
".",
"SEARCH_MODEL_CHOICES",
":",
"# No choices defined - build a list of leaf models (those",
"# without subclasses) that inherit from Displayable.",
"models",
"="... | Proxy to queryset's search method for the manager's model and
any models that subclass from this manager's model if the
model is abstract. | [
"Proxy",
"to",
"queryset",
"s",
"search",
"method",
"for",
"the",
"manager",
"s",
"model",
"and",
"any",
"models",
"that",
"subclass",
"from",
"this",
"manager",
"s",
"model",
"if",
"the",
"model",
"is",
"abstract",
"."
] | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/managers.py#L284-L355 |
minhhoit/yacms | yacms/core/managers.py | DisplayableManager.url_map | def url_map(self, for_user=None, **kwargs):
"""
Returns a dictionary of urls mapped to Displayable subclass
instances, including a fake homepage instance if none exists.
Used in ``yacms.core.sitemaps``.
"""
class Home:
title = _("Home")
home = Home()
... | python | def url_map(self, for_user=None, **kwargs):
"""
Returns a dictionary of urls mapped to Displayable subclass
instances, including a fake homepage instance if none exists.
Used in ``yacms.core.sitemaps``.
"""
class Home:
title = _("Home")
home = Home()
... | [
"def",
"url_map",
"(",
"self",
",",
"for_user",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"class",
"Home",
":",
"title",
"=",
"_",
"(",
"\"Home\"",
")",
"home",
"=",
"Home",
"(",
")",
"setattr",
"(",
"home",
",",
"\"get_absolute_url\"",
",",
... | Returns a dictionary of urls mapped to Displayable subclass
instances, including a fake homepage instance if none exists.
Used in ``yacms.core.sitemaps``. | [
"Returns",
"a",
"dictionary",
"of",
"urls",
"mapped",
"to",
"Displayable",
"subclass",
"instances",
"including",
"a",
"fake",
"homepage",
"instance",
"if",
"none",
"exists",
".",
"Used",
"in",
"yacms",
".",
"core",
".",
"sitemaps",
"."
] | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/managers.py#L390-L408 |
vecnet/vecnet.simulation | vecnet/simulation/sim_model.py | get_name | def get_name(model_id):
"""
Get the name for a model.
:returns str: The model's name. If the id has no associated name, then "id = {ID} (no name)" is returned.
"""
name = _names.get(model_id)
if name is None:
name = 'id = %s (no name)' % str(model_id)
return name | python | def get_name(model_id):
"""
Get the name for a model.
:returns str: The model's name. If the id has no associated name, then "id = {ID} (no name)" is returned.
"""
name = _names.get(model_id)
if name is None:
name = 'id = %s (no name)' % str(model_id)
return name | [
"def",
"get_name",
"(",
"model_id",
")",
":",
"name",
"=",
"_names",
".",
"get",
"(",
"model_id",
")",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"'id = %s (no name)'",
"%",
"str",
"(",
"model_id",
")",
"return",
"name"
] | Get the name for a model.
:returns str: The model's name. If the id has no associated name, then "id = {ID} (no name)" is returned. | [
"Get",
"the",
"name",
"for",
"a",
"model",
"."
] | train | https://github.com/vecnet/vecnet.simulation/blob/3a4b3df7b12418c6fa8a7d9cd49656a1c031fc0e/vecnet/simulation/sim_model.py#L51-L60 |
eisensheng/kaviar | kaviar/adapter.py | KvLoggerAdapter.get_logger | def get_logger(cls, *name, **kwargs):
"""Construct a new :class:`KvLoggerAdapter` which encapsulates
the :class:`logging.Logger` specified by ``name``.
:param name:
Any amount of symbols. Will be concatenated and normalized
to form the logger name. Can also be empty.
... | python | def get_logger(cls, *name, **kwargs):
"""Construct a new :class:`KvLoggerAdapter` which encapsulates
the :class:`logging.Logger` specified by ``name``.
:param name:
Any amount of symbols. Will be concatenated and normalized
to form the logger name. Can also be empty.
... | [
"def",
"get_logger",
"(",
"cls",
",",
"*",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"cls",
"(",
"getLogger",
"(",
"_normalize_name",
"(",
"name",
")",
")",
",",
"kwargs",
".",
"get",
"(",
"'extra'",
",",
"None",
")",
")"
] | Construct a new :class:`KvLoggerAdapter` which encapsulates
the :class:`logging.Logger` specified by ``name``.
:param name:
Any amount of symbols. Will be concatenated and normalized
to form the logger name. Can also be empty.
:param extra:
Additional conte... | [
"Construct",
"a",
"new",
":",
"class",
":",
"KvLoggerAdapter",
"which",
"encapsulates",
"the",
":",
"class",
":",
"logging",
".",
"Logger",
"specified",
"by",
"name",
"."
] | train | https://github.com/eisensheng/kaviar/blob/77ab934a3dd7b1cfabc0ec96acc0b8ed26edcb3f/kaviar/adapter.py#L54-L69 |
eisensheng/kaviar | kaviar/adapter.py | KvLoggerAdapter.define_logger_func | def define_logger_func(self, level, field_names, default=NO_DEFAULT,
filters=None, include_exc_info=False):
"""Define a new logger function that will log the given arguments
with the given predefined keys.
:param level:
The log level to use for each call.
... | python | def define_logger_func(self, level, field_names, default=NO_DEFAULT,
filters=None, include_exc_info=False):
"""Define a new logger function that will log the given arguments
with the given predefined keys.
:param level:
The log level to use for each call.
... | [
"def",
"define_logger_func",
"(",
"self",
",",
"level",
",",
"field_names",
",",
"default",
"=",
"NO_DEFAULT",
",",
"filters",
"=",
"None",
",",
"include_exc_info",
"=",
"False",
")",
":",
"kv_formatter",
"=",
"KvFormatter",
"(",
"field_names",
",",
"default",... | Define a new logger function that will log the given arguments
with the given predefined keys.
:param level:
The log level to use for each call.
:param field_names:
Set of predefined keys.
:param default:
A default value for each key.
:param f... | [
"Define",
"a",
"new",
"logger",
"function",
"that",
"will",
"log",
"the",
"given",
"arguments",
"with",
"the",
"given",
"predefined",
"keys",
"."
] | train | https://github.com/eisensheng/kaviar/blob/77ab934a3dd7b1cfabc0ec96acc0b8ed26edcb3f/kaviar/adapter.py#L71-L93 |
eisensheng/kaviar | kaviar/adapter.py | KvLoggerAdapter.log | def log(self, level, *args, **kwargs):
"""Delegate a log call to the underlying logger."""
return self._log_kw(level, args, kwargs) | python | def log(self, level, *args, **kwargs):
"""Delegate a log call to the underlying logger."""
return self._log_kw(level, args, kwargs) | [
"def",
"log",
"(",
"self",
",",
"level",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_log_kw",
"(",
"level",
",",
"args",
",",
"kwargs",
")"
] | Delegate a log call to the underlying logger. | [
"Delegate",
"a",
"log",
"call",
"to",
"the",
"underlying",
"logger",
"."
] | train | https://github.com/eisensheng/kaviar/blob/77ab934a3dd7b1cfabc0ec96acc0b8ed26edcb3f/kaviar/adapter.py#L95-L97 |
eisensheng/kaviar | kaviar/adapter.py | KvLoggerAdapter.exception | def exception(self, *args, **kwargs):
"""Delegate a exception call to the underlying logger."""
return self._log_kw(ERROR, args, kwargs, exc_info=True) | python | def exception(self, *args, **kwargs):
"""Delegate a exception call to the underlying logger."""
return self._log_kw(ERROR, args, kwargs, exc_info=True) | [
"def",
"exception",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_log_kw",
"(",
"ERROR",
",",
"args",
",",
"kwargs",
",",
"exc_info",
"=",
"True",
")"
] | Delegate a exception call to the underlying logger. | [
"Delegate",
"a",
"exception",
"call",
"to",
"the",
"underlying",
"logger",
"."
] | train | https://github.com/eisensheng/kaviar/blob/77ab934a3dd7b1cfabc0ec96acc0b8ed26edcb3f/kaviar/adapter.py#L115-L117 |
eagleamon/pynetio | pynetio.py | Netio.connect | def connect(self):
""" Simple connect """
try:
self.telnet = Telnet(self.host, self.port)
time.sleep(1)
self.get()
self.get('login admin admin')
self.update()
except socket.gaierror:
self.telnet = None
LOGGER.err... | python | def connect(self):
""" Simple connect """
try:
self.telnet = Telnet(self.host, self.port)
time.sleep(1)
self.get()
self.get('login admin admin')
self.update()
except socket.gaierror:
self.telnet = None
LOGGER.err... | [
"def",
"connect",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"telnet",
"=",
"Telnet",
"(",
"self",
".",
"host",
",",
"self",
".",
"port",
")",
"time",
".",
"sleep",
"(",
"1",
")",
"self",
".",
"get",
"(",
")",
"self",
".",
"get",
"(",
"'... | Simple connect | [
"Simple",
"connect"
] | train | https://github.com/eagleamon/pynetio/blob/3bc212cae18608de0214b964e395877d3ca4aa7b/pynetio.py#L33-L44 |
eagleamon/pynetio | pynetio.py | Netio.update | def update(self):
""" Update all the switch values """
self.states = [bool(int(x)) for x in self.get('port list') or '0000'] | python | def update(self):
""" Update all the switch values """
self.states = [bool(int(x)) for x in self.get('port list') or '0000'] | [
"def",
"update",
"(",
"self",
")",
":",
"self",
".",
"states",
"=",
"[",
"bool",
"(",
"int",
"(",
"x",
")",
")",
"for",
"x",
"in",
"self",
".",
"get",
"(",
"'port list'",
")",
"or",
"'0000'",
"]"
] | Update all the switch values | [
"Update",
"all",
"the",
"switch",
"values"
] | train | https://github.com/eagleamon/pynetio/blob/3bc212cae18608de0214b964e395877d3ca4aa7b/pynetio.py#L46-L49 |
eagleamon/pynetio | pynetio.py | Netio.get | def get(self, command=None):
"""
Interface function to send and receive decoded bytes
Retries the connect [self.retries] times
"""
try:
assert self.telnet
with self.lock:
if command:
if not command.endswith('\r\n'):
... | python | def get(self, command=None):
"""
Interface function to send and receive decoded bytes
Retries the connect [self.retries] times
"""
try:
assert self.telnet
with self.lock:
if command:
if not command.endswith('\r\n'):
... | [
"def",
"get",
"(",
"self",
",",
"command",
"=",
"None",
")",
":",
"try",
":",
"assert",
"self",
".",
"telnet",
"with",
"self",
".",
"lock",
":",
"if",
"command",
":",
"if",
"not",
"command",
".",
"endswith",
"(",
"'\\r\\n'",
")",
":",
"command",
"+... | Interface function to send and receive decoded bytes
Retries the connect [self.retries] times | [
"Interface",
"function",
"to",
"send",
"and",
"receive",
"decoded",
"bytes",
"Retries",
"the",
"connect",
"[",
"self",
".",
"retries",
"]",
"times"
] | train | https://github.com/eagleamon/pynetio/blob/3bc212cae18608de0214b964e395877d3ca4aa7b/pynetio.py#L54-L89 |
hmpf/dataporten-auth | src/dataporten/psa.py | DataportenOAuth2.get_user_details | def get_user_details(self, response):
"""
Return user details from Dataporten
Set fullname and fetch photoprofile url
"""
user = response
# Rename to what psa expects
fullname = user.get('name', None)
if fullname:
user['fullname'] = fullname
... | python | def get_user_details(self, response):
"""
Return user details from Dataporten
Set fullname and fetch photoprofile url
"""
user = response
# Rename to what psa expects
fullname = user.get('name', None)
if fullname:
user['fullname'] = fullname
... | [
"def",
"get_user_details",
"(",
"self",
",",
"response",
")",
":",
"user",
"=",
"response",
"# Rename to what psa expects",
"fullname",
"=",
"user",
".",
"get",
"(",
"'name'",
",",
"None",
")",
"if",
"fullname",
":",
"user",
"[",
"'fullname'",
"]",
"=",
"f... | Return user details from Dataporten
Set fullname and fetch photoprofile url | [
"Return",
"user",
"details",
"from",
"Dataporten"
] | train | https://github.com/hmpf/dataporten-auth/blob/bc2ff5e11a1fce2c3d7bffe3f2b513bd7e2c0fcc/src/dataporten/psa.py#L30-L50 |
hmpf/dataporten-auth | src/dataporten/psa.py | DataportenOAuth2.check_correct_audience | def check_correct_audience(self, audience):
"Assert that Dataporten sends back our own client id as audience"
client_id, _ = self.get_key_and_secret()
if audience != client_id:
raise AuthException('Wrong audience') | python | def check_correct_audience(self, audience):
"Assert that Dataporten sends back our own client id as audience"
client_id, _ = self.get_key_and_secret()
if audience != client_id:
raise AuthException('Wrong audience') | [
"def",
"check_correct_audience",
"(",
"self",
",",
"audience",
")",
":",
"client_id",
",",
"_",
"=",
"self",
".",
"get_key_and_secret",
"(",
")",
"if",
"audience",
"!=",
"client_id",
":",
"raise",
"AuthException",
"(",
"'Wrong audience'",
")"
] | Assert that Dataporten sends back our own client id as audience | [
"Assert",
"that",
"Dataporten",
"sends",
"back",
"our",
"own",
"client",
"id",
"as",
"audience"
] | train | https://github.com/hmpf/dataporten-auth/blob/bc2ff5e11a1fce2c3d7bffe3f2b513bd7e2c0fcc/src/dataporten/psa.py#L52-L56 |
hmpf/dataporten-auth | src/dataporten/psa.py | DataportenOAuth2.user_data | def user_data(self, access_token, *args, **kwargs):
"""Loads user data from service"""
url = '{}/userinfo'.format(self.BASE_URL)
response = self.get_json(
url,
headers={'Authorization': 'Bearer ' + access_token},
)
self.check_correct_audience(response['aud... | python | def user_data(self, access_token, *args, **kwargs):
"""Loads user data from service"""
url = '{}/userinfo'.format(self.BASE_URL)
response = self.get_json(
url,
headers={'Authorization': 'Bearer ' + access_token},
)
self.check_correct_audience(response['aud... | [
"def",
"user_data",
"(",
"self",
",",
"access_token",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"'{}/userinfo'",
".",
"format",
"(",
"self",
".",
"BASE_URL",
")",
"response",
"=",
"self",
".",
"get_json",
"(",
"url",
",",
"head... | Loads user data from service | [
"Loads",
"user",
"data",
"from",
"service"
] | train | https://github.com/hmpf/dataporten-auth/blob/bc2ff5e11a1fce2c3d7bffe3f2b513bd7e2c0fcc/src/dataporten/psa.py#L58-L68 |
hmpf/dataporten-auth | src/dataporten/psa.py | DataportenEmailOAuth2.get_user_details | def get_user_details(self, response):
"""
Return user details from Dataporten
Set username to email address
"""
user = super(DataportenEmailOAuth2, self).get_user_details(response)
user['username'] = user['email']
return user | python | def get_user_details(self, response):
"""
Return user details from Dataporten
Set username to email address
"""
user = super(DataportenEmailOAuth2, self).get_user_details(response)
user['username'] = user['email']
return user | [
"def",
"get_user_details",
"(",
"self",
",",
"response",
")",
":",
"user",
"=",
"super",
"(",
"DataportenEmailOAuth2",
",",
"self",
")",
".",
"get_user_details",
"(",
"response",
")",
"user",
"[",
"'username'",
"]",
"=",
"user",
"[",
"'email'",
"]",
"retur... | Return user details from Dataporten
Set username to email address | [
"Return",
"user",
"details",
"from",
"Dataporten"
] | train | https://github.com/hmpf/dataporten-auth/blob/bc2ff5e11a1fce2c3d7bffe3f2b513bd7e2c0fcc/src/dataporten/psa.py#L80-L88 |
hmpf/dataporten-auth | src/dataporten/psa.py | DataportenFeideOAuth2.get_user_details | def get_user_details(self, response):
"""
Return user details from Dataporten
Set username to eduPersonPrincipalName
"""
user = super(DataportenFeideOAuth2, self).get_user_details(response)
sec_userids = user['userid_sec']
for userid in sec_userids:
u... | python | def get_user_details(self, response):
"""
Return user details from Dataporten
Set username to eduPersonPrincipalName
"""
user = super(DataportenFeideOAuth2, self).get_user_details(response)
sec_userids = user['userid_sec']
for userid in sec_userids:
u... | [
"def",
"get_user_details",
"(",
"self",
",",
"response",
")",
":",
"user",
"=",
"super",
"(",
"DataportenFeideOAuth2",
",",
"self",
")",
".",
"get_user_details",
"(",
"response",
")",
"sec_userids",
"=",
"user",
"[",
"'userid_sec'",
"]",
"for",
"userid",
"in... | Return user details from Dataporten
Set username to eduPersonPrincipalName | [
"Return",
"user",
"details",
"from",
"Dataporten"
] | train | https://github.com/hmpf/dataporten-auth/blob/bc2ff5e11a1fce2c3d7bffe3f2b513bd7e2c0fcc/src/dataporten/psa.py#L95-L108 |
alexhayes/django-toolkit | django_toolkit/fields.py | ChoiceHumanReadable | def ChoiceHumanReadable(choices, choice):
"""
Return the human readable representation for a list of choices.
@see https://docs.djangoproject.com/en/dev/ref/models/fields/#choices
"""
if choice == None: raise NoChoiceError()
for _choice in choices:
if _choice[0] == choice:
... | python | def ChoiceHumanReadable(choices, choice):
"""
Return the human readable representation for a list of choices.
@see https://docs.djangoproject.com/en/dev/ref/models/fields/#choices
"""
if choice == None: raise NoChoiceError()
for _choice in choices:
if _choice[0] == choice:
... | [
"def",
"ChoiceHumanReadable",
"(",
"choices",
",",
"choice",
")",
":",
"if",
"choice",
"==",
"None",
":",
"raise",
"NoChoiceError",
"(",
")",
"for",
"_choice",
"in",
"choices",
":",
"if",
"_choice",
"[",
"0",
"]",
"==",
"choice",
":",
"return",
"_choice"... | Return the human readable representation for a list of choices.
@see https://docs.djangoproject.com/en/dev/ref/models/fields/#choices | [
"Return",
"the",
"human",
"readable",
"representation",
"for",
"a",
"list",
"of",
"choices",
"."
] | train | https://github.com/alexhayes/django-toolkit/blob/b64106392fad596defc915b8235fe6e1d0013b5b/django_toolkit/fields.py#L15-L25 |
alexhayes/django-toolkit | django_toolkit/fields.py | SeparatedValuesField.get_db_prep_value | def get_db_prep_value(self, value, connection=None, prepared=False):
"""Returns field's value prepared for interacting with the database
backend.
Used by the default implementations of ``get_db_prep_save``and
`get_db_prep_lookup```
"""
if not value:
return
... | python | def get_db_prep_value(self, value, connection=None, prepared=False):
"""Returns field's value prepared for interacting with the database
backend.
Used by the default implementations of ``get_db_prep_save``and
`get_db_prep_lookup```
"""
if not value:
return
... | [
"def",
"get_db_prep_value",
"(",
"self",
",",
"value",
",",
"connection",
"=",
"None",
",",
"prepared",
"=",
"False",
")",
":",
"if",
"not",
"value",
":",
"return",
"if",
"prepared",
":",
"return",
"value",
"else",
":",
"assert",
"(",
"isinstance",
"(",
... | Returns field's value prepared for interacting with the database
backend.
Used by the default implementations of ``get_db_prep_save``and
`get_db_prep_lookup``` | [
"Returns",
"field",
"s",
"value",
"prepared",
"for",
"interacting",
"with",
"the",
"database",
"backend",
"."
] | train | https://github.com/alexhayes/django-toolkit/blob/b64106392fad596defc915b8235fe6e1d0013b5b/django_toolkit/fields.py#L58-L71 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.