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
joestump/django-ajax
ajax/utils.py
https://github.com/joestump/django-ajax/blob/b71619d5c00d8e0bb990ddbea2c93cf303dc2c80/ajax/utils.py#L8-L32
def import_by_path(dotted_path, error_prefix=''): """ Import a dotted module path and return the attribute/class designated by the last name in the path. Raise ImproperlyConfigured if something goes wrong. This has come straight from Django 1.6 """ try: module_path, class_name = dotted_p...
[ "def", "import_by_path", "(", "dotted_path", ",", "error_prefix", "=", "''", ")", ":", "try", ":", "module_path", ",", "class_name", "=", "dotted_path", ".", "rsplit", "(", "'.'", ",", "1", ")", "except", "ValueError", ":", "raise", "ImproperlyConfigured", "...
Import a dotted module path and return the attribute/class designated by the last name in the path. Raise ImproperlyConfigured if something goes wrong. This has come straight from Django 1.6
[ "Import", "a", "dotted", "module", "path", "and", "return", "the", "attribute", "/", "class", "designated", "by", "the", "last", "name", "in", "the", "path", ".", "Raise", "ImproperlyConfigured", "if", "something", "goes", "wrong", ".", "This", "has", "come"...
python
train
unt-libraries/pypairtree
pypairtree/pairtree.py
https://github.com/unt-libraries/pypairtree/blob/2107b46718bbf9ef7ef3d5c63d557d1f772e5d69/pypairtree/pairtree.py#L104-L150
def sanitizeString(name): """Cleans string in preparation for splitting for use as a pairtree identifier.""" newString = name # string cleaning, pass 1 replaceTable = [ ('^', '^5e'), # we need to do this one first ('"', '^22'), ('<', '^3c'), ('?', '^3f'), ('*...
[ "def", "sanitizeString", "(", "name", ")", ":", "newString", "=", "name", "# string cleaning, pass 1", "replaceTable", "=", "[", "(", "'^'", ",", "'^5e'", ")", ",", "# we need to do this one first", "(", "'\"'", ",", "'^22'", ")", ",", "(", "'<'", ",", "'^3c...
Cleans string in preparation for splitting for use as a pairtree identifier.
[ "Cleans", "string", "in", "preparation", "for", "splitting", "for", "use", "as", "a", "pairtree", "identifier", "." ]
python
train
sirfoga/pyhal
hal/meta/attributes.py
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/meta/attributes.py#L26-L32
def _parse(self): """Parses file contents :return: Tree hierarchy of file """ with open(self.path, "rt") as reader: return ast.parse(reader.read(), filename=self.path)
[ "def", "_parse", "(", "self", ")", ":", "with", "open", "(", "self", ".", "path", ",", "\"rt\"", ")", "as", "reader", ":", "return", "ast", ".", "parse", "(", "reader", ".", "read", "(", ")", ",", "filename", "=", "self", ".", "path", ")" ]
Parses file contents :return: Tree hierarchy of file
[ "Parses", "file", "contents" ]
python
train
debugloop/saltobserver
saltobserver/views.py
https://github.com/debugloop/saltobserver/blob/55ff20aa2d2504fb85fa2f63cc9b52934245b849/saltobserver/views.py#L18-L22
def get_function_data(minion, jid): """AJAX access for loading function/job details.""" redis = Redis(connection_pool=redis_pool) data = redis.get('{0}:{1}'.format(minion, jid)) return Response(response=data, status=200, mimetype="application/json")
[ "def", "get_function_data", "(", "minion", ",", "jid", ")", ":", "redis", "=", "Redis", "(", "connection_pool", "=", "redis_pool", ")", "data", "=", "redis", ".", "get", "(", "'{0}:{1}'", ".", "format", "(", "minion", ",", "jid", ")", ")", "return", "R...
AJAX access for loading function/job details.
[ "AJAX", "access", "for", "loading", "function", "/", "job", "details", "." ]
python
train
TAPPGuild/sqlalchemy-models
sqlalchemy_models/wallet.py
https://github.com/TAPPGuild/sqlalchemy-models/blob/75988a23bdd98e79af8b8b0711c657c79b2f8eac/sqlalchemy_models/wallet.py#L131-L138
def load_commodities(self): """ Load the commodities for Amounts in this object. """ if isinstance(self.amount, Amount): self.amount = Amount("{0:.8f} {1}".format(self.amount.to_double(), self.currency)) else: self.amount = Amount("{0:.8f} {1}".format(self...
[ "def", "load_commodities", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "amount", ",", "Amount", ")", ":", "self", ".", "amount", "=", "Amount", "(", "\"{0:.8f} {1}\"", ".", "format", "(", "self", ".", "amount", ".", "to_double", "(", "...
Load the commodities for Amounts in this object.
[ "Load", "the", "commodities", "for", "Amounts", "in", "this", "object", "." ]
python
train
DarkEnergySurvey/ugali
ugali/utils/binning.py
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/binning.py#L177-L291
def fast_kde(x, y, gridsize=(200,200), extents=None, nocorrelation=False, weights=None): """ Performs a gaussian kernel density estimate over a regular grid using a convolution of the gaussian kernel with a 2D histogram of the data. This function is typically several orders of magnitude faster than ...
[ "def", "fast_kde", "(", "x", ",", "y", ",", "gridsize", "=", "(", "200", ",", "200", ")", ",", "extents", "=", "None", ",", "nocorrelation", "=", "False", ",", "weights", "=", "None", ")", ":", "#---- Setup -----------------------------------------------------...
Performs a gaussian kernel density estimate over a regular grid using a convolution of the gaussian kernel with a 2D histogram of the data. This function is typically several orders of magnitude faster than scipy.stats.kde.gaussian_kde for large (>1e7) numbers of points and produces an essentially id...
[ "Performs", "a", "gaussian", "kernel", "density", "estimate", "over", "a", "regular", "grid", "using", "a", "convolution", "of", "the", "gaussian", "kernel", "with", "a", "2D", "histogram", "of", "the", "data", "." ]
python
train
vanheeringen-lab/gimmemotifs
gimmemotifs/rocmetrics.py
https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/rocmetrics.py#L67-L95
def recall_at_fdr(fg_vals, bg_vals, fdr_cutoff=0.1): """ Computes the recall at a specific FDR (default 10%). Parameters ---------- fg_vals : array_like The list of values for the positive set. bg_vals : array_like The list of values for the negative set. fdr : float, ...
[ "def", "recall_at_fdr", "(", "fg_vals", ",", "bg_vals", ",", "fdr_cutoff", "=", "0.1", ")", ":", "if", "len", "(", "fg_vals", ")", "==", "0", ":", "return", "0.0", "y_true", ",", "y_score", "=", "values_to_labels", "(", "fg_vals", ",", "bg_vals", ")", ...
Computes the recall at a specific FDR (default 10%). Parameters ---------- fg_vals : array_like The list of values for the positive set. bg_vals : array_like The list of values for the negative set. fdr : float, optional The FDR (between 0.0 and 1.0). Returns ...
[ "Computes", "the", "recall", "at", "a", "specific", "FDR", "(", "default", "10%", ")", "." ]
python
train
sanger-pathogens/ariba
ariba/ref_genes_getter.py
https://github.com/sanger-pathogens/ariba/blob/16a0b1916ce0e886bd22550ba2d648542977001b/ariba/ref_genes_getter.py#L462-L483
def _fix_virulencefinder_fasta_file(cls, infile, outfile): '''Some line breaks are missing in the FASTA files from viruslence finder. Which means there are lines like this: AAGATCCAATAACTGAAGATGTTGAACAAACAATTCATAATATTTATGGTCAATATGCTATTTTCGTTGA AGGTGTTGCGCATTTACCTGGACATCTCTCTCCATTATTAAAAA...
[ "def", "_fix_virulencefinder_fasta_file", "(", "cls", ",", "infile", ",", "outfile", ")", ":", "with", "open", "(", "infile", ")", "as", "f_in", ",", "open", "(", "outfile", ",", "'w'", ")", "as", "f_out", ":", "for", "line", "in", "f_in", ":", "if", ...
Some line breaks are missing in the FASTA files from viruslence finder. Which means there are lines like this: AAGATCCAATAACTGAAGATGTTGAACAAACAATTCATAATATTTATGGTCAATATGCTATTTTCGTTGA AGGTGTTGCGCATTTACCTGGACATCTCTCTCCATTATTAAAAAAATTACTACTTAAATCTTTATAA>coa:1:BA000018.3 ATGAAAAAGCAAATAATTTCG...
[ "Some", "line", "breaks", "are", "missing", "in", "the", "FASTA", "files", "from", "viruslence", "finder", ".", "Which", "means", "there", "are", "lines", "like", "this", ":", "AAGATCCAATAACTGAAGATGTTGAACAAACAATTCATAATATTTATGGTCAATATGCTATTTTCGTTGA", "AGGTGTTGCGCATTTACCTGG...
python
train
tethysplatform/condorpy
condorpy/htcondor_object_base.py
https://github.com/tethysplatform/condorpy/blob/a5aaaef0d73198f7d9756dda7abe98b4e209f1f4/condorpy/htcondor_object_base.py#L144-L159
def remove(self, options=[], sub_job_num=None): """Removes a job from the job queue, or from being executed. Args: options (list of str, optional): A list of command line options for the condor_rm command. For details on valid options see: http://research.cs.wisc.edu/htcondo...
[ "def", "remove", "(", "self", ",", "options", "=", "[", "]", ",", "sub_job_num", "=", "None", ")", ":", "args", "=", "[", "'condor_rm'", "]", "args", ".", "extend", "(", "options", ")", "job_id", "=", "'%s.%s'", "%", "(", "self", ".", "cluster_id", ...
Removes a job from the job queue, or from being executed. Args: options (list of str, optional): A list of command line options for the condor_rm command. For details on valid options see: http://research.cs.wisc.edu/htcondor/manual/current/condor_rm.html. Defaults t...
[ "Removes", "a", "job", "from", "the", "job", "queue", "or", "from", "being", "executed", "." ]
python
train
shoebot/shoebot
extensions/gedit/gedit2-plugin/shoebotit/__init__.py
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/extensions/gedit/gedit2-plugin/shoebotit/__init__.py#L295-L306
def _create_view(self, name="shoebot-output"): """ Create the gtk.TextView used for shell output """ view = gtk.TextView() view.set_editable(False) fontdesc = pango.FontDescription("Monospace") view.modify_font(fontdesc) view.set_name(name) buff = view.get_buffe...
[ "def", "_create_view", "(", "self", ",", "name", "=", "\"shoebot-output\"", ")", ":", "view", "=", "gtk", ".", "TextView", "(", ")", "view", ".", "set_editable", "(", "False", ")", "fontdesc", "=", "pango", ".", "FontDescription", "(", "\"Monospace\"", ")"...
Create the gtk.TextView used for shell output
[ "Create", "the", "gtk", ".", "TextView", "used", "for", "shell", "output" ]
python
valid
mkoura/dump2polarion
dump2polarion/dumper_cli.py
https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/dumper_cli.py#L79-L87
def process_args(args): """Processes passed arguments.""" passed_args = args if isinstance(args, argparse.Namespace): passed_args = vars(passed_args) elif hasattr(args, "to_dict"): passed_args = passed_args.to_dict() return Box(passed_args, frozen_box=True, default_box=True)
[ "def", "process_args", "(", "args", ")", ":", "passed_args", "=", "args", "if", "isinstance", "(", "args", ",", "argparse", ".", "Namespace", ")", ":", "passed_args", "=", "vars", "(", "passed_args", ")", "elif", "hasattr", "(", "args", ",", "\"to_dict\"",...
Processes passed arguments.
[ "Processes", "passed", "arguments", "." ]
python
train
zhmcclient/python-zhmcclient
zhmcclient/_session.py
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_session.py#L58-L75
def _handle_request_exc(exc, retry_timeout_config): """ Handle a :exc:`request.exceptions.RequestException` exception that was raised. """ if isinstance(exc, requests.exceptions.ConnectTimeout): raise ConnectTimeout(_request_exc_message(exc), exc, retry_timeout_c...
[ "def", "_handle_request_exc", "(", "exc", ",", "retry_timeout_config", ")", ":", "if", "isinstance", "(", "exc", ",", "requests", ".", "exceptions", ".", "ConnectTimeout", ")", ":", "raise", "ConnectTimeout", "(", "_request_exc_message", "(", "exc", ")", ",", ...
Handle a :exc:`request.exceptions.RequestException` exception that was raised.
[ "Handle", "a", ":", "exc", ":", "request", ".", "exceptions", ".", "RequestException", "exception", "that", "was", "raised", "." ]
python
train
etcher-be/emiz
emiz/avwx/core.py
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/core.py#L104-L125
def make_number(num: str, repr_: str = None, speak: str = None): """ Returns a Number or Fraction dataclass for a number string """ if not num or is_unknown(num): return # Check CAVOK if num == 'CAVOK': return Number('CAVOK', 9999, 'ceiling and visibility ok') # type: ignore ...
[ "def", "make_number", "(", "num", ":", "str", ",", "repr_", ":", "str", "=", "None", ",", "speak", ":", "str", "=", "None", ")", ":", "if", "not", "num", "or", "is_unknown", "(", "num", ")", ":", "return", "# Check CAVOK", "if", "num", "==", "'CAVO...
Returns a Number or Fraction dataclass for a number string
[ "Returns", "a", "Number", "or", "Fraction", "dataclass", "for", "a", "number", "string" ]
python
train
gbowerman/azurerm
azurerm/networkrp.py
https://github.com/gbowerman/azurerm/blob/79d40431d3b13f8a36aadbff5029888383d72674/azurerm/networkrp.py#L383-L398
def get_network_usage(access_token, subscription_id, location): '''List network usage and limits for a location. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. location (str): Azure data center location. E.g. westus. Retu...
[ "def", "get_network_usage", "(", "access_token", ",", "subscription_id", ",", "location", ")", ":", "endpoint", "=", "''", ".", "join", "(", "[", "get_rm_endpoint", "(", ")", ",", "'/subscriptions/'", ",", "subscription_id", ",", "'/providers/Microsoft.Network/locat...
List network usage and limits for a location. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. location (str): Azure data center location. E.g. westus. Returns: HTTP response. JSON body of network usage.
[ "List", "network", "usage", "and", "limits", "for", "a", "location", "." ]
python
train
cmheisel/basecampreporting
src/basecampreporting/basecamp.py
https://github.com/cmheisel/basecampreporting/blob/88ecfc6e835608650ff6be23cbf2421d224c122b/src/basecampreporting/basecamp.py#L409-L425
def create_todo_item(self, list_id, content, party_id=None, notify=False): """ This call lets you add an item to an existing list. The item is added to the bottom of the list. If a person is responsible for the item, give their id as the party_id value. If a company is responsible, ...
[ "def", "create_todo_item", "(", "self", ",", "list_id", ",", "content", ",", "party_id", "=", "None", ",", "notify", "=", "False", ")", ":", "path", "=", "'/todos/create_item/%u'", "%", "list_id", "req", "=", "ET", ".", "Element", "(", "'request'", ")", ...
This call lets you add an item to an existing list. The item is added to the bottom of the list. If a person is responsible for the item, give their id as the party_id value. If a company is responsible, prefix their company id with a 'c' and use that as the party_id value. If the item h...
[ "This", "call", "lets", "you", "add", "an", "item", "to", "an", "existing", "list", ".", "The", "item", "is", "added", "to", "the", "bottom", "of", "the", "list", ".", "If", "a", "person", "is", "responsible", "for", "the", "item", "give", "their", "...
python
train
ska-sa/katcp-python
katcp/core.py
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/core.py#L1311-L1326
def set(self, timestamp, status, value): """Set the current value of the sensor. Parameters ---------- timestamp : float in seconds The time at which the sensor value was determined. status : Sensor status constant Whether the value represents an error con...
[ "def", "set", "(", "self", ",", "timestamp", ",", "status", ",", "value", ")", ":", "reading", "=", "self", ".", "_current_reading", "=", "Reading", "(", "timestamp", ",", "status", ",", "value", ")", "self", ".", "notify", "(", "reading", ")" ]
Set the current value of the sensor. Parameters ---------- timestamp : float in seconds The time at which the sensor value was determined. status : Sensor status constant Whether the value represents an error condition or not. value : object Th...
[ "Set", "the", "current", "value", "of", "the", "sensor", "." ]
python
train
bitesofcode/projexui
projexui/widgets/xcombobox.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xcombobox.py#L500-L527
def showPopup( self ): """ Displays a custom popup widget for this system if a checkable state \ is setup. """ if not self.isCheckable(): return super(XComboBox, self).showPopup() if not self.isVisible(): return # update t...
[ "def", "showPopup", "(", "self", ")", ":", "if", "not", "self", ".", "isCheckable", "(", ")", ":", "return", "super", "(", "XComboBox", ",", "self", ")", ".", "showPopup", "(", ")", "if", "not", "self", ".", "isVisible", "(", ")", ":", "return", "#...
Displays a custom popup widget for this system if a checkable state \ is setup.
[ "Displays", "a", "custom", "popup", "widget", "for", "this", "system", "if", "a", "checkable", "state", "\\", "is", "setup", "." ]
python
train
goshuirc/irc
girc/client.py
https://github.com/goshuirc/irc/blob/d6a5e3e04d337566c009b087f108cd76f9e122cc/girc/client.py#L369-L374
def join_channel(self, channel, key=None, tags=None): """Join the given channel.""" params = [channel] if key: params.append(key) self.send('JOIN', params=params, tags=tags)
[ "def", "join_channel", "(", "self", ",", "channel", ",", "key", "=", "None", ",", "tags", "=", "None", ")", ":", "params", "=", "[", "channel", "]", "if", "key", ":", "params", ".", "append", "(", "key", ")", "self", ".", "send", "(", "'JOIN'", "...
Join the given channel.
[ "Join", "the", "given", "channel", "." ]
python
train
quantmind/pulsar-odm
odm/mapper.py
https://github.com/quantmind/pulsar-odm/blob/5955c20beca0a89270c2b390335838deb7d5915e/odm/mapper.py#L327-L336
def table_create(self, remove_existing=False): """Creates all tables. """ for engine in self.engines(): tables = self._get_tables(engine, create_drop=True) logger.info('Create all tables for %s', engine) try: self.metadata.create_all(engine, ta...
[ "def", "table_create", "(", "self", ",", "remove_existing", "=", "False", ")", ":", "for", "engine", "in", "self", ".", "engines", "(", ")", ":", "tables", "=", "self", ".", "_get_tables", "(", "engine", ",", "create_drop", "=", "True", ")", "logger", ...
Creates all tables.
[ "Creates", "all", "tables", "." ]
python
train
DarkEnergySurvey/ugali
ugali/scratch/simulation/simulate_population.py
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/scratch/simulation/simulate_population.py#L103-L241
def catsimSatellite(config, lon_centroid, lat_centroid, distance, stellar_mass, r_physical, m_maglim_1, m_maglim_2, m_ebv, plot=False, title='test'): """ Simulate a single satellite. This is currently only valid for band_1 = g and band_2 = r. r_physical is azimuthall...
[ "def", "catsimSatellite", "(", "config", ",", "lon_centroid", ",", "lat_centroid", ",", "distance", ",", "stellar_mass", ",", "r_physical", ",", "m_maglim_1", ",", "m_maglim_2", ",", "m_ebv", ",", "plot", "=", "False", ",", "title", "=", "'test'", ")", ":", ...
Simulate a single satellite. This is currently only valid for band_1 = g and band_2 = r. r_physical is azimuthally averaged half-light radius, kpc
[ "Simulate", "a", "single", "satellite", ".", "This", "is", "currently", "only", "valid", "for", "band_1", "=", "g", "and", "band_2", "=", "r", ".", "r_physical", "is", "azimuthally", "averaged", "half", "-", "light", "radius", "kpc" ]
python
train
churchill-lab/emase
emase/AlignmentPropertyMatrix.py
https://github.com/churchill-lab/emase/blob/ae3c6955bb175c1dec88dbf9fac1a7dcc16f4449/emase/AlignmentPropertyMatrix.py#L299-L317
def get_unique_reads(self, ignore_haplotype=False, shallow=False): """ Pull out alignments of uniquely-aligning reads :param ignore_haplotype: whether to regard allelic multiread as uniquely-aligning read :param shallow: whether to copy sparse 3D matrix only or not :return...
[ "def", "get_unique_reads", "(", "self", ",", "ignore_haplotype", "=", "False", ",", "shallow", "=", "False", ")", ":", "if", "self", ".", "finalized", ":", "if", "ignore_haplotype", ":", "summat", "=", "self", ".", "sum", "(", "axis", "=", "self", ".", ...
Pull out alignments of uniquely-aligning reads :param ignore_haplotype: whether to regard allelic multiread as uniquely-aligning read :param shallow: whether to copy sparse 3D matrix only or not :return: a new AlignmentPropertyMatrix object that particular reads are
[ "Pull", "out", "alignments", "of", "uniquely", "-", "aligning", "reads", ":", "param", "ignore_haplotype", ":", "whether", "to", "regard", "allelic", "multiread", "as", "uniquely", "-", "aligning", "read", ":", "param", "shallow", ":", "whether", "to", "copy",...
python
valid
pmacosta/pexdoc
pexdoc/exh.py
https://github.com/pmacosta/pexdoc/blob/201ac243e5781347feb75896a4231429fe6da4b1/pexdoc/exh.py#L1280-L1305
def encode_call(self, call): """ Replace callables with tokens to reduce object memory footprint. A callable token is an integer that denotes the order in which the callable was encountered by the encoder, i.e. the first callable encoded is assigned token 0, the second callable ...
[ "def", "encode_call", "(", "self", ",", "call", ")", ":", "# Callable name is None when callable is part of exclude list", "if", "call", "is", "None", ":", "return", "None", "itokens", "=", "call", ".", "split", "(", "self", ".", "_callables_separator", ")", "otok...
Replace callables with tokens to reduce object memory footprint. A callable token is an integer that denotes the order in which the callable was encountered by the encoder, i.e. the first callable encoded is assigned token 0, the second callable encoded is assigned token 1, etc. ...
[ "Replace", "callables", "with", "tokens", "to", "reduce", "object", "memory", "footprint", "." ]
python
train
timothyhahn/rui
rui/rui.py
https://github.com/timothyhahn/rui/blob/ac9f587fb486760d77332866c6e876f78a810f74/rui/rui.py#L215-L223
def set_tag(self, tag): ''' Sets the tag. If the Entity belongs to the world it will check for tag conflicts. ''' if self._world: if self._world.get_entity_by_tag(tag): raise NonUniqueTagError(tag) self._tag = tag
[ "def", "set_tag", "(", "self", ",", "tag", ")", ":", "if", "self", ".", "_world", ":", "if", "self", ".", "_world", ".", "get_entity_by_tag", "(", "tag", ")", ":", "raise", "NonUniqueTagError", "(", "tag", ")", "self", ".", "_tag", "=", "tag" ]
Sets the tag. If the Entity belongs to the world it will check for tag conflicts.
[ "Sets", "the", "tag", ".", "If", "the", "Entity", "belongs", "to", "the", "world", "it", "will", "check", "for", "tag", "conflicts", "." ]
python
train
NAMD/pypln.api
pypln/api.py
https://github.com/NAMD/pypln.api/blob/ccb73fd80ca094669a85bd3991dc84a8564ab016/pypln/api.py#L239-L264
def _retrieve_resources(self, url, class_, full): '''Retrieve HTTP resources, return related objects (with pagination)''' objects_to_return = [] response = self.session.get(url) if response.status_code == 200: result = response.json() resources = result['results']...
[ "def", "_retrieve_resources", "(", "self", ",", "url", ",", "class_", ",", "full", ")", ":", "objects_to_return", "=", "[", "]", "response", "=", "self", ".", "session", ".", "get", "(", "url", ")", "if", "response", ".", "status_code", "==", "200", ":...
Retrieve HTTP resources, return related objects (with pagination)
[ "Retrieve", "HTTP", "resources", "return", "related", "objects", "(", "with", "pagination", ")" ]
python
train
tBaxter/tango-shared-core
build/lib/tango_shared/templatetags/formatting.py
https://github.com/tBaxter/tango-shared-core/blob/35fc10aef1ceedcdb4d6d866d44a22efff718812/build/lib/tango_shared/templatetags/formatting.py#L12-L22
def replace(value, arg): """ Replaces one string with another in a given string usage: {{ foo|replace:"aaa|xxx"}} """ replacement = arg.split('|') try: return value.replace(replacement[0], replacement[1]) except: return value
[ "def", "replace", "(", "value", ",", "arg", ")", ":", "replacement", "=", "arg", ".", "split", "(", "'|'", ")", "try", ":", "return", "value", ".", "replace", "(", "replacement", "[", "0", "]", ",", "replacement", "[", "1", "]", ")", "except", ":",...
Replaces one string with another in a given string usage: {{ foo|replace:"aaa|xxx"}}
[ "Replaces", "one", "string", "with", "another", "in", "a", "given", "string", "usage", ":", "{{", "foo|replace", ":", "aaa|xxx", "}}" ]
python
train
dranjan/python-plyfile
examples/plot.py
https://github.com/dranjan/python-plyfile/blob/9f8e8708d3a071229cf292caae7d13264e11c88b/examples/plot.py#L27-L51
def plot(ply): ''' Plot vertices and triangles from a PlyData instance. Assumptions: `ply' has a 'vertex' element with 'x', 'y', and 'z' properties; `ply' has a 'face' element with an integral list property 'vertex_indices', all of whose elements have length 3. ''' ...
[ "def", "plot", "(", "ply", ")", ":", "vertex", "=", "ply", "[", "'vertex'", "]", "(", "x", ",", "y", ",", "z", ")", "=", "(", "vertex", "[", "t", "]", "for", "t", "in", "(", "'x'", ",", "'y'", ",", "'z'", ")", ")", "mlab", ".", "points3d", ...
Plot vertices and triangles from a PlyData instance. Assumptions: `ply' has a 'vertex' element with 'x', 'y', and 'z' properties; `ply' has a 'face' element with an integral list property 'vertex_indices', all of whose elements have length 3.
[ "Plot", "vertices", "and", "triangles", "from", "a", "PlyData", "instance", ".", "Assumptions", ":", "ply", "has", "a", "vertex", "element", "with", "x", "y", "and", "z", "properties", ";" ]
python
train
materialsproject/pymatgen
pymatgen/core/structure.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/core/structure.py#L463-L482
def add_spin_by_site(self, spins): """ Add spin states to a structure by site. Args: spins (list): List of spins E.g., [+5, -5, 0, 0] """ if len(spins) != len(self.sites): raise ValueError("Spin of all sites must be " ...
[ "def", "add_spin_by_site", "(", "self", ",", "spins", ")", ":", "if", "len", "(", "spins", ")", "!=", "len", "(", "self", ".", "sites", ")", ":", "raise", "ValueError", "(", "\"Spin of all sites must be \"", "\"specified in the dictionary.\"", ")", "for", "sit...
Add spin states to a structure by site. Args: spins (list): List of spins E.g., [+5, -5, 0, 0]
[ "Add", "spin", "states", "to", "a", "structure", "by", "site", "." ]
python
train
tsileo/globster
globster.py
https://github.com/tsileo/globster/blob/9628bce60207b150d39b409cddc3fadb34e70841/globster.py#L60-L71
def add(self, pat, fun): r"""Add a pattern and replacement. The pattern must not contain capturing groups. The replacement might be either a string template in which \& will be replaced with the match, or a function that will get the matching text as argument. It does not get ma...
[ "def", "add", "(", "self", ",", "pat", ",", "fun", ")", ":", "self", ".", "_pat", "=", "None", "self", ".", "_pats", ".", "append", "(", "pat", ")", "self", ".", "_funs", ".", "append", "(", "fun", ")" ]
r"""Add a pattern and replacement. The pattern must not contain capturing groups. The replacement might be either a string template in which \& will be replaced with the match, or a function that will get the matching text as argument. It does not get match object, because capturing is ...
[ "r", "Add", "a", "pattern", "and", "replacement", "." ]
python
train
deepmind/sonnet
sonnet/python/modules/pondering_rnn.py
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/pondering_rnn.py#L38-L47
def _nested_unary_mul(nested_a, p): """Multiply `Tensors` in arbitrarily nested `Tensor` `nested_a` with `p`.""" def mul_with_broadcast(tensor): ndims = tensor.shape.ndims if ndims != 2: p_reshaped = tf.reshape(p, [-1] + [1] * (ndims - 1)) return p_reshaped * tensor else: return p * te...
[ "def", "_nested_unary_mul", "(", "nested_a", ",", "p", ")", ":", "def", "mul_with_broadcast", "(", "tensor", ")", ":", "ndims", "=", "tensor", ".", "shape", ".", "ndims", "if", "ndims", "!=", "2", ":", "p_reshaped", "=", "tf", ".", "reshape", "(", "p",...
Multiply `Tensors` in arbitrarily nested `Tensor` `nested_a` with `p`.
[ "Multiply", "Tensors", "in", "arbitrarily", "nested", "Tensor", "nested_a", "with", "p", "." ]
python
train
odlgroup/odl
odl/solvers/nonsmooth/proximal_operators.py
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/solvers/nonsmooth/proximal_operators.py#L1934-L1993
def proximal_huber(space, gamma): """Proximal factory of the Huber norm. Parameters ---------- space : `TensorSpace` The domain of the functional gamma : float The smoothing parameter of the Huber norm functional. Returns ------- prox_factory : function Factory ...
[ "def", "proximal_huber", "(", "space", ",", "gamma", ")", ":", "gamma", "=", "float", "(", "gamma", ")", "class", "ProximalHuber", "(", "Operator", ")", ":", "\"\"\"Proximal operator of Huber norm.\"\"\"", "def", "__init__", "(", "self", ",", "sigma", ")", ":"...
Proximal factory of the Huber norm. Parameters ---------- space : `TensorSpace` The domain of the functional gamma : float The smoothing parameter of the Huber norm functional. Returns ------- prox_factory : function Factory for the proximal operator to be initializ...
[ "Proximal", "factory", "of", "the", "Huber", "norm", "." ]
python
train
google/importlab
importlab/graph.py
https://github.com/google/importlab/blob/92090a0b4421137d1369c2ed952eda6bb4c7a155/importlab/graph.py#L194-L200
def get_all_unresolved(self): """Returns a set of all unresolved imports.""" assert self.final, 'Call build() before using the graph.' out = set() for v in self.broken_deps.values(): out |= v return out
[ "def", "get_all_unresolved", "(", "self", ")", ":", "assert", "self", ".", "final", ",", "'Call build() before using the graph.'", "out", "=", "set", "(", ")", "for", "v", "in", "self", ".", "broken_deps", ".", "values", "(", ")", ":", "out", "|=", "v", ...
Returns a set of all unresolved imports.
[ "Returns", "a", "set", "of", "all", "unresolved", "imports", "." ]
python
train
graphql-python/graphql-relay-py
graphql_relay/node/node.py
https://github.com/graphql-python/graphql-relay-py/blob/17ce2efa3c396df42791ae00667120b5fae64610/graphql_relay/node/node.py#L15-L49
def node_definitions(id_fetcher, type_resolver=None, id_resolver=None): ''' Given a function to map from an ID to an underlying object, and a function to map from an underlying object to the concrete GraphQLObjectType it corresponds to, constructs a `Node` interface that objects can implement, and a...
[ "def", "node_definitions", "(", "id_fetcher", ",", "type_resolver", "=", "None", ",", "id_resolver", "=", "None", ")", ":", "node_interface", "=", "GraphQLInterfaceType", "(", "'Node'", ",", "description", "=", "'An object with an ID'", ",", "fields", "=", "lambda...
Given a function to map from an ID to an underlying object, and a function to map from an underlying object to the concrete GraphQLObjectType it corresponds to, constructs a `Node` interface that objects can implement, and a field config for a `node` root field. If the type_resolver is omitted, object ...
[ "Given", "a", "function", "to", "map", "from", "an", "ID", "to", "an", "underlying", "object", "and", "a", "function", "to", "map", "from", "an", "underlying", "object", "to", "the", "concrete", "GraphQLObjectType", "it", "corresponds", "to", "constructs", "...
python
train
msiemens/PyGitUp
PyGitUp/gitup.py
https://github.com/msiemens/PyGitUp/blob/b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c/PyGitUp/gitup.py#L374-L424
def log(self, branch, remote): """ Call a log-command, if set by git-up.fetch.all. """ log_hook = self.settings['rebase.log-hook'] if log_hook: if ON_WINDOWS: # pragma: no cover # Running a string in CMD from Python is not that easy on # Windo...
[ "def", "log", "(", "self", ",", "branch", ",", "remote", ")", ":", "log_hook", "=", "self", ".", "settings", "[", "'rebase.log-hook'", "]", "if", "log_hook", ":", "if", "ON_WINDOWS", ":", "# pragma: no cover\r", "# Running a string in CMD from Python is not that eas...
Call a log-command, if set by git-up.fetch.all.
[ "Call", "a", "log", "-", "command", "if", "set", "by", "git", "-", "up", ".", "fetch", ".", "all", "." ]
python
train
fermiPy/fermipy
fermipy/jobs/target_sim.py
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/target_sim.py#L195-L233
def _build_skydir_dict(wcsgeom, rand_config): """Build a dictionary of random directions""" step_x = rand_config['step_x'] step_y = rand_config['step_y'] max_x = rand_config['max_x'] max_y = rand_config['max_y'] seed = rand_config['seed'] nsims = rand_config['nsim...
[ "def", "_build_skydir_dict", "(", "wcsgeom", ",", "rand_config", ")", ":", "step_x", "=", "rand_config", "[", "'step_x'", "]", "step_y", "=", "rand_config", "[", "'step_y'", "]", "max_x", "=", "rand_config", "[", "'max_x'", "]", "max_y", "=", "rand_config", ...
Build a dictionary of random directions
[ "Build", "a", "dictionary", "of", "random", "directions" ]
python
train
mitsei/dlkit
dlkit/json_/assessment_authoring/sessions.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/assessment_authoring/sessions.py#L286-L309
def get_assessment_parts_by_genus_type(self, assessment_part_genus_type): """Gets an ``AssessmentPartList`` corresponding to the given assessment part genus ``Type`` which does not include assessment parts of types derived from the specified ``Type``. arg: assessment_part_genus_type (osid.type.Type)...
[ "def", "get_assessment_parts_by_genus_type", "(", "self", ",", "assessment_part_genus_type", ")", ":", "# Implemented from template for", "# osid.resource.ResourceLookupSession.get_resources_by_genus_type", "# NOTE: This implementation currently ignores plenary view", "collection", "=", "J...
Gets an ``AssessmentPartList`` corresponding to the given assessment part genus ``Type`` which does not include assessment parts of types derived from the specified ``Type``. arg: assessment_part_genus_type (osid.type.Type): an assessment part genus type return: (osid.assessment.auth...
[ "Gets", "an", "AssessmentPartList", "corresponding", "to", "the", "given", "assessment", "part", "genus", "Type", "which", "does", "not", "include", "assessment", "parts", "of", "types", "derived", "from", "the", "specified", "Type", "." ]
python
train
gwastro/pycbc-glue
pycbc_glue/ligolw/table.py
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/table.py#L143-L149
def getColumnsByName(elem, name): """ Return a list of Column elements named name under elem. The name comparison is done with CompareColumnNames(). """ name = StripColumnName(name) return elem.getElements(lambda e: (e.tagName == ligolw.Column.tagName) and (e.Name == name))
[ "def", "getColumnsByName", "(", "elem", ",", "name", ")", ":", "name", "=", "StripColumnName", "(", "name", ")", "return", "elem", ".", "getElements", "(", "lambda", "e", ":", "(", "e", ".", "tagName", "==", "ligolw", ".", "Column", ".", "tagName", ")"...
Return a list of Column elements named name under elem. The name comparison is done with CompareColumnNames().
[ "Return", "a", "list", "of", "Column", "elements", "named", "name", "under", "elem", ".", "The", "name", "comparison", "is", "done", "with", "CompareColumnNames", "()", "." ]
python
train
wonambi-python/wonambi
wonambi/widgets/analysis.py
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/analysis.py#L1147-L1152
def check_all_local_prep(self): """Check or uncheck all enabled event pre-processing.""" all_local_pp_chk = self.event['global']['all_local_prep'].isChecked() for buttons in self.event['local'].values(): if buttons[1].isEnabled(): buttons[1].setChecked(all_local_pp_ch...
[ "def", "check_all_local_prep", "(", "self", ")", ":", "all_local_pp_chk", "=", "self", ".", "event", "[", "'global'", "]", "[", "'all_local_prep'", "]", ".", "isChecked", "(", ")", "for", "buttons", "in", "self", ".", "event", "[", "'local'", "]", ".", "...
Check or uncheck all enabled event pre-processing.
[ "Check", "or", "uncheck", "all", "enabled", "event", "pre", "-", "processing", "." ]
python
train
kennedyshead/aioasuswrt
aioasuswrt/asuswrt.py
https://github.com/kennedyshead/aioasuswrt/blob/0c4336433727abbb7b324ee29e4c5382be9aaa2b/aioasuswrt/asuswrt.py#L159-L180
async def async_get_connected_devices(self): """Retrieve data from ASUSWRT. Calls various commands on the router and returns the superset of all responses. Some commands will not work on some routers. """ devices = {} dev = await self.async_get_wl() devices.updat...
[ "async", "def", "async_get_connected_devices", "(", "self", ")", ":", "devices", "=", "{", "}", "dev", "=", "await", "self", ".", "async_get_wl", "(", ")", "devices", ".", "update", "(", "dev", ")", "dev", "=", "await", "self", ".", "async_get_arp", "(",...
Retrieve data from ASUSWRT. Calls various commands on the router and returns the superset of all responses. Some commands will not work on some routers.
[ "Retrieve", "data", "from", "ASUSWRT", "." ]
python
train
Jarn/jarn.mkrelease
jarn/mkrelease/mkrelease.py
https://github.com/Jarn/jarn.mkrelease/blob/844377f37a3cdc0a154148790a926f991019ec4a/jarn/mkrelease/mkrelease.py#L371-L386
def get_skipregister(self, location=None): """Return true if the register command is disabled (for the given server.) """ if location is None: return self.skipregister or not self.defaults.register else: server = self.defaults.servers[location] if self...
[ "def", "get_skipregister", "(", "self", ",", "location", "=", "None", ")", ":", "if", "location", "is", "None", ":", "return", "self", ".", "skipregister", "or", "not", "self", ".", "defaults", ".", "register", "else", ":", "server", "=", "self", ".", ...
Return true if the register command is disabled (for the given server.)
[ "Return", "true", "if", "the", "register", "command", "is", "disabled", "(", "for", "the", "given", "server", ".", ")" ]
python
train
edeposit/edeposit.amqp.harvester
src/edeposit/amqp/harvester/scrappers/utils.py
https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/scrappers/utils.py#L62-L87
def get_first_content(el_list, alt=None, strip=True): """ Return content of the first element in `el_list` or `alt`. Also return `alt` if the content string of first element is blank. Args: el_list (list): List of HTMLElement objects. alt (default None): Value returner when list or cont...
[ "def", "get_first_content", "(", "el_list", ",", "alt", "=", "None", ",", "strip", "=", "True", ")", ":", "if", "not", "el_list", ":", "return", "alt", "content", "=", "el_list", "[", "0", "]", ".", "getContent", "(", ")", "if", "strip", ":", "conten...
Return content of the first element in `el_list` or `alt`. Also return `alt` if the content string of first element is blank. Args: el_list (list): List of HTMLElement objects. alt (default None): Value returner when list or content is blank. strip (bool, default True): Call .strip() to...
[ "Return", "content", "of", "the", "first", "element", "in", "el_list", "or", "alt", ".", "Also", "return", "alt", "if", "the", "content", "string", "of", "first", "element", "is", "blank", "." ]
python
train
Qiskit/qiskit-terra
qiskit/qasm/qasmparser.py
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/qasm/qasmparser.py#L1078-L1085
def run(self, data): """Parser runner. To use this module stand-alone. """ ast = self.parser.parse(data, debug=True) self.parser.parse(data, debug=True) ast.to_string(0)
[ "def", "run", "(", "self", ",", "data", ")", ":", "ast", "=", "self", ".", "parser", ".", "parse", "(", "data", ",", "debug", "=", "True", ")", "self", ".", "parser", ".", "parse", "(", "data", ",", "debug", "=", "True", ")", "ast", ".", "to_st...
Parser runner. To use this module stand-alone.
[ "Parser", "runner", "." ]
python
test
libtcod/python-tcod
tcod/libtcodpy.py
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L1053-L1065
def console_map_string_to_font(s: str, fontCharX: int, fontCharY: int) -> None: """Remap a string of codes to a contiguous set of tiles. Args: s (AnyStr): A string of character codes to map to new values. The null character `'\\x00'` will prematurely end this fun...
[ "def", "console_map_string_to_font", "(", "s", ":", "str", ",", "fontCharX", ":", "int", ",", "fontCharY", ":", "int", ")", "->", "None", ":", "lib", ".", "TCOD_console_map_string_to_font_utf", "(", "_unicode", "(", "s", ")", ",", "fontCharX", ",", "fontChar...
Remap a string of codes to a contiguous set of tiles. Args: s (AnyStr): A string of character codes to map to new values. The null character `'\\x00'` will prematurely end this function. fontCharX (int): The starting X tile coordinate on the loaded tileset. ...
[ "Remap", "a", "string", "of", "codes", "to", "a", "contiguous", "set", "of", "tiles", "." ]
python
train
Clinical-Genomics/scout
scout/load/case.py
https://github.com/Clinical-Genomics/scout/blob/90a551e2e1653a319e654c2405c2866f93d0ebb9/scout/load/case.py#L9-L36
def load_case(adapter, case_obj, update=False): """Load a case into the database If the case already exists the function will exit. If the user want to load a case that is already in the database 'update' has to be 'True' Args: adapter (MongoAdapter): connection to the database cas...
[ "def", "load_case", "(", "adapter", ",", "case_obj", ",", "update", "=", "False", ")", ":", "logger", ".", "info", "(", "'Loading case {} into database'", ".", "format", "(", "case_obj", "[", "'display_name'", "]", ")", ")", "# Check if case exists in database", ...
Load a case into the database If the case already exists the function will exit. If the user want to load a case that is already in the database 'update' has to be 'True' Args: adapter (MongoAdapter): connection to the database case_obj (dict): case object to persist to the database ...
[ "Load", "a", "case", "into", "the", "database" ]
python
test
gem/oq-engine
openquake/hmtk/seismicity/selector.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/selector.py#L380-L406
def within_magnitude_range(self, lower_mag=None, upper_mag=None): ''' :param float lower_mag: Lower magnitude for consideration :param float upper_mag: Upper magnitude for consideration :returns: Instance of openquake.hmtk.seismicity.catalogue.Catalo...
[ "def", "within_magnitude_range", "(", "self", ",", "lower_mag", "=", "None", ",", "upper_mag", "=", "None", ")", ":", "if", "not", "lower_mag", ":", "if", "not", "upper_mag", ":", "# No limiting magnitudes defined - return entire catalogue!", "return", "self", ".", ...
:param float lower_mag: Lower magnitude for consideration :param float upper_mag: Upper magnitude for consideration :returns: Instance of openquake.hmtk.seismicity.catalogue.Catalogue class containing only selected events
[ ":", "param", "float", "lower_mag", ":", "Lower", "magnitude", "for", "consideration" ]
python
train
bitesofcode/projexui
projexui/widgets/xganttwidget/xganttwidget.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xganttwidget/xganttwidget.py#L202-L219
def addTopLevelItem(self, item): """ Adds the inputed item to the gantt widget. :param item | <XGanttWidgetItem> """ vitem = item.viewItem() self.treeWidget().addTopLevelItem(item) self.viewWidget().scene().addItem(vitem) ...
[ "def", "addTopLevelItem", "(", "self", ",", "item", ")", ":", "vitem", "=", "item", ".", "viewItem", "(", ")", "self", ".", "treeWidget", "(", ")", ".", "addTopLevelItem", "(", "item", ")", "self", ".", "viewWidget", "(", ")", ".", "scene", "(", ")",...
Adds the inputed item to the gantt widget. :param item | <XGanttWidgetItem>
[ "Adds", "the", "inputed", "item", "to", "the", "gantt", "widget", ".", ":", "param", "item", "|", "<XGanttWidgetItem", ">" ]
python
train
robotframework/Rammbock
src/Rammbock/core.py
https://github.com/robotframework/Rammbock/blob/c906058d055a6f7c68fe1a6096d78c2e3f642b1c/src/Rammbock/core.py#L472-L484
def load_copy_of_template(self, name, *parameters): """Load a copy of message template saved with `Save template` when originally saved values need to be preserved from test to test. Optional parameters are default values for message header separated with colon. Examples: ...
[ "def", "load_copy_of_template", "(", "self", ",", "name", ",", "*", "parameters", ")", ":", "template", ",", "fields", ",", "header_fields", "=", "self", ".", "_set_templates_fields_and_header_fields", "(", "name", ",", "parameters", ")", "copy_of_template", "=", ...
Load a copy of message template saved with `Save template` when originally saved values need to be preserved from test to test. Optional parameters are default values for message header separated with colon. Examples: | Load Copy Of Template | MyMessage | header_field:value |
[ "Load", "a", "copy", "of", "message", "template", "saved", "with", "Save", "template", "when", "originally", "saved", "values", "need", "to", "be", "preserved", "from", "test", "to", "test", ".", "Optional", "parameters", "are", "default", "values", "for", "...
python
train
pypa/pipenv
pipenv/vendor/yarg/package.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/yarg/package.py#L123-L131
def author(self): """ >>> package = yarg.get('yarg') >>> package.author Author(name=u'Kura', email=u'kura@kura.io') """ author = namedtuple('Author', 'name email') return author(name=self._package['author'], email=self._package['a...
[ "def", "author", "(", "self", ")", ":", "author", "=", "namedtuple", "(", "'Author'", ",", "'name email'", ")", "return", "author", "(", "name", "=", "self", ".", "_package", "[", "'author'", "]", ",", "email", "=", "self", ".", "_package", "[", "'auth...
>>> package = yarg.get('yarg') >>> package.author Author(name=u'Kura', email=u'kura@kura.io')
[ ">>>", "package", "=", "yarg", ".", "get", "(", "yarg", ")", ">>>", "package", ".", "author", "Author", "(", "name", "=", "u", "Kura", "email", "=", "u", "kura" ]
python
train
zhanglab/psamm
psamm/fluxanalysis.py
https://github.com/zhanglab/psamm/blob/dc427848c4f9d109ca590f0afa024c63b685b3f4/psamm/fluxanalysis.py#L35-L40
def _get_fba_problem(model, tfba, solver): """Convenience function for returning the right FBA problem instance""" p = FluxBalanceProblem(model, solver) if tfba: p.add_thermodynamic() return p
[ "def", "_get_fba_problem", "(", "model", ",", "tfba", ",", "solver", ")", ":", "p", "=", "FluxBalanceProblem", "(", "model", ",", "solver", ")", "if", "tfba", ":", "p", ".", "add_thermodynamic", "(", ")", "return", "p" ]
Convenience function for returning the right FBA problem instance
[ "Convenience", "function", "for", "returning", "the", "right", "FBA", "problem", "instance" ]
python
train
aio-libs/aiomcache
aiomcache/client.py
https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/client.py#L415-L422
def flush_all(self, conn): """Its effect is to invalidate all existing items immediately""" command = b'flush_all\r\n' response = yield from self._execute_simple_command( conn, command) if const.OK != response: raise ClientException('Memcached flush_all failed', ...
[ "def", "flush_all", "(", "self", ",", "conn", ")", ":", "command", "=", "b'flush_all\\r\\n'", "response", "=", "yield", "from", "self", ".", "_execute_simple_command", "(", "conn", ",", "command", ")", "if", "const", ".", "OK", "!=", "response", ":", "rais...
Its effect is to invalidate all existing items immediately
[ "Its", "effect", "is", "to", "invalidate", "all", "existing", "items", "immediately" ]
python
train
sanoma/django-arctic
arctic/utils.py
https://github.com/sanoma/django-arctic/blob/c81b092c2643ca220708bf3c586017d9175161f5/arctic/utils.py#L104-L128
def menu_clean(menu_config): """ Make sure that only the menu item with the largest weight is active. If a child of a menu item is active, the parent should be active too. :param menu: :return: """ max_weight = -1 for _, value in list(menu_config.items()): if value["submenu"]: ...
[ "def", "menu_clean", "(", "menu_config", ")", ":", "max_weight", "=", "-", "1", "for", "_", ",", "value", "in", "list", "(", "menu_config", ".", "items", "(", ")", ")", ":", "if", "value", "[", "\"submenu\"", "]", ":", "for", "_", ",", "v", "in", ...
Make sure that only the menu item with the largest weight is active. If a child of a menu item is active, the parent should be active too. :param menu: :return:
[ "Make", "sure", "that", "only", "the", "menu", "item", "with", "the", "largest", "weight", "is", "active", ".", "If", "a", "child", "of", "a", "menu", "item", "is", "active", "the", "parent", "should", "be", "active", "too", ".", ":", "param", "menu", ...
python
train
frictionlessdata/datapackage-pipelines
datapackage_pipelines/utilities/dirtools.py
https://github.com/frictionlessdata/datapackage-pipelines/blob/3a34bbdf042d13c3bec5eef46ff360ee41403874/datapackage_pipelines/utilities/dirtools.py#L138-L153
def hash(self, index_func=os.path.getmtime): """ Hash for the entire directory (except excluded files) recursively. Use mtime instead of sha256 by default for a faster hash. >>> dir.hash(index_func=dirtools.filehash) """ # TODO alternative to filehash => mtime as a faster alte...
[ "def", "hash", "(", "self", ",", "index_func", "=", "os", ".", "path", ".", "getmtime", ")", ":", "# TODO alternative to filehash => mtime as a faster alternative", "shadir", "=", "hashlib", ".", "sha256", "(", ")", "for", "f", "in", "self", ".", "files", "(",...
Hash for the entire directory (except excluded files) recursively. Use mtime instead of sha256 by default for a faster hash. >>> dir.hash(index_func=dirtools.filehash)
[ "Hash", "for", "the", "entire", "directory", "(", "except", "excluded", "files", ")", "recursively", "." ]
python
train
siemens/django-dingos
dingos/models.py
https://github.com/siemens/django-dingos/blob/7154f75b06d2538568e2f2455a76f3d0db0b7d70/dingos/models.py#L1510-L1586
def add_relation(self, target_id=None, relation_types=None, fact_dt_namespace_name=None, fact_dt_namespace_uri=DINGOS_NAMESPACE_URI, fact_dt_kind=FactDataType.UNKNOWN_KIND, fact_dt_name='String'...
[ "def", "add_relation", "(", "self", ",", "target_id", "=", "None", ",", "relation_types", "=", "None", ",", "fact_dt_namespace_name", "=", "None", ",", "fact_dt_namespace_uri", "=", "DINGOS_NAMESPACE_URI", ",", "fact_dt_kind", "=", "FactDataType", ".", "UNKNOWN_KIND...
Add a relationship between this object and another object.
[ "Add", "a", "relationship", "between", "this", "object", "and", "another", "object", "." ]
python
train
mikusjelly/apkutils
apkutils/apkfile.py
https://github.com/mikusjelly/apkutils/blob/2db1ed0cdb610dfc55bfd77266e9a91e4764bba4/apkutils/apkfile.py#L758-L806
def readline(self, limit=-1): """Read and return a line from the stream. If limit is specified, at most limit bytes will be read. """ if not self._universal and limit < 0: # Shortcut common case - newline found in buffer. i = self._readbuffer.find(b'\n', self._o...
[ "def", "readline", "(", "self", ",", "limit", "=", "-", "1", ")", ":", "if", "not", "self", ".", "_universal", "and", "limit", "<", "0", ":", "# Shortcut common case - newline found in buffer.", "i", "=", "self", ".", "_readbuffer", ".", "find", "(", "b'\\...
Read and return a line from the stream. If limit is specified, at most limit bytes will be read.
[ "Read", "and", "return", "a", "line", "from", "the", "stream", "." ]
python
train
ingolemo/python-lenses
examples/naughts_and_crosses.py
https://github.com/ingolemo/python-lenses/blob/a3a6ed0a31f6674451e542e7380a8aa16e6f8edf/examples/naughts_and_crosses.py#L42-L47
def make_move(self, x, y): '''Return a board with a cell filled in by the current player. If the cell is already occupied then return the board unchanged.''' if self.board[y][x] == ' ': return lens.board[y][x].set(self.player)(self) return self
[ "def", "make_move", "(", "self", ",", "x", ",", "y", ")", ":", "if", "self", ".", "board", "[", "y", "]", "[", "x", "]", "==", "' '", ":", "return", "lens", ".", "board", "[", "y", "]", "[", "x", "]", ".", "set", "(", "self", ".", "player",...
Return a board with a cell filled in by the current player. If the cell is already occupied then return the board unchanged.
[ "Return", "a", "board", "with", "a", "cell", "filled", "in", "by", "the", "current", "player", ".", "If", "the", "cell", "is", "already", "occupied", "then", "return", "the", "board", "unchanged", "." ]
python
test
tkem/uritools
uritools/split.py
https://github.com/tkem/uritools/blob/e77ba4acd937b68da9850138563debd4c925ef9f/uritools/split.py#L178-L187
def getquery(self, default=None, encoding='utf-8', errors='strict'): """Return the decoded query string, or `default` if the original URI reference did not contain a query component. """ query = self.query if query is None: return default else: re...
[ "def", "getquery", "(", "self", ",", "default", "=", "None", ",", "encoding", "=", "'utf-8'", ",", "errors", "=", "'strict'", ")", ":", "query", "=", "self", ".", "query", "if", "query", "is", "None", ":", "return", "default", "else", ":", "return", ...
Return the decoded query string, or `default` if the original URI reference did not contain a query component.
[ "Return", "the", "decoded", "query", "string", "or", "default", "if", "the", "original", "URI", "reference", "did", "not", "contain", "a", "query", "component", "." ]
python
train
SheffieldML/GPy
GPy/plotting/gpy_plot/data_plots.py
https://github.com/SheffieldML/GPy/blob/54c32d79d289d622fb18b898aee65a2a431d90cf/GPy/plotting/gpy_plot/data_plots.py#L199-L223
def plot_errorbars_trainset(self, which_data_rows='all', which_data_ycols='all', fixed_inputs=None, plot_raw=False, apply_link=False, label=None, projection='2d', predict_kw=None, **plot_kwargs): """ Plot the errorbars of the GP likelihood on the training data. These are the errorbar...
[ "def", "plot_errorbars_trainset", "(", "self", ",", "which_data_rows", "=", "'all'", ",", "which_data_ycols", "=", "'all'", ",", "fixed_inputs", "=", "None", ",", "plot_raw", "=", "False", ",", "apply_link", "=", "False", ",", "label", "=", "None", ",", "pro...
Plot the errorbars of the GP likelihood on the training data. These are the errorbars after the appropriate approximations according to the likelihood are done. This also works for heteroscedastic likelihoods. Give the Y_metadata in the predict_kw if you need it. :param which_data_rows: which of ...
[ "Plot", "the", "errorbars", "of", "the", "GP", "likelihood", "on", "the", "training", "data", ".", "These", "are", "the", "errorbars", "after", "the", "appropriate", "approximations", "according", "to", "the", "likelihood", "are", "done", "." ]
python
train
totalgood/nlpia
src/nlpia/gensim_utils.py
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/gensim_utils.py#L44-L90
def to_unicode(sorb, allow_eval=False): r"""Ensure that strings are unicode (UTF-8 encoded). Evaluate bytes literals that are sometimes accidentally created by str(b'whatever') >>> to_unicode(b'whatever') 'whatever' >>> to_unicode(b'b"whatever"') 'whatever' >>> to_unicode(repr(b'b"whatever...
[ "def", "to_unicode", "(", "sorb", ",", "allow_eval", "=", "False", ")", ":", "if", "sorb", "is", "None", ":", "return", "sorb", "if", "isinstance", "(", "sorb", ",", "bytes", ")", ":", "sorb", "=", "sorb", ".", "decode", "(", ")", "for", "i", ",", ...
r"""Ensure that strings are unicode (UTF-8 encoded). Evaluate bytes literals that are sometimes accidentally created by str(b'whatever') >>> to_unicode(b'whatever') 'whatever' >>> to_unicode(b'b"whatever"') 'whatever' >>> to_unicode(repr(b'b"whatever"')) 'whatever' >>> to_unicode(str(b...
[ "r", "Ensure", "that", "strings", "are", "unicode", "(", "UTF", "-", "8", "encoded", ")", "." ]
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#L3354-L3363
def get_partitions_ps(self, db_name, tbl_name, part_vals, max_parts): """ Parameters: - db_name - tbl_name - part_vals - max_parts """ self.send_get_partitions_ps(db_name, tbl_name, part_vals, max_parts) return self.recv_get_partitions_ps()
[ "def", "get_partitions_ps", "(", "self", ",", "db_name", ",", "tbl_name", ",", "part_vals", ",", "max_parts", ")", ":", "self", ".", "send_get_partitions_ps", "(", "db_name", ",", "tbl_name", ",", "part_vals", ",", "max_parts", ")", "return", "self", ".", "r...
Parameters: - db_name - tbl_name - part_vals - max_parts
[ "Parameters", ":", "-", "db_name", "-", "tbl_name", "-", "part_vals", "-", "max_parts" ]
python
train
saltstack/salt
salt/runners/vault.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/vault.py#L146-L163
def _validate_signature(minion_id, signature, impersonated_by_master): ''' Validate that either minion with id minion_id, or the master, signed the request ''' pki_dir = __opts__['pki_dir'] if impersonated_by_master: public_key = '{0}/master.pub'.format(pki_dir) else: public_...
[ "def", "_validate_signature", "(", "minion_id", ",", "signature", ",", "impersonated_by_master", ")", ":", "pki_dir", "=", "__opts__", "[", "'pki_dir'", "]", "if", "impersonated_by_master", ":", "public_key", "=", "'{0}/master.pub'", ".", "format", "(", "pki_dir", ...
Validate that either minion with id minion_id, or the master, signed the request
[ "Validate", "that", "either", "minion", "with", "id", "minion_id", "or", "the", "master", "signed", "the", "request" ]
python
train
carlospalol/money
money/exchange.py
https://github.com/carlospalol/money/blob/1e51f651f93edd62c16eb3d7aa034fec03096046/money/exchange.py#L119-L123
def quotation(self, origin, target): """Return quotation between two currencies (origin, target)""" if not self._backend: raise ExchangeBackendNotInstalled() return self._backend.quotation(origin, target)
[ "def", "quotation", "(", "self", ",", "origin", ",", "target", ")", ":", "if", "not", "self", ".", "_backend", ":", "raise", "ExchangeBackendNotInstalled", "(", ")", "return", "self", ".", "_backend", ".", "quotation", "(", "origin", ",", "target", ")" ]
Return quotation between two currencies (origin, target)
[ "Return", "quotation", "between", "two", "currencies", "(", "origin", "target", ")" ]
python
train
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/list_types.py
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/list_types.py#L208-L212
def process_bind_param(self, value: Optional[List[str]], dialect: Dialect) -> str: """Convert things on the way from Python to the database.""" retval = self._strlist_to_dbstr(value) return retval
[ "def", "process_bind_param", "(", "self", ",", "value", ":", "Optional", "[", "List", "[", "str", "]", "]", ",", "dialect", ":", "Dialect", ")", "->", "str", ":", "retval", "=", "self", ".", "_strlist_to_dbstr", "(", "value", ")", "return", "retval" ]
Convert things on the way from Python to the database.
[ "Convert", "things", "on", "the", "way", "from", "Python", "to", "the", "database", "." ]
python
train
Azure/msrest-for-python
msrest/universal_http/aiohttp.py
https://github.com/Azure/msrest-for-python/blob/0732bc90bdb290e5f58c675ffdd7dbfa9acefc93/msrest/universal_http/aiohttp.py#L50-L64
async def send(self, request: ClientRequest, **config: Any) -> AsyncClientResponse: """Send the request using this HTTP sender. Will pre-load the body into memory to be available with a sync method. pass stream=True to avoid this behavior. """ result = await self._session.reques...
[ "async", "def", "send", "(", "self", ",", "request", ":", "ClientRequest", ",", "*", "*", "config", ":", "Any", ")", "->", "AsyncClientResponse", ":", "result", "=", "await", "self", ".", "_session", ".", "request", "(", "request", ".", "method", ",", ...
Send the request using this HTTP sender. Will pre-load the body into memory to be available with a sync method. pass stream=True to avoid this behavior.
[ "Send", "the", "request", "using", "this", "HTTP", "sender", "." ]
python
train
hyperledger/sawtooth-core
validator/sawtooth_validator/state/batch_tracker.py
https://github.com/hyperledger/sawtooth-core/blob/8cf473bc2207e51f02bd182d825158a57d72b098/validator/sawtooth_validator/state/batch_tracker.py#L187-L190
def _has_no_pendings(self, statuses): """Returns True if a statuses dict has no PENDING statuses. """ return all(s != ClientBatchStatus.PENDING for s in statuses.values())
[ "def", "_has_no_pendings", "(", "self", ",", "statuses", ")", ":", "return", "all", "(", "s", "!=", "ClientBatchStatus", ".", "PENDING", "for", "s", "in", "statuses", ".", "values", "(", ")", ")" ]
Returns True if a statuses dict has no PENDING statuses.
[ "Returns", "True", "if", "a", "statuses", "dict", "has", "no", "PENDING", "statuses", "." ]
python
train
mezz64/pyEight
pyeight/user.py
https://github.com/mezz64/pyEight/blob/e557e4e6876f490d0964298e9475d68b64222d4f/pyeight/user.py#L494-L542
def dynamic_presence(self): """ Determine presence based on bed heating level and end presence time reported by the api. Idea originated from Alex Lee Yuk Cheung SmartThings Code. """ # self.heating_stats() if not self.presence: if self.heating_leve...
[ "def", "dynamic_presence", "(", "self", ")", ":", "# self.heating_stats()", "if", "not", "self", ".", "presence", ":", "if", "self", ".", "heating_level", ">", "50", ":", "# Can likely make this better", "if", "not", "self", ".", "now_heating", ":", "self", "....
Determine presence based on bed heating level and end presence time reported by the api. Idea originated from Alex Lee Yuk Cheung SmartThings Code.
[ "Determine", "presence", "based", "on", "bed", "heating", "level", "and", "end", "presence", "time", "reported", "by", "the", "api", "." ]
python
train
solocompt/plugs-mail
plugs_mail/management/commands/load_email_templates.py
https://github.com/solocompt/plugs-mail/blob/6139fa79ddb437562db1769d03bd3098c25a06fa/plugs_mail/management/commands/load_email_templates.py#L39-L52
def get_apps(self): """ Get the list of installed apps and return the apps that have an emails module """ templates = [] for app in settings.INSTALLED_APPS: try: app = import_module(app + '.emails') templates += self.get...
[ "def", "get_apps", "(", "self", ")", ":", "templates", "=", "[", "]", "for", "app", "in", "settings", ".", "INSTALLED_APPS", ":", "try", ":", "app", "=", "import_module", "(", "app", "+", "'.emails'", ")", "templates", "+=", "self", ".", "get_plugs_mail_...
Get the list of installed apps and return the apps that have an emails module
[ "Get", "the", "list", "of", "installed", "apps", "and", "return", "the", "apps", "that", "have", "an", "emails", "module" ]
python
train
wtsi-hgi/python-hgijson
hgijson/serialization.py
https://github.com/wtsi-hgi/python-hgijson/blob/6e8ccb562eabcaa816a136268a16504c2e0d4664/hgijson/serialization.py#L188-L237
def deserialize(self, to_deserialize: PrimitiveJsonType) \ -> Optional[Union[SerializableType, List[SerializableType]]]: """ Deserializes the given representation of the serialized object. :param to_deserialize: the serialized object as a dictionary :return: the deserialized ...
[ "def", "deserialize", "(", "self", ",", "to_deserialize", ":", "PrimitiveJsonType", ")", "->", "Optional", "[", "Union", "[", "SerializableType", ",", "List", "[", "SerializableType", "]", "]", "]", ":", "if", "to_deserialize", "is", "None", ":", "# Implements...
Deserializes the given representation of the serialized object. :param to_deserialize: the serialized object as a dictionary :return: the deserialized object or collection of deserialized objects
[ "Deserializes", "the", "given", "representation", "of", "the", "serialized", "object", ".", ":", "param", "to_deserialize", ":", "the", "serialized", "object", "as", "a", "dictionary", ":", "return", ":", "the", "deserialized", "object", "or", "collection", "of"...
python
train
Opentrons/opentrons
api/src/opentrons/legacy_api/instruments/pipette.py
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/instruments/pipette.py#L1159-L1192
def home(self): """ Home the pipette's plunger axis during a protocol run Notes ----- `Pipette.home()` homes the `Robot` Returns ------- This instance of :class:`Pipette`. Examples -------- .. >>> from opentrons import i...
[ "def", "home", "(", "self", ")", ":", "def", "_home", "(", "mount", ")", ":", "self", ".", "current_volume", "=", "0", "self", ".", "instrument_actuator", ".", "set_active_current", "(", "self", ".", "_plunger_current", ")", "self", ".", "robot", ".", "p...
Home the pipette's plunger axis during a protocol run Notes ----- `Pipette.home()` homes the `Robot` Returns ------- This instance of :class:`Pipette`. Examples -------- .. >>> from opentrons import instruments, robot # doctest: +SKIP ...
[ "Home", "the", "pipette", "s", "plunger", "axis", "during", "a", "protocol", "run" ]
python
train
gabstopper/smc-python
smc/core/engines.py
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/engines.py#L824-L848
def add_snmp(data, interfaces): """ Format data for adding SNMP to an engine. :param list data: list of interfaces as provided by kw :param list interfaces: interfaces to enable SNMP by id """ snmp_interface = [] if interfaces: # Not providing interfaces will enable SNMP on all NDIs ...
[ "def", "add_snmp", "(", "data", ",", "interfaces", ")", ":", "snmp_interface", "=", "[", "]", "if", "interfaces", ":", "# Not providing interfaces will enable SNMP on all NDIs", "interfaces", "=", "map", "(", "str", ",", "interfaces", ")", "for", "interface", "in"...
Format data for adding SNMP to an engine. :param list data: list of interfaces as provided by kw :param list interfaces: interfaces to enable SNMP by id
[ "Format", "data", "for", "adding", "SNMP", "to", "an", "engine", ".", ":", "param", "list", "data", ":", "list", "of", "interfaces", "as", "provided", "by", "kw", ":", "param", "list", "interfaces", ":", "interfaces", "to", "enable", "SNMP", "by", "id" ]
python
train
kdeldycke/maildir-deduplicate
maildir_deduplicate/deduplicate.py
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/deduplicate.py#L361-L380
def delete_bigger(self): """ Delete all bigger duplicates. Only keeps the subset sharing the smallest size. """ logger.info( "Deleting all mails strictly bigger than {} bytes...".format( self.smallest_size)) # Select candidates for deletion. c...
[ "def", "delete_bigger", "(", "self", ")", ":", "logger", ".", "info", "(", "\"Deleting all mails strictly bigger than {} bytes...\"", ".", "format", "(", "self", ".", "smallest_size", ")", ")", "# Select candidates for deletion.", "candidates", "=", "[", "mail", "for"...
Delete all bigger duplicates. Only keeps the subset sharing the smallest size.
[ "Delete", "all", "bigger", "duplicates", "." ]
python
train
fprimex/zdesk
zdesk/zdesk_api.py
https://github.com/fprimex/zdesk/blob/851611c13b4d530e9df31390b3ec709baf0a0188/zdesk/zdesk_api.py#L4098-L4102
def user_tags_delete(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/tags#remove-tags" api_path = "/api/v2/users/{id}/tags.json" api_path = api_path.format(id=id) return self.call(api_path, method="DELETE", **kwargs)
[ "def", "user_tags_delete", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/users/{id}/tags.json\"", "api_path", "=", "api_path", ".", "format", "(", "id", "=", "id", ")", "return", "self", ".", "call", "(", "api_path"...
https://developer.zendesk.com/rest_api/docs/core/tags#remove-tags
[ "https", ":", "//", "developer", ".", "zendesk", ".", "com", "/", "rest_api", "/", "docs", "/", "core", "/", "tags#remove", "-", "tags" ]
python
train
SeattleTestbed/seash
pyreadline/modes/emacs.py
https://github.com/SeattleTestbed/seash/blob/40f9d2285662ff8b61e0468b4196acee089b273b/pyreadline/modes/emacs.py#L251-L290
def _process_keyevent(self, keyinfo): u"""return True when line is final """ #Process exit keys. Only exit on empty line log(u"_process_keyevent <%s>"%keyinfo) def nop(e): pass if self.next_meta: self.next_meta = False keyinf...
[ "def", "_process_keyevent", "(", "self", ",", "keyinfo", ")", ":", "#Process exit keys. Only exit on empty line\r", "log", "(", "u\"_process_keyevent <%s>\"", "%", "keyinfo", ")", "def", "nop", "(", "e", ")", ":", "pass", "if", "self", ".", "next_meta", ":", "se...
u"""return True when line is final
[ "u", "return", "True", "when", "line", "is", "final" ]
python
train
DarkEnergySurvey/ugali
ugali/utils/fileio.py
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/fileio.py#L20-L42
def read(filename,**kwargs): """ Read a generic input file into a recarray. Accepted file formats: [.fits,.fz,.npy,.csv,.txt,.dat] Parameters: filename : input file name kwargs : keyword arguments for the reader Returns: recarray : data array """ base,ext = os.path.splitext(fi...
[ "def", "read", "(", "filename", ",", "*", "*", "kwargs", ")", ":", "base", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "if", "ext", "in", "(", "'.fits'", ",", "'.fz'", ")", ":", "# Abstract fits here...", "return", "fit...
Read a generic input file into a recarray. Accepted file formats: [.fits,.fz,.npy,.csv,.txt,.dat] Parameters: filename : input file name kwargs : keyword arguments for the reader Returns: recarray : data array
[ "Read", "a", "generic", "input", "file", "into", "a", "recarray", ".", "Accepted", "file", "formats", ":", "[", ".", "fits", ".", "fz", ".", "npy", ".", "csv", ".", "txt", ".", "dat", "]", "Parameters", ":", "filename", ":", "input", "file", "name", ...
python
train
Terrance/SkPy
skpy/conn.py
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/conn.py#L59-L89
def handle(*codes, **kwargs): """ Method decorator: if a given status code is received, re-authenticate and try again. Args: codes (int list): status codes to respond to regToken (bool): whether to try retrieving a new token on error Returns: method:...
[ "def", "handle", "(", "*", "codes", ",", "*", "*", "kwargs", ")", ":", "regToken", "=", "kwargs", ".", "get", "(", "\"regToken\"", ",", "False", ")", "subscribe", "=", "kwargs", ".", "get", "(", "\"subscribe\"", ")", "def", "decorator", "(", "fn", ")...
Method decorator: if a given status code is received, re-authenticate and try again. Args: codes (int list): status codes to respond to regToken (bool): whether to try retrieving a new token on error Returns: method: decorator function, ready to apply to other metho...
[ "Method", "decorator", ":", "if", "a", "given", "status", "code", "is", "received", "re", "-", "authenticate", "and", "try", "again", "." ]
python
test
lobocv/anonymoususage
anonymoususage/tools.py
https://github.com/lobocv/anonymoususage/blob/847bdad0746ad1cc6c57fb9def201beb59fb8300/anonymoususage/tools.py#L271-L281
def login_hq(host, user, passwd, path='', acct='', port=21, timeout=5): """ Create and return a logged in FTP object. :return: """ ftp = ftplib.FTP() ftp.connect(host=host, port=port, timeout=timeout) ftp.login(user=user, passwd=passwd, acct=acct) ftp.cwd(path) logger.debug('Login to...
[ "def", "login_hq", "(", "host", ",", "user", ",", "passwd", ",", "path", "=", "''", ",", "acct", "=", "''", ",", "port", "=", "21", ",", "timeout", "=", "5", ")", ":", "ftp", "=", "ftplib", ".", "FTP", "(", ")", "ftp", ".", "connect", "(", "h...
Create and return a logged in FTP object. :return:
[ "Create", "and", "return", "a", "logged", "in", "FTP", "object", ".", ":", "return", ":" ]
python
train
bwhite/hadoopy
hadoopy/thirdparty/pyinstaller/PyInstaller/bindepend.py
https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/bindepend.py#L341-L391
def selectImports(pth, xtrapath=None): """ Return the dependencies of a binary that should be included. Return a list of pairs (name, fullpath) """ rv = [] if xtrapath is None: xtrapath = [os.path.dirname(pth)] else: assert isinstance(xtrapath, list) xtrapath = [os.p...
[ "def", "selectImports", "(", "pth", ",", "xtrapath", "=", "None", ")", ":", "rv", "=", "[", "]", "if", "xtrapath", "is", "None", ":", "xtrapath", "=", "[", "os", ".", "path", ".", "dirname", "(", "pth", ")", "]", "else", ":", "assert", "isinstance"...
Return the dependencies of a binary that should be included. Return a list of pairs (name, fullpath)
[ "Return", "the", "dependencies", "of", "a", "binary", "that", "should", "be", "included", "." ]
python
train
hvac/hvac
hvac/api/system_backend/audit.py
https://github.com/hvac/hvac/blob/cce5b86889193f622c2a72a4a1b7e1c9c8aff1ce/hvac/api/system_backend/audit.py#L77-L102
def calculate_hash(self, path, input_to_hash): """Hash the given input data with the specified audit device's hash function and salt. This endpoint can be used to discover whether a given plaintext string (the input parameter) appears in the audit log in obfuscated form. Supported meth...
[ "def", "calculate_hash", "(", "self", ",", "path", ",", "input_to_hash", ")", ":", "params", "=", "{", "'input'", ":", "input_to_hash", ",", "}", "api_path", "=", "'/v1/sys/audit-hash/{path}'", ".", "format", "(", "path", "=", "path", ")", "response", "=", ...
Hash the given input data with the specified audit device's hash function and salt. This endpoint can be used to discover whether a given plaintext string (the input parameter) appears in the audit log in obfuscated form. Supported methods: POST: /sys/audit-hash/{path}. Produces: 2...
[ "Hash", "the", "given", "input", "data", "with", "the", "specified", "audit", "device", "s", "hash", "function", "and", "salt", "." ]
python
train
peterwittek/ncpol2sdpa
ncpol2sdpa/nc_utils.py
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L146-L165
def separate_scalar_factor(element): """Construct a monomial with the coefficient separated from an element in a polynomial. """ coeff = 1.0 monomial = S.One if isinstance(element, (int, float, complex)): coeff *= element return monomial, coeff for var in element.as_coeff_mul...
[ "def", "separate_scalar_factor", "(", "element", ")", ":", "coeff", "=", "1.0", "monomial", "=", "S", ".", "One", "if", "isinstance", "(", "element", ",", "(", "int", ",", "float", ",", "complex", ")", ")", ":", "coeff", "*=", "element", "return", "mon...
Construct a monomial with the coefficient separated from an element in a polynomial.
[ "Construct", "a", "monomial", "with", "the", "coefficient", "separated", "from", "an", "element", "in", "a", "polynomial", "." ]
python
train
hyperledger/indy-plenum
plenum/server/node.py
https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/node.py#L1890-L1916
def validateNodeMsg(self, wrappedMsg): """ Validate another node's message sent to this node. :param wrappedMsg: Tuple of message and the name of the node that sent the message :return: Tuple of message from node and name of the node """ msg, frm = wrappedMsg ...
[ "def", "validateNodeMsg", "(", "self", ",", "wrappedMsg", ")", ":", "msg", ",", "frm", "=", "wrappedMsg", "if", "self", ".", "isNodeBlacklisted", "(", "frm", ")", ":", "self", ".", "discard", "(", "str", "(", "msg", ")", "[", ":", "256", "]", ",", ...
Validate another node's message sent to this node. :param wrappedMsg: Tuple of message and the name of the node that sent the message :return: Tuple of message from node and name of the node
[ "Validate", "another", "node", "s", "message", "sent", "to", "this", "node", "." ]
python
train
PMEAL/OpenPNM
openpnm/utils/Project.py
https://github.com/PMEAL/OpenPNM/blob/0547b5724ffedc0a593aae48639d36fe10e0baed/openpnm/utils/Project.py#L235-L264
def find_phase(self, obj): r""" Find the Phase associated with a given object. Parameters ---------- obj : OpenPNM Object Can either be a Physics or Algorithm object Returns ------- An OpenPNM Phase object. Raises ------ ...
[ "def", "find_phase", "(", "self", ",", "obj", ")", ":", "# If received phase, just return self", "if", "obj", ".", "_isa", "(", "'phase'", ")", ":", "return", "obj", "# If phase happens to be in settings (i.e. algorithm), look it up", "if", "'phase'", "in", "obj", "."...
r""" Find the Phase associated with a given object. Parameters ---------- obj : OpenPNM Object Can either be a Physics or Algorithm object Returns ------- An OpenPNM Phase object. Raises ------ If no Phase object can be found...
[ "r", "Find", "the", "Phase", "associated", "with", "a", "given", "object", "." ]
python
train
Microsoft/nni
examples/tuners/weight_sharing/ga_customer_tuner/customer_tuner.py
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/tuners/weight_sharing/ga_customer_tuner/customer_tuner.py#L84-L91
def generate_new_id(self): """ generate new id and event hook for new Individual """ self.events.append(Event()) indiv_id = self.indiv_counter self.indiv_counter += 1 return indiv_id
[ "def", "generate_new_id", "(", "self", ")", ":", "self", ".", "events", ".", "append", "(", "Event", "(", ")", ")", "indiv_id", "=", "self", ".", "indiv_counter", "self", ".", "indiv_counter", "+=", "1", "return", "indiv_id" ]
generate new id and event hook for new Individual
[ "generate", "new", "id", "and", "event", "hook", "for", "new", "Individual" ]
python
train
iotile/coretools
iotileemulate/iotile/emulate/reference/controller_features/clock_manager.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/clock_manager.py#L281-L288
def set_time_offset(self, offset, is_utc): """Temporarily set the current time offset.""" is_utc = bool(is_utc) self.clock_manager.time_offset = offset self.clock_manager.is_utc = is_utc return [Error.NO_ERROR]
[ "def", "set_time_offset", "(", "self", ",", "offset", ",", "is_utc", ")", ":", "is_utc", "=", "bool", "(", "is_utc", ")", "self", ".", "clock_manager", ".", "time_offset", "=", "offset", "self", ".", "clock_manager", ".", "is_utc", "=", "is_utc", "return",...
Temporarily set the current time offset.
[ "Temporarily", "set", "the", "current", "time", "offset", "." ]
python
train
DLR-RM/RAFCON
source/rafcon/core/states/hierarchy_state.py
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/hierarchy_state.py#L169-L184
def _handle_backward_execution_before_child_execution(self): """ Sets up all data after receiving a backward execution step from the execution engine :return: a flag to indicate if normal child state execution should abort """ self.backward_execution = True last_history_item = se...
[ "def", "_handle_backward_execution_before_child_execution", "(", "self", ")", ":", "self", ".", "backward_execution", "=", "True", "last_history_item", "=", "self", ".", "execution_history", ".", "pop_last_item", "(", ")", "if", "last_history_item", ".", "state_referenc...
Sets up all data after receiving a backward execution step from the execution engine :return: a flag to indicate if normal child state execution should abort
[ "Sets", "up", "all", "data", "after", "receiving", "a", "backward", "execution", "step", "from", "the", "execution", "engine", ":", "return", ":", "a", "flag", "to", "indicate", "if", "normal", "child", "state", "execution", "should", "abort" ]
python
train
yola/yoconfigurator
yoconfigurator/credentials.py
https://github.com/yola/yoconfigurator/blob/dfb60fa1e30ae7cfec2526bb101fc205f5952639/yoconfigurator/credentials.py#L4-L9
def seeded_auth_token(client, service, seed): """Return an auth token based on the client+service+seed tuple.""" hash_func = hashlib.md5() token = ','.join((client, service, seed)).encode('utf-8') hash_func.update(token) return hash_func.hexdigest()
[ "def", "seeded_auth_token", "(", "client", ",", "service", ",", "seed", ")", ":", "hash_func", "=", "hashlib", ".", "md5", "(", ")", "token", "=", "','", ".", "join", "(", "(", "client", ",", "service", ",", "seed", ")", ")", ".", "encode", "(", "'...
Return an auth token based on the client+service+seed tuple.
[ "Return", "an", "auth", "token", "based", "on", "the", "client", "+", "service", "+", "seed", "tuple", "." ]
python
valid
hyperledger/sawtooth-core
rest_api/sawtooth_rest_api/route_handlers.py
https://github.com/hyperledger/sawtooth-core/blob/8cf473bc2207e51f02bd182d825158a57d72b098/rest_api/sawtooth_rest_api/route_handlers.py#L962-L973
def _set_wait(self, request, validator_query): """Parses the `wait` query parameter, and sets the corresponding `wait` and `timeout` properties in the validator query. """ wait = request.url.query.get('wait', 'false') if wait.lower() != 'false': validator_query.wait =...
[ "def", "_set_wait", "(", "self", ",", "request", ",", "validator_query", ")", ":", "wait", "=", "request", ".", "url", ".", "query", ".", "get", "(", "'wait'", ",", "'false'", ")", "if", "wait", ".", "lower", "(", ")", "!=", "'false'", ":", "validato...
Parses the `wait` query parameter, and sets the corresponding `wait` and `timeout` properties in the validator query.
[ "Parses", "the", "wait", "query", "parameter", "and", "sets", "the", "corresponding", "wait", "and", "timeout", "properties", "in", "the", "validator", "query", "." ]
python
train
C-Pro/pgdocgen
pgdocgen/files.py
https://github.com/C-Pro/pgdocgen/blob/b5d95c1bc1b38e3c7977aeddc20793a7b0f5d0fe/pgdocgen/files.py#L11-L21
def read_dir(input_dir,input_ext,func): '''reads all files with extension input_ext in a directory input_dir and apply function func to their contents''' import os for dirpath, dnames, fnames in os.walk(input_dir): for fname in fnames: if not dirpath.endswith(os.sep): ...
[ "def", "read_dir", "(", "input_dir", ",", "input_ext", ",", "func", ")", ":", "import", "os", "for", "dirpath", ",", "dnames", ",", "fnames", "in", "os", ".", "walk", "(", "input_dir", ")", ":", "for", "fname", "in", "fnames", ":", "if", "not", "dirp...
reads all files with extension input_ext in a directory input_dir and apply function func to their contents
[ "reads", "all", "files", "with", "extension", "input_ext", "in", "a", "directory", "input_dir", "and", "apply", "function", "func", "to", "their", "contents" ]
python
train
praekeltfoundation/seaworthy
seaworthy/definitions.py
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/definitions.py#L246-L267
def setup(self, helper=None, **run_kwargs): """ Creates the container, starts it, and waits for it to completely start. :param helper: The resource helper to use, if one was not provided when this container definition was created. :param **run_kwargs: Keyword arg...
[ "def", "setup", "(", "self", ",", "helper", "=", "None", ",", "*", "*", "run_kwargs", ")", ":", "if", "self", ".", "created", ":", "return", "self", ".", "set_helper", "(", "helper", ")", "self", ".", "run", "(", "*", "*", "run_kwargs", ")", "self"...
Creates the container, starts it, and waits for it to completely start. :param helper: The resource helper to use, if one was not provided when this container definition was created. :param **run_kwargs: Keyword arguments passed to :meth:`.run`. :returns: Th...
[ "Creates", "the", "container", "starts", "it", "and", "waits", "for", "it", "to", "completely", "start", "." ]
python
train
Azure/azure-storage-python
azure-storage-file/azure/storage/file/_deserialization.py
https://github.com/Azure/azure-storage-python/blob/52327354b192cbcf6b7905118ec6b5d57fa46275/azure-storage-file/azure/storage/file/_deserialization.py#L200-L227
def _convert_xml_to_ranges(response): ''' <?xml version="1.0" encoding="utf-8"?> <Ranges> <Range> <Start>Start Byte</Start> <End>End Byte</End> </Range> <Range> <Start>Start Byte</Start> <End>End Byte</End> </Range> </Ranges> ''' if respons...
[ "def", "_convert_xml_to_ranges", "(", "response", ")", ":", "if", "response", "is", "None", "or", "response", ".", "body", "is", "None", ":", "return", "None", "ranges", "=", "list", "(", ")", "ranges_element", "=", "ETree", ".", "fromstring", "(", "respon...
<?xml version="1.0" encoding="utf-8"?> <Ranges> <Range> <Start>Start Byte</Start> <End>End Byte</End> </Range> <Range> <Start>Start Byte</Start> <End>End Byte</End> </Range> </Ranges>
[ "<?xml", "version", "=", "1", ".", "0", "encoding", "=", "utf", "-", "8", "?", ">", "<Ranges", ">", "<Range", ">", "<Start", ">", "Start", "Byte<", "/", "Start", ">", "<End", ">", "End", "Byte<", "/", "End", ">", "<", "/", "Range", ">", "<Range",...
python
train
bitprophet/ssh
ssh/util.py
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/util.py#L151-L183
def generate_key_bytes(hashclass, salt, key, nbytes): """ Given a password, passphrase, or other human-source key, scramble it through a secure hash into some keyworthy bytes. This specific algorithm is used for encrypting/decrypting private key files. @param hashclass: class from L{Crypto.Hash} t...
[ "def", "generate_key_bytes", "(", "hashclass", ",", "salt", ",", "key", ",", "nbytes", ")", ":", "keydata", "=", "''", "digest", "=", "''", "if", "len", "(", "salt", ")", ">", "8", ":", "salt", "=", "salt", "[", ":", "8", "]", "while", "nbytes", ...
Given a password, passphrase, or other human-source key, scramble it through a secure hash into some keyworthy bytes. This specific algorithm is used for encrypting/decrypting private key files. @param hashclass: class from L{Crypto.Hash} that can be used as a secure hashing function (like C{MD5} ...
[ "Given", "a", "password", "passphrase", "or", "other", "human", "-", "source", "key", "scramble", "it", "through", "a", "secure", "hash", "into", "some", "keyworthy", "bytes", ".", "This", "specific", "algorithm", "is", "used", "for", "encrypting", "/", "dec...
python
train
StackStorm/pybind
pybind/nos/v7_2_0/rbridge_id/interface/ve/ip/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v7_2_0/rbridge_id/interface/ve/ip/__init__.py#L238-L259
def _set_icmp(self, v, load=False): """ Setter method for icmp, mapped from YANG variable /rbridge_id/interface/ve/ip/icmp (container) If this variable is read-only (config: false) in the source YANG file, then _set_icmp is considered as a private method. Backends looking to populate this variable s...
[ "def", "_set_icmp", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base", ...
Setter method for icmp, mapped from YANG variable /rbridge_id/interface/ve/ip/icmp (container) If this variable is read-only (config: false) in the source YANG file, then _set_icmp is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_icmp() ...
[ "Setter", "method", "for", "icmp", "mapped", "from", "YANG", "variable", "/", "rbridge_id", "/", "interface", "/", "ve", "/", "ip", "/", "icmp", "(", "container", ")", "If", "this", "variable", "is", "read", "-", "only", "(", "config", ":", "false", ")...
python
train
odrling/peony-twitter
peony/commands/utils.py
https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/peony/commands/utils.py#L4-L28
def doc(func): """ Find the message shown when someone calls the help command Parameters ---------- func : function the function Returns ------- str The help message for this command """ stripped_chars = " \t" if hasattr(func, '__doc__'): docstr...
[ "def", "doc", "(", "func", ")", ":", "stripped_chars", "=", "\" \\t\"", "if", "hasattr", "(", "func", ",", "'__doc__'", ")", ":", "docstring", "=", "func", ".", "__doc__", ".", "lstrip", "(", "\" \\n\\t\"", ")", "if", "\"\\n\"", "in", "docstring", ":", ...
Find the message shown when someone calls the help command Parameters ---------- func : function the function Returns ------- str The help message for this command
[ "Find", "the", "message", "shown", "when", "someone", "calls", "the", "help", "command" ]
python
valid
bioasp/iggy
src/query.py
https://github.com/bioasp/iggy/blob/451dee74f277d822d64cf8f3859c94b2f2b6d4db/src/query.py#L83-L102
def get_scenfit(instance, OS, FP, FC, EP): '''returns the scenfit of data and model described by the ``TermSet`` object [instance]. ''' sem = [sign_cons_prg, bwd_prop_prg] if OS : sem.append(one_state_prg) if FP : sem.append(fwd_prop_prg) if FC : sem.append(founded_prg) if EP : sem.append(elem_path_prg)...
[ "def", "get_scenfit", "(", "instance", ",", "OS", ",", "FP", ",", "FC", ",", "EP", ")", ":", "sem", "=", "[", "sign_cons_prg", ",", "bwd_prop_prg", "]", "if", "OS", ":", "sem", ".", "append", "(", "one_state_prg", ")", "if", "FP", ":", "sem", ".", ...
returns the scenfit of data and model described by the ``TermSet`` object [instance].
[ "returns", "the", "scenfit", "of", "data", "and", "model", "described", "by", "the", "TermSet", "object", "[", "instance", "]", "." ]
python
train
mfcovington/pubmed-lookup
pubmed_lookup/command_line.py
https://github.com/mfcovington/pubmed-lookup/blob/b0aa2945b354f0945db73da22dd15ea628212da8/pubmed_lookup/command_line.py#L7-L26
def pubmed_citation(args=sys.argv[1:], out=sys.stdout): """Get a citation via the command line using a PubMed ID or PubMed URL""" parser = argparse.ArgumentParser( description='Get a citation using a PubMed ID or PubMed URL') parser.add_argument('query', help='PubMed ID or PubMed URL') parser.a...
[ "def", "pubmed_citation", "(", "args", "=", "sys", ".", "argv", "[", "1", ":", "]", ",", "out", "=", "sys", ".", "stdout", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Get a citation using a PubMed ID or PubMed URL'", ...
Get a citation via the command line using a PubMed ID or PubMed URL
[ "Get", "a", "citation", "via", "the", "command", "line", "using", "a", "PubMed", "ID", "or", "PubMed", "URL" ]
python
train
ArduPilot/MAVProxy
MAVProxy/modules/lib/mp_checklist.py
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/lib/mp_checklist.py#L55-L58
def set_check(self, name, state): '''set a status value''' if self.child.is_alive(): self.parent_pipe.send(CheckItem(name, state))
[ "def", "set_check", "(", "self", ",", "name", ",", "state", ")", ":", "if", "self", ".", "child", ".", "is_alive", "(", ")", ":", "self", ".", "parent_pipe", ".", "send", "(", "CheckItem", "(", "name", ",", "state", ")", ")" ]
set a status value
[ "set", "a", "status", "value" ]
python
train
mapeveri/django-endless-pagination-vue
endless_pagination/utils.py
https://github.com/mapeveri/django-endless-pagination-vue/blob/3faa79a51b11d7ae0bd431abf8c38ecaf9180704/endless_pagination/utils.py#L38-L53
def get_page_number_from_request( request, querystring_key=PAGE_LABEL, default=1): """Retrieve the current page number from *GET* or *POST* data. If the page does not exists in *request*, or is not a number, then *default* number is returned. """ try: if request.method == 'POST': ...
[ "def", "get_page_number_from_request", "(", "request", ",", "querystring_key", "=", "PAGE_LABEL", ",", "default", "=", "1", ")", ":", "try", ":", "if", "request", ".", "method", "==", "'POST'", ":", "page_number", "=", "request", ".", "POST", "[", "querystri...
Retrieve the current page number from *GET* or *POST* data. If the page does not exists in *request*, or is not a number, then *default* number is returned.
[ "Retrieve", "the", "current", "page", "number", "from", "*", "GET", "*", "or", "*", "POST", "*", "data", "." ]
python
train
DataDog/integrations-core
rabbitmq/datadog_checks/rabbitmq/rabbitmq.py
https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/rabbitmq/datadog_checks/rabbitmq/rabbitmq.py#L375-L549
def get_stats( self, instance, base_url, object_type, max_detailed, filters, limit_vhosts, custom_tags, auth=None, ssl_verify=True, ): """ instance: the check instance base_url: the url of the rabbitmq management...
[ "def", "get_stats", "(", "self", ",", "instance", ",", "base_url", ",", "object_type", ",", "max_detailed", ",", "filters", ",", "limit_vhosts", ",", "custom_tags", ",", "auth", "=", "None", ",", "ssl_verify", "=", "True", ",", ")", ":", "instance_proxy", ...
instance: the check instance base_url: the url of the rabbitmq management api (e.g. http://localhost:15672/api) object_type: either QUEUE_TYPE or NODE_TYPE or EXCHANGE_TYPE max_detailed: the limit of objects to collect for this type filters: explicit or regexes filters of specified queue...
[ "instance", ":", "the", "check", "instance", "base_url", ":", "the", "url", "of", "the", "rabbitmq", "management", "api", "(", "e", ".", "g", ".", "http", ":", "//", "localhost", ":", "15672", "/", "api", ")", "object_type", ":", "either", "QUEUE_TYPE", ...
python
train
googledatalab/pydatalab
solutionbox/ml_workbench/tensorflow/trainer/feature_transforms.py
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/tensorflow/trainer/feature_transforms.py#L84-L108
def _scale(x, min_x_value, max_x_value, output_min, output_max): """Scale a column to [output_min, output_max]. Assumes the columns's range is [min_x_value, max_x_value]. If this is not true at training or prediction time, the output value of this scale could be outside the range [output_min, output_max]. R...
[ "def", "_scale", "(", "x", ",", "min_x_value", ",", "max_x_value", ",", "output_min", ",", "output_max", ")", ":", "if", "round", "(", "min_x_value", "-", "max_x_value", ",", "7", ")", "==", "0", ":", "# There is something wrong with the data.", "# Why round to ...
Scale a column to [output_min, output_max]. Assumes the columns's range is [min_x_value, max_x_value]. If this is not true at training or prediction time, the output value of this scale could be outside the range [output_min, output_max]. Raises: ValueError: if min_x_value = max_x_value, as the column is ...
[ "Scale", "a", "column", "to", "[", "output_min", "output_max", "]", "." ]
python
train
opennode/waldur-core
waldur_core/logging/views.py
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/logging/views.py#L270-L281
def acknowledge(self, request, *args, **kwargs): """ To acknowledge alert - run **POST** against */api/alerts/<alert_uuid>/acknowledge/*. No payload is required. All users that can see alerts can also acknowledge it. If alert is already acknowledged endpoint will return error with code 4...
[ "def", "acknowledge", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "alert", "=", "self", ".", "get_object", "(", ")", "if", "not", "alert", ".", "acknowledged", ":", "alert", ".", "acknowledge", "(", ")", "return"...
To acknowledge alert - run **POST** against */api/alerts/<alert_uuid>/acknowledge/*. No payload is required. All users that can see alerts can also acknowledge it. If alert is already acknowledged endpoint will return error with code 409(conflict).
[ "To", "acknowledge", "alert", "-", "run", "**", "POST", "**", "against", "*", "/", "api", "/", "alerts", "/", "<alert_uuid", ">", "/", "acknowledge", "/", "*", ".", "No", "payload", "is", "required", ".", "All", "users", "that", "can", "see", "alerts",...
python
train
aliyun/aliyun-odps-python-sdk
odps/ml/metrics/regression.py
https://github.com/aliyun/aliyun-odps-python-sdk/blob/4b0de18f5864386df6068f26f026e62f932c41e4/odps/ml/metrics/regression.py#L74-L91
def mean_absolute_percentage_error(df, col_true, col_pred=None): """ Compute mean absolute percentage error of a predicted DataFrame. Note that this method will trigger the defined flow to execute. :param df: predicted data frame :type df: DataFrame :param col_true: column name of true value ...
[ "def", "mean_absolute_percentage_error", "(", "df", ",", "col_true", ",", "col_pred", "=", "None", ")", ":", "if", "not", "col_pred", ":", "col_pred", "=", "get_field_name_by_role", "(", "df", ",", "FieldRole", ".", "PREDICTED_VALUE", ")", "return", "_run_evalua...
Compute mean absolute percentage error of a predicted DataFrame. Note that this method will trigger the defined flow to execute. :param df: predicted data frame :type df: DataFrame :param col_true: column name of true value :type col_true: str :param col_true: column name of predicted value, '...
[ "Compute", "mean", "absolute", "percentage", "error", "of", "a", "predicted", "DataFrame", "." ]
python
train
cocaine/cocaine-tools
cocaine/tools/dispatch.py
https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L1407-L1416
def group_pop(name, app, **kwargs): """ Remove application from the specified routing group. """ ctx = Context(**kwargs) ctx.execute_action('group:app:remove', **{ 'storage': ctx.repo.create_secure_service('storage'), 'name': name, 'app': app, })
[ "def", "group_pop", "(", "name", ",", "app", ",", "*", "*", "kwargs", ")", ":", "ctx", "=", "Context", "(", "*", "*", "kwargs", ")", "ctx", ".", "execute_action", "(", "'group:app:remove'", ",", "*", "*", "{", "'storage'", ":", "ctx", ".", "repo", ...
Remove application from the specified routing group.
[ "Remove", "application", "from", "the", "specified", "routing", "group", "." ]
python
train
symphonyoss/python-symphony
symphony/Agent/base.py
https://github.com/symphonyoss/python-symphony/blob/b939f35fbda461183ec0c01790c754f89a295be0/symphony/Agent/base.py#L29-L37
def create_datafeed(self): ''' create datafeed ''' response, status_code = self.__agent__.Datafeed.post_v4_datafeed_create( sessionToken=self.__session__, keyManagerToken=self.__keymngr__ ).result() # return the token self.logger.debug('%s: %s' % (status_c...
[ "def", "create_datafeed", "(", "self", ")", ":", "response", ",", "status_code", "=", "self", ".", "__agent__", ".", "Datafeed", ".", "post_v4_datafeed_create", "(", "sessionToken", "=", "self", ".", "__session__", ",", "keyManagerToken", "=", "self", ".", "__...
create datafeed
[ "create", "datafeed" ]
python
train