repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
eventbrite/eventbrite-sdk-python
eventbrite/access_methods.py
https://github.com/eventbrite/eventbrite-sdk-python/blob/f2e5dc5aa1aa3e45766de13f16fd65722163d91a/eventbrite/access_methods.py#L486-L495
def delete_one_series(self, id, **data): """ DELETE /series/:id/ Deletes a repeating event series and all of its occurrences if the delete is permitted. In order for a delete to be permitted, there must be no pending or completed orders for any dates in the series. Returns a boolean indi...
[ "def", "delete_one_series", "(", "self", ",", "id", ",", "*", "*", "data", ")", ":", "return", "self", ".", "delete", "(", "\"/series/{0}/\"", ".", "format", "(", "id", ")", ",", "data", "=", "data", ")" ]
DELETE /series/:id/ Deletes a repeating event series and all of its occurrences if the delete is permitted. In order for a delete to be permitted, there must be no pending or completed orders for any dates in the series. Returns a boolean indicating success or failure of the delete. .. _...
[ "DELETE", "/", "series", "/", ":", "id", "/", "Deletes", "a", "repeating", "event", "series", "and", "all", "of", "its", "occurrences", "if", "the", "delete", "is", "permitted", ".", "In", "order", "for", "a", "delete", "to", "be", "permitted", "there", ...
python
train
pandas-dev/pandas
pandas/core/frame.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/frame.py#L4955-L5055
def nsmallest(self, n, columns, keep='first'): """ Return the first `n` rows ordered by `columns` in ascending order. Return the first `n` rows with the smallest values in `columns`, in ascending order. The columns that are not specified are returned as well, but not used for or...
[ "def", "nsmallest", "(", "self", ",", "n", ",", "columns", ",", "keep", "=", "'first'", ")", ":", "return", "algorithms", ".", "SelectNFrame", "(", "self", ",", "n", "=", "n", ",", "keep", "=", "keep", ",", "columns", "=", "columns", ")", ".", "nsm...
Return the first `n` rows ordered by `columns` in ascending order. Return the first `n` rows with the smallest values in `columns`, in ascending order. The columns that are not specified are returned as well, but not used for ordering. This method is equivalent to ``df.sort_val...
[ "Return", "the", "first", "n", "rows", "ordered", "by", "columns", "in", "ascending", "order", "." ]
python
train
hirokiky/uiro
uiro/view.py
https://github.com/hirokiky/uiro/blob/8436976b21ac9b0eac4243768f5ada12479b9e00/uiro/view.py#L14-L22
def get_base_wrappers(method='get', template_name='', predicates=(), wrappers=()): """ basic View Wrappers used by view_config. """ wrappers += (preserve_view(MethodPredicate(method), *predicates),) if template_name: wrappers += (render_template(template_name),) return wrappers
[ "def", "get_base_wrappers", "(", "method", "=", "'get'", ",", "template_name", "=", "''", ",", "predicates", "=", "(", ")", ",", "wrappers", "=", "(", ")", ")", ":", "wrappers", "+=", "(", "preserve_view", "(", "MethodPredicate", "(", "method", ")", ",",...
basic View Wrappers used by view_config.
[ "basic", "View", "Wrappers", "used", "by", "view_config", "." ]
python
train
huge-success/sanic
sanic/exceptions.py
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/exceptions.py#L124-L134
def add_status_code(code): """ Decorator used for adding exceptions to :class:`SanicException`. """ def class_decorator(cls): cls.status_code = code _sanic_exceptions[code] = cls return cls return class_decorator
[ "def", "add_status_code", "(", "code", ")", ":", "def", "class_decorator", "(", "cls", ")", ":", "cls", ".", "status_code", "=", "code", "_sanic_exceptions", "[", "code", "]", "=", "cls", "return", "cls", "return", "class_decorator" ]
Decorator used for adding exceptions to :class:`SanicException`.
[ "Decorator", "used", "for", "adding", "exceptions", "to", ":", "class", ":", "SanicException", "." ]
python
train
XuShaohua/bcloud
bcloud/auth.py
https://github.com/XuShaohua/bcloud/blob/4b54e0fdccf2b3013285fef05c97354cfa31697b/bcloud/auth.py#L82-L102
def get_UBI(cookie, tokens): '''检查登录历史, 可以获得一个Cookie - UBI. 返回的信息类似于: {"errInfo":{ "no": "0" }, "data": {'displayname':['xxx@163.com']}} ''' url = ''.join([ const.PASSPORT_URL, '?loginhistory', '&token=', tokens['token'], '&tpl=pp&apiver=v3', '&tt=', util.tim...
[ "def", "get_UBI", "(", "cookie", ",", "tokens", ")", ":", "url", "=", "''", ".", "join", "(", "[", "const", ".", "PASSPORT_URL", ",", "'?loginhistory'", ",", "'&token='", ",", "tokens", "[", "'token'", "]", ",", "'&tpl=pp&apiver=v3'", ",", "'&tt='", ",",...
检查登录历史, 可以获得一个Cookie - UBI. 返回的信息类似于: {"errInfo":{ "no": "0" }, "data": {'displayname':['xxx@163.com']}}
[ "检查登录历史", "可以获得一个Cookie", "-", "UBI", ".", "返回的信息类似于", ":", "{", "errInfo", ":", "{", "no", ":", "0", "}", "data", ":", "{", "displayname", ":", "[", "xxx" ]
python
train
kwikteam/phy
phy/cluster/_history.py
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/cluster/_history.py#L28-L32
def current_item(self): """Return the current element.""" if self._history and self._index >= 0: self._check_index() return self._history[self._index]
[ "def", "current_item", "(", "self", ")", ":", "if", "self", ".", "_history", "and", "self", ".", "_index", ">=", "0", ":", "self", ".", "_check_index", "(", ")", "return", "self", ".", "_history", "[", "self", ".", "_index", "]" ]
Return the current element.
[ "Return", "the", "current", "element", "." ]
python
train
NASA-AMMOS/AIT-Core
ait/core/json.py
https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/json.py#L26-L56
def slotsToJSON(obj, slots=None): """Converts the given Python object to one suitable for Javascript Object Notation (JSON) serialization via :func:`json.dump` or :func:`json.dumps`. This function delegates to :func:`toJSON`. Specifically only attributes in the list of *slots* are converted. If *s...
[ "def", "slotsToJSON", "(", "obj", ",", "slots", "=", "None", ")", ":", "if", "slots", "is", "None", ":", "slots", "=", "list", "(", "obj", ".", "__slots__", ")", "if", "hasattr", "(", "obj", ",", "'__slots__'", ")", "else", "[", "]", "for", "base",...
Converts the given Python object to one suitable for Javascript Object Notation (JSON) serialization via :func:`json.dump` or :func:`json.dumps`. This function delegates to :func:`toJSON`. Specifically only attributes in the list of *slots* are converted. If *slots* is not provided, it defaults to the...
[ "Converts", "the", "given", "Python", "object", "to", "one", "suitable", "for", "Javascript", "Object", "Notation", "(", "JSON", ")", "serialization", "via", ":", "func", ":", "json", ".", "dump", "or", ":", "func", ":", "json", ".", "dumps", ".", "This"...
python
train
Jammy2211/PyAutoLens
autolens/data/ccd.py
https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/ccd.py#L688-L700
def setup_random_seed(seed): """Setup the random seed. If the input seed is -1, the code will use a random seed for every run. If it is \ positive, that seed is used for all runs, thereby giving reproducible results. Parameters ---------- seed : int The seed of the random number generator. ...
[ "def", "setup_random_seed", "(", "seed", ")", ":", "if", "seed", "==", "-", "1", ":", "seed", "=", "np", ".", "random", ".", "randint", "(", "0", ",", "int", "(", "1e9", ")", ")", "# Use one seed, so all regions have identical column non-uniformity.", "np", ...
Setup the random seed. If the input seed is -1, the code will use a random seed for every run. If it is \ positive, that seed is used for all runs, thereby giving reproducible results. Parameters ---------- seed : int The seed of the random number generator.
[ "Setup", "the", "random", "seed", ".", "If", "the", "input", "seed", "is", "-", "1", "the", "code", "will", "use", "a", "random", "seed", "for", "every", "run", ".", "If", "it", "is", "\\", "positive", "that", "seed", "is", "used", "for", "all", "r...
python
valid
watchforstock/evohome-client
evohomeclient2/__init__.py
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/__init__.py#L84-L93
def _headers(self): """Ensure the Authorization Header has a valid Access Token.""" if not self.access_token or not self.access_token_expires: self._basic_login() elif datetime.now() > self.access_token_expires - timedelta(seconds=30): self._basic_login() return...
[ "def", "_headers", "(", "self", ")", ":", "if", "not", "self", ".", "access_token", "or", "not", "self", ".", "access_token_expires", ":", "self", ".", "_basic_login", "(", ")", "elif", "datetime", ".", "now", "(", ")", ">", "self", ".", "access_token_ex...
Ensure the Authorization Header has a valid Access Token.
[ "Ensure", "the", "Authorization", "Header", "has", "a", "valid", "Access", "Token", "." ]
python
train
brouberol/contexttimer
contexttimer/timeout.py
https://github.com/brouberol/contexttimer/blob/a866f420ed4c10f29abf252c58b11f9db6706100/contexttimer/timeout.py#L39-L80
def timeout(limit, handler): """A decorator ensuring that the decorated function tun time does not exceeds the argument limit. :args limit: the time limit :type limit: int :args handler: the handler function called when the decorated function times out. :type handler: callable Example...
[ "def", "timeout", "(", "limit", ",", "handler", ")", ":", "def", "wrapper", "(", "f", ")", ":", "def", "wrapped_f", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "old_handler", "=", "signal", ".", "getsignal", "(", "signal", ".", "SIGALRM", ...
A decorator ensuring that the decorated function tun time does not exceeds the argument limit. :args limit: the time limit :type limit: int :args handler: the handler function called when the decorated function times out. :type handler: callable Example: >>>def timeout_handler(limit, ...
[ "A", "decorator", "ensuring", "that", "the", "decorated", "function", "tun", "time", "does", "not", "exceeds", "the", "argument", "limit", "." ]
python
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/multi_problem.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem.py#L38-L108
def normalize_example_nlp(task, example, is_infer, vocab_type, vocab_offset, max_input_length, max_target_length, fixed_train_length): """Normalize the examples from different tasks so they can be merged. This function is specific to NLP tasks and normalizes them...
[ "def", "normalize_example_nlp", "(", "task", ",", "example", ",", "is_infer", ",", "vocab_type", ",", "vocab_offset", ",", "max_input_length", ",", "max_target_length", ",", "fixed_train_length", ")", ":", "if", "task", ".", "has_inputs", ":", "example", "[", "\...
Normalize the examples from different tasks so they can be merged. This function is specific to NLP tasks and normalizes them so that in the end the example only has "targets" and "task_id". For tasks that originally have inputs, this is done by appending task_id to the inputs and prepending targets, so normal...
[ "Normalize", "the", "examples", "from", "different", "tasks", "so", "they", "can", "be", "merged", "." ]
python
train
Dallinger/Dallinger
demos/dlgr/demos/mcmcp/models.py
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/demos/dlgr/demos/mcmcp/models.py#L94-L103
def perturbed_contents(self): """Perturb the given animal.""" animal = json.loads(self.contents) for prop, prop_range in self.properties.items(): range = prop_range[1] - prop_range[0] jittered = animal[prop] + random.gauss(0, 0.1 * range) animal[prop] = max(m...
[ "def", "perturbed_contents", "(", "self", ")", ":", "animal", "=", "json", ".", "loads", "(", "self", ".", "contents", ")", "for", "prop", ",", "prop_range", "in", "self", ".", "properties", ".", "items", "(", ")", ":", "range", "=", "prop_range", "[",...
Perturb the given animal.
[ "Perturb", "the", "given", "animal", "." ]
python
train
veeti/decent
decent/validators.py
https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L92-L105
def Type(expected, message="Not of type {}"): """ Creates a validator that compares the type of the given value to ``expected``. This is a direct type() equality check. Also see ``Instance``, which is an isinstance() check. A custom message can be specified with ``message``. """ @wraps(Type...
[ "def", "Type", "(", "expected", ",", "message", "=", "\"Not of type {}\"", ")", ":", "@", "wraps", "(", "Type", ")", "def", "built", "(", "value", ")", ":", "if", "type", "(", "value", ")", "!=", "expected", ":", "raise", "Error", "(", "message", "."...
Creates a validator that compares the type of the given value to ``expected``. This is a direct type() equality check. Also see ``Instance``, which is an isinstance() check. A custom message can be specified with ``message``.
[ "Creates", "a", "validator", "that", "compares", "the", "type", "of", "the", "given", "value", "to", "expected", ".", "This", "is", "a", "direct", "type", "()", "equality", "check", ".", "Also", "see", "Instance", "which", "is", "an", "isinstance", "()", ...
python
train
oasiswork/zimsoap
zimsoap/client.py
https://github.com/oasiswork/zimsoap/blob/d1ea2eb4d50f263c9a16e5549af03f1eff3e295e/zimsoap/client.py#L1995-L2014
def get_filter_rules(self, way='in'): """ :param: way string discribing if filter is for 'in' or 'out' messages :returns: list of zobjects.FilterRule """ try: if way == 'in': filters = self.request( 'GetFilterRules')['filterRules'][...
[ "def", "get_filter_rules", "(", "self", ",", "way", "=", "'in'", ")", ":", "try", ":", "if", "way", "==", "'in'", ":", "filters", "=", "self", ".", "request", "(", "'GetFilterRules'", ")", "[", "'filterRules'", "]", "[", "'filterRule'", "]", "elif", "w...
:param: way string discribing if filter is for 'in' or 'out' messages :returns: list of zobjects.FilterRule
[ ":", "param", ":", "way", "string", "discribing", "if", "filter", "is", "for", "in", "or", "out", "messages", ":", "returns", ":", "list", "of", "zobjects", ".", "FilterRule" ]
python
train
tech-pi/doufo
src/python/doufo/function.py
https://github.com/tech-pi/doufo/blob/3d375fef30670597768a6eef809b75b4b1b5a3fd/src/python/doufo/function.py#L329-L335
def flip(f: Callable) -> Function: """ flip order of first two arguments to function. """ nargs_, nouts_, ndefs_ = nargs(f), nouts(f), ndefs(f) return WrappedFunction(lambda *args, **kwargs: f(args[1], args[0], *args[2:], **kwargs), nargs=nargs_, nouts=nouts_, ndefs=nd...
[ "def", "flip", "(", "f", ":", "Callable", ")", "->", "Function", ":", "nargs_", ",", "nouts_", ",", "ndefs_", "=", "nargs", "(", "f", ")", ",", "nouts", "(", "f", ")", ",", "ndefs", "(", "f", ")", "return", "WrappedFunction", "(", "lambda", "*", ...
flip order of first two arguments to function.
[ "flip", "order", "of", "first", "two", "arguments", "to", "function", "." ]
python
train
theosysbio/means
src/means/approximation/mea/closure_normal.py
https://github.com/theosysbio/means/blob/fe164916a1d84ab2a4fa039871d38ccdf638b1db/src/means/approximation/mea/closure_normal.py#L61-L98
def _compute_one_closed_central_moment(self, moment, covariance_matrix): r""" Compute each row of closed central moment based on Isserlis' Theorem of calculating higher order moments of multivariate normal distribution in terms of covariance matrix :param moment: moment matrix :...
[ "def", "_compute_one_closed_central_moment", "(", "self", ",", "moment", ",", "covariance_matrix", ")", ":", "# If moment order is odd, higher order moments equals 0", "if", "moment", ".", "order", "%", "2", "!=", "0", ":", "return", "sp", ".", "Integer", "(", "0", ...
r""" Compute each row of closed central moment based on Isserlis' Theorem of calculating higher order moments of multivariate normal distribution in terms of covariance matrix :param moment: moment matrix :param covariance_matrix: matrix containing variances and covariances :ret...
[ "r", "Compute", "each", "row", "of", "closed", "central", "moment", "based", "on", "Isserlis", "Theorem", "of", "calculating", "higher", "order", "moments", "of", "multivariate", "normal", "distribution", "in", "terms", "of", "covariance", "matrix" ]
python
train
richardkiss/pycoin
pycoin/crack/ecdsa.py
https://github.com/richardkiss/pycoin/blob/1e8d0d9fe20ce0347b97847bb529cd1bd84c7442/pycoin/crack/ecdsa.py#L2-L7
def crack_secret_exponent_from_k(generator, signed_value, sig, k): """ Given a signature of a signed_value and a known k, return the secret exponent. """ r, s = sig return ((s * k - signed_value) * generator.inverse(r)) % generator.order()
[ "def", "crack_secret_exponent_from_k", "(", "generator", ",", "signed_value", ",", "sig", ",", "k", ")", ":", "r", ",", "s", "=", "sig", "return", "(", "(", "s", "*", "k", "-", "signed_value", ")", "*", "generator", ".", "inverse", "(", "r", ")", ")"...
Given a signature of a signed_value and a known k, return the secret exponent.
[ "Given", "a", "signature", "of", "a", "signed_value", "and", "a", "known", "k", "return", "the", "secret", "exponent", "." ]
python
train
codenerix/django-codenerix
codenerix/multiforms.py
https://github.com/codenerix/django-codenerix/blob/1f5527b352141caaee902b37b2648791a06bd57d/codenerix/multiforms.py#L312-L327
def form_valid(self, form, forms): """ Called if all forms are valid. Creates a Recipe instance along with associated Ingredients and Instructions and then redirects to a success page. """ if self.object: form.save() for (formobj, linkerfield) in forms: ...
[ "def", "form_valid", "(", "self", ",", "form", ",", "forms", ")", ":", "if", "self", ".", "object", ":", "form", ".", "save", "(", ")", "for", "(", "formobj", ",", "linkerfield", ")", "in", "forms", ":", "if", "form", "!=", "formobj", ":", "formobj...
Called if all forms are valid. Creates a Recipe instance along with associated Ingredients and Instructions and then redirects to a success page.
[ "Called", "if", "all", "forms", "are", "valid", ".", "Creates", "a", "Recipe", "instance", "along", "with", "associated", "Ingredients", "and", "Instructions", "and", "then", "redirects", "to", "a", "success", "page", "." ]
python
train
trailofbits/manticore
manticore/native/cpu/x86.py
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L905-L934
def TEST(cpu, src1, src2): """ Logical compare. Computes the bit-wise logical AND of first operand (source 1 operand) and the second operand (source 2 operand) and sets the SF, ZF, and PF status flags according to the result. The result is then discarded:: TEMP = ...
[ "def", "TEST", "(", "cpu", ",", "src1", ",", "src2", ")", ":", "# Defined Flags: szp", "temp", "=", "src1", ".", "read", "(", ")", "&", "src2", ".", "read", "(", ")", "cpu", ".", "SF", "=", "(", "temp", "&", "(", "1", "<<", "(", "src1", ".", ...
Logical compare. Computes the bit-wise logical AND of first operand (source 1 operand) and the second operand (source 2 operand) and sets the SF, ZF, and PF status flags according to the result. The result is then discarded:: TEMP = SRC1 AND SRC2; SF = MSB(TEMP); ...
[ "Logical", "compare", "." ]
python
valid
tisimst/mcerp
mcerp/__init__.py
https://github.com/tisimst/mcerp/blob/2bb8260c9ad2d58a806847f1b627b6451e407de1/mcerp/__init__.py#L799-L809
def ChiSquared(k, tag=None): """ A Chi-Squared random variate Parameters ---------- k : int The degrees of freedom of the distribution (must be greater than one) """ assert int(k) == k and k >= 1, 'Chi-Squared "k" must be an integer greater than 0' return uv(ss.chi2(k), tag=...
[ "def", "ChiSquared", "(", "k", ",", "tag", "=", "None", ")", ":", "assert", "int", "(", "k", ")", "==", "k", "and", "k", ">=", "1", ",", "'Chi-Squared \"k\" must be an integer greater than 0'", "return", "uv", "(", "ss", ".", "chi2", "(", "k", ")", ","...
A Chi-Squared random variate Parameters ---------- k : int The degrees of freedom of the distribution (must be greater than one)
[ "A", "Chi", "-", "Squared", "random", "variate", "Parameters", "----------", "k", ":", "int", "The", "degrees", "of", "freedom", "of", "the", "distribution", "(", "must", "be", "greater", "than", "one", ")" ]
python
train
joke2k/faker
faker/utils/text.py
https://github.com/joke2k/faker/blob/965824b61132e52d92d1a6ce470396dbbe01c96c/faker/utils/text.py#L14-L35
def slugify(value, allow_dots=False, allow_unicode=False): """ Converts to lowercase, removes non-word characters (alphanumerics and underscores) and converts spaces to hyphens. Also strips leading and trailing whitespace. Modified to optionally allow dots. Adapted from Django 1.9 """ if al...
[ "def", "slugify", "(", "value", ",", "allow_dots", "=", "False", ",", "allow_unicode", "=", "False", ")", ":", "if", "allow_dots", ":", "pattern", "=", "_re_pattern_allow_dots", "else", ":", "pattern", "=", "_re_pattern", "value", "=", "six", ".", "text_type...
Converts to lowercase, removes non-word characters (alphanumerics and underscores) and converts spaces to hyphens. Also strips leading and trailing whitespace. Modified to optionally allow dots. Adapted from Django 1.9
[ "Converts", "to", "lowercase", "removes", "non", "-", "word", "characters", "(", "alphanumerics", "and", "underscores", ")", "and", "converts", "spaces", "to", "hyphens", ".", "Also", "strips", "leading", "and", "trailing", "whitespace", ".", "Modified", "to", ...
python
train
talkincode/toughlib
toughlib/apiutils.py
https://github.com/talkincode/toughlib/blob/1c2f7dde3a7f101248f1b5f5d428cc85466995cf/toughlib/apiutils.py#L98-L106
def parse_form_request(api_secret, request): """ >>> parse_form_request("123456",{"nonce": 1451122677, "msg": "helllo", "code": 0, "sign": "DB30F4D1112C20DFA736F65458F89C64"}) <Storage {'nonce': 1451122677, 'msg': 'helllo', 'code': 0, 'sign': 'DB30F4D1112C20DFA736F65458F89C64'}> """ if not c...
[ "def", "parse_form_request", "(", "api_secret", ",", "request", ")", ":", "if", "not", "check_sign", "(", "api_secret", ",", "request", ")", ":", "raise", "SignError", "(", "u\"message sign error\"", ")", "return", "Storage", "(", "request", ")" ]
>>> parse_form_request("123456",{"nonce": 1451122677, "msg": "helllo", "code": 0, "sign": "DB30F4D1112C20DFA736F65458F89C64"}) <Storage {'nonce': 1451122677, 'msg': 'helllo', 'code': 0, 'sign': 'DB30F4D1112C20DFA736F65458F89C64'}>
[ ">>>", "parse_form_request", "(", "123456", "{", "nonce", ":", "1451122677", "msg", ":", "helllo", "code", ":", "0", "sign", ":", "DB30F4D1112C20DFA736F65458F89C64", "}", ")", "<Storage", "{", "nonce", ":", "1451122677", "msg", ":", "helllo", "code", ":", "0...
python
train
inspirehep/inspire-schemas
inspire_schemas/utils.py
https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/utils.py#L681-L707
def get_validation_errors(data, schema=None): """Validation errors for a given record. Args: data (dict): record to validate. schema (Union[dict, str]): schema to validate against. If it is a string, it is intepreted as the name of the schema to load (e.g. ``authors`` or...
[ "def", "get_validation_errors", "(", "data", ",", "schema", "=", "None", ")", ":", "schema", "=", "_load_schema_for_record", "(", "data", ",", "schema", ")", "errors", "=", "Draft4Validator", "(", "schema", ",", "resolver", "=", "LocalRefResolver", ".", "from_...
Validation errors for a given record. Args: data (dict): record to validate. schema (Union[dict, str]): schema to validate against. If it is a string, it is intepreted as the name of the schema to load (e.g. ``authors`` or ``jobs``). If it is ``None``, the schema is taken ...
[ "Validation", "errors", "for", "a", "given", "record", "." ]
python
train
viniciuschiele/flask-apscheduler
flask_apscheduler/utils.py
https://github.com/viniciuschiele/flask-apscheduler/blob/cc52c39e1948c4e8de5da0d01db45f1779f61997/flask_apscheduler/utils.py#L26-L43
def job_to_dict(job): """Converts a job to an OrderedDict.""" data = OrderedDict() data['id'] = job.id data['name'] = job.name data['func'] = job.func_ref data['args'] = job.args data['kwargs'] = job.kwargs data.update(trigger_to_dict(job.trigger)) if not job.pending: data...
[ "def", "job_to_dict", "(", "job", ")", ":", "data", "=", "OrderedDict", "(", ")", "data", "[", "'id'", "]", "=", "job", ".", "id", "data", "[", "'name'", "]", "=", "job", ".", "name", "data", "[", "'func'", "]", "=", "job", ".", "func_ref", "data...
Converts a job to an OrderedDict.
[ "Converts", "a", "job", "to", "an", "OrderedDict", "." ]
python
train
awslabs/aws-sam-cli
samcli/lib/build/workflow_config.py
https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/lib/build/workflow_config.py#L188-L216
def get_config(self, code_dir, project_dir): """ Finds a configuration by looking for a manifest in the given directories. Returns ------- samcli.lib.build.workflow_config.CONFIG A supported configuration if one is found Raises ------ ValueEr...
[ "def", "get_config", "(", "self", ",", "code_dir", ",", "project_dir", ")", ":", "# Search for manifest first in code directory and then in the project directory.", "# Search order is important here because we want to prefer the manifest present within the code directory over", "# a manifest...
Finds a configuration by looking for a manifest in the given directories. Returns ------- samcli.lib.build.workflow_config.CONFIG A supported configuration if one is found Raises ------ ValueError If none of the supported manifests files are foun...
[ "Finds", "a", "configuration", "by", "looking", "for", "a", "manifest", "in", "the", "given", "directories", "." ]
python
train
goerz/better-apidoc
better_apidoc.py
https://github.com/goerz/better-apidoc/blob/bbf979e01d7eff1a597c2608ef2609d1e83e8001/better_apidoc.py#L160-L255
def _get_members( mod, typ=None, include_imported=False, out_format='names', in_list=None, known_refs=None): """Get (filtered) public/total members of the module or package `mod`. Returns: lists `public` and `items`. The lists contains the public and private + public members, a...
[ "def", "_get_members", "(", "mod", ",", "typ", "=", "None", ",", "include_imported", "=", "False", ",", "out_format", "=", "'names'", ",", "in_list", "=", "None", ",", "known_refs", "=", "None", ")", ":", "roles", "=", "{", "'function'", ":", "'func'", ...
Get (filtered) public/total members of the module or package `mod`. Returns: lists `public` and `items`. The lists contains the public and private + public members, as strings.
[ "Get", "(", "filtered", ")", "public", "/", "total", "members", "of", "the", "module", "or", "package", "mod", "." ]
python
train
earlzo/hfut
hfut/util.py
https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/util.py#L71-L95
def cal_gpa(grades): """ 根据成绩数组计算课程平均绩点和 gpa, 算法不一定与学校一致, 结果仅供参考 :param grades: :meth:`models.StudentSession.get_my_achievements` 返回的成绩数组 :return: 包含了课程平均绩点和 gpa 的元组 """ # 课程总数 courses_sum = len(grades) # 课程绩点和 points_sum = 0 # 学分和 credit_sum = 0 # 课程学分 x 课程绩点之和 gpa_...
[ "def", "cal_gpa", "(", "grades", ")", ":", "# 课程总数", "courses_sum", "=", "len", "(", "grades", ")", "# 课程绩点和", "points_sum", "=", "0", "# 学分和", "credit_sum", "=", "0", "# 课程学分 x 课程绩点之和", "gpa_points_sum", "=", "0", "for", "grade", "in", "grades", ":", "poi...
根据成绩数组计算课程平均绩点和 gpa, 算法不一定与学校一致, 结果仅供参考 :param grades: :meth:`models.StudentSession.get_my_achievements` 返回的成绩数组 :return: 包含了课程平均绩点和 gpa 的元组
[ "根据成绩数组计算课程平均绩点和", "gpa", "算法不一定与学校一致", "结果仅供参考" ]
python
train
miguelgrinberg/slam
slam/cli.py
https://github.com/miguelgrinberg/slam/blob/cf68a4bbc16d909718f8a9e71072b822e0a3d94b/slam/cli.py#L47-L56
def on_error(e): # pragma: no cover """Error handler RuntimeError or ValueError exceptions raised by commands will be handled by this function. """ exname = {'RuntimeError': 'Runtime error', 'Value Error': 'Value error'} sys.stderr.write('{}: {}\n'.format(exname[e.__class__.__name__], str(e)))...
[ "def", "on_error", "(", "e", ")", ":", "# pragma: no cover", "exname", "=", "{", "'RuntimeError'", ":", "'Runtime error'", ",", "'Value Error'", ":", "'Value error'", "}", "sys", ".", "stderr", ".", "write", "(", "'{}: {}\\n'", ".", "format", "(", "exname", ...
Error handler RuntimeError or ValueError exceptions raised by commands will be handled by this function.
[ "Error", "handler" ]
python
train
majerteam/sqla_inspect
sqla_inspect/py3o.py
https://github.com/majerteam/sqla_inspect/blob/67edb5541e6a56b0a657d3774d1e19c1110cd402/sqla_inspect/py3o.py#L262-L295
def _get_to_many_relationship_value(self, obj, column): """ Get the resulting datas for a One To many or a many to many relationship :param obj obj: The instance we manage :param dict column: The column description dictionnary :returns: The associated value """ r...
[ "def", "_get_to_many_relationship_value", "(", "self", ",", "obj", ",", "column", ")", ":", "related_key", "=", "column", ".", "get", "(", "'related_key'", ",", "None", ")", "related", "=", "getattr", "(", "obj", ",", "column", "[", "'__col__'", "]", ".", ...
Get the resulting datas for a One To many or a many to many relationship :param obj obj: The instance we manage :param dict column: The column description dictionnary :returns: The associated value
[ "Get", "the", "resulting", "datas", "for", "a", "One", "To", "many", "or", "a", "many", "to", "many", "relationship" ]
python
train
cloudera/cm_api
python/src/cm_api/endpoints/clusters.py
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/clusters.py#L140-L150
def update_cdh_version(self, new_cdh_version): """ Manually set the CDH version. @param new_cdh_version: New CDH version, e.g. 4.5.1 @return: An ApiCluster object @since: API v6 """ dic = self.to_json_dict() dic['fullVersion'] = new_cdh_version return self._put_cluster(dic)
[ "def", "update_cdh_version", "(", "self", ",", "new_cdh_version", ")", ":", "dic", "=", "self", ".", "to_json_dict", "(", ")", "dic", "[", "'fullVersion'", "]", "=", "new_cdh_version", "return", "self", ".", "_put_cluster", "(", "dic", ")" ]
Manually set the CDH version. @param new_cdh_version: New CDH version, e.g. 4.5.1 @return: An ApiCluster object @since: API v6
[ "Manually", "set", "the", "CDH", "version", "." ]
python
train
knipknap/exscript
Exscript/util/ipv4.py
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/ipv4.py#L72-L86
def normalize_ip(ip): """ Transform the address into a fixed-length form, such as:: 192.168.0.1 -> 192.168.000.001 :type ip: string :param ip: An IP address. :rtype: string :return: The normalized IP. """ theip = ip.split('.') if len(theip) != 4: raise ValueError(...
[ "def", "normalize_ip", "(", "ip", ")", ":", "theip", "=", "ip", ".", "split", "(", "'.'", ")", "if", "len", "(", "theip", ")", "!=", "4", ":", "raise", "ValueError", "(", "'ip should be 4 tuples'", ")", "return", "'.'", ".", "join", "(", "str", "(", ...
Transform the address into a fixed-length form, such as:: 192.168.0.1 -> 192.168.000.001 :type ip: string :param ip: An IP address. :rtype: string :return: The normalized IP.
[ "Transform", "the", "address", "into", "a", "fixed", "-", "length", "form", "such", "as", "::" ]
python
train
rh-marketingops/dwm
dwm/dwmmain.py
https://github.com/rh-marketingops/dwm/blob/66c7d18db857afbe5d574478ceaaad6159ae7469/dwm/dwmmain.py#L229-L242
def _norm_lookup(self, record, hist=None): """ Perform generic validation lookup :param dict record: dictionary of values to validate :param dict hist: existing input of history values """ record, hist = self.data_lookup_method(fields_list=self.fields, ...
[ "def", "_norm_lookup", "(", "self", ",", "record", ",", "hist", "=", "None", ")", ":", "record", ",", "hist", "=", "self", ".", "data_lookup_method", "(", "fields_list", "=", "self", ".", "fields", ",", "mongo_db_obj", "=", "self", ".", "mongo", ",", "...
Perform generic validation lookup :param dict record: dictionary of values to validate :param dict hist: existing input of history values
[ "Perform", "generic", "validation", "lookup" ]
python
train
quantmind/pulsar
pulsar/async/monitor.py
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/monitor.py#L153-L164
def stop_actors(self, monitor): """Maintain the number of workers by spawning or killing as required """ if monitor.cfg.workers: num_to_kill = len(self.managed_actors) - monitor.cfg.workers for i in range(num_to_kill, 0, -1): w, kage = 0, sys.maxsize ...
[ "def", "stop_actors", "(", "self", ",", "monitor", ")", ":", "if", "monitor", ".", "cfg", ".", "workers", ":", "num_to_kill", "=", "len", "(", "self", ".", "managed_actors", ")", "-", "monitor", ".", "cfg", ".", "workers", "for", "i", "in", "range", ...
Maintain the number of workers by spawning or killing as required
[ "Maintain", "the", "number", "of", "workers", "by", "spawning", "or", "killing", "as", "required" ]
python
train
dmort27/panphon
panphon/_panphon.py
https://github.com/dmort27/panphon/blob/17eaa482e3edb211f3a8138137d76e4b9246d201/panphon/_panphon.py#L77-L101
def word2array(ft_names, word): """Converts `word` [[(value, feature),...],...] to a NumPy array Given a word consisting of lists of lists/sets of (value, feature) tuples, return a NumPy array where each row is a segment and each column is a feature. Args: ft_names (list): list of feature ...
[ "def", "word2array", "(", "ft_names", ",", "word", ")", ":", "vdict", "=", "{", "'+'", ":", "1", ",", "'-'", ":", "-", "1", ",", "'0'", ":", "0", "}", "def", "seg2col", "(", "seg", ")", ":", "seg", "=", "dict", "(", "[", "(", "k", ",", "v",...
Converts `word` [[(value, feature),...],...] to a NumPy array Given a word consisting of lists of lists/sets of (value, feature) tuples, return a NumPy array where each row is a segment and each column is a feature. Args: ft_names (list): list of feature names (as strings) in order; this ...
[ "Converts", "word", "[[", "(", "value", "feature", ")", "...", "]", "...", "]", "to", "a", "NumPy", "array" ]
python
train
numenta/nupic
src/nupic/algorithms/backtracking_tm_shim.py
https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/backtracking_tm_shim.py#L256-L278
def compute(self, bottomUpInput, enableLearn, computeInfOutput=None): """ (From `backtracking_tm.py`) Handle one compute, possibly learning. @param bottomUpInput The bottom-up input, typically from a spatial pooler @param enableLearn If true, perform learning @param computeInfOutput ...
[ "def", "compute", "(", "self", ",", "bottomUpInput", ",", "enableLearn", ",", "computeInfOutput", "=", "None", ")", ":", "super", "(", "MonitoredTMShim", ",", "self", ")", ".", "compute", "(", "set", "(", "bottomUpInput", ".", "nonzero", "(", ")", "[", "...
(From `backtracking_tm.py`) Handle one compute, possibly learning. @param bottomUpInput The bottom-up input, typically from a spatial pooler @param enableLearn If true, perform learning @param computeInfOutput If None, default behavior is to disable the inference ...
[ "(", "From", "backtracking_tm", ".", "py", ")", "Handle", "one", "compute", "possibly", "learning", "." ]
python
valid
adrn/gala
gala/dynamics/orbit.py
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/orbit.py#L733-L800
def align_circulation_with_z(self, circulation=None): """ If the input orbit is a tube orbit, this function aligns the circulation axis with the z axis and returns a copy. Parameters ---------- circulation : array_like (optional) Array of bits that specify th...
[ "def", "align_circulation_with_z", "(", "self", ",", "circulation", "=", "None", ")", ":", "if", "circulation", "is", "None", ":", "circulation", "=", "self", ".", "circulation", "(", ")", "circulation", "=", "atleast_2d", "(", "circulation", ",", "insert_axis...
If the input orbit is a tube orbit, this function aligns the circulation axis with the z axis and returns a copy. Parameters ---------- circulation : array_like (optional) Array of bits that specify the axis about which the orbit circulates. If not provided, will...
[ "If", "the", "input", "orbit", "is", "a", "tube", "orbit", "this", "function", "aligns", "the", "circulation", "axis", "with", "the", "z", "axis", "and", "returns", "a", "copy", "." ]
python
train
syndbg/demonoid-api
demonoid/parser.py
https://github.com/syndbg/demonoid-api/blob/518aa389ac91b5243b92fc19923103f31041a61e/demonoid/parser.py#L154-L174
def parse_torrent_properties(table_datas): """ Static method that parses a given list of table data elements and using helper methods `Parser.is_subcategory`, `Parser.is_quality`, `Parser.is_language`, collects torrent properties. :param list lxml.HtmlElement table_datas: table_datas to...
[ "def", "parse_torrent_properties", "(", "table_datas", ")", ":", "output", "=", "{", "'category'", ":", "table_datas", "[", "0", "]", ".", "text", ",", "'subcategory'", ":", "None", ",", "'quality'", ":", "None", ",", "'language'", ":", "None", "}", "for",...
Static method that parses a given list of table data elements and using helper methods `Parser.is_subcategory`, `Parser.is_quality`, `Parser.is_language`, collects torrent properties. :param list lxml.HtmlElement table_datas: table_datas to parse :return: identified category, subcategory, quali...
[ "Static", "method", "that", "parses", "a", "given", "list", "of", "table", "data", "elements", "and", "using", "helper", "methods", "Parser", ".", "is_subcategory", "Parser", ".", "is_quality", "Parser", ".", "is_language", "collects", "torrent", "properties", "...
python
train
shendo/websnort
websnort/runner.py
https://github.com/shendo/websnort/blob/19495e8834a111e889ba28efad8cd90cf55eb661/websnort/runner.py#L86-L126
def run(pcap): """ Runs all configured IDS instances against the supplied pcap. :param pcap: File path to pcap file to analyse :returns: Dict with details and results of run/s """ start = datetime.now() errors = [] status = STATUS_FAILED analyses = [] pool = ThreadPool(MAX_THREA...
[ "def", "run", "(", "pcap", ")", ":", "start", "=", "datetime", ".", "now", "(", ")", "errors", "=", "[", "]", "status", "=", "STATUS_FAILED", "analyses", "=", "[", "]", "pool", "=", "ThreadPool", "(", "MAX_THREADS", ")", "try", ":", "if", "not", "i...
Runs all configured IDS instances against the supplied pcap. :param pcap: File path to pcap file to analyse :returns: Dict with details and results of run/s
[ "Runs", "all", "configured", "IDS", "instances", "against", "the", "supplied", "pcap", "." ]
python
train
inspirehep/inspire-query-parser
inspire_query_parser/visitors/elastic_search_visitor.py
https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/visitors/elastic_search_visitor.py#L191-L250
def _generate_author_query(self, author_name): """Generates a query handling specifically authors. Notes: The match query is generic enough to return many results. Then, using the filter clause we truncate these so that we imitate legacy's behaviour on returning more "exact" res...
[ "def", "_generate_author_query", "(", "self", ",", "author_name", ")", ":", "name_variations", "=", "[", "name_variation", ".", "lower", "(", ")", "for", "name_variation", "in", "generate_minimal_name_variations", "(", "author_name", ")", "]", "# When the query contai...
Generates a query handling specifically authors. Notes: The match query is generic enough to return many results. Then, using the filter clause we truncate these so that we imitate legacy's behaviour on returning more "exact" results. E.g. Searching for `Smith, John` shouldn...
[ "Generates", "a", "query", "handling", "specifically", "authors", "." ]
python
train
hyperledger/sawtooth-core
validator/sawtooth_validator/networking/interconnect.py
https://github.com/hyperledger/sawtooth-core/blob/8cf473bc2207e51f02bd182d825158a57d72b098/validator/sawtooth_validator/networking/interconnect.py#L481-L590
def setup(self, socket_type, complete_or_error_queue): """Setup the asyncio event loop. Args: socket_type (int from zmq.*): One of zmq.DEALER or zmq.ROUTER complete_or_error_queue (queue.Queue): A way to propagate errors back to the calling thread. Needed since t...
[ "def", "setup", "(", "self", ",", "socket_type", ",", "complete_or_error_queue", ")", ":", "try", ":", "if", "self", ".", "_secured", ":", "if", "self", ".", "_server_public_key", "is", "None", "or", "self", ".", "_server_private_key", "is", "None", ":", "...
Setup the asyncio event loop. Args: socket_type (int from zmq.*): One of zmq.DEALER or zmq.ROUTER complete_or_error_queue (queue.Queue): A way to propagate errors back to the calling thread. Needed since this function is directly used in Thread. ...
[ "Setup", "the", "asyncio", "event", "loop", "." ]
python
train
molmod/molmod
molmod/pairff.py
https://github.com/molmod/molmod/blob/a7b5b4364ed514ad4c465856c05b5eda1cb561e0/molmod/pairff.py#L282-L287
def esp(self): """Compute the electrostatic potential at each atom due to other atoms""" result = np.zeros(self.numc, float) for index1 in range(self.numc): result[index1] = self.esp_component(index1) return result
[ "def", "esp", "(", "self", ")", ":", "result", "=", "np", ".", "zeros", "(", "self", ".", "numc", ",", "float", ")", "for", "index1", "in", "range", "(", "self", ".", "numc", ")", ":", "result", "[", "index1", "]", "=", "self", ".", "esp_componen...
Compute the electrostatic potential at each atom due to other atoms
[ "Compute", "the", "electrostatic", "potential", "at", "each", "atom", "due", "to", "other", "atoms" ]
python
train
WebarchivCZ/WA-KAT
src/wa_kat/templates/static/js/Lib/site-packages/components/output_picker.py
https://github.com/WebarchivCZ/WA-KAT/blob/16d064a3a775dc1d2713debda7847ded52dd2a06/src/wa_kat/templates/static/js/Lib/site-packages/components/output_picker.py#L52-L62
def show(cls, values=None): """ Show the interface for picking / downloading the datasets. """ if values: cls.set(values) cls.el.style.display = "block" cls.overlay.show() cls.overlay.el.bind("click", lambda x: cls.hide())
[ "def", "show", "(", "cls", ",", "values", "=", "None", ")", ":", "if", "values", ":", "cls", ".", "set", "(", "values", ")", "cls", ".", "el", ".", "style", ".", "display", "=", "\"block\"", "cls", ".", "overlay", ".", "show", "(", ")", "cls", ...
Show the interface for picking / downloading the datasets.
[ "Show", "the", "interface", "for", "picking", "/", "downloading", "the", "datasets", "." ]
python
train
Qiskit/qiskit-terra
qiskit/tools/qcvv/fitters.py
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/qcvv/fitters.py#L93-L119
def rb_epc(fit, rb_pattern): """Take the rb fit data and convert it into EPC (error per Clifford) Args: fit (dict): dictionary of the fit quantities (A, alpha, B) with the keys 'qn' where n is the qubit and subkeys 'fit', e.g. {'q0':{'fit': [1, 0, 0.9], 'fiterr': [0, 0, 0]}}} ...
[ "def", "rb_epc", "(", "fit", ",", "rb_pattern", ")", ":", "for", "patterns", "in", "rb_pattern", ":", "for", "qubit", "in", "patterns", ":", "fitalpha", "=", "fit", "[", "'q%d'", "%", "qubit", "]", "[", "'fit'", "]", "[", "1", "]", "fitalphaerr", "="...
Take the rb fit data and convert it into EPC (error per Clifford) Args: fit (dict): dictionary of the fit quantities (A, alpha, B) with the keys 'qn' where n is the qubit and subkeys 'fit', e.g. {'q0':{'fit': [1, 0, 0.9], 'fiterr': [0, 0, 0]}}} rb_pattern (list): (see rando...
[ "Take", "the", "rb", "fit", "data", "and", "convert", "it", "into", "EPC", "(", "error", "per", "Clifford", ")" ]
python
test
tomduck/pandoc-tablenos
pandoc_tablenos.py
https://github.com/tomduck/pandoc-tablenos/blob/b3c7b6a259eec5fb7c8420033d05b32640f1f266/pandoc_tablenos.py#L89-L107
def attach_attrs_table(key, value, fmt, meta): """Extracts attributes and attaches them to element.""" # We can't use attach_attrs_factory() because Table is a block-level element if key in ['Table']: assert len(value) == 5 caption = value[0] # caption, align, x, head, body # Set ...
[ "def", "attach_attrs_table", "(", "key", ",", "value", ",", "fmt", ",", "meta", ")", ":", "# We can't use attach_attrs_factory() because Table is a block-level element", "if", "key", "in", "[", "'Table'", "]", ":", "assert", "len", "(", "value", ")", "==", "5", ...
Extracts attributes and attaches them to element.
[ "Extracts", "attributes", "and", "attaches", "them", "to", "element", "." ]
python
train
bcbio/bcbio-nextgen
bcbio/heterogeneity/theta.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/heterogeneity/theta.py#L100-L120
def _run_theta(cnv_info, data, work_dir, run_n3=True): """Run theta, calculating subpopulations and normal contamination. """ out = {"caller": "theta"} max_normal = "0.9" opts = ["-m", max_normal] n2_result = _safe_run_theta(cnv_info["theta_input"], os.path.join(work_dir, "n2"), ".n2.results", ...
[ "def", "_run_theta", "(", "cnv_info", ",", "data", ",", "work_dir", ",", "run_n3", "=", "True", ")", ":", "out", "=", "{", "\"caller\"", ":", "\"theta\"", "}", "max_normal", "=", "\"0.9\"", "opts", "=", "[", "\"-m\"", ",", "max_normal", "]", "n2_result",...
Run theta, calculating subpopulations and normal contamination.
[ "Run", "theta", "calculating", "subpopulations", "and", "normal", "contamination", "." ]
python
train
fermiPy/fermipy
fermipy/gtanalysis.py
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/gtanalysis.py#L4818-L4872
def weight_map(self): """Return 3-D weights map for this component as a Map object. Returns ------- map : `~fermipy.skymap.MapBase` """ # EAC we need the try blocks b/c older versions of the ST don't have some of these functions if isinstance(self.like, gtutils....
[ "def", "weight_map", "(", "self", ")", ":", "# EAC we need the try blocks b/c older versions of the ST don't have some of these functions", "if", "isinstance", "(", "self", ".", "like", ",", "gtutils", ".", "SummedLikelihood", ")", ":", "cmap", "=", "self", ".", "like",...
Return 3-D weights map for this component as a Map object. Returns ------- map : `~fermipy.skymap.MapBase`
[ "Return", "3", "-", "D", "weights", "map", "for", "this", "component", "as", "a", "Map", "object", "." ]
python
train
Microsoft/nni
src/sdk/pynni/nni/bohb_advisor/bohb_advisor.py
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/bohb_advisor/bohb_advisor.py#L215-L237
def get_hyperparameter_configurations(self, num, r, config_generator): """generate num hyperparameter configurations from search space using Bayesian optimization Parameters ---------- num: int the number of hyperparameter configurations Returns ------- ...
[ "def", "get_hyperparameter_configurations", "(", "self", ",", "num", ",", "r", ",", "config_generator", ")", ":", "global", "_KEY", "assert", "self", ".", "i", "==", "0", "hyperparameter_configs", "=", "dict", "(", ")", "for", "_", "in", "range", "(", "num...
generate num hyperparameter configurations from search space using Bayesian optimization Parameters ---------- num: int the number of hyperparameter configurations Returns ------- list a list of hyperparameter configurations. Format: [[key1, valu...
[ "generate", "num", "hyperparameter", "configurations", "from", "search", "space", "using", "Bayesian", "optimization" ]
python
train
KrishnaswamyLab/PHATE
Python/phate/phate.py
https://github.com/KrishnaswamyLab/PHATE/blob/346a4597dcfc523f8bef99bce482e677282b6719/Python/phate/phate.py#L813-L863
def calculate_potential(self, t=None, t_max=100, plot_optimal_t=False, ax=None): """Calculates the diffusion potential Parameters ---------- t : int power to which the diffusion operator is powered sets the level of diffusion ...
[ "def", "calculate_potential", "(", "self", ",", "t", "=", "None", ",", "t_max", "=", "100", ",", "plot_optimal_t", "=", "False", ",", "ax", "=", "None", ")", ":", "if", "t", "is", "None", ":", "t", "=", "self", ".", "t", "if", "self", ".", "diff_...
Calculates the diffusion potential Parameters ---------- t : int power to which the diffusion operator is powered sets the level of diffusion t_max : int, default: 100 Maximum value of `t` to test plot_optimal_t : boolean, default: False ...
[ "Calculates", "the", "diffusion", "potential" ]
python
train
klen/muffin-redis
muffin_redis.py
https://github.com/klen/muffin-redis/blob/b0cb8c1ba1511d501c2084def156710e75aaf781/muffin_redis.py#L126-L133
def publish(self, channel, message): """Publish message to channel. :returns: a coroutine """ if self.cfg.jsonpickle: message = jsonpickle.encode(message) return self.conn.publish(channel, message)
[ "def", "publish", "(", "self", ",", "channel", ",", "message", ")", ":", "if", "self", ".", "cfg", ".", "jsonpickle", ":", "message", "=", "jsonpickle", ".", "encode", "(", "message", ")", "return", "self", ".", "conn", ".", "publish", "(", "channel", ...
Publish message to channel. :returns: a coroutine
[ "Publish", "message", "to", "channel", "." ]
python
train
linkedin/naarad
lib/luminol/src/luminol/algorithms/correlator_algorithms/cross_correlator.py
https://github.com/linkedin/naarad/blob/261e2c0760fd6a6b0ee59064180bd8e3674311fe/lib/luminol/src/luminol/algorithms/correlator_algorithms/cross_correlator.py#L94-L108
def _find_first_bigger(self, timestamps, target, lower_bound, upper_bound): """ Find the first element in timestamps whose value is bigger than target. param list values: list of timestamps(epoch number). param target: target value. param lower_bound: lower bound for binary search. param upper_b...
[ "def", "_find_first_bigger", "(", "self", ",", "timestamps", ",", "target", ",", "lower_bound", ",", "upper_bound", ")", ":", "while", "lower_bound", "<", "upper_bound", ":", "pos", "=", "lower_bound", "+", "(", "upper_bound", "-", "lower_bound", ")", "/", "...
Find the first element in timestamps whose value is bigger than target. param list values: list of timestamps(epoch number). param target: target value. param lower_bound: lower bound for binary search. param upper_bound: upper bound for binary search.
[ "Find", "the", "first", "element", "in", "timestamps", "whose", "value", "is", "bigger", "than", "target", ".", "param", "list", "values", ":", "list", "of", "timestamps", "(", "epoch", "number", ")", ".", "param", "target", ":", "target", "value", ".", ...
python
valid
log2timeline/dfvfs
dfvfs/helpers/windows_path_resolver.py
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/windows_path_resolver.py#L261-L273
def SetEnvironmentVariable(self, name, value): """Sets an environment variable in the Windows path helper. Args: name (str): name of the environment variable without enclosing %-characters, e.g. SystemRoot as in %SystemRoot%. value (str): value of the environment variable. """ if ...
[ "def", "SetEnvironmentVariable", "(", "self", ",", "name", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "py2to3", ".", "STRING_TYPES", ")", ":", "value", "=", "self", ".", "_PathStripPrefix", "(", "value", ")", "if", "value", "is", "not...
Sets an environment variable in the Windows path helper. Args: name (str): name of the environment variable without enclosing %-characters, e.g. SystemRoot as in %SystemRoot%. value (str): value of the environment variable.
[ "Sets", "an", "environment", "variable", "in", "the", "Windows", "path", "helper", "." ]
python
train
MIT-LCP/wfdb-python
wfdb/plot/plot.py
https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/plot/plot.py#L11-L123
def plot_items(signal=None, ann_samp=None, ann_sym=None, fs=None, time_units='samples', sig_name=None, sig_units=None, ylabel=None, title=None, sig_style=[''], ann_style=['r*'], ecg_grids=[], figsize=None, return_fig=False): """ Subplot individual channels of signals...
[ "def", "plot_items", "(", "signal", "=", "None", ",", "ann_samp", "=", "None", ",", "ann_sym", "=", "None", ",", "fs", "=", "None", ",", "time_units", "=", "'samples'", ",", "sig_name", "=", "None", ",", "sig_units", "=", "None", ",", "ylabel", "=", ...
Subplot individual channels of signals and/or annotations. Parameters ---------- signal : 1d or 2d numpy array, optional The uniformly sampled signal to be plotted. If signal.ndim is 1, it is assumed to be a one channel signal. If it is 2, axes 0 and 1, must represent time and chann...
[ "Subplot", "individual", "channels", "of", "signals", "and", "/", "or", "annotations", "." ]
python
train
retr0h/git-url-parse
giturlparse/parser.py
https://github.com/retr0h/git-url-parse/blob/98a5377aa8c8f3b8896f277c5c81558749feef58/giturlparse/parser.py#L78-L106
def parse(self): """ Parses a GIT URL and returns an object. Raises an exception on invalid URL. :returns: Parsed object :raise: :class:`.ParserError` """ d = { 'pathname': None, 'protocols': self._get_protocols(), 'protocol':...
[ "def", "parse", "(", "self", ")", ":", "d", "=", "{", "'pathname'", ":", "None", ",", "'protocols'", ":", "self", ".", "_get_protocols", "(", ")", ",", "'protocol'", ":", "'ssh'", ",", "'href'", ":", "self", ".", "_url", ",", "'resource'", ":", "None...
Parses a GIT URL and returns an object. Raises an exception on invalid URL. :returns: Parsed object :raise: :class:`.ParserError`
[ "Parses", "a", "GIT", "URL", "and", "returns", "an", "object", ".", "Raises", "an", "exception", "on", "invalid", "URL", "." ]
python
train
google/flatbuffers
python/flatbuffers/table.py
https://github.com/google/flatbuffers/blob/6cc30b3272d79c85db7d4871ac0aa69541dc89de/python/flatbuffers/table.py#L32-L41
def Offset(self, vtableOffset): """Offset provides access into the Table's vtable. Deprecated fields are ignored by checking the vtable's length.""" vtable = self.Pos - self.Get(N.SOffsetTFlags, self.Pos) vtableEnd = self.Get(N.VOffsetTFlags, vtable) if vtableOffset < vtableEnd...
[ "def", "Offset", "(", "self", ",", "vtableOffset", ")", ":", "vtable", "=", "self", ".", "Pos", "-", "self", ".", "Get", "(", "N", ".", "SOffsetTFlags", ",", "self", ".", "Pos", ")", "vtableEnd", "=", "self", ".", "Get", "(", "N", ".", "VOffsetTFla...
Offset provides access into the Table's vtable. Deprecated fields are ignored by checking the vtable's length.
[ "Offset", "provides", "access", "into", "the", "Table", "s", "vtable", "." ]
python
train
iskandr/serializable
serializable/helpers.py
https://github.com/iskandr/serializable/blob/6807dfd582567b3bda609910806b7429d8d53b44/serializable/helpers.py#L188-L224
def from_serializable_dict(x): """ Reconstruct a dictionary by recursively reconstructing all its keys and values. This is the most hackish part since we rely on key names such as __name__, __class__, __module__ as metadata about how to reconstruct an object. TODO: It would be cleaner to a...
[ "def", "from_serializable_dict", "(", "x", ")", ":", "if", "\"__name__\"", "in", "x", ":", "return", "_lookup_value", "(", "x", ".", "pop", "(", "\"__module__\"", ")", ",", "x", ".", "pop", "(", "\"__name__\"", ")", ")", "non_string_key_objects", "=", "[",...
Reconstruct a dictionary by recursively reconstructing all its keys and values. This is the most hackish part since we rely on key names such as __name__, __class__, __module__ as metadata about how to reconstruct an object. TODO: It would be cleaner to always wrap each object in a layer of type ...
[ "Reconstruct", "a", "dictionary", "by", "recursively", "reconstructing", "all", "its", "keys", "and", "values", "." ]
python
train
openai/baselines
baselines/common/tf_util.py
https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/tf_util.py#L404-L416
def _check_shape(placeholder_shape, data_shape): ''' check if two shapes are compatible (i.e. differ only by dimensions of size 1, or by the batch dimension)''' return True squeezed_placeholder_shape = _squeeze_shape(placeholder_shape) squeezed_data_shape = _squeeze_shape(data_shape) for i, s_data...
[ "def", "_check_shape", "(", "placeholder_shape", ",", "data_shape", ")", ":", "return", "True", "squeezed_placeholder_shape", "=", "_squeeze_shape", "(", "placeholder_shape", ")", "squeezed_data_shape", "=", "_squeeze_shape", "(", "data_shape", ")", "for", "i", ",", ...
check if two shapes are compatible (i.e. differ only by dimensions of size 1, or by the batch dimension)
[ "check", "if", "two", "shapes", "are", "compatible", "(", "i", ".", "e", ".", "differ", "only", "by", "dimensions", "of", "size", "1", "or", "by", "the", "batch", "dimension", ")" ]
python
valid
timothyb0912/pylogit
pylogit/mixed_logit.py
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/mixed_logit.py#L358-L375
def convenience_calc_fisher_approx(self, params): """ Calculates the BHHH approximation of the Fisher Information Matrix for this model / dataset. Note that this function name is INCORRECT with regard to the actual actions performed. The Mixed Logit model uses a placeholder for t...
[ "def", "convenience_calc_fisher_approx", "(", "self", ",", "params", ")", ":", "shapes", ",", "intercepts", ",", "betas", "=", "self", ".", "convenience_split_params", "(", "params", ")", "placeholder_bhhh", "=", "np", ".", "diag", "(", "-", "1", "*", "np", ...
Calculates the BHHH approximation of the Fisher Information Matrix for this model / dataset. Note that this function name is INCORRECT with regard to the actual actions performed. The Mixed Logit model uses a placeholder for the BHHH approximation of the Fisher Information Matrix because...
[ "Calculates", "the", "BHHH", "approximation", "of", "the", "Fisher", "Information", "Matrix", "for", "this", "model", "/", "dataset", ".", "Note", "that", "this", "function", "name", "is", "INCORRECT", "with", "regard", "to", "the", "actual", "actions", "perfo...
python
train
portfors-lab/sparkle
sparkle/gui/plotting/pyqtgraph_widgets.py
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/plotting/pyqtgraph_widgets.py#L403-L412
def fromFile(self, fname): """Displays a spectrogram of an audio file. Supported formats see :func:`sparkle.tools.audiotools.audioread` :param fname: file path of the audiofile to display :type fname: str :returns: float -- duration of audio recording (seconds) """ spec,...
[ "def", "fromFile", "(", "self", ",", "fname", ")", ":", "spec", ",", "f", ",", "bins", ",", "dur", "=", "audiotools", ".", "spectrogram", "(", "fname", ",", "*", "*", "self", ".", "specgramArgs", ")", "self", ".", "updateImage", "(", "spec", ",", "...
Displays a spectrogram of an audio file. Supported formats see :func:`sparkle.tools.audiotools.audioread` :param fname: file path of the audiofile to display :type fname: str :returns: float -- duration of audio recording (seconds)
[ "Displays", "a", "spectrogram", "of", "an", "audio", "file", ".", "Supported", "formats", "see", ":", "func", ":", "sparkle", ".", "tools", ".", "audiotools", ".", "audioread" ]
python
train
jaraco/hgtools
hgtools/versioning.py
https://github.com/jaraco/hgtools/blob/bf5fe2324e5ae15e012487f95f0c97c3775c5d2e/hgtools/versioning.py#L111-L122
def get_tagged_version(self): """ Get the version of the local working set as a StrictVersion or None if no viable tag exists. If the local working set is itself the tagged commit and the tip and there are no local modifications, use the tag on the parent changeset. """ tags = list(self.get_tags()) if '...
[ "def", "get_tagged_version", "(", "self", ")", ":", "tags", "=", "list", "(", "self", ".", "get_tags", "(", ")", ")", "if", "'tip'", "in", "tags", "and", "not", "self", ".", "is_modified", "(", ")", ":", "tags", "=", "self", ".", "get_parent_tags", "...
Get the version of the local working set as a StrictVersion or None if no viable tag exists. If the local working set is itself the tagged commit and the tip and there are no local modifications, use the tag on the parent changeset.
[ "Get", "the", "version", "of", "the", "local", "working", "set", "as", "a", "StrictVersion", "or", "None", "if", "no", "viable", "tag", "exists", ".", "If", "the", "local", "working", "set", "is", "itself", "the", "tagged", "commit", "and", "the", "tip",...
python
train
apache/spark
python/pyspark/mllib/linalg/__init__.py
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/mllib/linalg/__init__.py#L297-L316
def parse(s): """ Parse string representation back into the DenseVector. >>> DenseVector.parse(' [ 0.0,1.0,2.0, 3.0]') DenseVector([0.0, 1.0, 2.0, 3.0]) """ start = s.find('[') if start == -1: raise ValueError("Array should start with '['.") ...
[ "def", "parse", "(", "s", ")", ":", "start", "=", "s", ".", "find", "(", "'['", ")", "if", "start", "==", "-", "1", ":", "raise", "ValueError", "(", "\"Array should start with '['.\"", ")", "end", "=", "s", ".", "find", "(", "']'", ")", "if", "end"...
Parse string representation back into the DenseVector. >>> DenseVector.parse(' [ 0.0,1.0,2.0, 3.0]') DenseVector([0.0, 1.0, 2.0, 3.0])
[ "Parse", "string", "representation", "back", "into", "the", "DenseVector", "." ]
python
train
cdeboever3/cdpybio
cdpybio/analysis.py
https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/analysis.py#L704-L753
def plot_variance_explained(self, cumulative=False, xtick_start=1, xtick_spacing=1, num_pc=None): """ Plot amount of variance explained by each principal component. Parameters ---------- num_pc : int Number of principal components...
[ "def", "plot_variance_explained", "(", "self", ",", "cumulative", "=", "False", ",", "xtick_start", "=", "1", ",", "xtick_spacing", "=", "1", ",", "num_pc", "=", "None", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "from", "numpy", "import...
Plot amount of variance explained by each principal component. Parameters ---------- num_pc : int Number of principal components to plot. If None, plot all. cumulative : bool If True, include cumulative variance. xtick_start : int ...
[ "Plot", "amount", "of", "variance", "explained", "by", "each", "principal", "component", ".", "Parameters", "----------", "num_pc", ":", "int", "Number", "of", "principal", "components", "to", "plot", ".", "If", "None", "plot", "all", ".", "cumulative", ":", ...
python
train
jason-weirather/py-seq-tools
seqtools/align.py
https://github.com/jason-weirather/py-seq-tools/blob/f642c2c73ffef2acc83656a78059a476fc734ca1/seqtools/align.py#L363-L398
def get_SAM(self,min_intron_size=68): """Get a SAM object representation of the alignment. :returns: SAM representation :rtype: SAM """ from seqtools.format.sam import SAM #ar is target then query qname = self.alignment_ranges[0][1].chr flag = 0 if self.strand == '-': flag = 16 ...
[ "def", "get_SAM", "(", "self", ",", "min_intron_size", "=", "68", ")", ":", "from", "seqtools", ".", "format", ".", "sam", "import", "SAM", "#ar is target then query", "qname", "=", "self", ".", "alignment_ranges", "[", "0", "]", "[", "1", "]", ".", "chr...
Get a SAM object representation of the alignment. :returns: SAM representation :rtype: SAM
[ "Get", "a", "SAM", "object", "representation", "of", "the", "alignment", "." ]
python
train
Fantomas42/django-blog-zinnia
zinnia/views/mixins/entry_protection.py
https://github.com/Fantomas42/django-blog-zinnia/blob/b4949304b104a8e1a7a7a0773cbfd024313c3a15/zinnia/views/mixins/entry_protection.py#L57-L73
def post(self, request, *args, **kwargs): """ Do the login and password protection. """ self.object = self.get_object() self.login() if self.object.password: entry_password = self.request.POST.get('entry_password') if entry_password: ...
[ "def", "post", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "object", "=", "self", ".", "get_object", "(", ")", "self", ".", "login", "(", ")", "if", "self", ".", "object", ".", "password", ":", ...
Do the login and password protection.
[ "Do", "the", "login", "and", "password", "protection", "." ]
python
train
vertexproject/synapse
synapse/lib/chop.py
https://github.com/vertexproject/synapse/blob/22e67c5a8f6d7caddbcf34b39ab1bd2d6c4a6e0b/synapse/lib/chop.py#L72-L78
def tags(norm): ''' Divide a normalized tag string into hierarchical layers. ''' # this is ugly for speed.... parts = norm.split('.') return ['.'.join(parts[:i]) for i in range(1, len(parts) + 1)]
[ "def", "tags", "(", "norm", ")", ":", "# this is ugly for speed....", "parts", "=", "norm", ".", "split", "(", "'.'", ")", "return", "[", "'.'", ".", "join", "(", "parts", "[", ":", "i", "]", ")", "for", "i", "in", "range", "(", "1", ",", "len", ...
Divide a normalized tag string into hierarchical layers.
[ "Divide", "a", "normalized", "tag", "string", "into", "hierarchical", "layers", "." ]
python
train
Parisson/TimeSide
timeside/server/models.py
https://github.com/Parisson/TimeSide/blob/0618d75cd2f16021afcfd3d5b77f692adad76ea5/timeside/server/models.py#L184-L190
def get_uri(self): """Return the Item source""" if self.source_file and os.path.exists(self.source_file.path): return self.source_file.path elif self.source_url: return self.source_url return None
[ "def", "get_uri", "(", "self", ")", ":", "if", "self", ".", "source_file", "and", "os", ".", "path", ".", "exists", "(", "self", ".", "source_file", ".", "path", ")", ":", "return", "self", ".", "source_file", ".", "path", "elif", "self", ".", "sourc...
Return the Item source
[ "Return", "the", "Item", "source" ]
python
train
bitesofcode/projexui
projexui/widgets/xtreewidget/xtreewidgetdelegate.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtreewidget/xtreewidgetdelegate.py#L265-L299
def drawGrid(self, painter, opt, rect, index): """ Draws the grid lines for this delegate. :param painter | <QtGui.QPainter> opt | <QtGui.QStyleOptionItem> rect | <QtCore.QRect> index | <QtGui.QModelIndex> ...
[ "def", "drawGrid", "(", "self", ",", "painter", ",", "opt", ",", "rect", ",", "index", ")", ":", "if", "not", "self", ".", "showGrid", "(", ")", ":", "return", "painter", ".", "setBrush", "(", "QtCore", ".", "Qt", ".", "NoBrush", ")", "painter", "....
Draws the grid lines for this delegate. :param painter | <QtGui.QPainter> opt | <QtGui.QStyleOptionItem> rect | <QtCore.QRect> index | <QtGui.QModelIndex>
[ "Draws", "the", "grid", "lines", "for", "this", "delegate", ".", ":", "param", "painter", "|", "<QtGui", ".", "QPainter", ">", "opt", "|", "<QtGui", ".", "QStyleOptionItem", ">", "rect", "|", "<QtCore", ".", "QRect", ">", "index", "|", "<QtGui", ".", "...
python
train
metagriffin/fso
fso/filesystemoverlay.py
https://github.com/metagriffin/fso/blob/c37701fbfdfde359a2044eb9420abe569a7b35e4/fso/filesystemoverlay.py#L374-L379
def _lexists(self, path): '''IMPORTANT: expects `path` to already be deref()'erenced.''' try: return bool(self._lstat(path)) except os.error: return False
[ "def", "_lexists", "(", "self", ",", "path", ")", ":", "try", ":", "return", "bool", "(", "self", ".", "_lstat", "(", "path", ")", ")", "except", "os", ".", "error", ":", "return", "False" ]
IMPORTANT: expects `path` to already be deref()'erenced.
[ "IMPORTANT", ":", "expects", "path", "to", "already", "be", "deref", "()", "erenced", "." ]
python
valid
deschler/django-modeltranslation
modeltranslation/translator.py
https://github.com/deschler/django-modeltranslation/blob/18fec04a5105cbd83fc3759f4fda20135b3a848c/modeltranslation/translator.py#L390-L428
def register(self, model_or_iterable, opts_class=None, **options): """ Registers the given model(s) with the given translation options. The model(s) should be Model classes, not instances. Fields declared for translation on a base class are inherited by subclasses. If the model...
[ "def", "register", "(", "self", ",", "model_or_iterable", ",", "opts_class", "=", "None", ",", "*", "*", "options", ")", ":", "if", "isinstance", "(", "model_or_iterable", ",", "ModelBase", ")", ":", "model_or_iterable", "=", "[", "model_or_iterable", "]", "...
Registers the given model(s) with the given translation options. The model(s) should be Model classes, not instances. Fields declared for translation on a base class are inherited by subclasses. If the model or one of its subclasses is already registered for translation, this will rais...
[ "Registers", "the", "given", "model", "(", "s", ")", "with", "the", "given", "translation", "options", "." ]
python
train
StackStorm/pybind
pybind/slxos/v17r_1_01a/isis_state/router_isis_config/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17r_1_01a/isis_state/router_isis_config/__init__.py#L1219-L1242
def _set_l2_spf_timer(self, v, load=False): """ Setter method for l2_spf_timer, mapped from YANG variable /isis_state/router_isis_config/l2_spf_timer (container) If this variable is read-only (config: false) in the source YANG file, then _set_l2_spf_timer is considered as a private method. Backends ...
[ "def", "_set_l2_spf_timer", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "b...
Setter method for l2_spf_timer, mapped from YANG variable /isis_state/router_isis_config/l2_spf_timer (container) If this variable is read-only (config: false) in the source YANG file, then _set_l2_spf_timer is considered as a private method. Backends looking to populate this variable should do so via c...
[ "Setter", "method", "for", "l2_spf_timer", "mapped", "from", "YANG", "variable", "/", "isis_state", "/", "router_isis_config", "/", "l2_spf_timer", "(", "container", ")", "If", "this", "variable", "is", "read", "-", "only", "(", "config", ":", "false", ")", ...
python
train
nvbn/thefuck
thefuck/corrector.py
https://github.com/nvbn/thefuck/blob/40ab4eb62db57627bff10cf029d29c94704086a2/thefuck/corrector.py#L8-L19
def get_loaded_rules(rules_paths): """Yields all available rules. :type rules_paths: [Path] :rtype: Iterable[Rule] """ for path in rules_paths: if path.name != '__init__.py': rule = Rule.from_path(path) if rule.is_enabled: yield rule
[ "def", "get_loaded_rules", "(", "rules_paths", ")", ":", "for", "path", "in", "rules_paths", ":", "if", "path", ".", "name", "!=", "'__init__.py'", ":", "rule", "=", "Rule", ".", "from_path", "(", "path", ")", "if", "rule", ".", "is_enabled", ":", "yield...
Yields all available rules. :type rules_paths: [Path] :rtype: Iterable[Rule]
[ "Yields", "all", "available", "rules", "." ]
python
train
has2k1/plotnine
plotnine/__init__.py
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/__init__.py#L22-L40
def _get_all_imports(): """ Return list of all the imports This prevents sub-modules (geoms, stats, utils, ...) from being imported into the user namespace by the following import statement from plotnine import * This is because `from Module import Something` leads to `Module` its...
[ "def", "_get_all_imports", "(", ")", ":", "import", "types", "lst", "=", "[", "name", "for", "name", ",", "obj", "in", "globals", "(", ")", ".", "items", "(", ")", "if", "not", "(", "name", ".", "startswith", "(", "'_'", ")", "or", "name", "==", ...
Return list of all the imports This prevents sub-modules (geoms, stats, utils, ...) from being imported into the user namespace by the following import statement from plotnine import * This is because `from Module import Something` leads to `Module` itself coming into the namespace!!
[ "Return", "list", "of", "all", "the", "imports" ]
python
train
pymupdf/PyMuPDF
fitz/utils.py
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/utils.py#L140-L288
def insertImage(page, rect, filename=None, pixmap=None, stream=None, rotate=0, keep_proportion = True, overlay=True): """Insert an image in a rectangle on the current page. Notes: Exactly one of filename, pixmap or stream must be provided. Args: rect: (rect-l...
[ "def", "insertImage", "(", "page", ",", "rect", ",", "filename", "=", "None", ",", "pixmap", "=", "None", ",", "stream", "=", "None", ",", "rotate", "=", "0", ",", "keep_proportion", "=", "True", ",", "overlay", "=", "True", ")", ":", "def", "calc_ma...
Insert an image in a rectangle on the current page. Notes: Exactly one of filename, pixmap or stream must be provided. Args: rect: (rect-like) where to place the source image filename: (str) name of an image file pixmap: (obj) a Pixmap object stream: (bytes) an image in ...
[ "Insert", "an", "image", "in", "a", "rectangle", "on", "the", "current", "page", "." ]
python
train
onicagroup/runway
runway/hooks/staticsite/build_staticsite.py
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/hooks/staticsite/build_staticsite.py#L37-L54
def download_and_extract_to_mkdtemp(bucket, key, session=None): """Download zip archive and extract it to temporary directory.""" if session: s3_client = session.client('s3') else: s3_client = boto3.client('s3') transfer = S3Transfer(s3_client) filedes, temp_file = tempfile.mkstemp(...
[ "def", "download_and_extract_to_mkdtemp", "(", "bucket", ",", "key", ",", "session", "=", "None", ")", ":", "if", "session", ":", "s3_client", "=", "session", ".", "client", "(", "'s3'", ")", "else", ":", "s3_client", "=", "boto3", ".", "client", "(", "'...
Download zip archive and extract it to temporary directory.
[ "Download", "zip", "archive", "and", "extract", "it", "to", "temporary", "directory", "." ]
python
train
Phylliade/ikpy
contrib/transformations.py
https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/contrib/transformations.py#L71-L78
def list_to_quat(quatlist): """ Convert a quaternion in the form of a list in geometry_msgs/Quaternion :param quatlist: [x, y, z, w] :return: """ return geometry_msgs.msg.Quaternion( x=quatlist[0], y=quatlist[1], z=quatlist[2], w=quatlist[3])
[ "def", "list_to_quat", "(", "quatlist", ")", ":", "return", "geometry_msgs", ".", "msg", ".", "Quaternion", "(", "x", "=", "quatlist", "[", "0", "]", ",", "y", "=", "quatlist", "[", "1", "]", ",", "z", "=", "quatlist", "[", "2", "]", ",", "w", "=...
Convert a quaternion in the form of a list in geometry_msgs/Quaternion :param quatlist: [x, y, z, w] :return:
[ "Convert", "a", "quaternion", "in", "the", "form", "of", "a", "list", "in", "geometry_msgs", "/", "Quaternion", ":", "param", "quatlist", ":", "[", "x", "y", "z", "w", "]", ":", "return", ":" ]
python
train
mitsei/dlkit
dlkit/json_/resource/sessions.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/resource/sessions.py#L2970-L2989
def is_ancestor_of_bin(self, id_, bin_id): """Tests if an ``Id`` is an ancestor of a bin. arg: id (osid.id.Id): an ``Id`` arg: bin_id (osid.id.Id): the ``Id`` of a bin return: (boolean) - ``true`` if this ``id`` is an ancestor of ``bin_id,`` ``false`` otherwise ...
[ "def", "is_ancestor_of_bin", "(", "self", ",", "id_", ",", "bin_id", ")", ":", "# Implemented from template for", "# osid.resource.BinHierarchySession.is_ancestor_of_bin", "if", "self", ".", "_catalog_session", "is", "not", "None", ":", "return", "self", ".", "_catalog_...
Tests if an ``Id`` is an ancestor of a bin. arg: id (osid.id.Id): an ``Id`` arg: bin_id (osid.id.Id): the ``Id`` of a bin return: (boolean) - ``true`` if this ``id`` is an ancestor of ``bin_id,`` ``false`` otherwise raise: NotFound - ``bin_id`` is not found ...
[ "Tests", "if", "an", "Id", "is", "an", "ancestor", "of", "a", "bin", "." ]
python
train
wind-python/windpowerlib
windpowerlib/wind_speed.py
https://github.com/wind-python/windpowerlib/blob/421b316139743311b7cb68a69f6b53d2665f7e23/windpowerlib/wind_speed.py#L92-L171
def hellman(wind_speed, wind_speed_height, hub_height, roughness_length=None, hellman_exponent=None): r""" Calculates the wind speed at hub height using the hellman equation. It is assumed that the wind profile follows a power law. This function is carried out when the parameter `wind_speed...
[ "def", "hellman", "(", "wind_speed", ",", "wind_speed_height", ",", "hub_height", ",", "roughness_length", "=", "None", ",", "hellman_exponent", "=", "None", ")", ":", "if", "hellman_exponent", "is", "None", ":", "if", "roughness_length", "is", "not", "None", ...
r""" Calculates the wind speed at hub height using the hellman equation. It is assumed that the wind profile follows a power law. This function is carried out when the parameter `wind_speed_model` of an instance of the :class:`~.modelchain.ModelChain` class is 'hellman'. Parameters ---------- ...
[ "r", "Calculates", "the", "wind", "speed", "at", "hub", "height", "using", "the", "hellman", "equation", "." ]
python
train
BeyondTheClouds/enoslib
docs/tutorials/grid5000/virt/tuto_grid5000_virt.py
https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/docs/tutorials/grid5000/virt/tuto_grid5000_virt.py#L16-L23
def range_mac(mac_start, mac_end, step=1): """Iterate over mac addresses (given as string).""" start = int(EUI(mac_start)) end = int(EUI(mac_end)) for i_mac in range(start, end, step): mac = EUI(int(EUI(i_mac)) + 1) ip = ['10'] + [str(int(i, 2)) for i in mac.bits().split('-')[-3:]] ...
[ "def", "range_mac", "(", "mac_start", ",", "mac_end", ",", "step", "=", "1", ")", ":", "start", "=", "int", "(", "EUI", "(", "mac_start", ")", ")", "end", "=", "int", "(", "EUI", "(", "mac_end", ")", ")", "for", "i_mac", "in", "range", "(", "star...
Iterate over mac addresses (given as string).
[ "Iterate", "over", "mac", "addresses", "(", "given", "as", "string", ")", "." ]
python
train
waqasbhatti/astrobase
astrobase/periodbase/kbls.py
https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/periodbase/kbls.py#L626-L1049
def bls_parallel_pfind( times, mags, errs, magsarefluxes=False, startp=0.1, # by default, search from 0.1 d to... endp=100.0, # ... 100.0 d -- don't search full timebase stepsize=1.0e-4, mintransitduration=0.01, # minimum transit length in phase maxtransitdurat...
[ "def", "bls_parallel_pfind", "(", "times", ",", "mags", ",", "errs", ",", "magsarefluxes", "=", "False", ",", "startp", "=", "0.1", ",", "# by default, search from 0.1 d to...", "endp", "=", "100.0", ",", "# ... 100.0 d -- don't search full timebase", "stepsize", "=",...
Runs the Box Least Squares Fitting Search for transit-shaped signals. Based on eebls.f from Kovacs et al. 2002 and python-bls from Foreman-Mackey et al. 2015. Breaks up the full frequency space into chunks and passes them to parallel BLS workers. NOTE: the combined BLS spectrum produced by this functi...
[ "Runs", "the", "Box", "Least", "Squares", "Fitting", "Search", "for", "transit", "-", "shaped", "signals", "." ]
python
valid
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L2620-L2641
def is_address_reserved(self, address): """ Determines if an address belongs to a reserved page. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address...
[ "def", "is_address_reserved", "(", "self", ",", "address", ")", ":", "try", ":", "mbi", "=", "self", ".", "mquery", "(", "address", ")", "except", "WindowsError", ":", "e", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "if", "e", ".", "wine...
Determines if an address belongs to a reserved page. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a reserved page. @raise WindowsError: A...
[ "Determines", "if", "an", "address", "belongs", "to", "a", "reserved", "page", "." ]
python
train
google/grr
grr/server/grr_response_server/databases/mysql_paths.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mysql_paths.py#L193-L199
def MultiWritePathInfos(self, path_infos): """Writes a collection of path info records for specified clients.""" try: self._MultiWritePathInfos(path_infos) except MySQLdb.IntegrityError as error: client_ids = list(iterkeys(path_infos)) raise db.AtLeastOneUnknownClientError(client_ids=clien...
[ "def", "MultiWritePathInfos", "(", "self", ",", "path_infos", ")", ":", "try", ":", "self", ".", "_MultiWritePathInfos", "(", "path_infos", ")", "except", "MySQLdb", ".", "IntegrityError", "as", "error", ":", "client_ids", "=", "list", "(", "iterkeys", "(", ...
Writes a collection of path info records for specified clients.
[ "Writes", "a", "collection", "of", "path", "info", "records", "for", "specified", "clients", "." ]
python
train
infothrill/python-dyndnsc
dyndnsc/conf.py
https://github.com/infothrill/python-dyndnsc/blob/2196d48aa6098da9835a7611fbdb0b5f0fbf51e4/dyndnsc/conf.py#L76-L126
def collect_config(cfg): """ Construct configuration dictionary from configparser. Resolves presets and returns a dictionary containing: .. code-block:: bash { "client_name": { "detector": ("detector_name", detector_opts), "updater": [ ...
[ "def", "collect_config", "(", "cfg", ")", ":", "collected_configs", "=", "{", "}", "_updater_str", "=", "\"updater\"", "_detector_str", "=", "\"detector\"", "_dash", "=", "\"-\"", "for", "client_name", ",", "client_cfg_dict", "in", "_iraw_client_configs", "(", "cf...
Construct configuration dictionary from configparser. Resolves presets and returns a dictionary containing: .. code-block:: bash { "client_name": { "detector": ("detector_name", detector_opts), "updater": [ ("updater_name", updater_opts)...
[ "Construct", "configuration", "dictionary", "from", "configparser", "." ]
python
train
quantopian/alphalens
alphalens/utils.py
https://github.com/quantopian/alphalens/blob/d43eac871bb061e956df936794d3dd514da99e44/alphalens/utils.py#L856-L862
def get_forward_returns_columns(columns): """ Utility that detects and returns the columns that are forward returns """ pattern = re.compile(r"^(\d+([Dhms]|ms|us|ns))+$", re.IGNORECASE) valid_columns = [(pattern.match(col) is not None) for col in columns] return columns[valid_columns]
[ "def", "get_forward_returns_columns", "(", "columns", ")", ":", "pattern", "=", "re", ".", "compile", "(", "r\"^(\\d+([Dhms]|ms|us|ns))+$\"", ",", "re", ".", "IGNORECASE", ")", "valid_columns", "=", "[", "(", "pattern", ".", "match", "(", "col", ")", "is", "...
Utility that detects and returns the columns that are forward returns
[ "Utility", "that", "detects", "and", "returns", "the", "columns", "that", "are", "forward", "returns" ]
python
train
econ-ark/HARK
HARK/utilities.py
https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/utilities.py#L1106-L1147
def kernelRegression(x,y,bot=None,top=None,N=500,h=None): ''' Performs a non-parametric Nadaraya-Watson 1D kernel regression on given data with optionally specified range, number of points, and kernel bandwidth. Parameters ---------- x : np.array The independent variable in the kernel r...
[ "def", "kernelRegression", "(", "x", ",", "y", ",", "bot", "=", "None", ",", "top", "=", "None", ",", "N", "=", "500", ",", "h", "=", "None", ")", ":", "# Fix omitted inputs", "if", "bot", "is", "None", ":", "bot", "=", "np", ".", "min", "(", "...
Performs a non-parametric Nadaraya-Watson 1D kernel regression on given data with optionally specified range, number of points, and kernel bandwidth. Parameters ---------- x : np.array The independent variable in the kernel regression. y : np.array The dependent variable in the kern...
[ "Performs", "a", "non", "-", "parametric", "Nadaraya", "-", "Watson", "1D", "kernel", "regression", "on", "given", "data", "with", "optionally", "specified", "range", "number", "of", "points", "and", "kernel", "bandwidth", "." ]
python
train
mitsei/dlkit
dlkit/json_/authorization/objects.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/authorization/objects.py#L104-L122
def get_resource(self): """Gets the ``Resource`` for this authorization. return: (osid.resource.Resource) - the ``Resource`` raise: IllegalState - ``has_resource()`` is ``false`` raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be ...
[ "def", "get_resource", "(", "self", ")", ":", "# Implemented from template for osid.resource.Resource.get_avatar_template", "if", "not", "bool", "(", "self", ".", "_my_map", "[", "'resourceId'", "]", ")", ":", "raise", "errors", ".", "IllegalState", "(", "'this Author...
Gets the ``Resource`` for this authorization. return: (osid.resource.Resource) - the ``Resource`` raise: IllegalState - ``has_resource()`` is ``false`` raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.*
[ "Gets", "the", "Resource", "for", "this", "authorization", "." ]
python
train
biolink/ontobio
ontobio/ontol.py
https://github.com/biolink/ontobio/blob/4e512a7831cfe6bc1b32f2c3be2ba41bc5cf7345/ontobio/ontol.py#L491-L526
def descendants(self, node, relations=None, reflexive=False): """ Returns all descendants of specified node. The default implementation is to use networkx, but some implementations of the Ontology class may use a database or service backed implementation, for large graphs. ...
[ "def", "descendants", "(", "self", ",", "node", ",", "relations", "=", "None", ",", "reflexive", "=", "False", ")", ":", "if", "reflexive", ":", "decs", "=", "self", ".", "descendants", "(", "node", ",", "relations", ",", "reflexive", "=", "False", ")"...
Returns all descendants of specified node. The default implementation is to use networkx, but some implementations of the Ontology class may use a database or service backed implementation, for large graphs. Arguments --------- node : str identifier for nod...
[ "Returns", "all", "descendants", "of", "specified", "node", "." ]
python
train
Azure/azure-storage-python
azure-storage-file/azure/storage/file/fileservice.py
https://github.com/Azure/azure-storage-python/blob/52327354b192cbcf6b7905118ec6b5d57fa46275/azure-storage-file/azure/storage/file/fileservice.py#L1555-L1597
def create_file(self, share_name, directory_name, file_name, content_length, content_settings=None, metadata=None, timeout=None): ''' Creates a new file. See create_file_from_* for high level functions that handle the creation and upload of large ...
[ "def", "create_file", "(", "self", ",", "share_name", ",", "directory_name", ",", "file_name", ",", "content_length", ",", "content_settings", "=", "None", ",", "metadata", "=", "None", ",", "timeout", "=", "None", ")", ":", "_validate_not_none", "(", "'share_...
Creates a new file. See create_file_from_* for high level functions that handle the creation and upload of large files with automatic chunking and progress notifications. :param str share_name: Name of existing share. :param str directory_name: The path ...
[ "Creates", "a", "new", "file", "." ]
python
train
fastai/fastai
fastai/vision/gan.py
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/gan.py#L226-L228
def wgan(cls, data:DataBunch, generator:nn.Module, critic:nn.Module, switcher:Callback=None, clip:float=0.01, **learn_kwargs): "Create a WGAN from `data`, `generator` and `critic`." return cls(data, generator, critic, NoopLoss(), WassersteinLoss(), switcher=switcher, clip=clip, **learn_kwargs)
[ "def", "wgan", "(", "cls", ",", "data", ":", "DataBunch", ",", "generator", ":", "nn", ".", "Module", ",", "critic", ":", "nn", ".", "Module", ",", "switcher", ":", "Callback", "=", "None", ",", "clip", ":", "float", "=", "0.01", ",", "*", "*", "...
Create a WGAN from `data`, `generator` and `critic`.
[ "Create", "a", "WGAN", "from", "data", "generator", "and", "critic", "." ]
python
train
openeemeter/eemeter
eemeter/caltrack/usage_per_day.py
https://github.com/openeemeter/eemeter/blob/e03b1cc5f4906e8f4f7fd16183bc037107d1dfa0/eemeter/caltrack/usage_per_day.py#L1018-L1136
def get_single_cdd_only_candidate_model( data, minimum_non_zero_cdd, minimum_total_cdd, beta_cdd_maximum_p_value, weights_col, balance_point, ): """ Return a single candidate cdd-only model for a particular balance point. Parameters ---------- data : :any:`pandas.DataFrame` ...
[ "def", "get_single_cdd_only_candidate_model", "(", "data", ",", "minimum_non_zero_cdd", ",", "minimum_total_cdd", ",", "beta_cdd_maximum_p_value", ",", "weights_col", ",", "balance_point", ",", ")", ":", "model_type", "=", "\"cdd_only\"", "cdd_column", "=", "\"cdd_%s\"", ...
Return a single candidate cdd-only model for a particular balance point. Parameters ---------- data : :any:`pandas.DataFrame` A DataFrame containing at least the column ``meter_value`` and ``cdd_<balance_point>`` DataFrames of this form can be made using the :any:`eemete...
[ "Return", "a", "single", "candidate", "cdd", "-", "only", "model", "for", "a", "particular", "balance", "point", "." ]
python
train
rueckstiess/mtools
mtools/mlaunch/mlaunch.py
https://github.com/rueckstiess/mtools/blob/a6a22910c3569c0c8a3908660ca218a4557e4249/mtools/mlaunch/mlaunch.py#L1433-L1446
def _create_paths(self, basedir, name=None): """Create datadir and subdir paths.""" if name: datapath = os.path.join(basedir, name) else: datapath = basedir dbpath = os.path.join(datapath, 'db') if not os.path.exists(dbpath): os.makedirs(dbpat...
[ "def", "_create_paths", "(", "self", ",", "basedir", ",", "name", "=", "None", ")", ":", "if", "name", ":", "datapath", "=", "os", ".", "path", ".", "join", "(", "basedir", ",", "name", ")", "else", ":", "datapath", "=", "basedir", "dbpath", "=", "...
Create datadir and subdir paths.
[ "Create", "datadir", "and", "subdir", "paths", "." ]
python
train
AkihikoITOH/capybara
capybara/virtualenv/lib/python2.7/site.py
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site.py#L133-L141
def addbuilddir(): """Append ./build/lib.<platform> in case we're running in the build dir (especially for Guido :-)""" from distutils.util import get_platform s = "build/lib.%s-%.3s" % (get_platform(), sys.version) if hasattr(sys, 'gettotalrefcount'): s += '-pydebug' s = os.path.join(os...
[ "def", "addbuilddir", "(", ")", ":", "from", "distutils", ".", "util", "import", "get_platform", "s", "=", "\"build/lib.%s-%.3s\"", "%", "(", "get_platform", "(", ")", ",", "sys", ".", "version", ")", "if", "hasattr", "(", "sys", ",", "'gettotalrefcount'", ...
Append ./build/lib.<platform> in case we're running in the build dir (especially for Guido :-)
[ "Append", ".", "/", "build", "/", "lib", ".", "<platform", ">", "in", "case", "we", "re", "running", "in", "the", "build", "dir", "(", "especially", "for", "Guido", ":", "-", ")" ]
python
test
proycon/pynlpl
pynlpl/formats/folia.py
https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L4601-L4611
def findspan(self, *words): """Returns the span element which spans over the specified words or morphemes. See also: :meth:`Word.findspans` """ for span in self.select(AbstractSpanAnnotation,None,True): if tuple(span.wrefs()) == words: return spa...
[ "def", "findspan", "(", "self", ",", "*", "words", ")", ":", "for", "span", "in", "self", ".", "select", "(", "AbstractSpanAnnotation", ",", "None", ",", "True", ")", ":", "if", "tuple", "(", "span", ".", "wrefs", "(", ")", ")", "==", "words", ":",...
Returns the span element which spans over the specified words or morphemes. See also: :meth:`Word.findspans`
[ "Returns", "the", "span", "element", "which", "spans", "over", "the", "specified", "words", "or", "morphemes", "." ]
python
train
ansible/ansible-runner
ansible_runner/runner_config.py
https://github.com/ansible/ansible-runner/blob/8ce485480a5d0b602428d9d64a752e06fb46cdb8/ansible_runner/runner_config.py#L278-L288
def prepare_command(self): """ Determines if the literal ``ansible`` or ``ansible-playbook`` commands are given and if not calls :py:meth:`ansible_runner.runner_config.RunnerConfig.generate_ansible_command` """ try: cmdline_args = self.loader.load_file('args', string_...
[ "def", "prepare_command", "(", "self", ")", ":", "try", ":", "cmdline_args", "=", "self", ".", "loader", ".", "load_file", "(", "'args'", ",", "string_types", ")", "self", ".", "command", "=", "shlex", ".", "split", "(", "cmdline_args", ".", "decode", "(...
Determines if the literal ``ansible`` or ``ansible-playbook`` commands are given and if not calls :py:meth:`ansible_runner.runner_config.RunnerConfig.generate_ansible_command`
[ "Determines", "if", "the", "literal", "ansible", "or", "ansible", "-", "playbook", "commands", "are", "given", "and", "if", "not", "calls", ":", "py", ":", "meth", ":", "ansible_runner", ".", "runner_config", ".", "RunnerConfig", ".", "generate_ansible_command" ...
python
train
pandas-dev/pandas
pandas/core/dtypes/common.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/dtypes/common.py#L1666-L1722
def is_extension_type(arr): """ Check whether an array-like is of a pandas extension class instance. Extension classes include categoricals, pandas sparse objects (i.e. classes represented within the pandas library and not ones external to it like scipy sparse matrices), and datetime-like arrays. ...
[ "def", "is_extension_type", "(", "arr", ")", ":", "if", "is_categorical", "(", "arr", ")", ":", "return", "True", "elif", "is_sparse", "(", "arr", ")", ":", "return", "True", "elif", "is_datetime64tz_dtype", "(", "arr", ")", ":", "return", "True", "return"...
Check whether an array-like is of a pandas extension class instance. Extension classes include categoricals, pandas sparse objects (i.e. classes represented within the pandas library and not ones external to it like scipy sparse matrices), and datetime-like arrays. Parameters ---------- arr : ...
[ "Check", "whether", "an", "array", "-", "like", "is", "of", "a", "pandas", "extension", "class", "instance", "." ]
python
train
annoviko/pyclustering
pyclustering/container/kdtree.py
https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/container/kdtree.py#L547-L560
def children(self, node_parent): """! @brief Returns list of children of node. @param[in] node_parent (node): Node whose children are required. @return (list) Children of node. If node haven't got any child then None is returned. """ ...
[ "def", "children", "(", "self", ",", "node_parent", ")", ":", "if", "node_parent", ".", "left", "is", "not", "None", ":", "yield", "node_parent", ".", "left", "if", "node_parent", ".", "right", "is", "not", "None", ":", "yield", "node_parent", ".", "righ...
! @brief Returns list of children of node. @param[in] node_parent (node): Node whose children are required. @return (list) Children of node. If node haven't got any child then None is returned.
[ "!" ]
python
valid
ilevkivskyi/typing_inspect
typing_inspect.py
https://github.com/ilevkivskyi/typing_inspect/blob/fd81278cc440b6003f8298bcb22d5bc0f82ee3cd/typing_inspect.py#L93-L116
def is_tuple_type(tp): """Test if the type is a generic tuple type, including subclasses excluding non-generic classes. Examples:: is_tuple_type(int) == False is_tuple_type(tuple) == False is_tuple_type(Tuple) == True is_tuple_type(Tuple[str, int]) == True class MyCl...
[ "def", "is_tuple_type", "(", "tp", ")", ":", "if", "NEW_TYPING", ":", "return", "(", "tp", "is", "Tuple", "or", "isinstance", "(", "tp", ",", "_GenericAlias", ")", "and", "tp", ".", "__origin__", "is", "tuple", "or", "isinstance", "(", "tp", ",", "type...
Test if the type is a generic tuple type, including subclasses excluding non-generic classes. Examples:: is_tuple_type(int) == False is_tuple_type(tuple) == False is_tuple_type(Tuple) == True is_tuple_type(Tuple[str, int]) == True class MyClass(Tuple[str, int]): ...
[ "Test", "if", "the", "type", "is", "a", "generic", "tuple", "type", "including", "subclasses", "excluding", "non", "-", "generic", "classes", ".", "Examples", "::" ]
python
train
scot-dev/scot
scot/varbase.py
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/varbase.py#L114-L156
def from_yw(self, acms): """Determine VAR model from autocorrelation matrices by solving the Yule-Walker equations. Parameters ---------- acms : array, shape (n_lags, n_channels, n_channels) acms[l] contains the autocorrelation matrix at lag l. The highest ...
[ "def", "from_yw", "(", "self", ",", "acms", ")", ":", "if", "len", "(", "acms", ")", "!=", "self", ".", "p", "+", "1", ":", "raise", "ValueError", "(", "\"Number of autocorrelation matrices ({}) does not\"", "\" match model order ({}) + 1.\"", ".", "format", "("...
Determine VAR model from autocorrelation matrices by solving the Yule-Walker equations. Parameters ---------- acms : array, shape (n_lags, n_channels, n_channels) acms[l] contains the autocorrelation matrix at lag l. The highest lag must equal the model order. ...
[ "Determine", "VAR", "model", "from", "autocorrelation", "matrices", "by", "solving", "the", "Yule", "-", "Walker", "equations", "." ]
python
train
awslabs/aws-sam-cli
samcli/cli/options.py
https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/cli/options.py#L11-L27
def debug_option(f): """ Configures --debug option for CLI :param f: Callback Function to be passed to Click """ def callback(ctx, param, value): state = ctx.ensure_object(Context) state.debug = value return value return click.option('--debug', e...
[ "def", "debug_option", "(", "f", ")", ":", "def", "callback", "(", "ctx", ",", "param", ",", "value", ")", ":", "state", "=", "ctx", ".", "ensure_object", "(", "Context", ")", "state", ".", "debug", "=", "value", "return", "value", "return", "click", ...
Configures --debug option for CLI :param f: Callback Function to be passed to Click
[ "Configures", "--", "debug", "option", "for", "CLI" ]
python
train
nagius/snmp_passpersist
snmp_passpersist.py
https://github.com/nagius/snmp_passpersist/blob/8cc584d2e90c920ae98a318164a55bde209a18f7/snmp_passpersist.py#L231-L234
def add_cnt_64bit(self,oid,value,label=None): """Short helper to add a 64 bit counter value to the MIB subtree.""" # Truncate integer to 64bits ma,x self.add_oid_entry(oid,'Counter64',int(value)%18446744073709551615,label=label)
[ "def", "add_cnt_64bit", "(", "self", ",", "oid", ",", "value", ",", "label", "=", "None", ")", ":", "# Truncate integer to 64bits ma,x", "self", ".", "add_oid_entry", "(", "oid", ",", "'Counter64'", ",", "int", "(", "value", ")", "%", "18446744073709551615", ...
Short helper to add a 64 bit counter value to the MIB subtree.
[ "Short", "helper", "to", "add", "a", "64", "bit", "counter", "value", "to", "the", "MIB", "subtree", "." ]
python
train
Shinichi-Nakagawa/pitchpx
pitchpx/game/inning.py
https://github.com/Shinichi-Nakagawa/pitchpx/blob/5747402a0b3416f5e910b479e100df858f0b6440/pitchpx/game/inning.py#L351-L365
def result(cls, ab, pa, pitch_list): """ At Bat Result :param ab: at bat object(type:Beautifulsoup) :param pa: atbat data for plate appearance :param pitch_list: Pitching data :return: pa result value(dict) """ atbat = OrderedDict() atbat['ball_ct'...
[ "def", "result", "(", "cls", ",", "ab", ",", "pa", ",", "pitch_list", ")", ":", "atbat", "=", "OrderedDict", "(", ")", "atbat", "[", "'ball_ct'", "]", "=", "MlbamUtil", ".", "get_attribute_stats", "(", "ab", ",", "'b'", ",", "int", ",", "None", ")", ...
At Bat Result :param ab: at bat object(type:Beautifulsoup) :param pa: atbat data for plate appearance :param pitch_list: Pitching data :return: pa result value(dict)
[ "At", "Bat", "Result", ":", "param", "ab", ":", "at", "bat", "object", "(", "type", ":", "Beautifulsoup", ")", ":", "param", "pa", ":", "atbat", "data", "for", "plate", "appearance", ":", "param", "pitch_list", ":", "Pitching", "data", ":", "return", "...
python
train
O365/python-o365
O365/mailbox.py
https://github.com/O365/python-o365/blob/02a71cf3775cc6a3c042e003365d6a07c8c75a73/O365/mailbox.py#L405-L432
def copy_folder(self, to_folder): """ Copy this folder and it's contents to into another folder :param to_folder: the destination Folder/folder_id to copy into :type to_folder: mailbox.Folder or str :return: The new folder after copying :rtype: mailbox.Folder or None """...
[ "def", "copy_folder", "(", "self", ",", "to_folder", ")", ":", "to_folder_id", "=", "to_folder", ".", "folder_id", "if", "isinstance", "(", "to_folder", ",", "Folder", ")", "else", "to_folder", "if", "self", ".", "root", "or", "not", "self", ".", "folder_i...
Copy this folder and it's contents to into another folder :param to_folder: the destination Folder/folder_id to copy into :type to_folder: mailbox.Folder or str :return: The new folder after copying :rtype: mailbox.Folder or None
[ "Copy", "this", "folder", "and", "it", "s", "contents", "to", "into", "another", "folder" ]
python
train