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
saltstack/salt
salt/modules/boto_ec2.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L1107-L1128
def create_key(key_name, save_path, region=None, key=None, keyid=None, profile=None): ''' Creates a key and saves it to a given path. Returns the private key. CLI Example: .. code-block:: bash salt myminion boto_ec2.create_key mykey /root/ ''' conn = _get_conn(regio...
[ "def", "create_key", "(", "key_name", ",", "save_path", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", ...
Creates a key and saves it to a given path. Returns the private key. CLI Example: .. code-block:: bash salt myminion boto_ec2.create_key mykey /root/
[ "Creates", "a", "key", "and", "saves", "it", "to", "a", "given", "path", ".", "Returns", "the", "private", "key", "." ]
python
train
27.272727
dls-controls/pymalcolm
malcolm/modules/builtin/controllers/managercontroller.py
https://github.com/dls-controls/pymalcolm/blob/80ea667e4da26365a6cebc0249f52fdc744bd983/malcolm/modules/builtin/controllers/managercontroller.py#L419-L423
def save(self, designName=""): # type: (ASaveDesign) -> None """Save the current design to file""" self.try_stateful_function( ss.SAVING, ss.READY, self.do_save, designName)
[ "def", "save", "(", "self", ",", "designName", "=", "\"\"", ")", ":", "# type: (ASaveDesign) -> None", "self", ".", "try_stateful_function", "(", "ss", ".", "SAVING", ",", "ss", ".", "READY", ",", "self", ".", "do_save", ",", "designName", ")" ]
Save the current design to file
[ "Save", "the", "current", "design", "to", "file" ]
python
train
41
muatik/flask-profiler
flask_profiler/flask_profiler.py
https://github.com/muatik/flask-profiler/blob/51b4354fc14f8cfdd538ec9db98fa1cf545ccd18/flask_profiler/flask_profiler.py#L167-L241
def registerInternalRouters(app): """ These are the endpoints which are used to display measurements in the flask-profiler dashboard. Note: these should be defined after wrapping user defined endpoints via wrapAppEndpoints() :param app: Flask application instance :return: """ urlPat...
[ "def", "registerInternalRouters", "(", "app", ")", ":", "urlPath", "=", "CONF", ".", "get", "(", "\"endpointRoot\"", ",", "\"flask-profiler\"", ")", "fp", "=", "Blueprint", "(", "'flask-profiler'", ",", "__name__", ",", "url_prefix", "=", "\"/\"", "+", "urlPat...
These are the endpoints which are used to display measurements in the flask-profiler dashboard. Note: these should be defined after wrapping user defined endpoints via wrapAppEndpoints() :param app: Flask application instance :return:
[ "These", "are", "the", "endpoints", "which", "are", "used", "to", "display", "measurements", "in", "the", "flask", "-", "profiler", "dashboard", "." ]
python
train
32.36
hyperledger/indy-plenum
plenum/common/stack_manager.py
https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/common/stack_manager.py#L58-L98
def _parse_pool_transaction_file( ledger, nodeReg, cliNodeReg, nodeKeys, activeValidators, ledger_size=None): """ helper function for parseLedgerForHaAndKeys """ for _, txn in ledger.getAllTxn(to=ledger_size): if get_type(txn) == NODE: ...
[ "def", "_parse_pool_transaction_file", "(", "ledger", ",", "nodeReg", ",", "cliNodeReg", ",", "nodeKeys", ",", "activeValidators", ",", "ledger_size", "=", "None", ")", ":", "for", "_", ",", "txn", "in", "ledger", ".", "getAllTxn", "(", "to", "=", "ledger_si...
helper function for parseLedgerForHaAndKeys
[ "helper", "function", "for", "parseLedgerForHaAndKeys" ]
python
train
44.829268
google/transitfeed
feedvalidator.py
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/feedvalidator.py#L700-L705
def RunValidationFromOptions(feed, options): """Validate feed, run in profiler if in options, and return an exit code.""" if options.performance: return ProfileRunValidationOutputFromOptions(feed, options) else: return RunValidationOutputFromOptions(feed, options)
[ "def", "RunValidationFromOptions", "(", "feed", ",", "options", ")", ":", "if", "options", ".", "performance", ":", "return", "ProfileRunValidationOutputFromOptions", "(", "feed", ",", "options", ")", "else", ":", "return", "RunValidationOutputFromOptions", "(", "fe...
Validate feed, run in profiler if in options, and return an exit code.
[ "Validate", "feed", "run", "in", "profiler", "if", "in", "options", "and", "return", "an", "exit", "code", "." ]
python
train
45.5
ethereum/py-evm
eth/db/journal.py
https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/journal.py#L372-L377
def discard(self, changeset_id: uuid.UUID) -> None: """ Throws away all journaled data starting at the given changeset """ self._validate_changeset(changeset_id) self.journal.pop_changeset(changeset_id)
[ "def", "discard", "(", "self", ",", "changeset_id", ":", "uuid", ".", "UUID", ")", "->", "None", ":", "self", ".", "_validate_changeset", "(", "changeset_id", ")", "self", ".", "journal", ".", "pop_changeset", "(", "changeset_id", ")" ]
Throws away all journaled data starting at the given changeset
[ "Throws", "away", "all", "journaled", "data", "starting", "at", "the", "given", "changeset" ]
python
train
39.5
Richienb/quilt
src/quilt_lang/__init__.py
https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L817-L829
def textalign(text, maxlength, align='left'): """ Align Text When Given Full Length """ if align == 'left': return text elif align == 'centre' or align == 'center': spaces = ' ' * (int((maxlength - len(text)) / 2)) elif align == 'right': spaces = (maxlength - len(text)) ...
[ "def", "textalign", "(", "text", ",", "maxlength", ",", "align", "=", "'left'", ")", ":", "if", "align", "==", "'left'", ":", "return", "text", "elif", "align", "==", "'centre'", "or", "align", "==", "'center'", ":", "spaces", "=", "' '", "*", "(", "...
Align Text When Given Full Length
[ "Align", "Text", "When", "Given", "Full", "Length" ]
python
train
30.615385
jobovy/galpy
galpy/orbit/planarOrbit.py
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/orbit/planarOrbit.py#L221-L248
def integrate(self,t,pot,method='symplec4_c',dt=None): """ NAME: integrate PURPOSE: integrate the orbit INPUT: t - list of times at which to output (0 has to be in this!) pot - potential instance or list of instances method= 'odeint'...
[ "def", "integrate", "(", "self", ",", "t", ",", "pot", ",", "method", "=", "'symplec4_c'", ",", "dt", "=", "None", ")", ":", "if", "hasattr", "(", "self", ",", "'_orbInterp'", ")", ":", "delattr", "(", "self", ",", "'_orbInterp'", ")", "if", "hasattr...
NAME: integrate PURPOSE: integrate the orbit INPUT: t - list of times at which to output (0 has to be in this!) pot - potential instance or list of instances method= 'odeint' for scipy's odeint 'leapfrog' for a simple leapfrog imp...
[ "NAME", ":", "integrate", "PURPOSE", ":", "integrate", "the", "orbit", "INPUT", ":", "t", "-", "list", "of", "times", "at", "which", "to", "output", "(", "0", "has", "to", "be", "in", "this!", ")", "pot", "-", "potential", "instance", "or", "list", "...
python
train
44.821429
MosesSymeonidis/aggregation_builder
aggregation_builder/operators/string.py
https://github.com/MosesSymeonidis/aggregation_builder/blob/a1f4b580401d400c53206e9c020e413166254274/aggregation_builder/operators/string.py#L147-L164
def INDEX_OF_CP(string_expression, substring_expression, start=None, end=None): """ Searches a string for an occurence of a substring and returns the UTF-8 code point index (zero-based) of the first occurence. If the substring is not found, returns -1. https://docs.mongodb.com/manual/reference/operator/...
[ "def", "INDEX_OF_CP", "(", "string_expression", ",", "substring_expression", ",", "start", "=", "None", ",", "end", "=", "None", ")", ":", "res", "=", "[", "string_expression", ",", "substring_expression", "]", "if", "start", "is", "not", "None", ":", "res",...
Searches a string for an occurence of a substring and returns the UTF-8 code point index (zero-based) of the first occurence. If the substring is not found, returns -1. https://docs.mongodb.com/manual/reference/operator/aggregation/indexOfCP/ for more details :param string_expression: The string or expr...
[ "Searches", "a", "string", "for", "an", "occurence", "of", "a", "substring", "and", "returns", "the", "UTF", "-", "8", "code", "point", "index", "(", "zero", "-", "based", ")", "of", "the", "first", "occurence", ".", "If", "the", "substring", "is", "no...
python
train
54.5
numenta/nupic
src/nupic/database/client_jobs_dao.py
https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/client_jobs_dao.py#L2012-L2041
def getFieldsForActiveJobsOfType(self, jobType, fields=[]): """ Helper function for querying the models table including relevant job info where the job type matches the specified jobType. Only records for which there is a matching jobId in both tables is returned, and only the requested fields are retu...
[ "def", "getFieldsForActiveJobsOfType", "(", "self", ",", "jobType", ",", "fields", "=", "[", "]", ")", ":", "dbFields", "=", "[", "self", ".", "_jobs", ".", "pubToDBNameDict", "[", "x", "]", "for", "x", "in", "fields", "]", "dbFieldsStr", "=", "','", "...
Helper function for querying the models table including relevant job info where the job type matches the specified jobType. Only records for which there is a matching jobId in both tables is returned, and only the requested fields are returned in each result, assuming that there is not a conflict. Thi...
[ "Helper", "function", "for", "querying", "the", "models", "table", "including", "relevant", "job", "info", "where", "the", "job", "type", "matches", "the", "specified", "jobType", ".", "Only", "records", "for", "which", "there", "is", "a", "matching", "jobId",...
python
valid
44.666667
saltstack/salt
salt/states/glassfish.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/glassfish.py#L52-L71
def _is_updated(old_conf, new_conf): ''' Compare the API results to the current statefile data ''' changed = {} # Dirty json hacking to get parameters in the same format new_conf = _json_to_unicode(salt.utils.json.loads( salt.utils.json.dumps(new_conf, ensure_ascii=False))) old_conf...
[ "def", "_is_updated", "(", "old_conf", ",", "new_conf", ")", ":", "changed", "=", "{", "}", "# Dirty json hacking to get parameters in the same format", "new_conf", "=", "_json_to_unicode", "(", "salt", ".", "utils", ".", "json", ".", "loads", "(", "salt", ".", ...
Compare the API results to the current statefile data
[ "Compare", "the", "API", "results", "to", "the", "current", "statefile", "data" ]
python
train
37.5
agile4you/SchemaFactory
schema_factory/nodes.py
https://github.com/agile4you/SchemaFactory/blob/515e3fb84cddf70fc17e5d300c74c3a63539f223/schema_factory/nodes.py#L131-L139
def field_value(self, value): """Validate against NodeType. """ if not self.is_array: return self.field_type(value) if isinstance(value, (list, tuple, set)): return [self.field_type(item) for item in value] return self.field_type(value)
[ "def", "field_value", "(", "self", ",", "value", ")", ":", "if", "not", "self", ".", "is_array", ":", "return", "self", ".", "field_type", "(", "value", ")", "if", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ",", "set", ")", ")", ":...
Validate against NodeType.
[ "Validate", "against", "NodeType", "." ]
python
train
32.555556
fastai/fastai
fastai/callbacks/tracker.py
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tracker.py#L39-L51
def get_monitor_value(self): "Pick the monitored value." if self.monitor=='trn_loss' and len(self.learn.recorder.losses) == 0: return None elif len(self.learn.recorder.val_losses) == 0: return None values = {'train_loss':self.learn.recorder.losses[-1].cpu().numpy(), 'va...
[ "def", "get_monitor_value", "(", "self", ")", ":", "if", "self", ".", "monitor", "==", "'trn_loss'", "and", "len", "(", "self", ".", "learn", ".", "recorder", ".", "losses", ")", "==", "0", ":", "return", "None", "elif", "len", "(", "self", ".", "lea...
Pick the monitored value.
[ "Pick", "the", "monitored", "value", "." ]
python
train
63.769231
takuti/flurs
flurs/utils/metric.py
https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/utils/metric.py#L159-L189
def ndcg(truth, recommend, k=None): """Normalized Discounted Cumulative Grain (NDCG). Args: truth (numpy 1d array): Set of truth samples. recommend (numpy 1d array): Ordered set of recommended samples. k (int): Top-k items in `recommend` will be recommended. Returns: float:...
[ "def", "ndcg", "(", "truth", ",", "recommend", ",", "k", "=", "None", ")", ":", "if", "k", "is", "None", ":", "k", "=", "len", "(", "recommend", ")", "def", "idcg", "(", "n_possible_truth", ")", ":", "res", "=", "0.", "for", "n", "in", "range", ...
Normalized Discounted Cumulative Grain (NDCG). Args: truth (numpy 1d array): Set of truth samples. recommend (numpy 1d array): Ordered set of recommended samples. k (int): Top-k items in `recommend` will be recommended. Returns: float: NDCG.
[ "Normalized", "Discounted", "Cumulative", "Grain", "(", "NDCG", ")", "." ]
python
train
24.258065
jim-easterbrook/pyctools
src/pyctools/core/compound.py
https://github.com/jim-easterbrook/pyctools/blob/2a958665326892f45f249bebe62c2c23f306732b/src/pyctools/core/compound.py#L178-L185
def bind(self, source, dest, destmeth): """Guild compatible version of :py:meth:`connect`. This allows Pyctools compound components to be used in `Guild <https://github.com/sparkslabs/guild>`_ pipelines. """ self.connect(source, getattr(dest, destmeth))
[ "def", "bind", "(", "self", ",", "source", ",", "dest", ",", "destmeth", ")", ":", "self", ".", "connect", "(", "source", ",", "getattr", "(", "dest", ",", "destmeth", ")", ")" ]
Guild compatible version of :py:meth:`connect`. This allows Pyctools compound components to be used in `Guild <https://github.com/sparkslabs/guild>`_ pipelines.
[ "Guild", "compatible", "version", "of", ":", "py", ":", "meth", ":", "connect", "." ]
python
train
36
aws/aws-iot-device-sdk-python
AWSIoTPythonSDK/core/protocol/paho/client.py
https://github.com/aws/aws-iot-device-sdk-python/blob/f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62/AWSIoTPythonSDK/core/protocol/paho/client.py#L1257-L1293
def will_set(self, topic, payload=None, qos=0, retain=False): """Set a Will to be sent by the broker in case the client disconnects unexpectedly. This must be called before connect() to have any effect. topic: The topic that the will message should be published on. payload: The message...
[ "def", "will_set", "(", "self", ",", "topic", ",", "payload", "=", "None", ",", "qos", "=", "0", ",", "retain", "=", "False", ")", ":", "if", "topic", "is", "None", "or", "len", "(", "topic", ")", "==", "0", ":", "raise", "ValueError", "(", "'Inv...
Set a Will to be sent by the broker in case the client disconnects unexpectedly. This must be called before connect() to have any effect. topic: The topic that the will message should be published on. payload: The message to send as a will. If not given, or set to None a zero length me...
[ "Set", "a", "Will", "to", "be", "sent", "by", "the", "broker", "in", "case", "the", "client", "disconnects", "unexpectedly", "." ]
python
train
45.756757
google/grr
grr/server/grr_response_server/aff4.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/aff4.py#L1880-L1903
def Close(self): """Close and destroy the object. This is similar to Flush, but does not maintain object validity. Hence the object should not be interacted with after Close(). Raises: LockError: The lease for this object has expired. """ if self.locked and self.CheckLease() == 0: ...
[ "def", "Close", "(", "self", ")", ":", "if", "self", ".", "locked", "and", "self", ".", "CheckLease", "(", ")", "==", "0", ":", "raise", "LockError", "(", "\"Can not update lease that has already expired.\"", ")", "self", ".", "_WriteAttributes", "(", ")", "...
Close and destroy the object. This is similar to Flush, but does not maintain object validity. Hence the object should not be interacted with after Close(). Raises: LockError: The lease for this object has expired.
[ "Close", "and", "destroy", "the", "object", "." ]
python
train
29.416667
fastai/fastai
fastai/vision/image.py
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L416-L424
def rle_decode(mask_rle:str, shape:Tuple[int,int])->NPArrayMask: "Return an image array from run-length encoded string `mask_rle` with `shape`." s = mask_rle.split() starts, lengths = [np.asarray(x, dtype=int) for x in (s[0:][::2], s[1:][::2])] starts -= 1 ends = starts + lengths img = np.zeros(...
[ "def", "rle_decode", "(", "mask_rle", ":", "str", ",", "shape", ":", "Tuple", "[", "int", ",", "int", "]", ")", "->", "NPArrayMask", ":", "s", "=", "mask_rle", ".", "split", "(", ")", "starts", ",", "lengths", "=", "[", "np", ".", "asarray", "(", ...
Return an image array from run-length encoded string `mask_rle` with `shape`.
[ "Return", "an", "image", "array", "from", "run", "-", "length", "encoded", "string", "mask_rle", "with", "shape", "." ]
python
train
47.666667
noumar/iso639
iso639/iso639.py
https://github.com/noumar/iso639/blob/2175cf04b8b8cec79d99a6c4ad31295d67c22cd6/iso639/iso639.py#L230-L256
def retired(self): """ Function for generating retired languages. Returns a dict('code', (datetime, [language, ...], 'description')). """ def gen(): import csv import re from datetime import datetime from pkg_resources import resource_file...
[ "def", "retired", "(", "self", ")", ":", "def", "gen", "(", ")", ":", "import", "csv", "import", "re", "from", "datetime", "import", "datetime", "from", "pkg_resources", "import", "resource_filename", "with", "open", "(", "resource_filename", "(", "__package__...
Function for generating retired languages. Returns a dict('code', (datetime, [language, ...], 'description')).
[ "Function", "for", "generating", "retired", "languages", ".", "Returns", "a", "dict", "(", "code", "(", "datetime", "[", "language", "...", "]", "description", "))", "." ]
python
train
38.148148
apple/turicreate
src/external/coremltools_wrap/coremltools/coremltools/models/neural_network.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/models/neural_network.py#L2226-L2268
def add_mvn(self, name, input_name, output_name, across_channels = True, normalize_variance = True, epsilon = 1e-5): """ Add an MVN (mean variance normalization) layer. Computes mean, variance and normalizes the input. Parameters ---------- name: str The name of this...
[ "def", "add_mvn", "(", "self", ",", "name", ",", "input_name", ",", "output_name", ",", "across_channels", "=", "True", ",", "normalize_variance", "=", "True", ",", "epsilon", "=", "1e-5", ")", ":", "spec", "=", "self", ".", "spec", "nn_spec", "=", "self...
Add an MVN (mean variance normalization) layer. Computes mean, variance and normalizes the input. Parameters ---------- name: str The name of this layer. input_name: str The input blob name of this layer. output_name: str The output blob name...
[ "Add", "an", "MVN", "(", "mean", "variance", "normalization", ")", "layer", ".", "Computes", "mean", "variance", "and", "normalizes", "the", "input", "." ]
python
train
30.697674
cloudendpoints/endpoints-management-python
endpoints_management/control/vendor/py3/sched.py
https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/vendor/py3/sched.py#L85-L92
def enter(self, delay, priority, action, argument=(), kwargs=_sentinel): """A variant that specifies the time as a relative time. This is actually the more commonly used interface. """ time = self.timefunc() + delay return self.enterabs(time, priority, action, argument, kwargs)
[ "def", "enter", "(", "self", ",", "delay", ",", "priority", ",", "action", ",", "argument", "=", "(", ")", ",", "kwargs", "=", "_sentinel", ")", ":", "time", "=", "self", ".", "timefunc", "(", ")", "+", "delay", "return", "self", ".", "enterabs", "...
A variant that specifies the time as a relative time. This is actually the more commonly used interface.
[ "A", "variant", "that", "specifies", "the", "time", "as", "a", "relative", "time", "." ]
python
train
39.125
PhilippeFerreiraDeSousa/bitext-matching
lib/enpc_aligner/words_correspondence.py
https://github.com/PhilippeFerreiraDeSousa/bitext-matching/blob/195c3e98775cfa5e63e4bb0bb1da6f741880d980/lib/enpc_aligner/words_correspondence.py#L12-L74
def _alignment(elist, flist, e2f, f2e): ''' elist, flist wordlist for each language e2f translatoin alignment from e to f alignment is [(e, f)] f2e translatoin alignment from f to e alignment is [(e, f)] return alignment: {...
[ "def", "_alignment", "(", "elist", ",", "flist", ",", "e2f", ",", "f2e", ")", ":", "neighboring", "=", "{", "(", "-", "1", ",", "0", ")", ",", "(", "0", ",", "-", "1", ")", ",", "(", "1", ",", "0", ")", ",", "(", "0", ",", "1", ")", ","...
elist, flist wordlist for each language e2f translatoin alignment from e to f alignment is [(e, f)] f2e translatoin alignment from f to e alignment is [(e, f)] return alignment: {(f, e)} flist ---------------...
[ "elist", "flist", "wordlist", "for", "each", "language", "e2f", "translatoin", "alignment", "from", "e", "to", "f", "alignment", "is", "[", "(", "e", "f", ")", "]", "f2e", "translatoin", "alignment", "from", "f", "to", "e", "alignment", "is", "[", "(", ...
python
train
34.984127
edx/i18n-tools
i18n/extract.py
https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/extract.py#L184-L216
def fix_header(pofile): """ Replace default headers with edX headers """ # By default, django-admin.py makemessages creates this header: # # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE...
[ "def", "fix_header", "(", "pofile", ")", ":", "# By default, django-admin.py makemessages creates this header:", "#", "# SOME DESCRIPTIVE TITLE.", "# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER", "# This file is distributed under the same license as the PACKAGE package.", "# FIRS...
Replace default headers with edX headers
[ "Replace", "default", "headers", "with", "edX", "headers" ]
python
train
37.424242
rigetti/grove
grove/pyqaoa/utils.py
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/pyqaoa/utils.py#L18-L27
def isclose(a, b, rel_tol=1e-10, abs_tol=0.0): """ Compares two parameter values. :param a: First parameter :param b: Second parameter :param rel_tol: Relative tolerance :param abs_tol: Absolute tolerance :return: Boolean telling whether or not the parameters are close enough to be the same ...
[ "def", "isclose", "(", "a", ",", "b", ",", "rel_tol", "=", "1e-10", ",", "abs_tol", "=", "0.0", ")", ":", "return", "abs", "(", "a", "-", "b", ")", "<=", "max", "(", "rel_tol", "*", "max", "(", "abs", "(", "a", ")", ",", "abs", "(", "b", ")...
Compares two parameter values. :param a: First parameter :param b: Second parameter :param rel_tol: Relative tolerance :param abs_tol: Absolute tolerance :return: Boolean telling whether or not the parameters are close enough to be the same
[ "Compares", "two", "parameter", "values", ".", ":", "param", "a", ":", "First", "parameter", ":", "param", "b", ":", "Second", "parameter", ":", "param", "rel_tol", ":", "Relative", "tolerance", ":", "param", "abs_tol", ":", "Absolute", "tolerance", ":", "...
python
train
38.5
codelv/enaml-native
src/enamlnative/android/android_popup_window.py
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_popup_window.py#L70-L80
def create_widget(self): """ Create the underlying widget. A dialog is not a subclass of view, hence we don't set name as widget or children will try to use it as their parent. """ d = self.declaration style = d.style or '@style/Widget.DeviceDefault.PopupMenu' s...
[ "def", "create_widget", "(", "self", ")", ":", "d", "=", "self", ".", "declaration", "style", "=", "d", ".", "style", "or", "'@style/Widget.DeviceDefault.PopupMenu'", "self", ".", "window", "=", "PopupWindow", "(", "self", ".", "get_context", "(", ")", ",", ...
Create the underlying widget. A dialog is not a subclass of view, hence we don't set name as widget or children will try to use it as their parent.
[ "Create", "the", "underlying", "widget", "." ]
python
train
36.272727
cloudera/impyla
impala/_thrift_gen/hive_metastore/ThriftHiveMetastore.py
https://github.com/cloudera/impyla/blob/547fa2ba3b6151e2a98b3544301471a643212dc3/impala/_thrift_gen/hive_metastore/ThriftHiveMetastore.py#L5147-L5155
def revoke_role(self, role_name, principal_name, principal_type): """ Parameters: - role_name - principal_name - principal_type """ self.send_revoke_role(role_name, principal_name, principal_type) return self.recv_revoke_role()
[ "def", "revoke_role", "(", "self", ",", "role_name", ",", "principal_name", ",", "principal_type", ")", ":", "self", ".", "send_revoke_role", "(", "role_name", ",", "principal_name", ",", "principal_type", ")", "return", "self", ".", "recv_revoke_role", "(", ")"...
Parameters: - role_name - principal_name - principal_type
[ "Parameters", ":", "-", "role_name", "-", "principal_name", "-", "principal_type" ]
python
train
28.222222
python-diamond/Diamond
src/collectors/endecadgraph/endecadgraph.py
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/endecadgraph/endecadgraph.py#L61-L72
def get_default_config(self): """ Returns the default collector settings """ config = super(EndecaDgraphCollector, self).get_default_config() config.update({ 'path': 'endeca.dgraph', 'host': 'localhost', 'port': 8080, 'timeout': 1, ...
[ "def", "get_default_config", "(", "self", ")", ":", "config", "=", "super", "(", "EndecaDgraphCollector", ",", "self", ")", ".", "get_default_config", "(", ")", "config", ".", "update", "(", "{", "'path'", ":", "'endeca.dgraph'", ",", "'host'", ":", "'localh...
Returns the default collector settings
[ "Returns", "the", "default", "collector", "settings" ]
python
train
28.416667
senaite/senaite.core
bika/lims/utils/__init__.py
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/utils/__init__.py#L754-L763
def get_registry_value(key, default=None): """ Gets the utility for IRegistry and returns the value for the key passed in. If there is no value for the key passed in, returns default value :param key: the key in the registry to look for :param default: default value if the key is not registered ...
[ "def", "get_registry_value", "(", "key", ",", "default", "=", "None", ")", ":", "registry", "=", "queryUtility", "(", "IRegistry", ")", "return", "registry", ".", "get", "(", "key", ",", "default", ")" ]
Gets the utility for IRegistry and returns the value for the key passed in. If there is no value for the key passed in, returns default value :param key: the key in the registry to look for :param default: default value if the key is not registered :return: value in the registry for the key passed in
[ "Gets", "the", "utility", "for", "IRegistry", "and", "returns", "the", "value", "for", "the", "key", "passed", "in", ".", "If", "there", "is", "no", "value", "for", "the", "key", "passed", "in", "returns", "default", "value", ":", "param", "key", ":", ...
python
train
44.8
iotile/coretools
iotileemulate/iotile/emulate/virtual/emulated_tile.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/emulated_tile.py#L446-L479
def parse_size_name(type_name): """Calculate size and encoding from a type name. This method takes a C-style type string like uint8_t[10] and returns - the total size in bytes - the unit size of each member (if it's an array) - the scruct.{pack,unpack} format code for decoding the base type - w...
[ "def", "parse_size_name", "(", "type_name", ")", ":", "if", "' '", "in", "type_name", ":", "raise", "ArgumentError", "(", "\"There should not be a space in config variable type specifier\"", ",", "specifier", "=", "type_name", ")", "variable", "=", "False", "count", "...
Calculate size and encoding from a type name. This method takes a C-style type string like uint8_t[10] and returns - the total size in bytes - the unit size of each member (if it's an array) - the scruct.{pack,unpack} format code for decoding the base type - whether it is an array.
[ "Calculate", "size", "and", "encoding", "from", "a", "type", "name", "." ]
python
train
34.294118
drdoctr/doctr
doctr/local.py
https://github.com/drdoctr/doctr/blob/0f19ff78c8239efcc98d417f36b0a31d9be01ba5/doctr/local.py#L86-L109
def encrypt_to_file(contents, filename): """ Encrypts ``contents`` and writes it to ``filename``. ``contents`` should be a bytes string. ``filename`` should end with ``.enc``. Returns the secret key used for the encryption. Decrypt the file with :func:`doctr.travis.decrypt_file`. """ ...
[ "def", "encrypt_to_file", "(", "contents", ",", "filename", ")", ":", "if", "not", "filename", ".", "endswith", "(", "'.enc'", ")", ":", "raise", "ValueError", "(", "\"%s does not end with .enc\"", "%", "filename", ")", "key", "=", "Fernet", ".", "generate_key...
Encrypts ``contents`` and writes it to ``filename``. ``contents`` should be a bytes string. ``filename`` should end with ``.enc``. Returns the secret key used for the encryption. Decrypt the file with :func:`doctr.travis.decrypt_file`.
[ "Encrypts", "contents", "and", "writes", "it", "to", "filename", "." ]
python
train
24.166667
saltstack/salt
salt/modules/yumpkg.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L156-L170
def _call_yum(args, **kwargs): ''' Call yum/dnf. ''' params = {'output_loglevel': 'trace', 'python_shell': False, 'env': salt.utils.environment.get_module_environment(globals())} params.update(kwargs) cmd = [] if salt.utils.systemd.has_scope(__context__) and __sal...
[ "def", "_call_yum", "(", "args", ",", "*", "*", "kwargs", ")", ":", "params", "=", "{", "'output_loglevel'", ":", "'trace'", ",", "'python_shell'", ":", "False", ",", "'env'", ":", "salt", ".", "utils", ".", "environment", ".", "get_module_environment", "(...
Call yum/dnf.
[ "Call", "yum", "/", "dnf", "." ]
python
train
32.6
mlperf/training
rnn_translator/pytorch/seq2seq/data/dataset.py
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/data/dataset.py#L137-L155
def filter_data(self, min_len, max_len): """ Preserves only samples which satisfy the following inequality: min_len <= sample sequence length <= max_len :param min_len: minimum sequence length :param max_len: maximum sequence length """ logging.info(f'Filteri...
[ "def", "filter_data", "(", "self", ",", "min_len", ",", "max_len", ")", ":", "logging", ".", "info", "(", "f'Filtering data, min len: {min_len}, max len: {max_len}'", ")", "initial_len", "=", "len", "(", "self", ".", "src", ")", "filtered_src", "=", "[", "]", ...
Preserves only samples which satisfy the following inequality: min_len <= sample sequence length <= max_len :param min_len: minimum sequence length :param max_len: maximum sequence length
[ "Preserves", "only", "samples", "which", "satisfy", "the", "following", "inequality", ":", "min_len", "<", "=", "sample", "sequence", "length", "<", "=", "max_len" ]
python
train
35.631579
floydhub/floyd-cli
floyd/cli/data.py
https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/data.py#L148-L196
def clone(id, path): """ - Download all files in a dataset or from a Job output Eg: alice/projects/mnist/1/files, alice/projects/mnist/1/output or alice/dataset/mnist-data/1/ Using /output will download the files that are saved at the end of the job. Note: This will download the files that are sa...
[ "def", "clone", "(", "id", ",", "path", ")", ":", "data_source", "=", "get_data_object", "(", "id", ",", "use_data_config", "=", "False", ")", "if", "not", "data_source", ":", "if", "'output'", "in", "id", ":", "floyd_logger", ".", "info", "(", "\"Note: ...
- Download all files in a dataset or from a Job output Eg: alice/projects/mnist/1/files, alice/projects/mnist/1/output or alice/dataset/mnist-data/1/ Using /output will download the files that are saved at the end of the job. Note: This will download the files that are saved at the end of the job. ...
[ "-", "Download", "all", "files", "in", "a", "dataset", "or", "from", "a", "Job", "output" ]
python
train
42.306122
ND-CSE-30151/tock
tock/grammars.py
https://github.com/ND-CSE-30151/tock/blob/b8d21901aaf0e6ac913c2afa855f5b5a882a16c6/tock/grammars.py#L76-L119
def remove_useless(self): """Returns a new grammar containing just useful rules.""" if not self.is_contextfree(): raise ValueError("grammar must be context-free") by_lhs = collections.defaultdict(list) by_rhs = collections.defaultdict(list) for [lhs], rhs in self.rule...
[ "def", "remove_useless", "(", "self", ")", ":", "if", "not", "self", ".", "is_contextfree", "(", ")", ":", "raise", "ValueError", "(", "\"grammar must be context-free\"", ")", "by_lhs", "=", "collections", ".", "defaultdict", "(", "list", ")", "by_rhs", "=", ...
Returns a new grammar containing just useful rules.
[ "Returns", "a", "new", "grammar", "containing", "just", "useful", "rules", "." ]
python
train
36.25
Chilipp/psyplot
psyplot/project.py
https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/project.py#L1135-L1322
def load_project(cls, fname, auto_update=None, make_plot=True, draw=False, alternative_axes=None, main=False, encoding=None, enable_post=False, new_fig=True, clear=None, **kwargs): """ Load a project from a file or dict This classme...
[ "def", "load_project", "(", "cls", ",", "fname", ",", "auto_update", "=", "None", ",", "make_plot", "=", "True", ",", "draw", "=", "False", ",", "alternative_axes", "=", "None", ",", "main", "=", "False", ",", "encoding", "=", "None", ",", "enable_post",...
Load a project from a file or dict This classmethod allows to load a project that has been stored using the :meth:`save_project` method and reads all the data and creates the figures. Since the data is stored in external files when saving a project, make sure that the data is a...
[ "Load", "a", "project", "from", "a", "file", "or", "dict" ]
python
train
44.489362
klmitch/turnstile
turnstile/tools.py
https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/tools.py#L712-L803
def turnstile_command(conf_file, command, arguments=[], channel=None, debug=False): """ Issue a command to all running control daemons. :param conf_file: Name of the configuration file. :param command: The command to execute. Note that 'ping' is handled specia...
[ "def", "turnstile_command", "(", "conf_file", ",", "command", ",", "arguments", "=", "[", "]", ",", "channel", "=", "None", ",", "debug", "=", "False", ")", ":", "# Connect to the database...", "conf", "=", "config", ".", "Config", "(", "conf_file", "=", "...
Issue a command to all running control daemons. :param conf_file: Name of the configuration file. :param command: The command to execute. Note that 'ping' is handled specially; in particular, the "channel" parameter is implied. (A random value will be ...
[ "Issue", "a", "command", "to", "all", "running", "control", "daemons", "." ]
python
train
35.336957
sendwithus/sendwithus_python
sendwithus/__init__.py
https://github.com/sendwithus/sendwithus_python/blob/8ae50d514febd44f7d9be3c838b4d92f99412832/sendwithus/__init__.py#L252-L254
def create_email(self, name, subject, html, text=''): """ [DECPRECATED] API call to create an email """ return self.create_template(name, subject, html, text)
[ "def", "create_email", "(", "self", ",", "name", ",", "subject", ",", "html", ",", "text", "=", "''", ")", ":", "return", "self", ".", "create_template", "(", "name", ",", "subject", ",", "html", ",", "text", ")" ]
[DECPRECATED] API call to create an email
[ "[", "DECPRECATED", "]", "API", "call", "to", "create", "an", "email" ]
python
valid
57.333333
Yubico/python-pyhsm
pyhsm/hmac_cmd.py
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/hmac_cmd.py#L110-L122
def _raw_pack(key_handle, flags, data): """ Common code for packing payload to YHSM_HMAC_SHA1_GENERATE command. """ # #define YHSM_HMAC_RESET 0x01 // Flag to indicate reset at first packet # #define YHSM_HMAC_FINAL 0x02 // Flag to indicate that the hash shall be calculated ...
[ "def", "_raw_pack", "(", "key_handle", ",", "flags", ",", "data", ")", ":", "# #define YHSM_HMAC_RESET 0x01 // Flag to indicate reset at first packet", "# #define YHSM_HMAC_FINAL 0x02 // Flag to indicate that the hash shall be calculated", "# typedef struct {", "# ...
Common code for packing payload to YHSM_HMAC_SHA1_GENERATE command.
[ "Common", "code", "for", "packing", "payload", "to", "YHSM_HMAC_SHA1_GENERATE", "command", "." ]
python
train
53
GNS3/gns3-server
gns3server/compute/vmware/vmware_vm.py
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/vmware_vm.py#L399-L411
def _stop_ubridge_capture(self, adapter_number): """ Stop a packet capture in uBridge. :param adapter_number: adapter number """ vnet = "ethernet{}.vnet".format(adapter_number) if vnet not in self._vmx_pairs: raise VMwareError("vnet {} not in VMX file".forma...
[ "def", "_stop_ubridge_capture", "(", "self", ",", "adapter_number", ")", ":", "vnet", "=", "\"ethernet{}.vnet\"", ".", "format", "(", "adapter_number", ")", "if", "vnet", "not", "in", "self", ".", "_vmx_pairs", ":", "raise", "VMwareError", "(", "\"vnet {} not in...
Stop a packet capture in uBridge. :param adapter_number: adapter number
[ "Stop", "a", "packet", "capture", "in", "uBridge", "." ]
python
train
40.846154
tensorflow/tensor2tensor
tensor2tensor/models/revnet.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/revnet.py#L386-L400
def revnet_cifar_base(): """Tiny hparams suitable for CIFAR/etc.""" hparams = revnet_base() hparams.num_channels_init_block = 32 hparams.first_batch_norm = [False, True, True] hparams.init_stride = 1 hparams.init_kernel_size = 3 hparams.init_maxpool = False hparams.strides = [1, 2, 2] hparams.batch_si...
[ "def", "revnet_cifar_base", "(", ")", ":", "hparams", "=", "revnet_base", "(", ")", "hparams", ".", "num_channels_init_block", "=", "32", "hparams", ".", "first_batch_norm", "=", "[", "False", ",", "True", ",", "True", "]", "hparams", ".", "init_stride", "="...
Tiny hparams suitable for CIFAR/etc.
[ "Tiny", "hparams", "suitable", "for", "CIFAR", "/", "etc", "." ]
python
train
29.466667
demurgos/py-pathmatch
pathmatch/gitmatch.py
https://github.com/demurgos/py-pathmatch/blob/70b3aa99ee34da8b80b6ec6340862b760159d2a1/pathmatch/gitmatch.py#L30-L69
def normalize_path(path, base_path=u'/', is_dir=None): u""" Normalize a path to use it with a gitmatch pattern. This ensures that the separators are forward slashes. If a path is rooted (starts with a slash), it has to be a subdirectory of `base_path`. The path root is then changed to be based of `b...
[ "def", "normalize_path", "(", "path", ",", "base_path", "=", "u'/'", ",", "is_dir", "=", "None", ")", ":", "path", "=", "posixpath", ".", "normpath", "(", "path", ")", "base_path", "=", "posixpath", ".", "normpath", "(", "base_path", ")", "if", "len", ...
u""" Normalize a path to use it with a gitmatch pattern. This ensures that the separators are forward slashes. If a path is rooted (starts with a slash), it has to be a subdirectory of `base_path`. The path root is then changed to be based of `base_path`. :type path: text_type :param path: A PO...
[ "u", "Normalize", "a", "path", "to", "use", "it", "with", "a", "gitmatch", "pattern", ".", "This", "ensures", "that", "the", "separators", "are", "forward", "slashes", ".", "If", "a", "path", "is", "rooted", "(", "starts", "with", "a", "slash", ")", "i...
python
train
36.425
cytoscape/py2cytoscape
py2cytoscape/cyrest/styles.py
https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/styles.py#L46-L59
def getSingleVisualProperty(self, visualProperty, verbose=None): """ Return the Visual Property specified by the `visualProperty` parameter. Additional details on common Visual Properties can be found in the [Basic Visual Lexicon JavaDoc API](http://chianti.ucsd.edu/cytoscape-3.6.1/API/...
[ "def", "getSingleVisualProperty", "(", "self", ",", "visualProperty", ",", "verbose", "=", "None", ")", ":", "response", "=", "api", "(", "url", "=", "self", ".", "___url", "+", "'styles/visualproperties/'", "+", "str", "(", "visualProperty", ")", "+", "''",...
Return the Visual Property specified by the `visualProperty` parameter. Additional details on common Visual Properties can be found in the [Basic Visual Lexicon JavaDoc API](http://chianti.ucsd.edu/cytoscape-3.6.1/API/org/cytoscape/view/presentation/property/BasicVisualLexicon.html) :param vis...
[ "Return", "the", "Visual", "Property", "specified", "by", "the", "visualProperty", "parameter", ".", "Additional", "details", "on", "common", "Visual", "Properties", "can", "be", "found", "in", "the", "[", "Basic", "Visual", "Lexicon", "JavaDoc", "API", "]", "...
python
train
49
daethnir/authprogs
authprogs/authprogs.py
https://github.com/daethnir/authprogs/blob/0b1e13a609ebeabdb0f10d11fc5dc6e0b20c0343/authprogs/authprogs.py#L344-L368
def find_match_command(self, rule): """Return a matching (possibly munged) command, if found in rule.""" command_string = rule['command'] command_list = command_string.split() self.logdebug('comparing "%s" to "%s"\n' % (command_list, self.original_command_list)) ...
[ "def", "find_match_command", "(", "self", ",", "rule", ")", ":", "command_string", "=", "rule", "[", "'command'", "]", "command_list", "=", "command_string", ".", "split", "(", ")", "self", ".", "logdebug", "(", "'comparing \"%s\" to \"%s\"\\n'", "%", "(", "co...
Return a matching (possibly munged) command, if found in rule.
[ "Return", "a", "matching", "(", "possibly", "munged", ")", "command", "if", "found", "in", "rule", "." ]
python
train
43.44
junzis/pyModeS
pyModeS/decoder/adsb.py
https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/adsb.py#L441-L465
def nac_v(msg): """Calculate NACv, Navigation Accuracy Category - Velocity Args: msg (string): 28 bytes hexadecimal message string, TC = 19 Returns: int or string: 95% horizontal accuracy bounds for velocity, Horizontal Figure of Merit int or string: 95% vertical accuracy bounds fo...
[ "def", "nac_v", "(", "msg", ")", ":", "tc", "=", "typecode", "(", "msg", ")", "if", "tc", "!=", "19", ":", "raise", "RuntimeError", "(", "\"%s: Not an airborne velocity message, expecting TC = 19\"", "%", "msg", ")", "msgbin", "=", "common", ".", "hex2bin", ...
Calculate NACv, Navigation Accuracy Category - Velocity Args: msg (string): 28 bytes hexadecimal message string, TC = 19 Returns: int or string: 95% horizontal accuracy bounds for velocity, Horizontal Figure of Merit int or string: 95% vertical accuracy bounds for velocity, Vertical Fi...
[ "Calculate", "NACv", "Navigation", "Accuracy", "Category", "-", "Velocity" ]
python
train
30.16
pyBookshelf/bookshelf
bookshelf/api_v1.py
https://github.com/pyBookshelf/bookshelf/blob/a6770678e735de95b194f6e6989223970db5f654/bookshelf/api_v1.py#L361-L372
def create_server(cloud, **kwargs): """ Create a new instance """ if cloud == 'ec2': _create_server_ec2(**kwargs) elif cloud == 'rackspace': _create_server_rackspace(**kwargs) elif cloud == 'gce': _create_server_gce(**kwargs) else: raise ValueError("Unknow...
[ "def", "create_server", "(", "cloud", ",", "*", "*", "kwargs", ")", ":", "if", "cloud", "==", "'ec2'", ":", "_create_server_ec2", "(", "*", "*", "kwargs", ")", "elif", "cloud", "==", "'rackspace'", ":", "_create_server_rackspace", "(", "*", "*", "kwargs", ...
Create a new instance
[ "Create", "a", "new", "instance" ]
python
train
28.416667
emory-libraries/eulcommon
eulcommon/djangoextras/auth/decorators.py
https://github.com/emory-libraries/eulcommon/blob/dc63a9b3b5e38205178235e0d716d1b28158d3a9/eulcommon/djangoextras/auth/decorators.py#L132-L147
def permission_required_with_ajax(perm, login_url=None): """ Decorator for views that checks whether a user has a particular permission enabled, redirecting to the log-in page if necessary, but returns a special response for ajax requests. See :meth:`eulcore.django.auth.decorators.user_passes_test_...
[ "def", "permission_required_with_ajax", "(", "perm", ",", "login_url", "=", "None", ")", ":", "return", "user_passes_test_with_ajax", "(", "lambda", "u", ":", "u", ".", "has_perm", "(", "perm", ")", ",", "login_url", "=", "login_url", ")" ]
Decorator for views that checks whether a user has a particular permission enabled, redirecting to the log-in page if necessary, but returns a special response for ajax requests. See :meth:`eulcore.django.auth.decorators.user_passes_test_with_ajax`. Usage is the same as :meth:`django.contrib.auth....
[ "Decorator", "for", "views", "that", "checks", "whether", "a", "user", "has", "a", "particular", "permission", "enabled", "redirecting", "to", "the", "log", "-", "in", "page", "if", "necessary", "but", "returns", "a", "special", "response", "for", "ajax", "r...
python
train
39.5625
yyuu/botornado
boto/s3/bucket.py
https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/s3/bucket.py#L1233-L1242
def get_website_endpoint(self): """ Returns the fully qualified hostname to use is you want to access this bucket as a website. This doesn't validate whether the bucket has been correctly configured as a website or not. """ l = [self.name] l.append(S3WebsiteEndpo...
[ "def", "get_website_endpoint", "(", "self", ")", ":", "l", "=", "[", "self", ".", "name", "]", "l", ".", "append", "(", "S3WebsiteEndpointTranslate", ".", "translate_region", "(", "self", ".", "get_location", "(", ")", ")", ")", "l", ".", "append", "(", ...
Returns the fully qualified hostname to use is you want to access this bucket as a website. This doesn't validate whether the bucket has been correctly configured as a website or not.
[ "Returns", "the", "fully", "qualified", "hostname", "to", "use", "is", "you", "want", "to", "access", "this", "bucket", "as", "a", "website", ".", "This", "doesn", "t", "validate", "whether", "the", "bucket", "has", "been", "correctly", "configured", "as", ...
python
train
45.4
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/_package.py
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/_package.py#L722-L739
def batch_predict(training_dir, prediction_input_file, output_dir, mode, batch_size=16, shard_files=True, output_format='csv', cloud=False): """Blocking versoin of batch_predict. See documentation of batch_prediction_async. """ job = batch_predict_async( training_dir=t...
[ "def", "batch_predict", "(", "training_dir", ",", "prediction_input_file", ",", "output_dir", ",", "mode", ",", "batch_size", "=", "16", ",", "shard_files", "=", "True", ",", "output_format", "=", "'csv'", ",", "cloud", "=", "False", ")", ":", "job", "=", ...
Blocking versoin of batch_predict. See documentation of batch_prediction_async.
[ "Blocking", "versoin", "of", "batch_predict", "." ]
python
train
32.388889
pycontribs/pyrax
pyrax/cloudblockstorage.py
https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/cloudblockstorage.py#L501-L509
def create_snapshot(self, volume, name=None, description=None, force=False): """ Creates a snapshot of the volume, with an optional name and description. Normally snapshots will not happen if the volume is attached. To override this default behavior, pass force=True. """ ...
[ "def", "create_snapshot", "(", "self", ",", "volume", ",", "name", "=", "None", ",", "description", "=", "None", ",", "force", "=", "False", ")", ":", "return", "self", ".", "_snapshot_manager", ".", "create", "(", "volume", "=", "volume", ",", "name", ...
Creates a snapshot of the volume, with an optional name and description. Normally snapshots will not happen if the volume is attached. To override this default behavior, pass force=True.
[ "Creates", "a", "snapshot", "of", "the", "volume", "with", "an", "optional", "name", "and", "description", "." ]
python
train
47.666667
spyder-ide/spyder
spyder/plugins/editor/utils/editor.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L618-L622
def clear_selection(self): """Clears text cursor selection.""" text_cursor = self._editor.textCursor() text_cursor.clearSelection() self._editor.setTextCursor(text_cursor)
[ "def", "clear_selection", "(", "self", ")", ":", "text_cursor", "=", "self", ".", "_editor", ".", "textCursor", "(", ")", "text_cursor", ".", "clearSelection", "(", ")", "self", ".", "_editor", ".", "setTextCursor", "(", "text_cursor", ")" ]
Clears text cursor selection.
[ "Clears", "text", "cursor", "selection", "." ]
python
train
39.8
django-blog-zinnia/wordpress2zinnia
zinnia_wordpress/management/commands/wp2zinnia.py
https://github.com/django-blog-zinnia/wordpress2zinnia/blob/656df6d431418a660f0e590d2226af5e6dd7a3e6/zinnia_wordpress/management/commands/wp2zinnia.py#L134-L158
def import_authors(self, tree): """ Retrieve all the authors used in posts and convert it to new or existing author and return the conversion. """ self.write_out(self.style.STEP('- Importing authors\n')) post_authors = set() for item in tree.findall('chan...
[ "def", "import_authors", "(", "self", ",", "tree", ")", ":", "self", ".", "write_out", "(", "self", ".", "style", ".", "STEP", "(", "'- Importing authors\\n'", ")", ")", "post_authors", "=", "set", "(", ")", "for", "item", "in", "tree", ".", "findall", ...
Retrieve all the authors used in posts and convert it to new or existing author and return the conversion.
[ "Retrieve", "all", "the", "authors", "used", "in", "posts", "and", "convert", "it", "to", "new", "or", "existing", "author", "and", "return", "the", "conversion", "." ]
python
train
36.04
knipknap/exscript
Exscript/host.py
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/host.py#L317-L328
def set(self, name, value): """ Stores the given variable/value in the object for later retrieval. :type name: string :param name: The name of the variable. :type value: object :param value: The value of the variable. """ if self.vars is None: ...
[ "def", "set", "(", "self", ",", "name", ",", "value", ")", ":", "if", "self", ".", "vars", "is", "None", ":", "self", ".", "vars", "=", "{", "}", "self", ".", "vars", "[", "name", "]", "=", "value" ]
Stores the given variable/value in the object for later retrieval. :type name: string :param name: The name of the variable. :type value: object :param value: The value of the variable.
[ "Stores", "the", "given", "variable", "/", "value", "in", "the", "object", "for", "later", "retrieval", "." ]
python
train
29.833333
heitzmann/gdspy
gdspy/__init__.py
https://github.com/heitzmann/gdspy/blob/2c8d1313248c544e2066d19095b7ad7158c79bc9/gdspy/__init__.py#L1103-L1230
def arc(self, radius, initial_angle, final_angle, number_of_points=0.01, max_points=199, final_width=None, final_distance=None, layer=0, datatype=0): """ Add a curved section to the path. ...
[ "def", "arc", "(", "self", ",", "radius", ",", "initial_angle", ",", "final_angle", ",", "number_of_points", "=", "0.01", ",", "max_points", "=", "199", ",", "final_width", "=", "None", ",", "final_distance", "=", "None", ",", "layer", "=", "0", ",", "da...
Add a curved section to the path. Parameters ---------- radius : number Central radius of the section. initial_angle : number Initial angle of the curve (in *radians*). final_angle : number Final angle of the curve (in *radians*). numb...
[ "Add", "a", "curved", "section", "to", "the", "path", "." ]
python
train
45.1875
onnx/onnx
onnx/external_data_helper.py
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/external_data_helper.py#L197-L209
def remove_external_data_field(tensor, field_key): # type: (TensorProto, Text) -> None """ Remove a field from a Tensor's external_data key-value store. Modifies tensor object in place. @params tensor: Tensor object from which value will be removed field_key: The key of the field to be remove...
[ "def", "remove_external_data_field", "(", "tensor", ",", "field_key", ")", ":", "# type: (TensorProto, Text) -> None", "for", "(", "i", ",", "field", ")", "in", "enumerate", "(", "tensor", ".", "external_data", ")", ":", "if", "field", ".", "key", "==", "field...
Remove a field from a Tensor's external_data key-value store. Modifies tensor object in place. @params tensor: Tensor object from which value will be removed field_key: The key of the field to be removed
[ "Remove", "a", "field", "from", "a", "Tensor", "s", "external_data", "key", "-", "value", "store", "." ]
python
train
34.384615
softlayer/softlayer-python
SoftLayer/CLI/environment.py
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/environment.py#L45-L47
def err(self, output, newline=True): """Outputs an error string to the console (stderr).""" click.echo(output, nl=newline, err=True)
[ "def", "err", "(", "self", ",", "output", ",", "newline", "=", "True", ")", ":", "click", ".", "echo", "(", "output", ",", "nl", "=", "newline", ",", "err", "=", "True", ")" ]
Outputs an error string to the console (stderr).
[ "Outputs", "an", "error", "string", "to", "the", "console", "(", "stderr", ")", "." ]
python
train
48.666667
kubernetes-client/python
kubernetes/client/apis/rbac_authorization_v1_api.py
https://github.com/kubernetes-client/python/blob/5e512ff564c244c50cab780d821542ed56aa965a/kubernetes/client/apis/rbac_authorization_v1_api.py#L845-L871
def delete_collection_cluster_role_binding(self, **kwargs): """ delete collection of ClusterRoleBinding This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_cluster_role_bindin...
[ "def", "delete_collection_cluster_role_binding", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "delete_collection_clus...
delete collection of ClusterRoleBinding This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_cluster_role_binding(async_req=True) >>> result = thread.get() :param async_req bo...
[ "delete", "collection", "of", "ClusterRoleBinding", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request", "please", "pass", "async_req", "=", "True", ">>>", "thread", "=", ...
python
train
169.111111
CityOfZion/neo-python
neo/Core/Helper.py
https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/Helper.py#L93-L111
def ToStream(value): """ Serialize the given `value` to a an array of bytes. Args: value (neo.IO.Mixins.SerializableMixin): object extending SerializableMixin. Returns: bytes: not hexlified """ ms = StreamManager.GetStream() writer = Bina...
[ "def", "ToStream", "(", "value", ")", ":", "ms", "=", "StreamManager", ".", "GetStream", "(", ")", "writer", "=", "BinaryWriter", "(", "ms", ")", "value", ".", "Serialize", "(", "writer", ")", "retVal", "=", "ms", ".", "getvalue", "(", ")", "StreamMana...
Serialize the given `value` to a an array of bytes. Args: value (neo.IO.Mixins.SerializableMixin): object extending SerializableMixin. Returns: bytes: not hexlified
[ "Serialize", "the", "given", "value", "to", "a", "an", "array", "of", "bytes", "." ]
python
train
23.263158
saltstack/salt
salt/modules/boto_vpc.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2853-L2888
def describe_vpc_peering_connection(name, region=None, key=None, keyid=None, profile=None): ''' Returns any VPC peering connection id(s) for the given VPC peering c...
[ "def", "describe_vpc_peering_connection", "(", "name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn3", "(", "region", "=", "region", ",", "key", "=", "key...
Returns any VPC peering connection id(s) for the given VPC peering connection name. VPC peering connection ids are only returned for connections that are in the ``active``, ``pending-acceptance`` or ``provisioning`` state. .. versionadded:: 2016.11.0 :param name: The string name for this VPC ...
[ "Returns", "any", "VPC", "peering", "connection", "id", "(", "s", ")", "for", "the", "given", "VPC", "peering", "connection", "name", "." ]
python
train
32.305556
etalab/cada
cada/commands.py
https://github.com/etalab/cada/blob/36e8b57514445c01ff7cd59a1c965180baf83d5e/cada/commands.py#L60-L67
def echo(msg, *args, **kwargs): '''Wraps click.echo, handles formatting and check encoding''' file = kwargs.pop('file', None) nl = kwargs.pop('nl', True) err = kwargs.pop('err', False) color = kwargs.pop('color', None) msg = safe_unicode(msg).format(*args, **kwargs) click.echo(msg, file=file...
[ "def", "echo", "(", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "file", "=", "kwargs", ".", "pop", "(", "'file'", ",", "None", ")", "nl", "=", "kwargs", ".", "pop", "(", "'nl'", ",", "True", ")", "err", "=", "kwargs", ".", "po...
Wraps click.echo, handles formatting and check encoding
[ "Wraps", "click", ".", "echo", "handles", "formatting", "and", "check", "encoding" ]
python
train
42.875
mediaburst/clockwork-python
clockwork/clockwork.py
https://github.com/mediaburst/clockwork-python/blob/7f8368bbed1fcb5218584fbc5094d93c6aa365d1/clockwork/clockwork.py#L69-L115
def send(self, messages): """Send a SMS message, or an array of SMS messages""" tmpSms = SMS(to='', message='') if str(type(messages)) == str(type(tmpSms)): messages = [messages] xml_root = self.__init_xml('Message') wrapper_id = 0 for m in messages: ...
[ "def", "send", "(", "self", ",", "messages", ")", ":", "tmpSms", "=", "SMS", "(", "to", "=", "''", ",", "message", "=", "''", ")", "if", "str", "(", "type", "(", "messages", ")", ")", "==", "str", "(", "type", "(", "tmpSms", ")", ")", ":", "m...
Send a SMS message, or an array of SMS messages
[ "Send", "a", "SMS", "message", "or", "an", "array", "of", "SMS", "messages" ]
python
train
38.361702
joke2k/faker
faker/providers/ssn/en_US/__init__.py
https://github.com/joke2k/faker/blob/965824b61132e52d92d1a6ce470396dbbe01c96c/faker/providers/ssn/en_US/__init__.py#L13-L33
def itin(self): """Generate a random United States Individual Taxpayer Identification Number (ITIN). An United States Individual Taxpayer Identification Number (ITIN) is a tax processing number issued by the Internal Revenue Service. It is a nine-digit number that always begins ...
[ "def", "itin", "(", "self", ")", ":", "area", "=", "self", ".", "random_int", "(", "min", "=", "900", ",", "max", "=", "999", ")", "serial", "=", "self", ".", "random_int", "(", "min", "=", "0", ",", "max", "=", "9999", ")", "# The group number mus...
Generate a random United States Individual Taxpayer Identification Number (ITIN). An United States Individual Taxpayer Identification Number (ITIN) is a tax processing number issued by the Internal Revenue Service. It is a nine-digit number that always begins with the number 9 and has a...
[ "Generate", "a", "random", "United", "States", "Individual", "Taxpayer", "Identification", "Number", "(", "ITIN", ")", "." ]
python
train
48.238095
narfman0/helga-markovify
helga_markovify/markov.py
https://github.com/narfman0/helga-markovify/blob/b5a82de070102e6da1fd3f5f81cad12d0a9185d8/helga_markovify/markov.py#L15-L21
def ingest(topic, text, **kwargs): """ Ingest the given text for the topic """ if not text: raise ValueError('No text given to ingest for topic: ' + topic) data = {'topic': topic, 'text': text.strip()} data.update(kwargs) db.markovify.insert(data)
[ "def", "ingest", "(", "topic", ",", "text", ",", "*", "*", "kwargs", ")", ":", "if", "not", "text", ":", "raise", "ValueError", "(", "'No text given to ingest for topic: '", "+", "topic", ")", "data", "=", "{", "'topic'", ":", "topic", ",", "'text'", ":"...
Ingest the given text for the topic
[ "Ingest", "the", "given", "text", "for", "the", "topic" ]
python
train
38.428571
codelv/enaml-native
src/enamlnative/android/android_sensors.py
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_sensors.py#L131-L155
def start(self, callback, rate=SENSOR_DELAY_NORMAL): """ Start listening to sensor events. Sensor event data depends on the type of sensor that was given to Parameters ---------- callback: Callable A callback that takes one argument that will be pass...
[ "def", "start", "(", "self", ",", "callback", ",", "rate", "=", "SENSOR_DELAY_NORMAL", ")", ":", "if", "not", "self", ".", "manager", ":", "raise", "RuntimeError", "(", "\"Cannot start a sensor without a SensorManager!\"", ")", "self", ".", "onSensorChanged", ".",...
Start listening to sensor events. Sensor event data depends on the type of sensor that was given to Parameters ---------- callback: Callable A callback that takes one argument that will be passed the sensor data. Sensor data is a dict with da...
[ "Start", "listening", "to", "sensor", "events", ".", "Sensor", "event", "data", "depends", "on", "the", "type", "of", "sensor", "that", "was", "given", "to", "Parameters", "----------", "callback", ":", "Callable", "A", "callback", "that", "takes", "one", "a...
python
train
37.6
hharnisc/python-ddp
DDPClient.py
https://github.com/hharnisc/python-ddp/blob/00bdf33c20ecba56623890515381154e14c5b757/DDPClient.py#L43-L47
def _debug_log(self, msg): """Debug log messages if debug=True""" if not self.debug: return sys.stderr.write('{}\n'.format(msg))
[ "def", "_debug_log", "(", "self", ",", "msg", ")", ":", "if", "not", "self", ".", "debug", ":", "return", "sys", ".", "stderr", ".", "write", "(", "'{}\\n'", ".", "format", "(", "msg", ")", ")" ]
Debug log messages if debug=True
[ "Debug", "log", "messages", "if", "debug", "=", "True" ]
python
train
32
TrafficSenseMSD/SumoTools
traci/_vehicle.py
https://github.com/TrafficSenseMSD/SumoTools/blob/8607b4f885f1d1798e43240be643efe6dccccdaa/traci/_vehicle.py#L674-L682
def getLaneChangeState(self, vehID, direction): """getLaneChangeState(string, int) -> (int, int) Return the lane change state for the vehicle """ self._connection._beginMessage( tc.CMD_GET_VEHICLE_VARIABLE, tc.CMD_CHANGELANE, vehID, 1 + 4) self._connection._string += ...
[ "def", "getLaneChangeState", "(", "self", ",", "vehID", ",", "direction", ")", ":", "self", ".", "_connection", ".", "_beginMessage", "(", "tc", ".", "CMD_GET_VEHICLE_VARIABLE", ",", "tc", ".", "CMD_CHANGELANE", ",", "vehID", ",", "1", "+", "4", ")", "self...
getLaneChangeState(string, int) -> (int, int) Return the lane change state for the vehicle
[ "getLaneChangeState", "(", "string", "int", ")", "-", ">", "(", "int", "int", ")", "Return", "the", "lane", "change", "state", "for", "the", "vehicle" ]
python
train
55.888889
CivicSpleen/ambry
ambry/bundle/process.py
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/process.py#L258-L260
def start(self, phase, stage, **kwargs): """Start a new routine, stage or phase""" return ProgressSection(self, self._session, phase, stage, self._logger, **kwargs)
[ "def", "start", "(", "self", ",", "phase", ",", "stage", ",", "*", "*", "kwargs", ")", ":", "return", "ProgressSection", "(", "self", ",", "self", ".", "_session", ",", "phase", ",", "stage", ",", "self", ".", "_logger", ",", "*", "*", "kwargs", ")...
Start a new routine, stage or phase
[ "Start", "a", "new", "routine", "stage", "or", "phase" ]
python
train
59.333333
angr/angr
angr/state_plugins/heap/heap_libc.py
https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/state_plugins/heap/heap_libc.py#L27-L36
def calloc(self, sim_nmemb, sim_size): """ A somewhat faithful implementation of libc `calloc`. :param sim_nmemb: the number of elements to allocated :param sim_size: the size of each element (in bytes) :returns: the address of the allocation, or a NULL pointer if the a...
[ "def", "calloc", "(", "self", ",", "sim_nmemb", ",", "sim_size", ")", ":", "raise", "NotImplementedError", "(", "\"%s not implemented for %s\"", "%", "(", "self", ".", "calloc", ".", "__func__", ".", "__name__", ",", "self", ".", "__class__", ".", "__name__", ...
A somewhat faithful implementation of libc `calloc`. :param sim_nmemb: the number of elements to allocated :param sim_size: the size of each element (in bytes) :returns: the address of the allocation, or a NULL pointer if the allocation failed
[ "A", "somewhat", "faithful", "implementation", "of", "libc", "calloc", "." ]
python
train
52.6
fabioz/PyDev.Debugger
_pydev_imps/_pydev_BaseHTTPServer.py
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydev_imps/_pydev_BaseHTTPServer.py#L302-L335
def handle_one_request(self): """Handle a single HTTP request. You normally don't need to override this method; see the class __doc__ string for information on how to handle specific HTTP commands such as GET and POST. """ try: self.raw_requestline = self.rf...
[ "def", "handle_one_request", "(", "self", ")", ":", "try", ":", "self", ".", "raw_requestline", "=", "self", ".", "rfile", ".", "readline", "(", "65537", ")", "if", "len", "(", "self", ".", "raw_requestline", ")", ">", "65536", ":", "self", ".", "reque...
Handle a single HTTP request. You normally don't need to override this method; see the class __doc__ string for information on how to handle specific HTTP commands such as GET and POST.
[ "Handle", "a", "single", "HTTP", "request", "." ]
python
train
38.529412
dhain/potpy
potpy/wsgi.py
https://github.com/dhain/potpy/blob/e39a5a84f763fbf144b07a620afb02a5ff3741c9/potpy/wsgi.py#L88-L99
def reverse(self, *args, **kwargs): """Look up a path by name and fill in the provided parameters. Example: >>> handler = lambda: None # just a bogus handler >>> router = PathRouter(('post', '/posts/{slug}', handler)) >>> router.reverse('post', slug='my-post') ...
[ "def", "reverse", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "(", "name", ",", ")", "=", "args", "return", "self", ".", "_templates", "[", "name", "]", ".", "fill", "(", "*", "*", "kwargs", ")" ]
Look up a path by name and fill in the provided parameters. Example: >>> handler = lambda: None # just a bogus handler >>> router = PathRouter(('post', '/posts/{slug}', handler)) >>> router.reverse('post', slug='my-post') '/posts/my-post'
[ "Look", "up", "a", "path", "by", "name", "and", "fill", "in", "the", "provided", "parameters", "." ]
python
train
35
OSSOS/MOP
src/ossos/utils/get_image_lists.py
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/utils/get_image_lists.py#L17-L46
def main(): """ Input asteroid family, filter type, and image type to query SSOIS """ parser = argparse.ArgumentParser(description='Run SSOIS and return the available images in a particular filter.') parser.add_argument("--filter", action="store", de...
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Run SSOIS and return the available images in a particular filter.'", ")", "parser", ".", "add_argument", "(", "\"--filter\"", ",", "action", "=", "\"store\"", ",...
Input asteroid family, filter type, and image type to query SSOIS
[ "Input", "asteroid", "family", "filter", "type", "and", "image", "type", "to", "query", "SSOIS" ]
python
train
37.666667
rushter/heamy
heamy/dataset.py
https://github.com/rushter/heamy/blob/c330854cee3c547417eb353a4a4a23331b40b4bc/heamy/dataset.py#L326-L329
def to_csc(self): """Convert Dataset to scipy's Compressed Sparse Column matrix.""" self._X_train = csc_matrix(self._X_train) self._X_test = csc_matrix(self._X_test)
[ "def", "to_csc", "(", "self", ")", ":", "self", ".", "_X_train", "=", "csc_matrix", "(", "self", ".", "_X_train", ")", "self", ".", "_X_test", "=", "csc_matrix", "(", "self", ".", "_X_test", ")" ]
Convert Dataset to scipy's Compressed Sparse Column matrix.
[ "Convert", "Dataset", "to", "scipy", "s", "Compressed", "Sparse", "Column", "matrix", "." ]
python
train
46.5
BYU-PCCL/holodeck
holodeck/shmem.py
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/shmem.py#L51-L58
def unlink(self): """unlinks the shared memory""" if os.name == "posix": self.__linux_unlink__() elif os.name == "nt": self.__windows_unlink__() else: raise HolodeckException("Currently unsupported os: " + os.name)
[ "def", "unlink", "(", "self", ")", ":", "if", "os", ".", "name", "==", "\"posix\"", ":", "self", ".", "__linux_unlink__", "(", ")", "elif", "os", ".", "name", "==", "\"nt\"", ":", "self", ".", "__windows_unlink__", "(", ")", "else", ":", "raise", "Ho...
unlinks the shared memory
[ "unlinks", "the", "shared", "memory" ]
python
train
34.375
saltstack/salt
salt/states/zfs.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zfs.py#L810-L847
def _schedule_snapshot_retrieve(dataset, prefix, snapshots): ''' Update snapshots dict with current snapshots dataset: string name of filesystem or volume prefix : string prefix for the snapshots e.g. 'test' will result in snapshots being named 'test-yyyymmdd_hhmm' snapshots...
[ "def", "_schedule_snapshot_retrieve", "(", "dataset", ",", "prefix", ",", "snapshots", ")", ":", "## NOTE: retrieve all snapshots for the dataset", "for", "snap", "in", "sorted", "(", "__salt__", "[", "'zfs.list'", "]", "(", "dataset", ",", "*", "*", "{", "'recurs...
Update snapshots dict with current snapshots dataset: string name of filesystem or volume prefix : string prefix for the snapshots e.g. 'test' will result in snapshots being named 'test-yyyymmdd_hhmm' snapshots : OrderedDict preseeded OrderedDict with configuration
[ "Update", "snapshots", "dict", "with", "current", "snapshots" ]
python
train
37.184211
jleclanche/fireplace
fireplace/game.py
https://github.com/jleclanche/fireplace/blob/d0fc0e97e185c0210de86631be20638659c0609e/fireplace/game.py#L193-L201
def queue_actions(self, source, actions, event_args=None): """ Queue a list of \a actions for processing from \a source. Triggers an aura refresh afterwards. """ source.event_args = event_args ret = self.trigger_actions(source, actions) source.event_args = None return ret
[ "def", "queue_actions", "(", "self", ",", "source", ",", "actions", ",", "event_args", "=", "None", ")", ":", "source", ".", "event_args", "=", "event_args", "ret", "=", "self", ".", "trigger_actions", "(", "source", ",", "actions", ")", "source", ".", "...
Queue a list of \a actions for processing from \a source. Triggers an aura refresh afterwards.
[ "Queue", "a", "list", "of", "\\", "a", "actions", "for", "processing", "from", "\\", "a", "source", ".", "Triggers", "an", "aura", "refresh", "afterwards", "." ]
python
train
31.111111
pip-services/pip-services-commons-python
pip_services_commons/commands/InterceptedCommand.py
https://github.com/pip-services/pip-services-commons-python/blob/2205b18c45c60372966c62c1f23ac4fbc31e11b3/pip_services_commons/commands/InterceptedCommand.py#L42-L55
def execute(self, correlation_id, args): """ Executes the command given specific arguments as an input. Args: correlation_id: a unique correlation/transaction id args: command arguments Returns: an execution result. Rai...
[ "def", "execute", "(", "self", ",", "correlation_id", ",", "args", ")", ":", "return", "self", ".", "_intercepter", ".", "execute", "(", "_next", ",", "correlation_id", ",", "args", ")" ]
Executes the command given specific arguments as an input. Args: correlation_id: a unique correlation/transaction id args: command arguments Returns: an execution result. Raises: MicroserviceError: when execution fails for w...
[ "Executes", "the", "command", "given", "specific", "arguments", "as", "an", "input", ".", "Args", ":", "correlation_id", ":", "a", "unique", "correlation", "/", "transaction", "id", "args", ":", "command", "arguments", "Returns", ":", "an", "execution", "resul...
python
valid
33.5
pgmpy/pgmpy
pgmpy/models/LinearGaussianBayesianNetwork.py
https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/models/LinearGaussianBayesianNetwork.py#L129-L189
def to_joint_gaussian(self): """ The linear Gaussian Bayesian Networks are an alternative representation for the class of multivariate Gaussian distributions. This method returns an equivalent joint Gaussian distribution. Returns ------- GaussianDistribution: An ...
[ "def", "to_joint_gaussian", "(", "self", ")", ":", "variables", "=", "nx", ".", "topological_sort", "(", "self", ")", "mean", "=", "np", ".", "zeros", "(", "len", "(", "variables", ")", ")", "covariance", "=", "np", ".", "zeros", "(", "(", "len", "("...
The linear Gaussian Bayesian Networks are an alternative representation for the class of multivariate Gaussian distributions. This method returns an equivalent joint Gaussian distribution. Returns ------- GaussianDistribution: An equivalent joint Gaussian ...
[ "The", "linear", "Gaussian", "Bayesian", "Networks", "are", "an", "alternative", "representation", "for", "the", "class", "of", "multivariate", "Gaussian", "distributions", ".", "This", "method", "returns", "an", "equivalent", "joint", "Gaussian", "distribution", "....
python
train
42.377049
saltstack/salt
salt/cli/support/console.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/support/console.py#L30-L43
def put(self, message, indent=0): ''' Print message with an indent. :param message: :param indent: :return: ''' color = self._colors_conf.get(indent + indent % 2, self._colors_conf.get(0, self._default_color)) for chunk in [' ' * indent, self._colors[col...
[ "def", "put", "(", "self", ",", "message", ",", "indent", "=", "0", ")", ":", "color", "=", "self", ".", "_colors_conf", ".", "get", "(", "indent", "+", "indent", "%", "2", ",", "self", ".", "_colors_conf", ".", "get", "(", "0", ",", "self", ".",...
Print message with an indent. :param message: :param indent: :return:
[ "Print", "message", "with", "an", "indent", "." ]
python
train
32.428571
dereneaton/ipyrad
ipyrad/assemble/refmap.py
https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/refmap.py#L116-L324
def mapreads(data, sample, nthreads, force): """ Attempt to map reads to reference sequence. This reads in the fasta files (samples.files.edits), and maps each read to the reference. Unmapped reads are dropped right back in the de novo pipeline. Reads that map successfully are processed and pushed...
[ "def", "mapreads", "(", "data", ",", "sample", ",", "nthreads", ",", "force", ")", ":", "LOGGER", ".", "info", "(", "\"Entering mapreads(): %s %s\"", ",", "sample", ".", "name", ",", "nthreads", ")", "## This is the input derep file, for paired data we need to split t...
Attempt to map reads to reference sequence. This reads in the fasta files (samples.files.edits), and maps each read to the reference. Unmapped reads are dropped right back in the de novo pipeline. Reads that map successfully are processed and pushed downstream and joined with the rest of the data post...
[ "Attempt", "to", "map", "reads", "to", "reference", "sequence", ".", "This", "reads", "in", "the", "fasta", "files", "(", "samples", ".", "files", ".", "edits", ")", "and", "maps", "each", "read", "to", "the", "reference", ".", "Unmapped", "reads", "are"...
python
valid
44.966507
cuihantao/andes
andes/utils/solver.py
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/utils/solver.py#L17-L38
def symbolic(self, A): """ Return the symbolic factorization of sparse matrix ``A`` Parameters ---------- sparselib Library name in ``umfpack`` and ``klu`` A Sparse matrix Returns symbolic factorization ------- ""...
[ "def", "symbolic", "(", "self", ",", "A", ")", ":", "if", "self", ".", "sparselib", "==", "'umfpack'", ":", "return", "umfpack", ".", "symbolic", "(", "A", ")", "elif", "self", ".", "sparselib", "==", "'klu'", ":", "return", "klu", ".", "symbolic", "...
Return the symbolic factorization of sparse matrix ``A`` Parameters ---------- sparselib Library name in ``umfpack`` and ``klu`` A Sparse matrix Returns symbolic factorization -------
[ "Return", "the", "symbolic", "factorization", "of", "sparse", "matrix", "A" ]
python
train
20.636364
materialsproject/pymatgen
pymatgen/analysis/graphs.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/graphs.py#L2272-L2320
def find_rings(self, including=None): """ Find ring structures in the MoleculeGraph. :param including: list of site indices. If including is not None, then find_rings will only return those rings including the specified sites. By default, this parameter is None, and ...
[ "def", "find_rings", "(", "self", ",", "including", "=", "None", ")", ":", "# Copies self.graph such that all edges (u, v) matched by edges (v, u)", "undirected", "=", "self", ".", "graph", ".", "to_undirected", "(", ")", "directed", "=", "undirected", ".", "to_direct...
Find ring structures in the MoleculeGraph. :param including: list of site indices. If including is not None, then find_rings will only return those rings including the specified sites. By default, this parameter is None, and all rings will be returned. :return: dict {ind...
[ "Find", "ring", "structures", "in", "the", "MoleculeGraph", "." ]
python
train
35.469388
skggm/skggm
examples/estimator_suite_spark.py
https://github.com/skggm/skggm/blob/a0ed406586c4364ea3297a658f415e13b5cbdaf8/examples/estimator_suite_spark.py#L232-L237
def empirical(X): """Compute empirical covariance as baseline estimator. """ print("Empirical") cov = np.dot(X.T, X) / n_samples return cov, np.linalg.inv(cov)
[ "def", "empirical", "(", "X", ")", ":", "print", "(", "\"Empirical\"", ")", "cov", "=", "np", ".", "dot", "(", "X", ".", "T", ",", "X", ")", "/", "n_samples", "return", "cov", ",", "np", ".", "linalg", ".", "inv", "(", "cov", ")" ]
Compute empirical covariance as baseline estimator.
[ "Compute", "empirical", "covariance", "as", "baseline", "estimator", "." ]
python
train
29
numenta/nupic
src/nupic/data/generators/pattern_machine.py
https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/generators/pattern_machine.py#L202-L213
def _generate(self): """ Generates set of consecutive patterns. """ n = self._n w = self._w assert type(w) is int, "List for w not supported" for i in xrange(n / w): pattern = set(xrange(i * w, (i+1) * w)) self._patterns[i] = pattern
[ "def", "_generate", "(", "self", ")", ":", "n", "=", "self", ".", "_n", "w", "=", "self", ".", "_w", "assert", "type", "(", "w", ")", "is", "int", ",", "\"List for w not supported\"", "for", "i", "in", "xrange", "(", "n", "/", "w", ")", ":", "pat...
Generates set of consecutive patterns.
[ "Generates", "set", "of", "consecutive", "patterns", "." ]
python
valid
22
thomasleese/mo
mo/steps.py
https://github.com/thomasleese/mo/blob/b757f52b42e51ad19c14724ceb7c5db5d52abaea/mo/steps.py#L96-L113
def help(project, task, step, variables): """Run a help step.""" task_name = step.args or variables['task'] try: task = project.find_task(task_name) except NoSuchTaskError as e: yield events.task_not_found(task_name, e.similarities) raise StopTask text = f'# {task.name}\n'...
[ "def", "help", "(", "project", ",", "task", ",", "step", ",", "variables", ")", ":", "task_name", "=", "step", ".", "args", "or", "variables", "[", "'task'", "]", "try", ":", "task", "=", "project", ".", "find_task", "(", "task_name", ")", "except", ...
Run a help step.
[ "Run", "a", "help", "step", "." ]
python
train
25.888889
saltstack/salt
salt/cloud/clouds/proxmox.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/proxmox.py#L275-L289
def _lookup_proxmox_task(upid): ''' Retrieve the (latest) logs and retrieve the status for a UPID. This can be used to verify whether a task has completed. ''' log.debug('Getting creation status for upid: %s', upid) tasks = query('get', 'cluster/tasks') if tasks: for task in tasks: ...
[ "def", "_lookup_proxmox_task", "(", "upid", ")", ":", "log", ".", "debug", "(", "'Getting creation status for upid: %s'", ",", "upid", ")", "tasks", "=", "query", "(", "'get'", ",", "'cluster/tasks'", ")", "if", "tasks", ":", "for", "task", "in", "tasks", ":...
Retrieve the (latest) logs and retrieve the status for a UPID. This can be used to verify whether a task has completed.
[ "Retrieve", "the", "(", "latest", ")", "logs", "and", "retrieve", "the", "status", "for", "a", "UPID", ".", "This", "can", "be", "used", "to", "verify", "whether", "a", "task", "has", "completed", "." ]
python
train
29.533333
mozilla-iot/webthing-python
webthing/server.py
https://github.com/mozilla-iot/webthing-python/blob/65d467c89ed79d0bbc42b8b3c8f9e5a320edd237/webthing/server.py#L116-L122
def set_default_headers(self, *args, **kwargs): """Set the default headers for all requests.""" self.set_header('Access-Control-Allow-Origin', '*') self.set_header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept') self.set_header('A...
[ "def", "set_default_headers", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "set_header", "(", "'Access-Control-Allow-Origin'", ",", "'*'", ")", "self", ".", "set_header", "(", "'Access-Control-Allow-Headers'", ",", "'Origin, X-R...
Set the default headers for all requests.
[ "Set", "the", "default", "headers", "for", "all", "requests", "." ]
python
test
57
arne-cl/discoursegraphs
src/discoursegraphs/readwrite/tiger.py
https://github.com/arne-cl/discoursegraphs/blob/842f0068a3190be2c75905754521b176b25a54fb/src/discoursegraphs/readwrite/tiger.py#L344-L369
def get_subordinate_clauses(tiger_docgraph): """ given a document graph of a TIGER syntax tree, return all node IDs of nodes representing subordinate clause constituents. Parameters ---------- tiger_docgraph : DiscourseDocumentGraph or TigerDocumentGraph document graph from which subord...
[ "def", "get_subordinate_clauses", "(", "tiger_docgraph", ")", ":", "subord_clause_rels", "=", "dg", ".", "select_edges_by_attribute", "(", "tiger_docgraph", ",", "attribute", "=", "'tiger:label'", ",", "value", "=", "[", "'MO'", ",", "'RC'", ",", "'SB'", "]", ")...
given a document graph of a TIGER syntax tree, return all node IDs of nodes representing subordinate clause constituents. Parameters ---------- tiger_docgraph : DiscourseDocumentGraph or TigerDocumentGraph document graph from which subordinate clauses will be extracted Returns ------- ...
[ "given", "a", "document", "graph", "of", "a", "TIGER", "syntax", "tree", "return", "all", "node", "IDs", "of", "nodes", "representing", "subordinate", "clause", "constituents", "." ]
python
train
35.423077
srossross/rpmfile
rpmfile/__init__.py
https://github.com/srossross/rpmfile/blob/3ab96f211da7b56f5e99d8cc248f714a6e542d31/rpmfile/__init__.py#L149-L158
def extractfile(self, member): ''' Extract a member from the archive as a file object. `member' may be a filename or an RPMInfo object. The file-like object is read-only and provides the following methods: read(), readline(), readlines(), seek() and tell() ''' if ...
[ "def", "extractfile", "(", "self", ",", "member", ")", ":", "if", "not", "isinstance", "(", "member", ",", "RPMInfo", ")", ":", "member", "=", "self", ".", "getmember", "(", "member", ")", "return", "_SubFile", "(", "self", ".", "data_file", ",", "memb...
Extract a member from the archive as a file object. `member' may be a filename or an RPMInfo object. The file-like object is read-only and provides the following methods: read(), readline(), readlines(), seek() and tell()
[ "Extract", "a", "member", "from", "the", "archive", "as", "a", "file", "object", ".", "member", "may", "be", "a", "filename", "or", "an", "RPMInfo", "object", ".", "The", "file", "-", "like", "object", "is", "read", "-", "only", "and", "provides", "the...
python
train
45.9
helixyte/everest
everest/representers/base.py
https://github.com/helixyte/everest/blob/70c9b93c3061db5cb62428349d18b8fb8566411b/everest/representers/base.py#L294-L302
def with_updated_configuration(self, options=None, attribute_options=None): """ Returns a context in which this representer is updated with the given options and attribute options. """ return self._mapping.with_updated_configuration(options=opti...
[ "def", "with_updated_configuration", "(", "self", ",", "options", "=", "None", ",", "attribute_options", "=", "None", ")", ":", "return", "self", ".", "_mapping", ".", "with_updated_configuration", "(", "options", "=", "options", ",", "attribute_options", "=", "...
Returns a context in which this representer is updated with the given options and attribute options.
[ "Returns", "a", "context", "in", "which", "this", "representer", "is", "updated", "with", "the", "given", "options", "and", "attribute", "options", "." ]
python
train
52.222222
pydata/xarray
xarray/core/variable.py
https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/core/variable.py#L1896-L1927
def copy(self, deep=True, data=None): """Returns a copy of this object. `deep` is ignored since data is stored in the form of pandas.Index, which is already immutable. Dimensions, attributes and encodings are always copied. Use `data` to create a new object with the same struct...
[ "def", "copy", "(", "self", ",", "deep", "=", "True", ",", "data", "=", "None", ")", ":", "if", "data", "is", "None", ":", "data", "=", "self", ".", "_data", "else", ":", "data", "=", "as_compatible_data", "(", "data", ")", "if", "self", ".", "sh...
Returns a copy of this object. `deep` is ignored since data is stored in the form of pandas.Index, which is already immutable. Dimensions, attributes and encodings are always copied. Use `data` to create a new object with the same structure as original but entirely new data. ...
[ "Returns", "a", "copy", "of", "this", "object", "." ]
python
train
36.03125
UCL-INGI/INGInious
inginious/frontend/pages/course.py
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/course.py#L40-L74
def show_page(self, course): """ Prepares and shows the course page """ username = self.user_manager.session_username() if not self.user_manager.course_is_open_to_user(course, lti=False): return self.template_helper.get_renderer().course_unavailable() else: tasks ...
[ "def", "show_page", "(", "self", ",", "course", ")", ":", "username", "=", "self", ".", "user_manager", ".", "session_username", "(", ")", "if", "not", "self", ".", "user_manager", ".", "course_is_open_to_user", "(", "course", ",", "lti", "=", "False", ")"...
Prepares and shows the course page
[ "Prepares", "and", "shows", "the", "course", "page" ]
python
train
59.428571
DistrictDataLabs/yellowbrick
yellowbrick/classifier/base.py
https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/classifier/base.py#L84-L111
def fit(self, X, y=None, **kwargs): """ Parameters ---------- X : ndarray or DataFrame of shape n x m A matrix of n instances with m features y : ndarray or Series of length n An array or series of target or class values kwargs: keyword argument...
[ "def", "fit", "(", "self", ",", "X", ",", "y", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Fit the inner estimator", "self", ".", "estimator", ".", "fit", "(", "X", ",", "y", ")", "# Extract the classes from the estimator", "if", "self", ".", "cla...
Parameters ---------- X : ndarray or DataFrame of shape n x m A matrix of n instances with m features y : ndarray or Series of length n An array or series of target or class values kwargs: keyword arguments passed to Scikit-Learn API. Returns -...
[ "Parameters", "----------" ]
python
train
25.928571
google/transitfeed
gtfsscheduleviewer/marey_graph.py
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/gtfsscheduleviewer/marey_graph.py#L380-L398
def _DrawHours(self): """Generates svg to show a vertical hour and sub-hour grid Returns: # A string containing a polyline tag for each grid line " <polyline class="FullHour" points="20,0 ..." """ tmpstrs = [] for i in range(0, self._gwidth, self._min_grid): if i % self._hour_grid...
[ "def", "_DrawHours", "(", "self", ")", ":", "tmpstrs", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "self", ".", "_gwidth", ",", "self", ".", "_min_grid", ")", ":", "if", "i", "%", "self", ".", "_hour_grid", "==", "0", ":", "tmpstrs",...
Generates svg to show a vertical hour and sub-hour grid Returns: # A string containing a polyline tag for each grid line " <polyline class="FullHour" points="20,0 ..."
[ "Generates", "svg", "to", "show", "a", "vertical", "hour", "and", "sub", "-", "hour", "grid" ]
python
train
43.368421
gabstopper/smc-python
smc/base/util.py
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/base/util.py#L106-L131
def merge_dicts(dict1, dict2, append_lists=False): """ Merge the second dict into the first Not intended to merge list of dicts. :param append_lists: If true, instead of clobbering a list with the new value, append all of the new values onto the original list. """ for key in dict2: ...
[ "def", "merge_dicts", "(", "dict1", ",", "dict2", ",", "append_lists", "=", "False", ")", ":", "for", "key", "in", "dict2", ":", "if", "isinstance", "(", "dict2", "[", "key", "]", ",", "dict", ")", ":", "if", "key", "in", "dict1", "and", "key", "in...
Merge the second dict into the first Not intended to merge list of dicts. :param append_lists: If true, instead of clobbering a list with the new value, append all of the new values onto the original list.
[ "Merge", "the", "second", "dict", "into", "the", "first", "Not", "intended", "to", "merge", "list", "of", "dicts", "." ]
python
train
41.653846
AkihikoITOH/capybara
capybara/virtualenv/lib/python2.7/site-packages/flask/app.py
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/flask/app.py#L1441-L1461
def dispatch_request(self): """Does the request dispatching. Matches the URL and returns the return value of the view or error handler. This does not have to be a response object. In order to convert the return value to a proper response object, call :func:`make_response`. .....
[ "def", "dispatch_request", "(", "self", ")", ":", "req", "=", "_request_ctx_stack", ".", "top", ".", "request", "if", "req", ".", "routing_exception", "is", "not", "None", ":", "self", ".", "raise_routing_exception", "(", "req", ")", "rule", "=", "req", "....
Does the request dispatching. Matches the URL and returns the return value of the view or error handler. This does not have to be a response object. In order to convert the return value to a proper response object, call :func:`make_response`. .. versionchanged:: 0.7 This n...
[ "Does", "the", "request", "dispatching", ".", "Matches", "the", "URL", "and", "returns", "the", "return", "value", "of", "the", "view", "or", "error", "handler", ".", "This", "does", "not", "have", "to", "be", "a", "response", "object", ".", "In", "order...
python
test
49.761905
uber/multidimensional_urlencode
multidimensional_urlencode/urlencoder.py
https://github.com/uber/multidimensional_urlencode/blob/f626528bc3535503fa1557a53bbfacaa29920251/multidimensional_urlencode/urlencoder.py#L41-L54
def parametrize(params): """Return list of params as params. >>> parametrize(['a']) 'a' >>> parametrize(['a', 'b']) 'a[b]' >>> parametrize(['a', 'b', 'c']) 'a[b][c]' """ returned = str(params[0]) returned += "".join("[" + str(p) + "]" for p in params[1:]) return returned
[ "def", "parametrize", "(", "params", ")", ":", "returned", "=", "str", "(", "params", "[", "0", "]", ")", "returned", "+=", "\"\"", ".", "join", "(", "\"[\"", "+", "str", "(", "p", ")", "+", "\"]\"", "for", "p", "in", "params", "[", "1", ":", "...
Return list of params as params. >>> parametrize(['a']) 'a' >>> parametrize(['a', 'b']) 'a[b]' >>> parametrize(['a', 'b', 'c']) 'a[b][c]'
[ "Return", "list", "of", "params", "as", "params", "." ]
python
train
21.714286
saltstack/salt
salt/spm/__init__.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/spm/__init__.py#L569-L618
def _resolve_deps(self, formula_def): ''' Return a list of packages which need to be installed, to resolve all dependencies ''' pkg_info = self.pkgdb['{0}.info'.format(self.db_prov)](formula_def['name']) if not isinstance(pkg_info, dict): pkg_info = {} ...
[ "def", "_resolve_deps", "(", "self", ",", "formula_def", ")", ":", "pkg_info", "=", "self", ".", "pkgdb", "[", "'{0}.info'", ".", "format", "(", "self", ".", "db_prov", ")", "]", "(", "formula_def", "[", "'name'", "]", ")", "if", "not", "isinstance", "...
Return a list of packages which need to be installed, to resolve all dependencies
[ "Return", "a", "list", "of", "packages", "which", "need", "to", "be", "installed", "to", "resolve", "all", "dependencies" ]
python
train
36.56
mbedmicro/pyOCD
pyocd/probe/pydapaccess/dap_access_cmsis_dap.py
https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/probe/pydapaccess/dap_access_cmsis_dap.py#L939-L992
def _write(self, dap_index, transfer_count, transfer_request, transfer_data): """ Write one or more commands """ assert dap_index == 0 # dap index currently unsupported assert isinstance(transfer_count, six.integer_types) assert isinstance(transfer_request...
[ "def", "_write", "(", "self", ",", "dap_index", ",", "transfer_count", ",", "transfer_request", ",", "transfer_data", ")", ":", "assert", "dap_index", "==", "0", "# dap index currently unsupported", "assert", "isinstance", "(", "transfer_count", ",", "six", ".", "...
Write one or more commands
[ "Write", "one", "or", "more", "commands" ]
python
train
37.537037
zerotk/easyfs
zerotk/easyfs/_easyfs.py
https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/_easyfs.py#L1654-L1682
def Split(cls, extended_path_mask): ''' Splits the given path into their components: recursive, dirname, in_filters and out_filters :param str: extended_path_mask: The "extended path mask" to split :rtype: tuple(bool,bool,str,list(str),list(str)) :returns: ...
[ "def", "Split", "(", "cls", ",", "extended_path_mask", ")", ":", "import", "os", ".", "path", "r_tree_recurse", "=", "extended_path_mask", "[", "0", "]", "in", "'+-'", "r_flat_recurse", "=", "extended_path_mask", "[", "0", "]", "in", "'-'", "r_dirname", ",",...
Splits the given path into their components: recursive, dirname, in_filters and out_filters :param str: extended_path_mask: The "extended path mask" to split :rtype: tuple(bool,bool,str,list(str),list(str)) :returns: Returns the extended path 5 components: -...
[ "Splits", "the", "given", "path", "into", "their", "components", ":", "recursive", "dirname", "in_filters", "and", "out_filters" ]
python
valid
36.517241
BerkeleyAutomation/autolab_core
autolab_core/rigid_transformations.py
https://github.com/BerkeleyAutomation/autolab_core/blob/8f3813f6401972868cc5e3981ba1b4382d4418d5/autolab_core/rigid_transformations.py#L199-L204
def quaternion(self): """:obj:`numpy.ndarray` of float: A quaternion vector in wxyz layout. """ q_xyzw = transformations.quaternion_from_matrix(self.matrix) q_wxyz = np.roll(q_xyzw, 1) return q_wxyz
[ "def", "quaternion", "(", "self", ")", ":", "q_xyzw", "=", "transformations", ".", "quaternion_from_matrix", "(", "self", ".", "matrix", ")", "q_wxyz", "=", "np", ".", "roll", "(", "q_xyzw", ",", "1", ")", "return", "q_wxyz" ]
:obj:`numpy.ndarray` of float: A quaternion vector in wxyz layout.
[ ":", "obj", ":", "numpy", ".", "ndarray", "of", "float", ":", "A", "quaternion", "vector", "in", "wxyz", "layout", "." ]
python
train
38.833333
facelessuser/pyspelling
pyspelling/filters/odf.py
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/odf.py#L139-L147
def get_sub_node(self, node): """Extract node from document if desired.""" subnode = node.find('office:document') if subnode: mimetype = subnode.attrs['office:mimetype'] self.type = MIMEMAP[mimetype] node = node.find('office:body') return node
[ "def", "get_sub_node", "(", "self", ",", "node", ")", ":", "subnode", "=", "node", ".", "find", "(", "'office:document'", ")", "if", "subnode", ":", "mimetype", "=", "subnode", ".", "attrs", "[", "'office:mimetype'", "]", "self", ".", "type", "=", "MIMEM...
Extract node from document if desired.
[ "Extract", "node", "from", "document", "if", "desired", "." ]
python
train
33.777778