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 |
|---|---|---|---|---|---|---|---|---|
spacetelescope/pysynphot | commissioning/basecase.py | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/commissioning/basecase.py#L163-L177 | def savepysyn(self,wave,flux,fname,units=None):
""" Cannot ever use the .writefits() method, because the array is
frequently just sampled at the synphot waveset; plus, writefits
is smart and does things like tapering."""
if units is None:
ytype='throughput'
units=... | [
"def",
"savepysyn",
"(",
"self",
",",
"wave",
",",
"flux",
",",
"fname",
",",
"units",
"=",
"None",
")",
":",
"if",
"units",
"is",
"None",
":",
"ytype",
"=",
"'throughput'",
"units",
"=",
"' '",
"else",
":",
"ytype",
"=",
"'flux'",
"col1",
"=",
"py... | Cannot ever use the .writefits() method, because the array is
frequently just sampled at the synphot waveset; plus, writefits
is smart and does things like tapering. | [
"Cannot",
"ever",
"use",
"the",
".",
"writefits",
"()",
"method",
"because",
"the",
"array",
"is",
"frequently",
"just",
"sampled",
"at",
"the",
"synphot",
"waveset",
";",
"plus",
"writefits",
"is",
"smart",
"and",
"does",
"things",
"like",
"tapering",
"."
] | python | train |
Microsoft/LightGBM | python-package/lightgbm/basic.py | https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1846-L1892 | def update(self, train_set=None, fobj=None):
"""Update Booster for one iteration.
Parameters
----------
train_set : Dataset or None, optional (default=None)
Training data.
If None, last training data is used.
fobj : callable or None, optional (default=Non... | [
"def",
"update",
"(",
"self",
",",
"train_set",
"=",
"None",
",",
"fobj",
"=",
"None",
")",
":",
"# need reset training data",
"if",
"train_set",
"is",
"not",
"None",
"and",
"train_set",
"is",
"not",
"self",
".",
"train_set",
":",
"if",
"not",
"isinstance"... | Update Booster for one iteration.
Parameters
----------
train_set : Dataset or None, optional (default=None)
Training data.
If None, last training data is used.
fobj : callable or None, optional (default=None)
Customized objective function.
... | [
"Update",
"Booster",
"for",
"one",
"iteration",
"."
] | python | train |
mozilla/treeherder | treeherder/log_parser/artifactbuilders.py | https://github.com/mozilla/treeherder/blob/cc47bdec872e5c668d0f01df89517390a164cda3/treeherder/log_parser/artifactbuilders.py#L61-L64 | def get_artifact(self):
"""Return the job artifact built by the parser."""
self.artifact[self.parser.name] = self.parser.get_artifact()
return self.artifact | [
"def",
"get_artifact",
"(",
"self",
")",
":",
"self",
".",
"artifact",
"[",
"self",
".",
"parser",
".",
"name",
"]",
"=",
"self",
".",
"parser",
".",
"get_artifact",
"(",
")",
"return",
"self",
".",
"artifact"
] | Return the job artifact built by the parser. | [
"Return",
"the",
"job",
"artifact",
"built",
"by",
"the",
"parser",
"."
] | python | train |
sunt05/SuPy | docs/source/proc_var_info/gen_df_state_csv.py | https://github.com/sunt05/SuPy/blob/47178bd5aee50a059414e3e504940662fbfae0dc/docs/source/proc_var_info/gen_df_state_csv.py#L56-L79 | def extract_var_suews(dict_var_full: dict, var_supy: str)->list:
'''extract related SUEWS variables for a supy variable `var_supy`
Parameters
----------
dict_var_full : dict
dict_var_full = sp.supy_load.exp_dict_full(sp.supy_load.dict_var2SiteSelect)
var_supy : str
supy variable nam... | [
"def",
"extract_var_suews",
"(",
"dict_var_full",
":",
"dict",
",",
"var_supy",
":",
"str",
")",
"->",
"list",
":",
"x",
"=",
"sp",
".",
"supy_load",
".",
"flatten_list",
"(",
"dict_var_full",
"[",
"var_supy",
"]",
")",
"x",
"=",
"np",
".",
"unique",
"... | extract related SUEWS variables for a supy variable `var_supy`
Parameters
----------
dict_var_full : dict
dict_var_full = sp.supy_load.exp_dict_full(sp.supy_load.dict_var2SiteSelect)
var_supy : str
supy variable name
Returns
-------
list
related SUEWS variables for ... | [
"extract",
"related",
"SUEWS",
"variables",
"for",
"a",
"supy",
"variable",
"var_supy"
] | python | train |
morse-talk/morse-talk | morse_talk/plot.py | https://github.com/morse-talk/morse-talk/blob/71e09ace0aa554d28cada5ee658e43758305b8fa/morse_talk/plot.py#L31-L53 | def _create_x_y(l, duration=1):
"""
Create 2 lists
x: time (as unit of dot (dit)
y: bits
from a list of bit
>>> l = [1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1]
>>> x, y = _create_x_y(l)
>>> x
[-1, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6... | [
"def",
"_create_x_y",
"(",
"l",
",",
"duration",
"=",
"1",
")",
":",
"l",
"=",
"[",
"0",
"]",
"+",
"l",
"+",
"[",
"0",
"]",
"y",
"=",
"[",
"]",
"x",
"=",
"[",
"]",
"for",
"i",
",",
"bit",
"in",
"enumerate",
"(",
"l",
")",
":",
"y",
".",... | Create 2 lists
x: time (as unit of dot (dit)
y: bits
from a list of bit
>>> l = [1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1]
>>> x, y = _create_x_y(l)
>>> x
[-1, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, ... | [
"Create",
"2",
"lists",
"x",
":",
"time",
"(",
"as",
"unit",
"of",
"dot",
"(",
"dit",
")",
"y",
":",
"bits",
"from",
"a",
"list",
"of",
"bit"
] | python | train |
codeinn/vcs | vcs/backends/hg/changeset.py | https://github.com/codeinn/vcs/blob/e6cd94188e9c36d273411bf3adc0584ac6ab92a0/vcs/backends/hg/changeset.py#L97-L102 | def parents(self):
"""
Returns list of parents changesets.
"""
return [self.repository.get_changeset(parent.rev())
for parent in self._ctx.parents() if parent.rev() >= 0] | [
"def",
"parents",
"(",
"self",
")",
":",
"return",
"[",
"self",
".",
"repository",
".",
"get_changeset",
"(",
"parent",
".",
"rev",
"(",
")",
")",
"for",
"parent",
"in",
"self",
".",
"_ctx",
".",
"parents",
"(",
")",
"if",
"parent",
".",
"rev",
"("... | Returns list of parents changesets. | [
"Returns",
"list",
"of",
"parents",
"changesets",
"."
] | python | train |
IDSIA/sacred | sacred/ingredient.py | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L328-L362 | def get_experiment_info(self):
"""Get a dictionary with information about this experiment.
Contains:
* *name*: the name
* *sources*: a list of sources (filename, md5)
* *dependencies*: a list of package dependencies (name, version)
:return: experiment information
... | [
"def",
"get_experiment_info",
"(",
"self",
")",
":",
"dependencies",
"=",
"set",
"(",
")",
"sources",
"=",
"set",
"(",
")",
"for",
"ing",
",",
"_",
"in",
"self",
".",
"traverse_ingredients",
"(",
")",
":",
"dependencies",
"|=",
"ing",
".",
"dependencies"... | Get a dictionary with information about this experiment.
Contains:
* *name*: the name
* *sources*: a list of sources (filename, md5)
* *dependencies*: a list of package dependencies (name, version)
:return: experiment information
:rtype: dict | [
"Get",
"a",
"dictionary",
"with",
"information",
"about",
"this",
"experiment",
"."
] | python | train |
spotify/luigi | luigi/worker.py | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/worker.py#L395-L404 | def check_complete(task, out_queue):
"""
Checks if task is complete, puts the result to out_queue.
"""
logger.debug("Checking if %s is complete", task)
try:
is_complete = task.complete()
except Exception:
is_complete = TracebackWrapper(traceback.format_exc())
out_queue.put((t... | [
"def",
"check_complete",
"(",
"task",
",",
"out_queue",
")",
":",
"logger",
".",
"debug",
"(",
"\"Checking if %s is complete\"",
",",
"task",
")",
"try",
":",
"is_complete",
"=",
"task",
".",
"complete",
"(",
")",
"except",
"Exception",
":",
"is_complete",
"... | Checks if task is complete, puts the result to out_queue. | [
"Checks",
"if",
"task",
"is",
"complete",
"puts",
"the",
"result",
"to",
"out_queue",
"."
] | python | train |
michael-lazar/rtv | rtv/packages/praw/__init__.py | https://github.com/michael-lazar/rtv/blob/ccef2af042566ad384977028cf0bde01bc524dda/rtv/packages/praw/__init__.py#L2047-L2059 | def get_edited(self, subreddit='mod', *args, **kwargs):
"""Return a get_content generator of edited items.
:param subreddit: Either a Subreddit object or the name of the
subreddit to return the edited items for. Defaults to `mod` which
includes items for all the subreddits you m... | [
"def",
"get_edited",
"(",
"self",
",",
"subreddit",
"=",
"'mod'",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"self",
".",
"config",
"[",
"'edited'",
"]",
".",
"format",
"(",
"subreddit",
"=",
"six",
".",
"text_type",
"(",
"sub... | Return a get_content generator of edited items.
:param subreddit: Either a Subreddit object or the name of the
subreddit to return the edited items for. Defaults to `mod` which
includes items for all the subreddits you moderate.
The additional parameters are passed directly int... | [
"Return",
"a",
"get_content",
"generator",
"of",
"edited",
"items",
"."
] | python | train |
marvin-ai/marvin-python-toolbox | marvin_python_toolbox/common/http_client.py | https://github.com/marvin-ai/marvin-python-toolbox/blob/7c95cb2f9698b989150ab94c1285f3a9eaaba423/marvin_python_toolbox/common/http_client.py#L101-L103 | def get_all(self, path, data=None, limit=100):
"""Encapsulates GET all requests"""
return ListResultSet(path=path, data=data or {}, limit=limit) | [
"def",
"get_all",
"(",
"self",
",",
"path",
",",
"data",
"=",
"None",
",",
"limit",
"=",
"100",
")",
":",
"return",
"ListResultSet",
"(",
"path",
"=",
"path",
",",
"data",
"=",
"data",
"or",
"{",
"}",
",",
"limit",
"=",
"limit",
")"
] | Encapsulates GET all requests | [
"Encapsulates",
"GET",
"all",
"requests"
] | python | train |
tcalmant/ipopo | pelix/shell/core.py | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/core.py#L298-L312 | def var_set(self, session, **kwargs):
"""
Sets the given variables or prints the current ones. "set answer=42"
"""
if not kwargs:
session.write_line(
self._utils.make_table(
("Name", "Value"), session.variables.items()
)
... | [
"def",
"var_set",
"(",
"self",
",",
"session",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"kwargs",
":",
"session",
".",
"write_line",
"(",
"self",
".",
"_utils",
".",
"make_table",
"(",
"(",
"\"Name\"",
",",
"\"Value\"",
")",
",",
"session",
".... | Sets the given variables or prints the current ones. "set answer=42" | [
"Sets",
"the",
"given",
"variables",
"or",
"prints",
"the",
"current",
"ones",
".",
"set",
"answer",
"=",
"42"
] | python | train |
taborlab/FlowCal | FlowCal/io.py | https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/io.py#L1395-L1545 | def hist_bins(self, channels=None, nbins=None, scale='logicle', **kwargs):
"""
Get histogram bin edges for the specified channel(s).
These cover the range specified in ``FCSData.range(channels)`` with
a number of bins `nbins`, with linear, logarithmic, or logicle
spacing.
... | [
"def",
"hist_bins",
"(",
"self",
",",
"channels",
"=",
"None",
",",
"nbins",
"=",
"None",
",",
"scale",
"=",
"'logicle'",
",",
"*",
"*",
"kwargs",
")",
":",
"# Default: all channels",
"if",
"channels",
"is",
"None",
":",
"channels",
"=",
"list",
"(",
"... | Get histogram bin edges for the specified channel(s).
These cover the range specified in ``FCSData.range(channels)`` with
a number of bins `nbins`, with linear, logarithmic, or logicle
spacing.
Parameters
----------
channels : int, str, list of int, list of str
... | [
"Get",
"histogram",
"bin",
"edges",
"for",
"the",
"specified",
"channel",
"(",
"s",
")",
"."
] | python | train |
yunojuno/elasticsearch-django | elasticsearch_django/index.py | https://github.com/yunojuno/elasticsearch-django/blob/e8d98d32bcd77f1bedb8f1a22b6523ca44ffd489/elasticsearch_django/index.py#L119-L140 | def scan_index(index, model):
"""
Yield all documents of model type in an index.
This function calls the elasticsearch.helpers.scan function,
and yields all the documents in the index that match the doc_type
produced by a specific Django model.
Args:
index: string, the name of the inde... | [
"def",
"scan_index",
"(",
"index",
",",
"model",
")",
":",
"# see https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-type-query.html",
"query",
"=",
"{",
"\"query\"",
":",
"{",
"\"type\"",
":",
"{",
"\"value\"",
":",
"model",
".",
"_meta",
".",
... | Yield all documents of model type in an index.
This function calls the elasticsearch.helpers.scan function,
and yields all the documents in the index that match the doc_type
produced by a specific Django model.
Args:
index: string, the name of the index to scan, must be a configured
... | [
"Yield",
"all",
"documents",
"of",
"model",
"type",
"in",
"an",
"index",
"."
] | python | train |
log2timeline/plaso | plaso/parsers/winreg_plugins/networks.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/parsers/winreg_plugins/networks.py#L138-L207 | def ExtractEvents(self, parser_mediator, registry_key, **kwargs):
"""Extracts events from a Windows Registry key.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
registry_key (dfwinreg.WinRegistryKey): Windows ... | [
"def",
"ExtractEvents",
"(",
"self",
",",
"parser_mediator",
",",
"registry_key",
",",
"*",
"*",
"kwargs",
")",
":",
"network_info",
"=",
"{",
"}",
"signatures",
"=",
"registry_key",
".",
"GetSubkeyByName",
"(",
"'Signatures'",
")",
"if",
"signatures",
":",
... | Extracts events from a Windows Registry key.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
registry_key (dfwinreg.WinRegistryKey): Windows Registry key. | [
"Extracts",
"events",
"from",
"a",
"Windows",
"Registry",
"key",
"."
] | python | train |
GoogleCloudPlatform/appengine-mapreduce | python/src/mapreduce/util.py | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/util.py#L127-L154 | def get_queue_name(queue_name):
"""Determine which queue MR should run on.
How to choose the queue:
1. If user provided one, use that.
2. If we are starting a mr from taskqueue, inherit that queue.
If it's a special queue, fall back to the default queue.
3. Default queue.
If user is using any MR pipe... | [
"def",
"get_queue_name",
"(",
"queue_name",
")",
":",
"if",
"queue_name",
":",
"return",
"queue_name",
"queue_name",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"HTTP_X_APPENGINE_QUEUENAME\"",
",",
"parameters",
".",
"config",
".",
"QUEUE_NAME",
")",
"if",
"... | Determine which queue MR should run on.
How to choose the queue:
1. If user provided one, use that.
2. If we are starting a mr from taskqueue, inherit that queue.
If it's a special queue, fall back to the default queue.
3. Default queue.
If user is using any MR pipeline interface, pipeline.start takes ... | [
"Determine",
"which",
"queue",
"MR",
"should",
"run",
"on",
"."
] | python | train |
onnx/onnx-mxnet | onnx_mxnet/import_onnx.py | https://github.com/onnx/onnx-mxnet/blob/b602d75c5a01f5ed8f68b11150a06374f058a86b/onnx_mxnet/import_onnx.py#L302-L326 | def _fix_channels(self, op, attrs, inputs):
"""A workaround for getting 'channels' or 'units' since onnx don't provide
these attributes. We check the shape of weights provided to get the number.
"""
if op not in [mx.sym.Convolution, mx.sym.Deconvolution, mx.sym.FullyConnected]:
... | [
"def",
"_fix_channels",
"(",
"self",
",",
"op",
",",
"attrs",
",",
"inputs",
")",
":",
"if",
"op",
"not",
"in",
"[",
"mx",
".",
"sym",
".",
"Convolution",
",",
"mx",
".",
"sym",
".",
"Deconvolution",
",",
"mx",
".",
"sym",
".",
"FullyConnected",
"]... | A workaround for getting 'channels' or 'units' since onnx don't provide
these attributes. We check the shape of weights provided to get the number. | [
"A",
"workaround",
"for",
"getting",
"channels",
"or",
"units",
"since",
"onnx",
"don",
"t",
"provide",
"these",
"attributes",
".",
"We",
"check",
"the",
"shape",
"of",
"weights",
"provided",
"to",
"get",
"the",
"number",
"."
] | python | train |
davebridges/mousedb | mousedb/animal/views.py | https://github.com/davebridges/mousedb/blob/2a33f6d15d88b1540b05f7232b154fdbf8568580/mousedb/animal/views.py#L528-L537 | def todo(request):
"""This view generates a summary of the todo lists.
The login restricted view passes lists for ear tagging, genotyping and weaning and passes them to the template todo.html."""
eartag_list = Animal.objects.filter(Born__lt=(datetime.date.today() - datetime.timedelta(days=settings... | [
"def",
"todo",
"(",
"request",
")",
":",
"eartag_list",
"=",
"Animal",
".",
"objects",
".",
"filter",
"(",
"Born__lt",
"=",
"(",
"datetime",
".",
"date",
".",
"today",
"(",
")",
"-",
"datetime",
".",
"timedelta",
"(",
"days",
"=",
"settings",
".",
"W... | This view generates a summary of the todo lists.
The login restricted view passes lists for ear tagging, genotyping and weaning and passes them to the template todo.html. | [
"This",
"view",
"generates",
"a",
"summary",
"of",
"the",
"todo",
"lists",
".",
"The",
"login",
"restricted",
"view",
"passes",
"lists",
"for",
"ear",
"tagging",
"genotyping",
"and",
"weaning",
"and",
"passes",
"them",
"to",
"the",
"template",
"todo",
".",
... | python | train |
tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3844-L3855 | def weight_targeting(w, k):
"""Weight-level magnitude pruning."""
k = tf.to_int32(k)
w_shape = shape_list(w)
size = tf.to_int32(tf.reduce_prod(w_shape[:-1]))
w = tf.reshape(w, [size, w_shape[-1]])
transpose_w = tf.transpose(w)
thres = tf.contrib.framework.sort(tf.abs(transpose_w), axis=1)[:, k]
mask = ... | [
"def",
"weight_targeting",
"(",
"w",
",",
"k",
")",
":",
"k",
"=",
"tf",
".",
"to_int32",
"(",
"k",
")",
"w_shape",
"=",
"shape_list",
"(",
"w",
")",
"size",
"=",
"tf",
".",
"to_int32",
"(",
"tf",
".",
"reduce_prod",
"(",
"w_shape",
"[",
":",
"-"... | Weight-level magnitude pruning. | [
"Weight",
"-",
"level",
"magnitude",
"pruning",
"."
] | python | train |
Leeps-Lab/otree-redwood | otree_redwood/models.py | https://github.com/Leeps-Lab/otree-redwood/blob/59212f61a256ef77e0a9ed392ff497ea83ee6245/otree_redwood/models.py#L50-L58 | def message(self):
"""Dictionary representation of the Event appropriate for JSON-encoding."""
return {
'timestamp': time.mktime(self.timestamp.timetuple())*1e3 + self.timestamp.microsecond/1e3,
'group': self.group_pk,
'participant': None if not self.participant else ... | [
"def",
"message",
"(",
"self",
")",
":",
"return",
"{",
"'timestamp'",
":",
"time",
".",
"mktime",
"(",
"self",
".",
"timestamp",
".",
"timetuple",
"(",
")",
")",
"*",
"1e3",
"+",
"self",
".",
"timestamp",
".",
"microsecond",
"/",
"1e3",
",",
"'group... | Dictionary representation of the Event appropriate for JSON-encoding. | [
"Dictionary",
"representation",
"of",
"the",
"Event",
"appropriate",
"for",
"JSON",
"-",
"encoding",
"."
] | python | train |
MarcoFavorito/flloat | flloat/parser/ldlf.py | https://github.com/MarcoFavorito/flloat/blob/5e6de1bea444b68d46d288834031860a8b2f8c2d/flloat/parser/ldlf.py#L63-L66 | def t_ATOM(self, t):
r'[a-zA-Z_][a-zA-Z_0-9]*'
t.type = LDLfLexer.reserved.get(t.value, 'ATOM') # Check for reserved words
return t | [
"def",
"t_ATOM",
"(",
"self",
",",
"t",
")",
":",
"t",
".",
"type",
"=",
"LDLfLexer",
".",
"reserved",
".",
"get",
"(",
"t",
".",
"value",
",",
"'ATOM'",
")",
"# Check for reserved words",
"return",
"t"
] | r'[a-zA-Z_][a-zA-Z_0-9]* | [
"r",
"[",
"a",
"-",
"zA",
"-",
"Z_",
"]",
"[",
"a",
"-",
"zA",
"-",
"Z_0",
"-",
"9",
"]",
"*"
] | python | train |
tensorlayer/tensorlayer | tensorlayer/files/utils.py | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L1838-L1899 | def load_ckpt(sess=None, mode_name='model.ckpt', save_dir='checkpoint', var_list=None, is_latest=True, printable=False):
"""Load parameters from `ckpt` file.
Parameters
------------
sess : Session
TensorFlow Session.
mode_name : str
The name of the model, default is ``model.ckpt``.
... | [
"def",
"load_ckpt",
"(",
"sess",
"=",
"None",
",",
"mode_name",
"=",
"'model.ckpt'",
",",
"save_dir",
"=",
"'checkpoint'",
",",
"var_list",
"=",
"None",
",",
"is_latest",
"=",
"True",
",",
"printable",
"=",
"False",
")",
":",
"if",
"sess",
"is",
"None",
... | Load parameters from `ckpt` file.
Parameters
------------
sess : Session
TensorFlow Session.
mode_name : str
The name of the model, default is ``model.ckpt``.
save_dir : str
The path / file directory to the `ckpt`, default is ``checkpoint``.
var_list : list of tensor
... | [
"Load",
"parameters",
"from",
"ckpt",
"file",
"."
] | python | valid |
wtolson/gnsq | gnsq/nsqd.py | https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L453-L462 | def requeue(self, message_id, timeout=0, backoff=True):
"""Re-queue a message (indicate failure to process)."""
self.send(nsq.requeue(message_id, timeout))
self.finish_inflight()
self.on_requeue.send(
self,
message_id=message_id,
timeout=timeout,
... | [
"def",
"requeue",
"(",
"self",
",",
"message_id",
",",
"timeout",
"=",
"0",
",",
"backoff",
"=",
"True",
")",
":",
"self",
".",
"send",
"(",
"nsq",
".",
"requeue",
"(",
"message_id",
",",
"timeout",
")",
")",
"self",
".",
"finish_inflight",
"(",
")",... | Re-queue a message (indicate failure to process). | [
"Re",
"-",
"queue",
"a",
"message",
"(",
"indicate",
"failure",
"to",
"process",
")",
"."
] | python | train |
underworldcode/stripy | stripy-src/stripy/__init__.py | https://github.com/underworldcode/stripy/blob/d4c3480c3e58c88489ded695eadbe7cd5bf94b48/stripy-src/stripy/__init__.py#L25-L72 | def weighted_average_to_nodes(x1, x2, data, interpolator ):
""" Weighted average of scattered data to the nodal points
of a triangulation using the barycentric coordinates as
weightings.
Parameters
----------
x1, x2 : 1D arrays arrays of x,y or lon, lat (radians)
data : 1D array of data... | [
"def",
"weighted_average_to_nodes",
"(",
"x1",
",",
"x2",
",",
"data",
",",
"interpolator",
")",
":",
"import",
"numpy",
"as",
"np",
"gridded_data",
"=",
"np",
".",
"zeros",
"(",
"interpolator",
".",
"npoints",
")",
"norm",
"=",
"np",
".",
"zeros",
"(",
... | Weighted average of scattered data to the nodal points
of a triangulation using the barycentric coordinates as
weightings.
Parameters
----------
x1, x2 : 1D arrays arrays of x,y or lon, lat (radians)
data : 1D array of data to be lumped to the node locations
interpolator : a stripy.Tri... | [
"Weighted",
"average",
"of",
"scattered",
"data",
"to",
"the",
"nodal",
"points",
"of",
"a",
"triangulation",
"using",
"the",
"barycentric",
"coordinates",
"as",
"weightings",
"."
] | python | train |
emin63/eyap | eyap/core/github_comments.py | https://github.com/emin63/eyap/blob/a610761973b478ca0e864e970be05ce29d5994a5/eyap/core/github_comments.py#L356-L374 | def raw_pull(self, topic):
"""Do a raw pull of data for given topic down from github.
:arg topic: String topic (i.e., issue title).
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
:returns: Result of request data from github API.
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~... | [
"def",
"raw_pull",
"(",
"self",
",",
"topic",
")",
":",
"assert",
"topic",
"is",
"not",
"None",
",",
"'A topic of None is not allowed'",
"kwargs",
"=",
"{",
"}",
"if",
"not",
"self",
".",
"user",
"else",
"{",
"'auth'",
":",
"(",
"self",
".",
"user",
",... | Do a raw pull of data for given topic down from github.
:arg topic: String topic (i.e., issue title).
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
:returns: Result of request data from github API.
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
PURPO... | [
"Do",
"a",
"raw",
"pull",
"of",
"data",
"for",
"given",
"topic",
"down",
"from",
"github",
"."
] | python | train |
codelv/enaml-native | src/enamlnative/android/android_view.py | https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_view.py#L140-L145 | def create_widget(self):
""" Create the underlying label widget.
"""
d = self.declaration
self.widget = View(self.get_context(), None, d.style) | [
"def",
"create_widget",
"(",
"self",
")",
":",
"d",
"=",
"self",
".",
"declaration",
"self",
".",
"widget",
"=",
"View",
"(",
"self",
".",
"get_context",
"(",
")",
",",
"None",
",",
"d",
".",
"style",
")"
] | Create the underlying label widget. | [
"Create",
"the",
"underlying",
"label",
"widget",
"."
] | python | train |
datasift/datasift-python | datasift/pylon.py | https://github.com/datasift/datasift-python/blob/bfaca1a47501a18e11065ecf630d9c31df818f65/datasift/pylon.py#L123-L155 | def list(self, page=None, per_page=None, order_by='created_at',
order_dir='DESC', service='facebook'):
""" List pylon recordings
:param page: page number for pagination
:type page: int
:param per_page: number of items per page, default 20
:type per_... | [
"def",
"list",
"(",
"self",
",",
"page",
"=",
"None",
",",
"per_page",
"=",
"None",
",",
"order_by",
"=",
"'created_at'",
",",
"order_dir",
"=",
"'DESC'",
",",
"service",
"=",
"'facebook'",
")",
":",
"params",
"=",
"{",
"}",
"if",
"page",
":",
"param... | List pylon recordings
:param page: page number for pagination
:type page: int
:param per_page: number of items per page, default 20
:type per_page: int
:param order_by: field to order by, default request_time
:type order_by: str
:param... | [
"List",
"pylon",
"recordings"
] | python | train |
rosenbrockc/acorn | acorn/acrn.py | https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/acrn.py#L35-L49 | def _parser_options():
"""Parses the options and arguments from the command line."""
#We have two options: get some of the details from the config file,
import argparse
from acorn import base
pdescr = "ACORN setup and custom configuration"
parser = argparse.ArgumentParser(parents=[base.bparser],... | [
"def",
"_parser_options",
"(",
")",
":",
"#We have two options: get some of the details from the config file,",
"import",
"argparse",
"from",
"acorn",
"import",
"base",
"pdescr",
"=",
"\"ACORN setup and custom configuration\"",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
... | Parses the options and arguments from the command line. | [
"Parses",
"the",
"options",
"and",
"arguments",
"from",
"the",
"command",
"line",
"."
] | python | train |
refenv/cijoe | modules/cij/ssh.py | https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/ssh.py#L54-L88 | def command(cmd, shell=True, echo=True, suffix=None):
"""SSH: Run the given command over SSH as defined in environment"""
if env():
cij.err("cij.ssh.command: Invalid SSH environment")
return 1
prefix = []
if cij.ENV.get("SSH_CMD_TIME") == "1":
prefix.append("/usr/bin/time")
... | [
"def",
"command",
"(",
"cmd",
",",
"shell",
"=",
"True",
",",
"echo",
"=",
"True",
",",
"suffix",
"=",
"None",
")",
":",
"if",
"env",
"(",
")",
":",
"cij",
".",
"err",
"(",
"\"cij.ssh.command: Invalid SSH environment\"",
")",
"return",
"1",
"prefix",
"... | SSH: Run the given command over SSH as defined in environment | [
"SSH",
":",
"Run",
"the",
"given",
"command",
"over",
"SSH",
"as",
"defined",
"in",
"environment"
] | python | valid |
collectiveacuity/labPack | labpack/databases/couchbase.py | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/databases/couchbase.py#L255-L364 | def create_view(self, query_criteria=None, uid='_all_users'):
'''
a method to add a view to a design document of a uid
:param query_criteria: dictionary with valid jsonmodel query criteria
:param uid: [optional] string with uid of design document to update
... | [
"def",
"create_view",
"(",
"self",
",",
"query_criteria",
"=",
"None",
",",
"uid",
"=",
"'_all_users'",
")",
":",
"# https://developer.couchbase.com/documentation/mobile/1.5/references/sync-gateway/admin-rest-api/index.html#/query/put__db___design__ddoc_",
"# https://developer.couchbas... | a method to add a view to a design document of a uid
:param query_criteria: dictionary with valid jsonmodel query criteria
:param uid: [optional] string with uid of design document to update
:return: integer with status of operation
an example of how to construct the quer... | [
"a",
"method",
"to",
"add",
"a",
"view",
"to",
"a",
"design",
"document",
"of",
"a",
"uid",
":",
"param",
"query_criteria",
":",
"dictionary",
"with",
"valid",
"jsonmodel",
"query",
"criteria",
":",
"param",
"uid",
":",
"[",
"optional",
"]",
"string",
"w... | python | train |
CivicSpleen/ambry | ambry/bundle/files.py | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/files.py#L549-L571 | def record_to_objects(self):
"""Create config records to match the file metadata"""
from ..util import AttrDict
fr = self.record
contents = fr.unpacked_contents
if not contents:
return
ad = AttrDict(contents)
# Get time that filessystem was synch... | [
"def",
"record_to_objects",
"(",
"self",
")",
":",
"from",
".",
".",
"util",
"import",
"AttrDict",
"fr",
"=",
"self",
".",
"record",
"contents",
"=",
"fr",
".",
"unpacked_contents",
"if",
"not",
"contents",
":",
"return",
"ad",
"=",
"AttrDict",
"(",
"con... | Create config records to match the file metadata | [
"Create",
"config",
"records",
"to",
"match",
"the",
"file",
"metadata"
] | python | train |
kensho-technologies/graphql-compiler | graphql_compiler/query_formatting/gremlin_formatting.py | https://github.com/kensho-technologies/graphql-compiler/blob/f6079c6d10f64932f6b3af309b79bcea2123ca8f/graphql_compiler/query_formatting/gremlin_formatting.py#L18-L48 | def _safe_gremlin_string(value):
"""Sanitize and represent a string argument in Gremlin."""
if not isinstance(value, six.string_types):
if isinstance(value, bytes): # should only happen in py3
value = value.decode('utf-8')
else:
raise GraphQLInvalidArgumentError(u'Attemp... | [
"def",
"_safe_gremlin_string",
"(",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"bytes",
")",
":",
"# should only happen in py3",
"value",
"=",
"value",
".",
... | Sanitize and represent a string argument in Gremlin. | [
"Sanitize",
"and",
"represent",
"a",
"string",
"argument",
"in",
"Gremlin",
"."
] | python | train |
Ouranosinc/xclim | xclim/utils.py | https://github.com/Ouranosinc/xclim/blob/2080d139188bd8de2aeca097a025c2d89d6e0e09/xclim/utils.py#L888-L953 | def daily_downsampler(da, freq='YS'):
r"""Daily climate data downsampler
Parameters
----------
da : xarray.DataArray
freq : string
Returns
-------
xarray.DataArray
Note
----
Usage Example
grouper = daily_downsampler(da_std, freq='YS')
x2 = gr... | [
"def",
"daily_downsampler",
"(",
"da",
",",
"freq",
"=",
"'YS'",
")",
":",
"# generate tags from da.time and freq",
"if",
"isinstance",
"(",
"da",
".",
"time",
".",
"values",
"[",
"0",
"]",
",",
"np",
".",
"datetime64",
")",
":",
"years",
"=",
"[",
"'{:0... | r"""Daily climate data downsampler
Parameters
----------
da : xarray.DataArray
freq : string
Returns
-------
xarray.DataArray
Note
----
Usage Example
grouper = daily_downsampler(da_std, freq='YS')
x2 = grouper.mean()
# add time coord... | [
"r",
"Daily",
"climate",
"data",
"downsampler"
] | python | train |
gem/oq-engine | openquake/hmtk/faults/tectonic_regionalisation.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/faults/tectonic_regionalisation.py#L111-L140 | def populate_regions(self, tectonic_region_dict):
'''
Populates the tectonic region from the list of dictionaries, where each
region is a dictionary of with the following format::
region = {'Shear_Modulus': [(val1, weight1), (val2, weight2), ...],
'Displacement_Lengt... | [
"def",
"populate_regions",
"(",
"self",
",",
"tectonic_region_dict",
")",
":",
"for",
"tect_reg",
"in",
"tectonic_region_dict",
":",
"if",
"'Shear_Modulus'",
"in",
"tect_reg",
".",
"keys",
"(",
")",
":",
"shear_modulus",
"=",
"tect_reg",
"[",
"'Shear_Modulus'",
... | Populates the tectonic region from the list of dictionaries, where each
region is a dictionary of with the following format::
region = {'Shear_Modulus': [(val1, weight1), (val2, weight2), ...],
'Displacement_Length_Ratio': [(val1, weight1), ...],
'Magnitude_Scalin... | [
"Populates",
"the",
"tectonic",
"region",
"from",
"the",
"list",
"of",
"dictionaries",
"where",
"each",
"region",
"is",
"a",
"dictionary",
"of",
"with",
"the",
"following",
"format",
"::"
] | python | train |
UDST/orca | orca/orca.py | https://github.com/UDST/orca/blob/07b34aeef13cc87c966b2e30cbe7e76cc9d3622c/orca/orca.py#L295-L325 | def column_type(self, column_name):
"""
Report column type as one of 'local', 'series', or 'function'.
Parameters
----------
column_name : str
Returns
-------
col_type : {'local', 'series', 'function'}
'local' means that the column is part of... | [
"def",
"column_type",
"(",
"self",
",",
"column_name",
")",
":",
"extra_cols",
"=",
"list_columns_for_table",
"(",
"self",
".",
"name",
")",
"if",
"column_name",
"in",
"extra_cols",
":",
"col",
"=",
"_COLUMNS",
"[",
"(",
"self",
".",
"name",
",",
"column_n... | Report column type as one of 'local', 'series', or 'function'.
Parameters
----------
column_name : str
Returns
-------
col_type : {'local', 'series', 'function'}
'local' means that the column is part of the registered table,
'series' means the co... | [
"Report",
"column",
"type",
"as",
"one",
"of",
"local",
"series",
"or",
"function",
"."
] | python | train |
FlaskGuys/Flask-Imagine | flask_imagine/filters/watermark.py | https://github.com/FlaskGuys/Flask-Imagine/blob/f79c6517ecb5480b63a2b3b8554edb6e2ac8be8c/flask_imagine/filters/watermark.py#L169-L180 | def _bottom_position(self, resource):
"""
Place watermark to bottom position
:param resource: Image.Image
:return: Image.Image
"""
image = self._get_scaled_image(resource)
left = int(round(resource.size[0] // 2 - image.size[0] // 2))
upper = int(round(res... | [
"def",
"_bottom_position",
"(",
"self",
",",
"resource",
")",
":",
"image",
"=",
"self",
".",
"_get_scaled_image",
"(",
"resource",
")",
"left",
"=",
"int",
"(",
"round",
"(",
"resource",
".",
"size",
"[",
"0",
"]",
"//",
"2",
"-",
"image",
".",
"siz... | Place watermark to bottom position
:param resource: Image.Image
:return: Image.Image | [
"Place",
"watermark",
"to",
"bottom",
"position",
":",
"param",
"resource",
":",
"Image",
".",
"Image",
":",
"return",
":",
"Image",
".",
"Image"
] | python | train |
sryza/spark-timeseries | python/sparkts/timeseriesrdd.py | https://github.com/sryza/spark-timeseries/blob/280aa887dc08ab114411245268f230fdabb76eec/python/sparkts/timeseriesrdd.py#L141-L146 | def to_pandas_series_rdd(self):
"""
Returns an RDD of Pandas Series objects indexed with Pandas DatetimeIndexes
"""
pd_index = self.index().to_pandas_index()
return self.map(lambda x: (x[0], pd.Series(x[1], pd_index))) | [
"def",
"to_pandas_series_rdd",
"(",
"self",
")",
":",
"pd_index",
"=",
"self",
".",
"index",
"(",
")",
".",
"to_pandas_index",
"(",
")",
"return",
"self",
".",
"map",
"(",
"lambda",
"x",
":",
"(",
"x",
"[",
"0",
"]",
",",
"pd",
".",
"Series",
"(",
... | Returns an RDD of Pandas Series objects indexed with Pandas DatetimeIndexes | [
"Returns",
"an",
"RDD",
"of",
"Pandas",
"Series",
"objects",
"indexed",
"with",
"Pandas",
"DatetimeIndexes"
] | python | train |
pyvisa/pyvisa-sim | pyvisa-sim/parser.py | https://github.com/pyvisa/pyvisa-sim/blob/9836166b6b57c165fc63a276f87fe81f106a4e26/pyvisa-sim/parser.py#L82-L106 | def _load(content_or_fp):
"""YAML Parse a file or str and check version.
"""
try:
data = yaml.load(content_or_fp, Loader=yaml.loader.BaseLoader)
except Exception as e:
raise type(e)('Malformed yaml file:\n%r' % format_exc())
try:
ver = data['spec']
except:
raise ... | [
"def",
"_load",
"(",
"content_or_fp",
")",
":",
"try",
":",
"data",
"=",
"yaml",
".",
"load",
"(",
"content_or_fp",
",",
"Loader",
"=",
"yaml",
".",
"loader",
".",
"BaseLoader",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"type",
"(",
"e",
"... | YAML Parse a file or str and check version. | [
"YAML",
"Parse",
"a",
"file",
"or",
"str",
"and",
"check",
"version",
"."
] | python | train |
mayfield/shellish | shellish/data.py | https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/data.py#L151-L204 | def make_hone_cache_wrapper(inner_func, maxsize, maxage, finder,
store_partials):
""" Keeps a cache of requests we've already made and use that for
generating results if possible. If the user asked for a root prior
to this call we can use it to skip a new lookup using `finder`. ... | [
"def",
"make_hone_cache_wrapper",
"(",
"inner_func",
",",
"maxsize",
",",
"maxage",
",",
"finder",
",",
"store_partials",
")",
":",
"hits",
"=",
"misses",
"=",
"partials",
"=",
"0",
"cache",
"=",
"TTLMapping",
"(",
"maxsize",
",",
"maxage",
")",
"def",
"wr... | Keeps a cache of requests we've already made and use that for
generating results if possible. If the user asked for a root prior
to this call we can use it to skip a new lookup using `finder`. A
top-level lookup will effectively serves as a global cache. | [
"Keeps",
"a",
"cache",
"of",
"requests",
"we",
"ve",
"already",
"made",
"and",
"use",
"that",
"for",
"generating",
"results",
"if",
"possible",
".",
"If",
"the",
"user",
"asked",
"for",
"a",
"root",
"prior",
"to",
"this",
"call",
"we",
"can",
"use",
"i... | python | train |
liip/taxi | taxi/timesheet/entry.py | https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/timesheet/entry.py#L411-L509 | def filter(self, date=None, regroup=False, ignored=None, pushed=None, unmapped=None, current_workday=None):
"""
Return the entries as a dict of {:class:`datetime.date`: :class:`~taxi.timesheet.lines.Entry`}
items.
`date` can either be a single :class:`datetime.date` object to filter onl... | [
"def",
"filter",
"(",
"self",
",",
"date",
"=",
"None",
",",
"regroup",
"=",
"False",
",",
"ignored",
"=",
"None",
",",
"pushed",
"=",
"None",
",",
"unmapped",
"=",
"None",
",",
"current_workday",
"=",
"None",
")",
":",
"def",
"entry_filter",
"(",
"e... | Return the entries as a dict of {:class:`datetime.date`: :class:`~taxi.timesheet.lines.Entry`}
items.
`date` can either be a single :class:`datetime.date` object to filter only entries from the given date,
or a tuple of :class:`datetime.date` objects representing `(from, to)`. `filter_callback`... | [
"Return",
"the",
"entries",
"as",
"a",
"dict",
"of",
"{",
":",
"class",
":",
"datetime",
".",
"date",
":",
":",
"class",
":",
"~taxi",
".",
"timesheet",
".",
"lines",
".",
"Entry",
"}",
"items",
"."
] | python | train |
pennlabs/penn-sdk-python | penn/registrar.py | https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/registrar.py#L80-L91 | def section(self, dept, course_number, sect_number):
"""Return a single section object for the given section. All arguments
should be strings. Throws a `ValueError` if the section is not found.
>>> lgst101_bfs = r.course('lgst', '101', '301')
"""
section_id = dept + course_numbe... | [
"def",
"section",
"(",
"self",
",",
"dept",
",",
"course_number",
",",
"sect_number",
")",
":",
"section_id",
"=",
"dept",
"+",
"course_number",
"+",
"sect_number",
"sections",
"=",
"self",
".",
"search",
"(",
"{",
"'course_id'",
":",
"section_id",
"}",
")... | Return a single section object for the given section. All arguments
should be strings. Throws a `ValueError` if the section is not found.
>>> lgst101_bfs = r.course('lgst', '101', '301') | [
"Return",
"a",
"single",
"section",
"object",
"for",
"the",
"given",
"section",
".",
"All",
"arguments",
"should",
"be",
"strings",
".",
"Throws",
"a",
"ValueError",
"if",
"the",
"section",
"is",
"not",
"found",
"."
] | python | train |
basho/riak-python-client | riak/bucket.py | https://github.com/basho/riak-python-client/blob/91de13a16607cdf553d1a194e762734e3bec4231/riak/bucket.py#L116-L128 | def get_decoder(self, content_type):
"""
Get the decoding function for the provided content type for
this bucket.
:param content_type: the requested media type
:type content_type: str
:rtype: function
"""
if content_type in self._decoders:
ret... | [
"def",
"get_decoder",
"(",
"self",
",",
"content_type",
")",
":",
"if",
"content_type",
"in",
"self",
".",
"_decoders",
":",
"return",
"self",
".",
"_decoders",
"[",
"content_type",
"]",
"else",
":",
"return",
"self",
".",
"_client",
".",
"get_decoder",
"(... | Get the decoding function for the provided content type for
this bucket.
:param content_type: the requested media type
:type content_type: str
:rtype: function | [
"Get",
"the",
"decoding",
"function",
"for",
"the",
"provided",
"content",
"type",
"for",
"this",
"bucket",
"."
] | python | train |
rackerlabs/python-lunrclient | lunrclient/lunr_shell.py | https://github.com/rackerlabs/python-lunrclient/blob/f26a450a422600f492480bfa42cbee50a5c7016f/lunrclient/lunr_shell.py#L324-L327 | def create(self, id):
""" Create a new tenant id """
resp = self.client.accounts.create(id=id)
self.display(resp) | [
"def",
"create",
"(",
"self",
",",
"id",
")",
":",
"resp",
"=",
"self",
".",
"client",
".",
"accounts",
".",
"create",
"(",
"id",
"=",
"id",
")",
"self",
".",
"display",
"(",
"resp",
")"
] | Create a new tenant id | [
"Create",
"a",
"new",
"tenant",
"id"
] | python | train |
tanghaibao/jcvi | jcvi/apps/base.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/base.py#L1109-L1129 | def timestamp(args):
"""
%prog timestamp path > timestamp.info
Record the timestamps for all files in the current folder.
filename atime mtime
This file can be used later to recover previous timestamps through touch().
"""
p = OptionParser(timestamp.__doc__)
opts, args = p.parse_args(a... | [
"def",
"timestamp",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"timestamp",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"1",
":",
"sys",
".",
"exit",
"("... | %prog timestamp path > timestamp.info
Record the timestamps for all files in the current folder.
filename atime mtime
This file can be used later to recover previous timestamps through touch(). | [
"%prog",
"timestamp",
"path",
">",
"timestamp",
".",
"info"
] | python | train |
saltstack/salt | salt/modules/file.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L1037-L1046 | def _sed_esc(string, escape_all=False):
'''
Escape single quotes and forward slashes
'''
special_chars = "^.[$()|*+?{"
string = string.replace("'", "'\"'\"'").replace("/", "\\/")
if escape_all is True:
for char in special_chars:
string = string.replace(char, "\\" + char)
... | [
"def",
"_sed_esc",
"(",
"string",
",",
"escape_all",
"=",
"False",
")",
":",
"special_chars",
"=",
"\"^.[$()|*+?{\"",
"string",
"=",
"string",
".",
"replace",
"(",
"\"'\"",
",",
"\"'\\\"'\\\"'\"",
")",
".",
"replace",
"(",
"\"/\"",
",",
"\"\\\\/\"",
")",
"... | Escape single quotes and forward slashes | [
"Escape",
"single",
"quotes",
"and",
"forward",
"slashes"
] | python | train |
googledatalab/pydatalab | google/datalab/bigquery/commands/_bigquery.py | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/commands/_bigquery.py#L645-L647 | def _render_list(data):
""" Helper to render a list of objects as an HTML list object. """
return IPython.core.display.HTML(google.datalab.utils.commands.HtmlBuilder.render_list(data)) | [
"def",
"_render_list",
"(",
"data",
")",
":",
"return",
"IPython",
".",
"core",
".",
"display",
".",
"HTML",
"(",
"google",
".",
"datalab",
".",
"utils",
".",
"commands",
".",
"HtmlBuilder",
".",
"render_list",
"(",
"data",
")",
")"
] | Helper to render a list of objects as an HTML list object. | [
"Helper",
"to",
"render",
"a",
"list",
"of",
"objects",
"as",
"an",
"HTML",
"list",
"object",
"."
] | python | train |
pavoni/pyvera | pyvera/__init__.py | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L471-L481 | def call_service(self, service_id, action):
"""Call a Vera service.
This will call the Vera api to change device state.
"""
result = self.vera_request(id='action', serviceId=service_id,
action=action)
logger.debug("call_service: "
... | [
"def",
"call_service",
"(",
"self",
",",
"service_id",
",",
"action",
")",
":",
"result",
"=",
"self",
".",
"vera_request",
"(",
"id",
"=",
"'action'",
",",
"serviceId",
"=",
"service_id",
",",
"action",
"=",
"action",
")",
"logger",
".",
"debug",
"(",
... | Call a Vera service.
This will call the Vera api to change device state. | [
"Call",
"a",
"Vera",
"service",
"."
] | python | train |
bcbio/bcbio-nextgen | bcbio/bam/fastq.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/fastq.py#L278-L292 | def estimate_read_length(fastq_file, quality_format="fastq-sanger", nreads=1000):
"""
estimate average read length of a fastq file
"""
in_handle = SeqIO.parse(open_fastq(fastq_file), quality_format)
read = next(in_handle)
average = len(read.seq)
for _ in range(nreads):
try:
... | [
"def",
"estimate_read_length",
"(",
"fastq_file",
",",
"quality_format",
"=",
"\"fastq-sanger\"",
",",
"nreads",
"=",
"1000",
")",
":",
"in_handle",
"=",
"SeqIO",
".",
"parse",
"(",
"open_fastq",
"(",
"fastq_file",
")",
",",
"quality_format",
")",
"read",
"=",... | estimate average read length of a fastq file | [
"estimate",
"average",
"read",
"length",
"of",
"a",
"fastq",
"file"
] | python | train |
pgmpy/pgmpy | ez_setup.py | https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/ez_setup.py#L161-L172 | def download_file_powershell(url, target):
"""
Download the file at url to target using Powershell (which will validate
trust). Raise an exception if the command cannot complete.
"""
target = os.path.abspath(target)
cmd = [
'powershell',
'-Command',
"(new-object System.Ne... | [
"def",
"download_file_powershell",
"(",
"url",
",",
"target",
")",
":",
"target",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"target",
")",
"cmd",
"=",
"[",
"'powershell'",
",",
"'-Command'",
",",
"\"(new-object System.Net.WebClient).DownloadFile(%(url)r, %(target... | Download the file at url to target using Powershell (which will validate
trust). Raise an exception if the command cannot complete. | [
"Download",
"the",
"file",
"at",
"url",
"to",
"target",
"using",
"Powershell",
"(",
"which",
"will",
"validate",
"trust",
")",
".",
"Raise",
"an",
"exception",
"if",
"the",
"command",
"cannot",
"complete",
"."
] | python | train |
allenai/allennlp | allennlp/data/iterators/data_iterator.py | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/iterators/data_iterator.py#L22-L28 | def add_epoch_number(batch: Batch, epoch: int) -> Batch:
"""
Add the epoch number to the batch instances as a MetadataField.
"""
for instance in batch.instances:
instance.fields['epoch_num'] = MetadataField(epoch)
return batch | [
"def",
"add_epoch_number",
"(",
"batch",
":",
"Batch",
",",
"epoch",
":",
"int",
")",
"->",
"Batch",
":",
"for",
"instance",
"in",
"batch",
".",
"instances",
":",
"instance",
".",
"fields",
"[",
"'epoch_num'",
"]",
"=",
"MetadataField",
"(",
"epoch",
")"... | Add the epoch number to the batch instances as a MetadataField. | [
"Add",
"the",
"epoch",
"number",
"to",
"the",
"batch",
"instances",
"as",
"a",
"MetadataField",
"."
] | python | train |
annoviko/pyclustering | pyclustering/cluster/ga.py | https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/cluster/ga.py#L648-L671 | def _get_best_chromosome(chromosomes, data, count_clusters):
"""!
@brief Returns the current best chromosome.
@param[in] chromosomes (list): Chromosomes that are used for searching.
@param[in] data (list): Input data that is used for clustering process.
@param[in] count_... | [
"def",
"_get_best_chromosome",
"(",
"chromosomes",
",",
"data",
",",
"count_clusters",
")",
":",
"# Calc centers",
"centres",
"=",
"ga_math",
".",
"get_centres",
"(",
"chromosomes",
",",
"data",
",",
"count_clusters",
")",
"# Calc Fitness functions",
"fitness_function... | !
@brief Returns the current best chromosome.
@param[in] chromosomes (list): Chromosomes that are used for searching.
@param[in] data (list): Input data that is used for clustering process.
@param[in] count_clusters (uint): Amount of clusters that should be allocated.
... | [
"!"
] | python | valid |
googleapis/google-cloud-python | core/google/cloud/_helpers.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/core/google/cloud/_helpers.py#L603-L627 | def make_insecure_stub(stub_class, host, port=None):
"""Makes an insecure stub for an RPC service.
Uses / depends on gRPC.
:type stub_class: type
:param stub_class: A gRPC stub type for a given service.
:type host: str
:param host: The host for the service. May also include the port
... | [
"def",
"make_insecure_stub",
"(",
"stub_class",
",",
"host",
",",
"port",
"=",
"None",
")",
":",
"if",
"port",
"is",
"None",
":",
"target",
"=",
"host",
"else",
":",
"# NOTE: This assumes port != http_client.HTTPS_PORT:",
"target",
"=",
"\"%s:%d\"",
"%",
"(",
... | Makes an insecure stub for an RPC service.
Uses / depends on gRPC.
:type stub_class: type
:param stub_class: A gRPC stub type for a given service.
:type host: str
:param host: The host for the service. May also include the port
if ``port`` is unspecified.
:type port: int
... | [
"Makes",
"an",
"insecure",
"stub",
"for",
"an",
"RPC",
"service",
"."
] | python | train |
TheOneHyer/arandomness | build/lib.linux-x86_64-3.6/arandomness/arandom/agenerator.py | https://github.com/TheOneHyer/arandomness/blob/ae9f630e9a1d67b0eb6d61644a49756de8a5268c/build/lib.linux-x86_64-3.6/arandomness/arandom/agenerator.py#L35-L44 | def agenerator():
"""Arandom number generator"""
free_mem = psutil.virtual_memory().available
mem_24 = 0.24 * free_mem
mem_26 = 0.26 * free_mem
a = MemEater(int(mem_24))
b = MemEater(int(mem_26))
sleep(5)
return free_mem/1000/1000, psutil.virtual_memory().available/1000/1000 | [
"def",
"agenerator",
"(",
")",
":",
"free_mem",
"=",
"psutil",
".",
"virtual_memory",
"(",
")",
".",
"available",
"mem_24",
"=",
"0.24",
"*",
"free_mem",
"mem_26",
"=",
"0.26",
"*",
"free_mem",
"a",
"=",
"MemEater",
"(",
"int",
"(",
"mem_24",
")",
")",... | Arandom number generator | [
"Arandom",
"number",
"generator"
] | python | train |
erikvw/django-collect-offline | django_collect_offline/site_offline_models.py | https://github.com/erikvw/django-collect-offline/blob/3d5efd66c68e2db4b060a82b070ae490dc399ca7/django_collect_offline/site_offline_models.py#L71-L89 | def site_models(self, app_label=None):
"""Returns a dictionary of registered models.
"""
site_models = {}
app_configs = (
django_apps.get_app_configs()
if app_label is None
else [django_apps.get_app_config(app_label)]
)
for app_config i... | [
"def",
"site_models",
"(",
"self",
",",
"app_label",
"=",
"None",
")",
":",
"site_models",
"=",
"{",
"}",
"app_configs",
"=",
"(",
"django_apps",
".",
"get_app_configs",
"(",
")",
"if",
"app_label",
"is",
"None",
"else",
"[",
"django_apps",
".",
"get_app_c... | Returns a dictionary of registered models. | [
"Returns",
"a",
"dictionary",
"of",
"registered",
"models",
"."
] | python | train |
SKA-ScienceDataProcessor/integration-prototype | sip/science_pipeline_workflows/ingest_visibilities/send/async_send.py | https://github.com/SKA-ScienceDataProcessor/integration-prototype/blob/8c8006de6ad71dcd44114b0338780738079c87d4/sip/science_pipeline_workflows/ingest_visibilities/send/async_send.py#L278-L304 | def main():
"""Main function for SPEAD sender module."""
# Check command line arguments.
if len(sys.argv) != 2:
raise RuntimeError('Usage: python3 async_send.py <json config>')
# Set up logging.
sip_logging.init_logger(show_thread=False)
# Load SPEAD configuration from JSON file.
#... | [
"def",
"main",
"(",
")",
":",
"# Check command line arguments.",
"if",
"len",
"(",
"sys",
".",
"argv",
")",
"!=",
"2",
":",
"raise",
"RuntimeError",
"(",
"'Usage: python3 async_send.py <json config>'",
")",
"# Set up logging.",
"sip_logging",
".",
"init_logger",
"("... | Main function for SPEAD sender module. | [
"Main",
"function",
"for",
"SPEAD",
"sender",
"module",
"."
] | python | train |
opencobra/memote | memote/support/basic.py | https://github.com/opencobra/memote/blob/276630fcd4449fb7b914186edfd38c239e7052df/memote/support/basic.py#L236-L242 | def is_constrained_reaction(model, rxn):
"""Return whether a reaction has fixed constraints."""
lower_bound, upper_bound = helpers.find_bounds(model)
if rxn.reversibility:
return rxn.lower_bound > lower_bound or rxn.upper_bound < upper_bound
else:
return rxn.lower_bound > 0 or rxn.upper_... | [
"def",
"is_constrained_reaction",
"(",
"model",
",",
"rxn",
")",
":",
"lower_bound",
",",
"upper_bound",
"=",
"helpers",
".",
"find_bounds",
"(",
"model",
")",
"if",
"rxn",
".",
"reversibility",
":",
"return",
"rxn",
".",
"lower_bound",
">",
"lower_bound",
"... | Return whether a reaction has fixed constraints. | [
"Return",
"whether",
"a",
"reaction",
"has",
"fixed",
"constraints",
"."
] | python | train |
PaloAltoNetworks/pancloud | pancloud/logging.py | https://github.com/PaloAltoNetworks/pancloud/blob/c51e4c8aca3c988c60f062291007534edcb55285/pancloud/logging.py#L199-L296 | def xpoll(self, query_id=None, sequence_no=None, params=None,
delete_query=True, **kwargs): # pragma: no cover
"""Retrieve individual logs iteratively in a non-greedy manner.
Generator function to return individual log entries from poll
API request.
Args:
par... | [
"def",
"xpoll",
"(",
"self",
",",
"query_id",
"=",
"None",
",",
"sequence_no",
"=",
"None",
",",
"params",
"=",
"None",
",",
"delete_query",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"# pragma: no cover",
"def",
"_delete",
"(",
"query_id",
",",
"... | Retrieve individual logs iteratively in a non-greedy manner.
Generator function to return individual log entries from poll
API request.
Args:
params (dict): Payload/request dictionary.
query_id (str): Specifies the ID of the query job.
sequence_no (int): Spe... | [
"Retrieve",
"individual",
"logs",
"iteratively",
"in",
"a",
"non",
"-",
"greedy",
"manner",
"."
] | python | train |
pypa/pipenv | pipenv/vendor/click/core.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/core.py#L444-L454 | def command_path(self):
"""The computed command path. This is used for the ``usage``
information on the help page. It's automatically created by
combining the info names of the chain of contexts to the root.
"""
rv = ''
if self.info_name is not None:
rv = se... | [
"def",
"command_path",
"(",
"self",
")",
":",
"rv",
"=",
"''",
"if",
"self",
".",
"info_name",
"is",
"not",
"None",
":",
"rv",
"=",
"self",
".",
"info_name",
"if",
"self",
".",
"parent",
"is",
"not",
"None",
":",
"rv",
"=",
"self",
".",
"parent",
... | The computed command path. This is used for the ``usage``
information on the help page. It's automatically created by
combining the info names of the chain of contexts to the root. | [
"The",
"computed",
"command",
"path",
".",
"This",
"is",
"used",
"for",
"the",
"usage",
"information",
"on",
"the",
"help",
"page",
".",
"It",
"s",
"automatically",
"created",
"by",
"combining",
"the",
"info",
"names",
"of",
"the",
"chain",
"of",
"contexts... | python | train |
kensho-technologies/graphql-compiler | graphql_compiler/compiler/expressions.py | https://github.com/kensho-technologies/graphql-compiler/blob/f6079c6d10f64932f6b3af309b79bcea2123ca8f/graphql_compiler/compiler/expressions.py#L918-L945 | def to_match(self):
"""Return a unicode object with the MATCH representation of this TernaryConditional."""
self.validate()
# For MATCH, an additional validation step is needed -- we currently do not support
# emitting MATCH code for TernaryConditional that contains another TernaryCondi... | [
"def",
"to_match",
"(",
"self",
")",
":",
"self",
".",
"validate",
"(",
")",
"# For MATCH, an additional validation step is needed -- we currently do not support",
"# emitting MATCH code for TernaryConditional that contains another TernaryConditional",
"# anywhere within the predicate expr... | Return a unicode object with the MATCH representation of this TernaryConditional. | [
"Return",
"a",
"unicode",
"object",
"with",
"the",
"MATCH",
"representation",
"of",
"this",
"TernaryConditional",
"."
] | python | train |
susam/ice | ice.py | https://github.com/susam/ice/blob/532e685c504ea96f9e42833594585159ac1d2068/ice.py#L172-L194 | def error(self, status=None):
"""Decorator to add a callback that generates error page.
The *status* parameter specifies the HTTP response status code
for which the decorated callback should be invoked. If the
*status* argument is not specified, then the decorated callable
is co... | [
"def",
"error",
"(",
"self",
",",
"status",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"callback",
")",
":",
"self",
".",
"_error_handlers",
"[",
"status",
"]",
"=",
"callback",
"return",
"callback",
"return",
"decorator"
] | Decorator to add a callback that generates error page.
The *status* parameter specifies the HTTP response status code
for which the decorated callback should be invoked. If the
*status* argument is not specified, then the decorated callable
is considered to be a fallback callback.
... | [
"Decorator",
"to",
"add",
"a",
"callback",
"that",
"generates",
"error",
"page",
"."
] | python | test |
KnightConan/sspdatatables | src/sspdatatables/utils/data_type_ensure.py | https://github.com/KnightConan/sspdatatables/blob/1179a11358734e5e472e5eee703e8d34fa49e9bf/src/sspdatatables/utils/data_type_ensure.py#L7-L27 | def ensure(data_type, check_value, default_value=None):
"""
function to ensure the given check value is in the given data type, if yes,
return the check value directly, otherwise return the default value
:param data_type: different data type: can be int, str, list, tuple etc,
must be python suppo... | [
"def",
"ensure",
"(",
"data_type",
",",
"check_value",
",",
"default_value",
"=",
"None",
")",
":",
"if",
"default_value",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"default_value",
",",
"data_type",
")",
":",
"raise",
"ValueError",
"(",
"\"defau... | function to ensure the given check value is in the given data type, if yes,
return the check value directly, otherwise return the default value
:param data_type: different data type: can be int, str, list, tuple etc,
must be python supportable data type or new defined data type
:param check_value: di... | [
"function",
"to",
"ensure",
"the",
"given",
"check",
"value",
"is",
"in",
"the",
"given",
"data",
"type",
"if",
"yes",
"return",
"the",
"check",
"value",
"directly",
"otherwise",
"return",
"the",
"default",
"value"
] | python | train |
hhatto/autopep8 | autopep8.py | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L1882-L1948 | def _shorten_line(tokens, source, indentation, indent_word,
aggressive=False, previous_line=''):
"""Separate line at OPERATOR.
The input is expected to be free of newlines except for inside multiline
strings and at the end.
Multiple candidates will be yielded.
"""
for (token... | [
"def",
"_shorten_line",
"(",
"tokens",
",",
"source",
",",
"indentation",
",",
"indent_word",
",",
"aggressive",
"=",
"False",
",",
"previous_line",
"=",
"''",
")",
":",
"for",
"(",
"token_type",
",",
"token_string",
",",
"start_offset",
",",
"end_offset",
"... | Separate line at OPERATOR.
The input is expected to be free of newlines except for inside multiline
strings and at the end.
Multiple candidates will be yielded. | [
"Separate",
"line",
"at",
"OPERATOR",
"."
] | python | train |
Kronuz/pyScss | scss/compiler.py | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/compiler.py#L427-L431 | def _at_dump_functions(self, calculator, rule, scope, block):
"""
Implements @dump_functions
"""
sys.stderr.write("%s\n" % repr(rule.namespace._functions)) | [
"def",
"_at_dump_functions",
"(",
"self",
",",
"calculator",
",",
"rule",
",",
"scope",
",",
"block",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"%s\\n\"",
"%",
"repr",
"(",
"rule",
".",
"namespace",
".",
"_functions",
")",
")"
] | Implements @dump_functions | [
"Implements"
] | python | train |
saltstack/salt | salt/modules/gpg.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/gpg.py#L1120-L1223 | def encrypt(user=None,
recipients=None,
text=None,
filename=None,
output=None,
sign=None,
use_passphrase=False,
gnupghome=None,
bare=False):
'''
Encrypt a message or file
user
Which user's keychain to ac... | [
"def",
"encrypt",
"(",
"user",
"=",
"None",
",",
"recipients",
"=",
"None",
",",
"text",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"output",
"=",
"None",
",",
"sign",
"=",
"None",
",",
"use_passphrase",
"=",
"False",
",",
"gnupghome",
"=",
"Non... | Encrypt a message or file
user
Which user's keychain to access, defaults to user Salt is running as.
Passing the user as ``salt`` will set the GnuPG home directory to the
``/etc/salt/gpgkeys``.
recipients
The fingerprints for those recipient whom the data is being encrypted for... | [
"Encrypt",
"a",
"message",
"or",
"file"
] | python | train |
Brightmd/TxPx | txpx/process.py | https://github.com/Brightmd/TxPx/blob/403c18b3006fc68842ec05b259e8611fe80763aa/txpx/process.py#L128-L153 | def background(cl, proto=EchoProcess, **kw):
"""
Use the reactor to run a process in the background.
Keep the pid around.
``proto'' may be any callable which returns an instance of ProcessProtocol
"""
if isinstance(cl, basestring):
cl = shlex.split(cl)
if not cl[0].startswith('/')... | [
"def",
"background",
"(",
"cl",
",",
"proto",
"=",
"EchoProcess",
",",
"*",
"*",
"kw",
")",
":",
"if",
"isinstance",
"(",
"cl",
",",
"basestring",
")",
":",
"cl",
"=",
"shlex",
".",
"split",
"(",
"cl",
")",
"if",
"not",
"cl",
"[",
"0",
"]",
"."... | Use the reactor to run a process in the background.
Keep the pid around.
``proto'' may be any callable which returns an instance of ProcessProtocol | [
"Use",
"the",
"reactor",
"to",
"run",
"a",
"process",
"in",
"the",
"background",
"."
] | python | train |
westurner/pyrpo | pyrpo/pyrpo.py | https://github.com/westurner/pyrpo/blob/2a910af055dc405b761571a52ef87842397ddadf/pyrpo/pyrpo.py#L1986-L2026 | def get_option_parser():
"""
Build an ``optparse.OptionParser`` for pyrpo commandline use
"""
import optparse
prs = optparse.OptionParser(
usage=(
"$0 pyrpo [-h] [-v] [-q] [-s .] "
"[-r <report>] [--thg]"))
prs.add_option('-s', '--scan',
dest=... | [
"def",
"get_option_parser",
"(",
")",
":",
"import",
"optparse",
"prs",
"=",
"optparse",
".",
"OptionParser",
"(",
"usage",
"=",
"(",
"\"$0 pyrpo [-h] [-v] [-q] [-s .] \"",
"\"[-r <report>] [--thg]\"",
")",
")",
"prs",
".",
"add_option",
"(",
"'-s'",
",",
"'--scan... | Build an ``optparse.OptionParser`` for pyrpo commandline use | [
"Build",
"an",
"optparse",
".",
"OptionParser",
"for",
"pyrpo",
"commandline",
"use"
] | python | train |
pmacosta/peng | peng/functions.py | https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/functions.py#L599-L629 | def peng_power(snum):
r"""
Return engineering suffix and its floating point equivalent of a number.
:py:func:`peng.peng` lists the correspondence between suffix and floating
point exponent.
:param snum: Number
:type snum: :ref:`EngineeringNotationNumber`
:rtype: named tuple in which the ... | [
"def",
"peng_power",
"(",
"snum",
")",
":",
"suffix",
"=",
"\" \"",
"if",
"snum",
"[",
"-",
"1",
"]",
".",
"isdigit",
"(",
")",
"else",
"snum",
"[",
"-",
"1",
"]",
"return",
"EngPower",
"(",
"suffix",
",",
"_SUFFIX_POWER_DICT",
"[",
"suffix",
"]",
... | r"""
Return engineering suffix and its floating point equivalent of a number.
:py:func:`peng.peng` lists the correspondence between suffix and floating
point exponent.
:param snum: Number
:type snum: :ref:`EngineeringNotationNumber`
:rtype: named tuple in which the first item is the engineer... | [
"r",
"Return",
"engineering",
"suffix",
"and",
"its",
"floating",
"point",
"equivalent",
"of",
"a",
"number",
"."
] | python | test |
google/grumpy | third_party/pythonparser/parser.py | https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pythonparser/parser.py#L1296-L1300 | def with_stmt__27(self, with_loc, items, colon_loc, body):
"""(2.7, 3.1-) with_stmt: 'with' with_item (',' with_item)* ':' suite"""
return ast.With(items=items, body=body,
keyword_loc=with_loc, colon_loc=colon_loc,
loc=with_loc.join(body[-1].loc)) | [
"def",
"with_stmt__27",
"(",
"self",
",",
"with_loc",
",",
"items",
",",
"colon_loc",
",",
"body",
")",
":",
"return",
"ast",
".",
"With",
"(",
"items",
"=",
"items",
",",
"body",
"=",
"body",
",",
"keyword_loc",
"=",
"with_loc",
",",
"colon_loc",
"=",... | (2.7, 3.1-) with_stmt: 'with' with_item (',' with_item)* ':' suite | [
"(",
"2",
".",
"7",
"3",
".",
"1",
"-",
")",
"with_stmt",
":",
"with",
"with_item",
"(",
"with_item",
")",
"*",
":",
"suite"
] | python | valid |
programa-stic/barf-project | barf/core/smt/smttranslator.py | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/smt/smttranslator.py#L575-L586 | def _translate_bisz(self, oprnd1, oprnd2, oprnd3):
"""Return a formula representation of a BISZ instruction.
"""
assert oprnd1.size and oprnd3.size
op1_var = self._translate_src_oprnd(oprnd1)
op3_var, op3_var_constrs = self._translate_dst_oprnd(oprnd3)
result = smtfunct... | [
"def",
"_translate_bisz",
"(",
"self",
",",
"oprnd1",
",",
"oprnd2",
",",
"oprnd3",
")",
":",
"assert",
"oprnd1",
".",
"size",
"and",
"oprnd3",
".",
"size",
"op1_var",
"=",
"self",
".",
"_translate_src_oprnd",
"(",
"oprnd1",
")",
"op3_var",
",",
"op3_var_c... | Return a formula representation of a BISZ instruction. | [
"Return",
"a",
"formula",
"representation",
"of",
"a",
"BISZ",
"instruction",
"."
] | python | train |
OpenHumans/open-humans-api | ohapi/public.py | https://github.com/OpenHumans/open-humans-api/blob/ca2a28cf5d55cfdae13dd222ba58c25565bdb86e/ohapi/public.py#L175-L183 | def get_members_by_source(base_url=BASE_URL_API):
"""
Function returns which members have joined each activity.
:param base_url: It is URL: `https://www.openhumans.org/api/public-data`.
"""
url = '{}members-by-source/'.format(base_url)
response = get_page(url)
return response | [
"def",
"get_members_by_source",
"(",
"base_url",
"=",
"BASE_URL_API",
")",
":",
"url",
"=",
"'{}members-by-source/'",
".",
"format",
"(",
"base_url",
")",
"response",
"=",
"get_page",
"(",
"url",
")",
"return",
"response"
] | Function returns which members have joined each activity.
:param base_url: It is URL: `https://www.openhumans.org/api/public-data`. | [
"Function",
"returns",
"which",
"members",
"have",
"joined",
"each",
"activity",
"."
] | python | train |
adamcharnock/django-hordak | hordak/utilities/currency.py | https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/utilities/currency.py#L246-L260 | def get_rate(self, currency, date):
"""Get the exchange rate for ``currency`` against ``_INTERNAL_CURRENCY``
If implementing your own backend, you should probably override :meth:`_get_rate()`
rather than this.
"""
if str(currency) == defaults.INTERNAL_CURRENCY:
retur... | [
"def",
"get_rate",
"(",
"self",
",",
"currency",
",",
"date",
")",
":",
"if",
"str",
"(",
"currency",
")",
"==",
"defaults",
".",
"INTERNAL_CURRENCY",
":",
"return",
"Decimal",
"(",
"1",
")",
"cached",
"=",
"cache",
".",
"get",
"(",
"_cache_key",
"(",
... | Get the exchange rate for ``currency`` against ``_INTERNAL_CURRENCY``
If implementing your own backend, you should probably override :meth:`_get_rate()`
rather than this. | [
"Get",
"the",
"exchange",
"rate",
"for",
"currency",
"against",
"_INTERNAL_CURRENCY"
] | python | train |
rwl/pylon | pylon/solver.py | https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/solver.py#L515-L539 | def _f(self, x, user_data=None):
""" Evaluates the objective function.
"""
p_gen = x[self._Pg.i1:self._Pg.iN + 1] # Active generation in p.u.
q_gen = x[self._Qg.i1:self._Qg.iN + 1] # Reactive generation in p.u.
# Polynomial cost of P and Q.
xx = r_[p_gen, q_gen] * self._... | [
"def",
"_f",
"(",
"self",
",",
"x",
",",
"user_data",
"=",
"None",
")",
":",
"p_gen",
"=",
"x",
"[",
"self",
".",
"_Pg",
".",
"i1",
":",
"self",
".",
"_Pg",
".",
"iN",
"+",
"1",
"]",
"# Active generation in p.u.",
"q_gen",
"=",
"x",
"[",
"self",
... | Evaluates the objective function. | [
"Evaluates",
"the",
"objective",
"function",
"."
] | python | train |
limix/chiscore | chiscore/_davies.py | https://github.com/limix/chiscore/blob/c3e774648b8166a5161df86e6bcad34af3cec95c/chiscore/_davies.py#L10-L34 | def davies_pvalue(q, w):
r"""Joint significance of statistics derived from chi2-squared distributions.
Parameters
----------
q : float
Test statistics.
w : array_like
Weights of the linear combination.
Returns
-------
float
Estimated p-value.
"""
q = as... | [
"def",
"davies_pvalue",
"(",
"q",
",",
"w",
")",
":",
"q",
"=",
"asarray",
"(",
"atleast_1d",
"(",
"q",
")",
",",
"float",
")",
"w",
"=",
"asarray",
"(",
"w",
",",
"float",
")",
"re",
"=",
"_pvalue_lambda",
"(",
"_lambda",
"(",
"w",
")",
",",
"... | r"""Joint significance of statistics derived from chi2-squared distributions.
Parameters
----------
q : float
Test statistics.
w : array_like
Weights of the linear combination.
Returns
-------
float
Estimated p-value. | [
"r",
"Joint",
"significance",
"of",
"statistics",
"derived",
"from",
"chi2",
"-",
"squared",
"distributions",
"."
] | python | train |
thombashi/SimpleSQLite | simplesqlite/core.py | https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L1502-L1522 | def close(self):
"""
Commit and close the connection.
.. seealso:: :py:meth:`sqlite3.Connection.close`
"""
if self.__delayed_connection_path and self.__connection is None:
self.__initialize_connection()
return
try:
self.check_connect... | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"__delayed_connection_path",
"and",
"self",
".",
"__connection",
"is",
"None",
":",
"self",
".",
"__initialize_connection",
"(",
")",
"return",
"try",
":",
"self",
".",
"check_connection",
"(",
")",
... | Commit and close the connection.
.. seealso:: :py:meth:`sqlite3.Connection.close` | [
"Commit",
"and",
"close",
"the",
"connection",
"."
] | python | train |
toumorokoshi/sprinter | sprinter/core/globals.py | https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/globals.py#L117-L135 | def _configure_shell(config):
""" Checks and queries values for the shell """
config.has_section('shell') or config.add_section('shell')
logger.info(
"What shells or environments would you like sprinter to work with?\n"
"(Sprinter will not try to inject into environments not specified here.)... | [
"def",
"_configure_shell",
"(",
"config",
")",
":",
"config",
".",
"has_section",
"(",
"'shell'",
")",
"or",
"config",
".",
"add_section",
"(",
"'shell'",
")",
"logger",
".",
"info",
"(",
"\"What shells or environments would you like sprinter to work with?\\n\"",
"\"(... | Checks and queries values for the shell | [
"Checks",
"and",
"queries",
"values",
"for",
"the",
"shell"
] | python | train |
nirum/descent | descent/objectives.py | https://github.com/nirum/descent/blob/074c8452f15a0da638668a4fe139fde06ccfae7f/descent/objectives.py#L209-L217 | def styblinski_tang(theta):
"""Styblinski-Tang function"""
x, y = theta
obj = 0.5 * (x ** 4 - 16 * x ** 2 + 5 * x + y ** 4 - 16 * y ** 2 + 5 * y)
grad = np.array([
2 * x ** 3 - 16 * x + 2.5,
2 * y ** 3 - 16 * y + 2.5,
])
return obj, grad | [
"def",
"styblinski_tang",
"(",
"theta",
")",
":",
"x",
",",
"y",
"=",
"theta",
"obj",
"=",
"0.5",
"*",
"(",
"x",
"**",
"4",
"-",
"16",
"*",
"x",
"**",
"2",
"+",
"5",
"*",
"x",
"+",
"y",
"**",
"4",
"-",
"16",
"*",
"y",
"**",
"2",
"+",
"5... | Styblinski-Tang function | [
"Styblinski",
"-",
"Tang",
"function"
] | python | valid |
jeremylow/pyshk | pyshk/models.py | https://github.com/jeremylow/pyshk/blob/3ab92f6706397cde7a18367266eba9e0f1ada868/pyshk/models.py#L522-L551 | def NewFromJSON(data):
"""
Create a new SharedFile instance from a JSON dict.
Args:
data (dict): JSON dictionary representing a SharedFile.
Returns:
A SharedFile instance.
"""
return SharedFile(
sharekey=data.get('sharekey', None),
... | [
"def",
"NewFromJSON",
"(",
"data",
")",
":",
"return",
"SharedFile",
"(",
"sharekey",
"=",
"data",
".",
"get",
"(",
"'sharekey'",
",",
"None",
")",
",",
"name",
"=",
"data",
".",
"get",
"(",
"'name'",
",",
"None",
")",
",",
"user",
"=",
"User",
"."... | Create a new SharedFile instance from a JSON dict.
Args:
data (dict): JSON dictionary representing a SharedFile.
Returns:
A SharedFile instance. | [
"Create",
"a",
"new",
"SharedFile",
"instance",
"from",
"a",
"JSON",
"dict",
"."
] | python | train |
streamlink/streamlink | src/streamlink_cli/main.py | https://github.com/streamlink/streamlink/blob/c8ed1daff14ac03195870238b9b900c1109dd5c1/src/streamlink_cli/main.py#L301-L333 | def output_stream(plugin, stream):
"""Open stream, create output and finally write the stream to output."""
global output
success_open = False
for i in range(args.retry_open):
try:
stream_fd, prebuffer = open_stream(stream)
success_open = True
break
e... | [
"def",
"output_stream",
"(",
"plugin",
",",
"stream",
")",
":",
"global",
"output",
"success_open",
"=",
"False",
"for",
"i",
"in",
"range",
"(",
"args",
".",
"retry_open",
")",
":",
"try",
":",
"stream_fd",
",",
"prebuffer",
"=",
"open_stream",
"(",
"st... | Open stream, create output and finally write the stream to output. | [
"Open",
"stream",
"create",
"output",
"and",
"finally",
"write",
"the",
"stream",
"to",
"output",
"."
] | python | test |
wummel/patool | patoolib/__init__.py | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/__init__.py#L725-L733 | def diff_archives(archive1, archive2, verbosity=0, interactive=True):
"""Print differences between two archives."""
util.check_existing_filename(archive1)
util.check_existing_filename(archive2)
if verbosity >= 0:
util.log_info("Comparing %s with %s ..." % (archive1, archive2))
res = _diff_ar... | [
"def",
"diff_archives",
"(",
"archive1",
",",
"archive2",
",",
"verbosity",
"=",
"0",
",",
"interactive",
"=",
"True",
")",
":",
"util",
".",
"check_existing_filename",
"(",
"archive1",
")",
"util",
".",
"check_existing_filename",
"(",
"archive2",
")",
"if",
... | Print differences between two archives. | [
"Print",
"differences",
"between",
"two",
"archives",
"."
] | python | train |
swharden/SWHLab | doc/oldcode/swhlab/core/common.py | https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/common.py#L845-L861 | def version_upload(fname,username="nibjb"):
"""Only scott should do this. Upload new version to site."""
print("popping up pasword window...")
password=TK_askPassword("FTP LOGIN","enter password for %s"%username)
if not password:
return
print("username:",username)
print("password:","*"*(... | [
"def",
"version_upload",
"(",
"fname",
",",
"username",
"=",
"\"nibjb\"",
")",
":",
"print",
"(",
"\"popping up pasword window...\"",
")",
"password",
"=",
"TK_askPassword",
"(",
"\"FTP LOGIN\"",
",",
"\"enter password for %s\"",
"%",
"username",
")",
"if",
"not",
... | Only scott should do this. Upload new version to site. | [
"Only",
"scott",
"should",
"do",
"this",
".",
"Upload",
"new",
"version",
"to",
"site",
"."
] | python | valid |
yyuu/botornado | boto/s3/bucket.py | https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/s3/bucket.py#L1015-L1063 | def configure_versioning(self, versioning, mfa_delete=False,
mfa_token=None, headers=None):
"""
Configure versioning for this bucket.
..note:: This feature is currently in beta.
:type versioning: bool
:param versioning: A bo... | [
"def",
"configure_versioning",
"(",
"self",
",",
"versioning",
",",
"mfa_delete",
"=",
"False",
",",
"mfa_token",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"if",
"versioning",
":",
"ver",
"=",
"'Enabled'",
"else",
":",
"ver",
"=",
"'Suspended'",
... | Configure versioning for this bucket.
..note:: This feature is currently in beta.
:type versioning: bool
:param versioning: A boolean indicating whether version is
enabled (True) or disabled (False).
:type mfa_delete: bool
:p... | [
"Configure",
"versioning",
"for",
"this",
"bucket",
".",
"..",
"note",
"::",
"This",
"feature",
"is",
"currently",
"in",
"beta",
".",
":",
"type",
"versioning",
":",
"bool",
":",
"param",
"versioning",
":",
"A",
"boolean",
"indicating",
"whether",
"version",... | python | train |
raiden-network/raiden | raiden/transfer/mediated_transfer/mediator.py | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L154-L171 | def is_send_transfer_almost_equal(
send_channel: NettingChannelState,
send: LockedTransferUnsignedState,
received: LockedTransferSignedState,
) -> bool:
""" True if both transfers are for the same mediated transfer. """
# The only thing that may change is the direction of the transfer
... | [
"def",
"is_send_transfer_almost_equal",
"(",
"send_channel",
":",
"NettingChannelState",
",",
"send",
":",
"LockedTransferUnsignedState",
",",
"received",
":",
"LockedTransferSignedState",
",",
")",
"->",
"bool",
":",
"# The only thing that may change is the direction of the tr... | True if both transfers are for the same mediated transfer. | [
"True",
"if",
"both",
"transfers",
"are",
"for",
"the",
"same",
"mediated",
"transfer",
"."
] | python | train |
foremast/gogo-utils | src/gogoutils/generator.py | https://github.com/foremast/gogo-utils/blob/3909c2d26e49baa8ad68e6be40977d4370d7c1ca/src/gogoutils/generator.py#L170-L175 | def jenkins(self):
"""Generate jenkins job details."""
job_name = self.format['jenkins_job_name'].format(**self.data)
job = {'name': job_name}
return job | [
"def",
"jenkins",
"(",
"self",
")",
":",
"job_name",
"=",
"self",
".",
"format",
"[",
"'jenkins_job_name'",
"]",
".",
"format",
"(",
"*",
"*",
"self",
".",
"data",
")",
"job",
"=",
"{",
"'name'",
":",
"job_name",
"}",
"return",
"job"
] | Generate jenkins job details. | [
"Generate",
"jenkins",
"job",
"details",
"."
] | python | train |
spyder-ide/spyder | spyder/plugins/editor/widgets/base.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/base.py#L1004-L1015 | def extend_selection_to_complete_lines(self):
"""Extend current selection to complete lines"""
cursor = self.textCursor()
start_pos, end_pos = cursor.selectionStart(), cursor.selectionEnd()
cursor.setPosition(start_pos)
cursor.setPosition(end_pos, QTextCursor.KeepAnchor)
... | [
"def",
"extend_selection_to_complete_lines",
"(",
"self",
")",
":",
"cursor",
"=",
"self",
".",
"textCursor",
"(",
")",
"start_pos",
",",
"end_pos",
"=",
"cursor",
".",
"selectionStart",
"(",
")",
",",
"cursor",
".",
"selectionEnd",
"(",
")",
"cursor",
".",
... | Extend current selection to complete lines | [
"Extend",
"current",
"selection",
"to",
"complete",
"lines"
] | python | train |
RRZE-HPC/kerncraft | kerncraft/models/ecm.py | https://github.com/RRZE-HPC/kerncraft/blob/c60baf8043e4da8d8d66da7575021c2f4c6c78af/kerncraft/models/ecm.py#L167-L173 | def analyze(self):
"""Run complete anaylysis and return results."""
self.calculate_cache_access()
self.calculate_cycles()
self.results['flops per iteration'] = sum(self.kernel._flops.values())
return self.results | [
"def",
"analyze",
"(",
"self",
")",
":",
"self",
".",
"calculate_cache_access",
"(",
")",
"self",
".",
"calculate_cycles",
"(",
")",
"self",
".",
"results",
"[",
"'flops per iteration'",
"]",
"=",
"sum",
"(",
"self",
".",
"kernel",
".",
"_flops",
".",
"v... | Run complete anaylysis and return results. | [
"Run",
"complete",
"anaylysis",
"and",
"return",
"results",
"."
] | python | test |
jtwhite79/pyemu | pyemu/pst/pst_handler.py | https://github.com/jtwhite79/pyemu/blob/c504d8e7a4097cec07655a6318d275739bd8148a/pyemu/pst/pst_handler.py#L2068-L2099 | def from_io_files(cls,tpl_files,in_files,ins_files,out_files,pst_filename=None):
""" create a Pst instance from model interface files. Assigns generic values for
parameter info. Tries to use INSCHEK to set somewhat meaningful observation
values
Parameters
----------
tpl... | [
"def",
"from_io_files",
"(",
"cls",
",",
"tpl_files",
",",
"in_files",
",",
"ins_files",
",",
"out_files",
",",
"pst_filename",
"=",
"None",
")",
":",
"from",
"pyemu",
"import",
"helpers",
"return",
"helpers",
".",
"pst_from_io_files",
"(",
"tpl_files",
"=",
... | create a Pst instance from model interface files. Assigns generic values for
parameter info. Tries to use INSCHEK to set somewhat meaningful observation
values
Parameters
----------
tpl_files : list
list of template file names
in_files : list
lis... | [
"create",
"a",
"Pst",
"instance",
"from",
"model",
"interface",
"files",
".",
"Assigns",
"generic",
"values",
"for",
"parameter",
"info",
".",
"Tries",
"to",
"use",
"INSCHEK",
"to",
"set",
"somewhat",
"meaningful",
"observation",
"values"
] | python | train |
saltstack/salt | salt/modules/virt.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L5290-L5298 | def _get_all_volumes_paths(conn):
'''
Extract the path and backing stores path of all volumes.
:param conn: libvirt connection to use
'''
volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l]
return {vol.path(): [path.text for path in ElementTree.fro... | [
"def",
"_get_all_volumes_paths",
"(",
"conn",
")",
":",
"volumes",
"=",
"[",
"vol",
"for",
"l",
"in",
"[",
"obj",
".",
"listAllVolumes",
"(",
")",
"for",
"obj",
"in",
"conn",
".",
"listAllStoragePools",
"(",
")",
"]",
"for",
"vol",
"in",
"l",
"]",
"r... | Extract the path and backing stores path of all volumes.
:param conn: libvirt connection to use | [
"Extract",
"the",
"path",
"and",
"backing",
"stores",
"path",
"of",
"all",
"volumes",
"."
] | python | train |
jelmer/python-fastimport | fastimport/commands.py | https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/commands.py#L270-L275 | def iter_files(self):
"""Iterate over files."""
# file_iter may be a callable or an iterator
if callable(self.file_iter):
return self.file_iter()
return iter(self.file_iter) | [
"def",
"iter_files",
"(",
"self",
")",
":",
"# file_iter may be a callable or an iterator",
"if",
"callable",
"(",
"self",
".",
"file_iter",
")",
":",
"return",
"self",
".",
"file_iter",
"(",
")",
"return",
"iter",
"(",
"self",
".",
"file_iter",
")"
] | Iterate over files. | [
"Iterate",
"over",
"files",
"."
] | python | train |
dw/mitogen | mitogen/core.py | https://github.com/dw/mitogen/blob/a7fdb55e1300a7e0a5e404b09eb730cf9a525da7/mitogen/core.py#L391-L397 | def listen(obj, name, func):
"""
Arrange for `func(*args, **kwargs)` to be invoked when the named signal is
fired by `obj`.
"""
signals = vars(obj).setdefault('_signals', {})
signals.setdefault(name, []).append(func) | [
"def",
"listen",
"(",
"obj",
",",
"name",
",",
"func",
")",
":",
"signals",
"=",
"vars",
"(",
"obj",
")",
".",
"setdefault",
"(",
"'_signals'",
",",
"{",
"}",
")",
"signals",
".",
"setdefault",
"(",
"name",
",",
"[",
"]",
")",
".",
"append",
"(",... | Arrange for `func(*args, **kwargs)` to be invoked when the named signal is
fired by `obj`. | [
"Arrange",
"for",
"func",
"(",
"*",
"args",
"**",
"kwargs",
")",
"to",
"be",
"invoked",
"when",
"the",
"named",
"signal",
"is",
"fired",
"by",
"obj",
"."
] | python | train |
vaexio/vaex | packages/vaex-core/vaex/dataframe.py | https://github.com/vaexio/vaex/blob/a45b672f8287afca2ada8e36b74b604b9b28dd85/packages/vaex-core/vaex/dataframe.py#L3077-L3102 | def add_virtual_columns_polar_velocities_to_cartesian(self, x='x', y='y', azimuth=None, vr='vr_polar', vazimuth='vphi_polar', vx_out='vx', vy_out='vy', propagate_uncertainties=False):
""" Convert cylindrical polar velocities to Cartesian.
:param x:
:param y:
:param azimuth: Optional exp... | [
"def",
"add_virtual_columns_polar_velocities_to_cartesian",
"(",
"self",
",",
"x",
"=",
"'x'",
",",
"y",
"=",
"'y'",
",",
"azimuth",
"=",
"None",
",",
"vr",
"=",
"'vr_polar'",
",",
"vazimuth",
"=",
"'vphi_polar'",
",",
"vx_out",
"=",
"'vx'",
",",
"vy_out",
... | Convert cylindrical polar velocities to Cartesian.
:param x:
:param y:
:param azimuth: Optional expression for the azimuth in degrees , may lead to a better performance when given.
:param vr:
:param vazimuth:
:param vx_out:
:param vy_out:
:param propagate... | [
"Convert",
"cylindrical",
"polar",
"velocities",
"to",
"Cartesian",
"."
] | python | test |
anjishnu/ask-alexa-pykit | ask/alexa_io.py | https://github.com/anjishnu/ask-alexa-pykit/blob/a47c278ca7a60532bbe1a9b789f6c37e609fea8b/ask/alexa_io.py#L103-L118 | def create_response(self, message=None, end_session=False, card_obj=None,
reprompt_message=None, is_ssml=None):
"""
message - text message to be spoken out by the Echo
end_session - flag to determine whether this interaction should end the session
card_obj = JSON ... | [
"def",
"create_response",
"(",
"self",
",",
"message",
"=",
"None",
",",
"end_session",
"=",
"False",
",",
"card_obj",
"=",
"None",
",",
"reprompt_message",
"=",
"None",
",",
"is_ssml",
"=",
"None",
")",
":",
"response",
"=",
"dict",
"(",
"self",
".",
... | message - text message to be spoken out by the Echo
end_session - flag to determine whether this interaction should end the session
card_obj = JSON card object to substitute the 'card' field in the raw_response | [
"message",
"-",
"text",
"message",
"to",
"be",
"spoken",
"out",
"by",
"the",
"Echo",
"end_session",
"-",
"flag",
"to",
"determine",
"whether",
"this",
"interaction",
"should",
"end",
"the",
"session",
"card_obj",
"=",
"JSON",
"card",
"object",
"to",
"substit... | python | train |
TeamHG-Memex/eli5 | eli5/sklearn/explain_weights.py | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/sklearn/explain_weights.py#L396-L467 | def explain_linear_regressor_weights(reg,
vec=None,
top=_TOP,
target_names=None,
targets=None,
feature_names=None,
... | [
"def",
"explain_linear_regressor_weights",
"(",
"reg",
",",
"vec",
"=",
"None",
",",
"top",
"=",
"_TOP",
",",
"target_names",
"=",
"None",
",",
"targets",
"=",
"None",
",",
"feature_names",
"=",
"None",
",",
"coef_scale",
"=",
"None",
",",
"feature_re",
"=... | Return an explanation of a linear regressor weights.
See :func:`eli5.explain_weights` for description of
``top``, ``target_names``, ``targets``, ``feature_names``,
``feature_re`` and ``feature_filter`` parameters.
``vec`` is a vectorizer instance used to transform
raw features to the input of the ... | [
"Return",
"an",
"explanation",
"of",
"a",
"linear",
"regressor",
"weights",
"."
] | python | train |
shidenggui/easytrader | easytrader/helpers.py | https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/helpers.py#L32-L53 | def get_stock_type(stock_code):
"""判断股票ID对应的证券市场
匹配规则
['50', '51', '60', '90', '110'] 为 sh
['00', '13', '18', '15', '16', '18', '20', '30', '39', '115'] 为 sz
['5', '6', '9'] 开头的为 sh, 其余为 sz
:param stock_code:股票ID, 若以 'sz', 'sh' 开头直接返回对应类型,否则使用内置规则判断
:return 'sh' or 'sz'"""
stock_code = s... | [
"def",
"get_stock_type",
"(",
"stock_code",
")",
":",
"stock_code",
"=",
"str",
"(",
"stock_code",
")",
"if",
"stock_code",
".",
"startswith",
"(",
"(",
"\"sh\"",
",",
"\"sz\"",
")",
")",
":",
"return",
"stock_code",
"[",
":",
"2",
"]",
"if",
"stock_code... | 判断股票ID对应的证券市场
匹配规则
['50', '51', '60', '90', '110'] 为 sh
['00', '13', '18', '15', '16', '18', '20', '30', '39', '115'] 为 sz
['5', '6', '9'] 开头的为 sh, 其余为 sz
:param stock_code:股票ID, 若以 'sz', 'sh' 开头直接返回对应类型,否则使用内置规则判断
:return 'sh' or 'sz | [
"判断股票ID对应的证券市场",
"匹配规则",
"[",
"50",
"51",
"60",
"90",
"110",
"]",
"为",
"sh",
"[",
"00",
"13",
"18",
"15",
"16",
"18",
"20",
"30",
"39",
"115",
"]",
"为",
"sz",
"[",
"5",
"6",
"9",
"]",
"开头的为",
"sh,",
"其余为",
"sz",
":",
"param",
"stock_code",
":... | python | train |
quiltdata/quilt | compiler/quilt/tools/store.py | https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/tools/store.py#L327-L333 | def team_path(self, team=None):
"""
Returns the path to directory with the team's users' package repositories.
"""
if team is None:
team = DEFAULT_TEAM
return os.path.join(self._path, self.PKG_DIR, team) | [
"def",
"team_path",
"(",
"self",
",",
"team",
"=",
"None",
")",
":",
"if",
"team",
"is",
"None",
":",
"team",
"=",
"DEFAULT_TEAM",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_path",
",",
"self",
".",
"PKG_DIR",
",",
"team",
")"
] | Returns the path to directory with the team's users' package repositories. | [
"Returns",
"the",
"path",
"to",
"directory",
"with",
"the",
"team",
"s",
"users",
"package",
"repositories",
"."
] | python | train |
ratt-ru/PyMORESANE | pymoresane/main.py | https://github.com/ratt-ru/PyMORESANE/blob/b024591ad0bbb69320d08841f28a2c27f62ae1af/pymoresane/main.py#L601-L616 | def restore(self):
"""
This method constructs the restoring beam and then adds the convolution to the residual.
"""
clean_beam, beam_params = beam_fit(self.psf_data, self.cdelt1, self.cdelt2)
if np.all(np.array(self.psf_data_shape)==2*np.array(self.dirty_data_shape)):
... | [
"def",
"restore",
"(",
"self",
")",
":",
"clean_beam",
",",
"beam_params",
"=",
"beam_fit",
"(",
"self",
".",
"psf_data",
",",
"self",
".",
"cdelt1",
",",
"self",
".",
"cdelt2",
")",
"if",
"np",
".",
"all",
"(",
"np",
".",
"array",
"(",
"self",
"."... | This method constructs the restoring beam and then adds the convolution to the residual. | [
"This",
"method",
"constructs",
"the",
"restoring",
"beam",
"and",
"then",
"adds",
"the",
"convolution",
"to",
"the",
"residual",
"."
] | python | train |
tornadoweb/tornado | tornado/iostream.py | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/iostream.py#L349-L384 | def read_until_regex(self, regex: bytes, max_bytes: int = None) -> Awaitable[bytes]:
"""Asynchronously read until we have matched the given regex.
The result includes the data that matches the regex and anything
that came before it.
If ``max_bytes`` is not None, the connection will be ... | [
"def",
"read_until_regex",
"(",
"self",
",",
"regex",
":",
"bytes",
",",
"max_bytes",
":",
"int",
"=",
"None",
")",
"->",
"Awaitable",
"[",
"bytes",
"]",
":",
"future",
"=",
"self",
".",
"_start_read",
"(",
")",
"self",
".",
"_read_regex",
"=",
"re",
... | Asynchronously read until we have matched the given regex.
The result includes the data that matches the regex and anything
that came before it.
If ``max_bytes`` is not None, the connection will be closed
if more than ``max_bytes`` bytes have been read and the regex is
not sati... | [
"Asynchronously",
"read",
"until",
"we",
"have",
"matched",
"the",
"given",
"regex",
"."
] | python | train |
spacetelescope/drizzlepac | drizzlepac/imageObject.py | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imageObject.py#L734-L779 | def buildIVMmask(self ,chip, dqarr, scale):
""" Builds a weight mask from an input DQ array and either an IVM array
provided by the user or a self-generated IVM array derived from the
flat-field reference file associated with the input image.
"""
sci_chip = self._image[self.scien... | [
"def",
"buildIVMmask",
"(",
"self",
",",
"chip",
",",
"dqarr",
",",
"scale",
")",
":",
"sci_chip",
"=",
"self",
".",
"_image",
"[",
"self",
".",
"scienceExt",
",",
"chip",
"]",
"ivmname",
"=",
"self",
".",
"outputNames",
"[",
"'ivmFile'",
"]",
"if",
... | Builds a weight mask from an input DQ array and either an IVM array
provided by the user or a self-generated IVM array derived from the
flat-field reference file associated with the input image. | [
"Builds",
"a",
"weight",
"mask",
"from",
"an",
"input",
"DQ",
"array",
"and",
"either",
"an",
"IVM",
"array",
"provided",
"by",
"the",
"user",
"or",
"a",
"self",
"-",
"generated",
"IVM",
"array",
"derived",
"from",
"the",
"flat",
"-",
"field",
"reference... | python | train |
log2timeline/dfvfs | dfvfs/mount/manager.py | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/mount/manager.py#L61-L74 | def RegisterMountPoint(cls, mount_point, path_spec):
"""Registers a path specification mount point.
Args:
mount_point (str): mount point identifier.
path_spec (PathSpec): path specification of the mount point.
Raises:
KeyError: if the corresponding mount point is already set.
"""
... | [
"def",
"RegisterMountPoint",
"(",
"cls",
",",
"mount_point",
",",
"path_spec",
")",
":",
"if",
"mount_point",
"in",
"cls",
".",
"_mount_points",
":",
"raise",
"KeyError",
"(",
"'Mount point: {0:s} already set.'",
".",
"format",
"(",
"mount_point",
")",
")",
"cls... | Registers a path specification mount point.
Args:
mount_point (str): mount point identifier.
path_spec (PathSpec): path specification of the mount point.
Raises:
KeyError: if the corresponding mount point is already set. | [
"Registers",
"a",
"path",
"specification",
"mount",
"point",
"."
] | python | train |
thebigmunch/google-music-utils | src/google_music_utils/misc.py | https://github.com/thebigmunch/google-music-utils/blob/2e8873defe7d5aab7321b9d5ec8a80d72687578e/src/google_music_utils/misc.py#L54-L138 | def template_to_filepath(template, metadata, template_patterns=None):
"""Create directory structure and file name based on metadata template.
Note:
A template meant to be a base directory for suggested
names should have a trailing slash or backslash.
Parameters:
template (str or ~os.PathLike): A filepath whic... | [
"def",
"template_to_filepath",
"(",
"template",
",",
"metadata",
",",
"template_patterns",
"=",
"None",
")",
":",
"path",
"=",
"Path",
"(",
"template",
")",
"if",
"template_patterns",
"is",
"None",
":",
"template_patterns",
"=",
"TEMPLATE_PATTERNS",
"suggested_fil... | Create directory structure and file name based on metadata template.
Note:
A template meant to be a base directory for suggested
names should have a trailing slash or backslash.
Parameters:
template (str or ~os.PathLike): A filepath which can include template patterns as defined by :param template_patterns:.
... | [
"Create",
"directory",
"structure",
"and",
"file",
"name",
"based",
"on",
"metadata",
"template",
"."
] | python | train |
ktbyers/netmiko | netmiko/base_connection.py | https://github.com/ktbyers/netmiko/blob/54e6116c0b4664de2123081937e0a9a27bdfdfea/netmiko/base_connection.py#L935-L948 | def _build_ssh_client(self):
"""Prepare for Paramiko SSH connection."""
# Create instance of SSHClient object
remote_conn_pre = paramiko.SSHClient()
# Load host_keys for better SSH security
if self.system_host_keys:
remote_conn_pre.load_system_host_keys()
if ... | [
"def",
"_build_ssh_client",
"(",
"self",
")",
":",
"# Create instance of SSHClient object",
"remote_conn_pre",
"=",
"paramiko",
".",
"SSHClient",
"(",
")",
"# Load host_keys for better SSH security",
"if",
"self",
".",
"system_host_keys",
":",
"remote_conn_pre",
".",
"loa... | Prepare for Paramiko SSH connection. | [
"Prepare",
"for",
"Paramiko",
"SSH",
"connection",
"."
] | python | train |
sdispater/pendulum | pendulum/date.py | https://github.com/sdispater/pendulum/blob/94d28b0d3cb524ae02361bd1ed7ea03e2e655e4e/pendulum/date.py#L244-L262 | def subtract(self, years=0, months=0, weeks=0, days=0):
"""
Remove duration from the instance.
:param years: The number of years
:type years: int
:param months: The number of months
:type months: int
:param weeks: The number of weeks
:type weeks: int
... | [
"def",
"subtract",
"(",
"self",
",",
"years",
"=",
"0",
",",
"months",
"=",
"0",
",",
"weeks",
"=",
"0",
",",
"days",
"=",
"0",
")",
":",
"return",
"self",
".",
"add",
"(",
"years",
"=",
"-",
"years",
",",
"months",
"=",
"-",
"months",
",",
"... | Remove duration from the instance.
:param years: The number of years
:type years: int
:param months: The number of months
:type months: int
:param weeks: The number of weeks
:type weeks: int
:param days: The number of days
:type days: int
:rty... | [
"Remove",
"duration",
"from",
"the",
"instance",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.