repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
tony-landis/datomic-py
datomic/datomic.py
https://github.com/tony-landis/datomic-py/blob/54f713d29ad85ba86d53d5115c9b312ff14b7846/datomic/datomic.py#L129-L137
def retract(self, e, a, v): """ redact the value of an attribute """ ta = datetime.datetime.now() ret = u"[:db/retract %i :%s %s]" % (e, a, dump_edn_val(v)) rs = self.tx(ret) tb = datetime.datetime.now() - ta print cl('<<< retracted %s,%s,%s in %sms' % (e,a,v, tb.microseconds/1000.0), 'cyan'...
[ "def", "retract", "(", "self", ",", "e", ",", "a", ",", "v", ")", ":", "ta", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "ret", "=", "u\"[:db/retract %i :%s %s]\"", "%", "(", "e", ",", "a", ",", "dump_edn_val", "(", "v", ")", ")", "rs...
redact the value of an attribute
[ "redact", "the", "value", "of", "an", "attribute" ]
python
train
f3at/feat
src/feat/agencies/agency.py
https://github.com/f3at/feat/blob/15da93fc9d6ec8154f52a9172824e25821195ef8/src/feat/agencies/agency.py#L1477-L1526
def _start_host_agent(self): ''' This method starts saves the host agent descriptor and runs it. To make this happen following conditions needs to be fulfilled: - it is a master agency, - we are not starting a host agent already, - we are not terminating, - an...
[ "def", "_start_host_agent", "(", "self", ")", ":", "def", "set_flag", "(", "value", ")", ":", "self", ".", "_starting_host", "=", "value", "if", "not", "self", ".", "_can_start_host_agent", "(", ")", ":", "return", "def", "handle_error_on_get", "(", "fail", ...
This method starts saves the host agent descriptor and runs it. To make this happen following conditions needs to be fulfilled: - it is a master agency, - we are not starting a host agent already, - we are not terminating, - and last but not least, we dont have a host agent r...
[ "This", "method", "starts", "saves", "the", "host", "agent", "descriptor", "and", "runs", "it", ".", "To", "make", "this", "happen", "following", "conditions", "needs", "to", "be", "fulfilled", ":", "-", "it", "is", "a", "master", "agency", "-", "we", "a...
python
train
nicferrier/md
src/mdlib/pull.py
https://github.com/nicferrier/md/blob/302ca8882dae060fb15bd5ae470d8e661fb67ec4/src/mdlib/pull.py#L144-L152
def _filter(msgdata, mailparser, mdfolder, mailfilters): """Filter msgdata by mailfilters""" if mailfilters: for f in mailfilters: msg = mailparser.parse(StringIO(msgdata)) rule = f(msg, folder=mdfolder) if rule: yield rule return
[ "def", "_filter", "(", "msgdata", ",", "mailparser", ",", "mdfolder", ",", "mailfilters", ")", ":", "if", "mailfilters", ":", "for", "f", "in", "mailfilters", ":", "msg", "=", "mailparser", ".", "parse", "(", "StringIO", "(", "msgdata", ")", ")", "rule",...
Filter msgdata by mailfilters
[ "Filter", "msgdata", "by", "mailfilters" ]
python
train
CZ-NIC/yangson
yangson/statement.py
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/statement.py#L291-L320
def argument(self) -> bool: """Parse statement argument. Return ``True`` if the argument is followed by block of substatements. """ next = self.peek() if next == "'": quoted = True self.sq_argument() elif next == '"': quoted = True ...
[ "def", "argument", "(", "self", ")", "->", "bool", ":", "next", "=", "self", ".", "peek", "(", ")", "if", "next", "==", "\"'\"", ":", "quoted", "=", "True", "self", ".", "sq_argument", "(", ")", "elif", "next", "==", "'\"'", ":", "quoted", "=", "...
Parse statement argument. Return ``True`` if the argument is followed by block of substatements.
[ "Parse", "statement", "argument", "." ]
python
train
ganguli-lab/proxalgs
proxalgs/operators.py
https://github.com/ganguli-lab/proxalgs/blob/74f54467ad072d3229edea93fa84ddd98dd77c67/proxalgs/operators.py#L214-L244
def nucnorm(x0, rho, gamma): """ Proximal operator for the nuclear norm (sum of the singular values of a matrix) Parameters ---------- x0 : array_like The starting or initial point used in the proximal update step rho : float Momentum parameter for the proximal step (larger val...
[ "def", "nucnorm", "(", "x0", ",", "rho", ",", "gamma", ")", ":", "# compute SVD", "u", ",", "s", ",", "v", "=", "np", ".", "linalg", ".", "svd", "(", "x0", ",", "full_matrices", "=", "False", ")", "# soft threshold the singular values", "sthr", "=", "n...
Proximal operator for the nuclear norm (sum of the singular values of a matrix) Parameters ---------- x0 : array_like The starting or initial point used in the proximal update step rho : float Momentum parameter for the proximal step (larger value -> stays closer to x0) gamma : fl...
[ "Proximal", "operator", "for", "the", "nuclear", "norm", "(", "sum", "of", "the", "singular", "values", "of", "a", "matrix", ")" ]
python
train
cloudera/impyla
impala/_thrift_gen/hive_metastore/ThriftHiveMetastore.py
https://github.com/cloudera/impyla/blob/547fa2ba3b6151e2a98b3544301471a643212dc3/impala/_thrift_gen/hive_metastore/ThriftHiveMetastore.py#L3481-L3490
def get_partitions_by_filter(self, db_name, tbl_name, filter, max_parts): """ Parameters: - db_name - tbl_name - filter - max_parts """ self.send_get_partitions_by_filter(db_name, tbl_name, filter, max_parts) return self.recv_get_partitions_by_filter()
[ "def", "get_partitions_by_filter", "(", "self", ",", "db_name", ",", "tbl_name", ",", "filter", ",", "max_parts", ")", ":", "self", ".", "send_get_partitions_by_filter", "(", "db_name", ",", "tbl_name", ",", "filter", ",", "max_parts", ")", "return", "self", "...
Parameters: - db_name - tbl_name - filter - max_parts
[ "Parameters", ":", "-", "db_name", "-", "tbl_name", "-", "filter", "-", "max_parts" ]
python
train
xtuml/pyxtuml
xtuml/meta.py
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/meta.py#L632-L644
def clone(self, instance): ''' Create a shallow clone of an *instance*. **Note:** the clone and the original instance **does not** have to be part of the same metaclass. ''' args = list() for name, _ in get_metaclass(instance).attributes: val...
[ "def", "clone", "(", "self", ",", "instance", ")", ":", "args", "=", "list", "(", ")", "for", "name", ",", "_", "in", "get_metaclass", "(", "instance", ")", ".", "attributes", ":", "value", "=", "getattr", "(", "instance", ",", "name", ")", "args", ...
Create a shallow clone of an *instance*. **Note:** the clone and the original instance **does not** have to be part of the same metaclass.
[ "Create", "a", "shallow", "clone", "of", "an", "*", "instance", "*", ".", "**", "Note", ":", "**", "the", "clone", "and", "the", "original", "instance", "**", "does", "not", "**", "have", "to", "be", "part", "of", "the", "same", "metaclass", "." ]
python
test
log2timeline/dfvfs
dfvfs/lib/sqlite_database.py
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/lib/sqlite_database.py#L61-L93
def GetNumberOfRows(self, table_name): """Retrieves the number of rows in the table. Args: table_name (str): name of the table. Returns: int: number of rows. Raises: IOError: if the file-like object has not been opened. OSError: if the file-like object has not been opened. ...
[ "def", "GetNumberOfRows", "(", "self", ",", "table_name", ")", ":", "if", "not", "self", ".", "_connection", ":", "raise", "IOError", "(", "'Not opened.'", ")", "self", ".", "_cursor", ".", "execute", "(", "self", ".", "_NUMBER_OF_ROWS_QUERY", ".", "format",...
Retrieves the number of rows in the table. Args: table_name (str): name of the table. Returns: int: number of rows. Raises: IOError: if the file-like object has not been opened. OSError: if the file-like object has not been opened.
[ "Retrieves", "the", "number", "of", "rows", "in", "the", "table", "." ]
python
train
summa-tx/riemann
riemann/tx/tx.py
https://github.com/summa-tx/riemann/blob/04ae336dfd4007ceaed748daadc91cc32fa278ec/riemann/tx/tx.py#L604-L614
def _sighash_final_hashing(self, copy_tx, sighash_type): ''' Tx, int -> bytes Returns the hash that should be signed https://en.bitcoin.it/wiki/OP_CHECKSIG#Procedure_for_Hashtype_SIGHASH_ANYONECANPAY ''' sighash = ByteData() sighash += copy_tx.to_bytes() s...
[ "def", "_sighash_final_hashing", "(", "self", ",", "copy_tx", ",", "sighash_type", ")", ":", "sighash", "=", "ByteData", "(", ")", "sighash", "+=", "copy_tx", ".", "to_bytes", "(", ")", "sighash", "+=", "utils", ".", "i2le_padded", "(", "sighash_type", ",", ...
Tx, int -> bytes Returns the hash that should be signed https://en.bitcoin.it/wiki/OP_CHECKSIG#Procedure_for_Hashtype_SIGHASH_ANYONECANPAY
[ "Tx", "int", "-", ">", "bytes", "Returns", "the", "hash", "that", "should", "be", "signed", "https", ":", "//", "en", ".", "bitcoin", ".", "it", "/", "wiki", "/", "OP_CHECKSIG#Procedure_for_Hashtype_SIGHASH_ANYONECANPAY" ]
python
train
numenta/nupic
src/nupic/database/client_jobs_dao.py
https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/client_jobs_dao.py#L2782-L2825
def modelSetCompleted(self, modelID, completionReason, completionMsg, cpuTime=0, useConnectionID=True): """ Mark a model as completed, with the given completionReason and completionMsg. This will fail if the model does not currently belong to this client (connection_id doesn't match)...
[ "def", "modelSetCompleted", "(", "self", ",", "modelID", ",", "completionReason", ",", "completionMsg", ",", "cpuTime", "=", "0", ",", "useConnectionID", "=", "True", ")", ":", "if", "completionMsg", "is", "None", ":", "completionMsg", "=", "''", "query", "=...
Mark a model as completed, with the given completionReason and completionMsg. This will fail if the model does not currently belong to this client (connection_id doesn't match). Parameters: ---------------------------------------------------------------- modelID: model ID of model to mo...
[ "Mark", "a", "model", "as", "completed", "with", "the", "given", "completionReason", "and", "completionMsg", ".", "This", "will", "fail", "if", "the", "model", "does", "not", "currently", "belong", "to", "this", "client", "(", "connection_id", "doesn", "t", ...
python
valid
apache/incubator-heron
heronpy/streamlet/streamlet.py
https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/streamlet/streamlet.py#L233-L244
def _default_stage_name_calculator(self, prefix, existing_stage_names): """This is the method that's implemented by the operators to get the name of the Streamlet :return: The name of the operator """ index = 1 calculated_name = "" while True: calculated_name = prefix + "-" + str(index) ...
[ "def", "_default_stage_name_calculator", "(", "self", ",", "prefix", ",", "existing_stage_names", ")", ":", "index", "=", "1", "calculated_name", "=", "\"\"", "while", "True", ":", "calculated_name", "=", "prefix", "+", "\"-\"", "+", "str", "(", "index", ")", ...
This is the method that's implemented by the operators to get the name of the Streamlet :return: The name of the operator
[ "This", "is", "the", "method", "that", "s", "implemented", "by", "the", "operators", "to", "get", "the", "name", "of", "the", "Streamlet", ":", "return", ":", "The", "name", "of", "the", "operator" ]
python
valid
ZeitOnline/briefkasten
application/briefkasten/__init__.py
https://github.com/ZeitOnline/briefkasten/blob/ce6b6eeb89196014fe21d68614c20059d02daa11/application/briefkasten/__init__.py#L51-L62
def is_equal(a, b): """ a constant time comparison implementation taken from http://codahale.com/a-lesson-in-timing-attacks/ and Django's `util` module https://github.com/django/django/blob/master/django/utils/crypto.py#L82 """ if len(a) != len(b): return False result = 0 fo...
[ "def", "is_equal", "(", "a", ",", "b", ")", ":", "if", "len", "(", "a", ")", "!=", "len", "(", "b", ")", ":", "return", "False", "result", "=", "0", "for", "x", ",", "y", "in", "zip", "(", "a", ",", "b", ")", ":", "result", "|=", "ord", "...
a constant time comparison implementation taken from http://codahale.com/a-lesson-in-timing-attacks/ and Django's `util` module https://github.com/django/django/blob/master/django/utils/crypto.py#L82
[ "a", "constant", "time", "comparison", "implementation", "taken", "from", "http", ":", "//", "codahale", ".", "com", "/", "a", "-", "lesson", "-", "in", "-", "timing", "-", "attacks", "/", "and", "Django", "s", "util", "module", "https", ":", "//", "gi...
python
valid
sporsh/carnifex
fabfile.py
https://github.com/sporsh/carnifex/blob/82dd3bd2bc134dfb69a78f43171e227f2127060b/fabfile.py#L22-L30
def trial(path=TESTS_PATH, coverage=False): """Run tests using trial """ args = ['trial'] if coverage: args.append('--coverage') args.append(path) print args local(' '.join(args))
[ "def", "trial", "(", "path", "=", "TESTS_PATH", ",", "coverage", "=", "False", ")", ":", "args", "=", "[", "'trial'", "]", "if", "coverage", ":", "args", ".", "append", "(", "'--coverage'", ")", "args", ".", "append", "(", "path", ")", "print", "args...
Run tests using trial
[ "Run", "tests", "using", "trial" ]
python
train
kxxoling/flask-decorators
flask_decorators/__init__.py
https://github.com/kxxoling/flask-decorators/blob/e0bf4fc1a5260548063ef8b8adbb782151cd72cc/flask_decorators/__init__.py#L46-L64
def gen(mimetype): """``gen`` is a decorator factory function, you just need to set a mimetype before using:: @app.route('/') @gen('') def index(): pass A full demo for creating a image stream is available on `GitHub <https://github.com/kxxoling/flask-video-streamin...
[ "def", "gen", "(", "mimetype", ")", ":", "def", "streaming", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "@", "wraps", "(", "func", ")", "def", "_", "(", ")", ":", "return", "Response", "(", "func", "(", "*", "args", ",", ...
``gen`` is a decorator factory function, you just need to set a mimetype before using:: @app.route('/') @gen('') def index(): pass A full demo for creating a image stream is available on `GitHub <https://github.com/kxxoling/flask-video-streaming>`__ .
[ "gen", "is", "a", "decorator", "factory", "function", "you", "just", "need", "to", "set", "a", "mimetype", "before", "using", "::" ]
python
train
indico/indico-plugins
piwik/indico_piwik/queries/metrics.py
https://github.com/indico/indico-plugins/blob/fe50085cc63be9b8161b09539e662e7b04e4b38e/piwik/indico_piwik/queries/metrics.py#L69-L81
def _get_cumulative_results(self, results): """ Returns a dictionary of {'total': x, 'unique': y} for the date range. """ hits = {'total': 0, 'unique': 0} day_hits = list(hits[0] for hits in results.values() if hits) for metrics in day_hits: hits['tot...
[ "def", "_get_cumulative_results", "(", "self", ",", "results", ")", ":", "hits", "=", "{", "'total'", ":", "0", ",", "'unique'", ":", "0", "}", "day_hits", "=", "list", "(", "hits", "[", "0", "]", "for", "hits", "in", "results", ".", "values", "(", ...
Returns a dictionary of {'total': x, 'unique': y} for the date range.
[ "Returns", "a", "dictionary", "of", "{", "total", ":", "x", "unique", ":", "y", "}", "for", "the", "date", "range", "." ]
python
train
django-danceschool/django-danceschool
danceschool/core/forms.py
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/forms.py#L942-L947
def save(self, commit=True): ''' If the staff member is an instructor, also update the availableForPrivates field on the Instructor record. ''' if getattr(self.instance,'instructor',None): self.instance.instructor.availableForPrivates = self.cleaned_data.pop('availableForPrivates',self.insta...
[ "def", "save", "(", "self", ",", "commit", "=", "True", ")", ":", "if", "getattr", "(", "self", ".", "instance", ",", "'instructor'", ",", "None", ")", ":", "self", ".", "instance", ".", "instructor", ".", "availableForPrivates", "=", "self", ".", "cle...
If the staff member is an instructor, also update the availableForPrivates field on the Instructor record.
[ "If", "the", "staff", "member", "is", "an", "instructor", "also", "update", "the", "availableForPrivates", "field", "on", "the", "Instructor", "record", "." ]
python
train
Kane610/deconz
pydeconz/group.py
https://github.com/Kane610/deconz/blob/8a9498dbbc8c168d4a081173ad6c3b1e17fffdf6/pydeconz/group.py#L46-L61
async def async_set_state(self, data): """Set state of light group. { "on": true, "bri": 180, "hue": 43680, "sat": 255, "transitiontime": 10 } Also update local values of group since websockets doesn't. """ fie...
[ "async", "def", "async_set_state", "(", "self", ",", "data", ")", ":", "field", "=", "self", ".", "deconz_id", "+", "'/action'", "await", "self", ".", "_async_set_state_callback", "(", "field", ",", "data", ")", "self", ".", "async_update", "(", "{", "'sta...
Set state of light group. { "on": true, "bri": 180, "hue": 43680, "sat": 255, "transitiontime": 10 } Also update local values of group since websockets doesn't.
[ "Set", "state", "of", "light", "group", "." ]
python
train
Qiskit/qiskit-terra
qiskit/visualization/counts_visualization.py
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/counts_visualization.py#L45-L184
def plot_histogram(data, figsize=(7, 5), color=None, number_to_keep=None, sort='asc', target_string=None, legend=None, bar_labels=True, title=None): """Plot a histogram of data. Args: data (list or dict): This is either a list of dictionaries or a single ...
[ "def", "plot_histogram", "(", "data", ",", "figsize", "=", "(", "7", ",", "5", ")", ",", "color", "=", "None", ",", "number_to_keep", "=", "None", ",", "sort", "=", "'asc'", ",", "target_string", "=", "None", ",", "legend", "=", "None", ",", "bar_lab...
Plot a histogram of data. Args: data (list or dict): This is either a list of dictionaries or a single dict containing the values to represent (ex {'001': 130}) figsize (tuple): Figure size in inches. color (list or str): String or list of strings for histogram bar colors. ...
[ "Plot", "a", "histogram", "of", "data", "." ]
python
test
basecrm/basecrm-python
basecrm/services.py
https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L528-L541
def list(self, **params): """ Retrieve all deal unqualified reasons Returns all deal unqualified reasons available to the user according to the parameters provided :calls: ``get /deal_unqualified_reasons`` :param dict params: (optional) Search options. :return: List of ...
[ "def", "list", "(", "self", ",", "*", "*", "params", ")", ":", "_", ",", "_", ",", "deal_unqualified_reasons", "=", "self", ".", "http_client", ".", "get", "(", "\"/deal_unqualified_reasons\"", ",", "params", "=", "params", ")", "return", "deal_unqualified_r...
Retrieve all deal unqualified reasons Returns all deal unqualified reasons available to the user according to the parameters provided :calls: ``get /deal_unqualified_reasons`` :param dict params: (optional) Search options. :return: List of dictionaries that support attriubte-style acce...
[ "Retrieve", "all", "deal", "unqualified", "reasons" ]
python
train
AltSchool/dynamic-rest
dynamic_rest/routers.py
https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/routers.py#L108-L154
def register(self, prefix, viewset, base_name=None): """Add any registered route into a global API directory. If the prefix includes a path separator, store the URL in the directory under the first path segment. Otherwise, store it as-is. For example, if there are two registere...
[ "def", "register", "(", "self", ",", "prefix", ",", "viewset", ",", "base_name", "=", "None", ")", ":", "if", "base_name", "is", "None", ":", "base_name", "=", "prefix", "super", "(", "DynamicRouter", ",", "self", ")", ".", "register", "(", "prefix", "...
Add any registered route into a global API directory. If the prefix includes a path separator, store the URL in the directory under the first path segment. Otherwise, store it as-is. For example, if there are two registered prefixes, 'v1/users' and 'groups', `directory` will lo...
[ "Add", "any", "registered", "route", "into", "a", "global", "API", "directory", "." ]
python
train
twilio/twilio-python
twilio/rest/ip_messaging/v2/service/channel/message.py
https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/ip_messaging/v2/service/channel/message.py#L230-L244
def get_instance(self, payload): """ Build an instance of MessageInstance :param dict payload: Payload response from the API :returns: twilio.rest.chat.v2.service.channel.message.MessageInstance :rtype: twilio.rest.chat.v2.service.channel.message.MessageInstance """ ...
[ "def", "get_instance", "(", "self", ",", "payload", ")", ":", "return", "MessageInstance", "(", "self", ".", "_version", ",", "payload", ",", "service_sid", "=", "self", ".", "_solution", "[", "'service_sid'", "]", ",", "channel_sid", "=", "self", ".", "_s...
Build an instance of MessageInstance :param dict payload: Payload response from the API :returns: twilio.rest.chat.v2.service.channel.message.MessageInstance :rtype: twilio.rest.chat.v2.service.channel.message.MessageInstance
[ "Build", "an", "instance", "of", "MessageInstance" ]
python
train
dillonhicks/rekt
rekt/service.py
https://github.com/dillonhicks/rekt/blob/3848b272726c78214cb96b906f9b9f289497f27e/rekt/service.py#L227-L249
def create_rest_client_class(name, apis, BaseClass=RestClient): """ Generate the api call functions and attach them to the generated RestClient subclass with the name <Service>Client. """ apis_with_actions = list(itertools.chain.from_iterable([ zip([api] * len(api.actions), api.actions) for api in ...
[ "def", "create_rest_client_class", "(", "name", ",", "apis", ",", "BaseClass", "=", "RestClient", ")", ":", "apis_with_actions", "=", "list", "(", "itertools", ".", "chain", ".", "from_iterable", "(", "[", "zip", "(", "[", "api", "]", "*", "len", "(", "a...
Generate the api call functions and attach them to the generated RestClient subclass with the name <Service>Client.
[ "Generate", "the", "api", "call", "functions", "and", "attach", "them", "to", "the", "generated", "RestClient", "subclass", "with", "the", "name", "<Service", ">", "Client", "." ]
python
train
cuihantao/andes
andes/utils/time.py
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/utils/time.py#L5-L19
def elapsed(t0=0.0): """get elapsed time from the give time Returns: now: the absolute time now dt_str: elapsed time in string """ now = time() dt = now - t0 dt_sec = Decimal(str(dt)).quantize(Decimal('.0001'), rounding=ROUND_DOWN) if dt_sec <= 1: dt_str = str(dt...
[ "def", "elapsed", "(", "t0", "=", "0.0", ")", ":", "now", "=", "time", "(", ")", "dt", "=", "now", "-", "t0", "dt_sec", "=", "Decimal", "(", "str", "(", "dt", ")", ")", ".", "quantize", "(", "Decimal", "(", "'.0001'", ")", ",", "rounding", "=",...
get elapsed time from the give time Returns: now: the absolute time now dt_str: elapsed time in string
[ "get", "elapsed", "time", "from", "the", "give", "time" ]
python
train
senaite/senaite.core
bika/lims/browser/analysisrequest/analysisrequests.py
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/analysisrequest/analysisrequests.py#L434-L517
def update(self): """Called before the listing renders """ super(AnalysisRequestsView, self).update() self.workflow = api.get_tool("portal_workflow") self.member = self.mtool.getAuthenticatedMember() self.roles = self.member.getRoles() setup = api.get_bika_setup...
[ "def", "update", "(", "self", ")", ":", "super", "(", "AnalysisRequestsView", ",", "self", ")", ".", "update", "(", ")", "self", ".", "workflow", "=", "api", ".", "get_tool", "(", "\"portal_workflow\"", ")", "self", ".", "member", "=", "self", ".", "mt...
Called before the listing renders
[ "Called", "before", "the", "listing", "renders" ]
python
train
pypa/pipenv
pipenv/vendor/click/utils.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/utils.py#L105-L121
def open(self): """Opens the file if it's not yet open. This call might fail with a :exc:`FileError`. Not handling this error will produce an error that Click shows. """ if self._f is not None: return self._f try: rv, self.should_close = open_str...
[ "def", "open", "(", "self", ")", ":", "if", "self", ".", "_f", "is", "not", "None", ":", "return", "self", ".", "_f", "try", ":", "rv", ",", "self", ".", "should_close", "=", "open_stream", "(", "self", ".", "name", ",", "self", ".", "mode", ",",...
Opens the file if it's not yet open. This call might fail with a :exc:`FileError`. Not handling this error will produce an error that Click shows.
[ "Opens", "the", "file", "if", "it", "s", "not", "yet", "open", ".", "This", "call", "might", "fail", "with", "a", ":", "exc", ":", "FileError", ".", "Not", "handling", "this", "error", "will", "produce", "an", "error", "that", "Click", "shows", "." ]
python
train
mixmastamyk/fr
fr/utils.py
https://github.com/mixmastamyk/fr/blob/f96df8ed7210a033b9e711bbed768d4116213bfb/fr/utils.py#L67-L74
def run(cmd, shell=False, debug=False): 'Run a command and return the output.' proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=shell) (out, _) = proc.communicate() # no need for stderr if debug: print(cmd) print(out) return out
[ "def", "run", "(", "cmd", ",", "shell", "=", "False", ",", "debug", "=", "False", ")", ":", "proc", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "shell", "=", "shell", ")", "(", "out", ",", "_",...
Run a command and return the output.
[ "Run", "a", "command", "and", "return", "the", "output", "." ]
python
train
scottrice/pysteam
pysteam/_crc_algorithms.py
https://github.com/scottrice/pysteam/blob/1eb2254b5235a053a953e596fa7602d0b110245d/pysteam/_crc_algorithms.py#L190-L212
def gen_table(self): """ This function generates the CRC table used for the table_driven CRC algorithm. The Python version cannot handle tables of an index width other than 8. See the generated C code for tables with different sizes instead. """ table_length = 1...
[ "def", "gen_table", "(", "self", ")", ":", "table_length", "=", "1", "<<", "self", ".", "TableIdxWidth", "tbl", "=", "[", "0", "]", "*", "table_length", "for", "i", "in", "range", "(", "table_length", ")", ":", "register", "=", "i", "if", "self", "."...
This function generates the CRC table used for the table_driven CRC algorithm. The Python version cannot handle tables of an index width other than 8. See the generated C code for tables with different sizes instead.
[ "This", "function", "generates", "the", "CRC", "table", "used", "for", "the", "table_driven", "CRC", "algorithm", ".", "The", "Python", "version", "cannot", "handle", "tables", "of", "an", "index", "width", "other", "than", "8", ".", "See", "the", "generated...
python
train
tyarkoni/pliers
pliers/external/tensorflow/classify_image.py
https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/external/tensorflow/classify_image.py#L130-L167
def run_inference_on_image(image): """Runs inference on an image. Args: image: Image file name. Returns: Nothing """ if not tf.gfile.Exists(image): tf.logging.fatal('File does not exist %s', image) image_data = tf.gfile.FastGFile(image, 'rb').read() # Creates graph from saved GraphDef. cr...
[ "def", "run_inference_on_image", "(", "image", ")", ":", "if", "not", "tf", ".", "gfile", ".", "Exists", "(", "image", ")", ":", "tf", ".", "logging", ".", "fatal", "(", "'File does not exist %s'", ",", "image", ")", "image_data", "=", "tf", ".", "gfile"...
Runs inference on an image. Args: image: Image file name. Returns: Nothing
[ "Runs", "inference", "on", "an", "image", "." ]
python
train
MagicStack/asyncpg
asyncpg/pool.py
https://github.com/MagicStack/asyncpg/blob/92c2d81256a1efd8cab12c0118d74ccd1c18131b/asyncpg/pool.py#L276-L293
def _release(self): """Release this connection holder.""" if self._in_use is None: # The holder is not checked out. return if not self._in_use.done(): self._in_use.set_result(None) self._in_use = None # Deinitialize the connection proxy. All...
[ "def", "_release", "(", "self", ")", ":", "if", "self", ".", "_in_use", "is", "None", ":", "# The holder is not checked out.", "return", "if", "not", "self", ".", "_in_use", ".", "done", "(", ")", ":", "self", ".", "_in_use", ".", "set_result", "(", "Non...
Release this connection holder.
[ "Release", "this", "connection", "holder", "." ]
python
train
pletzer/pnumpy
src/pnGhostedDistArray.py
https://github.com/pletzer/pnumpy/blob/9e6d308be94a42637466b91ab1a7b4d64b4c29ae/src/pnGhostedDistArray.py#L161-L172
def gmdaZeros(shape, dtype, mask=None, numGhosts=1): """ ghosted distributed array zero constructor @param shape the shape of the array @param dtype the numpy data type @param numGhosts the number of ghosts (>= 0) """ res = GhostedMaskedDistArray(shape, dtype) res.mas = mask res.setN...
[ "def", "gmdaZeros", "(", "shape", ",", "dtype", ",", "mask", "=", "None", ",", "numGhosts", "=", "1", ")", ":", "res", "=", "GhostedMaskedDistArray", "(", "shape", ",", "dtype", ")", "res", ".", "mas", "=", "mask", "res", ".", "setNumberOfGhosts", "(",...
ghosted distributed array zero constructor @param shape the shape of the array @param dtype the numpy data type @param numGhosts the number of ghosts (>= 0)
[ "ghosted", "distributed", "array", "zero", "constructor" ]
python
train
outini/python-pylls
pylls/cachet.py
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/cachet.py#L303-L334
def update(self, incident_id, name=None, message=None, status=None, visible=None, component_id=None, component_status=None, notify=None, created_at=None, template=None, tpl_vars=None): """Update an Incident :param int incident_id: Incident ID :param str name: Name ...
[ "def", "update", "(", "self", ",", "incident_id", ",", "name", "=", "None", ",", "message", "=", "None", ",", "status", "=", "None", ",", "visible", "=", "None", ",", "component_id", "=", "None", ",", "component_status", "=", "None", ",", "notify", "="...
Update an Incident :param int incident_id: Incident ID :param str name: Name of the incident :param str message: Incident explanation message :param int status: Status of the incident :param int visible: Whether the incident is publicly visible :param int component_id: C...
[ "Update", "an", "Incident" ]
python
train
liampauling/betfair
betfairlightweight/resources/baseresource.py
https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/resources/baseresource.py#L26-L39
def strip_datetime(value): """ Converts value to datetime if string or int. """ if isinstance(value, basestring): try: return parse_datetime(value) except ValueError: return elif isinstance(value, integer_types): ...
[ "def", "strip_datetime", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "basestring", ")", ":", "try", ":", "return", "parse_datetime", "(", "value", ")", "except", "ValueError", ":", "return", "elif", "isinstance", "(", "value", ",", "inte...
Converts value to datetime if string or int.
[ "Converts", "value", "to", "datetime", "if", "string", "or", "int", "." ]
python
train
maxharp3r/archive-rotator
archive_rotator/rotator.py
https://github.com/maxharp3r/archive-rotator/blob/40b8e571461c54717cee7daead04dbc9751062c8/archive_rotator/rotator.py#L85-L92
def _locate_files_to_delete(algorithm, rotated_files, next_rotation_id): """Looks for hanoi_rotator generated files that occupy the same slot that will be given to rotation_id. """ rotation_slot = algorithm.id_to_slot(next_rotation_id) for a_path, a_rotation_id in rotated_files: if rotation_...
[ "def", "_locate_files_to_delete", "(", "algorithm", ",", "rotated_files", ",", "next_rotation_id", ")", ":", "rotation_slot", "=", "algorithm", ".", "id_to_slot", "(", "next_rotation_id", ")", "for", "a_path", ",", "a_rotation_id", "in", "rotated_files", ":", "if", ...
Looks for hanoi_rotator generated files that occupy the same slot that will be given to rotation_id.
[ "Looks", "for", "hanoi_rotator", "generated", "files", "that", "occupy", "the", "same", "slot", "that", "will", "be", "given", "to", "rotation_id", "." ]
python
train
fhs/pyhdf
pyhdf/V.py
https://github.com/fhs/pyhdf/blob/dbdc1810a74a38df50dcad81fe903e239d2b388d/pyhdf/V.py#L1039-L1059
def delete(self, tag, ref): """Delete from the vgroup the member identified by its tag and reference number. Args:: tag tag of the member to delete ref reference number of the member to delete Returns:: None Only the link of the member wit...
[ "def", "delete", "(", "self", ",", "tag", ",", "ref", ")", ":", "_checkErr", "(", "'delete'", ",", "_C", ".", "Vdeletetagref", "(", "self", ".", "_id", ",", "tag", ",", "ref", ")", ",", "\"error deleting member\"", ")" ]
Delete from the vgroup the member identified by its tag and reference number. Args:: tag tag of the member to delete ref reference number of the member to delete Returns:: None Only the link of the member with the vgroup is deleted. The me...
[ "Delete", "from", "the", "vgroup", "the", "member", "identified", "by", "its", "tag", "and", "reference", "number", "." ]
python
train
fedora-infra/fedora-messaging
fedora_messaging/config.py
https://github.com/fedora-infra/fedora-messaging/blob/be3e88534e2b15d579bcd24f9c4b7e795cb7e0b7/fedora_messaging/config.py#L391-L418
def validate_queues(queues): """ Validate the queues configuration. Raises: exceptions.ConfigurationException: If the configuration provided is of an invalid format. """ if not isinstance(queues, dict): raise exceptions.ConfigurationException( "'queues' must ...
[ "def", "validate_queues", "(", "queues", ")", ":", "if", "not", "isinstance", "(", "queues", ",", "dict", ")", ":", "raise", "exceptions", ".", "ConfigurationException", "(", "\"'queues' must be a dictionary mapping queue names to settings.\"", ")", "for", "queue", ",...
Validate the queues configuration. Raises: exceptions.ConfigurationException: If the configuration provided is of an invalid format.
[ "Validate", "the", "queues", "configuration", "." ]
python
train
ouroboroscoding/format-oc-python
FormatOC/__init__.py
https://github.com/ouroboroscoding/format-oc-python/blob/c160b46fe4ff2c92333c776991c712de23991225/FormatOC/__init__.py#L2217-L2228
def keys(self): """Keys Returns a list of the node names in the parent Returns: list """ if hasattr(self._nodes, 'iterkeys'): return self._nodes.keys() else: return tuple(self._nodes.keys())
[ "def", "keys", "(", "self", ")", ":", "if", "hasattr", "(", "self", ".", "_nodes", ",", "'iterkeys'", ")", ":", "return", "self", ".", "_nodes", ".", "keys", "(", ")", "else", ":", "return", "tuple", "(", "self", ".", "_nodes", ".", "keys", "(", ...
Keys Returns a list of the node names in the parent Returns: list
[ "Keys" ]
python
train
alimanfoo/csvvalidator
csvvalidator.py
https://github.com/alimanfoo/csvvalidator/blob/50a86eefdc549c48f65a91a5c0a66099010ee65d/csvvalidator.py#L883-L905
def _apply_skips(self, i, r, summarize=False, report_unexpected_exceptions=True, context=None): """Apply skip functions on `r`.""" for skip in self._skips: try: result = skip(r) if result is True:...
[ "def", "_apply_skips", "(", "self", ",", "i", ",", "r", ",", "summarize", "=", "False", ",", "report_unexpected_exceptions", "=", "True", ",", "context", "=", "None", ")", ":", "for", "skip", "in", "self", ".", "_skips", ":", "try", ":", "result", "=",...
Apply skip functions on `r`.
[ "Apply", "skip", "functions", "on", "r", "." ]
python
valid
poppy-project/pypot
pypot/primitive/primitive.py
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/primitive/primitive.py#L116-L124
def start(self): """ Start or restart (the :meth:`~pypot.primitive.primitive.Primitive.stop` method will automatically be called) the primitive. """ if not self.robot._primitive_manager.running: raise RuntimeError('Cannot run a primitive when the sync is stopped!') StoppableThread.s...
[ "def", "start", "(", "self", ")", ":", "if", "not", "self", ".", "robot", ".", "_primitive_manager", ".", "running", ":", "raise", "RuntimeError", "(", "'Cannot run a primitive when the sync is stopped!'", ")", "StoppableThread", ".", "start", "(", "self", ")", ...
Start or restart (the :meth:`~pypot.primitive.primitive.Primitive.stop` method will automatically be called) the primitive.
[ "Start", "or", "restart", "(", "the", ":", "meth", ":", "~pypot", ".", "primitive", ".", "primitive", ".", "Primitive", ".", "stop", "method", "will", "automatically", "be", "called", ")", "the", "primitive", "." ]
python
train
pypa/pipenv
pipenv/vendor/pyparsing.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pyparsing.py#L3067-L3094
def sub(self, repl): """ Return Regex with an attached parse action to transform the parsed result as if called using `re.sub(expr, repl, string) <https://docs.python.org/3/library/re.html#re.sub>`_. Example:: make_html = Regex(r"(\w+):(.*?):").sub(r"<\1>\2</\1>") ...
[ "def", "sub", "(", "self", ",", "repl", ")", ":", "if", "self", ".", "asGroupList", ":", "warnings", ".", "warn", "(", "\"cannot use sub() with Regex(asGroupList=True)\"", ",", "SyntaxWarning", ",", "stacklevel", "=", "2", ")", "raise", "SyntaxError", "(", ")"...
Return Regex with an attached parse action to transform the parsed result as if called using `re.sub(expr, repl, string) <https://docs.python.org/3/library/re.html#re.sub>`_. Example:: make_html = Regex(r"(\w+):(.*?):").sub(r"<\1>\2</\1>") print(make_html.transformString("h1:ma...
[ "Return", "Regex", "with", "an", "attached", "parse", "action", "to", "transform", "the", "parsed", "result", "as", "if", "called", "using", "re", ".", "sub", "(", "expr", "repl", "string", ")", "<https", ":", "//", "docs", ".", "python", ".", "org", "...
python
train
paolodragone/pymzn
pymzn/mzn/minizinc.py
https://github.com/paolodragone/pymzn/blob/35b04cfb244918551649b9bb8a0ab65d37c31fe4/pymzn/mzn/minizinc.py#L502-L658
def minizinc( mzn, *dzn_files, args=None, data=None, include=None, stdlib_dir=None, globals_dir=None, declare_enums=True, allow_multiple_assignments=False, keep=False, output_vars=None, output_base=None, output_mode='dict', solver=None, timeout=None, two_pass=None, pre_passes=None, output_objective=...
[ "def", "minizinc", "(", "mzn", ",", "*", "dzn_files", ",", "args", "=", "None", ",", "data", "=", "None", ",", "include", "=", "None", ",", "stdlib_dir", "=", "None", ",", "globals_dir", "=", "None", ",", "declare_enums", "=", "True", ",", "allow_multi...
Implements the workflow for solving a CSP problem encoded with MiniZinc. Parameters ---------- mzn : str The minizinc model. This can be either the path to the ``.mzn`` file or the content of the model itself. *dzn_files A list of paths to dzn files to attach to the minizinc exe...
[ "Implements", "the", "workflow", "for", "solving", "a", "CSP", "problem", "encoded", "with", "MiniZinc", "." ]
python
train
pywbem/pywbem
pywbem/cim_obj.py
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_obj.py#L4063-L4074
def path(self, path): """Setter method; for a description see the getter method.""" # pylint: disable=attribute-defined-outside-init self._path = copy_.copy(path) # The provided path is shallow copied; it does not have any attributes # with mutable types. # We perform ...
[ "def", "path", "(", "self", ",", "path", ")", ":", "# pylint: disable=attribute-defined-outside-init", "self", ".", "_path", "=", "copy_", ".", "copy", "(", "path", ")", "# The provided path is shallow copied; it does not have any attributes", "# with mutable types.", "# We...
Setter method; for a description see the getter method.
[ "Setter", "method", ";", "for", "a", "description", "see", "the", "getter", "method", "." ]
python
train
mozilla-services/python-dockerflow
src/dockerflow/flask/app.py
https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/flask/app.py#L354-L391
def check(self, func=None, name=None): """ A decorator to register a new Dockerflow check to be run when the /__heartbeat__ endpoint is called., e.g.:: from dockerflow.flask import checks @dockerflow.check def storage_reachable(): try: ...
[ "def", "check", "(", "self", ",", "func", "=", "None", ",", "name", "=", "None", ")", ":", "if", "func", "is", "None", ":", "return", "functools", ".", "partial", "(", "self", ".", "check", ",", "name", "=", "name", ")", "if", "name", "is", "None...
A decorator to register a new Dockerflow check to be run when the /__heartbeat__ endpoint is called., e.g.:: from dockerflow.flask import checks @dockerflow.check def storage_reachable(): try: acme.storage.ping() except Sl...
[ "A", "decorator", "to", "register", "a", "new", "Dockerflow", "check", "to", "be", "run", "when", "the", "/", "__heartbeat__", "endpoint", "is", "called", ".", "e", ".", "g", ".", "::" ]
python
train
llazzaro/analyzerstrategies
analyzerstrategies/periodStrategy.py
https://github.com/llazzaro/analyzerstrategies/blob/3c647802f582bf2f06c6793f282bee0d26514cd6/analyzerstrategies/periodStrategy.py#L27-L34
def increase_and_check_counter(self): ''' increase counter by one and check whether a period is end ''' self.counter += 1 self.counter %= self.period if not self.counter: return True else: return False
[ "def", "increase_and_check_counter", "(", "self", ")", ":", "self", ".", "counter", "+=", "1", "self", ".", "counter", "%=", "self", ".", "period", "if", "not", "self", ".", "counter", ":", "return", "True", "else", ":", "return", "False" ]
increase counter by one and check whether a period is end
[ "increase", "counter", "by", "one", "and", "check", "whether", "a", "period", "is", "end" ]
python
train
jwodder/javaproperties
javaproperties/propclass.py
https://github.com/jwodder/javaproperties/blob/8b48f040305217ebeb80c98c4354691bbb01429b/javaproperties/propclass.py#L155-L167
def store(self, out, comments=None): """ Write the `Properties` object's entries (in unspecified order) in ``.properties`` format to ``out``, including the current timestamp. :param out: A file-like object to write the properties to. It must have been opened as a text file ...
[ "def", "store", "(", "self", ",", "out", ",", "comments", "=", "None", ")", ":", "dump", "(", "self", ".", "data", ",", "out", ",", "comments", "=", "comments", ")" ]
Write the `Properties` object's entries (in unspecified order) in ``.properties`` format to ``out``, including the current timestamp. :param out: A file-like object to write the properties to. It must have been opened as a text file with a Latin-1-compatible encoding. :param commen...
[ "Write", "the", "Properties", "object", "s", "entries", "(", "in", "unspecified", "order", ")", "in", ".", "properties", "format", "to", "out", "including", "the", "current", "timestamp", "." ]
python
train
ionelmc/python-hunter
src/hunter/event.py
https://github.com/ionelmc/python-hunter/blob/b3a1310b0593d2c6b6ef430883843896e17d6a81/src/hunter/event.py#L247-L258
def source(self, getline=linecache.getline): """ A string with the sourcecode for the current line (from ``linecache`` - failures are ignored). Fast but sometimes incomplete. :type: str """ try: return getline(self.filename, self.lineno) except Excep...
[ "def", "source", "(", "self", ",", "getline", "=", "linecache", ".", "getline", ")", ":", "try", ":", "return", "getline", "(", "self", ".", "filename", ",", "self", ".", "lineno", ")", "except", "Exception", "as", "exc", ":", "return", "\"??? NO SOURCE:...
A string with the sourcecode for the current line (from ``linecache`` - failures are ignored). Fast but sometimes incomplete. :type: str
[ "A", "string", "with", "the", "sourcecode", "for", "the", "current", "line", "(", "from", "linecache", "-", "failures", "are", "ignored", ")", "." ]
python
train
Rapptz/discord.py
discord/ext/commands/help.py
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/help.py#L865-L869
def shorten_text(self, text): """Shortens text to fit into the :attr:`width`.""" if len(text) > self.width: return text[:self.width - 3] + '...' return text
[ "def", "shorten_text", "(", "self", ",", "text", ")", ":", "if", "len", "(", "text", ")", ">", "self", ".", "width", ":", "return", "text", "[", ":", "self", ".", "width", "-", "3", "]", "+", "'...'", "return", "text" ]
Shortens text to fit into the :attr:`width`.
[ "Shortens", "text", "to", "fit", "into", "the", ":", "attr", ":", "width", "." ]
python
train
tempodb/tempodb-python
tempodb/protocol/objects.py
https://github.com/tempodb/tempodb-python/blob/8ce45231bd728c6c97ef799cf0f1513ea3a9a7d3/tempodb/protocol/objects.py#L475-L502
def from_json(self, json_text): """Deserialize a JSON object into this object. This method will check that the JSON object has the required keys and will set each of the keys in that JSON object as an instance attribute of this object. :param json_text: the JSON text or object ...
[ "def", "from_json", "(", "self", ",", "json_text", ")", ":", "if", "type", "(", "json_text", ")", "in", "[", "str", ",", "unicode", "]", ":", "j", "=", "json", ".", "loads", "(", "json_text", ")", "else", ":", "j", "=", "json_text", "try", ":", "...
Deserialize a JSON object into this object. This method will check that the JSON object has the required keys and will set each of the keys in that JSON object as an instance attribute of this object. :param json_text: the JSON text or object to deserialize from :type json_text...
[ "Deserialize", "a", "JSON", "object", "into", "this", "object", ".", "This", "method", "will", "check", "that", "the", "JSON", "object", "has", "the", "required", "keys", "and", "will", "set", "each", "of", "the", "keys", "in", "that", "JSON", "object", ...
python
train
pyblish/pyblish-qml
pyblish_qml/vendor/mock.py
https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/vendor/mock.py#L1879-L1886
def mock_add_spec(self, spec, spec_set=False): """Add a spec to a mock. `spec` can either be an object or a list of strings. Only attributes on the `spec` can be fetched as attributes from the mock. If `spec_set` is True then only attributes on the spec can be set.""" self._mock...
[ "def", "mock_add_spec", "(", "self", ",", "spec", ",", "spec_set", "=", "False", ")", ":", "self", ".", "_mock_add_spec", "(", "spec", ",", "spec_set", ")", "self", ".", "_mock_set_magics", "(", ")" ]
Add a spec to a mock. `spec` can either be an object or a list of strings. Only attributes on the `spec` can be fetched as attributes from the mock. If `spec_set` is True then only attributes on the spec can be set.
[ "Add", "a", "spec", "to", "a", "mock", ".", "spec", "can", "either", "be", "an", "object", "or", "a", "list", "of", "strings", ".", "Only", "attributes", "on", "the", "spec", "can", "be", "fetched", "as", "attributes", "from", "the", "mock", "." ]
python
train
data-8/datascience
datascience/tables.py
https://github.com/data-8/datascience/blob/4cee38266903ca169cea4a53b8cc39502d85c464/datascience/tables.py#L2765-L2776
def _is_array_integer(arr): """Returns True if an array contains integers (integer type or near-int float values) and False otherwise. >>> _is_array_integer(np.arange(10)) True >>> _is_array_integer(np.arange(7.0, 20.0, 1.0)) True >>> _is_array_integer(np.arange(0, 1, 0.1)) False ""...
[ "def", "_is_array_integer", "(", "arr", ")", ":", "return", "issubclass", "(", "arr", ".", "dtype", ".", "type", ",", "np", ".", "integer", ")", "or", "np", ".", "allclose", "(", "arr", ",", "np", ".", "round", "(", "arr", ")", ")" ]
Returns True if an array contains integers (integer type or near-int float values) and False otherwise. >>> _is_array_integer(np.arange(10)) True >>> _is_array_integer(np.arange(7.0, 20.0, 1.0)) True >>> _is_array_integer(np.arange(0, 1, 0.1)) False
[ "Returns", "True", "if", "an", "array", "contains", "integers", "(", "integer", "type", "or", "near", "-", "int", "float", "values", ")", "and", "False", "otherwise", "." ]
python
train
Erotemic/utool
utool/util_latex.py
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_latex.py#L727-L875
def get_latex_figure_str(fpath_list, caption_str=None, label_str=None, width_str=r'\textwidth', height_str=None, nCols=None, dpath=None, colpos_sep=' ', nlsep='', use_sublbls=None, use_frame=False): r""" Args: fpath_list (list): ...
[ "def", "get_latex_figure_str", "(", "fpath_list", ",", "caption_str", "=", "None", ",", "label_str", "=", "None", ",", "width_str", "=", "r'\\textwidth'", ",", "height_str", "=", "None", ",", "nCols", "=", "None", ",", "dpath", "=", "None", ",", "colpos_sep"...
r""" Args: fpath_list (list): dpath (str): directory relative to main tex file Returns: str: figure_str CommandLine: python -m utool.util_latex --test-get_latex_figure_str Example: >>> # DISABLE_DOCTEST >>> from utool.util_latex import * # NOQA ...
[ "r", "Args", ":", "fpath_list", "(", "list", ")", ":", "dpath", "(", "str", ")", ":", "directory", "relative", "to", "main", "tex", "file" ]
python
train
xtuml/pyxtuml
xtuml/load.py
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/load.py#L274-L282
def populate_unique_identifiers(self, metamodel): ''' Populate a *metamodel* with class unique identifiers previously encountered from input. ''' for stmt in self.statements: if isinstance(stmt, CreateUniqueStmt): metamodel.define_unique_identifier(stm...
[ "def", "populate_unique_identifiers", "(", "self", ",", "metamodel", ")", ":", "for", "stmt", "in", "self", ".", "statements", ":", "if", "isinstance", "(", "stmt", ",", "CreateUniqueStmt", ")", ":", "metamodel", ".", "define_unique_identifier", "(", "stmt", "...
Populate a *metamodel* with class unique identifiers previously encountered from input.
[ "Populate", "a", "*", "metamodel", "*", "with", "class", "unique", "identifiers", "previously", "encountered", "from", "input", "." ]
python
test
ThreshingFloor/libtf
libtf/logparsers/tf_log_base.py
https://github.com/ThreshingFloor/libtf/blob/f1a8710f750639c9b9e2a468ece0d2923bf8c3df/libtf/logparsers/tf_log_base.py#L80-L92
def reduce(self, show_noisy=False): """ Yield the reduced log lines :param show_noisy: If this is true, shows the reduced log file. If this is false, it shows the logs that were deleted. """ if not show_noisy: for log in self.quiet_logs: yield...
[ "def", "reduce", "(", "self", ",", "show_noisy", "=", "False", ")", ":", "if", "not", "show_noisy", ":", "for", "log", "in", "self", ".", "quiet_logs", ":", "yield", "log", "[", "'raw'", "]", ".", "strip", "(", ")", "else", ":", "for", "log", "in",...
Yield the reduced log lines :param show_noisy: If this is true, shows the reduced log file. If this is false, it shows the logs that were deleted.
[ "Yield", "the", "reduced", "log", "lines" ]
python
train
mitsei/dlkit
dlkit/json_/hierarchy/sessions.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/hierarchy/sessions.py#L555-L570
def remove_root(self, id_): """Removes a root node. arg: id (osid.id.Id): the ``Id`` of the node raise: NotFound - ``id`` was not found or not in hierarchy raise: NullArgument - ``id`` is ``null`` raise: OperationFailed - unable to complete request raise: Permissi...
[ "def", "remove_root", "(", "self", ",", "id_", ")", ":", "result", "=", "self", ".", "_rls", ".", "get_relationships_by_genus_type_for_peers", "(", "self", ".", "_phantom_root_id", ",", "id_", ",", "self", ".", "_relationship_type", ")", "if", "not", "bool", ...
Removes a root node. arg: id (osid.id.Id): the ``Id`` of the node raise: NotFound - ``id`` was not found or not in hierarchy raise: NullArgument - ``id`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure ...
[ "Removes", "a", "root", "node", "." ]
python
train
uber/doubles
doubles/class_double.py
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/class_double.py#L7-L20
def patch_class(input_class): """Create a new class based on the input_class. :param class input_class: The class to patch. :rtype class: """ class Instantiator(object): @classmethod def _doubles__new__(self, *args, **kwargs): pass new_class = type(input_class.__na...
[ "def", "patch_class", "(", "input_class", ")", ":", "class", "Instantiator", "(", "object", ")", ":", "@", "classmethod", "def", "_doubles__new__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "pass", "new_class", "=", "type", "(", ...
Create a new class based on the input_class. :param class input_class: The class to patch. :rtype class:
[ "Create", "a", "new", "class", "based", "on", "the", "input_class", "." ]
python
train
titusjan/argos
argos/repo/rtiplugins/pillowio.py
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/rtiplugins/pillowio.py#L135-L153
def dimensionNames(self): """ Returns ['Y', 'X', 'Band']. The underlying array is expected to be 3-dimensional. If this is not the case we fall back on the default dimension names ['Dim-0', 'Dim-1', ...] """ if self._array is None: return [] if self._...
[ "def", "dimensionNames", "(", "self", ")", ":", "if", "self", ".", "_array", "is", "None", ":", "return", "[", "]", "if", "self", ".", "_array", ".", "ndim", "==", "2", ":", "return", "[", "'Y'", ",", "'X'", "]", "elif", "self", ".", "_array", "....
Returns ['Y', 'X', 'Band']. The underlying array is expected to be 3-dimensional. If this is not the case we fall back on the default dimension names ['Dim-0', 'Dim-1', ...]
[ "Returns", "[", "Y", "X", "Band", "]", ".", "The", "underlying", "array", "is", "expected", "to", "be", "3", "-", "dimensional", ".", "If", "this", "is", "not", "the", "case", "we", "fall", "back", "on", "the", "default", "dimension", "names", "[", "...
python
train
pallets/werkzeug
examples/simplewiki/actions.py
https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/examples/simplewiki/actions.py#L45-L85
def on_edit(request, page_name): """Edit the current revision of a page.""" change_note = error = "" revision = ( Revision.query.filter( (Page.name == page_name) & (Page.page_id == Revision.page_id) ) .order_by(Revision.revision_id.desc()) .first() ) if re...
[ "def", "on_edit", "(", "request", ",", "page_name", ")", ":", "change_note", "=", "error", "=", "\"\"", "revision", "=", "(", "Revision", ".", "query", ".", "filter", "(", "(", "Page", ".", "name", "==", "page_name", ")", "&", "(", "Page", ".", "page...
Edit the current revision of a page.
[ "Edit", "the", "current", "revision", "of", "a", "page", "." ]
python
train
cloud-custodian/cloud-custodian
tools/sandbox/c7n_sphere11/c7n_sphere11/controller.py
https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/sandbox/c7n_sphere11/c7n_sphere11/controller.py#L50-L60
def get_session(self, account_id): """Get an active session in the target account.""" if account_id not in self.account_sessions: if account_id not in self.config['accounts']: raise AccountNotFound("account:%s is unknown" % account_id) self.account_sessions[accou...
[ "def", "get_session", "(", "self", ",", "account_id", ")", ":", "if", "account_id", "not", "in", "self", ".", "account_sessions", ":", "if", "account_id", "not", "in", "self", ".", "config", "[", "'accounts'", "]", ":", "raise", "AccountNotFound", "(", "\"...
Get an active session in the target account.
[ "Get", "an", "active", "session", "in", "the", "target", "account", "." ]
python
train
tensorflow/tensor2tensor
tensor2tensor/trax/models/transformer.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/models/transformer.py#L123-L151
def DecoderLayer(feature_depth, feedforward_depth, num_heads, dropout, mode): """Transformer decoder layer. Args: feature_depth: int: depth of embedding feedforward_depth: int: depth of feed-forward layer num_heads: int: number of att...
[ "def", "DecoderLayer", "(", "feature_depth", ",", "feedforward_depth", ",", "num_heads", ",", "dropout", ",", "mode", ")", ":", "return", "layers", ".", "Serial", "(", "layers", ".", "Residual", "(", "# Self-attention block.", "layers", ".", "LayerNorm", "(", ...
Transformer decoder layer. Args: feature_depth: int: depth of embedding feedforward_depth: int: depth of feed-forward layer num_heads: int: number of attention heads dropout: float: dropout rate (how much to drop out) mode: str: 'train' or 'eval' Returns: the layer.
[ "Transformer", "decoder", "layer", "." ]
python
train
Shapeways/coyote_framework
coyote_framework/util/apps/objects.py
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/util/apps/objects.py#L6-L12
def objectify(dictionary, name='Object'): """Converts a dictionary into a named tuple (shallow) """ o = namedtuple(name, dictionary.keys())(*dictionary.values()) return o
[ "def", "objectify", "(", "dictionary", ",", "name", "=", "'Object'", ")", ":", "o", "=", "namedtuple", "(", "name", ",", "dictionary", ".", "keys", "(", ")", ")", "(", "*", "dictionary", ".", "values", "(", ")", ")", "return", "o" ]
Converts a dictionary into a named tuple (shallow)
[ "Converts", "a", "dictionary", "into", "a", "named", "tuple", "(", "shallow", ")" ]
python
train
rq/Flask-RQ2
src/flask_rq2/functions.py
https://github.com/rq/Flask-RQ2/blob/58eedf6f0cd7bcde4ccd787074762ea08f531337/src/flask_rq2/functions.py#L223-L279
def cron(self, pattern, name, *args, **kwargs): """ A function to setup a RQ job as a cronjob:: @rq.job('low', timeout=60) def add(x, y): return x + y add.cron('* * * * *', 'add-some-numbers', 1, 2, timeout=10) :param \\*args: The positional...
[ "def", "cron", "(", "self", ",", "pattern", ",", "name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "queue_name", "=", "kwargs", ".", "pop", "(", "'queue'", ",", "self", ".", "queue_name", ")", "timeout", "=", "kwargs", ".", "pop", "(", ...
A function to setup a RQ job as a cronjob:: @rq.job('low', timeout=60) def add(x, y): return x + y add.cron('* * * * *', 'add-some-numbers', 1, 2, timeout=10) :param \\*args: The positional arguments to pass to the queued job. :param \\*\\*kwargs: ...
[ "A", "function", "to", "setup", "a", "RQ", "job", "as", "a", "cronjob", "::" ]
python
train
3DLIRIOUS/MeshLabXML
meshlabxml/transform.py
https://github.com/3DLIRIOUS/MeshLabXML/blob/177cce21e92baca500f56a932d66bd9a33257af8/meshlabxml/transform.py#L623-L655
def wrap2cylinder(script, radius=1, pitch=0, taper=0, pitch_func=None, taper_func=None): """Deform mesh around cylinder of radius and axis z y = 0 will be on the surface of radius "radius" pitch != 0 will create a helix, with distance "pitch" traveled in z for each rotation taper = ch...
[ "def", "wrap2cylinder", "(", "script", ",", "radius", "=", "1", ",", "pitch", "=", "0", ",", "taper", "=", "0", ",", "pitch_func", "=", "None", ",", "taper_func", "=", "None", ")", ":", "\"\"\"vert_function(s=s, x='(%s+y-taper)*sin(x/(%s+y))' % (radius, radius),\n...
Deform mesh around cylinder of radius and axis z y = 0 will be on the surface of radius "radius" pitch != 0 will create a helix, with distance "pitch" traveled in z for each rotation taper = change in r over z. E.g. a value of 0.5 will shrink r by 0.5 for every z length of 1
[ "Deform", "mesh", "around", "cylinder", "of", "radius", "and", "axis", "z" ]
python
test
cloud9ers/gurumate
environment/lib/python2.7/site-packages/nose/plugins/prof.py
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/plugins/prof.py#L33-L54
def options(self, parser, env): """Register commandline options. """ if not self.available(): return Plugin.options(self, parser, env) parser.add_option('--profile-sort', action='store', dest='profile_sort', default=env.get('NOSE_PROFILE_SORT...
[ "def", "options", "(", "self", ",", "parser", ",", "env", ")", ":", "if", "not", "self", ".", "available", "(", ")", ":", "return", "Plugin", ".", "options", "(", "self", ",", "parser", ",", "env", ")", "parser", ".", "add_option", "(", "'--profile-s...
Register commandline options.
[ "Register", "commandline", "options", "." ]
python
test
polyaxon/rhea
rhea/manager.py
https://github.com/polyaxon/rhea/blob/f47b59777cd996d834a0497a1ab442541aaa8a62/rhea/manager.py#L231-L285
def get_dict(self, key, is_list=False, is_optional=False, is_secret=False, is_local=False, default=None, options=None): """ Get a the value corresponding to the key and converts it to `...
[ "def", "get_dict", "(", "self", ",", "key", ",", "is_list", "=", "False", ",", "is_optional", "=", "False", ",", "is_secret", "=", "False", ",", "is_local", "=", "False", ",", "default", "=", "None", ",", "options", "=", "None", ")", ":", "def", "con...
Get a the value corresponding to the key and converts it to `dict`. Args: key: the dict key. is_list: If this is one element or a list of elements. is_optional: To raise an error if key was not found. is_secret: If the key is a secret. is_local: If th...
[ "Get", "a", "the", "value", "corresponding", "to", "the", "key", "and", "converts", "it", "to", "dict", "." ]
python
train
google-research/batch-ppo
agents/algorithms/ppo/ppo.py
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/algorithms/ppo/ppo.py#L382-L415
def _update_step(self, sequence): """Compute the current combined loss and perform a gradient update step. The sequences must be a dict containing the keys `length` and `sequence`, where the latter is a tuple containing observations, actions, parameters of the behavioral policy, rewards, and advantages...
[ "def", "_update_step", "(", "self", ",", "sequence", ")", ":", "observ", ",", "action", ",", "old_policy_params", ",", "reward", ",", "advantage", "=", "sequence", "[", "'sequence'", "]", "length", "=", "sequence", "[", "'length'", "]", "old_policy", "=", ...
Compute the current combined loss and perform a gradient update step. The sequences must be a dict containing the keys `length` and `sequence`, where the latter is a tuple containing observations, actions, parameters of the behavioral policy, rewards, and advantages. Args: sequence: Sequences of...
[ "Compute", "the", "current", "combined", "loss", "and", "perform", "a", "gradient", "update", "step", "." ]
python
train
9wfox/tornadoweb
tornadoweb/utility.py
https://github.com/9wfox/tornadoweb/blob/2286b66fbe10e4d9f212b979664c15fa17adf378/tornadoweb/utility.py#L28-L40
def get_modules(pkg_name, module_filter = None): """ 返回包中所有符合条件的模块。 参数: pkg_name 包名称 module_filter 模块名过滤器 def (module_name) """ path = app_path(pkg_name) #py_filter = lambda f: all((fnmatch(f, "*.py"), not f.startswith("__"), module_filter and m...
[ "def", "get_modules", "(", "pkg_name", ",", "module_filter", "=", "None", ")", ":", "path", "=", "app_path", "(", "pkg_name", ")", "#py_filter = lambda f: all((fnmatch(f, \"*.py\"), not f.startswith(\"__\"), module_filter and module_filter(f) or True))\r", "py_filter", "=", "la...
返回包中所有符合条件的模块。 参数: pkg_name 包名称 module_filter 模块名过滤器 def (module_name)
[ "返回包中所有符合条件的模块。", "参数", ":", "pkg_name", "包名称", "module_filter", "模块名过滤器", "def", "(", "module_name", ")" ]
python
train
SuryaSankar/flask-sqlalchemy-booster
flask_sqlalchemy_booster/model_booster/queryable_mixin.py
https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L203-L235
def update(self, **kwargs): """Updates an instance. Args: **kwargs : Arbitrary keyword arguments. Column names are keywords and their new values are the values. Examples: >>> customer.update(email="newemail@x.com", name="new") """ kwa...
[ "def", "update", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "self", ".", "_preprocess_params", "(", "kwargs", ")", "kwargs", "=", "self", ".", "preprocess_kwargs_before_update", "(", "kwargs", ")", "for", "key", ",", "value", "in", "k...
Updates an instance. Args: **kwargs : Arbitrary keyword arguments. Column names are keywords and their new values are the values. Examples: >>> customer.update(email="newemail@x.com", name="new")
[ "Updates", "an", "instance", "." ]
python
train
LEMS/pylems
lems/model/simulation.py
https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/model/simulation.py#L367-L397
def toxml(self): """ Exports this object into a LEMS XML object """ chxmlstr = '' for run in self.runs: chxmlstr += run.toxml() for record in self.records: chxmlstr += record.toxml() for event_record in self.event_records: c...
[ "def", "toxml", "(", "self", ")", ":", "chxmlstr", "=", "''", "for", "run", "in", "self", ".", "runs", ":", "chxmlstr", "+=", "run", ".", "toxml", "(", ")", "for", "record", "in", "self", ".", "records", ":", "chxmlstr", "+=", "record", ".", "toxml...
Exports this object into a LEMS XML object
[ "Exports", "this", "object", "into", "a", "LEMS", "XML", "object" ]
python
train
fermiPy/fermipy
fermipy/jobs/batch.py
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/batch.py#L17-L41
def get_batch_job_args(job_time=1500): """ Get the correct set of batch jobs arguments. Parameters ---------- job_time : int Expected max length of the job, in seconds. This is used to select the batch queue and set the job_check_sleep parameter that sets how often we c...
[ "def", "get_batch_job_args", "(", "job_time", "=", "1500", ")", ":", "if", "DEFAULT_JOB_TYPE", "==", "'slac'", ":", "from", "fermipy", ".", "jobs", ".", "slac_impl", "import", "get_slac_default_args", "return", "get_slac_default_args", "(", "job_time", ")", "elif"...
Get the correct set of batch jobs arguments. Parameters ---------- job_time : int Expected max length of the job, in seconds. This is used to select the batch queue and set the job_check_sleep parameter that sets how often we check for job completion. Returns -----...
[ "Get", "the", "correct", "set", "of", "batch", "jobs", "arguments", "." ]
python
train
tnkteja/myhelp
virtualEnvironment/lib/python2.7/site-packages/coverage/control.py
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/control.py#L495-L510
def combine(self): """Combine together a number of similarly-named coverage data files. All coverage data files whose name starts with `data_file` (from the coverage() constructor) will be read, and combined together into the current measurements. """ aliases = None ...
[ "def", "combine", "(", "self", ")", ":", "aliases", "=", "None", "if", "self", ".", "config", ".", "paths", ":", "aliases", "=", "PathAliases", "(", "self", ".", "file_locator", ")", "for", "paths", "in", "self", ".", "config", ".", "paths", ".", "va...
Combine together a number of similarly-named coverage data files. All coverage data files whose name starts with `data_file` (from the coverage() constructor) will be read, and combined together into the current measurements.
[ "Combine", "together", "a", "number", "of", "similarly", "-", "named", "coverage", "data", "files", "." ]
python
test
rueckstiess/mtools
mtools/util/logevent.py
https://github.com/rueckstiess/mtools/blob/a6a22910c3569c0c8a3908660ca218a4557e4249/mtools/util/logevent.py#L618-L624
def w(self): """Extract write lock (w) counter if available (lazy).""" if not self._counters_calculated: self._counters_calculated = True self._extract_counters() return self._w
[ "def", "w", "(", "self", ")", ":", "if", "not", "self", ".", "_counters_calculated", ":", "self", ".", "_counters_calculated", "=", "True", "self", ".", "_extract_counters", "(", ")", "return", "self", ".", "_w" ]
Extract write lock (w) counter if available (lazy).
[ "Extract", "write", "lock", "(", "w", ")", "counter", "if", "available", "(", "lazy", ")", "." ]
python
train
StagPython/StagPy
stagpy/args.py
https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/args.py#L65-L103
def parse_args(arglist=None): """Parse cmd line arguments. Update :attr:`stagpy.conf` accordingly. Args: arglist (list of str): the list of cmd line arguments. If set to None, the arguments are taken from :attr:`sys.argv`. Returns: function: the function implementing the s...
[ "def", "parse_args", "(", "arglist", "=", "None", ")", ":", "climan", "=", "CLIManager", "(", "conf", ",", "*", "*", "SUB_CMDS", ")", "create_complete_files", "(", "climan", ",", "CONFIG_DIR", ",", "'stagpy'", ",", "'stagpy-git'", ",", "zsh_sourceable", "=",...
Parse cmd line arguments. Update :attr:`stagpy.conf` accordingly. Args: arglist (list of str): the list of cmd line arguments. If set to None, the arguments are taken from :attr:`sys.argv`. Returns: function: the function implementing the sub command to be executed.
[ "Parse", "cmd", "line", "arguments", "." ]
python
train
jonathf/chaospy
chaospy/distributions/operators/trunkation.py
https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/distributions/operators/trunkation.py#L163-L194
def _ppf(self, q, left, right, cache): """ Point percentile function. Example: >>> print(chaospy.Uniform().inv([0.1, 0.2, 0.9])) [0.1 0.2 0.9] >>> print(chaospy.Trunc(chaospy.Uniform(), 0.4).inv([0.1, 0.2, 0.9])) [0.04 0.08 0.36] >>> p...
[ "def", "_ppf", "(", "self", ",", "q", ",", "left", ",", "right", ",", "cache", ")", ":", "if", "isinstance", "(", "left", ",", "Dist", ")", "and", "left", "in", "cache", ":", "left", "=", "cache", "[", "left", "]", "if", "isinstance", "(", "right...
Point percentile function. Example: >>> print(chaospy.Uniform().inv([0.1, 0.2, 0.9])) [0.1 0.2 0.9] >>> print(chaospy.Trunc(chaospy.Uniform(), 0.4).inv([0.1, 0.2, 0.9])) [0.04 0.08 0.36] >>> print(chaospy.Trunc(0.6, chaospy.Uniform()).inv([0.1, 0.2, 0...
[ "Point", "percentile", "function", "." ]
python
train
user-cont/conu
conu/utils/probes.py
https://github.com/user-cont/conu/blob/08caae7bb6bdd265b55bb106c3da6a7946a5a352/conu/utils/probes.py#L92-L116
def _wrapper(self, q, start): """ _wrapper checks return status of Probe.fnc and provides the result for process managing :param q: Queue for function results :param start: Time of function run (used for logging) :return: Return value or Exception """ tr...
[ "def", "_wrapper", "(", "self", ",", "q", ",", "start", ")", ":", "try", ":", "func_name", "=", "self", ".", "fnc", ".", "__name__", "except", "AttributeError", ":", "func_name", "=", "str", "(", "self", ".", "fnc", ")", "logger", ".", "debug", "(", ...
_wrapper checks return status of Probe.fnc and provides the result for process managing :param q: Queue for function results :param start: Time of function run (used for logging) :return: Return value or Exception
[ "_wrapper", "checks", "return", "status", "of", "Probe", ".", "fnc", "and", "provides", "the", "result", "for", "process", "managing" ]
python
train
pydata/xarray
xarray/core/dataset.py
https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/core/dataset.py#L923-L933
def _level_coords(self): """Return a mapping of all MultiIndex levels and their corresponding coordinate name. """ level_coords = OrderedDict() for name, index in self.indexes.items(): if isinstance(index, pd.MultiIndex): level_names = index.names ...
[ "def", "_level_coords", "(", "self", ")", ":", "level_coords", "=", "OrderedDict", "(", ")", "for", "name", ",", "index", "in", "self", ".", "indexes", ".", "items", "(", ")", ":", "if", "isinstance", "(", "index", ",", "pd", ".", "MultiIndex", ")", ...
Return a mapping of all MultiIndex levels and their corresponding coordinate name.
[ "Return", "a", "mapping", "of", "all", "MultiIndex", "levels", "and", "their", "corresponding", "coordinate", "name", "." ]
python
train
cltk/cltk
cltk/inflection/old_norse/phonemic_rules.py
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/inflection/old_norse/phonemic_rules.py#L122-L213
def add_r_ending_to_syllable(last_syllable: str, is_first=True) -> str: """ Adds an the -r ending to the last syllable of an Old Norse word. In some cases, it really adds an -r. In other cases, it on doubles the last character or left the syllable unchanged. >>> add_r_ending_to_syllable("arm", True...
[ "def", "add_r_ending_to_syllable", "(", "last_syllable", ":", "str", ",", "is_first", "=", "True", ")", "->", "str", ":", "if", "len", "(", "last_syllable", ")", ">=", "2", ":", "if", "last_syllable", "[", "-", "1", "]", "in", "[", "'l'", ",", "'n'", ...
Adds an the -r ending to the last syllable of an Old Norse word. In some cases, it really adds an -r. In other cases, it on doubles the last character or left the syllable unchanged. >>> add_r_ending_to_syllable("arm", True) 'armr' >>> add_r_ending_to_syllable("ás", True) 'áss' >>> add_r_...
[ "Adds", "an", "the", "-", "r", "ending", "to", "the", "last", "syllable", "of", "an", "Old", "Norse", "word", ".", "In", "some", "cases", "it", "really", "adds", "an", "-", "r", ".", "In", "other", "cases", "it", "on", "doubles", "the", "last", "ch...
python
train
mitsei/dlkit
dlkit/json_/grading/sessions.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/grading/sessions.py#L705-L747
def create_grade_system(self, grade_system_form): """Creates a new ``GradeSystem``. arg: grade_system_form (osid.grading.GradeSystemForm): the form for this ``GradeSystem`` return: (osid.grading.GradeSystem) - the new ``GradeSystem`` raise: IllegalState - ``grade_sys...
[ "def", "create_grade_system", "(", "self", ",", "grade_system_form", ")", ":", "# Implemented from template for", "# osid.resource.ResourceAdminSession.create_resource_template", "collection", "=", "JSONClientValidated", "(", "'grading'", ",", "collection", "=", "'GradeSystem'", ...
Creates a new ``GradeSystem``. arg: grade_system_form (osid.grading.GradeSystemForm): the form for this ``GradeSystem`` return: (osid.grading.GradeSystem) - the new ``GradeSystem`` raise: IllegalState - ``grade_system_form`` already used in a create transacti...
[ "Creates", "a", "new", "GradeSystem", "." ]
python
train
GoogleCloudPlatform/appengine-gcs-client
python/src/cloudstorage/storage_api.py
https://github.com/GoogleCloudPlatform/appengine-gcs-client/blob/d11078331ecd915d753c886e96a80133599f3f98/python/src/cloudstorage/storage_api.py#L332-L372
def readline(self, size=-1): """Read one line delimited by '\n' from the file. A trailing newline character is kept in the string. It may be absent when a file ends with an incomplete line. If the size argument is non-negative, it specifies the maximum string size (counting the newline) to return. ...
[ "def", "readline", "(", "self", ",", "size", "=", "-", "1", ")", ":", "self", ".", "_check_open", "(", ")", "if", "size", "==", "0", "or", "not", "self", ".", "_remaining", "(", ")", ":", "return", "''", "data_list", "=", "[", "]", "newline_offset"...
Read one line delimited by '\n' from the file. A trailing newline character is kept in the string. It may be absent when a file ends with an incomplete line. If the size argument is non-negative, it specifies the maximum string size (counting the newline) to return. A negative size is the same as unspe...
[ "Read", "one", "line", "delimited", "by", "\\", "n", "from", "the", "file", "." ]
python
train
jic-dtool/dtoolcore
dtoolcore/storagebroker.py
https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/storagebroker.py#L372-L400
def list_dataset_uris(cls, base_uri, config_path): """Return list containing URIs in location given by base_uri.""" parsed_uri = generous_parse_uri(base_uri) uri_list = [] path = parsed_uri.path if IS_WINDOWS: path = unix_to_windows_path(parsed_uri.path, parsed_uri....
[ "def", "list_dataset_uris", "(", "cls", ",", "base_uri", ",", "config_path", ")", ":", "parsed_uri", "=", "generous_parse_uri", "(", "base_uri", ")", "uri_list", "=", "[", "]", "path", "=", "parsed_uri", ".", "path", "if", "IS_WINDOWS", ":", "path", "=", "...
Return list containing URIs in location given by base_uri.
[ "Return", "list", "containing", "URIs", "in", "location", "given", "by", "base_uri", "." ]
python
train
xgfs/NetLSD
netlsd/kernels.py
https://github.com/xgfs/NetLSD/blob/54820b3669a94852bd9653be23b09e126e901ab3/netlsd/kernels.py#L208-L247
def _wkt(eivals, timescales, normalization, normalized_laplacian): """ Computes wave kernel trace from given eigenvalues, timescales, and normalization. For precise definition, please refer to "NetLSD: Hearing the Shape of a Graph" by A. Tsitsulin, D. Mottin, P. Karras, A. Bronstein, E. Müller. Published a...
[ "def", "_wkt", "(", "eivals", ",", "timescales", ",", "normalization", ",", "normalized_laplacian", ")", ":", "nv", "=", "eivals", ".", "shape", "[", "0", "]", "wkt", "=", "np", ".", "zeros", "(", "timescales", ".", "shape", ")", "for", "idx", ",", "...
Computes wave kernel trace from given eigenvalues, timescales, and normalization. For precise definition, please refer to "NetLSD: Hearing the Shape of a Graph" by A. Tsitsulin, D. Mottin, P. Karras, A. Bronstein, E. Müller. Published at KDD'18. Parameters ---------- eivals : numpy.ndarray ...
[ "Computes", "wave", "kernel", "trace", "from", "given", "eigenvalues", "timescales", "and", "normalization", "." ]
python
train
bfontaine/p7magma
magma/courses.py
https://github.com/bfontaine/p7magma/blob/713647aa9e3187c93c2577ef812f33ec42ae5494/magma/courses.py#L105-L125
def _populate_large_table(self, trs): """ Populate the list, given that ``trs`` is a ``BeautifulSoup`` elements list from a large table (8 columns). """ for tr in trs: tds = tr.select('td') cs = Course( code=coursecode(tds[0]), ...
[ "def", "_populate_large_table", "(", "self", ",", "trs", ")", ":", "for", "tr", "in", "trs", ":", "tds", "=", "tr", ".", "select", "(", "'td'", ")", "cs", "=", "Course", "(", "code", "=", "coursecode", "(", "tds", "[", "0", "]", ")", ",", "title"...
Populate the list, given that ``trs`` is a ``BeautifulSoup`` elements list from a large table (8 columns).
[ "Populate", "the", "list", "given", "that", "trs", "is", "a", "BeautifulSoup", "elements", "list", "from", "a", "large", "table", "(", "8", "columns", ")", "." ]
python
train
PyPSA/PyPSA
pypsa/pf.py
https://github.com/PyPSA/PyPSA/blob/46954b1b3c21460550f7104681517065279a53b7/pypsa/pf.py#L155-L185
def newton_raphson_sparse(f, guess, dfdx, x_tol=1e-10, lim_iter=100): """Solve f(x) = 0 with initial guess for x and dfdx(x). dfdx(x) should return a sparse Jacobian. Terminate if error on norm of f(x) is < x_tol or there were more than lim_iter iterations. """ converged = False n_iter = 0 ...
[ "def", "newton_raphson_sparse", "(", "f", ",", "guess", ",", "dfdx", ",", "x_tol", "=", "1e-10", ",", "lim_iter", "=", "100", ")", ":", "converged", "=", "False", "n_iter", "=", "0", "F", "=", "f", "(", "guess", ")", "diff", "=", "norm", "(", "F", ...
Solve f(x) = 0 with initial guess for x and dfdx(x). dfdx(x) should return a sparse Jacobian. Terminate if error on norm of f(x) is < x_tol or there were more than lim_iter iterations.
[ "Solve", "f", "(", "x", ")", "=", "0", "with", "initial", "guess", "for", "x", "and", "dfdx", "(", "x", ")", ".", "dfdx", "(", "x", ")", "should", "return", "a", "sparse", "Jacobian", ".", "Terminate", "if", "error", "on", "norm", "of", "f", "(",...
python
train
ciena/afkak
afkak/producer.py
https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/producer.py#L235-L252
def stop(self): """ Terminate any outstanding requests. :returns: :class:``Deferred` which fires when fully stopped. """ self.stopping = True # Cancel any outstanding request to our client if self._batch_send_d: self._batch_send_d.cancel() # D...
[ "def", "stop", "(", "self", ")", ":", "self", ".", "stopping", "=", "True", "# Cancel any outstanding request to our client", "if", "self", ".", "_batch_send_d", ":", "self", ".", "_batch_send_d", ".", "cancel", "(", ")", "# Do we have to worry about our looping call?...
Terminate any outstanding requests. :returns: :class:``Deferred` which fires when fully stopped.
[ "Terminate", "any", "outstanding", "requests", "." ]
python
train
log2timeline/plaso
plaso/analysis/windows_services.py
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/analysis/windows_services.py#L230-L253
def CompileReport(self, mediator): """Compiles an analysis report. Args: mediator (AnalysisMediator): mediates interactions between analysis plugins and other components, such as storage and dfvfs. Returns: AnalysisReport: report. """ # TODO: move YAML representation out of p...
[ "def", "CompileReport", "(", "self", ",", "mediator", ")", ":", "# TODO: move YAML representation out of plugin and into serialization.", "lines_of_text", "=", "[", "]", "if", "self", ".", "_output_format", "==", "'yaml'", ":", "lines_of_text", ".", "append", "(", "ya...
Compiles an analysis report. Args: mediator (AnalysisMediator): mediates interactions between analysis plugins and other components, such as storage and dfvfs. Returns: AnalysisReport: report.
[ "Compiles", "an", "analysis", "report", "." ]
python
train
sorgerlab/indra
rest_api/api.py
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/rest_api/api.py#L534-L543
def map_grounding(): """Map grounding on a list of INDRA Statements.""" if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) stmts_json = body.get('statements') stmts = stmts_from_json(stmts_json) stmts_out = ac.map_grou...
[ "def", "map_grounding", "(", ")", ":", "if", "request", ".", "method", "==", "'OPTIONS'", ":", "return", "{", "}", "response", "=", "request", ".", "body", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "body", "=", "json", ".", "loads", ...
Map grounding on a list of INDRA Statements.
[ "Map", "grounding", "on", "a", "list", "of", "INDRA", "Statements", "." ]
python
train
scizzorz/bumpy
bumpy.py
https://github.com/scizzorz/bumpy/blob/99ed5c5ccaa61842cafe9faf8b082de44bdf01f9/bumpy.py#L270-L293
def require(*reqs): '''Require tasks or files at runtime.''' for req in reqs: if type(req) is str: # does not exist and unknown generator if not os.path.exists(req) and req not in GENERATES: abort(LOCALE['abort_bad_file'].format(req)) # exists but unknown generator if req not in GENERATES: retu...
[ "def", "require", "(", "*", "reqs", ")", ":", "for", "req", "in", "reqs", ":", "if", "type", "(", "req", ")", "is", "str", ":", "# does not exist and unknown generator", "if", "not", "os", ".", "path", ".", "exists", "(", "req", ")", "and", "req", "n...
Require tasks or files at runtime.
[ "Require", "tasks", "or", "files", "at", "runtime", "." ]
python
train
phoebe-project/phoebe2
phoebe/frontend/bundle.py
https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/frontend/bundle.py#L3320-L3330
def remove_model(self, model, **kwargs): """ Remove a 'model' from the bundle :parameter str twig: twig to filter for the model :parameter **kwargs: any other tags to do the filter (except twig or context) """ kwargs['model'] = model kwargs['context']...
[ "def", "remove_model", "(", "self", ",", "model", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'model'", "]", "=", "model", "kwargs", "[", "'context'", "]", "=", "'model'", "self", ".", "remove_parameters_all", "(", "*", "*", "kwargs", ")" ]
Remove a 'model' from the bundle :parameter str twig: twig to filter for the model :parameter **kwargs: any other tags to do the filter (except twig or context)
[ "Remove", "a", "model", "from", "the", "bundle" ]
python
train
waqasbhatti/astrobase
astrobase/lcmodels/eclipses.py
https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcmodels/eclipses.py#L19-L46
def _gaussian(x, amp, loc, std): '''This is a simple gaussian. Parameters ---------- x : np.array The items at which the Gaussian is evaluated. amp : float The amplitude of the Gaussian. loc : float The central value of the Gaussian. std : float The stand...
[ "def", "_gaussian", "(", "x", ",", "amp", ",", "loc", ",", "std", ")", ":", "return", "amp", "*", "np", ".", "exp", "(", "-", "(", "(", "x", "-", "loc", ")", "*", "(", "x", "-", "loc", ")", ")", "/", "(", "2.0", "*", "std", "*", "std", ...
This is a simple gaussian. Parameters ---------- x : np.array The items at which the Gaussian is evaluated. amp : float The amplitude of the Gaussian. loc : float The central value of the Gaussian. std : float The standard deviation of the Gaussian. Retu...
[ "This", "is", "a", "simple", "gaussian", "." ]
python
valid
spyder-ide/spyder
spyder/utils/introspection/rope_patch.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/introspection/rope_patch.py#L30-L211
def apply(): """Monkey patching rope See [1], [2], [3], [4] and [5] in module docstring.""" from spyder.utils.programs import is_module_installed if is_module_installed('rope', '<0.9.4'): import rope raise ImportError("rope %s can't be patched" % rope.VERSION) # [1] Patchi...
[ "def", "apply", "(", ")", ":", "from", "spyder", ".", "utils", ".", "programs", "import", "is_module_installed", "if", "is_module_installed", "(", "'rope'", ",", "'<0.9.4'", ")", ":", "import", "rope", "raise", "ImportError", "(", "\"rope %s can't be patched\"", ...
Monkey patching rope See [1], [2], [3], [4] and [5] in module docstring.
[ "Monkey", "patching", "rope", "See", "[", "1", "]", "[", "2", "]", "[", "3", "]", "[", "4", "]", "and", "[", "5", "]", "in", "module", "docstring", "." ]
python
train
pdkit/pdkit
pdkit/finger_tapping_processor.py
https://github.com/pdkit/pdkit/blob/c7120263da2071bb139815fbdb56ca77b544f340/pdkit/finger_tapping_processor.py#L209-L229
def extract_features(self, data_frame, pre=''): """ This method extracts all the features available to the Finger Tapping Processor class. :param data_frame: the data frame :type data_frame: pandas.DataFrame :return: 'frequency', 'moving_frequency','continuous_fr...
[ "def", "extract_features", "(", "self", ",", "data_frame", ",", "pre", "=", "''", ")", ":", "try", ":", "return", "{", "pre", "+", "'frequency'", ":", "self", ".", "frequency", "(", "data_frame", ")", "[", "0", "]", ",", "pre", "+", "'mean_moving_time'...
This method extracts all the features available to the Finger Tapping Processor class. :param data_frame: the data frame :type data_frame: pandas.DataFrame :return: 'frequency', 'moving_frequency','continuous_frequency','mean_moving_time','incoordination_score', \ ...
[ "This", "method", "extracts", "all", "the", "features", "available", "to", "the", "Finger", "Tapping", "Processor", "class", "." ]
python
train
dropbox/stone
stone/ir/data_types.py
https://github.com/dropbox/stone/blob/2e95cbcd1c48e05cca68c919fd8d24adec6b0f58/stone/ir/data_types.py#L1979-L2001
def unwrap(data_type): """ Convenience method to unwrap all Aliases and Nullables from around a DataType. This checks for nullable wrapping aliases, as well as aliases wrapping nullables. Args: data_type (DataType): The target to unwrap. Return: Tuple[DataType, bool, bool]: The...
[ "def", "unwrap", "(", "data_type", ")", ":", "unwrapped_nullable", "=", "False", "unwrapped_alias", "=", "False", "while", "is_alias", "(", "data_type", ")", "or", "is_nullable_type", "(", "data_type", ")", ":", "if", "is_nullable_type", "(", "data_type", ")", ...
Convenience method to unwrap all Aliases and Nullables from around a DataType. This checks for nullable wrapping aliases, as well as aliases wrapping nullables. Args: data_type (DataType): The target to unwrap. Return: Tuple[DataType, bool, bool]: The underlying data type; a bool that ...
[ "Convenience", "method", "to", "unwrap", "all", "Aliases", "and", "Nullables", "from", "around", "a", "DataType", ".", "This", "checks", "for", "nullable", "wrapping", "aliases", "as", "well", "as", "aliases", "wrapping", "nullables", "." ]
python
train
rpcope1/HackerNewsAPI-Py
HackerNewsAPI/API.py
https://github.com/rpcope1/HackerNewsAPI-Py/blob/b231aed24ec59fc32af320bbef27d48cc4b69914/HackerNewsAPI/API.py#L108-L120
def get_top_stories(self): """ Get the item numbers for the current top stories. Will raise an requests.HTTPError if we got a non-200 response back. :return: A list with the top story item numbers. """ suburl = "v0/topstories.json" try: top_stories = s...
[ "def", "get_top_stories", "(", "self", ")", ":", "suburl", "=", "\"v0/topstories.json\"", "try", ":", "top_stories", "=", "self", ".", "_make_request", "(", "suburl", ")", "except", "requests", ".", "HTTPError", "as", "e", ":", "hn_logger", ".", "exception", ...
Get the item numbers for the current top stories. Will raise an requests.HTTPError if we got a non-200 response back. :return: A list with the top story item numbers.
[ "Get", "the", "item", "numbers", "for", "the", "current", "top", "stories", ".", "Will", "raise", "an", "requests", ".", "HTTPError", "if", "we", "got", "a", "non", "-", "200", "response", "back", ".", ":", "return", ":", "A", "list", "with", "the", ...
python
train
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/brocade_threshold_monitor.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_threshold_monitor.py#L263-L278
def threshold_monitor_hidden_threshold_monitor_security_policy_area_sec_area_value(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") threshold_monitor_hidden = ET.SubElement(config, "threshold-monitor-hidden", xmlns="urn:brocade.com:mgmt:brocade-threshold-monitor"...
[ "def", "threshold_monitor_hidden_threshold_monitor_security_policy_area_sec_area_value", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "threshold_monitor_hidden", "=", "ET", ".", "SubElement", "(", "config...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
RetailMeNotSandbox/acky
acky/ec2.py
https://github.com/RetailMeNotSandbox/acky/blob/fcd4d092c42892ede7c924cafc41e9cf4be3fb9f/acky/ec2.py#L485-L508
def create(self, az, size_or_snap, volume_type=None, iops=None, encrypted=True): """Create an EBS Volume using an availability-zone and size_or_snap parameter, encrypted by default. If the volume is crated from a snapshot, (str)size_or_snap denotes the snapshot id. Otherwi...
[ "def", "create", "(", "self", ",", "az", ",", "size_or_snap", ",", "volume_type", "=", "None", ",", "iops", "=", "None", ",", "encrypted", "=", "True", ")", ":", "kwargs", "=", "{", "}", "kwargs", "[", "'encrypted'", "]", "=", "encrypted", "if", "vol...
Create an EBS Volume using an availability-zone and size_or_snap parameter, encrypted by default. If the volume is crated from a snapshot, (str)size_or_snap denotes the snapshot id. Otherwise, (int)size_or_snap denotes the amount of GiB's to allocate. iops must be set if the volume type ...
[ "Create", "an", "EBS", "Volume", "using", "an", "availability", "-", "zone", "and", "size_or_snap", "parameter", "encrypted", "by", "default", ".", "If", "the", "volume", "is", "crated", "from", "a", "snapshot", "(", "str", ")", "size_or_snap", "denotes", "t...
python
train
xolox/python-update-dotdee
update_dotdee/__init__.py
https://github.com/xolox/python-update-dotdee/blob/04d5836f0d217e32778745b533beeb8159d80c32/update_dotdee/__init__.py#L251-L265
def available_files(self): """ The filenames of the available configuration files (a list of strings). The value of :attr:`available_files` is computed the first time its needed by searching for available configuration files that match :attr:`filename_patterns` using :func:`~glo...
[ "def", "available_files", "(", "self", ")", ":", "matches", "=", "[", "]", "for", "pattern", "in", "self", ".", "filename_patterns", ":", "logger", ".", "debug", "(", "\"Matching filename pattern: %s\"", ",", "pattern", ")", "matches", ".", "extend", "(", "n...
The filenames of the available configuration files (a list of strings). The value of :attr:`available_files` is computed the first time its needed by searching for available configuration files that match :attr:`filename_patterns` using :func:`~glob.glob()`. If you set :attr:`available_...
[ "The", "filenames", "of", "the", "available", "configuration", "files", "(", "a", "list", "of", "strings", ")", "." ]
python
train
yinkaisheng/Python-UIAutomation-for-Windows
uiautomation/uiautomation.py
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L7703-L7719
def WaitHotKeyReleased(hotkey: tuple) -> None: """hotkey: tuple, two ints tuple(modifierKey, key)""" mod = {ModifierKey.Alt: Keys.VK_MENU, ModifierKey.Control: Keys.VK_CONTROL, ModifierKey.Shift: Keys.VK_SHIFT, ModifierKey.Win: Keys.VK_LWIN } while Tru...
[ "def", "WaitHotKeyReleased", "(", "hotkey", ":", "tuple", ")", "->", "None", ":", "mod", "=", "{", "ModifierKey", ".", "Alt", ":", "Keys", ".", "VK_MENU", ",", "ModifierKey", ".", "Control", ":", "Keys", ".", "VK_CONTROL", ",", "ModifierKey", ".", "Shift...
hotkey: tuple, two ints tuple(modifierKey, key)
[ "hotkey", ":", "tuple", "two", "ints", "tuple", "(", "modifierKey", "key", ")" ]
python
valid
mpg-age-bioinformatics/AGEpy
AGEpy/kegg.py
https://github.com/mpg-age-bioinformatics/AGEpy/blob/887808a7a2c1504f39ce8d8cb36c15c1721cd29f/AGEpy/kegg.py#L83-L105
def ensembl_to_kegg(organism,kegg_db): """ Looks up KEGG mappings of KEGG ids to ensembl ids :param organism: an organisms as listed in organismsKEGG() :param kegg_db: a matching KEGG db as reported in databasesKEGG :returns: a Pandas dataframe of with 'KEGGid' and 'ENSid'. """ print("KEG...
[ "def", "ensembl_to_kegg", "(", "organism", ",", "kegg_db", ")", ":", "print", "(", "\"KEGG API: http://rest.genome.jp/link/\"", "+", "kegg_db", "+", "\"/\"", "+", "organism", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "kegg_ens", "=", "urlopen", "(", ...
Looks up KEGG mappings of KEGG ids to ensembl ids :param organism: an organisms as listed in organismsKEGG() :param kegg_db: a matching KEGG db as reported in databasesKEGG :returns: a Pandas dataframe of with 'KEGGid' and 'ENSid'.
[ "Looks", "up", "KEGG", "mappings", "of", "KEGG", "ids", "to", "ensembl", "ids" ]
python
train
sorgerlab/indra
indra/sources/bel/rdf_processor.py
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/bel/rdf_processor.py#L21-L35
def namespace_from_uri(uri): """Return the entity namespace from the URI. Examples: http://www.openbel.org/bel/p_HGNC_RAF1 -> HGNC http://www.openbel.org/bel/p_RGD_Raf1 -> RGD http://www.openbel.org/bel/p_PFH_MEK1/2_Family -> PFH """ patterns = ['http://www.openbel.org/bel/[pragm]_([A-Za-z]+)_.*...
[ "def", "namespace_from_uri", "(", "uri", ")", ":", "patterns", "=", "[", "'http://www.openbel.org/bel/[pragm]_([A-Za-z]+)_.*'", ",", "'http://www.openbel.org/bel/[a-z]+_[pr]_([A-Za-z]+)_.*'", ",", "'http://www.openbel.org/bel/[a-z]+_complex_([A-Za-z]+)_.*'", ",", "'http://www.openbel.o...
Return the entity namespace from the URI. Examples: http://www.openbel.org/bel/p_HGNC_RAF1 -> HGNC http://www.openbel.org/bel/p_RGD_Raf1 -> RGD http://www.openbel.org/bel/p_PFH_MEK1/2_Family -> PFH
[ "Return", "the", "entity", "namespace", "from", "the", "URI", ".", "Examples", ":", "http", ":", "//", "www", ".", "openbel", ".", "org", "/", "bel", "/", "p_HGNC_RAF1", "-", ">", "HGNC", "http", ":", "//", "www", ".", "openbel", ".", "org", "/", "...
python
train
ContextLab/hypertools
hypertools/tools/reduce.py
https://github.com/ContextLab/hypertools/blob/b76c7ac8061998b560e969ff8e4f4c915088e7a0/hypertools/tools/reduce.py#L36-L158
def reduce(x, reduce='IncrementalPCA', ndims=None, normalize=None, align=None, model=None, model_params=None, internal=False, format_data=True): """ Reduces dimensionality of an array, or list of arrays Parameters ---------- x : Numpy array or list of arrays Dimensionality reduct...
[ "def", "reduce", "(", "x", ",", "reduce", "=", "'IncrementalPCA'", ",", "ndims", "=", "None", ",", "normalize", "=", "None", ",", "align", "=", "None", ",", "model", "=", "None", ",", "model_params", "=", "None", ",", "internal", "=", "False", ",", "...
Reduces dimensionality of an array, or list of arrays Parameters ---------- x : Numpy array or list of arrays Dimensionality reduction using PCA is performed on this array. reduce : str or dict Decomposition/manifold learning model to use. Models supported: PCA, IncrementalPCA...
[ "Reduces", "dimensionality", "of", "an", "array", "or", "list", "of", "arrays" ]
python
train
jobovy/galpy
galpy/orbit/Orbit.py
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/orbit/Orbit.py#L794-L825
def E(self,*args,**kwargs): """ NAME: E PURPOSE: calculate the energy INPUT: t - (optional) time at which to get the energy (can be Quantity) pot= Potential instance or list of such instances vo= (Object-wide default) physical...
[ "def", "E", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "kwargs", ".", "get", "(", "'pot'", ",", "None", ")", "is", "None", ":", "kwargs", "[", "'pot'", "]", "=", "flatten_potential", "(", "kwargs", ".", "get", ...
NAME: E PURPOSE: calculate the energy INPUT: t - (optional) time at which to get the energy (can be Quantity) pot= Potential instance or list of such instances vo= (Object-wide default) physical scale for velocities to use to convert (can be ...
[ "NAME", ":" ]
python
train
pavlin-policar/openTSNE
openTSNE/affinity.py
https://github.com/pavlin-policar/openTSNE/blob/28513a0d669f2f20e7b971c0c6373dc375f72771/openTSNE/affinity.py#L139-L178
def set_perplexity(self, new_perplexity): """Change the perplexity of the affinity matrix. Note that we only allow lowering the perplexity or restoring it to its original value. This restriction exists because setting a higher perplexity value requires recomputing all the nearest neighb...
[ "def", "set_perplexity", "(", "self", ",", "new_perplexity", ")", ":", "# If the value hasn't changed, there's nothing to do", "if", "new_perplexity", "==", "self", ".", "perplexity", ":", "return", "# Verify that the perplexity isn't too large", "new_perplexity", "=", "self"...
Change the perplexity of the affinity matrix. Note that we only allow lowering the perplexity or restoring it to its original value. This restriction exists because setting a higher perplexity value requires recomputing all the nearest neighbors, which can take a long time. To avoid pot...
[ "Change", "the", "perplexity", "of", "the", "affinity", "matrix", "." ]
python
train