repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
3 values
summary
stringlengths
4
350
kavdev/ldap-groups
ldap_groups/groups.py
ADGroup.get_children
def get_children(self, page_size=500): """ Returns a list of this group's children. :param page_size (optional): Many servers have a limit on the number of results that can be returned. Paged searches circumvent that limit. Adjust the page_size to be below the ...
python
def get_children(self, page_size=500): """ Returns a list of this group's children. :param page_size (optional): Many servers have a limit on the number of results that can be returned. Paged searches circumvent that limit. Adjust the page_size to be below the ...
[ "def", "get_children", "(", "self", ",", "page_size", "=", "500", ")", ":", "children", "=", "[", "]", "object_class", "=", "self", ".", "get_attribute", "(", "\"objectClass\"", ")", "group_type", "=", "object_class", "[", "-", "1", "]", "if", "object_clas...
Returns a list of this group's children. :param page_size (optional): Many servers have a limit on the number of results that can be returned. Paged searches circumvent that limit. Adjust the page_size to be below the server's size l...
[ "Returns", "a", "list", "of", "this", "group", "s", "children", ".", ":", "param", "page_size", "(", "optional", ")", ":", "Many", "servers", "have", "a", "limit", "on", "the", "number", "of", "results", "that", "can", "be", "returned", ".", "Paged", "...
0dd3a7d9eafa3903127364839b12a4b3dd3ca521
https://github.com/kavdev/ldap-groups/blob/0dd3a7d9eafa3903127364839b12a4b3dd3ca521/ldap_groups/groups.py#L614-L666
train
Returns a list of all the children of this group.
kavdev/ldap-groups
ldap_groups/groups.py
ADGroup.child
def child(self, group_name, page_size=500): """ Returns the child ad group that matches the provided group_name or none if the child does not exist. :param group_name: The name of the child group. NOTE: A name does not contain 'CN=' or 'OU=' :type group_name: str :param page_size (...
python
def child(self, group_name, page_size=500): """ Returns the child ad group that matches the provided group_name or none if the child does not exist. :param group_name: The name of the child group. NOTE: A name does not contain 'CN=' or 'OU=' :type group_name: str :param page_size (...
[ "def", "child", "(", "self", ",", "group_name", ",", "page_size", "=", "500", ")", ":", "object_class", "=", "self", ".", "get_attribute", "(", "\"objectClass\"", ")", "group_type", "=", "object_class", "[", "-", "1", "]", "if", "object_class", "else", "No...
Returns the child ad group that matches the provided group_name or none if the child does not exist. :param group_name: The name of the child group. NOTE: A name does not contain 'CN=' or 'OU=' :type group_name: str :param page_size (optional): Many servers have a limit on the number of res...
[ "Returns", "the", "child", "ad", "group", "that", "matches", "the", "provided", "group_name", "or", "none", "if", "the", "child", "does", "not", "exist", ".", ":", "param", "group_name", ":", "The", "name", "of", "the", "child", "group", ".", "NOTE", ":"...
0dd3a7d9eafa3903127364839b12a4b3dd3ca521
https://github.com/kavdev/ldap-groups/blob/0dd3a7d9eafa3903127364839b12a4b3dd3ca521/ldap_groups/groups.py#L668-L714
train
Returns the child ad group that matches the provided group_name or None if the child does not exist.
kavdev/ldap-groups
ldap_groups/groups.py
ADGroup.parent
def parent(self): """ Returns this group's parent (up to the DC)""" # Don't go above the DC if ''.join(self.group_dn.split("DC")[0].split()) == '': return self else: parent_dn = self.group_dn.split(",", 1).pop() return ADGroup( ...
python
def parent(self): """ Returns this group's parent (up to the DC)""" # Don't go above the DC if ''.join(self.group_dn.split("DC")[0].split()) == '': return self else: parent_dn = self.group_dn.split(",", 1).pop() return ADGroup( ...
[ "def", "parent", "(", "self", ")", ":", "# Don't go above the DC\r", "if", "''", ".", "join", "(", "self", ".", "group_dn", ".", "split", "(", "\"DC\"", ")", "[", "0", "]", ".", "split", "(", ")", ")", "==", "''", ":", "return", "self", "else", ":"...
Returns this group's parent (up to the DC)
[ "Returns", "this", "group", "s", "parent", "(", "up", "to", "the", "DC", ")" ]
0dd3a7d9eafa3903127364839b12a4b3dd3ca521
https://github.com/kavdev/ldap-groups/blob/0dd3a7d9eafa3903127364839b12a4b3dd3ca521/ldap_groups/groups.py#L716-L729
train
Returns the parent of this group.
kavdev/ldap-groups
ldap_groups/groups.py
ADGroup.ancestor
def ancestor(self, generation): """ Returns an ancestor of this group given a generation (up to the DC). :param generation: Determines how far up the path to go. Example: 0 = self, 1 = parent, 2 = grandparent ... :type generation: int """ # Don't go below the current g...
python
def ancestor(self, generation): """ Returns an ancestor of this group given a generation (up to the DC). :param generation: Determines how far up the path to go. Example: 0 = self, 1 = parent, 2 = grandparent ... :type generation: int """ # Don't go below the current g...
[ "def", "ancestor", "(", "self", ",", "generation", ")", ":", "# Don't go below the current generation and don't go above the DC\r", "if", "generation", "<", "1", ":", "return", "self", "else", ":", "ancestor_dn", "=", "self", ".", "group_dn", "for", "_index", "in", ...
Returns an ancestor of this group given a generation (up to the DC). :param generation: Determines how far up the path to go. Example: 0 = self, 1 = parent, 2 = grandparent ... :type generation: int
[ "Returns", "an", "ancestor", "of", "this", "group", "given", "a", "generation", "(", "up", "to", "the", "DC", ")", ".", ":", "param", "generation", ":", "Determines", "how", "far", "up", "the", "path", "to", "go", ".", "Example", ":", "0", "=", "self...
0dd3a7d9eafa3903127364839b12a4b3dd3ca521
https://github.com/kavdev/ldap-groups/blob/0dd3a7d9eafa3903127364839b12a4b3dd3ca521/ldap_groups/groups.py#L731-L756
train
Returns an ancestor of this group given a generation.
kmike/port-for
port_for/utils.py
ranges_to_set
def ranges_to_set(lst): """ Convert a list of ranges to a set of numbers:: >>> ranges = [(1,3), (5,6)] >>> sorted(list(ranges_to_set(ranges))) [1, 2, 3, 5, 6] """ return set(itertools.chain(*(range(x[0], x[1]+1) for x in lst)))
python
def ranges_to_set(lst): """ Convert a list of ranges to a set of numbers:: >>> ranges = [(1,3), (5,6)] >>> sorted(list(ranges_to_set(ranges))) [1, 2, 3, 5, 6] """ return set(itertools.chain(*(range(x[0], x[1]+1) for x in lst)))
[ "def", "ranges_to_set", "(", "lst", ")", ":", "return", "set", "(", "itertools", ".", "chain", "(", "*", "(", "range", "(", "x", "[", "0", "]", ",", "x", "[", "1", "]", "+", "1", ")", "for", "x", "in", "lst", ")", ")", ")" ]
Convert a list of ranges to a set of numbers:: >>> ranges = [(1,3), (5,6)] >>> sorted(list(ranges_to_set(ranges))) [1, 2, 3, 5, 6]
[ "Convert", "a", "list", "of", "ranges", "to", "a", "set", "of", "numbers", "::" ]
f61ebf3c2caf54eabe8233b40ef67b973176a6f5
https://github.com/kmike/port-for/blob/f61ebf3c2caf54eabe8233b40ef67b973176a6f5/port_for/utils.py#L6-L15
train
Convert a list of ranges to a set of numbers.
kmike/port-for
port_for/utils.py
to_ranges
def to_ranges(lst): """ Convert a list of numbers to a list of ranges:: >>> numbers = [1,2,3,5,6] >>> list(to_ranges(numbers)) [(1, 3), (5, 6)] """ for a, b in itertools.groupby(enumerate(lst), lambda t: t[1] - t[0]): b = list(b) yield b[0][1], b[-1][1]
python
def to_ranges(lst): """ Convert a list of numbers to a list of ranges:: >>> numbers = [1,2,3,5,6] >>> list(to_ranges(numbers)) [(1, 3), (5, 6)] """ for a, b in itertools.groupby(enumerate(lst), lambda t: t[1] - t[0]): b = list(b) yield b[0][1], b[-1][1]
[ "def", "to_ranges", "(", "lst", ")", ":", "for", "a", ",", "b", "in", "itertools", ".", "groupby", "(", "enumerate", "(", "lst", ")", ",", "lambda", "t", ":", "t", "[", "1", "]", "-", "t", "[", "0", "]", ")", ":", "b", "=", "list", "(", "b"...
Convert a list of numbers to a list of ranges:: >>> numbers = [1,2,3,5,6] >>> list(to_ranges(numbers)) [(1, 3), (5, 6)]
[ "Convert", "a", "list", "of", "numbers", "to", "a", "list", "of", "ranges", "::" ]
f61ebf3c2caf54eabe8233b40ef67b973176a6f5
https://github.com/kmike/port-for/blob/f61ebf3c2caf54eabe8233b40ef67b973176a6f5/port_for/utils.py#L18-L29
train
Convert a list of numbers to a list of ranges
Parsely/schemato
schemato/utils.py
deepest_node
def deepest_node((subj, pred, obj), graph): """recurse down the tree and return a list of the most deeply nested child nodes of the given triple""" # i don't fully accept the premise that this docstring presents # i'm not a docstring literalist to_return = [] def _deepest_node((subj, pred, obj)...
python
def deepest_node((subj, pred, obj), graph): """recurse down the tree and return a list of the most deeply nested child nodes of the given triple""" # i don't fully accept the premise that this docstring presents # i'm not a docstring literalist to_return = [] def _deepest_node((subj, pred, obj)...
[ "def", "deepest_node", "(", "(", "subj", ",", "pred", ",", "obj", ")", ",", "graph", ")", ":", "# i don't fully accept the premise that this docstring presents", "# i'm not a docstring literalist", "to_return", "=", "[", "]", "def", "_deepest_node", "(", "(", "subj", ...
recurse down the tree and return a list of the most deeply nested child nodes of the given triple
[ "recurse", "down", "the", "tree", "and", "return", "a", "list", "of", "the", "most", "deeply", "nested", "child", "nodes", "of", "the", "given", "triple" ]
7002316fbcd52f2e669f8372bf1338c572e3df4b
https://github.com/Parsely/schemato/blob/7002316fbcd52f2e669f8372bf1338c572e3df4b/schemato/utils.py#L4-L27
train
recurse down the tree and return a list of the most deeply nested child nodes of the given triple
magopian/django-data-exports
data_exports/templatetags/getter_tags.py
getattribute
def getattribute(model, item): """Chained lookup of item on model If item has dots (eg: 'foo.bar.baz'), recursively call getattribute(): e = getattr(model, 'foo') e = getattr(e, 'bar') e = getattr(e, 'baz') At each step, check if e is a callable, and if so, use e() """ elements = item....
python
def getattribute(model, item): """Chained lookup of item on model If item has dots (eg: 'foo.bar.baz'), recursively call getattribute(): e = getattr(model, 'foo') e = getattr(e, 'bar') e = getattr(e, 'baz') At each step, check if e is a callable, and if so, use e() """ elements = item....
[ "def", "getattribute", "(", "model", ",", "item", ")", ":", "elements", "=", "item", ".", "split", "(", "'.'", ")", "element", "=", "elements", ".", "pop", "(", "0", ")", "try", ":", "attr", "=", "getattr", "(", "model", ",", "element", ",", "None"...
Chained lookup of item on model If item has dots (eg: 'foo.bar.baz'), recursively call getattribute(): e = getattr(model, 'foo') e = getattr(e, 'bar') e = getattr(e, 'baz') At each step, check if e is a callable, and if so, use e()
[ "Chained", "lookup", "of", "item", "on", "model" ]
a73db486779d93046ad89c5bf582ff8ae869120f
https://github.com/magopian/django-data-exports/blob/a73db486779d93046ad89c5bf582ff8ae869120f/data_exports/templatetags/getter_tags.py#L13-L38
train
Get attribute of a single item on a model.
magopian/django-data-exports
data_exports/templatetags/getter_tags.py
nice_display
def nice_display(item): """Display a comma-separated list of models for M2M fields""" if hasattr(item, 'all'): # RelatedManager: display a list return ', '.join(map(text_type, item.all())) return item
python
def nice_display(item): """Display a comma-separated list of models for M2M fields""" if hasattr(item, 'all'): # RelatedManager: display a list return ', '.join(map(text_type, item.all())) return item
[ "def", "nice_display", "(", "item", ")", ":", "if", "hasattr", "(", "item", ",", "'all'", ")", ":", "# RelatedManager: display a list", "return", "', '", ".", "join", "(", "map", "(", "text_type", ",", "item", ".", "all", "(", ")", ")", ")", "return", ...
Display a comma-separated list of models for M2M fields
[ "Display", "a", "comma", "-", "separated", "list", "of", "models", "for", "M2M", "fields" ]
a73db486779d93046ad89c5bf582ff8ae869120f
https://github.com/magopian/django-data-exports/blob/a73db486779d93046ad89c5bf582ff8ae869120f/data_exports/templatetags/getter_tags.py#L48-L52
train
Display a comma - separated list of models for M2M fields
nicfit/MishMash
mishmash/util.py
normalizeCountry
def normalizeCountry(country_str, target="iso3c", title_case=False): """Return a normalized name/code for country in ``country_str``. The input can be a code or name, the ``target`` determines output value. 3 character ISO code is the default (iso3c), 'country_name', and 'iso2c' are common also. See ``c...
python
def normalizeCountry(country_str, target="iso3c", title_case=False): """Return a normalized name/code for country in ``country_str``. The input can be a code or name, the ``target`` determines output value. 3 character ISO code is the default (iso3c), 'country_name', and 'iso2c' are common also. See ``c...
[ "def", "normalizeCountry", "(", "country_str", ",", "target", "=", "\"iso3c\"", ",", "title_case", "=", "False", ")", ":", "iso2", "=", "\"iso2c\"", "iso3", "=", "\"iso3c\"", "raw", "=", "\"country_name\"", "if", "country_str", "is", "None", ":", "return", "...
Return a normalized name/code for country in ``country_str``. The input can be a code or name, the ``target`` determines output value. 3 character ISO code is the default (iso3c), 'country_name', and 'iso2c' are common also. See ``countrycode.countrycode`` for details and other options. Raises ``ValueEr...
[ "Return", "a", "normalized", "name", "/", "code", "for", "country", "in", "country_str", ".", "The", "input", "can", "be", "a", "code", "or", "name", "the", "target", "determines", "output", "value", ".", "3", "character", "ISO", "code", "is", "the", "de...
8f988936340bf0ffb83ea90ea124efb3c36a1174
https://github.com/nicfit/MishMash/blob/8f988936340bf0ffb83ea90ea124efb3c36a1174/mishmash/util.py#L24-L54
train
Return a normalized name or code for a country in the specified ISO code.
nicfit/MishMash
mishmash/util.py
mostCommonItem
def mostCommonItem(lst): """Choose the most common item from the list, or the first item if all items are unique.""" # This elegant solution from: http://stackoverflow.com/a/1518632/1760218 lst = [l for l in lst if l] if lst: return max(set(lst), key=lst.count) else: return None
python
def mostCommonItem(lst): """Choose the most common item from the list, or the first item if all items are unique.""" # This elegant solution from: http://stackoverflow.com/a/1518632/1760218 lst = [l for l in lst if l] if lst: return max(set(lst), key=lst.count) else: return None
[ "def", "mostCommonItem", "(", "lst", ")", ":", "# This elegant solution from: http://stackoverflow.com/a/1518632/1760218", "lst", "=", "[", "l", "for", "l", "in", "lst", "if", "l", "]", "if", "lst", ":", "return", "max", "(", "set", "(", "lst", ")", ",", "ke...
Choose the most common item from the list, or the first item if all items are unique.
[ "Choose", "the", "most", "common", "item", "from", "the", "list", "or", "the", "first", "item", "if", "all", "items", "are", "unique", "." ]
8f988936340bf0ffb83ea90ea124efb3c36a1174
https://github.com/nicfit/MishMash/blob/8f988936340bf0ffb83ea90ea124efb3c36a1174/mishmash/util.py#L61-L69
train
Choose the most common item from the list or the first item.
nicfit/MishMash
mishmash/util.py
safeDbUrl
def safeDbUrl(db_url): """Obfuscates password from a database URL.""" url = urlparse(db_url) return db_url.replace(url.password, "****") if url.password else db_url
python
def safeDbUrl(db_url): """Obfuscates password from a database URL.""" url = urlparse(db_url) return db_url.replace(url.password, "****") if url.password else db_url
[ "def", "safeDbUrl", "(", "db_url", ")", ":", "url", "=", "urlparse", "(", "db_url", ")", "return", "db_url", ".", "replace", "(", "url", ".", "password", ",", "\"****\"", ")", "if", "url", ".", "password", "else", "db_url" ]
Obfuscates password from a database URL.
[ "Obfuscates", "password", "from", "a", "database", "URL", "." ]
8f988936340bf0ffb83ea90ea124efb3c36a1174
https://github.com/nicfit/MishMash/blob/8f988936340bf0ffb83ea90ea124efb3c36a1174/mishmash/util.py#L72-L75
train
Obfuscates password from a database URL.
bear/bearlib
bearlib/config.py
bConfig.loadJson
def loadJson(self, filename): """ Read, parse and return given Json config file """ jsonConfig = {} if os.path.isfile(filename): jsonConfig = json.loads(' '.join(open(filename, 'r').readlines())) return jsonConfig
python
def loadJson(self, filename): """ Read, parse and return given Json config file """ jsonConfig = {} if os.path.isfile(filename): jsonConfig = json.loads(' '.join(open(filename, 'r').readlines())) return jsonConfig
[ "def", "loadJson", "(", "self", ",", "filename", ")", ":", "jsonConfig", "=", "{", "}", "if", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "jsonConfig", "=", "json", ".", "loads", "(", "' '", ".", "join", "(", "open", "(", "filename...
Read, parse and return given Json config file
[ "Read", "parse", "and", "return", "given", "Json", "config", "file" ]
30f9b8ba4b7a8db4cd2f4c6e07966ae51d0a00dd
https://github.com/bear/bearlib/blob/30f9b8ba4b7a8db4cd2f4c6e07966ae51d0a00dd/bearlib/config.py#L203-L209
train
Read and parse and return given Json config file
magopian/django-data-exports
data_exports/admin.py
ExportAdmin.get_readonly_fields
def get_readonly_fields(self, request, obj=None): """The model can't be changed once the export is created""" if obj is None: return [] return super(ExportAdmin, self).get_readonly_fields(request, obj)
python
def get_readonly_fields(self, request, obj=None): """The model can't be changed once the export is created""" if obj is None: return [] return super(ExportAdmin, self).get_readonly_fields(request, obj)
[ "def", "get_readonly_fields", "(", "self", ",", "request", ",", "obj", "=", "None", ")", ":", "if", "obj", "is", "None", ":", "return", "[", "]", "return", "super", "(", "ExportAdmin", ",", "self", ")", ".", "get_readonly_fields", "(", "request", ",", ...
The model can't be changed once the export is created
[ "The", "model", "can", "t", "be", "changed", "once", "the", "export", "is", "created" ]
a73db486779d93046ad89c5bf582ff8ae869120f
https://github.com/magopian/django-data-exports/blob/a73db486779d93046ad89c5bf582ff8ae869120f/data_exports/admin.py#L31-L35
train
The export model can t be changed once the export is created
magopian/django-data-exports
data_exports/admin.py
ExportAdmin.response_add
def response_add(self, request, obj, post_url_continue=POST_URL_CONTINUE): """If we're adding, save must be "save and continue editing" Two exceptions to that workflow: * The user has pressed the 'Save and add another' button * We are adding a user in a popup """ if '_a...
python
def response_add(self, request, obj, post_url_continue=POST_URL_CONTINUE): """If we're adding, save must be "save and continue editing" Two exceptions to that workflow: * The user has pressed the 'Save and add another' button * We are adding a user in a popup """ if '_a...
[ "def", "response_add", "(", "self", ",", "request", ",", "obj", ",", "post_url_continue", "=", "POST_URL_CONTINUE", ")", ":", "if", "'_addanother'", "not", "in", "request", ".", "POST", "and", "'_popup'", "not", "in", "request", ".", "POST", ":", "request", ...
If we're adding, save must be "save and continue editing" Two exceptions to that workflow: * The user has pressed the 'Save and add another' button * We are adding a user in a popup
[ "If", "we", "re", "adding", "save", "must", "be", "save", "and", "continue", "editing" ]
a73db486779d93046ad89c5bf582ff8ae869120f
https://github.com/magopian/django-data-exports/blob/a73db486779d93046ad89c5bf582ff8ae869120f/data_exports/admin.py#L45-L57
train
This method is used to add a new entry in the database.
astraw38/lint
lint/validators/pylint_validator.py
no_new_errors
def no_new_errors(new_data, old_data, strict=False): """ Pylint Validator that will fail any review if there are new Pylint errors in it (Pylint message starts with 'E:') :param new_data: :param old_data: :return: """ success = True score = 0 message = '' if new_data['errors...
python
def no_new_errors(new_data, old_data, strict=False): """ Pylint Validator that will fail any review if there are new Pylint errors in it (Pylint message starts with 'E:') :param new_data: :param old_data: :return: """ success = True score = 0 message = '' if new_data['errors...
[ "def", "no_new_errors", "(", "new_data", ",", "old_data", ",", "strict", "=", "False", ")", ":", "success", "=", "True", "score", "=", "0", "message", "=", "''", "if", "new_data", "[", "'errors'", "]", ">", "old_data", "[", "'errors'", "]", ":", "succe...
Pylint Validator that will fail any review if there are new Pylint errors in it (Pylint message starts with 'E:') :param new_data: :param old_data: :return:
[ "Pylint", "Validator", "that", "will", "fail", "any", "review", "if", "there", "are", "new", "Pylint", "errors", "in", "it", "(", "Pylint", "message", "starts", "with", "E", ":", ")" ]
162ceefcb812f07d18544aaa887b9ec4f102cfb1
https://github.com/astraw38/lint/blob/162ceefcb812f07d18544aaa887b9ec4f102cfb1/lint/validators/pylint_validator.py#L49-L69
train
This function checks if there are new errors in the current node and returns a success score and message
astraw38/lint
lint/validators/pylint_validator.py
above_score_threshold
def above_score_threshold(new_data, old_data, strict=False, threshold=PYLINT_SCORE_THRESHOLD): """ Verifies that the pylint score is above a given threshold. :param new_data: :param old_data: :return: """ success = True score = 0 message = '' if strict: for fscore, fname...
python
def above_score_threshold(new_data, old_data, strict=False, threshold=PYLINT_SCORE_THRESHOLD): """ Verifies that the pylint score is above a given threshold. :param new_data: :param old_data: :return: """ success = True score = 0 message = '' if strict: for fscore, fname...
[ "def", "above_score_threshold", "(", "new_data", ",", "old_data", ",", "strict", "=", "False", ",", "threshold", "=", "PYLINT_SCORE_THRESHOLD", ")", ":", "success", "=", "True", "score", "=", "0", "message", "=", "''", "if", "strict", ":", "for", "fscore", ...
Verifies that the pylint score is above a given threshold. :param new_data: :param old_data: :return:
[ "Verifies", "that", "the", "pylint", "score", "is", "above", "a", "given", "threshold", "." ]
162ceefcb812f07d18544aaa887b9ec4f102cfb1
https://github.com/astraw38/lint/blob/162ceefcb812f07d18544aaa887b9ec4f102cfb1/lint/validators/pylint_validator.py#L72-L99
train
Verifies that the pylint score is above a given threshold.
astraw38/lint
lint/validators/pylint_validator.py
PylintValidator.run
def run(self, new_pylint_data, old_pylint_data): """ Run the new pylint data through given all current checkers, including comparisons to old pylint data. """ for validator in self.checkers: success, score, message = validator(new_pylint_data, old_pylint_data) ...
python
def run(self, new_pylint_data, old_pylint_data): """ Run the new pylint data through given all current checkers, including comparisons to old pylint data. """ for validator in self.checkers: success, score, message = validator(new_pylint_data, old_pylint_data) ...
[ "def", "run", "(", "self", ",", "new_pylint_data", ",", "old_pylint_data", ")", ":", "for", "validator", "in", "self", ".", "checkers", ":", "success", ",", "score", ",", "message", "=", "validator", "(", "new_pylint_data", ",", "old_pylint_data", ")", "if",...
Run the new pylint data through given all current checkers, including comparisons to old pylint data.
[ "Run", "the", "new", "pylint", "data", "through", "given", "all", "current", "checkers", "including", "comparisons", "to", "old", "pylint", "data", "." ]
162ceefcb812f07d18544aaa887b9ec4f102cfb1
https://github.com/astraw38/lint/blob/162ceefcb812f07d18544aaa887b9ec4f102cfb1/lint/validators/pylint_validator.py#L34-L46
train
Run the new pylint data through all current checkers and return the score and message.
Parsely/schemato
schemato/schemato.py
Schemato._document_lines
def _document_lines(self, text): """helper, get a list of (linetext, linenum) from a string with newlines """ inlines = text.split('\n') doc_lines = [(re.sub(r'^ +| +$', '', line), num) for line, num in zip(inlines, xrange(1, len(inlines)...
python
def _document_lines(self, text): """helper, get a list of (linetext, linenum) from a string with newlines """ inlines = text.split('\n') doc_lines = [(re.sub(r'^ +| +$', '', line), num) for line, num in zip(inlines, xrange(1, len(inlines)...
[ "def", "_document_lines", "(", "self", ",", "text", ")", ":", "inlines", "=", "text", ".", "split", "(", "'\\n'", ")", "doc_lines", "=", "[", "(", "re", ".", "sub", "(", "r'^ +| +$'", ",", "''", ",", "line", ")", ",", "num", ")", "for", "line", "...
helper, get a list of (linetext, linenum) from a string with newlines
[ "helper", "get", "a", "list", "of", "(", "linetext", "linenum", ")", "from", "a", "string", "with", "newlines" ]
7002316fbcd52f2e669f8372bf1338c572e3df4b
https://github.com/Parsely/schemato/blob/7002316fbcd52f2e669f8372bf1338c572e3df4b/schemato/schemato.py#L64-L72
train
helper function to get a list of ( linetext linenum ) from a string with newlines
Parsely/schemato
schemato/schemato.py
Schemato._get_document
def _get_document(self, source): """helper, open a file or url and return the content and identifier""" scheme_url = source if not source.startswith("http"): scheme_url = "http://%s" % source text = source try: text = urllib.urlopen(scheme_url).read() ...
python
def _get_document(self, source): """helper, open a file or url and return the content and identifier""" scheme_url = source if not source.startswith("http"): scheme_url = "http://%s" % source text = source try: text = urllib.urlopen(scheme_url).read() ...
[ "def", "_get_document", "(", "self", ",", "source", ")", ":", "scheme_url", "=", "source", "if", "not", "source", ".", "startswith", "(", "\"http\"", ")", ":", "scheme_url", "=", "\"http://%s\"", "%", "source", "text", "=", "source", "try", ":", "text", ...
helper, open a file or url and return the content and identifier
[ "helper", "open", "a", "file", "or", "url", "and", "return", "the", "content", "and", "identifier" ]
7002316fbcd52f2e669f8372bf1338c572e3df4b
https://github.com/Parsely/schemato/blob/7002316fbcd52f2e669f8372bf1338c572e3df4b/schemato/schemato.py#L74-L96
train
helper function to open a file or url and return the content and identifier
kmike/port-for
port_for/api.py
select_random
def select_random(ports=None, exclude_ports=None): """ Returns random unused port number. """ if ports is None: ports = available_good_ports() if exclude_ports is None: exclude_ports = set() ports.difference_update(set(exclude_ports)) for port in random.sample(ports, min(l...
python
def select_random(ports=None, exclude_ports=None): """ Returns random unused port number. """ if ports is None: ports = available_good_ports() if exclude_ports is None: exclude_ports = set() ports.difference_update(set(exclude_ports)) for port in random.sample(ports, min(l...
[ "def", "select_random", "(", "ports", "=", "None", ",", "exclude_ports", "=", "None", ")", ":", "if", "ports", "is", "None", ":", "ports", "=", "available_good_ports", "(", ")", "if", "exclude_ports", "is", "None", ":", "exclude_ports", "=", "set", "(", ...
Returns random unused port number.
[ "Returns", "random", "unused", "port", "number", "." ]
f61ebf3c2caf54eabe8233b40ef67b973176a6f5
https://github.com/kmike/port-for/blob/f61ebf3c2caf54eabe8233b40ef67b973176a6f5/port_for/api.py#L15-L30
train
Returns random unused port number.
kmike/port-for
port_for/api.py
available_ports
def available_ports(low=1024, high=65535, exclude_ranges=None): """ Returns a set of possible ports (excluding system, ephemeral and well-known ports). Pass ``high`` and/or ``low`` to limit the port range. """ if exclude_ranges is None: exclude_ranges = [] available = utils.ranges_t...
python
def available_ports(low=1024, high=65535, exclude_ranges=None): """ Returns a set of possible ports (excluding system, ephemeral and well-known ports). Pass ``high`` and/or ``low`` to limit the port range. """ if exclude_ranges is None: exclude_ranges = [] available = utils.ranges_t...
[ "def", "available_ports", "(", "low", "=", "1024", ",", "high", "=", "65535", ",", "exclude_ranges", "=", "None", ")", ":", "if", "exclude_ranges", "is", "None", ":", "exclude_ranges", "=", "[", "]", "available", "=", "utils", ".", "ranges_to_set", "(", ...
Returns a set of possible ports (excluding system, ephemeral and well-known ports). Pass ``high`` and/or ``low`` to limit the port range.
[ "Returns", "a", "set", "of", "possible", "ports", "(", "excluding", "system", "ephemeral", "and", "well", "-", "known", "ports", ")", "." ]
f61ebf3c2caf54eabe8233b40ef67b973176a6f5
https://github.com/kmike/port-for/blob/f61ebf3c2caf54eabe8233b40ef67b973176a6f5/port_for/api.py#L40-L58
train
Returns a set of possible ports in a node.
kmike/port-for
port_for/api.py
good_port_ranges
def good_port_ranges(ports=None, min_range_len=20, border=3): """ Returns a list of 'good' port ranges. Such ranges are large and don't contain ephemeral or well-known ports. Ranges borders are also excluded. """ min_range_len += border*2 if ports is None: ports = available_ports() ...
python
def good_port_ranges(ports=None, min_range_len=20, border=3): """ Returns a list of 'good' port ranges. Such ranges are large and don't contain ephemeral or well-known ports. Ranges borders are also excluded. """ min_range_len += border*2 if ports is None: ports = available_ports() ...
[ "def", "good_port_ranges", "(", "ports", "=", "None", ",", "min_range_len", "=", "20", ",", "border", "=", "3", ")", ":", "min_range_len", "+=", "border", "*", "2", "if", "ports", "is", "None", ":", "ports", "=", "available_ports", "(", ")", "ranges", ...
Returns a list of 'good' port ranges. Such ranges are large and don't contain ephemeral or well-known ports. Ranges borders are also excluded.
[ "Returns", "a", "list", "of", "good", "port", "ranges", ".", "Such", "ranges", "are", "large", "and", "don", "t", "contain", "ephemeral", "or", "well", "-", "known", "ports", ".", "Ranges", "borders", "are", "also", "excluded", "." ]
f61ebf3c2caf54eabe8233b40ef67b973176a6f5
https://github.com/kmike/port-for/blob/f61ebf3c2caf54eabe8233b40ef67b973176a6f5/port_for/api.py#L61-L74
train
Returns a list of good port ranges.
kmike/port-for
port_for/api.py
port_is_used
def port_is_used(port, host='127.0.0.1'): """ Returns if port is used. Port is considered used if the current process can't bind to it or the port doesn't refuse connections. """ unused = _can_bind(port, host) and _refuses_connection(port, host) return not unused
python
def port_is_used(port, host='127.0.0.1'): """ Returns if port is used. Port is considered used if the current process can't bind to it or the port doesn't refuse connections. """ unused = _can_bind(port, host) and _refuses_connection(port, host) return not unused
[ "def", "port_is_used", "(", "port", ",", "host", "=", "'127.0.0.1'", ")", ":", "unused", "=", "_can_bind", "(", "port", ",", "host", ")", "and", "_refuses_connection", "(", "port", ",", "host", ")", "return", "not", "unused" ]
Returns if port is used. Port is considered used if the current process can't bind to it or the port doesn't refuse connections.
[ "Returns", "if", "port", "is", "used", ".", "Port", "is", "considered", "used", "if", "the", "current", "process", "can", "t", "bind", "to", "it", "or", "the", "port", "doesn", "t", "refuse", "connections", "." ]
f61ebf3c2caf54eabe8233b40ef67b973176a6f5
https://github.com/kmike/port-for/blob/f61ebf3c2caf54eabe8233b40ef67b973176a6f5/port_for/api.py#L83-L89
train
Returns if the given port is used.
wimglenn/advent-of-code-data
aocd/get.py
get_data
def get_data(session=None, day=None, year=None): """ Get data for day (1-25) and year (>= 2015) User's session cookie is needed (puzzle inputs differ by user) """ if session is None: user = default_user() else: user = User(token=session) if day is None: day = current_...
python
def get_data(session=None, day=None, year=None): """ Get data for day (1-25) and year (>= 2015) User's session cookie is needed (puzzle inputs differ by user) """ if session is None: user = default_user() else: user = User(token=session) if day is None: day = current_...
[ "def", "get_data", "(", "session", "=", "None", ",", "day", "=", "None", ",", "year", "=", "None", ")", ":", "if", "session", "is", "None", ":", "user", "=", "default_user", "(", ")", "else", ":", "user", "=", "User", "(", "token", "=", "session", ...
Get data for day (1-25) and year (>= 2015) User's session cookie is needed (puzzle inputs differ by user)
[ "Get", "data", "for", "day", "(", "1", "-", "25", ")", "and", "year", "(", ">", "=", "2015", ")", "User", "s", "session", "cookie", "is", "needed", "(", "puzzle", "inputs", "differ", "by", "user", ")" ]
a3856459d225840f2b6919659fc65aa7a6a74533
https://github.com/wimglenn/advent-of-code-data/blob/a3856459d225840f2b6919659fc65aa7a6a74533/aocd/get.py#L23-L39
train
Get data for a specific day and year
wimglenn/advent-of-code-data
aocd/get.py
most_recent_year
def most_recent_year(): """ This year, if it's December. The most recent year, otherwise. Note: Advent of Code started in 2015 """ aoc_now = datetime.datetime.now(tz=AOC_TZ) year = aoc_now.year if aoc_now.month < 12: year -= 1 if year < 2015: raise AocdError("Time tra...
python
def most_recent_year(): """ This year, if it's December. The most recent year, otherwise. Note: Advent of Code started in 2015 """ aoc_now = datetime.datetime.now(tz=AOC_TZ) year = aoc_now.year if aoc_now.month < 12: year -= 1 if year < 2015: raise AocdError("Time tra...
[ "def", "most_recent_year", "(", ")", ":", "aoc_now", "=", "datetime", ".", "datetime", ".", "now", "(", "tz", "=", "AOC_TZ", ")", "year", "=", "aoc_now", ".", "year", "if", "aoc_now", ".", "month", "<", "12", ":", "year", "-=", "1", "if", "year", "...
This year, if it's December. The most recent year, otherwise. Note: Advent of Code started in 2015
[ "This", "year", "if", "it", "s", "December", ".", "The", "most", "recent", "year", "otherwise", ".", "Note", ":", "Advent", "of", "Code", "started", "in", "2015" ]
a3856459d225840f2b6919659fc65aa7a6a74533
https://github.com/wimglenn/advent-of-code-data/blob/a3856459d225840f2b6919659fc65aa7a6a74533/aocd/get.py#L42-L54
train
This year is the most recent year.
wimglenn/advent-of-code-data
aocd/get.py
current_day
def current_day(): """ Most recent day, if it's during the Advent of Code. Happy Holidays! Day 1 is assumed, otherwise. """ aoc_now = datetime.datetime.now(tz=AOC_TZ) if aoc_now.month != 12: log.warning("current_day is only available in December (EST)") return 1 day = min(aoc...
python
def current_day(): """ Most recent day, if it's during the Advent of Code. Happy Holidays! Day 1 is assumed, otherwise. """ aoc_now = datetime.datetime.now(tz=AOC_TZ) if aoc_now.month != 12: log.warning("current_day is only available in December (EST)") return 1 day = min(aoc...
[ "def", "current_day", "(", ")", ":", "aoc_now", "=", "datetime", ".", "datetime", ".", "now", "(", "tz", "=", "AOC_TZ", ")", "if", "aoc_now", ".", "month", "!=", "12", ":", "log", ".", "warning", "(", "\"current_day is only available in December (EST)\"", ")...
Most recent day, if it's during the Advent of Code. Happy Holidays! Day 1 is assumed, otherwise.
[ "Most", "recent", "day", "if", "it", "s", "during", "the", "Advent", "of", "Code", ".", "Happy", "Holidays!", "Day", "1", "is", "assumed", "otherwise", "." ]
a3856459d225840f2b6919659fc65aa7a6a74533
https://github.com/wimglenn/advent-of-code-data/blob/a3856459d225840f2b6919659fc65aa7a6a74533/aocd/get.py#L57-L67
train
Return the current day of the AOC.
wimglenn/advent-of-code-data
aocd/get.py
get_day_and_year
def get_day_and_year(): """ Returns tuple (day, year). Here be dragons! The correct date is determined with introspection of the call stack, first finding the filename of the module from which ``aocd`` was imported. This means your filenames should be something sensible, which identify the ...
python
def get_day_and_year(): """ Returns tuple (day, year). Here be dragons! The correct date is determined with introspection of the call stack, first finding the filename of the module from which ``aocd`` was imported. This means your filenames should be something sensible, which identify the ...
[ "def", "get_day_and_year", "(", ")", ":", "pattern_year", "=", "r\"201[5-9]|202[0-9]\"", "pattern_day", "=", "r\"2[0-5]|1[0-9]|[1-9]\"", "stack", "=", "[", "f", "[", "0", "]", "for", "f", "in", "traceback", ".", "extract_stack", "(", ")", "]", "for", "name", ...
Returns tuple (day, year). Here be dragons! The correct date is determined with introspection of the call stack, first finding the filename of the module from which ``aocd`` was imported. This means your filenames should be something sensible, which identify the day and year unambiguously. The ex...
[ "Returns", "tuple", "(", "day", "year", ")", "." ]
a3856459d225840f2b6919659fc65aa7a6a74533
https://github.com/wimglenn/advent-of-code-data/blob/a3856459d225840f2b6919659fc65aa7a6a74533/aocd/get.py#L70-L134
train
Returns tuple of day and year of the current AoC file.
astraw38/lint
lint/linters/lint_factory.py
LintFactory.register_linter
def register_linter(linter): """ Register a Linter class for file verification. :param linter: :return: """ if hasattr(linter, "EXTS") and hasattr(linter, "run"): LintFactory.PLUGINS.append(linter) else: raise LinterException("Linter does ...
python
def register_linter(linter): """ Register a Linter class for file verification. :param linter: :return: """ if hasattr(linter, "EXTS") and hasattr(linter, "run"): LintFactory.PLUGINS.append(linter) else: raise LinterException("Linter does ...
[ "def", "register_linter", "(", "linter", ")", ":", "if", "hasattr", "(", "linter", ",", "\"EXTS\"", ")", "and", "hasattr", "(", "linter", ",", "\"run\"", ")", ":", "LintFactory", ".", "PLUGINS", ".", "append", "(", "linter", ")", "else", ":", "raise", ...
Register a Linter class for file verification. :param linter: :return:
[ "Register", "a", "Linter", "class", "for", "file", "verification", "." ]
162ceefcb812f07d18544aaa887b9ec4f102cfb1
https://github.com/astraw38/lint/blob/162ceefcb812f07d18544aaa887b9ec4f102cfb1/lint/linters/lint_factory.py#L32-L42
train
Register a Linter class for file verification.
kavdev/ldap-groups
ldap_groups/utils.py
escape_query
def escape_query(query): """Escapes certain filter characters from an LDAP query.""" return query.replace("\\", r"\5C").replace("*", r"\2A").replace("(", r"\28").replace(")", r"\29")
python
def escape_query(query): """Escapes certain filter characters from an LDAP query.""" return query.replace("\\", r"\5C").replace("*", r"\2A").replace("(", r"\28").replace(")", r"\29")
[ "def", "escape_query", "(", "query", ")", ":", "return", "query", ".", "replace", "(", "\"\\\\\"", ",", "r\"\\5C\"", ")", ".", "replace", "(", "\"*\"", ",", "r\"\\2A\"", ")", ".", "replace", "(", "\"(\"", ",", "r\"\\28\"", ")", ".", "replace", "(", "\"...
Escapes certain filter characters from an LDAP query.
[ "Escapes", "certain", "filter", "characters", "from", "an", "LDAP", "query", "." ]
0dd3a7d9eafa3903127364839b12a4b3dd3ca521
https://github.com/kavdev/ldap-groups/blob/0dd3a7d9eafa3903127364839b12a4b3dd3ca521/ldap_groups/utils.py#L23-L26
train
Escapes certain filter characters from an LDAP query.
ambitioninc/kmatch
kmatch/kmatch.py
K._compile
def _compile(self, p): """ Recursively compiles the regexs in the pattern (p). """ if self._is_value_filter(p) and p[0] == '=~': try: p[2] = re.compile(p[2]) except: # Python doesn't document exactly what exceptions re.compile throws ...
python
def _compile(self, p): """ Recursively compiles the regexs in the pattern (p). """ if self._is_value_filter(p) and p[0] == '=~': try: p[2] = re.compile(p[2]) except: # Python doesn't document exactly what exceptions re.compile throws ...
[ "def", "_compile", "(", "self", ",", "p", ")", ":", "if", "self", ".", "_is_value_filter", "(", "p", ")", "and", "p", "[", "0", "]", "==", "'=~'", ":", "try", ":", "p", "[", "2", "]", "=", "re", ".", "compile", "(", "p", "[", "2", "]", ")",...
Recursively compiles the regexs in the pattern (p).
[ "Recursively", "compiles", "the", "regexs", "in", "the", "pattern", "(", "p", ")", "." ]
22bb5f0c1d86d0e4a69bdf18f092f095934ebb0d
https://github.com/ambitioninc/kmatch/blob/22bb5f0c1d86d0e4a69bdf18f092f095934ebb0d/kmatch/kmatch.py#L73-L84
train
Recursively compiles the regexs in the pattern p.
ambitioninc/kmatch
kmatch/kmatch.py
K._validate
def _validate(self, p): """ Recursively validates the pattern (p), ensuring it adheres to the proper key names and structure. """ if self._is_operator(p): for operator_or_filter in (p[1] if p[0] != '!' else [p[1]]): if p[0] == '^': self._va...
python
def _validate(self, p): """ Recursively validates the pattern (p), ensuring it adheres to the proper key names and structure. """ if self._is_operator(p): for operator_or_filter in (p[1] if p[0] != '!' else [p[1]]): if p[0] == '^': self._va...
[ "def", "_validate", "(", "self", ",", "p", ")", ":", "if", "self", ".", "_is_operator", "(", "p", ")", ":", "for", "operator_or_filter", "in", "(", "p", "[", "1", "]", "if", "p", "[", "0", "]", "!=", "'!'", "else", "[", "p", "[", "1", "]", "]...
Recursively validates the pattern (p), ensuring it adheres to the proper key names and structure.
[ "Recursively", "validates", "the", "pattern", "(", "p", ")", "ensuring", "it", "adheres", "to", "the", "proper", "key", "names", "and", "structure", "." ]
22bb5f0c1d86d0e4a69bdf18f092f095934ebb0d
https://github.com/ambitioninc/kmatch/blob/22bb5f0c1d86d0e4a69bdf18f092f095934ebb0d/kmatch/kmatch.py#L86-L96
train
Recursively validates the pattern p and raises an exception if it does not adheres to the proper key names and structure.
ambitioninc/kmatch
kmatch/kmatch.py
K._validate_xor_args
def _validate_xor_args(self, p): """ Raises ValueError if 2 arguments are not passed to an XOR """ if len(p[1]) != 2: raise ValueError('Invalid syntax: XOR only accepts 2 arguments, got {0}: {1}'.format(len(p[1]), p))
python
def _validate_xor_args(self, p): """ Raises ValueError if 2 arguments are not passed to an XOR """ if len(p[1]) != 2: raise ValueError('Invalid syntax: XOR only accepts 2 arguments, got {0}: {1}'.format(len(p[1]), p))
[ "def", "_validate_xor_args", "(", "self", ",", "p", ")", ":", "if", "len", "(", "p", "[", "1", "]", ")", "!=", "2", ":", "raise", "ValueError", "(", "'Invalid syntax: XOR only accepts 2 arguments, got {0}: {1}'", ".", "format", "(", "len", "(", "p", "[", "...
Raises ValueError if 2 arguments are not passed to an XOR
[ "Raises", "ValueError", "if", "2", "arguments", "are", "not", "passed", "to", "an", "XOR" ]
22bb5f0c1d86d0e4a69bdf18f092f095934ebb0d
https://github.com/ambitioninc/kmatch/blob/22bb5f0c1d86d0e4a69bdf18f092f095934ebb0d/kmatch/kmatch.py#L98-L103
train
Raises ValueError if 2 arguments are not passed to an XOR
ambitioninc/kmatch
kmatch/kmatch.py
K._match
def _match(self, p, value): """ Calls either _match_operator or _match_operand depending on the pattern (p) provided. """ if self._is_operator(p): return self._match_operator(p, value) else: try: if self._is_value_filter(p): ...
python
def _match(self, p, value): """ Calls either _match_operator or _match_operand depending on the pattern (p) provided. """ if self._is_operator(p): return self._match_operator(p, value) else: try: if self._is_value_filter(p): ...
[ "def", "_match", "(", "self", ",", "p", ",", "value", ")", ":", "if", "self", ".", "_is_operator", "(", "p", ")", ":", "return", "self", ".", "_match_operator", "(", "p", ",", "value", ")", "else", ":", "try", ":", "if", "self", ".", "_is_value_fil...
Calls either _match_operator or _match_operand depending on the pattern (p) provided.
[ "Calls", "either", "_match_operator", "or", "_match_operand", "depending", "on", "the", "pattern", "(", "p", ")", "provided", "." ]
22bb5f0c1d86d0e4a69bdf18f092f095934ebb0d
https://github.com/ambitioninc/kmatch/blob/22bb5f0c1d86d0e4a69bdf18f092f095934ebb0d/kmatch/kmatch.py#L105-L126
train
Returns True if the value matches the pattern p.
ambitioninc/kmatch
kmatch/kmatch.py
K._match_operator
def _match_operator(self, p, value): """ Returns True or False if the operator (&, |, or ! with filters, or ^ with filters) matches the value dictionary """ if p[0] == '!': return self._OPERATOR_MAP[p[0]](self._match(p[1], value)) elif p[0] == '^': return ...
python
def _match_operator(self, p, value): """ Returns True or False if the operator (&, |, or ! with filters, or ^ with filters) matches the value dictionary """ if p[0] == '!': return self._OPERATOR_MAP[p[0]](self._match(p[1], value)) elif p[0] == '^': return ...
[ "def", "_match_operator", "(", "self", ",", "p", ",", "value", ")", ":", "if", "p", "[", "0", "]", "==", "'!'", ":", "return", "self", ".", "_OPERATOR_MAP", "[", "p", "[", "0", "]", "]", "(", "self", ".", "_match", "(", "p", "[", "1", "]", ",...
Returns True or False if the operator (&, |, or ! with filters, or ^ with filters) matches the value dictionary
[ "Returns", "True", "or", "False", "if", "the", "operator", "(", "&", "|", "or", "!", "with", "filters", "or", "^", "with", "filters", ")", "matches", "the", "value", "dictionary" ]
22bb5f0c1d86d0e4a69bdf18f092f095934ebb0d
https://github.com/ambitioninc/kmatch/blob/22bb5f0c1d86d0e4a69bdf18f092f095934ebb0d/kmatch/kmatch.py#L128-L137
train
Returns True or False if the operator or filter matches the value dictionary.
ambitioninc/kmatch
kmatch/kmatch.py
K._match_value_filter
def _match_value_filter(self, p, value): """ Returns True of False if value in the pattern p matches the filter. """ return self._VALUE_FILTER_MAP[p[0]](value[p[1]], p[2])
python
def _match_value_filter(self, p, value): """ Returns True of False if value in the pattern p matches the filter. """ return self._VALUE_FILTER_MAP[p[0]](value[p[1]], p[2])
[ "def", "_match_value_filter", "(", "self", ",", "p", ",", "value", ")", ":", "return", "self", ".", "_VALUE_FILTER_MAP", "[", "p", "[", "0", "]", "]", "(", "value", "[", "p", "[", "1", "]", "]", ",", "p", "[", "2", "]", ")" ]
Returns True of False if value in the pattern p matches the filter.
[ "Returns", "True", "of", "False", "if", "value", "in", "the", "pattern", "p", "matches", "the", "filter", "." ]
22bb5f0c1d86d0e4a69bdf18f092f095934ebb0d
https://github.com/ambitioninc/kmatch/blob/22bb5f0c1d86d0e4a69bdf18f092f095934ebb0d/kmatch/kmatch.py#L139-L143
train
Returns True of False if the value in the pattern p matches the filter.
ambitioninc/kmatch
kmatch/kmatch.py
K.get_field_keys
def get_field_keys(self, pattern=None): """ Builds a set of all field keys used in the pattern including nested fields. :param pattern: The kmatch pattern to get field keys from or None to use self.pattern :type pattern: list or None :returns: A set object of all field keys used...
python
def get_field_keys(self, pattern=None): """ Builds a set of all field keys used in the pattern including nested fields. :param pattern: The kmatch pattern to get field keys from or None to use self.pattern :type pattern: list or None :returns: A set object of all field keys used...
[ "def", "get_field_keys", "(", "self", ",", "pattern", "=", "None", ")", ":", "# Use own pattern or passed in argument for recursion", "pattern", "=", "pattern", "or", "self", ".", "pattern", "# Validate the pattern so we can make assumptions about the data", "self", ".", "_...
Builds a set of all field keys used in the pattern including nested fields. :param pattern: The kmatch pattern to get field keys from or None to use self.pattern :type pattern: list or None :returns: A set object of all field keys used in the pattern :rtype: set
[ "Builds", "a", "set", "of", "all", "field", "keys", "used", "in", "the", "pattern", "including", "nested", "fields", "." ]
22bb5f0c1d86d0e4a69bdf18f092f095934ebb0d
https://github.com/ambitioninc/kmatch/blob/22bb5f0c1d86d0e4a69bdf18f092f095934ebb0d/kmatch/kmatch.py#L164-L194
train
Builds a set of all field keys used in the pattern including nested fields.
jim-easterbrook/pyctools
src/pyctools/core/frame.py
Frame.initialise
def initialise(self, other): """Initialise a :py:class:`Frame` from another :py:class:`Frame`. Copies the metadata and (a reference to) the data from :py:obj:`other`. Note that the data is not actually copied -- you must make a copy of the data before changing it. :param Frame ...
python
def initialise(self, other): """Initialise a :py:class:`Frame` from another :py:class:`Frame`. Copies the metadata and (a reference to) the data from :py:obj:`other`. Note that the data is not actually copied -- you must make a copy of the data before changing it. :param Frame ...
[ "def", "initialise", "(", "self", ",", "other", ")", ":", "self", ".", "frame_no", "=", "other", ".", "frame_no", "self", ".", "data", "=", "other", ".", "data", "self", ".", "type", "=", "other", ".", "type", "self", ".", "metadata", ".", "copy", ...
Initialise a :py:class:`Frame` from another :py:class:`Frame`. Copies the metadata and (a reference to) the data from :py:obj:`other`. Note that the data is not actually copied -- you must make a copy of the data before changing it. :param Frame other: The frame to copy.
[ "Initialise", "a", ":", "py", ":", "class", ":", "Frame", "from", "another", ":", "py", ":", "class", ":", "Frame", "." ]
2a958665326892f45f249bebe62c2c23f306732b
https://github.com/jim-easterbrook/pyctools/blob/2a958665326892f45f249bebe62c2c23f306732b/src/pyctools/core/frame.py#L67-L80
train
Initialise a : py : class : Frame from another.
jim-easterbrook/pyctools
src/pyctools/core/frame.py
Frame.size
def size(self): """Return image dimensions (height, width)""" if isinstance(self.data, numpy.ndarray): h, w = self.data.shape[:2] elif isinstance(self.data, PIL.Image.Image): w, h = self.data.size() else: raise RuntimeError( 'Cannot get...
python
def size(self): """Return image dimensions (height, width)""" if isinstance(self.data, numpy.ndarray): h, w = self.data.shape[:2] elif isinstance(self.data, PIL.Image.Image): w, h = self.data.size() else: raise RuntimeError( 'Cannot get...
[ "def", "size", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "data", ",", "numpy", ".", "ndarray", ")", ":", "h", ",", "w", "=", "self", ".", "data", ".", "shape", "[", ":", "2", "]", "elif", "isinstance", "(", "self", ".", "data...
Return image dimensions (height, width)
[ "Return", "image", "dimensions", "(", "height", "width", ")" ]
2a958665326892f45f249bebe62c2c23f306732b
https://github.com/jim-easterbrook/pyctools/blob/2a958665326892f45f249bebe62c2c23f306732b/src/pyctools/core/frame.py#L82-L91
train
Return image dimensions h and w
jim-easterbrook/pyctools
src/pyctools/core/frame.py
Frame.as_numpy
def as_numpy(self, dtype=None, copy=False): """Get image data in :py:class:`numpy:numpy.ndarray` form. Note that if the image data is already in the correct format this can be a null operation. When converting to limited range types (``numpy.uint8``, ``numpy.uint16``) the data ...
python
def as_numpy(self, dtype=None, copy=False): """Get image data in :py:class:`numpy:numpy.ndarray` form. Note that if the image data is already in the correct format this can be a null operation. When converting to limited range types (``numpy.uint8``, ``numpy.uint16``) the data ...
[ "def", "as_numpy", "(", "self", ",", "dtype", "=", "None", ",", "copy", "=", "False", ")", ":", "if", "isinstance", "(", "self", ".", "data", ",", "numpy", ".", "ndarray", ")", ":", "result", "=", "self", ".", "data", "elif", "isinstance", "(", "se...
Get image data in :py:class:`numpy:numpy.ndarray` form. Note that if the image data is already in the correct format this can be a null operation. When converting to limited range types (``numpy.uint8``, ``numpy.uint16``) the data is clipped (limited) to the range. :keyword nu...
[ "Get", "image", "data", "in", ":", "py", ":", "class", ":", "numpy", ":", "numpy", ".", "ndarray", "form", "." ]
2a958665326892f45f249bebe62c2c23f306732b
https://github.com/jim-easterbrook/pyctools/blob/2a958665326892f45f249bebe62c2c23f306732b/src/pyctools/core/frame.py#L93-L144
train
Returns the image data in numpy. ndarray form.
jim-easterbrook/pyctools
src/pyctools/core/frame.py
Frame.as_PIL
def as_PIL(self): """Get image data in :py:mod:`PIL:PIL.Image` form. Note that if the image data is already in the correct format this is a null operation. :return: The image data as :py:mod:`PIL:PIL.Image`. :rtype: :py:mod:`PIL:PIL.Image` """ if isinstance(se...
python
def as_PIL(self): """Get image data in :py:mod:`PIL:PIL.Image` form. Note that if the image data is already in the correct format this is a null operation. :return: The image data as :py:mod:`PIL:PIL.Image`. :rtype: :py:mod:`PIL:PIL.Image` """ if isinstance(se...
[ "def", "as_PIL", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "data", ",", "numpy", ".", "ndarray", ")", ":", "if", "self", ".", "data", ".", "dtype", "==", "numpy", ".", "uint8", ":", "result", "=", "PIL", ".", "Image", ".", "fro...
Get image data in :py:mod:`PIL:PIL.Image` form. Note that if the image data is already in the correct format this is a null operation. :return: The image data as :py:mod:`PIL:PIL.Image`. :rtype: :py:mod:`PIL:PIL.Image`
[ "Get", "image", "data", "in", ":", "py", ":", "mod", ":", "PIL", ":", "PIL", ".", "Image", "form", "." ]
2a958665326892f45f249bebe62c2c23f306732b
https://github.com/jim-easterbrook/pyctools/blob/2a958665326892f45f249bebe62c2c23f306732b/src/pyctools/core/frame.py#L146-L168
train
Get image data in PIL. Image form.
jim-easterbrook/pyctools
src/pyctools/core/frame.py
Metadata.from_file
def from_file(self, path): """Read metadata from an XMP sidecar file or, if there is no sidecar, from the image/video file (if it has metadata). Returns the :py:class:`Metadata` object, allowing convenient code like this:: md = Metadata().from_file(path) :param str...
python
def from_file(self, path): """Read metadata from an XMP sidecar file or, if there is no sidecar, from the image/video file (if it has metadata). Returns the :py:class:`Metadata` object, allowing convenient code like this:: md = Metadata().from_file(path) :param str...
[ "def", "from_file", "(", "self", ",", "path", ")", ":", "for", "xmp_path", "in", "(", "path", "+", "'.xmp'", ",", "path", ")", ":", "md", "=", "GExiv2", ".", "Metadata", "(", ")", "try", ":", "md", ".", "open_path", "(", "xmp_path", ")", "except", ...
Read metadata from an XMP sidecar file or, if there is no sidecar, from the image/video file (if it has metadata). Returns the :py:class:`Metadata` object, allowing convenient code like this:: md = Metadata().from_file(path) :param str path: The image/video file path name....
[ "Read", "metadata", "from", "an", "XMP", "sidecar", "file", "or", "if", "there", "is", "no", "sidecar", "from", "the", "image", "/", "video", "file", "(", "if", "it", "has", "metadata", ")", "." ]
2a958665326892f45f249bebe62c2c23f306732b
https://github.com/jim-easterbrook/pyctools/blob/2a958665326892f45f249bebe62c2c23f306732b/src/pyctools/core/frame.py#L201-L229
train
Read metadata from an XMP sidecar file or from the image / video file.
jim-easterbrook/pyctools
src/pyctools/core/frame.py
Metadata.to_file
def to_file(self, path): """Write metadata to an image, video or XMP sidecar file. :param str path: The image/video file path name. """ xmp_path = path + '.xmp' # remove any existing XMP file if os.path.exists(xmp_path): os.unlink(xmp_path) # attempt...
python
def to_file(self, path): """Write metadata to an image, video or XMP sidecar file. :param str path: The image/video file path name. """ xmp_path = path + '.xmp' # remove any existing XMP file if os.path.exists(xmp_path): os.unlink(xmp_path) # attempt...
[ "def", "to_file", "(", "self", ",", "path", ")", ":", "xmp_path", "=", "path", "+", "'.xmp'", "# remove any existing XMP file", "if", "os", ".", "path", ".", "exists", "(", "xmp_path", ")", ":", "os", ".", "unlink", "(", "xmp_path", ")", "# attempt to open...
Write metadata to an image, video or XMP sidecar file. :param str path: The image/video file path name.
[ "Write", "metadata", "to", "an", "image", "video", "or", "XMP", "sidecar", "file", "." ]
2a958665326892f45f249bebe62c2c23f306732b
https://github.com/jim-easterbrook/pyctools/blob/2a958665326892f45f249bebe62c2c23f306732b/src/pyctools/core/frame.py#L231-L274
train
Write metadata to an image video or XMP sidecar file.
jim-easterbrook/pyctools
src/pyctools/core/frame.py
Metadata.copy
def copy(self, other): """Copy metadata from another :py:class:`Metadata` object. Returns the :py:class:`Metadata` object, allowing convenient code like this:: md = Metadata().copy(other_md) :param Metadata other: The metadata to copy. :rtype: :py:class:`Metadata`...
python
def copy(self, other): """Copy metadata from another :py:class:`Metadata` object. Returns the :py:class:`Metadata` object, allowing convenient code like this:: md = Metadata().copy(other_md) :param Metadata other: The metadata to copy. :rtype: :py:class:`Metadata`...
[ "def", "copy", "(", "self", ",", "other", ")", ":", "# copy from other to self", "self", ".", "data", ".", "update", "(", "other", ".", "data", ")", "if", "other", ".", "comment", "is", "not", "None", ":", "self", ".", "comment", "=", "other", ".", "...
Copy metadata from another :py:class:`Metadata` object. Returns the :py:class:`Metadata` object, allowing convenient code like this:: md = Metadata().copy(other_md) :param Metadata other: The metadata to copy. :rtype: :py:class:`Metadata`
[ "Copy", "metadata", "from", "another", ":", "py", ":", "class", ":", "Metadata", "object", "." ]
2a958665326892f45f249bebe62c2c23f306732b
https://github.com/jim-easterbrook/pyctools/blob/2a958665326892f45f249bebe62c2c23f306732b/src/pyctools/core/frame.py#L276-L293
train
Returns a copy of this object with the contents of the other object.
jim-easterbrook/pyctools
src/pyctools/core/frame.py
Metadata.image_size
def image_size(self): """Get image dimensions from metadata. This is primarily used by the :py:class:`~pyctools.components.io.rawfilereader.RawFileReader` component, as raw video files don't have a header in which to store the dimensions. :returns: width, height. ...
python
def image_size(self): """Get image dimensions from metadata. This is primarily used by the :py:class:`~pyctools.components.io.rawfilereader.RawFileReader` component, as raw video files don't have a header in which to store the dimensions. :returns: width, height. ...
[ "def", "image_size", "(", "self", ")", ":", "xlen", "=", "None", "ylen", "=", "None", "for", "tag", "in", "(", "'Xmp.pyctools.xlen'", ",", "'Exif.Photo.PixelXDimension'", ",", "'Exif.Image.ImageWidth'", ",", "'Xmp.tiff.ImageWidth'", ")", ":", "if", "tag", "in", ...
Get image dimensions from metadata. This is primarily used by the :py:class:`~pyctools.components.io.rawfilereader.RawFileReader` component, as raw video files don't have a header in which to store the dimensions. :returns: width, height. :rtype: :py:class:`int`, :py:c...
[ "Get", "image", "dimensions", "from", "metadata", "." ]
2a958665326892f45f249bebe62c2c23f306732b
https://github.com/jim-easterbrook/pyctools/blob/2a958665326892f45f249bebe62c2c23f306732b/src/pyctools/core/frame.py#L295-L322
train
Get image dimensions from metadata.
jim-easterbrook/pyctools
src/pyctools/core/frame.py
Metadata.get
def get(self, tag, default=None): """Get a metadata value. Each metadata value is referenced by a ``tag`` -- a short string such as ``'xlen'`` or ``'audit'``. In the sidecar file these tag names are prepended with ``'Xmp.pyctools.'``, which corresponds to a custom namespace in t...
python
def get(self, tag, default=None): """Get a metadata value. Each metadata value is referenced by a ``tag`` -- a short string such as ``'xlen'`` or ``'audit'``. In the sidecar file these tag names are prepended with ``'Xmp.pyctools.'``, which corresponds to a custom namespace in t...
[ "def", "get", "(", "self", ",", "tag", ",", "default", "=", "None", ")", ":", "full_tag", "=", "'Xmp.pyctools.'", "+", "tag", "if", "full_tag", "in", "self", ".", "data", ":", "return", "self", ".", "data", "[", "full_tag", "]", "return", "default" ]
Get a metadata value. Each metadata value is referenced by a ``tag`` -- a short string such as ``'xlen'`` or ``'audit'``. In the sidecar file these tag names are prepended with ``'Xmp.pyctools.'``, which corresponds to a custom namespace in the XML file. :param str tag: The tag...
[ "Get", "a", "metadata", "value", "." ]
2a958665326892f45f249bebe62c2c23f306732b
https://github.com/jim-easterbrook/pyctools/blob/2a958665326892f45f249bebe62c2c23f306732b/src/pyctools/core/frame.py#L324-L342
train
Get a metadata value associated with a tag.
jim-easterbrook/pyctools
src/pyctools/core/frame.py
Metadata.set
def set(self, tag, value): """Set a metadata value. Each metadata value is referenced by a ``tag`` -- a short string such as ``'xlen'`` or ``'audit'``. In the sidecar file these tag names are prepended with ``'Xmp.pyctools.'``, which corresponds to a custom namespace in the XML ...
python
def set(self, tag, value): """Set a metadata value. Each metadata value is referenced by a ``tag`` -- a short string such as ``'xlen'`` or ``'audit'``. In the sidecar file these tag names are prepended with ``'Xmp.pyctools.'``, which corresponds to a custom namespace in the XML ...
[ "def", "set", "(", "self", ",", "tag", ",", "value", ")", ":", "full_tag", "=", "'Xmp.pyctools.'", "+", "tag", "self", ".", "data", "[", "full_tag", "]", "=", "value" ]
Set a metadata value. Each metadata value is referenced by a ``tag`` -- a short string such as ``'xlen'`` or ``'audit'``. In the sidecar file these tag names are prepended with ``'Xmp.pyctools.'``, which corresponds to a custom namespace in the XML file. :param str tag: The tag...
[ "Set", "a", "metadata", "value", "." ]
2a958665326892f45f249bebe62c2c23f306732b
https://github.com/jim-easterbrook/pyctools/blob/2a958665326892f45f249bebe62c2c23f306732b/src/pyctools/core/frame.py#L344-L358
train
Set a metadata value.
biplap-sarkar/pylimit
pylimit/redis_helper.py
RedisHelper.get_connection
def get_connection(self, is_read_only=False) -> redis.StrictRedis: """ Gets a StrictRedis connection for normal redis or for redis sentinel based upon redis mode in configuration. :type is_read_only: bool :param is_read_only: In case of redis sentinel, it returns connection to slave ...
python
def get_connection(self, is_read_only=False) -> redis.StrictRedis: """ Gets a StrictRedis connection for normal redis or for redis sentinel based upon redis mode in configuration. :type is_read_only: bool :param is_read_only: In case of redis sentinel, it returns connection to slave ...
[ "def", "get_connection", "(", "self", ",", "is_read_only", "=", "False", ")", "->", "redis", ".", "StrictRedis", ":", "if", "self", ".", "connection", "is", "not", "None", ":", "return", "self", ".", "connection", "if", "self", ".", "is_sentinel", ":", "...
Gets a StrictRedis connection for normal redis or for redis sentinel based upon redis mode in configuration. :type is_read_only: bool :param is_read_only: In case of redis sentinel, it returns connection to slave :return: Returns a StrictRedis connection
[ "Gets", "a", "StrictRedis", "connection", "for", "normal", "redis", "or", "for", "redis", "sentinel", "based", "upon", "redis", "mode", "in", "configuration", "." ]
d2170a8c02a9be083f37c9e4ec1e28700a33d64e
https://github.com/biplap-sarkar/pylimit/blob/d2170a8c02a9be083f37c9e4ec1e28700a33d64e/pylimit/redis_helper.py#L18-L43
train
Gets a StrictRedis connection for the current instance of the class.
nicoddemus/ss
ss.py
filter_bad_results
def filter_bad_results(search_results, guessit_query): """ filter out search results with bad season and episode number (if applicable); sometimes OpenSubtitles will report search results subtitles that belong to a different episode or season from a tv show; no reason why, but it seems to work well ...
python
def filter_bad_results(search_results, guessit_query): """ filter out search results with bad season and episode number (if applicable); sometimes OpenSubtitles will report search results subtitles that belong to a different episode or season from a tv show; no reason why, but it seems to work well ...
[ "def", "filter_bad_results", "(", "search_results", ",", "guessit_query", ")", ":", "if", "'season'", "in", "guessit_query", "and", "'episode'", "in", "guessit_query", ":", "guessit_season_episode", "=", "(", "guessit_query", "[", "'season'", "]", ",", "guessit_quer...
filter out search results with bad season and episode number (if applicable); sometimes OpenSubtitles will report search results subtitles that belong to a different episode or season from a tv show; no reason why, but it seems to work well just filtering those out
[ "filter", "out", "search", "results", "with", "bad", "season", "and", "episode", "number", "(", "if", "applicable", ")", ";", "sometimes", "OpenSubtitles", "will", "report", "search", "results", "subtitles", "that", "belong", "to", "a", "different", "episode", ...
df77c745e511f542c456450ed94adff1b969fc92
https://github.com/nicoddemus/ss/blob/df77c745e511f542c456450ed94adff1b969fc92/ss.py#L66-L77
train
Filter out search results with bad season and episode number.
nicoddemus/ss
ss.py
calculate_hash_for_file
def calculate_hash_for_file(name): ''' Calculates the hash for the given filename. Algorithm from: http://trac.opensubtitles.org/projects/opensubtitles/wiki/HashSourceCodes @param name: str Path to the file @return: str The calculated hash code, as an hex string. ''' longl...
python
def calculate_hash_for_file(name): ''' Calculates the hash for the given filename. Algorithm from: http://trac.opensubtitles.org/projects/opensubtitles/wiki/HashSourceCodes @param name: str Path to the file @return: str The calculated hash code, as an hex string. ''' longl...
[ "def", "calculate_hash_for_file", "(", "name", ")", ":", "longlongformat", "=", "'q'", "# long long", "bytesize", "=", "struct", ".", "calcsize", "(", "longlongformat", ")", "f", "=", "open", "(", "name", ",", "\"rb\"", ")", "filesize", "=", "os", ".", "pa...
Calculates the hash for the given filename. Algorithm from: http://trac.opensubtitles.org/projects/opensubtitles/wiki/HashSourceCodes @param name: str Path to the file @return: str The calculated hash code, as an hex string.
[ "Calculates", "the", "hash", "for", "the", "given", "filename", "." ]
df77c745e511f542c456450ed94adff1b969fc92
https://github.com/nicoddemus/ss/blob/df77c745e511f542c456450ed94adff1b969fc92/ss.py#L218-L259
train
Calculates the hash for the given file.
nicoddemus/ss
ss.py
check_output
def check_output(params): """ Python 2.6 support: subprocess.check_output from Python 2.7. """ popen = subprocess.Popen(params, shell=True, stderr=subprocess.STDOUT, stdout=subprocess.PIPE) output, _ = popen.communicate() returncode = popen.poll() if returncode ...
python
def check_output(params): """ Python 2.6 support: subprocess.check_output from Python 2.7. """ popen = subprocess.Popen(params, shell=True, stderr=subprocess.STDOUT, stdout=subprocess.PIPE) output, _ = popen.communicate() returncode = popen.poll() if returncode ...
[ "def", "check_output", "(", "params", ")", ":", "popen", "=", "subprocess", ".", "Popen", "(", "params", ",", "shell", "=", "True", ",", "stderr", "=", "subprocess", ".", "STDOUT", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "output", ",", "_",...
Python 2.6 support: subprocess.check_output from Python 2.7.
[ "Python", "2", ".", "6", "support", ":", "subprocess", ".", "check_output", "from", "Python", "2", ".", "7", "." ]
df77c745e511f542c456450ed94adff1b969fc92
https://github.com/nicoddemus/ss/blob/df77c745e511f542c456450ed94adff1b969fc92/ss.py#L493-L506
train
Python 2. 6 support subprocess. check_output from Python 2. 7.
jim-easterbrook/pyctools
src/pyctools/core/config.py
ConfigParent.parser_add
def parser_add(self, parser, prefix=''): """Add config to an :py:class:`argparse.ArgumentParser` object. The parser’s :py:meth:`~argparse.ArgumentParser.add_argument` method is called for each config item. The argument name is constructed from the parent and item names, with a dot ...
python
def parser_add(self, parser, prefix=''): """Add config to an :py:class:`argparse.ArgumentParser` object. The parser’s :py:meth:`~argparse.ArgumentParser.add_argument` method is called for each config item. The argument name is constructed from the parent and item names, with a dot ...
[ "def", "parser_add", "(", "self", ",", "parser", ",", "prefix", "=", "''", ")", ":", "if", "prefix", ":", "prefix", "+=", "'.'", "for", "key", ",", "value", "in", "self", ".", "items", "(", ")", ":", "value", ".", "parser_add", "(", "parser", ",", ...
Add config to an :py:class:`argparse.ArgumentParser` object. The parser’s :py:meth:`~argparse.ArgumentParser.add_argument` method is called for each config item. The argument name is constructed from the parent and item names, with a dot separator. :param argparse.ArgumentParse...
[ "Add", "config", "to", "an", ":", "py", ":", "class", ":", "argparse", ".", "ArgumentParser", "object", "." ]
2a958665326892f45f249bebe62c2c23f306732b
https://github.com/jim-easterbrook/pyctools/blob/2a958665326892f45f249bebe62c2c23f306732b/src/pyctools/core/config.py#L289-L305
train
Add config to an argument parser object.
jim-easterbrook/pyctools
src/pyctools/core/config.py
ConfigParent.parser_set
def parser_set(self, args): """Set config from an :py:class:`argparse.Namespace` object. Call this method with the return value from :py:meth:`~argparse.ArgumentParser.parse_args`. :param argparse.Namespace args: The populated :py:class:`argparse.Namespace` object. ...
python
def parser_set(self, args): """Set config from an :py:class:`argparse.Namespace` object. Call this method with the return value from :py:meth:`~argparse.ArgumentParser.parse_args`. :param argparse.Namespace args: The populated :py:class:`argparse.Namespace` object. ...
[ "def", "parser_set", "(", "self", ",", "args", ")", ":", "for", "key", ",", "value", "in", "vars", "(", "args", ")", ".", "items", "(", ")", ":", "self", ".", "_parser_update", "(", "key", ",", "value", ")" ]
Set config from an :py:class:`argparse.Namespace` object. Call this method with the return value from :py:meth:`~argparse.ArgumentParser.parse_args`. :param argparse.Namespace args: The populated :py:class:`argparse.Namespace` object.
[ "Set", "config", "from", "an", ":", "py", ":", "class", ":", "argparse", ".", "Namespace", "object", "." ]
2a958665326892f45f249bebe62c2c23f306732b
https://github.com/jim-easterbrook/pyctools/blob/2a958665326892f45f249bebe62c2c23f306732b/src/pyctools/core/config.py#L307-L318
train
Set config from an argparse. Namespace object.
jim-easterbrook/pyctools
src/pyctools/core/config.py
ConfigMixin.set_config
def set_config(self, config): """Update the component's configuration. Use the :py:meth:`get_config` method to get a copy of the component's configuration, update that copy then call :py:meth:`set_config` to update the component. This enables the configuration to be changed in a...
python
def set_config(self, config): """Update the component's configuration. Use the :py:meth:`get_config` method to get a copy of the component's configuration, update that copy then call :py:meth:`set_config` to update the component. This enables the configuration to be changed in a...
[ "def", "set_config", "(", "self", ",", "config", ")", ":", "# put copy of config on queue for running component", "self", ".", "_configmixin_queue", ".", "append", "(", "copy", ".", "deepcopy", "(", "config", ")", ")", "# notify component, using thread safe method", "se...
Update the component's configuration. Use the :py:meth:`get_config` method to get a copy of the component's configuration, update that copy then call :py:meth:`set_config` to update the component. This enables the configuration to be changed in a threadsafe manner while the comp...
[ "Update", "the", "component", "s", "configuration", "." ]
2a958665326892f45f249bebe62c2c23f306732b
https://github.com/jim-easterbrook/pyctools/blob/2a958665326892f45f249bebe62c2c23f306732b/src/pyctools/core/config.py#L381-L397
train
Update the component s configuration.
jim-easterbrook/pyctools
src/pyctools/core/config.py
ConfigMixin.update_config
def update_config(self): """Pull any changes made with :py:meth:`set_config`. Call this from within your component before using any config values to ensure you have the latest values set by the user. :return: Whether the config was updated. :rtype: bool """ res...
python
def update_config(self): """Pull any changes made with :py:meth:`set_config`. Call this from within your component before using any config values to ensure you have the latest values set by the user. :return: Whether the config was updated. :rtype: bool """ res...
[ "def", "update_config", "(", "self", ")", ":", "result", "=", "False", "while", "self", ".", "_configmixin_queue", ":", "config", "=", "self", ".", "_configmixin_queue", ".", "popleft", "(", ")", "self", ".", "config", ".", "update", "(", "config", ")", ...
Pull any changes made with :py:meth:`set_config`. Call this from within your component before using any config values to ensure you have the latest values set by the user. :return: Whether the config was updated. :rtype: bool
[ "Pull", "any", "changes", "made", "with", ":", "py", ":", "meth", ":", "set_config", "." ]
2a958665326892f45f249bebe62c2c23f306732b
https://github.com/jim-easterbrook/pyctools/blob/2a958665326892f45f249bebe62c2c23f306732b/src/pyctools/core/config.py#L399-L414
train
Update the config with any changes made with set_config.
jim-easterbrook/pyctools
src/pyctools/components/interp/gaussianfilter.py
GaussianFilterCore
def GaussianFilterCore(x_sigma=0.0, y_sigma=0.0): """Gaussian filter generator core. Alternative to the :py:class:`GaussianFilter` component that can be used to make a non-reconfigurable resizer:: resize = Resize() resize.filter(GaussianFilterCore(x_sigma=1.5)) ... start(.....
python
def GaussianFilterCore(x_sigma=0.0, y_sigma=0.0): """Gaussian filter generator core. Alternative to the :py:class:`GaussianFilter` component that can be used to make a non-reconfigurable resizer:: resize = Resize() resize.filter(GaussianFilterCore(x_sigma=1.5)) ... start(.....
[ "def", "GaussianFilterCore", "(", "x_sigma", "=", "0.0", ",", "y_sigma", "=", "0.0", ")", ":", "def", "filter_1D", "(", "sigma", ")", ":", "alpha", "=", "1.0", "/", "(", "2.0", "*", "(", "max", "(", "sigma", ",", "0.0001", ")", "**", "2.0", ")", ...
Gaussian filter generator core. Alternative to the :py:class:`GaussianFilter` component that can be used to make a non-reconfigurable resizer:: resize = Resize() resize.filter(GaussianFilterCore(x_sigma=1.5)) ... start(..., resize, ...) ... :keyword float x_sigma: ...
[ "Gaussian", "filter", "generator", "core", "." ]
2a958665326892f45f249bebe62c2c23f306732b
https://github.com/jim-easterbrook/pyctools/blob/2a958665326892f45f249bebe62c2c23f306732b/src/pyctools/components/interp/gaussianfilter.py#L92-L147
train
Gaussian Filter generator core.
jim-easterbrook/pyctools
src/pyctools/core/qt.py
QtEventLoop.queue_command
def queue_command(self, command): """Put a command on the queue to be called in the component's thread. :param callable command: the method to be invoked, e.g. :py:meth:`~Component.new_frame_event`. """ if self._running: # queue event normally ...
python
def queue_command(self, command): """Put a command on the queue to be called in the component's thread. :param callable command: the method to be invoked, e.g. :py:meth:`~Component.new_frame_event`. """ if self._running: # queue event normally ...
[ "def", "queue_command", "(", "self", ",", "command", ")", ":", "if", "self", ".", "_running", ":", "# queue event normally", "QtCore", ".", "QCoreApplication", ".", "postEvent", "(", "self", ",", "ActionEvent", "(", "command", ")", ",", "QtCore", ".", "Qt", ...
Put a command on the queue to be called in the component's thread. :param callable command: the method to be invoked, e.g. :py:meth:`~Component.new_frame_event`.
[ "Put", "a", "command", "on", "the", "queue", "to", "be", "called", "in", "the", "component", "s", "thread", "." ]
2a958665326892f45f249bebe62c2c23f306732b
https://github.com/jim-easterbrook/pyctools/blob/2a958665326892f45f249bebe62c2c23f306732b/src/pyctools/core/qt.py#L72-L86
train
Put a command on the queue to be called in the component s thread.
jim-easterbrook/pyctools
src/pyctools/core/qt.py
QtEventLoop.start
def start(self): """Start the component's event loop (thread-safe). After the event loop is started the Qt thread calls the component's :py:meth:`~Component.start_event` method, then calls its :py:meth:`~Component.new_frame_event` and :py:meth:`~Component.new_config_event` metho...
python
def start(self): """Start the component's event loop (thread-safe). After the event loop is started the Qt thread calls the component's :py:meth:`~Component.start_event` method, then calls its :py:meth:`~Component.new_frame_event` and :py:meth:`~Component.new_config_event` metho...
[ "def", "start", "(", "self", ")", ":", "if", "self", ".", "_running", ":", "raise", "RuntimeError", "(", "'Component {} is already running'", ".", "format", "(", "self", ".", "_owner", ".", "__class__", ".", "__name__", ")", ")", "self", ".", "_running", "...
Start the component's event loop (thread-safe). After the event loop is started the Qt thread calls the component's :py:meth:`~Component.start_event` method, then calls its :py:meth:`~Component.new_frame_event` and :py:meth:`~Component.new_config_event` methods as required until ...
[ "Start", "the", "component", "s", "event", "loop", "(", "thread", "-", "safe", ")", "." ]
2a958665326892f45f249bebe62c2c23f306732b
https://github.com/jim-easterbrook/pyctools/blob/2a958665326892f45f249bebe62c2c23f306732b/src/pyctools/core/qt.py#L91-L110
train
Start the event loop.
jim-easterbrook/pyctools
src/pyctools/core/qt.py
QtEventLoop.join
def join(self, timeout=3600): """Wait until the event loop terminates or ``timeout`` is reached. This method is not meaningful unless called from the Qt "main thread", which is almost certainly the thread in which the component was created. :keyword float timeout: timeo...
python
def join(self, timeout=3600): """Wait until the event loop terminates or ``timeout`` is reached. This method is not meaningful unless called from the Qt "main thread", which is almost certainly the thread in which the component was created. :keyword float timeout: timeo...
[ "def", "join", "(", "self", ",", "timeout", "=", "3600", ")", ":", "start", "=", "time", ".", "time", "(", ")", "while", "self", ".", "_running", ":", "now", "=", "time", ".", "time", "(", ")", "maxtime", "=", "timeout", "+", "start", "-", "now",...
Wait until the event loop terminates or ``timeout`` is reached. This method is not meaningful unless called from the Qt "main thread", which is almost certainly the thread in which the component was created. :keyword float timeout: timeout in seconds.
[ "Wait", "until", "the", "event", "loop", "terminates", "or", "timeout", "is", "reached", "." ]
2a958665326892f45f249bebe62c2c23f306732b
https://github.com/jim-easterbrook/pyctools/blob/2a958665326892f45f249bebe62c2c23f306732b/src/pyctools/core/qt.py#L112-L130
train
Wait until the event loop terminates or timeout is reached.
jim-easterbrook/pyctools
src/pyctools/components/deinterlace/intrafield.py
IntraField
def IntraField(config={}): """Intra field interlace to sequential converter. This uses a vertical filter with an aperture of 8 lines, generated by :py:class:`~pyctools.components.interp.filtergenerator.FilterGenerator`. The aperture (and other parameters) can be adjusted after the :py:class:`In...
python
def IntraField(config={}): """Intra field interlace to sequential converter. This uses a vertical filter with an aperture of 8 lines, generated by :py:class:`~pyctools.components.interp.filtergenerator.FilterGenerator`. The aperture (and other parameters) can be adjusted after the :py:class:`In...
[ "def", "IntraField", "(", "config", "=", "{", "}", ")", ":", "return", "Compound", "(", "config", "=", "config", ",", "deint", "=", "SimpleDeinterlace", "(", ")", ",", "interp", "=", "Resize", "(", ")", ",", "filgen", "=", "FilterGenerator", "(", "yape...
Intra field interlace to sequential converter. This uses a vertical filter with an aperture of 8 lines, generated by :py:class:`~pyctools.components.interp.filtergenerator.FilterGenerator`. The aperture (and other parameters) can be adjusted after the :py:class:`IntraField` component is created.
[ "Intra", "field", "interlace", "to", "sequential", "converter", "." ]
2a958665326892f45f249bebe62c2c23f306732b
https://github.com/jim-easterbrook/pyctools/blob/2a958665326892f45f249bebe62c2c23f306732b/src/pyctools/components/deinterlace/intrafield.py#L28-L52
train
Intra field interlace to sequential converter.
biplap-sarkar/pylimit
pylimit/pyratelimit.py
PyRateLimit.init
def init(cls, redis_host: str, redis_port: int, is_sentinel_redis=False, redis_sentinel_service="mymaster", redis_password=None): """ Initializes redis connection :param redis_host: Hostname of redis server :type redis_host: str :param redis_port: Port at which redi...
python
def init(cls, redis_host: str, redis_port: int, is_sentinel_redis=False, redis_sentinel_service="mymaster", redis_password=None): """ Initializes redis connection :param redis_host: Hostname of redis server :type redis_host: str :param redis_port: Port at which redi...
[ "def", "init", "(", "cls", ",", "redis_host", ":", "str", ",", "redis_port", ":", "int", ",", "is_sentinel_redis", "=", "False", ",", "redis_sentinel_service", "=", "\"mymaster\"", ",", "redis_password", "=", "None", ")", ":", "if", "not", "cls", ".", "red...
Initializes redis connection :param redis_host: Hostname of redis server :type redis_host: str :param redis_port: Port at which redis server is listening :type redis_port:int :param is_sentinel_redis: Parameter indicating if redis server is a sentinel server. Default is false ...
[ "Initializes", "redis", "connection", ":", "param", "redis_host", ":", "Hostname", "of", "redis", "server", ":", "type", "redis_host", ":", "str" ]
d2170a8c02a9be083f37c9e4ec1e28700a33d64e
https://github.com/biplap-sarkar/pylimit/blob/d2170a8c02a9be083f37c9e4ec1e28700a33d64e/pylimit/pyratelimit.py#L15-L37
train
Initializes Redis connection object for a specific entry set.
biplap-sarkar/pylimit
pylimit/pyratelimit.py
PyRateLimit.create
def create(self, period: int, limit: int): """ Creates a rate limiting rule with rate limiting period and attempt limit :param period: Rate limiting period in seconds :type period: int :param limit: Number of attempts permitted by rate limiting within a given period :ty...
python
def create(self, period: int, limit: int): """ Creates a rate limiting rule with rate limiting period and attempt limit :param period: Rate limiting period in seconds :type period: int :param limit: Number of attempts permitted by rate limiting within a given period :ty...
[ "def", "create", "(", "self", ",", "period", ":", "int", ",", "limit", ":", "int", ")", ":", "self", ".", "period", "=", "period", "self", ".", "limit", "=", "limit" ]
Creates a rate limiting rule with rate limiting period and attempt limit :param period: Rate limiting period in seconds :type period: int :param limit: Number of attempts permitted by rate limiting within a given period :type limit: int
[ "Creates", "a", "rate", "limiting", "rule", "with", "rate", "limiting", "period", "and", "attempt", "limit" ]
d2170a8c02a9be083f37c9e4ec1e28700a33d64e
https://github.com/biplap-sarkar/pylimit/blob/d2170a8c02a9be083f37c9e4ec1e28700a33d64e/pylimit/pyratelimit.py#L39-L51
train
Creates a rate limiting rule with rate limiting period and attempt limit
biplap-sarkar/pylimit
pylimit/pyratelimit.py
PyRateLimit.__can_attempt
def __can_attempt(self, namespace: str, add_attempt=True) -> bool: """ Checks if a namespace is rate limited or not with including/excluding the current call :param namespace: Rate limiting namespace :type namespace: str :param add_attempt: Boolean value indicating if the curre...
python
def __can_attempt(self, namespace: str, add_attempt=True) -> bool: """ Checks if a namespace is rate limited or not with including/excluding the current call :param namespace: Rate limiting namespace :type namespace: str :param add_attempt: Boolean value indicating if the curre...
[ "def", "__can_attempt", "(", "self", ",", "namespace", ":", "str", ",", "add_attempt", "=", "True", ")", "->", "bool", ":", "can_attempt", "=", "False", "if", "not", "PyRateLimit", ".", "redis_helper", ":", "raise", "PyRateLimitException", "(", "\"redis connec...
Checks if a namespace is rate limited or not with including/excluding the current call :param namespace: Rate limiting namespace :type namespace: str :param add_attempt: Boolean value indicating if the current call should be considered as an attempt or not :type add_attempt: bool ...
[ "Checks", "if", "a", "namespace", "is", "rate", "limited", "or", "not", "with", "including", "/", "excluding", "the", "current", "call" ]
d2170a8c02a9be083f37c9e4ec1e28700a33d64e
https://github.com/biplap-sarkar/pylimit/blob/d2170a8c02a9be083f37c9e4ec1e28700a33d64e/pylimit/pyratelimit.py#L53-L83
train
Checks if a namespace is rate limited or not with including or excluding the current call.
biplap-sarkar/pylimit
pylimit/pyratelimit.py
PyRateLimit.is_rate_limited
def is_rate_limited(self, namespace: str) -> bool: """ Checks if a namespace is already rate limited or not without making any additional attempts :param namespace: Rate limiting namespace :type namespace: str :return: Returns true if attempt can go ahead under current rate...
python
def is_rate_limited(self, namespace: str) -> bool: """ Checks if a namespace is already rate limited or not without making any additional attempts :param namespace: Rate limiting namespace :type namespace: str :return: Returns true if attempt can go ahead under current rate...
[ "def", "is_rate_limited", "(", "self", ",", "namespace", ":", "str", ")", "->", "bool", ":", "return", "not", "self", ".", "__can_attempt", "(", "namespace", "=", "namespace", ",", "add_attempt", "=", "False", ")" ]
Checks if a namespace is already rate limited or not without making any additional attempts :param namespace: Rate limiting namespace :type namespace: str :return: Returns true if attempt can go ahead under current rate limiting rules, false otherwise
[ "Checks", "if", "a", "namespace", "is", "already", "rate", "limited", "or", "not", "without", "making", "any", "additional", "attempts" ]
d2170a8c02a9be083f37c9e4ec1e28700a33d64e
https://github.com/biplap-sarkar/pylimit/blob/d2170a8c02a9be083f37c9e4ec1e28700a33d64e/pylimit/pyratelimit.py#L96-L105
train
Checks if a namespace is already rate limited or not
NUAA-Open-Source/NUAA-iCal-Python
NUAAiCal/AddToGCal.py
get_credentials
def get_credentials(): """Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to obtain the new credentials. Returns: Credentials, the obtained credential. """ home_dir = os.path.expanduser('~') ...
python
def get_credentials(): """Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to obtain the new credentials. Returns: Credentials, the obtained credential. """ home_dir = os.path.expanduser('~') ...
[ "def", "get_credentials", "(", ")", ":", "home_dir", "=", "os", ".", "path", ".", "expanduser", "(", "'~'", ")", "credential_dir", "=", "os", ".", "path", ".", "join", "(", "home_dir", ",", "'.credentials'", ")", "if", "not", "os", ".", "path", ".", ...
Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to obtain the new credentials. Returns: Credentials, the obtained credential.
[ "Gets", "valid", "user", "credentials", "from", "storage", "." ]
1bdc4016e4d8b236a12bba5047a5150f889bc880
https://github.com/NUAA-Open-Source/NUAA-iCal-Python/blob/1bdc4016e4d8b236a12bba5047a5150f889bc880/NUAAiCal/AddToGCal.py#L25-L51
train
Gets valid user credentials from storage.
NUAA-Open-Source/NUAA-iCal-Python
NUAAiCal/AddToGCal.py
main
def main(): """Shows basic usage of the Google Calendar API. Creates a Google Calendar API service object and outputs a list of the next 10 events on the user's calendar. """ credentials = get_credentials() http = credentials.authorize(httplib2.Http()) service = discovery.build('calendar', ...
python
def main(): """Shows basic usage of the Google Calendar API. Creates a Google Calendar API service object and outputs a list of the next 10 events on the user's calendar. """ credentials = get_credentials() http = credentials.authorize(httplib2.Http()) service = discovery.build('calendar', ...
[ "def", "main", "(", ")", ":", "credentials", "=", "get_credentials", "(", ")", "http", "=", "credentials", ".", "authorize", "(", "httplib2", ".", "Http", "(", ")", ")", "service", "=", "discovery", ".", "build", "(", "'calendar'", ",", "'v3'", ",", "h...
Shows basic usage of the Google Calendar API. Creates a Google Calendar API service object and outputs a list of the next 10 events on the user's calendar.
[ "Shows", "basic", "usage", "of", "the", "Google", "Calendar", "API", "." ]
1bdc4016e4d8b236a12bba5047a5150f889bc880
https://github.com/NUAA-Open-Source/NUAA-iCal-Python/blob/1bdc4016e4d8b236a12bba5047a5150f889bc880/NUAAiCal/AddToGCal.py#L54-L75
train
Shows basic usage of the Google Calendar API.
kmike/port-for
port_for/docopt.py
parse_atom
def parse_atom(tokens, options): """atom ::= '(' expr ')' | '[' expr ']' | 'options' | long | shorts | argument | command ; """ token = tokens.current() result = [] if token == '(': tokens.move() result = [Required(*parse_expr(tokens, options))] if tokens.move() ...
python
def parse_atom(tokens, options): """atom ::= '(' expr ')' | '[' expr ']' | 'options' | long | shorts | argument | command ; """ token = tokens.current() result = [] if token == '(': tokens.move() result = [Required(*parse_expr(tokens, options))] if tokens.move() ...
[ "def", "parse_atom", "(", "tokens", ",", "options", ")", ":", "token", "=", "tokens", ".", "current", "(", ")", "result", "=", "[", "]", "if", "token", "==", "'('", ":", "tokens", ".", "move", "(", ")", "result", "=", "[", "Required", "(", "*", "...
atom ::= '(' expr ')' | '[' expr ']' | 'options' | long | shorts | argument | command ;
[ "atom", "::", "=", "(", "expr", ")", "|", "[", "expr", "]", "|", "options", "|", "long", "|", "shorts", "|", "argument", "|", "command", ";" ]
f61ebf3c2caf54eabe8233b40ef67b973176a6f5
https://github.com/kmike/port-for/blob/f61ebf3c2caf54eabe8233b40ef67b973176a6f5/port_for/docopt.py#L365-L393
train
Parse an atom from the tokens.
kmike/port-for
port_for/docopt.py
Pattern.fix_list_arguments
def fix_list_arguments(self): """Find arguments that should accumulate values and fix them.""" either = [list(c.children) for c in self.either.children] for case in either: case = [c for c in case if case.count(c) > 1] for a in [e for e in case if type(e) == Argument]: ...
python
def fix_list_arguments(self): """Find arguments that should accumulate values and fix them.""" either = [list(c.children) for c in self.either.children] for case in either: case = [c for c in case if case.count(c) > 1] for a in [e for e in case if type(e) == Argument]: ...
[ "def", "fix_list_arguments", "(", "self", ")", ":", "either", "=", "[", "list", "(", "c", ".", "children", ")", "for", "c", "in", "self", ".", "either", ".", "children", "]", "for", "case", "in", "either", ":", "case", "=", "[", "c", "for", "c", ...
Find arguments that should accumulate values and fix them.
[ "Find", "arguments", "that", "should", "accumulate", "values", "and", "fix", "them", "." ]
f61ebf3c2caf54eabe8233b40ef67b973176a6f5
https://github.com/kmike/port-for/blob/f61ebf3c2caf54eabe8233b40ef67b973176a6f5/port_for/docopt.py#L59-L66
train
Find arguments that should accumulate values and fix them.
kmike/port-for
port_for/docopt.py
Pattern.either
def either(self): """Transform pattern into an equivalent, with only top-level Either.""" # Currently the pattern will not be equivalent, but more "narrow", # although good enough to reason about list arguments. if not hasattr(self, 'children'): return Either(Required(self)) ...
python
def either(self): """Transform pattern into an equivalent, with only top-level Either.""" # Currently the pattern will not be equivalent, but more "narrow", # although good enough to reason about list arguments. if not hasattr(self, 'children'): return Either(Required(self)) ...
[ "def", "either", "(", "self", ")", ":", "# Currently the pattern will not be equivalent, but more \"narrow\",", "# although good enough to reason about list arguments.", "if", "not", "hasattr", "(", "self", ",", "'children'", ")", ":", "return", "Either", "(", "Required", "...
Transform pattern into an equivalent, with only top-level Either.
[ "Transform", "pattern", "into", "an", "equivalent", "with", "only", "top", "-", "level", "Either", "." ]
f61ebf3c2caf54eabe8233b40ef67b973176a6f5
https://github.com/kmike/port-for/blob/f61ebf3c2caf54eabe8233b40ef67b973176a6f5/port_for/docopt.py#L69-L100
train
Transform pattern into an equivalent with only top - level Either.
nicfit/MishMash
mishmash/commands/sync/utils.py
syncImage
def syncImage(img, current, session): """Add or updated the Image.""" def _img_str(i): return "%s - %s" % (i.type, i.description) for db_img in current.images: img_info = (img.type, img.md5, img.size) db_img_info = (db_img.type, db_img.md5, db_img.size) if db_img_info == im...
python
def syncImage(img, current, session): """Add or updated the Image.""" def _img_str(i): return "%s - %s" % (i.type, i.description) for db_img in current.images: img_info = (img.type, img.md5, img.size) db_img_info = (db_img.type, db_img.md5, db_img.size) if db_img_info == im...
[ "def", "syncImage", "(", "img", ",", "current", ",", "session", ")", ":", "def", "_img_str", "(", "i", ")", ":", "return", "\"%s - %s\"", "%", "(", "i", ".", "type", ",", "i", ".", "description", ")", "for", "db_img", "in", "current", ".", "images", ...
Add or updated the Image.
[ "Add", "or", "updated", "the", "Image", "." ]
8f988936340bf0ffb83ea90ea124efb3c36a1174
https://github.com/nicfit/MishMash/blob/8f988936340bf0ffb83ea90ea124efb3c36a1174/mishmash/commands/sync/utils.py#L64-L92
train
Add or updated the Image.
magopian/django-data-exports
data_exports/forms.py
ColumnFormSet.add_fields
def add_fields(self, form, index): """Filter the form's column choices This is done at the formset level as there's no other way i could find to get the parent object (stored in self.instance), and the form at the same time. """ super(ColumnFormSet, self).add_fields(for...
python
def add_fields(self, form, index): """Filter the form's column choices This is done at the formset level as there's no other way i could find to get the parent object (stored in self.instance), and the form at the same time. """ super(ColumnFormSet, self).add_fields(for...
[ "def", "add_fields", "(", "self", ",", "form", ",", "index", ")", ":", "super", "(", "ColumnFormSet", ",", "self", ")", ".", "add_fields", "(", "form", ",", "index", ")", "form", ".", "fields", "[", "'column'", "]", ".", "choices", "=", "self", ".", ...
Filter the form's column choices This is done at the formset level as there's no other way i could find to get the parent object (stored in self.instance), and the form at the same time.
[ "Filter", "the", "form", "s", "column", "choices" ]
a73db486779d93046ad89c5bf582ff8ae869120f
https://github.com/magopian/django-data-exports/blob/a73db486779d93046ad89c5bf582ff8ae869120f/data_exports/forms.py#L39-L48
train
Filter the form s column choices
jim-easterbrook/pyctools
src/pyctools/setup.py
find_packages
def find_packages(): """Walk source directory tree and convert each sub directory to a package name. """ packages = ['pyctools'] for root, dirs, files in os.walk(os.path.join('src', 'pyctools')): package = '.'.join(root.split(os.sep)[1:]) for name in dirs: packages.appen...
python
def find_packages(): """Walk source directory tree and convert each sub directory to a package name. """ packages = ['pyctools'] for root, dirs, files in os.walk(os.path.join('src', 'pyctools')): package = '.'.join(root.split(os.sep)[1:]) for name in dirs: packages.appen...
[ "def", "find_packages", "(", ")", ":", "packages", "=", "[", "'pyctools'", "]", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "os", ".", "path", ".", "join", "(", "'src'", ",", "'pyctools'", ")", ")", ":", "package", "=", ...
Walk source directory tree and convert each sub directory to a package name.
[ "Walk", "source", "directory", "tree", "and", "convert", "each", "sub", "directory", "to", "a", "package", "name", "." ]
2a958665326892f45f249bebe62c2c23f306732b
https://github.com/jim-easterbrook/pyctools/blob/2a958665326892f45f249bebe62c2c23f306732b/src/pyctools/setup.py#L41-L51
train
Walk source directory tree and convert each sub directory to a package name.
jim-easterbrook/pyctools
src/pyctools/setup.py
write_init_files
def write_init_files(packages): """Make sure package hierarchy is a "pkgutil-style namespace package". For more detail see https://packaging.python.org/guides/packaging-namespace-packages/ """ init_text = """__path__ = __import__('pkgutil').extend_path(__path__, __name__) try: from .__doc_...
python
def write_init_files(packages): """Make sure package hierarchy is a "pkgutil-style namespace package". For more detail see https://packaging.python.org/guides/packaging-namespace-packages/ """ init_text = """__path__ = __import__('pkgutil').extend_path(__path__, __name__) try: from .__doc_...
[ "def", "write_init_files", "(", "packages", ")", ":", "init_text", "=", "\"\"\"__path__ = __import__('pkgutil').extend_path(__path__, __name__)\n\ntry:\n from .__doc__ import __doc__\nexcept ImportError:\n pass\n\"\"\"", "for", "package", "in", "packages", ":", "path", "=", "os...
Make sure package hierarchy is a "pkgutil-style namespace package". For more detail see https://packaging.python.org/guides/packaging-namespace-packages/
[ "Make", "sure", "package", "hierarchy", "is", "a", "pkgutil", "-", "style", "namespace", "package", ".", "For", "more", "detail", "see", "https", ":", "//", "packaging", ".", "python", ".", "org", "/", "guides", "/", "packaging", "-", "namespace", "-", "...
2a958665326892f45f249bebe62c2c23f306732b
https://github.com/jim-easterbrook/pyctools/blob/2a958665326892f45f249bebe62c2c23f306732b/src/pyctools/setup.py#L53-L75
train
Write the init. py files for the given packages.
jaraco/jaraco.mongodb
jaraco/mongodb/cli.py
extract_param
def extract_param(param, args, type=None): """ From a list of args, extract the one param if supplied, returning the value and unused args. >>> extract_param('port', ['foo', '--port=999', 'bar'], type=int) (999, ['foo', 'bar']) >>> extract_param('port', ['foo', '--port', '999', 'bar'], type=int...
python
def extract_param(param, args, type=None): """ From a list of args, extract the one param if supplied, returning the value and unused args. >>> extract_param('port', ['foo', '--port=999', 'bar'], type=int) (999, ['foo', 'bar']) >>> extract_param('port', ['foo', '--port', '999', 'bar'], type=int...
[ "def", "extract_param", "(", "param", ",", "args", ",", "type", "=", "None", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "'--'", "+", "param", ",", "type", "=", "type", ")", "res", ",", "u...
From a list of args, extract the one param if supplied, returning the value and unused args. >>> extract_param('port', ['foo', '--port=999', 'bar'], type=int) (999, ['foo', 'bar']) >>> extract_param('port', ['foo', '--port', '999', 'bar'], type=int) (999, ['foo', 'bar']) >>> extract_param('port...
[ "From", "a", "list", "of", "args", "extract", "the", "one", "param", "if", "supplied", "returning", "the", "value", "and", "unused", "args", "." ]
280f17894941f4babf2e97db033dbb1fd2b9f705
https://github.com/jaraco/jaraco.mongodb/blob/280f17894941f4babf2e97db033dbb1fd2b9f705/jaraco/mongodb/cli.py#L4-L19
train
Extract a param from a list of args returning the value and unused args.
yeraydiazdiaz/lunr.py
lunr/languages/__init__.py
get_nltk_builder
def get_nltk_builder(languages): """Returns a builder with stemmers for all languages added to it. Args: languages (list): A list of supported languages. """ all_stemmers = [] all_stopwords_filters = [] all_word_characters = set() for language in languages: if language == "...
python
def get_nltk_builder(languages): """Returns a builder with stemmers for all languages added to it. Args: languages (list): A list of supported languages. """ all_stemmers = [] all_stopwords_filters = [] all_word_characters = set() for language in languages: if language == "...
[ "def", "get_nltk_builder", "(", "languages", ")", ":", "all_stemmers", "=", "[", "]", "all_stopwords_filters", "=", "[", "]", "all_word_characters", "=", "set", "(", ")", "for", "language", "in", "languages", ":", "if", "language", "==", "\"en\"", ":", "# us...
Returns a builder with stemmers for all languages added to it. Args: languages (list): A list of supported languages.
[ "Returns", "a", "builder", "with", "stemmers", "for", "all", "languages", "added", "to", "it", "." ]
28ec3f6d4888295eed730211ee9617aa488d6ba3
https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/languages/__init__.py#L51-L89
train
Returns a Builder with stemmers for all languages added to it.
yeraydiazdiaz/lunr.py
lunr/languages/__init__.py
register_languages
def register_languages(): """Register all supported languages to ensure compatibility.""" for language in set(SUPPORTED_LANGUAGES) - {"en"}: language_stemmer = partial(nltk_stemmer, get_language_stemmer(language)) Pipeline.register_function(language_stemmer, "stemmer-{}".format(language))
python
def register_languages(): """Register all supported languages to ensure compatibility.""" for language in set(SUPPORTED_LANGUAGES) - {"en"}: language_stemmer = partial(nltk_stemmer, get_language_stemmer(language)) Pipeline.register_function(language_stemmer, "stemmer-{}".format(language))
[ "def", "register_languages", "(", ")", ":", "for", "language", "in", "set", "(", "SUPPORTED_LANGUAGES", ")", "-", "{", "\"en\"", "}", ":", "language_stemmer", "=", "partial", "(", "nltk_stemmer", ",", "get_language_stemmer", "(", "language", ")", ")", "Pipelin...
Register all supported languages to ensure compatibility.
[ "Register", "all", "supported", "languages", "to", "ensure", "compatibility", "." ]
28ec3f6d4888295eed730211ee9617aa488d6ba3
https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/languages/__init__.py#L92-L96
train
Register all supported languages to ensure compatibility.
tehmaze/natural
natural/number.py
ordinal
def ordinal(value): ''' Converts a number to its ordinal representation. :param value: number >>> print(ordinal(1)) 1st >>> print(ordinal(11)) 11th >>> print(ordinal(101)) 101st >>> print(ordinal(104)) 104th >>> print(ordinal(113)) 113th >>> print(ordinal(123)) ...
python
def ordinal(value): ''' Converts a number to its ordinal representation. :param value: number >>> print(ordinal(1)) 1st >>> print(ordinal(11)) 11th >>> print(ordinal(101)) 101st >>> print(ordinal(104)) 104th >>> print(ordinal(113)) 113th >>> print(ordinal(123)) ...
[ "def", "ordinal", "(", "value", ")", ":", "try", ":", "value", "=", "int", "(", "value", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "raise", "ValueError", "if", "value", "%", "100", "in", "(", "11", ",", "12", ",", "13", ")", "...
Converts a number to its ordinal representation. :param value: number >>> print(ordinal(1)) 1st >>> print(ordinal(11)) 11th >>> print(ordinal(101)) 101st >>> print(ordinal(104)) 104th >>> print(ordinal(113)) 113th >>> print(ordinal(123)) 123rd
[ "Converts", "a", "number", "to", "its", "ordinal", "representation", "." ]
d7a1fc9de712f9bcf68884a80826a7977df356fb
https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/number.py#L45-L73
train
Converts a number to its ordinal representation.
tehmaze/natural
natural/number.py
percentage
def percentage(value, digits=2): ''' Converts a fraction to a formatted percentage. :param value: number :param digits: default ``2`` >>> print(percentage(1)) 100.00 % >>> print(percentage(0.23, digits=0)) 23 % >>> print(percentage(23.421)) 2,342.10 % ''' value = floa...
python
def percentage(value, digits=2): ''' Converts a fraction to a formatted percentage. :param value: number :param digits: default ``2`` >>> print(percentage(1)) 100.00 % >>> print(percentage(0.23, digits=0)) 23 % >>> print(percentage(23.421)) 2,342.10 % ''' value = floa...
[ "def", "percentage", "(", "value", ",", "digits", "=", "2", ")", ":", "value", "=", "float", "(", "value", ")", "*", "100.0", "return", "u''", "+", "'%s %%'", "%", "(", "_format", "(", "value", ",", "digits", ")", ",", ")" ]
Converts a fraction to a formatted percentage. :param value: number :param digits: default ``2`` >>> print(percentage(1)) 100.00 % >>> print(percentage(0.23, digits=0)) 23 % >>> print(percentage(23.421)) 2,342.10 %
[ "Converts", "a", "fraction", "to", "a", "formatted", "percentage", "." ]
d7a1fc9de712f9bcf68884a80826a7977df356fb
https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/number.py#L117-L134
train
Converts a fraction to a formatted percentage.
tehmaze/natural
natural/number.py
word
def word(value, digits=2): ''' Converts a large number to a formatted number containing the textual suffix for that number. :param value: number >>> print(word(1)) 1 >>> print(word(123456789)) 123.46 million ''' convention = locale.localeconv() decimal_point = convention[...
python
def word(value, digits=2): ''' Converts a large number to a formatted number containing the textual suffix for that number. :param value: number >>> print(word(1)) 1 >>> print(word(123456789)) 123.46 million ''' convention = locale.localeconv() decimal_point = convention[...
[ "def", "word", "(", "value", ",", "digits", "=", "2", ")", ":", "convention", "=", "locale", ".", "localeconv", "(", ")", "decimal_point", "=", "convention", "[", "'decimal_point'", "]", "decimal_zero", "=", "re", ".", "compile", "(", "r'%s0+'", "%", "re...
Converts a large number to a formatted number containing the textual suffix for that number. :param value: number >>> print(word(1)) 1 >>> print(word(123456789)) 123.46 million
[ "Converts", "a", "large", "number", "to", "a", "formatted", "number", "containing", "the", "textual", "suffix", "for", "that", "number", "." ]
d7a1fc9de712f9bcf68884a80826a7977df356fb
https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/number.py#L137-L174
train
Converts a large number to a formatted number containing the textual suffix for that number.
jaraco/jaraco.mongodb
jaraco/mongodb/oplog.py
parse_args
def parse_args(*args, **kwargs): """ Parse the args for the command. It should be possible for one to specify '--ns', '-x', and '--rename' multiple times: >>> args = parse_args(['--ns', 'foo', 'bar', '--ns', 'baz']) >>> args.ns ['foo', 'bar', 'baz'] >>> parse_args(['-x', '--exclude'])...
python
def parse_args(*args, **kwargs): """ Parse the args for the command. It should be possible for one to specify '--ns', '-x', and '--rename' multiple times: >>> args = parse_args(['--ns', 'foo', 'bar', '--ns', 'baz']) >>> args.ns ['foo', 'bar', 'baz'] >>> parse_args(['-x', '--exclude'])...
[ "def", "parse_args", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "add_help", "=", "False", ")", "parser", ".", "add_argument", "(", "\"--help\"", ",", "help", "=", "\"show usage information\"", ...
Parse the args for the command. It should be possible for one to specify '--ns', '-x', and '--rename' multiple times: >>> args = parse_args(['--ns', 'foo', 'bar', '--ns', 'baz']) >>> args.ns ['foo', 'bar', 'baz'] >>> parse_args(['-x', '--exclude']).exclude [] >>> renames = parse_args...
[ "Parse", "the", "args", "for", "the", "command", "." ]
280f17894941f4babf2e97db033dbb1fd2b9f705
https://github.com/jaraco/jaraco.mongodb/blob/280f17894941f4babf2e97db033dbb1fd2b9f705/jaraco/mongodb/oplog.py#L30-L154
train
Parse the command line arguments for the mongod server.
jaraco/jaraco.mongodb
jaraco/mongodb/oplog.py
_full_rename
def _full_rename(args): """ Return True only if the arguments passed specify exact namespaces and to conduct a rename of every namespace. """ return ( args.ns and all(map(args.rename.affects, args.ns)) )
python
def _full_rename(args): """ Return True only if the arguments passed specify exact namespaces and to conduct a rename of every namespace. """ return ( args.ns and all(map(args.rename.affects, args.ns)) )
[ "def", "_full_rename", "(", "args", ")", ":", "return", "(", "args", ".", "ns", "and", "all", "(", "map", "(", "args", ".", "rename", ".", "affects", ",", "args", ".", "ns", ")", ")", ")" ]
Return True only if the arguments passed specify exact namespaces and to conduct a rename of every namespace.
[ "Return", "True", "only", "if", "the", "arguments", "passed", "specify", "exact", "namespaces", "and", "to", "conduct", "a", "rename", "of", "every", "namespace", "." ]
280f17894941f4babf2e97db033dbb1fd2b9f705
https://github.com/jaraco/jaraco.mongodb/blob/280f17894941f4babf2e97db033dbb1fd2b9f705/jaraco/mongodb/oplog.py#L297-L305
train
Return True only if the arguments passed specify exact namespaces and to conduct a rename of every namespace.
jaraco/jaraco.mongodb
jaraco/mongodb/oplog.py
apply
def apply(db, op): """ Apply operation in db """ dbname = op['ns'].split('.')[0] or "admin" opts = bson.CodecOptions(uuid_representation=bson.binary.STANDARD) db[dbname].command("applyOps", [op], codec_options=opts)
python
def apply(db, op): """ Apply operation in db """ dbname = op['ns'].split('.')[0] or "admin" opts = bson.CodecOptions(uuid_representation=bson.binary.STANDARD) db[dbname].command("applyOps", [op], codec_options=opts)
[ "def", "apply", "(", "db", ",", "op", ")", ":", "dbname", "=", "op", "[", "'ns'", "]", ".", "split", "(", "'.'", ")", "[", "0", "]", "or", "\"admin\"", "opts", "=", "bson", ".", "CodecOptions", "(", "uuid_representation", "=", "bson", ".", "binary"...
Apply operation in db
[ "Apply", "operation", "in", "db" ]
280f17894941f4babf2e97db033dbb1fd2b9f705
https://github.com/jaraco/jaraco.mongodb/blob/280f17894941f4babf2e97db033dbb1fd2b9f705/jaraco/mongodb/oplog.py#L445-L451
train
Apply operation in db
jaraco/jaraco.mongodb
jaraco/mongodb/oplog.py
RenameSpec.from_spec
def from_spec(cls, string_spec): """ Construct RenameSpec from a pair separated by equal sign ('='). """ old_ns, new_ns = string_spec.split('=') return cls(old_ns, new_ns)
python
def from_spec(cls, string_spec): """ Construct RenameSpec from a pair separated by equal sign ('='). """ old_ns, new_ns = string_spec.split('=') return cls(old_ns, new_ns)
[ "def", "from_spec", "(", "cls", ",", "string_spec", ")", ":", "old_ns", ",", "new_ns", "=", "string_spec", ".", "split", "(", "'='", ")", "return", "cls", "(", "old_ns", ",", "new_ns", ")" ]
Construct RenameSpec from a pair separated by equal sign ('=').
[ "Construct", "RenameSpec", "from", "a", "pair", "separated", "by", "equal", "sign", "(", "=", ")", "." ]
280f17894941f4babf2e97db033dbb1fd2b9f705
https://github.com/jaraco/jaraco.mongodb/blob/280f17894941f4babf2e97db033dbb1fd2b9f705/jaraco/mongodb/oplog.py#L159-L164
train
Construct a new object from a string spec separated by equal sign (' = ).
jaraco/jaraco.mongodb
jaraco/mongodb/oplog.py
Oplog.since
def since(self, ts): """ Query the oplog for items since ts and then return """ spec = {'ts': {'$gt': ts}} cursor = self.query(spec) while True: # todo: trap InvalidDocument errors: # except bson.errors.InvalidDocument as e: # logging....
python
def since(self, ts): """ Query the oplog for items since ts and then return """ spec = {'ts': {'$gt': ts}} cursor = self.query(spec) while True: # todo: trap InvalidDocument errors: # except bson.errors.InvalidDocument as e: # logging....
[ "def", "since", "(", "self", ",", "ts", ")", ":", "spec", "=", "{", "'ts'", ":", "{", "'$gt'", ":", "ts", "}", "}", "cursor", "=", "self", ".", "query", "(", "spec", ")", "while", "True", ":", "# todo: trap InvalidDocument errors:", "# except bson.errors...
Query the oplog for items since ts and then return
[ "Query", "the", "oplog", "for", "items", "since", "ts", "and", "then", "return" ]
280f17894941f4babf2e97db033dbb1fd2b9f705
https://github.com/jaraco/jaraco.mongodb/blob/280f17894941f4babf2e97db033dbb1fd2b9f705/jaraco/mongodb/oplog.py#L472-L486
train
Query the oplog for items since ts and then return the result.
jaraco/jaraco.mongodb
jaraco/mongodb/oplog.py
Oplog.has_ops_before
def has_ops_before(self, ts): """ Determine if there are any ops before ts """ spec = {'ts': {'$lt': ts}} return bool(self.coll.find_one(spec))
python
def has_ops_before(self, ts): """ Determine if there are any ops before ts """ spec = {'ts': {'$lt': ts}} return bool(self.coll.find_one(spec))
[ "def", "has_ops_before", "(", "self", ",", "ts", ")", ":", "spec", "=", "{", "'ts'", ":", "{", "'$lt'", ":", "ts", "}", "}", "return", "bool", "(", "self", ".", "coll", ".", "find_one", "(", "spec", ")", ")" ]
Determine if there are any ops before ts
[ "Determine", "if", "there", "are", "any", "ops", "before", "ts" ]
280f17894941f4babf2e97db033dbb1fd2b9f705
https://github.com/jaraco/jaraco.mongodb/blob/280f17894941f4babf2e97db033dbb1fd2b9f705/jaraco/mongodb/oplog.py#L488-L493
train
Determines if there are any ops before ts
jaraco/jaraco.mongodb
jaraco/mongodb/oplog.py
TailingOplog.since
def since(self, ts): """ Tail the oplog, starting from ts. """ while True: items = super(TailingOplog, self).since(ts) for doc in items: yield doc ts = doc['ts']
python
def since(self, ts): """ Tail the oplog, starting from ts. """ while True: items = super(TailingOplog, self).since(ts) for doc in items: yield doc ts = doc['ts']
[ "def", "since", "(", "self", ",", "ts", ")", ":", "while", "True", ":", "items", "=", "super", "(", "TailingOplog", ",", "self", ")", ".", "since", "(", "ts", ")", "for", "doc", "in", "items", ":", "yield", "doc", "ts", "=", "doc", "[", "'ts'", ...
Tail the oplog, starting from ts.
[ "Tail", "the", "oplog", "starting", "from", "ts", "." ]
280f17894941f4babf2e97db033dbb1fd2b9f705
https://github.com/jaraco/jaraco.mongodb/blob/280f17894941f4babf2e97db033dbb1fd2b9f705/jaraco/mongodb/oplog.py#L502-L510
train
Yield the most recent items from the tailing oplog starting from ts.
jaraco/jaraco.mongodb
jaraco/mongodb/oplog.py
Timestamp.dump
def dump(self, stream): """Serialize self to text stream. Matches convention of mongooplog. """ items = ( ('time', self.time), ('inc', self.inc), ) # use ordered dict to retain order ts = collections.OrderedDict(items) json.dump(di...
python
def dump(self, stream): """Serialize self to text stream. Matches convention of mongooplog. """ items = ( ('time', self.time), ('inc', self.inc), ) # use ordered dict to retain order ts = collections.OrderedDict(items) json.dump(di...
[ "def", "dump", "(", "self", ",", "stream", ")", ":", "items", "=", "(", "(", "'time'", ",", "self", ".", "time", ")", ",", "(", "'inc'", ",", "self", ".", "inc", ")", ",", ")", "# use ordered dict to retain order", "ts", "=", "collections", ".", "Ord...
Serialize self to text stream. Matches convention of mongooplog.
[ "Serialize", "self", "to", "text", "stream", "." ]
280f17894941f4babf2e97db033dbb1fd2b9f705
https://github.com/jaraco/jaraco.mongodb/blob/280f17894941f4babf2e97db033dbb1fd2b9f705/jaraco/mongodb/oplog.py#L524-L535
train
Serialize this object to text stream.
jaraco/jaraco.mongodb
jaraco/mongodb/oplog.py
Timestamp.for_window
def for_window(cls, window): """ Given a timedelta window, return a timestamp representing that time. """ utcnow = datetime.datetime.utcnow() return cls(utcnow - window, 0)
python
def for_window(cls, window): """ Given a timedelta window, return a timestamp representing that time. """ utcnow = datetime.datetime.utcnow() return cls(utcnow - window, 0)
[ "def", "for_window", "(", "cls", ",", "window", ")", ":", "utcnow", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "return", "cls", "(", "utcnow", "-", "window", ",", "0", ")" ]
Given a timedelta window, return a timestamp representing that time.
[ "Given", "a", "timedelta", "window", "return", "a", "timestamp", "representing", "that", "time", "." ]
280f17894941f4babf2e97db033dbb1fd2b9f705
https://github.com/jaraco/jaraco.mongodb/blob/280f17894941f4babf2e97db033dbb1fd2b9f705/jaraco/mongodb/oplog.py#L547-L553
train
Given a timedelta window return a timestamp representing that time.
jaraco/jaraco.mongodb
jaraco/mongodb/oplog.py
ResumeFile.save
def save(self, ts): """ Save timestamp to file. """ with open(self, 'w') as f: Timestamp.wrap(ts).dump(f)
python
def save(self, ts): """ Save timestamp to file. """ with open(self, 'w') as f: Timestamp.wrap(ts).dump(f)
[ "def", "save", "(", "self", ",", "ts", ")", ":", "with", "open", "(", "self", ",", "'w'", ")", "as", "f", ":", "Timestamp", ".", "wrap", "(", "ts", ")", ".", "dump", "(", "f", ")" ]
Save timestamp to file.
[ "Save", "timestamp", "to", "file", "." ]
280f17894941f4babf2e97db033dbb1fd2b9f705
https://github.com/jaraco/jaraco.mongodb/blob/280f17894941f4babf2e97db033dbb1fd2b9f705/jaraco/mongodb/oplog.py#L557-L562
train
Save the current object to file.
yeraydiazdiaz/lunr.py
lunr/tokenizer.py
Tokenizer
def Tokenizer(obj, metadata=None, separator=SEPARATOR): """Splits a string into tokens ready to be inserted into the search index. This tokenizer will convert its parameter to a string by calling `str` and then will split this string on characters matching `separator`. Lists will have their elements co...
python
def Tokenizer(obj, metadata=None, separator=SEPARATOR): """Splits a string into tokens ready to be inserted into the search index. This tokenizer will convert its parameter to a string by calling `str` and then will split this string on characters matching `separator`. Lists will have their elements co...
[ "def", "Tokenizer", "(", "obj", ",", "metadata", "=", "None", ",", "separator", "=", "SEPARATOR", ")", ":", "if", "obj", "is", "None", ":", "return", "[", "]", "metadata", "=", "metadata", "or", "{", "}", "if", "isinstance", "(", "obj", ",", "(", "...
Splits a string into tokens ready to be inserted into the search index. This tokenizer will convert its parameter to a string by calling `str` and then will split this string on characters matching `separator`. Lists will have their elements converted to strings and wrapped in a lunr `Token`. Opti...
[ "Splits", "a", "string", "into", "tokens", "ready", "to", "be", "inserted", "into", "the", "search", "index", "." ]
28ec3f6d4888295eed730211ee9617aa488d6ba3
https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/tokenizer.py#L14-L59
train
This tokenizer will convert a string into a list of tokens ready to be inserted into the search index.
jaraco/jaraco.mongodb
jaraco/mongodb/manage.py
all_databases
def all_databases(client, exclude=['local']): """ Yield all databases except excluded (default excludes 'local'). """ return ( client[db_name] for db_name in client.list_database_names() if db_name not in exclude )
python
def all_databases(client, exclude=['local']): """ Yield all databases except excluded (default excludes 'local'). """ return ( client[db_name] for db_name in client.list_database_names() if db_name not in exclude )
[ "def", "all_databases", "(", "client", ",", "exclude", "=", "[", "'local'", "]", ")", ":", "return", "(", "client", "[", "db_name", "]", "for", "db_name", "in", "client", ".", "list_database_names", "(", ")", "if", "db_name", "not", "in", "exclude", ")" ...
Yield all databases except excluded (default excludes 'local').
[ "Yield", "all", "databases", "except", "excluded", "(", "default", "excludes", "local", ")", "." ]
280f17894941f4babf2e97db033dbb1fd2b9f705
https://github.com/jaraco/jaraco.mongodb/blob/280f17894941f4babf2e97db033dbb1fd2b9f705/jaraco/mongodb/manage.py#L4-L13
train
Yield all databases except excluded
jaraco/jaraco.mongodb
jaraco/mongodb/manage.py
all_collections
def all_collections(db): """ Yield all non-sytem collections in db. """ include_pattern = r'(?!system\.)' return ( db[name] for name in db.list_collection_names() if re.match(include_pattern, name) )
python
def all_collections(db): """ Yield all non-sytem collections in db. """ include_pattern = r'(?!system\.)' return ( db[name] for name in db.list_collection_names() if re.match(include_pattern, name) )
[ "def", "all_collections", "(", "db", ")", ":", "include_pattern", "=", "r'(?!system\\.)'", "return", "(", "db", "[", "name", "]", "for", "name", "in", "db", ".", "list_collection_names", "(", ")", "if", "re", ".", "match", "(", "include_pattern", ",", "nam...
Yield all non-sytem collections in db.
[ "Yield", "all", "non", "-", "sytem", "collections", "in", "db", "." ]
280f17894941f4babf2e97db033dbb1fd2b9f705
https://github.com/jaraco/jaraco.mongodb/blob/280f17894941f4babf2e97db033dbb1fd2b9f705/jaraco/mongodb/manage.py#L16-L25
train
Yield all non - symbolic collections in db.
jaraco/jaraco.mongodb
jaraco/mongodb/manage.py
safe_purge_collection
def safe_purge_collection(coll): """ Cannot remove documents from capped collections in later versions of MongoDB, so drop the collection instead. """ op = ( drop_collection if coll.options().get('capped', False) else purge_collection ) return op(coll)
python
def safe_purge_collection(coll): """ Cannot remove documents from capped collections in later versions of MongoDB, so drop the collection instead. """ op = ( drop_collection if coll.options().get('capped', False) else purge_collection ) return op(coll)
[ "def", "safe_purge_collection", "(", "coll", ")", ":", "op", "=", "(", "drop_collection", "if", "coll", ".", "options", "(", ")", ".", "get", "(", "'capped'", ",", "False", ")", "else", "purge_collection", ")", "return", "op", "(", "coll", ")" ]
Cannot remove documents from capped collections in later versions of MongoDB, so drop the collection instead.
[ "Cannot", "remove", "documents", "from", "capped", "collections", "in", "later", "versions", "of", "MongoDB", "so", "drop", "the", "collection", "instead", "." ]
280f17894941f4babf2e97db033dbb1fd2b9f705
https://github.com/jaraco/jaraco.mongodb/blob/280f17894941f4babf2e97db033dbb1fd2b9f705/jaraco/mongodb/manage.py#L32-L43
train
Remove documents from capped collections in later versions of MongoDB so drop the collection instead.
yeraydiazdiaz/lunr.py
lunr/stop_word_filter.py
generate_stop_word_filter
def generate_stop_word_filter(stop_words, language=None): """Builds a stopWordFilter function from the provided list of stop words. The built in `stop_word_filter` is built using this factory and can be used to generate custom `stop_word_filter` for applications or non English languages. """ d...
python
def generate_stop_word_filter(stop_words, language=None): """Builds a stopWordFilter function from the provided list of stop words. The built in `stop_word_filter` is built using this factory and can be used to generate custom `stop_word_filter` for applications or non English languages. """ d...
[ "def", "generate_stop_word_filter", "(", "stop_words", ",", "language", "=", "None", ")", ":", "def", "stop_word_filter", "(", "token", ",", "i", "=", "None", ",", "tokens", "=", "None", ")", ":", "if", "token", "and", "str", "(", "token", ")", "not", ...
Builds a stopWordFilter function from the provided list of stop words. The built in `stop_word_filter` is built using this factory and can be used to generate custom `stop_word_filter` for applications or non English languages.
[ "Builds", "a", "stopWordFilter", "function", "from", "the", "provided", "list", "of", "stop", "words", "." ]
28ec3f6d4888295eed730211ee9617aa488d6ba3
https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/stop_word_filter.py#L130-L149
train
Builds a stopWordFilter function from the provided list of stop words.
CiscoUcs/UcsPythonSDK
src/UcsSdk/utils/spmanager.py
BootPolicy.get_boot_device
def get_boot_device(self): """Get the current boot device for the node. Provides the current boot device of the node. Be aware that not all drivers support this. :raises: InvalidParameterValue if any connection parameters are incorrect. :...
python
def get_boot_device(self): """Get the current boot device for the node. Provides the current boot device of the node. Be aware that not all drivers support this. :raises: InvalidParameterValue if any connection parameters are incorrect. :...
[ "def", "get_boot_device", "(", "self", ")", ":", "operation", "=", "'get_boot_device'", "try", ":", "boot_device", "=", "None", "boot_devices", "=", "get_children_by_dn", "(", "self", ".", "__handle", ",", "self", ".", "__boot_policy_dn", ")", "if", "boot_device...
Get the current boot device for the node. Provides the current boot device of the node. Be aware that not all drivers support this. :raises: InvalidParameterValue if any connection parameters are incorrect. :raises: MissingParameterValue if a requ...
[ "Get", "the", "current", "boot", "device", "for", "the", "node", ".", "Provides", "the", "current", "boot", "device", "of", "the", "node", ".", "Be", "aware", "that", "not", "all", "drivers", "support", "this", ".", ":", "raises", ":", "InvalidParameterVal...
bf6b07d6abeacb922c92b198352eda4eb9e4629b
https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/utils/spmanager.py#L88-L117
train
Gets the current boot device for the node.
tehmaze/natural
natural/phone.py
e123
def e123(number, areasize=3, groupsize=4, national=False): ''' Printable E.123 (Notation for national and international telephone numbers from ITU) numbers. :param number: string :param areasize: int :param groupsize: int :param national: bool >>> print(e123(155542315678)) +1 555 4...
python
def e123(number, areasize=3, groupsize=4, national=False): ''' Printable E.123 (Notation for national and international telephone numbers from ITU) numbers. :param number: string :param areasize: int :param groupsize: int :param national: bool >>> print(e123(155542315678)) +1 555 4...
[ "def", "e123", "(", "number", ",", "areasize", "=", "3", ",", "groupsize", "=", "4", ",", "national", "=", "False", ")", ":", "if", "isinstance", "(", "number", ",", "six", ".", "integer_types", ")", ":", "return", "e123", "(", "'+%s'", "%", "number"...
Printable E.123 (Notation for national and international telephone numbers from ITU) numbers. :param number: string :param areasize: int :param groupsize: int :param national: bool >>> print(e123(155542315678)) +1 555 4231 5678 >>> print(e123('+31654231567', areasize=1)) +31 6 5423...
[ "Printable", "E", ".", "123", "(", "Notation", "for", "national", "and", "international", "telephone", "numbers", "from", "ITU", ")", "numbers", "." ]
d7a1fc9de712f9bcf68884a80826a7977df356fb
https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/phone.py#L10-L64
train
Printable E. 123 notation for national and international telephone numbers.
tehmaze/natural
natural/phone.py
e161
def e161(number, alphabet=PHONE_E161_ALPHABET): ''' Printable a 26 Latin letters (A to Z) phone number to the 12-key telephone keypad number. :param number: string :param alphabet: dict >>> print(e161('0800-PIZZA123')) 080074992123 >>> e161('0800^PIZZA123') Traceback (most recent c...
python
def e161(number, alphabet=PHONE_E161_ALPHABET): ''' Printable a 26 Latin letters (A to Z) phone number to the 12-key telephone keypad number. :param number: string :param alphabet: dict >>> print(e161('0800-PIZZA123')) 080074992123 >>> e161('0800^PIZZA123') Traceback (most recent c...
[ "def", "e161", "(", "number", ",", "alphabet", "=", "PHONE_E161_ALPHABET", ")", ":", "digits", "=", "[", "]", "for", "char", "in", "strip", "(", "number", ",", "'+-. ()'", ")", ".", "lower", "(", ")", ":", "length", "=", "len", "(", "digits", ")", ...
Printable a 26 Latin letters (A to Z) phone number to the 12-key telephone keypad number. :param number: string :param alphabet: dict >>> print(e161('0800-PIZZA123')) 080074992123 >>> e161('0800^PIZZA123') Traceback (most recent call last): ... ValueError: Character "^" (0x5e) ...
[ "Printable", "a", "26", "Latin", "letters", "(", "A", "to", "Z", ")", "phone", "number", "to", "the", "12", "-", "key", "telephone", "keypad", "number", "." ]
d7a1fc9de712f9bcf68884a80826a7977df356fb
https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/phone.py#L67-L97
train
Printable a 26 Latin letters A to Z phone number to the 12 - key telephone keypad number.
tehmaze/natural
natural/phone.py
e164
def e164(number): ''' Printable E.164 (The international public telecommunication numbering plan from ITU) numbers. :param number: string >>> print(e164(155542315678)) +155542315678 >>> print(e164('+31 20 5423 1567')) +312054231567 ''' if isinstance(number, six.integer_types): ...
python
def e164(number): ''' Printable E.164 (The international public telecommunication numbering plan from ITU) numbers. :param number: string >>> print(e164(155542315678)) +155542315678 >>> print(e164('+31 20 5423 1567')) +312054231567 ''' if isinstance(number, six.integer_types): ...
[ "def", "e164", "(", "number", ")", ":", "if", "isinstance", "(", "number", ",", "six", ".", "integer_types", ")", ":", "return", "e164", "(", "'+%s'", "%", "number", ")", "elif", "isinstance", "(", "number", ",", "six", ".", "string_types", ")", ":", ...
Printable E.164 (The international public telecommunication numbering plan from ITU) numbers. :param number: string >>> print(e164(155542315678)) +155542315678 >>> print(e164('+31 20 5423 1567')) +312054231567
[ "Printable", "E", ".", "164", "(", "The", "international", "public", "telecommunication", "numbering", "plan", "from", "ITU", ")", "numbers", "." ]
d7a1fc9de712f9bcf68884a80826a7977df356fb
https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/phone.py#L100-L120
train
Printable E. 164 numbering plan .
tehmaze/natural
natural/phone.py
enum
def enum(number, zone='e164.arpa'): ''' Printable DNS ENUM (telephone number mapping) record. :param number: string :param zone: string >>> print(enum('+31 20 5423 1567')) 7.6.5.1.3.2.4.5.0.2.1.3.e164.arpa. >>> print(enum('+31 97 99 6642', zone='e164.spacephone.org')) 2.4.6.6.9.9.7.9....
python
def enum(number, zone='e164.arpa'): ''' Printable DNS ENUM (telephone number mapping) record. :param number: string :param zone: string >>> print(enum('+31 20 5423 1567')) 7.6.5.1.3.2.4.5.0.2.1.3.e164.arpa. >>> print(enum('+31 97 99 6642', zone='e164.spacephone.org')) 2.4.6.6.9.9.7.9....
[ "def", "enum", "(", "number", ",", "zone", "=", "'e164.arpa'", ")", ":", "number", "=", "e164", "(", "number", ")", ".", "lstrip", "(", "'+'", ")", "return", "u'.'", ".", "join", "(", "[", "u'.'", ".", "join", "(", "number", "[", ":", ":", "-", ...
Printable DNS ENUM (telephone number mapping) record. :param number: string :param zone: string >>> print(enum('+31 20 5423 1567')) 7.6.5.1.3.2.4.5.0.2.1.3.e164.arpa. >>> print(enum('+31 97 99 6642', zone='e164.spacephone.org')) 2.4.6.6.9.9.7.9.1.3.e164.spacephone.org.
[ "Printable", "DNS", "ENUM", "(", "telephone", "number", "mapping", ")", "record", "." ]
d7a1fc9de712f9bcf68884a80826a7977df356fb
https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/phone.py#L123-L142
train
Printable DNS ENUM record.
tehmaze/natural
natural/phone.py
imei
def imei(number): ''' Printable International Mobile Station Equipment Identity (IMEI) numbers. :param number: string or int >>> print(imei(12345678901234)) 12-345678-901234-7 >>> print(imei(1234567890123456)) 12-345678-901234-56 ''' number = to_decimal(number) length = len(num...
python
def imei(number): ''' Printable International Mobile Station Equipment Identity (IMEI) numbers. :param number: string or int >>> print(imei(12345678901234)) 12-345678-901234-7 >>> print(imei(1234567890123456)) 12-345678-901234-56 ''' number = to_decimal(number) length = len(num...
[ "def", "imei", "(", "number", ")", ":", "number", "=", "to_decimal", "(", "number", ")", "length", "=", "len", "(", "number", ")", "if", "length", "not", "in", "(", "14", ",", "15", ",", "16", ")", ":", "raise", "ValueError", "(", "_", "(", "'Inv...
Printable International Mobile Station Equipment Identity (IMEI) numbers. :param number: string or int >>> print(imei(12345678901234)) 12-345678-901234-7 >>> print(imei(1234567890123456)) 12-345678-901234-56
[ "Printable", "International", "Mobile", "Station", "Equipment", "Identity", "(", "IMEI", ")", "numbers", "." ]
d7a1fc9de712f9bcf68884a80826a7977df356fb
https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/phone.py#L145-L168
train
Return a string that can be used as a base for the IMEI number.