repo
stringlengths
7
55
path
stringlengths
4
223
url
stringlengths
87
315
code
stringlengths
75
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
avg_line_len
float64
7.91
980
tensorflow/tensor2tensor
tensor2tensor/models/xception.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/xception.py#L113-L133
def xception_exit(inputs): """Xception exit flow.""" with tf.variable_scope("xception_exit"): x = inputs x_shape = x.get_shape().as_list() if x_shape[1] is None or x_shape[2] is None: length_float = tf.to_float(tf.shape(x)[1]) length_float *= tf.to_float(tf.shape(x)[2]) spatial_dim_flo...
[ "def", "xception_exit", "(", "inputs", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"xception_exit\"", ")", ":", "x", "=", "inputs", "x_shape", "=", "x", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "if", "x_shape", "[", "1", "]", "...
Xception exit flow.
[ "Xception", "exit", "flow", "." ]
python
train
43.952381
mcocdawc/chemcoord
src/chemcoord/cartesian_coordinates/_cartesian_class_symmetry.py
https://github.com/mcocdawc/chemcoord/blob/95561ce387c142227c38fb14a1d182179aef8f5f/src/chemcoord/cartesian_coordinates/_cartesian_class_symmetry.py#L16-L29
def _convert_eq(self, eq): """WORKS INPLACE on eq """ rename = dict(enumerate(self.index)) eq['eq_sets'] = {rename[k]: {rename[x] for x in v} for k, v in eq['eq_sets'].items()} eq['sym_ops'] = {rename[k]: {rename[x]: v[x] for x in v} ...
[ "def", "_convert_eq", "(", "self", ",", "eq", ")", ":", "rename", "=", "dict", "(", "enumerate", "(", "self", ".", "index", ")", ")", "eq", "[", "'eq_sets'", "]", "=", "{", "rename", "[", "k", "]", ":", "{", "rename", "[", "x", "]", "for", "x",...
WORKS INPLACE on eq
[ "WORKS", "INPLACE", "on", "eq" ]
python
train
39.571429
hollenstein/maspy
maspy/core.py
https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/core.py#L1974-L2008
def load(self, specfiles=None): """Imports the specified ``fic`` files from the hard disk. :param specfiles: the name of an ms-run file or a list of names. If None all specfiles are selected. :type specfiles: None, str, [str, str] """ if specfiles is None: ...
[ "def", "load", "(", "self", ",", "specfiles", "=", "None", ")", ":", "if", "specfiles", "is", "None", ":", "specfiles", "=", "[", "_", "for", "_", "in", "viewkeys", "(", "self", ".", "info", ")", "]", "else", ":", "specfiles", "=", "aux", ".", "t...
Imports the specified ``fic`` files from the hard disk. :param specfiles: the name of an ms-run file or a list of names. If None all specfiles are selected. :type specfiles: None, str, [str, str]
[ "Imports", "the", "specified", "fic", "files", "from", "the", "hard", "disk", "." ]
python
train
49.285714
svenevs/exhale
exhale/utils.py
https://github.com/svenevs/exhale/blob/fe7644829057af622e467bb529db6c03a830da99/exhale/utils.py#L668-L676
def printAllColorsToConsole(cls): ''' A simple enumeration of the colors to the console to help decide :) ''' for elem in cls.__dict__: # ignore specials such as __class__ or __module__ if not elem.startswith("__"): color_fmt = cls.__dict__[elem] i...
[ "def", "printAllColorsToConsole", "(", "cls", ")", ":", "for", "elem", "in", "cls", ".", "__dict__", ":", "# ignore specials such as __class__ or __module__", "if", "not", "elem", ".", "startswith", "(", "\"__\"", ")", ":", "color_fmt", "=", "cls", ".", "__dict_...
A simple enumeration of the colors to the console to help decide :)
[ "A", "simple", "enumeration", "of", "the", "colors", "to", "the", "console", "to", "help", "decide", ":", ")" ]
python
train
63.555556
senaite/senaite.core
bika/lims/browser/auditlog.py
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/auditlog.py#L110-L116
def get_widget_for(self, fieldname): """Lookup the widget """ field = self.context.getField(fieldname) if not field: return None return field.widget
[ "def", "get_widget_for", "(", "self", ",", "fieldname", ")", ":", "field", "=", "self", ".", "context", ".", "getField", "(", "fieldname", ")", "if", "not", "field", ":", "return", "None", "return", "field", ".", "widget" ]
Lookup the widget
[ "Lookup", "the", "widget" ]
python
train
27.714286
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/generator/mavgen.py
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/generator/mavgen.py#L29-L154
def mavgen(opts, args): """Generate mavlink message formatters and parsers (C and Python ) using options and args where args are a list of xml files. This function allows python scripts under Windows to control mavgen using the same interface as shell scripts under Unix""" xml = [] # Enable va...
[ "def", "mavgen", "(", "opts", ",", "args", ")", ":", "xml", "=", "[", "]", "# Enable validation by default, disabling it if explicitly requested", "if", "opts", ".", "validate", ":", "try", ":", "from", "lxml", "import", "etree", "with", "open", "(", "schemaFile...
Generate mavlink message formatters and parsers (C and Python ) using options and args where args are a list of xml files. This function allows python scripts under Windows to control mavgen using the same interface as shell scripts under Unix
[ "Generate", "mavlink", "message", "formatters", "and", "parsers", "(", "C", "and", "Python", ")", "using", "options", "and", "args", "where", "args", "are", "a", "list", "of", "xml", "files", ".", "This", "function", "allows", "python", "scripts", "under", ...
python
train
42.373016
galaxy-genome-annotation/python-apollo
apollo/annotations/__init__.py
https://github.com/galaxy-genome-annotation/python-apollo/blob/2bc9991302abe4402ec2885dcaac35915475b387/apollo/annotations/__init__.py#L469-L484
def get_features(self, organism=None, sequence=None): """ Get the features for an organism / sequence :type organism: str :param organism: Organism Common Name :type sequence: str :param sequence: Sequence Name :rtype: dict :return: A standard apollo fe...
[ "def", "get_features", "(", "self", ",", "organism", "=", "None", ",", "sequence", "=", "None", ")", ":", "data", "=", "{", "}", "data", "=", "self", ".", "_update_data", "(", "data", ",", "organism", ",", "sequence", ")", "return", "self", ".", "pos...
Get the features for an organism / sequence :type organism: str :param organism: Organism Common Name :type sequence: str :param sequence: Sequence Name :rtype: dict :return: A standard apollo feature dictionary ({"features": [{...}]})
[ "Get", "the", "features", "for", "an", "organism", "/", "sequence" ]
python
train
30
fxsjy/jieba
jieba/analyse/textrank.py
https://github.com/fxsjy/jieba/blob/8212b6c5725d08311952a3a08e5509eeaee33eb7/jieba/analyse/textrank.py#L69-L108
def textrank(self, sentence, topK=20, withWeight=False, allowPOS=('ns', 'n', 'vn', 'v'), withFlag=False): """ Extract keywords from sentence using TextRank algorithm. Parameter: - topK: return how many top keywords. `None` for all possible words. - withWeight: if True, re...
[ "def", "textrank", "(", "self", ",", "sentence", ",", "topK", "=", "20", ",", "withWeight", "=", "False", ",", "allowPOS", "=", "(", "'ns'", ",", "'n'", ",", "'vn'", ",", "'v'", ")", ",", "withFlag", "=", "False", ")", ":", "self", ".", "pos_filt",...
Extract keywords from sentence using TextRank algorithm. Parameter: - topK: return how many top keywords. `None` for all possible words. - withWeight: if True, return a list of (word, weight); if False, return a list of words. - allowPOS: the allowed...
[ "Extract", "keywords", "from", "sentence", "using", "TextRank", "algorithm", ".", "Parameter", ":", "-", "topK", ":", "return", "how", "many", "top", "keywords", ".", "None", "for", "all", "possible", "words", ".", "-", "withWeight", ":", "if", "True", "re...
python
train
42.55
geographika/mappyfile
mappyfile/transformer.py
https://github.com/geographika/mappyfile/blob/aecbc5e66ec06896bc4c5db41313503468829d00/mappyfile/transformer.py#L318-L347
def process_value_pairs(self, tokens, type_): """ Metadata, Values, and Validation blocks can either have string pairs or attributes Attributes will already be processed """ key, body = self.check_composite_tokens(type_, tokens) key_name = self.key_name(key) ...
[ "def", "process_value_pairs", "(", "self", ",", "tokens", ",", "type_", ")", ":", "key", ",", "body", "=", "self", ".", "check_composite_tokens", "(", "type_", ",", "tokens", ")", "key_name", "=", "self", ".", "key_name", "(", "key", ")", "d", "=", "Ca...
Metadata, Values, and Validation blocks can either have string pairs or attributes Attributes will already be processed
[ "Metadata", "Values", "and", "Validation", "blocks", "can", "either", "have", "string", "pairs", "or", "attributes", "Attributes", "will", "already", "be", "processed" ]
python
train
32.566667
tensorflow/tensor2tensor
tensor2tensor/utils/t2t_model.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L443-L516
def bottom(self, features): """Transforms features to feed into body. Args: features: dict of str to Tensor. Typically it is the preprocessed data batch after Problem's preprocess_example(). Returns: transformed_features: dict of same key-value pairs as features. The value Tens...
[ "def", "bottom", "(", "self", ",", "features", ")", ":", "if", "not", "self", ".", "_problem_hparams", ":", "log_warn", "(", "\"Without a Problem, T2TModel.bottom is a passthrough.\"", ")", "return", "features", "transformed_features", "=", "collections", ".", "Ordere...
Transforms features to feed into body. Args: features: dict of str to Tensor. Typically it is the preprocessed data batch after Problem's preprocess_example(). Returns: transformed_features: dict of same key-value pairs as features. The value Tensors are newly transformed.
[ "Transforms", "features", "to", "feed", "into", "body", "." ]
python
train
45.527027
plaid/plaid-python
plaid/client.py
https://github.com/plaid/plaid-python/blob/c549c3108790266a3b344c47e0c83fff59146eeb/plaid/client.py#L89-L91
def post_public(self, path, data, is_json=True): '''Make a post request requiring no auth.''' return self._post(path, data, is_json)
[ "def", "post_public", "(", "self", ",", "path", ",", "data", ",", "is_json", "=", "True", ")", ":", "return", "self", ".", "_post", "(", "path", ",", "data", ",", "is_json", ")" ]
Make a post request requiring no auth.
[ "Make", "a", "post", "request", "requiring", "no", "auth", "." ]
python
train
48.666667
sveetch/py-css-styleguide
py_css_styleguide/serializer.py
https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/serializer.py#L412-L434
def get_available_references(self, datas): """ Get available manifest reference names. Every rules starting with prefix from ``nomenclature.RULE_REFERENCE`` are available references. Only name validation is performed on these references. Arguments: datas (d...
[ "def", "get_available_references", "(", "self", ",", "datas", ")", ":", "names", "=", "[", "]", "for", "k", ",", "v", "in", "datas", ".", "items", "(", ")", ":", "if", "k", ".", "startswith", "(", "RULE_REFERENCE", ")", ":", "names", ".", "append", ...
Get available manifest reference names. Every rules starting with prefix from ``nomenclature.RULE_REFERENCE`` are available references. Only name validation is performed on these references. Arguments: datas (dict): Data where to search for reference declarations. ...
[ "Get", "available", "manifest", "reference", "names", "." ]
python
train
29.086957
tensorlayer/tensorlayer
tensorlayer/nlp.py
https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/nlp.py#L1063-L1139
def moses_multi_bleu(hypotheses, references, lowercase=False): """Calculate the bleu score for hypotheses and references using the MOSES ulti-bleu.perl script. Parameters ------------ hypotheses : numpy.array.string A numpy array of strings where each string is a single example. referen...
[ "def", "moses_multi_bleu", "(", "hypotheses", ",", "references", ",", "lowercase", "=", "False", ")", ":", "if", "np", ".", "size", "(", "hypotheses", ")", "==", "0", ":", "return", "np", ".", "float32", "(", "0.0", ")", "# Get MOSES multi-bleu script", "t...
Calculate the bleu score for hypotheses and references using the MOSES ulti-bleu.perl script. Parameters ------------ hypotheses : numpy.array.string A numpy array of strings where each string is a single example. references : numpy.array.string A numpy array of strings where each s...
[ "Calculate", "the", "bleu", "score", "for", "hypotheses", "and", "references", "using", "the", "MOSES", "ulti", "-", "bleu", ".", "perl", "script", "." ]
python
valid
37.077922
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/device_directory/device_directory.py
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/device_directory/device_directory.py#L194-L225
def add_query(self, name, filter, **kwargs): """Add a new query to device query service. .. code-block:: python f = api.add_query( name = "Query name", filter = { "device_id": {"$eq": "01234"}, custom_attributes = { ...
[ "def", "add_query", "(", "self", ",", "name", ",", "filter", ",", "*", "*", "kwargs", ")", ":", "# Ensure we have the correct types and get the new query object", "filter_obj", "=", "filters", ".", "legacy_filter_formatter", "(", "dict", "(", "filter", "=", "filter"...
Add a new query to device query service. .. code-block:: python f = api.add_query( name = "Query name", filter = { "device_id": {"$eq": "01234"}, custom_attributes = { "foo": {"$eq": "bar"} ...
[ "Add", "a", "new", "query", "to", "device", "query", "service", "." ]
python
train
36.8125
wavefrontHQ/python-client
wavefront_api_client/api/dashboard_api.py
https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/api/dashboard_api.py#L805-L827
def get_dashboard_history(self, id, **kwargs): # noqa: E501 """Get the version history of a specific dashboard # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api...
[ "def", "get_dashboard_history", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "get_da...
Get the version history of a specific dashboard # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_dashboard_history(id, async_req=True) >>> result = thread.g...
[ "Get", "the", "version", "history", "of", "a", "specific", "dashboard", "#", "noqa", ":", "E501" ]
python
train
41.652174
saltstack/salt
salt/modules/mac_keychain.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_keychain.py#L236-L265
def get_hash(name, password=None): ''' Returns the hash of a certificate in the keychain. name The name of the certificate (which you can get from keychain.get_friendly_name) or the location of a p12 file. password The password that is used in the certificate. Only required if ...
[ "def", "get_hash", "(", "name", ",", "password", "=", "None", ")", ":", "if", "'.p12'", "in", "name", "[", "-", "4", ":", "]", ":", "cmd", "=", "'openssl pkcs12 -in {0} -passin pass:{1} -passout pass:{1}'", ".", "format", "(", "name", ",", "password", ")", ...
Returns the hash of a certificate in the keychain. name The name of the certificate (which you can get from keychain.get_friendly_name) or the location of a p12 file. password The password that is used in the certificate. Only required if your passing a p12 file. Note: This wil...
[ "Returns", "the", "hash", "of", "a", "certificate", "in", "the", "keychain", "." ]
python
train
30.2
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L296-L308
def contains(self, time: datetime.datetime, inclusive: bool = True) -> bool: """ Does the interval contain a momentary time? Args: time: the ``datetime.datetime`` to check inclusive: use inclusive rather than exclusive range checks? """ i...
[ "def", "contains", "(", "self", ",", "time", ":", "datetime", ".", "datetime", ",", "inclusive", ":", "bool", "=", "True", ")", "->", "bool", ":", "if", "inclusive", ":", "return", "self", ".", "start", "<=", "time", "<=", "self", ".", "end", "else",...
Does the interval contain a momentary time? Args: time: the ``datetime.datetime`` to check inclusive: use inclusive rather than exclusive range checks?
[ "Does", "the", "interval", "contain", "a", "momentary", "time?" ]
python
train
33.230769
asyrjasalo/RESTinstance
src/REST/keywords.py
https://github.com/asyrjasalo/RESTinstance/blob/9b003ffc6a89ec4b8b6f05eeb6cc8e56aad4be4e/src/REST/keywords.py#L63-L78
def set_client_cert(self, cert): """*Sets the client cert for the requests.* The cert is either a path to a .pem file, or a JSON array, or a list having the cert path and the key path. Values ``null`` and ``${None}`` can be used for clearing the cert. *Examples* | `Se...
[ "def", "set_client_cert", "(", "self", ",", "cert", ")", ":", "self", ".", "request", "[", "\"cert\"", "]", "=", "self", ".", "_input_client_cert", "(", "cert", ")", "return", "self", ".", "request", "[", "\"cert\"", "]" ]
*Sets the client cert for the requests.* The cert is either a path to a .pem file, or a JSON array, or a list having the cert path and the key path. Values ``null`` and ``${None}`` can be used for clearing the cert. *Examples* | `Set Client Cert` | ${CURDIR}/client.pem | ...
[ "*", "Sets", "the", "client", "cert", "for", "the", "requests", ".", "*" ]
python
train
36.3125
chaoss/grimoirelab-perceval
perceval/backends/core/bugzillarest.py
https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/bugzillarest.py#L98-L117
def fetch_items(self, category, **kwargs): """Fetch the bugs :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items """ from_date = kwargs['from_date'] logger.info("Looking for bugs: '%s' updated from '%...
[ "def", "fetch_items", "(", "self", ",", "category", ",", "*", "*", "kwargs", ")", ":", "from_date", "=", "kwargs", "[", "'from_date'", "]", "logger", ".", "info", "(", "\"Looking for bugs: '%s' updated from '%s'\"", ",", "self", ".", "url", ",", "str", "(", ...
Fetch the bugs :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items
[ "Fetch", "the", "bugs" ]
python
test
27.3
saltstack/salt
salt/states/service.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/service.py#L226-L320
def _disable(name, started, result=True, skip_verify=False, **kwargs): ''' Disable the service ''' ret = {} if not skip_verify: # is service available? try: if not _available(name, ret): ret['result'] = True return ret except Comma...
[ "def", "_disable", "(", "name", ",", "started", ",", "result", "=", "True", ",", "skip_verify", "=", "False", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "}", "if", "not", "skip_verify", ":", "# is service available?", "try", ":", "if", "not", ...
Disable the service
[ "Disable", "the", "service" ]
python
train
40.663158
ev3dev/ev3dev-lang-python
ev3dev2/motor.py
https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/motor.py#L525-L533
def position(self): """ Returns the current position of the motor in pulses of the rotary encoder. When the motor rotates clockwise, the position will increase. Likewise, rotating counter-clockwise causes the position to decrease. Writing will set the position to that value. ...
[ "def", "position", "(", "self", ")", ":", "self", ".", "_position", ",", "value", "=", "self", ".", "get_attr_int", "(", "self", ".", "_position", ",", "'position'", ")", "return", "value" ]
Returns the current position of the motor in pulses of the rotary encoder. When the motor rotates clockwise, the position will increase. Likewise, rotating counter-clockwise causes the position to decrease. Writing will set the position to that value.
[ "Returns", "the", "current", "position", "of", "the", "motor", "in", "pulses", "of", "the", "rotary", "encoder", ".", "When", "the", "motor", "rotates", "clockwise", "the", "position", "will", "increase", ".", "Likewise", "rotating", "counter", "-", "clockwise...
python
train
46.444444
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgets/filebrowser.py
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/filebrowser.py#L122-L137
def setup_icons(self, ): """Set all icons on buttons :returns: None :rtype: None :raises: None """ folder_icon = get_icon('glyphicons_144_folder_open.png', asicon=True) self.asset_open_path_tb.setIcon(folder_icon) self.shot_open_path_tb.setIcon(folder_ico...
[ "def", "setup_icons", "(", "self", ",", ")", ":", "folder_icon", "=", "get_icon", "(", "'glyphicons_144_folder_open.png'", ",", "asicon", "=", "True", ")", "self", ".", "asset_open_path_tb", ".", "setIcon", "(", "folder_icon", ")", "self", ".", "shot_open_path_t...
Set all icons on buttons :returns: None :rtype: None :raises: None
[ "Set", "all", "icons", "on", "buttons" ]
python
train
33.8125
sibirrer/lenstronomy
lenstronomy/Cosmo/lens_cosmo.py
https://github.com/sibirrer/lenstronomy/blob/4edb100a4f3f4fdc4fac9b0032d2b0283d0aa1d6/lenstronomy/Cosmo/lens_cosmo.py#L74-L84
def epsilon_crit(self): """ returns the critical projected mass density in units of M_sun/Mpc^2 (physical units) :return: critical projected mass density """ if not hasattr(self, '_Epsilon_Crit'): const_SI = const.c ** 2 / (4 * np.pi * const.G) #c^2/(4*pi*G) in units...
[ "def", "epsilon_crit", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_Epsilon_Crit'", ")", ":", "const_SI", "=", "const", ".", "c", "**", "2", "/", "(", "4", "*", "np", ".", "pi", "*", "const", ".", "G", ")", "#c^2/(4*pi*G) in ...
returns the critical projected mass density in units of M_sun/Mpc^2 (physical units) :return: critical projected mass density
[ "returns", "the", "critical", "projected", "mass", "density", "in", "units", "of", "M_sun", "/", "Mpc^2", "(", "physical", "units", ")", ":", "return", ":", "critical", "projected", "mass", "density" ]
python
train
55
testing-cabal/mock
mock/mock.py
https://github.com/testing-cabal/mock/blob/2f356b28d42a1fd0057c9d8763d3a2cac2284165/mock/mock.py#L985-L998
def assert_any_call(self, *args, **kwargs): """assert the mock has been called with the specified arguments. The assert passes if the mock has *ever* been called, unlike `assert_called_with` and `assert_called_once_with` that only pass if the call is the most recent one.""" expe...
[ "def", "assert_any_call", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "expected", "=", "self", ".", "_call_matcher", "(", "(", "args", ",", "kwargs", ")", ")", "actual", "=", "[", "self", ".", "_call_matcher", "(", "c", ")", "...
assert the mock has been called with the specified arguments. The assert passes if the mock has *ever* been called, unlike `assert_called_with` and `assert_called_once_with` that only pass if the call is the most recent one.
[ "assert", "the", "mock", "has", "been", "called", "with", "the", "specified", "arguments", "." ]
python
train
51.642857
nakagami/pyfirebirdsql
firebirdsql/decfloat.py
https://github.com/nakagami/pyfirebirdsql/blob/5ce366c2fc8318510444f4a89801442f3e9e52ca/firebirdsql/decfloat.py#L103-L121
def calc_significand(prefix, dpd_bits, num_bits): """ prefix: High bits integer value dpd_bits: dpd encoded bits num_bits: bit length of dpd_bits """ # https://en.wikipedia.org/wiki/Decimal128_floating-point_format#Densely_packed_decimal_significand_field num_segments = num_bits // 10 se...
[ "def", "calc_significand", "(", "prefix", ",", "dpd_bits", ",", "num_bits", ")", ":", "# https://en.wikipedia.org/wiki/Decimal128_floating-point_format#Densely_packed_decimal_significand_field", "num_segments", "=", "num_bits", "//", "10", "segments", "=", "[", "]", "for", ...
prefix: High bits integer value dpd_bits: dpd encoded bits num_bits: bit length of dpd_bits
[ "prefix", ":", "High", "bits", "integer", "value", "dpd_bits", ":", "dpd", "encoded", "bits", "num_bits", ":", "bit", "length", "of", "dpd_bits" ]
python
train
28.263158
bearyinnovative/bearychat.py
examples/rtm_loop.py
https://github.com/bearyinnovative/bearychat.py/blob/6c7af2d215c2ff7135bb5af66ca333d0ea1089fd/examples/rtm_loop.py#L59-L69
def on_message(self, ws, message): """Websocket on_message event handler Saves message as RTMMessage in self._inbox """ try: data = json.loads(message) except Exception: self._set_error(message, "decode message failed") else: self._inb...
[ "def", "on_message", "(", "self", ",", "ws", ",", "message", ")", ":", "try", ":", "data", "=", "json", ".", "loads", "(", "message", ")", "except", "Exception", ":", "self", ".", "_set_error", "(", "message", ",", "\"decode message failed\"", ")", "else...
Websocket on_message event handler Saves message as RTMMessage in self._inbox
[ "Websocket", "on_message", "event", "handler" ]
python
train
30.363636
m32/endesive
endesive/pdf/fpdf/fpdf.py
https://github.com/m32/endesive/blob/973091dc69847fe2df594c80ac9235a8d08460ff/endesive/pdf/fpdf/fpdf.py#L629-L635
def set_link(self, link,y=0,page=-1): "Set destination of internal link" if(y==-1): y=self.y if(page==-1): page=self.page self.links[link]=[page,y]
[ "def", "set_link", "(", "self", ",", "link", ",", "y", "=", "0", ",", "page", "=", "-", "1", ")", ":", "if", "(", "y", "==", "-", "1", ")", ":", "y", "=", "self", ".", "y", "if", "(", "page", "==", "-", "1", ")", ":", "page", "=", "self...
Set destination of internal link
[ "Set", "destination", "of", "internal", "link" ]
python
train
28.142857
dpkp/kafka-python
kafka/producer/record_accumulator.py
https://github.com/dpkp/kafka-python/blob/f6a8a38937688ea2cc5dc13d3d1039493be5c9b5/kafka/producer/record_accumulator.py#L520-L536
def await_flush_completion(self, timeout=None): """ Mark all partitions as ready to send and block until the send is complete """ try: for batch in self._incomplete.all(): log.debug('Waiting on produce to %s', batch.produce_future.top...
[ "def", "await_flush_completion", "(", "self", ",", "timeout", "=", "None", ")", ":", "try", ":", "for", "batch", "in", "self", ".", "_incomplete", ".", "all", "(", ")", ":", "log", ".", "debug", "(", "'Waiting on produce to %s'", ",", "batch", ".", "prod...
Mark all partitions as ready to send and block until the send is complete
[ "Mark", "all", "partitions", "as", "ready", "to", "send", "and", "block", "until", "the", "send", "is", "complete" ]
python
train
45
zmathew/django-backbone
backbone/__init__.py
https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/__init__.py#L16-L41
def autodiscover(): """ Auto-discover INSTALLED_APPS backbone_api.py modules. """ # This code is based off django.contrib.admin.__init__ from django.conf import settings try: # Django versions >= 1.9 from django.utils.module_loading import import_module except ImportError: ...
[ "def", "autodiscover", "(", ")", ":", "# This code is based off django.contrib.admin.__init__", "from", "django", ".", "conf", "import", "settings", "try", ":", "# Django versions >= 1.9", "from", "django", ".", "utils", ".", "module_loading", "import", "import_module", ...
Auto-discover INSTALLED_APPS backbone_api.py modules.
[ "Auto", "-", "discover", "INSTALLED_APPS", "backbone_api", ".", "py", "modules", "." ]
python
train
40.115385
Azure/azure-cosmos-python
azure/cosmos/cosmos_client.py
https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L741-L764
def DeleteUser(self, user_link, options=None): """Deletes a user. :param str user_link: The link to the user entity. :param dict options: The request options for the request. :return: The deleted user. :rtype: dict """ ...
[ "def", "DeleteUser", "(", "self", ",", "user_link", ",", "options", "=", "None", ")", ":", "if", "options", "is", "None", ":", "options", "=", "{", "}", "path", "=", "base", ".", "GetPathFromLink", "(", "user_link", ")", "user_id", "=", "base", ".", ...
Deletes a user. :param str user_link: The link to the user entity. :param dict options: The request options for the request. :return: The deleted user. :rtype: dict
[ "Deletes", "a", "user", "." ]
python
train
28.125
codejamninja/sphinx-markdown-builder
sphinx_markdown_builder/markdown_writer.py
https://github.com/codejamninja/sphinx-markdown-builder/blob/a28f48df937d4b0e158ba453e5e1c66824299196/sphinx_markdown_builder/markdown_writer.py#L203-L214
def visit_image(self, node): """ Image directive """ uri = node.attributes['uri'] doc_folder = os.path.dirname(self.builder.current_docname) if uri.startswith(doc_folder): # drop docname prefix uri = uri[len(doc_folder):] if uri.startsw...
[ "def", "visit_image", "(", "self", ",", "node", ")", ":", "uri", "=", "node", ".", "attributes", "[", "'uri'", "]", "doc_folder", "=", "os", ".", "path", ".", "dirname", "(", "self", ".", "builder", ".", "current_docname", ")", "if", "uri", ".", "sta...
Image directive
[ "Image", "directive" ]
python
train
33.083333
Alignak-monitoring/alignak
alignak/daemons/arbiterdaemon.py
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemons/arbiterdaemon.py#L268-L291
def push_broks_to_broker(self): # pragma: no cover - not used! """Send all broks from arbiter internal list to broker The arbiter get some broks and then pushes them to all the brokers. :return: None """ someone_is_concerned = False sent = False for broker_link...
[ "def", "push_broks_to_broker", "(", "self", ")", ":", "# pragma: no cover - not used!", "someone_is_concerned", "=", "False", "sent", "=", "False", "for", "broker_link", "in", "self", ".", "conf", ".", "brokers", ":", "# Send only if the broker is concerned...", "if", ...
Send all broks from arbiter internal list to broker The arbiter get some broks and then pushes them to all the brokers. :return: None
[ "Send", "all", "broks", "from", "arbiter", "internal", "list", "to", "broker" ]
python
train
38.166667
saltstack/salt
salt/states/docker_container.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/docker_container.py#L2488-L2549
def absent(name, force=False): ''' Ensure that a container is absent name Name of the container force : False Set to ``True`` to remove the container even if it is running Usage Examples: .. code-block:: yaml mycontainer: docker_container.absent mu...
[ "def", "absent", "(", "name", ",", "force", "=", "False", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "False", ",", "'comment'", ":", "''", "}", "if", "name", "not", "in", "__salt__", "...
Ensure that a container is absent name Name of the container force : False Set to ``True`` to remove the container even if it is running Usage Examples: .. code-block:: yaml mycontainer: docker_container.absent multiple_containers: docker_contain...
[ "Ensure", "that", "a", "container", "is", "absent" ]
python
train
27.741935
caseyjlaw/activegit
activegit/activegit.py
https://github.com/caseyjlaw/activegit/blob/2b4a0ee0fecf13345b5257130ba98b48f46e1098/activegit/activegit.py#L161-L169
def write_training_data(self, features, targets): """ Writes data dictionary to filename """ assert len(features) == len(targets) data = dict(zip(features, targets)) with open(os.path.join(self.repopath, 'training.pkl'), 'w') as fp: pickle.dump(data, fp)
[ "def", "write_training_data", "(", "self", ",", "features", ",", "targets", ")", ":", "assert", "len", "(", "features", ")", "==", "len", "(", "targets", ")", "data", "=", "dict", "(", "zip", "(", "features", ",", "targets", ")", ")", "with", "open", ...
Writes data dictionary to filename
[ "Writes", "data", "dictionary", "to", "filename" ]
python
train
32.555556
gdoermann/voicebase
voicebase/api/media.py
https://github.com/gdoermann/voicebase/blob/53cb4735327898a7a284dea3a60ace0b3956a8ec/voicebase/api/media.py#L153-L161
def prediction_model_dict(self): """ Converts the list of prediction_models passed in into properly formatted dictionaries :return: formatted prediction model dict """ models = {} for model in self.predictions_models: models[model.name] = model.keywords ...
[ "def", "prediction_model_dict", "(", "self", ")", ":", "models", "=", "{", "}", "for", "model", "in", "self", ".", "predictions_models", ":", "models", "[", "model", ".", "name", "]", "=", "model", ".", "keywords", "return", "models" ]
Converts the list of prediction_models passed in into properly formatted dictionaries :return: formatted prediction model dict
[ "Converts", "the", "list", "of", "prediction_models", "passed", "in", "into", "properly", "formatted", "dictionaries", ":", "return", ":", "formatted", "prediction", "model", "dict" ]
python
train
36.333333
hubo1016/vlcp
vlcp/utils/http.py
https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/utils/http.py#L512-L519
def basicauthfail(self, realm = b'all'): """ Return 401 for authentication failure. This will end the handler. """ if not isinstance(realm, bytes): realm = realm.encode('ascii') self.start_response(401, [(b'WWW-Authenticate', b'Basic realm="' + realm + b'"')]) ...
[ "def", "basicauthfail", "(", "self", ",", "realm", "=", "b'all'", ")", ":", "if", "not", "isinstance", "(", "realm", ",", "bytes", ")", ":", "realm", "=", "realm", ".", "encode", "(", "'ascii'", ")", "self", ".", "start_response", "(", "401", ",", "[...
Return 401 for authentication failure. This will end the handler.
[ "Return", "401", "for", "authentication", "failure", ".", "This", "will", "end", "the", "handler", "." ]
python
train
45.5
ronaldguillen/wave
wave/views.py
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/views.py#L334-L341
def check_throttles(self, request): """ Check if request should be throttled. Raises an appropriate exception if the request is throttled. """ for throttle in self.get_throttles(): if not throttle.allow_request(request, self): self.throttled(request, t...
[ "def", "check_throttles", "(", "self", ",", "request", ")", ":", "for", "throttle", "in", "self", ".", "get_throttles", "(", ")", ":", "if", "not", "throttle", ".", "allow_request", "(", "request", ",", "self", ")", ":", "self", ".", "throttled", "(", ...
Check if request should be throttled. Raises an appropriate exception if the request is throttled.
[ "Check", "if", "request", "should", "be", "throttled", ".", "Raises", "an", "appropriate", "exception", "if", "the", "request", "is", "throttled", "." ]
python
train
41
hanguokai/youku
youku/youku_schemas.py
https://github.com/hanguokai/youku/blob/b2df060c7dccfad990bcfa289fff68bb77d1e69b/youku/youku_schemas.py#L19-L25
def video_category(self): """doc: http://open.youku.com/docs/doc?id=90 """ url = 'https://openapi.youku.com/v2/schemas/video/category.json' r = requests.get(url) check_error(r) return r.json()
[ "def", "video_category", "(", "self", ")", ":", "url", "=", "'https://openapi.youku.com/v2/schemas/video/category.json'", "r", "=", "requests", ".", "get", "(", "url", ")", "check_error", "(", "r", ")", "return", "r", ".", "json", "(", ")" ]
doc: http://open.youku.com/docs/doc?id=90
[ "doc", ":", "http", ":", "//", "open", ".", "youku", ".", "com", "/", "docs", "/", "doc?id", "=", "90" ]
python
train
33.428571
sphinx-gallery/sphinx-gallery
sphinx_gallery/notebook.py
https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/notebook.py#L123-L139
def add_code_cell(work_notebook, code): """Add a code cell to the notebook Parameters ---------- code : str Cell content """ code_cell = { "cell_type": "code", "execution_count": None, "metadata": {"collapsed": False}, "outputs": [], "source": [c...
[ "def", "add_code_cell", "(", "work_notebook", ",", "code", ")", ":", "code_cell", "=", "{", "\"cell_type\"", ":", "\"code\"", ",", "\"execution_count\"", ":", "None", ",", "\"metadata\"", ":", "{", "\"collapsed\"", ":", "False", "}", ",", "\"outputs\"", ":", ...
Add a code cell to the notebook Parameters ---------- code : str Cell content
[ "Add", "a", "code", "cell", "to", "the", "notebook" ]
python
train
21.588235
ttu/ruuvitag-sensor
ruuvitag_sensor/decoder.py
https://github.com/ttu/ruuvitag-sensor/blob/b5d1367c26844ae5875b2964c68e7b2f4e1cb082/ruuvitag_sensor/decoder.py#L195-L205
def _get_acceleration(self, data): '''Return acceleration mG''' if (data[7:8] == 0x7FFF or data[9:10] == 0x7FFF or data[11:12] == 0x7FFF): return (None, None, None) acc_x = twos_complement((data[7] << 8) + data[8], 16) acc_y = twos_complement(...
[ "def", "_get_acceleration", "(", "self", ",", "data", ")", ":", "if", "(", "data", "[", "7", ":", "8", "]", "==", "0x7FFF", "or", "data", "[", "9", ":", "10", "]", "==", "0x7FFF", "or", "data", "[", "11", ":", "12", "]", "==", "0x7FFF", ")", ...
Return acceleration mG
[ "Return", "acceleration", "mG" ]
python
train
40.090909
Sanji-IO/sanji
sanji/core.py
https://github.com/Sanji-IO/sanji/blob/5c54cc2772bdfeae3337f785de1957237b828b34/sanji/core.py#L230-L262
def start(self): """ start """ def main_thread(): # create resp, req thread pool self._create_thread_pool() # start connection, this will block until stop() self.conn_thread = Thread(target=self._conn.connect) self.conn_thread.d...
[ "def", "start", "(", "self", ")", ":", "def", "main_thread", "(", ")", ":", "# create resp, req thread pool", "self", ".", "_create_thread_pool", "(", ")", "# start connection, this will block until stop()", "self", ".", "conn_thread", "=", "Thread", "(", "target", ...
start
[ "start" ]
python
train
30.242424
hydpy-dev/hydpy
hydpy/models/hland/hland_model.py
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/models/hland/hland_model.py#L98-L156
def calc_fracrain_v1(self): """Determine the temperature-dependent fraction of (liquid) rainfall and (total) precipitation. Required control parameters: |NmbZones| |TT|, |TTInt| Required flux sequence: |TC| Calculated flux sequences: |FracRain| Basic equation: ...
[ "def", "calc_fracrain_v1", "(", "self", ")", ":", "con", "=", "self", ".", "parameters", ".", "control", ".", "fastaccess", "flu", "=", "self", ".", "sequences", ".", "fluxes", ".", "fastaccess", "for", "k", "in", "range", "(", "con", ".", "nmbzones", ...
Determine the temperature-dependent fraction of (liquid) rainfall and (total) precipitation. Required control parameters: |NmbZones| |TT|, |TTInt| Required flux sequence: |TC| Calculated flux sequences: |FracRain| Basic equation: :math:`FracRain = \\frac{TC-(T...
[ "Determine", "the", "temperature", "-", "dependent", "fraction", "of", "(", "liquid", ")", "rainfall", "and", "(", "total", ")", "precipitation", "." ]
python
train
29.322034
PythonicNinja/pydrill
pydrill/connection/base.py
https://github.com/PythonicNinja/pydrill/blob/0713e78c84d44cd438018e4ba1588a8e242f78c4/pydrill/connection/base.py#L99-L113
def _raise_error(self, status_code, raw_data): """ Locate appropriate exception and raise it. """ error_message = raw_data additional_info = None try: additional_info = json.loads(raw_data) error_message = additional_info.get('error', error_message...
[ "def", "_raise_error", "(", "self", ",", "status_code", ",", "raw_data", ")", ":", "error_message", "=", "raw_data", "additional_info", "=", "None", "try", ":", "additional_info", "=", "json", ".", "loads", "(", "raw_data", ")", "error_message", "=", "addition...
Locate appropriate exception and raise it.
[ "Locate", "appropriate", "exception", "and", "raise", "it", "." ]
python
train
38.6
ktbyers/netmiko
netmiko/_textfsm/_texttable.py
https://github.com/ktbyers/netmiko/blob/54e6116c0b4664de2123081937e0a9a27bdfdfea/netmiko/_textfsm/_texttable.py#L482-L525
def extend(self, table, keys=None): """Extends all rows in the texttable. The rows are extended with the new columns from the table. Args: table: A texttable, the table to extend this table by. keys: A set, the set of columns to use as the key. If None, the row index is used. ...
[ "def", "extend", "(", "self", ",", "table", ",", "keys", "=", "None", ")", ":", "if", "keys", ":", "for", "k", "in", "keys", ":", "if", "k", "not", "in", "self", ".", "_Header", "(", ")", ":", "raise", "IndexError", "(", "\"Unknown key: '%s'\"", ",...
Extends all rows in the texttable. The rows are extended with the new columns from the table. Args: table: A texttable, the table to extend this table by. keys: A set, the set of columns to use as the key. If None, the row index is used. Raises: IndexError: If key is not a valid...
[ "Extends", "all", "rows", "in", "the", "texttable", "." ]
python
train
28.386364
libtcod/python-tcod
tcod/libtcodpy.py
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L818-L833
def color_scale_HSV(c: Color, scoef: float, vcoef: float) -> None: """Scale a color's saturation and value. Does not return a new Color. ``c`` is modified inplace. Args: c (Union[Color, List[int]]): A Color instance, or an [r, g, b] list. scoef (float): Saturation multiplier, from 0 to 1....
[ "def", "color_scale_HSV", "(", "c", ":", "Color", ",", "scoef", ":", "float", ",", "vcoef", ":", "float", ")", "->", "None", ":", "color_p", "=", "ffi", ".", "new", "(", "\"TCOD_color_t*\"", ")", "color_p", ".", "r", ",", "color_p", ".", "g", ",", ...
Scale a color's saturation and value. Does not return a new Color. ``c`` is modified inplace. Args: c (Union[Color, List[int]]): A Color instance, or an [r, g, b] list. scoef (float): Saturation multiplier, from 0 to 1. Use 1 to keep current saturation. vcoef (f...
[ "Scale", "a", "color", "s", "saturation", "and", "value", "." ]
python
train
41.375
novopl/peltak
src/peltak/core/fs.py
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/core/fs.py#L152-L173
def write_file(path, content, mode='w'): # type: (Text, Union[Text,bytes], Text) -> None """ --pretend aware file writing. You can always write files manually but you should always handle the --pretend case. Args: path (str): content (str): mode (str): """ from pelt...
[ "def", "write_file", "(", "path", ",", "content", ",", "mode", "=", "'w'", ")", ":", "# type: (Text, Union[Text,bytes], Text) -> None", "from", "peltak", ".", "core", "import", "context", "from", "peltak", ".", "core", "import", "log", "if", "context", ".", "g...
--pretend aware file writing. You can always write files manually but you should always handle the --pretend case. Args: path (str): content (str): mode (str):
[ "--", "pretend", "aware", "file", "writing", "." ]
python
train
27.409091
tensorflow/tensor2tensor
tensor2tensor/data_generators/tokenizer.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/tokenizer.py#L91-L105
def decode(tokens): """Decode a list of tokens to a unicode string. Args: tokens: a list of Unicode strings Returns: a unicode string """ token_is_alnum = [t[0] in _ALPHANUMERIC_CHAR_SET for t in tokens] ret = [] for i, token in enumerate(tokens): if i > 0 and token_is_alnum[i - 1] and token_...
[ "def", "decode", "(", "tokens", ")", ":", "token_is_alnum", "=", "[", "t", "[", "0", "]", "in", "_ALPHANUMERIC_CHAR_SET", "for", "t", "in", "tokens", "]", "ret", "=", "[", "]", "for", "i", ",", "token", "in", "enumerate", "(", "tokens", ")", ":", "...
Decode a list of tokens to a unicode string. Args: tokens: a list of Unicode strings Returns: a unicode string
[ "Decode", "a", "list", "of", "tokens", "to", "a", "unicode", "string", "." ]
python
train
25.666667
pywbem/pywbem
pywbem/tupleparse.py
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L869-L889
def parse_classname(self, tup_tree): """ Parse a CLASSNAME element and return the class path it represents as a CIMClassName object. :: <!ELEMENT CLASSNAME EMPTY> <!ATTLIST CLASSNAME %CIMName;> Returns: CIMClassName object ...
[ "def", "parse_classname", "(", "self", ",", "tup_tree", ")", ":", "self", ".", "check_node", "(", "tup_tree", ",", "'CLASSNAME'", ",", "(", "'NAME'", ",", ")", ",", "(", ")", ",", "(", ")", ")", "classname", "=", "attrs", "(", "tup_tree", ")", "[", ...
Parse a CLASSNAME element and return the class path it represents as a CIMClassName object. :: <!ELEMENT CLASSNAME EMPTY> <!ATTLIST CLASSNAME %CIMName;> Returns: CIMClassName object (without namespace or host)
[ "Parse", "a", "CLASSNAME", "element", "and", "return", "the", "class", "path", "it", "represents", "as", "a", "CIMClassName", "object", "." ]
python
train
24.904762
sammchardy/python-binance
binance/websockets.py
https://github.com/sammchardy/python-binance/blob/31c0d0a32f9edd528c6c2c1dd3044d9a34ce43cc/binance/websockets.py#L174-L218
def start_kline_socket(self, symbol, callback, interval=Client.KLINE_INTERVAL_1MINUTE): """Start a websocket for symbol kline data https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#klinecandlestick-streams :param symbol: required :type symb...
[ "def", "start_kline_socket", "(", "self", ",", "symbol", ",", "callback", ",", "interval", "=", "Client", ".", "KLINE_INTERVAL_1MINUTE", ")", ":", "socket_name", "=", "'{}@kline_{}'", ".", "format", "(", "symbol", ".", "lower", "(", ")", ",", "interval", ")"...
Start a websocket for symbol kline data https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#klinecandlestick-streams :param symbol: required :type symbol: str :param callback: callback function to handle messages :type callback: funct...
[ "Start", "a", "websocket", "for", "symbol", "kline", "data" ]
python
train
42.266667
StackStorm/pybind
pybind/nos/v6_0_2f/brocade_vcs_rpc/show_vcs/output/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v6_0_2f/brocade_vcs_rpc/show_vcs/output/__init__.py#L178-L201
def _set_vcs_cluster_type_info(self, v, load=False): """ Setter method for vcs_cluster_type_info, mapped from YANG variable /brocade_vcs_rpc/show_vcs/output/vcs_cluster_type_info (vcs-cluster-type) If this variable is read-only (config: false) in the source YANG file, then _set_vcs_cluster_type_info is ...
[ "def", "_set_vcs_cluster_type_info", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ...
Setter method for vcs_cluster_type_info, mapped from YANG variable /brocade_vcs_rpc/show_vcs/output/vcs_cluster_type_info (vcs-cluster-type) If this variable is read-only (config: false) in the source YANG file, then _set_vcs_cluster_type_info is considered as a private method. Backends looking to populate ...
[ "Setter", "method", "for", "vcs_cluster_type_info", "mapped", "from", "YANG", "variable", "/", "brocade_vcs_rpc", "/", "show_vcs", "/", "output", "/", "vcs_cluster_type_info", "(", "vcs", "-", "cluster", "-", "type", ")", "If", "this", "variable", "is", "read", ...
python
train
90.833333
codelv/enaml-native
src/enamlnative/core/hotswap/core.py
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/core/hotswap/core.py#L38-L41
def check(self, check_all=True, do_reload=True): """Check whether some modules need to be reloaded.""" with enaml.imports(): super(EnamlReloader, self).check(check_all=check_all, do_reload=do_reload)
[ "def", "check", "(", "self", ",", "check_all", "=", "True", ",", "do_reload", "=", "True", ")", ":", "with", "enaml", ".", "imports", "(", ")", ":", "super", "(", "EnamlReloader", ",", "self", ")", ".", "check", "(", "check_all", "=", "check_all", ",...
Check whether some modules need to be reloaded.
[ "Check", "whether", "some", "modules", "need", "to", "be", "reloaded", "." ]
python
train
56
evetrivia/thanatos
thanatos/questions/base.py
https://github.com/evetrivia/thanatos/blob/664c12a8ccf4d27ab0e06e0969bbb6381f74789c/thanatos/questions/base.py#L77-L97
def convert_choices_to_dict(choices): """ Takes a list of tuples and converts it to a list of dictionaries of where each dictionary has a value and text key. This is the expected format of question choices to be returned by self.ask() :param convert_choices_to_dict: :type conver...
[ "def", "convert_choices_to_dict", "(", "choices", ")", ":", "formatted_choices", "=", "[", "]", "for", "x", "in", "choices", ":", "formatted_choices", ".", "append", "(", "{", "'value'", ":", "x", "[", "0", "]", ",", "'text'", ":", "x", "[", "1", "]", ...
Takes a list of tuples and converts it to a list of dictionaries of where each dictionary has a value and text key. This is the expected format of question choices to be returned by self.ask() :param convert_choices_to_dict: :type convert_choices_to_dict: list :return: ...
[ "Takes", "a", "list", "of", "tuples", "and", "converts", "it", "to", "a", "list", "of", "dictionaries", "of", "where", "each", "dictionary", "has", "a", "value", "and", "text", "key", ".", "This", "is", "the", "expected", "format", "of", "question", "cho...
python
train
27.47619
255BITS/hyperchamber
examples/shared/variational_autoencoder.py
https://github.com/255BITS/hyperchamber/blob/4d5774bde9ea6ce1113f77a069ffc605148482b8/examples/shared/variational_autoencoder.py#L155-L162
def partial_fit(self, X): """Train model based on mini-batch of input data. Return cost of mini-batch. """ opt, cost = self.sess.run((self.optimizer, self.cost), feed_dict={self.x: X}) return cost
[ "def", "partial_fit", "(", "self", ",", "X", ")", ":", "opt", ",", "cost", "=", "self", ".", "sess", ".", "run", "(", "(", "self", ".", "optimizer", ",", "self", ".", "cost", ")", ",", "feed_dict", "=", "{", "self", ".", "x", ":", "X", "}", "...
Train model based on mini-batch of input data. Return cost of mini-batch.
[ "Train", "model", "based", "on", "mini", "-", "batch", "of", "input", "data", ".", "Return", "cost", "of", "mini", "-", "batch", "." ]
python
train
34.125
inbo/pyinaturalist
pyinaturalist/rest_api.py
https://github.com/inbo/pyinaturalist/blob/d380ede84bdf15eca8ccab9efefe08d2505fe6a8/pyinaturalist/rest_api.py#L175-L192
def update_observation(observation_id: int, params: Dict[str, Any], access_token: str) -> List[Dict[str, Any]]: """ Update a single observation. See https://www.inaturalist.org/pages/api+reference#put-observations-id :param observation_id: the ID of the observation to update :param params: to be passed...
[ "def", "update_observation", "(", "observation_id", ":", "int", ",", "params", ":", "Dict", "[", "str", ",", "Any", "]", ",", "access_token", ":", "str", ")", "->", "List", "[", "Dict", "[", "str", ",", "Any", "]", "]", ":", "response", "=", "request...
Update a single observation. See https://www.inaturalist.org/pages/api+reference#put-observations-id :param observation_id: the ID of the observation to update :param params: to be passed to iNaturalist API :param access_token: the access token, as returned by :func:`get_access_token()` :return: iNatu...
[ "Update", "a", "single", "observation", ".", "See", "https", ":", "//", "www", ".", "inaturalist", ".", "org", "/", "pages", "/", "api", "+", "reference#put", "-", "observations", "-", "id" ]
python
train
53.277778
annayqho/TheCannon
code/lamost/abundances/calc_gradient_spectra.py
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/abundances/calc_gradient_spectra.py#L38-L41
def resample(grid, wl, flux): """ Resample spectrum onto desired grid """ flux_rs = (interpolate.interp1d(wl, flux))(grid) return flux_rs
[ "def", "resample", "(", "grid", ",", "wl", ",", "flux", ")", ":", "flux_rs", "=", "(", "interpolate", ".", "interp1d", "(", "wl", ",", "flux", ")", ")", "(", "grid", ")", "return", "flux_rs" ]
Resample spectrum onto desired grid
[ "Resample", "spectrum", "onto", "desired", "grid" ]
python
train
36.5
vinci1it2000/schedula
schedula/dispatcher.py
https://github.com/vinci1it2000/schedula/blob/addb9fd685be81544b796c51383ac00a31543ce9/schedula/dispatcher.py#L1384-L1393
def data_nodes(self): """ Returns all data nodes of the dispatcher. :return: All data nodes of the dispatcher. :rtype: dict[str, dict] """ return {k: v for k, v in self.nodes.items() if v['type'] == 'data'}
[ "def", "data_nodes", "(", "self", ")", ":", "return", "{", "k", ":", "v", "for", "k", ",", "v", "in", "self", ".", "nodes", ".", "items", "(", ")", "if", "v", "[", "'type'", "]", "==", "'data'", "}" ]
Returns all data nodes of the dispatcher. :return: All data nodes of the dispatcher. :rtype: dict[str, dict]
[ "Returns", "all", "data", "nodes", "of", "the", "dispatcher", "." ]
python
train
25.9
quantumlib/Cirq
cirq/google/programs.py
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/google/programs.py#L235-L266
def unpack_results( data: bytes, repetitions: int, key_sizes: Sequence[Tuple[str, int]] ) -> Dict[str, np.ndarray]: """Unpack data from a bitstring into individual measurement results. Args: data: Packed measurement results, in the form <rep0><rep1>... where each rep...
[ "def", "unpack_results", "(", "data", ":", "bytes", ",", "repetitions", ":", "int", ",", "key_sizes", ":", "Sequence", "[", "Tuple", "[", "str", ",", "int", "]", "]", ")", "->", "Dict", "[", "str", ",", "np", ".", "ndarray", "]", ":", "bits_per_rep",...
Unpack data from a bitstring into individual measurement results. Args: data: Packed measurement results, in the form <rep0><rep1>... where each repetition is <key0_0>..<key0_{size0-1}><key1_0>... with bits packed in little-endian order in each byte. repetitions: number of r...
[ "Unpack", "data", "from", "a", "bitstring", "into", "individual", "measurement", "results", "." ]
python
train
36.03125
shoeffner/cvloop
cvloop/functions.py
https://github.com/shoeffner/cvloop/blob/3ddd311e9b679d16c8fd36779931380374de343c/cvloop/functions.py#L188-L211
def find_faces(self, image, draw_box=False): """Uses a haarcascade to detect faces inside an image. Args: image: The image. draw_box: If True, the image will be marked with a rectangle. Return: The faces as returned by OpenCV's detectMultiScale method for ...
[ "def", "find_faces", "(", "self", ",", "image", ",", "draw_box", "=", "False", ")", ":", "frame_gray", "=", "cv2", ".", "cvtColor", "(", "image", ",", "cv2", ".", "COLOR_RGB2GRAY", ")", "faces", "=", "self", ".", "cascade", ".", "detectMultiScale", "(", ...
Uses a haarcascade to detect faces inside an image. Args: image: The image. draw_box: If True, the image will be marked with a rectangle. Return: The faces as returned by OpenCV's detectMultiScale method for cascades.
[ "Uses", "a", "haarcascade", "to", "detect", "faces", "inside", "an", "image", "." ]
python
train
31.458333
mweb/appconfig
appconfig/appconfig.py
https://github.com/mweb/appconfig/blob/780c1fe3b2f537463a46e335186b7741add88a1e/appconfig/appconfig.py#L77-L102
def init_default_config(self, path): ''' Initialize the config object and load the default configuration. The path to the config file must be provided. The name of the application is read from the config file. The config file stores the description and the default values for ...
[ "def", "init_default_config", "(", "self", ",", "path", ")", ":", "if", "not", "(", "os", ".", "path", ".", "exists", "(", "path", ")", "and", "os", ".", "path", ".", "isfile", "(", "path", ")", ")", ":", "raise", "AppConfigValueException", "(", "'Th...
Initialize the config object and load the default configuration. The path to the config file must be provided. The name of the application is read from the config file. The config file stores the description and the default values for all configurations including the appl...
[ "Initialize", "the", "config", "object", "and", "load", "the", "default", "configuration", ".", "The", "path", "to", "the", "config", "file", "must", "be", "provided", ".", "The", "name", "of", "the", "application", "is", "read", "from", "the", "config", "...
python
train
45.307692
spyder-ide/spyder
spyder/plugins/console/widgets/console.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/console.py#L72-L115
def set_style(self): """ Set font style with the following attributes: 'foreground_color', 'background_color', 'italic', 'bold' and 'underline' """ if self.current_format is None: assert self.base_format is not None self.current_format = QTextCharF...
[ "def", "set_style", "(", "self", ")", ":", "if", "self", ".", "current_format", "is", "None", ":", "assert", "self", ".", "base_format", "is", "not", "None", "self", ".", "current_format", "=", "QTextCharFormat", "(", "self", ".", "base_format", ")", "# Fo...
Set font style with the following attributes: 'foreground_color', 'background_color', 'italic', 'bold' and 'underline'
[ "Set", "font", "style", "with", "the", "following", "attributes", ":", "foreground_color", "background_color", "italic", "bold", "and", "underline" ]
python
train
34.659091
DataONEorg/d1_python
lib_common/src/d1_common/multipart.py
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/multipart.py#L71-L87
def normalize(body_part_tup,): """Normalize a tuple of BodyPart objects to a string. Normalization is done by sorting the body_parts by the Content- Disposition headers, which is typically on the form, ``form-data; name="name_of_part``. """ return '\n\n'.join( [ '{}\n\n{}'.form...
[ "def", "normalize", "(", "body_part_tup", ",", ")", ":", "return", "'\\n\\n'", ".", "join", "(", "[", "'{}\\n\\n{}'", ".", "format", "(", "str", "(", "p", ".", "headers", "[", "b'Content-Disposition'", "]", ",", "p", ".", "encoding", ")", ",", "p", "."...
Normalize a tuple of BodyPart objects to a string. Normalization is done by sorting the body_parts by the Content- Disposition headers, which is typically on the form, ``form-data; name="name_of_part``.
[ "Normalize", "a", "tuple", "of", "BodyPart", "objects", "to", "a", "string", "." ]
python
train
31.411765
openergy/oplus
oplus/util.py
https://github.com/openergy/oplus/blob/f095868d1990c1d126e906ada6acbab26348b3d3/oplus/util.py#L81-L116
def run_subprocess(command, cwd=None, stdout=None, stderr=None, shell=False, beat_freq=None): """ Parameters ---------- command: command cwd: current working directory stdout: output info stream (must have 'write' method) stderr: output error stream (must have 'write' method) shell: see ...
[ "def", "run_subprocess", "(", "command", ",", "cwd", "=", "None", ",", "stdout", "=", "None", ",", "stderr", "=", "None", ",", "shell", "=", "False", ",", "beat_freq", "=", "None", ")", ":", "sys", ".", "encoding", "=", "CONF", ".", "encoding", "# pr...
Parameters ---------- command: command cwd: current working directory stdout: output info stream (must have 'write' method) stderr: output error stream (must have 'write' method) shell: see subprocess.Popen beat_freq: if not none, stdout will be used at least every beat_freq (in seconds)
[ "Parameters", "----------", "command", ":", "command", "cwd", ":", "current", "working", "directory", "stdout", ":", "output", "info", "stream", "(", "must", "have", "write", "method", ")", "stderr", ":", "output", "error", "stream", "(", "must", "have", "wr...
python
test
35.055556
bokeh/bokeh
bokeh/io/util.py
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/io/util.py#L120-L126
def _shares_exec_prefix(basedir): ''' Whether a give base directory is on the system exex prefix ''' import sys prefix = sys.exec_prefix return (prefix is not None and basedir.startswith(prefix))
[ "def", "_shares_exec_prefix", "(", "basedir", ")", ":", "import", "sys", "prefix", "=", "sys", ".", "exec_prefix", "return", "(", "prefix", "is", "not", "None", "and", "basedir", ".", "startswith", "(", "prefix", ")", ")" ]
Whether a give base directory is on the system exex prefix
[ "Whether", "a", "give", "base", "directory", "is", "on", "the", "system", "exex", "prefix" ]
python
train
30
GemHQ/round-py
round/users.py
https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/users.py#L20-L97
def create(self, email, device_name, passphrase=None, api_token=None, redirect_uri=None, **kwargs): """Create a new User object and add it to this Users collection. In addition to creating a user, this call will create a device for that user, whose device_token will be returned f...
[ "def", "create", "(", "self", ",", "email", ",", "device_name", ",", "passphrase", "=", "None", ",", "api_token", "=", "None", ",", "redirect_uri", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "passphrase", "and", "u'default_wallet'", "no...
Create a new User object and add it to this Users collection. In addition to creating a user, this call will create a device for that user, whose device_token will be returned from this call. Store the device_token, as it's required to complete Gem-Device authentication after the user a...
[ "Create", "a", "new", "User", "object", "and", "add", "it", "to", "this", "Users", "collection", "." ]
python
train
44.089744
pybel/pybel-tools
src/pybel_tools/analysis/spia.py
https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/spia.py#L184-L200
def spia_matrices_to_excel(spia_matrices: Mapping[str, pd.DataFrame], path: str) -> None: """Export a SPIA data dictionary into an Excel sheet at the given path. .. note:: # The R import should add the values: # ["nodes"] from the columns # ["title"] from the name of the file #...
[ "def", "spia_matrices_to_excel", "(", "spia_matrices", ":", "Mapping", "[", "str", ",", "pd", ".", "DataFrame", "]", ",", "path", ":", "str", ")", "->", "None", ":", "writer", "=", "pd", ".", "ExcelWriter", "(", "path", ",", "engine", "=", "'xlsxwriter'"...
Export a SPIA data dictionary into an Excel sheet at the given path. .. note:: # The R import should add the values: # ["nodes"] from the columns # ["title"] from the name of the file # ["NumberOfReactions"] set to "0"
[ "Export", "a", "SPIA", "data", "dictionary", "into", "an", "Excel", "sheet", "at", "the", "given", "path", "." ]
python
valid
32.117647
jaraco/jaraco.services
jaraco/services/__init__.py
https://github.com/jaraco/jaraco.services/blob/4ccce53541201f778035b69e9c59e41e34ee5992/jaraco/services/__init__.py#L350-L361
def _run_env(self): """ Augment the current environment providing the PYTHONUSERBASE. """ env = dict(os.environ) env.update( getattr(self, 'env', {}), PYTHONUSERBASE=self.env_path, PIP_USER="1", ) self._disable_venv(env) ...
[ "def", "_run_env", "(", "self", ")", ":", "env", "=", "dict", "(", "os", ".", "environ", ")", "env", ".", "update", "(", "getattr", "(", "self", ",", "'env'", ",", "{", "}", ")", ",", "PYTHONUSERBASE", "=", "self", ".", "env_path", ",", "PIP_USER",...
Augment the current environment providing the PYTHONUSERBASE.
[ "Augment", "the", "current", "environment", "providing", "the", "PYTHONUSERBASE", "." ]
python
train
26.666667
PyHDI/Pyverilog
pyverilog/vparser/parser.py
https://github.com/PyHDI/Pyverilog/blob/b852cc5ed6a7a2712e33639f9d9782d0d1587a53/pyverilog/vparser/parser.py#L1647-L1650
def p_casecontent_statement(self, p): 'casecontent_statement : casecontent_condition COLON basic_statement' p[0] = Case(p[1], p[3], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
[ "def", "p_casecontent_statement", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "Case", "(", "p", "[", "1", "]", ",", "p", "[", "3", "]", ",", "lineno", "=", "p", ".", "lineno", "(", "1", ")", ")", "p", ".", "set_lineno", "(", "...
casecontent_statement : casecontent_condition COLON basic_statement
[ "casecontent_statement", ":", "casecontent_condition", "COLON", "basic_statement" ]
python
train
50.25
awslabs/aws-sam-cli
samcli/lib/utils/stream_writer.py
https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/lib/utils/stream_writer.py#L22-L34
def write(self, output): """ Writes specified text to the underlying stream Parameters ---------- output bytes-like object Bytes to write """ self._stream.write(output) if self._auto_flush: self._stream.flush()
[ "def", "write", "(", "self", ",", "output", ")", ":", "self", ".", "_stream", ".", "write", "(", "output", ")", "if", "self", ".", "_auto_flush", ":", "self", ".", "_stream", ".", "flush", "(", ")" ]
Writes specified text to the underlying stream Parameters ---------- output bytes-like object Bytes to write
[ "Writes", "specified", "text", "to", "the", "underlying", "stream" ]
python
train
22.153846
jobovy/galpy
galpy/orbit/OrbitTop.py
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/orbit/OrbitTop.py#L1158-L1202
def L(self,*args,**kwargs): """ NAME: L PURPOSE: calculate the angular momentum INPUT: (none) OUTPUT: angular momentum HISTORY: 2010-09-15 - Written - Bovy (NYU) """ #Make sure you are not using physic...
[ "def", "L", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "#Make sure you are not using physical coordinates", "old_physical", "=", "kwargs", ".", "get", "(", "'use_physical'", ",", "None", ")", "kwargs", "[", "'use_physical'", "]", "=", ...
NAME: L PURPOSE: calculate the angular momentum INPUT: (none) OUTPUT: angular momentum HISTORY: 2010-09-15 - Written - Bovy (NYU)
[ "NAME", ":", "L", "PURPOSE", ":", "calculate", "the", "angular", "momentum", "INPUT", ":", "(", "none", ")", "OUTPUT", ":", "angular", "momentum", "HISTORY", ":", "2010", "-", "09", "-", "15", "-", "Written", "-", "Bovy", "(", "NYU", ")" ]
python
train
35.333333
singnet/snet-cli
snet_cli/mpe_service_command.py
https://github.com/singnet/snet-cli/blob/1b5ac98cb9a64211c861ead9fcfe6208f2749032/snet_cli/mpe_service_command.py#L82-L100
def metadata_add_description(self): """ Metadata: add description """ service_description = {} if (self.args.json): service_description = json.loads(self.args.json) if (self.args.url): if "url" in service_description: raise Exception("json service ...
[ "def", "metadata_add_description", "(", "self", ")", ":", "service_description", "=", "{", "}", "if", "(", "self", ".", "args", ".", "json", ")", ":", "service_description", "=", "json", ".", "loads", "(", "self", ".", "args", ".", "json", ")", "if", "...
Metadata: add description
[ "Metadata", ":", "add", "description" ]
python
train
55.421053
iotile/coretools
iotilecore/iotile/core/hw/reports/signed_list_format.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/reports/signed_list_format.py#L44-L124
def FromReadings(cls, uuid, readings, root_key=AuthProvider.NoKey, signer=None, report_id=IOTileReading.InvalidReadingID, selector=0xFFFF, streamer=0, sent_timestamp=0): """Generate an instance of the report format from a list of readings and a uuid. The signed list report is creat...
[ "def", "FromReadings", "(", "cls", ",", "uuid", ",", "readings", ",", "root_key", "=", "AuthProvider", ".", "NoKey", ",", "signer", "=", "None", ",", "report_id", "=", "IOTileReading", ".", "InvalidReadingID", ",", "selector", "=", "0xFFFF", ",", "streamer",...
Generate an instance of the report format from a list of readings and a uuid. The signed list report is created using the passed readings and signed using the specified method and AuthProvider. If no auth provider is specified, the report is signed using the default authorization chain. ...
[ "Generate", "an", "instance", "of", "the", "report", "format", "from", "a", "list", "of", "readings", "and", "a", "uuid", "." ]
python
train
52.333333
PmagPy/PmagPy
SPD/lib/lib_ptrm_statistics.py
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/SPD/lib/lib_ptrm_statistics.py#L29-L63
def get_max_ptrm_check(ptrm_checks_included_temps, ptrm_checks_all_temps, ptrm_x, t_Arai, x_Arai): """ input: ptrm_checks_included_temps, ptrm_checks_all_temps, ptrm_x, t_Arai, x_Arai. sorts through included ptrm_checks and finds the largest ptrm check diff, the sum of the total diffs, and the perce...
[ "def", "get_max_ptrm_check", "(", "ptrm_checks_included_temps", ",", "ptrm_checks_all_temps", ",", "ptrm_x", ",", "t_Arai", ",", "x_Arai", ")", ":", "if", "not", "ptrm_checks_included_temps", ":", "return", "[", "]", ",", "float", "(", "'nan'", ")", ",", "float"...
input: ptrm_checks_included_temps, ptrm_checks_all_temps, ptrm_x, t_Arai, x_Arai. sorts through included ptrm_checks and finds the largest ptrm check diff, the sum of the total diffs, and the percentage of the largest check / original measurement at that temperature step output: max_diff, sum_diffs, che...
[ "input", ":", "ptrm_checks_included_temps", "ptrm_checks_all_temps", "ptrm_x", "t_Arai", "x_Arai", ".", "sorts", "through", "included", "ptrm_checks", "and", "finds", "the", "largest", "ptrm", "check", "diff", "the", "sum", "of", "the", "total", "diffs", "and", "t...
python
train
44.914286
pytorch/ignite
ignite/metrics/confusion_matrix.py
https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/metrics/confusion_matrix.py#L212-L227
def cmRecall(cm, average=True): """ Calculates recall using :class:`~ignite.metrics.ConfusionMatrix` metric. Args: cm (ConfusionMatrix): instance of confusion matrix metric average (bool, optional): if True metric value is averaged over all classes Returns: MetricsLambda """ ...
[ "def", "cmRecall", "(", "cm", ",", "average", "=", "True", ")", ":", "# Increase floating point precision", "cm", "=", "cm", ".", "type", "(", "torch", ".", "float64", ")", "recall", "=", "cm", ".", "diag", "(", ")", "/", "(", "cm", ".", "sum", "(", ...
Calculates recall using :class:`~ignite.metrics.ConfusionMatrix` metric. Args: cm (ConfusionMatrix): instance of confusion matrix metric average (bool, optional): if True metric value is averaged over all classes Returns: MetricsLambda
[ "Calculates", "recall", "using", ":", "class", ":", "~ignite", ".", "metrics", ".", "ConfusionMatrix", "metric", ".", "Args", ":", "cm", "(", "ConfusionMatrix", ")", ":", "instance", "of", "confusion", "matrix", "metric", "average", "(", "bool", "optional", ...
python
train
30.5625
resync/resync
resync/client_state.py
https://github.com/resync/resync/blob/98292c17b2c00f2d6f5191c6ab51fef8c292a018/resync/client_state.py#L28-L49
def set_state(self, site, timestamp=None): """Write status dict to client status file. FIXME - should have some file lock to avoid race """ parser = ConfigParser() parser.read(self.status_file) status_section = 'incremental' if (not parser.has_section(status_sect...
[ "def", "set_state", "(", "self", ",", "site", ",", "timestamp", "=", "None", ")", ":", "parser", "=", "ConfigParser", "(", ")", "parser", ".", "read", "(", "self", ".", "status_file", ")", "status_section", "=", "'incremental'", "if", "(", "not", "parser...
Write status dict to client status file. FIXME - should have some file lock to avoid race
[ "Write", "status", "dict", "to", "client", "status", "file", "." ]
python
train
35.090909
williamgilpin/pypdb
pypdb/pypdb.py
https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L797-L841
def get_blast(pdb_id, chain_id='A'): """ Return BLAST search results for a given PDB ID The key of the output dict())that outputs the full search results is 'BlastOutput_iterations' To get a list of just the results without the metadata of the search use: hits = full_results['BlastOutput_iterat...
[ "def", "get_blast", "(", "pdb_id", ",", "chain_id", "=", "'A'", ")", ":", "raw_results", "=", "get_raw_blast", "(", "pdb_id", ",", "output_form", "=", "'XML'", ",", "chain_id", "=", "chain_id", ")", "out", "=", "xmltodict", ".", "parse", "(", "raw_results"...
Return BLAST search results for a given PDB ID The key of the output dict())that outputs the full search results is 'BlastOutput_iterations' To get a list of just the results without the metadata of the search use: hits = full_results['BlastOutput_iterations']['Iteration']['Iteration_hits']['Hit'] ...
[ "Return", "BLAST", "search", "results", "for", "a", "given", "PDB", "ID", "The", "key", "of", "the", "output", "dict", "()", ")", "that", "outputs", "the", "full", "search", "results", "is", "BlastOutput_iterations" ]
python
train
34.488889
ets-labs/python-domain-models
domain_models/views.py
https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/views.py#L54-L73
def check_include_exclude(attributes): """Check __include__ and __exclude__ attributes. :type attributes: dict """ include = attributes.get('__include__', tuple()) exclude = attributes.get('__exclude__', tuple()) if not isinstance(include, tuple): raise Type...
[ "def", "check_include_exclude", "(", "attributes", ")", ":", "include", "=", "attributes", ".", "get", "(", "'__include__'", ",", "tuple", "(", ")", ")", "exclude", "=", "attributes", ".", "get", "(", "'__exclude__'", ",", "tuple", "(", ")", ")", "if", "...
Check __include__ and __exclude__ attributes. :type attributes: dict
[ "Check", "__include__", "and", "__exclude__", "attributes", "." ]
python
train
35.45
senaite/senaite.core
bika/lims/browser/analysisrequest/add2.py
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/analysisrequest/add2.py#L1004-L1067
def get_sampletype_info(self, obj): """Returns the info for a Sample Type """ info = self.get_base_info(obj) # Bika Setup folder bika_setup = api.get_bika_setup() # bika samplepoints bika_samplepoints = bika_setup.bika_samplepoints bika_samplepoints_uid ...
[ "def", "get_sampletype_info", "(", "self", ",", "obj", ")", ":", "info", "=", "self", ".", "get_base_info", "(", "obj", ")", "# Bika Setup folder", "bika_setup", "=", "api", ".", "get_bika_setup", "(", ")", "# bika samplepoints", "bika_samplepoints", "=", "bika_...
Returns the info for a Sample Type
[ "Returns", "the", "info", "for", "a", "Sample", "Type" ]
python
train
36.734375
noxdafox/clipspy
clips/facts.py
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/facts.py#L76-L83
def templates(self): """Iterate over the defined Templates.""" template = lib.EnvGetNextDeftemplate(self._env, ffi.NULL) while template != ffi.NULL: yield Template(self._env, template) template = lib.EnvGetNextDeftemplate(self._env, template)
[ "def", "templates", "(", "self", ")", ":", "template", "=", "lib", ".", "EnvGetNextDeftemplate", "(", "self", ".", "_env", ",", "ffi", ".", "NULL", ")", "while", "template", "!=", "ffi", ".", "NULL", ":", "yield", "Template", "(", "self", ".", "_env", ...
Iterate over the defined Templates.
[ "Iterate", "over", "the", "defined", "Templates", "." ]
python
train
35.625
Cymmetria/honeycomb
honeycomb/utils/config_utils.py
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/utils/config_utils.py#L60-L78
def validate_field_matches_type(field, value, field_type, select_items=None, _min=None, _max=None): """Validate a config field against a specific type.""" if (field_type == defs.TEXT_TYPE and not isinstance(value, six.string_types)) or \ (field_type == defs.STRING_TYPE and not isinstance(value, six.strin...
[ "def", "validate_field_matches_type", "(", "field", ",", "value", ",", "field_type", ",", "select_items", "=", "None", ",", "_min", "=", "None", ",", "_max", "=", "None", ")", ":", "if", "(", "field_type", "==", "defs", ".", "TEXT_TYPE", "and", "not", "i...
Validate a config field against a specific type.
[ "Validate", "a", "config", "field", "against", "a", "specific", "type", "." ]
python
train
60.631579
BernardFW/bernard
src/bernard/middleware/_manager.py
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/middleware/_manager.py#L173-L184
def get(self, name: Text, final: C) -> C: """ Get the function to call which will run all middlewares. :param name: Name of the function to be called :param final: Function to call at the bottom of the stack (that's the one provided by the implementer). :re...
[ "def", "get", "(", "self", ",", "name", ":", "Text", ",", "final", ":", "C", ")", "->", "C", ":", "# noinspection PyTypeChecker", "return", "Caller", "(", "self", ",", "name", ",", "final", ")" ]
Get the function to call which will run all middlewares. :param name: Name of the function to be called :param final: Function to call at the bottom of the stack (that's the one provided by the implementer). :return:
[ "Get", "the", "function", "to", "call", "which", "will", "run", "all", "middlewares", "." ]
python
train
33.75
bids-standard/pybids
bids/variables/kollekshuns.py
https://github.com/bids-standard/pybids/blob/30d924ce770622bda0e390d613a8da42a2a20c32/bids/variables/kollekshuns.py#L152-L158
def clone(self): ''' Returns a shallow copy of the current instance, except that all variables are deep-cloned. ''' clone = copy(self) clone.variables = {k: v.clone() for (k, v) in self.variables.items()} return clone
[ "def", "clone", "(", "self", ")", ":", "clone", "=", "copy", "(", "self", ")", "clone", ".", "variables", "=", "{", "k", ":", "v", ".", "clone", "(", ")", "for", "(", "k", ",", "v", ")", "in", "self", ".", "variables", ".", "items", "(", ")",...
Returns a shallow copy of the current instance, except that all variables are deep-cloned.
[ "Returns", "a", "shallow", "copy", "of", "the", "current", "instance", "except", "that", "all", "variables", "are", "deep", "-", "cloned", "." ]
python
train
37
fermiPy/fermipy
fermipy/jobs/scatter_gather.py
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/scatter_gather.py#L199-L228
def _run_link(self, stream=sys.stdout, dry_run=False, stage_files=True, resubmit_failed=False): """Internal function that actually runs this link. This checks if input and output files are present. If input files are missing this will raise `OSError` if dry_run is False ...
[ "def", "_run_link", "(", "self", ",", "stream", "=", "sys", ".", "stdout", ",", "dry_run", "=", "False", ",", "stage_files", "=", "True", ",", "resubmit_failed", "=", "False", ")", ":", "if", "resubmit_failed", ":", "self", ".", "args", "[", "'action'", ...
Internal function that actually runs this link. This checks if input and output files are present. If input files are missing this will raise `OSError` if dry_run is False If all output files are present this will skip execution. Parameters ----------- stream : `file` ...
[ "Internal", "function", "that", "actually", "runs", "this", "link", "." ]
python
train
32.2
AndrewAnnex/SpiceyPy
spiceypy/spiceypy.py
https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L2258-L2272
def dasopr(fname): """ Open a DAS file for reading. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dasopr_c.html :param fname: Name of a DAS file to be opened. :type fname: str :return: Handle assigned to the opened DAS file. :rtype: int """ fname = stypes.stringToCharP(fn...
[ "def", "dasopr", "(", "fname", ")", ":", "fname", "=", "stypes", ".", "stringToCharP", "(", "fname", ")", "handle", "=", "ctypes", ".", "c_int", "(", ")", "libspice", ".", "dasopr_c", "(", "fname", ",", "ctypes", ".", "byref", "(", "handle", ")", ")"...
Open a DAS file for reading. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dasopr_c.html :param fname: Name of a DAS file to be opened. :type fname: str :return: Handle assigned to the opened DAS file. :rtype: int
[ "Open", "a", "DAS", "file", "for", "reading", "." ]
python
train
27.533333
spulec/moto
moto/iam/models.py
https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/iam/models.py#L1066-L1083
def enable_mfa_device(self, user_name, serial_number, authentication_code_1, authentication_code_2): """Enable MFA Device for user.""" user = self.get_user(user_name) if serial_number in user....
[ "def", "enable_mfa_device", "(", "self", ",", "user_name", ",", "serial_number", ",", "authentication_code_1", ",", "authentication_code_2", ")", ":", "user", "=", "self", ".", "get_user", "(", "user_name", ")", "if", "serial_number", "in", "user", ".", "mfa_dev...
Enable MFA Device for user.
[ "Enable", "MFA", "Device", "for", "user", "." ]
python
train
34.055556
aws/sagemaker-containers
src/sagemaker_containers/_files.py
https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_files.py#L140-L157
def s3_download(url, dst): # type: (str, str) -> None """Download a file from S3. Args: url (str): the s3 url of the file. dst (str): the destination where the file will be saved. """ url = parse.urlparse(url) if url.scheme != 's3': raise ValueError("Expecting 's3' scheme,...
[ "def", "s3_download", "(", "url", ",", "dst", ")", ":", "# type: (str, str) -> None", "url", "=", "parse", ".", "urlparse", "(", "url", ")", "if", "url", ".", "scheme", "!=", "'s3'", ":", "raise", "ValueError", "(", "\"Expecting 's3' scheme, got: %s in %s\"", ...
Download a file from S3. Args: url (str): the s3 url of the file. dst (str): the destination where the file will be saved.
[ "Download", "a", "file", "from", "S3", "." ]
python
train
31.777778
dnanexus/dx-toolkit
src/python/dxpy/api.py
https://github.com/dnanexus/dx-toolkit/blob/74befb53ad90fcf902d8983ae6d74580f402d619/src/python/dxpy/api.py#L830-L836
def job_terminate(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /job-xxxx/terminate API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Applets-and-Entry-Points#API-method%3A-%2Fjob-xxxx%2Fterminate """ return DXHTTPRequest('/%s/terminate' ...
[ "def", "job_terminate", "(", "object_id", ",", "input_params", "=", "{", "}", ",", "always_retry", "=", "True", ",", "*", "*", "kwargs", ")", ":", "return", "DXHTTPRequest", "(", "'/%s/terminate'", "%", "object_id", ",", "input_params", ",", "always_retry", ...
Invokes the /job-xxxx/terminate API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Applets-and-Entry-Points#API-method%3A-%2Fjob-xxxx%2Fterminate
[ "Invokes", "the", "/", "job", "-", "xxxx", "/", "terminate", "API", "method", "." ]
python
train
53.857143
pjuren/pyokit
src/pyokit/datastruct/retrotransposon.py
https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/datastruct/retrotransposon.py#L452-L512
def __liftover_coordinates_genomic_deletions(self, intersecting_region): """ A 'private' helper member function to perform liftover in coordinate space when the length of the genomic match is smaller than the concensus match. We assume the genomic region contains deletions. In this case, we uniformly ...
[ "def", "__liftover_coordinates_genomic_deletions", "(", "self", ",", "intersecting_region", ")", ":", "# should never happen, but check anyway...", "consensus_match_length", "=", "self", ".", "consensus_end", "-", "self", ".", "consensus_start", "size_dif", "=", "consensus_ma...
A 'private' helper member function to perform liftover in coordinate space when the length of the genomic match is smaller than the concensus match. We assume the genomic region contains deletions. In this case, we uniformly distribute the deletions (gaps) through the genomic region. This is the trickie...
[ "A", "private", "helper", "member", "function", "to", "perform", "liftover", "in", "coordinate", "space", "when", "the", "length", "of", "the", "genomic", "match", "is", "smaller", "than", "the", "concensus", "match", ".", "We", "assume", "the", "genomic", "...
python
train
50.131148
PmagPy/PmagPy
programs/forc_diagram.py
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/forc_diagram.py#L187-L268
def rawData(self, fileAdres=None): # skip skiprows skiprows = None skip_from = [b'Field', b'Moment'] with open(fileAdres, 'rb') as fr: #f = fr.read() for i, line in enumerate(fr, 1): # print(line.split()) if skip_from == line.split(...
[ "def", "rawData", "(", "self", ",", "fileAdres", "=", "None", ")", ":", "# skip skiprows", "skiprows", "=", "None", "skip_from", "=", "[", "b'Field'", ",", "b'Moment'", "]", "with", "open", "(", "fileAdres", ",", "'rb'", ")", "as", "fr", ":", "#f = fr.re...
#================================================= /datainterval_H/_M /slice the measured data into pieces /for every measured FORC #=================================================
[ "#", "=================================================", "/", "datainterval_H", "/", "_M", "/", "slice", "the", "measured", "data", "into", "pieces", "/", "for", "every", "measured", "FORC", "#", "=================================================" ]
python
train
40.829268
wuher/devil
example/userdb/api/resources.py
https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/example/userdb/api/resources.py#L70-L72
def _get_all(self): """ Get all users from db and turn into list of dicts """ return [self._to_dict(row) for row in models.User.objects.all()]
[ "def", "_get_all", "(", "self", ")", ":", "return", "[", "self", ".", "_to_dict", "(", "row", ")", "for", "row", "in", "models", ".", "User", ".", "objects", ".", "all", "(", ")", "]" ]
Get all users from db and turn into list of dicts
[ "Get", "all", "users", "from", "db", "and", "turn", "into", "list", "of", "dicts" ]
python
train
52
cloudant/python-cloudant
src/cloudant/_client_session.py
https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/_client_session.py#L275-L301
def _get_access_token(self): """ Get IAM access token using API key. """ err = 'Failed to contact IAM token service' try: resp = super(IAMSession, self).request( 'POST', self._token_url, auth=self._token_auth, ...
[ "def", "_get_access_token", "(", "self", ")", ":", "err", "=", "'Failed to contact IAM token service'", "try", ":", "resp", "=", "super", "(", "IAMSession", ",", "self", ")", ".", "request", "(", "'POST'", ",", "self", ".", "_token_url", ",", "auth", "=", ...
Get IAM access token using API key.
[ "Get", "IAM", "access", "token", "using", "API", "key", "." ]
python
train
33.925926
feliphebueno/Rinzler
rinzler/__init__.py
https://github.com/feliphebueno/Rinzler/blob/7f6d5445b5662cba2e8938bb82c7f3ef94e5ded8/rinzler/__init__.py#L125-L165
def handle(self, request: HttpRequest) -> HttpResponse: """ Prepares for the CallBackResolver and handles the response and exceptions :param request HttpRequest :rtype: HttpResponse """ self.__request_start = datetime.now() self.__request = request self.__...
[ "def", "handle", "(", "self", ",", "request", ":", "HttpRequest", ")", "->", "HttpResponse", ":", "self", ".", "__request_start", "=", "datetime", ".", "now", "(", ")", "self", ".", "__request", "=", "request", "self", ".", "__uri", "=", "request", ".", ...
Prepares for the CallBackResolver and handles the response and exceptions :param request HttpRequest :rtype: HttpResponse
[ "Prepares", "for", "the", "CallBackResolver", "and", "handles", "the", "response", "and", "exceptions", ":", "param", "request", "HttpRequest", ":", "rtype", ":", "HttpResponse" ]
python
train
40
cslarsen/elv
elv/elv.py
https://github.com/cslarsen/elv/blob/4bacf2093a0dcbe6a2b4d79be0fe339bb2b99097/elv/elv.py#L434-L453
def parse(filename, format=u"Jæren Sparebank", encoding="latin1"): """Parses bank CSV file and returns Transactions instance. Args: filename: Path to CSV file to read. format: CSV format; one of the entries in `elv.formats`. encoding: The CSV file encoding. Returns: A ``Tra...
[ "def", "parse", "(", "filename", ",", "format", "=", "u\"Jæren Sparebank\",", " ", "ncoding=", "\"", "latin1\")", ":", "", "Class", "=", "formats", "[", "format", ".", "lower", "(", ")", "]", "if", "PY3", ":", "kw", "=", "{", "\"encoding\"", ":", "enco...
Parses bank CSV file and returns Transactions instance. Args: filename: Path to CSV file to read. format: CSV format; one of the entries in `elv.formats`. encoding: The CSV file encoding. Returns: A ``Transactions`` object.
[ "Parses", "bank", "CSV", "file", "and", "returns", "Transactions", "instance", "." ]
python
train
26.3
harmsm/PyCmdMessenger
PyCmdMessenger/PyCmdMessenger.py
https://github.com/harmsm/PyCmdMessenger/blob/215d6f9402262662a14a2996f532934339639a5b/PyCmdMessenger/PyCmdMessenger.py#L455-L470
def _send_float(self,value): """ Return a float as a IEEE 754 format bytes object. """ # convert to float. this will throw a ValueError if the type is not # readily converted if type(value) != float: value = float(value) # Range check if val...
[ "def", "_send_float", "(", "self", ",", "value", ")", ":", "# convert to float. this will throw a ValueError if the type is not ", "# readily converted", "if", "type", "(", "value", ")", "!=", "float", ":", "value", "=", "float", "(", "value", ")", "# Range check", ...
Return a float as a IEEE 754 format bytes object.
[ "Return", "a", "float", "as", "a", "IEEE", "754", "format", "bytes", "object", "." ]
python
train
33.6875
google/transitfeed
kmlwriter.py
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/kmlwriter.py#L244-L257
def _CreateLineStringForShape(self, parent, shape): """Create a KML LineString using coordinates from a shape. Args: parent: The parent ElementTree.Element instance. shape: The transitfeed.Shape instance. Returns: The LineString ElementTree.Element instance or None if coordinate_list is ...
[ "def", "_CreateLineStringForShape", "(", "self", ",", "parent", ",", "shape", ")", ":", "coordinate_list", "=", "[", "(", "longitude", ",", "latitude", ")", "for", "(", "latitude", ",", "longitude", ",", "distance", ")", "in", "shape", ".", "points", "]", ...
Create a KML LineString using coordinates from a shape. Args: parent: The parent ElementTree.Element instance. shape: The transitfeed.Shape instance. Returns: The LineString ElementTree.Element instance or None if coordinate_list is empty.
[ "Create", "a", "KML", "LineString", "using", "coordinates", "from", "a", "shape", "." ]
python
train
36.214286
HewlettPackard/python-hpOneView
hpOneView/resources/search/labels.py
https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/search/labels.py#L100-L111
def create(self, resource): """ Set all the labels for a resource. Args: resource: The object containing the resource URI and a list of labels Returns: dict: Resource Labels """ uri = self.URI + self.RESOURCES_PATH return self._client.cre...
[ "def", "create", "(", "self", ",", "resource", ")", ":", "uri", "=", "self", ".", "URI", "+", "self", ".", "RESOURCES_PATH", "return", "self", ".", "_client", ".", "create", "(", "resource", "=", "resource", ",", "uri", "=", "uri", ")" ]
Set all the labels for a resource. Args: resource: The object containing the resource URI and a list of labels Returns: dict: Resource Labels
[ "Set", "all", "the", "labels", "for", "a", "resource", "." ]
python
train
28.333333
steffann/pylisp
pylisp/packet/lisp/control/map_referral_record.py
https://github.com/steffann/pylisp/blob/907340f0c7ef2c4d4fe0c8e0a48df5be0d969407/pylisp/packet/lisp/control/map_referral_record.py#L84-L278
def sanitize(self): ''' Check if the current settings conform to the LISP specifications and fix where possible. ''' # WARNING: http://tools.ietf.org/html/draft-ietf-lisp-ddt-00 # does not define this field so the description is taken from # http://tools.ietf.org/...
[ "def", "sanitize", "(", "self", ")", ":", "# WARNING: http://tools.ietf.org/html/draft-ietf-lisp-ddt-00", "# does not define this field so the description is taken from", "# http://tools.ietf.org/html/draft-ietf-lisp-24", "#", "# Record TTL: The time in minutes the recipient of the Map-Reply wi...
Check if the current settings conform to the LISP specifications and fix where possible.
[ "Check", "if", "the", "current", "settings", "conform", "to", "the", "LISP", "specifications", "and", "fix", "where", "possible", "." ]
python
train
49.4
pjmark/NIMPA
niftypet/nimpa/prc/imio.py
https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/imio.py#L415-L550
def dcmanonym( dcmpth, displayonly=False, patient='anonymised', physician='anonymised', dob='19800101', verbose=True): ''' Anonymise DICOM file(s) Arguments: > dcmpth: it can be passed as a single DICOM file, or a folder containi...
[ "def", "dcmanonym", "(", "dcmpth", ",", "displayonly", "=", "False", ",", "patient", "=", "'anonymised'", ",", "physician", "=", "'anonymised'", ",", "dob", "=", "'19800101'", ",", "verbose", "=", "True", ")", ":", "#> check if a single DICOM file", "if", "isi...
Anonymise DICOM file(s) Arguments: > dcmpth: it can be passed as a single DICOM file, or a folder containing DICOM files, or a list of DICOM file paths. > patient: the name of the patient. > physician:the name of the referring physician. > dob: patient...
[ "Anonymise", "DICOM", "file", "(", "s", ")", "Arguments", ":", ">", "dcmpth", ":", "it", "can", "be", "passed", "as", "a", "single", "DICOM", "file", "or", "a", "folder", "containing", "DICOM", "files", "or", "a", "list", "of", "DICOM", "file", "paths"...
python
train
35.242647
erikrose/more-itertools
more_itertools/more.py
https://github.com/erikrose/more-itertools/blob/6a91b4e25c8e12fcf9fc2b53cf8ee0fba293e6f9/more_itertools/more.py#L1174-L1206
def distribute(n, iterable): """Distribute the items from *iterable* among *n* smaller iterables. >>> group_1, group_2 = distribute(2, [1, 2, 3, 4, 5, 6]) >>> list(group_1) [1, 3, 5] >>> list(group_2) [2, 4, 6] If the length of *iterable* is not evenly divisible by *n*,...
[ "def", "distribute", "(", "n", ",", "iterable", ")", ":", "if", "n", "<", "1", ":", "raise", "ValueError", "(", "'n must be at least 1'", ")", "children", "=", "tee", "(", "iterable", ",", "n", ")", "return", "[", "islice", "(", "it", ",", "index", "...
Distribute the items from *iterable* among *n* smaller iterables. >>> group_1, group_2 = distribute(2, [1, 2, 3, 4, 5, 6]) >>> list(group_1) [1, 3, 5] >>> list(group_2) [2, 4, 6] If the length of *iterable* is not evenly divisible by *n*, then the length of the returned...
[ "Distribute", "the", "items", "from", "*", "iterable", "*", "among", "*", "n", "*", "smaller", "iterables", "." ]
python
train
33.30303
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py#L12319-L12331
def resource_request_encode(self, request_id, uri_type, uri, transfer_type, storage): ''' The autopilot is requesting a resource (file, binary, other type of data) request_id : Request ID. This ID should be re-used when sending back URI con...
[ "def", "resource_request_encode", "(", "self", ",", "request_id", ",", "uri_type", ",", "uri", ",", "transfer_type", ",", "storage", ")", ":", "return", "MAVLink_resource_request_message", "(", "request_id", ",", "uri_type", ",", "uri", ",", "transfer_type", ",", ...
The autopilot is requesting a resource (file, binary, other type of data) request_id : Request ID. This ID should be re-used when sending back URI contents (uint8_t) uri_type : The type of requested URI. 0 = a file via URL. 1 = a UAVCAN bi...
[ "The", "autopilot", "is", "requesting", "a", "resource", "(", "file", "binary", "other", "type", "of", "data", ")" ]
python
train
83.769231
python-cmd2/cmd2
cmd2/cmd2.py
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L3763-L3784
def enable_command(self, command: str) -> None: """ Enable a command by restoring its functions :param command: the command being enabled """ # If the commands is already enabled, then return if command not in self.disabled_commands: return help_func_...
[ "def", "enable_command", "(", "self", ",", "command", ":", "str", ")", "->", "None", ":", "# If the commands is already enabled, then return", "if", "command", "not", "in", "self", ".", "disabled_commands", ":", "return", "help_func_name", "=", "HELP_FUNC_PREFIX", "...
Enable a command by restoring its functions :param command: the command being enabled
[ "Enable", "a", "command", "by", "restoring", "its", "functions", ":", "param", "command", ":", "the", "command", "being", "enabled" ]
python
train
34.863636