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 |
|---|---|---|---|---|---|---|---|---|
projectatomic/atomic-reactor | atomic_reactor/core.py | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/core.py#L491-L520 | def get_image_info_by_image_name(self, image, exact_tag=True):
"""
using `docker images`, provide information about an image
:param image: ImageName, name of image
:param exact_tag: bool, if false then return info for all images of the
given name regardless wha... | [
"def",
"get_image_info_by_image_name",
"(",
"self",
",",
"image",
",",
"exact_tag",
"=",
"True",
")",
":",
"logger",
".",
"info",
"(",
"\"getting info about provided image specified by name '%s'\"",
",",
"image",
")",
"logger",
".",
"debug",
"(",
"\"image_name = '%s'\... | using `docker images`, provide information about an image
:param image: ImageName, name of image
:param exact_tag: bool, if false then return info for all images of the
given name regardless what their tag is
:return: list of dicts | [
"using",
"docker",
"images",
"provide",
"information",
"about",
"an",
"image"
] | python | train |
RudolfCardinal/pythonlib | cardinal_pythonlib/convert.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/convert.py#L90-L98 | def convert_attrs_to_bool(obj: Any,
attrs: Iterable[str],
default: bool = None) -> None:
"""
Applies :func:`convert_to_bool` to the specified attributes of an object,
modifying it in place.
"""
for a in attrs:
setattr(obj, a, convert_to_boo... | [
"def",
"convert_attrs_to_bool",
"(",
"obj",
":",
"Any",
",",
"attrs",
":",
"Iterable",
"[",
"str",
"]",
",",
"default",
":",
"bool",
"=",
"None",
")",
"->",
"None",
":",
"for",
"a",
"in",
"attrs",
":",
"setattr",
"(",
"obj",
",",
"a",
",",
"convert... | Applies :func:`convert_to_bool` to the specified attributes of an object,
modifying it in place. | [
"Applies",
":",
"func",
":",
"convert_to_bool",
"to",
"the",
"specified",
"attributes",
"of",
"an",
"object",
"modifying",
"it",
"in",
"place",
"."
] | python | train |
gwastro/pycbc | pycbc/filter/matchedfilter.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/filter/matchedfilter.py#L1101-L1120 | def sigma(htilde, psd = None, low_frequency_cutoff=None,
high_frequency_cutoff=None):
""" Return the sigma of the waveform. See sigmasq for more details.
Parameters
----------
htilde : TimeSeries or FrequencySeries
The input vector containing a waveform.
psd : {None, FrequencySeries... | [
"def",
"sigma",
"(",
"htilde",
",",
"psd",
"=",
"None",
",",
"low_frequency_cutoff",
"=",
"None",
",",
"high_frequency_cutoff",
"=",
"None",
")",
":",
"return",
"sqrt",
"(",
"sigmasq",
"(",
"htilde",
",",
"psd",
",",
"low_frequency_cutoff",
",",
"high_freque... | Return the sigma of the waveform. See sigmasq for more details.
Parameters
----------
htilde : TimeSeries or FrequencySeries
The input vector containing a waveform.
psd : {None, FrequencySeries}, optional
The psd used to weight the accumulated power.
low_frequency_cutoff : {None, fl... | [
"Return",
"the",
"sigma",
"of",
"the",
"waveform",
".",
"See",
"sigmasq",
"for",
"more",
"details",
"."
] | python | train |
sirfoga/pyhal | hal/streams/pretty_table.py | https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/streams/pretty_table.py#L111-L122 | def get_blank_row(self, filler="-", splitter="+"):
"""Gets blank row
:param filler: Fill empty columns with this char
:param splitter: Separate columns with this char
:return: Pretty formatted blank row (with no meaningful data in it)
"""
return self.get_pretty_row(
... | [
"def",
"get_blank_row",
"(",
"self",
",",
"filler",
"=",
"\"-\"",
",",
"splitter",
"=",
"\"+\"",
")",
":",
"return",
"self",
".",
"get_pretty_row",
"(",
"[",
"\"\"",
"for",
"_",
"in",
"self",
".",
"widths",
"]",
",",
"# blanks",
"filler",
",",
"# fill ... | Gets blank row
:param filler: Fill empty columns with this char
:param splitter: Separate columns with this char
:return: Pretty formatted blank row (with no meaningful data in it) | [
"Gets",
"blank",
"row"
] | python | train |
astropy/photutils | photutils/psf/epsf.py | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/psf/epsf.py#L862-L916 | def _interpolate_missing_data(data, mask, method='cubic'):
"""
Interpolate missing data as identified by the ``mask`` keyword.
Parameters
----------
data : 2D `~numpy.ndarray`
An array containing the 2D image.
mask : 2D bool `~numpy.ndarray`
A 2D booleen mask array with the sam... | [
"def",
"_interpolate_missing_data",
"(",
"data",
",",
"mask",
",",
"method",
"=",
"'cubic'",
")",
":",
"from",
"scipy",
"import",
"interpolate",
"data_interp",
"=",
"np",
".",
"array",
"(",
"data",
",",
"copy",
"=",
"True",
")",
"if",
"len",
"(",
"data_i... | Interpolate missing data as identified by the ``mask`` keyword.
Parameters
----------
data : 2D `~numpy.ndarray`
An array containing the 2D image.
mask : 2D bool `~numpy.ndarray`
A 2D booleen mask array with the same shape as the input
``data``, where a `True` value indicates t... | [
"Interpolate",
"missing",
"data",
"as",
"identified",
"by",
"the",
"mask",
"keyword",
"."
] | python | train |
BerkeleyAutomation/autolab_core | autolab_core/points.py | https://github.com/BerkeleyAutomation/autolab_core/blob/8f3813f6401972868cc5e3981ba1b4382d4418d5/autolab_core/points.py#L1201-L1212 | def remove_zero_points(self):
"""Remove all elements where the norms and points are zero.
Note
----
This returns nothing and updates the NormalCloud in-place.
"""
points_of_interest = np.where((np.linalg.norm(self.point_cloud.data, axis=0) != 0.0) &
... | [
"def",
"remove_zero_points",
"(",
"self",
")",
":",
"points_of_interest",
"=",
"np",
".",
"where",
"(",
"(",
"np",
".",
"linalg",
".",
"norm",
"(",
"self",
".",
"point_cloud",
".",
"data",
",",
"axis",
"=",
"0",
")",
"!=",
"0.0",
")",
"&",
"(",
"np... | Remove all elements where the norms and points are zero.
Note
----
This returns nothing and updates the NormalCloud in-place. | [
"Remove",
"all",
"elements",
"where",
"the",
"norms",
"and",
"points",
"are",
"zero",
"."
] | python | train |
why2pac/dp-tornado | dp_tornado/helper/serialization/json.py | https://github.com/why2pac/dp-tornado/blob/a5948f5693f6ee2d9bab31f611fedc074e1caa96/dp_tornado/helper/serialization/json.py#L17-L23 | def parse(self, text, encoding='utf8', raise_exception=False):
"""Alias of helper.string.serialization.json.parse"""
return self.helper.string.serialization.json.parse(
text=text,
encoding=encoding,
raise_exception=raise_exception) | [
"def",
"parse",
"(",
"self",
",",
"text",
",",
"encoding",
"=",
"'utf8'",
",",
"raise_exception",
"=",
"False",
")",
":",
"return",
"self",
".",
"helper",
".",
"string",
".",
"serialization",
".",
"json",
".",
"parse",
"(",
"text",
"=",
"text",
",",
... | Alias of helper.string.serialization.json.parse | [
"Alias",
"of",
"helper",
".",
"string",
".",
"serialization",
".",
"json",
".",
"parse"
] | python | train |
RJT1990/pyflux | pyflux/var/var.py | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/var/var.py#L409-L433 | def neg_loglik(self,beta):
""" Creates the negative log-likelihood of the model
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
Returns
----------
The negative logliklihood of the model
""" ... | [
"def",
"neg_loglik",
"(",
"self",
",",
"beta",
")",
":",
"mu",
",",
"Y",
"=",
"self",
".",
"_model",
"(",
"beta",
")",
"if",
"self",
".",
"use_ols_covariance",
"is",
"False",
":",
"cm",
"=",
"self",
".",
"custom_covariance",
"(",
"beta",
")",
"else",... | Creates the negative log-likelihood of the model
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
Returns
----------
The negative logliklihood of the model | [
"Creates",
"the",
"negative",
"log",
"-",
"likelihood",
"of",
"the",
"model"
] | python | train |
theislab/scanpy | scanpy/preprocessing/_recipes.py | https://github.com/theislab/scanpy/blob/9e4e5ee02e04cf618872d9b098e24f0542e8b227/scanpy/preprocessing/_recipes.py#L62-L119 | def recipe_zheng17(adata, n_top_genes=1000, log=True, plot=False, copy=False):
"""Normalization and filtering as of [Zheng17]_.
Reproduces the preprocessing of [Zheng17]_ - the Cell Ranger R Kit of 10x
Genomics.
Expects non-logarithmized data. If using logarithmized data, pass `log=False`.
The re... | [
"def",
"recipe_zheng17",
"(",
"adata",
",",
"n_top_genes",
"=",
"1000",
",",
"log",
"=",
"True",
",",
"plot",
"=",
"False",
",",
"copy",
"=",
"False",
")",
":",
"logg",
".",
"info",
"(",
"'running recipe zheng17'",
",",
"reset",
"=",
"True",
")",
"if",... | Normalization and filtering as of [Zheng17]_.
Reproduces the preprocessing of [Zheng17]_ - the Cell Ranger R Kit of 10x
Genomics.
Expects non-logarithmized data. If using logarithmized data, pass `log=False`.
The recipe runs the following steps
.. code:: python
sc.pp.filter_genes(adata,... | [
"Normalization",
"and",
"filtering",
"as",
"of",
"[",
"Zheng17",
"]",
"_",
"."
] | python | train |
erdc/RAPIDpy | RAPIDpy/inflow/CreateInflowFileFromGriddedRunoff.py | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/inflow/CreateInflowFileFromGriddedRunoff.py#L52-L86 | def read_in_weight_table(self, in_weight_table):
"""
Read in weight table
"""
print("Reading the weight table...")
with open_csv(in_weight_table, "r") as csvfile:
reader = csv.reader(csvfile)
header_row = next(reader)
# check number of ... | [
"def",
"read_in_weight_table",
"(",
"self",
",",
"in_weight_table",
")",
":",
"print",
"(",
"\"Reading the weight table...\"",
")",
"with",
"open_csv",
"(",
"in_weight_table",
",",
"\"r\"",
")",
"as",
"csvfile",
":",
"reader",
"=",
"csv",
".",
"reader",
"(",
"... | Read in weight table | [
"Read",
"in",
"weight",
"table"
] | python | train |
inasafe/inasafe | safe/plugin.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/plugin.py#L170-L185 | def _create_dock_toggle_action(self):
"""Create action for plugin dockable window (show/hide)."""
# pylint: disable=W0201
icon = resources_path('img', 'icons', 'icon.svg')
self.action_dock = QAction(
QIcon(icon),
self.tr('Toggle InaSAFE Dock'), self.iface.mainWind... | [
"def",
"_create_dock_toggle_action",
"(",
"self",
")",
":",
"# pylint: disable=W0201",
"icon",
"=",
"resources_path",
"(",
"'img'",
",",
"'icons'",
",",
"'icon.svg'",
")",
"self",
".",
"action_dock",
"=",
"QAction",
"(",
"QIcon",
"(",
"icon",
")",
",",
"self",... | Create action for plugin dockable window (show/hide). | [
"Create",
"action",
"for",
"plugin",
"dockable",
"window",
"(",
"show",
"/",
"hide",
")",
"."
] | python | train |
DataDog/integrations-core | sqlserver/datadog_checks/sqlserver/sqlserver.py | https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/sqlserver/datadog_checks/sqlserver/sqlserver.py#L597-L611 | def close_db_connections(self, instance, db_key, db_name=None):
"""
We close the db connections explicitly b/c when we don't they keep
locks on the db. This presents as issues such as the SQL Server Agent
being unable to stop.
"""
conn_key = self._conn_key(instance, db_ke... | [
"def",
"close_db_connections",
"(",
"self",
",",
"instance",
",",
"db_key",
",",
"db_name",
"=",
"None",
")",
":",
"conn_key",
"=",
"self",
".",
"_conn_key",
"(",
"instance",
",",
"db_key",
",",
"db_name",
")",
"if",
"conn_key",
"not",
"in",
"self",
".",... | We close the db connections explicitly b/c when we don't they keep
locks on the db. This presents as issues such as the SQL Server Agent
being unable to stop. | [
"We",
"close",
"the",
"db",
"connections",
"explicitly",
"b",
"/",
"c",
"when",
"we",
"don",
"t",
"they",
"keep",
"locks",
"on",
"the",
"db",
".",
"This",
"presents",
"as",
"issues",
"such",
"as",
"the",
"SQL",
"Server",
"Agent",
"being",
"unable",
"to... | python | train |
dpkp/kafka-python | kafka/consumer/fetcher.py | https://github.com/dpkp/kafka-python/blob/f6a8a38937688ea2cc5dc13d3d1039493be5c9b5/kafka/consumer/fetcher.py#L218-L245 | def _reset_offset(self, partition):
"""Reset offsets for the given partition using the offset reset strategy.
Arguments:
partition (TopicPartition): the partition that needs reset offset
Raises:
NoOffsetForPartitionError: if no offset reset strategy is defined
"... | [
"def",
"_reset_offset",
"(",
"self",
",",
"partition",
")",
":",
"timestamp",
"=",
"self",
".",
"_subscriptions",
".",
"assignment",
"[",
"partition",
"]",
".",
"reset_strategy",
"if",
"timestamp",
"is",
"OffsetResetStrategy",
".",
"EARLIEST",
":",
"strategy",
... | Reset offsets for the given partition using the offset reset strategy.
Arguments:
partition (TopicPartition): the partition that needs reset offset
Raises:
NoOffsetForPartitionError: if no offset reset strategy is defined | [
"Reset",
"offsets",
"for",
"the",
"given",
"partition",
"using",
"the",
"offset",
"reset",
"strategy",
"."
] | python | train |
botstory/botstory | botstory/ast/story_context/reducers.py | https://github.com/botstory/botstory/blob/9c5b2fc7f7a14dbd467d70f60d5ba855ef89dac3/botstory/ast/story_context/reducers.py#L161-L194 | def scope_out(ctx):
"""
drop last stack item if:
- we have reach the end of stack
- and don't wait any input
:param ctx:
:return:
"""
logger.debug('# scope_out')
logger.debug(ctx)
# we reach the end of story line
# so we could collapse previous scope and related stack item... | [
"def",
"scope_out",
"(",
"ctx",
")",
":",
"logger",
".",
"debug",
"(",
"'# scope_out'",
")",
"logger",
".",
"debug",
"(",
"ctx",
")",
"# we reach the end of story line",
"# so we could collapse previous scope and related stack item",
"if",
"ctx",
".",
"is_tail_of_story"... | drop last stack item if:
- we have reach the end of stack
- and don't wait any input
:param ctx:
:return: | [
"drop",
"last",
"stack",
"item",
"if",
":",
"-",
"we",
"have",
"reach",
"the",
"end",
"of",
"stack",
"-",
"and",
"don",
"t",
"wait",
"any",
"input"
] | python | train |
mkouhei/tonicdnscli | src/tonicdnscli/command.py | https://github.com/mkouhei/tonicdnscli/blob/df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c/src/tonicdnscli/command.py#L121-L136 | def show(args):
"""Convert and print JSON.
Argument:
args: arguments object
"""
domain = check_infile(args.infile)
action = True
try:
print(json.dumps(set_json(domain, action, filename=args.infile),
sort_keys=True, indent=2))
except UnicodeDecodeErr... | [
"def",
"show",
"(",
"args",
")",
":",
"domain",
"=",
"check_infile",
"(",
"args",
".",
"infile",
")",
"action",
"=",
"True",
"try",
":",
"print",
"(",
"json",
".",
"dumps",
"(",
"set_json",
"(",
"domain",
",",
"action",
",",
"filename",
"=",
"args",
... | Convert and print JSON.
Argument:
args: arguments object | [
"Convert",
"and",
"print",
"JSON",
"."
] | python | train |
neuropsychology/NeuroKit.py | examples/UnderDev/eeg/eeg_microstates.py | https://github.com/neuropsychology/NeuroKit.py/blob/c9589348fbbde0fa7e986048c48f38e6b488adfe/examples/UnderDev/eeg/eeg_microstates.py#L489-L547 | def eeg_microstates_plot(method, path="", extension=".png", show_sensors_position=False, show_sensors_name=False, plot=True, save=True, dpi=150, contours=0, colorbar=False, separate=False):
"""
Plot the microstates.
"""
# Generate and store figures
figures = []
names = []
# Check if microst... | [
"def",
"eeg_microstates_plot",
"(",
"method",
",",
"path",
"=",
"\"\"",
",",
"extension",
"=",
"\".png\"",
",",
"show_sensors_position",
"=",
"False",
",",
"show_sensors_name",
"=",
"False",
",",
"plot",
"=",
"True",
",",
"save",
"=",
"True",
",",
"dpi",
"... | Plot the microstates. | [
"Plot",
"the",
"microstates",
"."
] | python | train |
SetBased/py-stratum | pystratum/Constants.py | https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/Constants.py#L131-L142 | def _read_configuration_file(self, config_filename):
"""
Reads parameters from the configuration file.
:param str config_filename: The name of the configuration file.
"""
config = configparser.ConfigParser()
config.read(config_filename)
self._constants_filename ... | [
"def",
"_read_configuration_file",
"(",
"self",
",",
"config_filename",
")",
":",
"config",
"=",
"configparser",
".",
"ConfigParser",
"(",
")",
"config",
".",
"read",
"(",
"config_filename",
")",
"self",
".",
"_constants_filename",
"=",
"config",
".",
"get",
"... | Reads parameters from the configuration file.
:param str config_filename: The name of the configuration file. | [
"Reads",
"parameters",
"from",
"the",
"configuration",
"file",
"."
] | python | train |
e7dal/bubble3 | behave4cmd0/textutil.py | https://github.com/e7dal/bubble3/blob/59c735281a95b44f6263a25f4d6ce24fca520082/behave4cmd0/textutil.py#L174-L188 | def text_normalize(text):
"""
Whitespace normalization:
- Strip empty lines
- Strip leading whitespace in a line
- Strip trailing whitespace in a line
- Normalize line endings
"""
# if not isinstance(text, str):
if isinstance(text, bytes):
# -- MAYBE: command.ouput ... | [
"def",
"text_normalize",
"(",
"text",
")",
":",
"# if not isinstance(text, str):",
"if",
"isinstance",
"(",
"text",
",",
"bytes",
")",
":",
"# -- MAYBE: command.ouput => bytes, encoded stream output.",
"text",
"=",
"codecs",
".",
"decode",
"(",
"text",
")",
"lines",
... | Whitespace normalization:
- Strip empty lines
- Strip leading whitespace in a line
- Strip trailing whitespace in a line
- Normalize line endings | [
"Whitespace",
"normalization",
":"
] | python | train |
senaite/senaite.core | bika/lims/browser/__init__.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/__init__.py#L86-L123 | def ulocalized_time(time, long_format=None, time_only=None, context=None,
request=None):
"""
This function gets ans string as time or a DateTime objects and returns a
string with the time formatted
:param time: The time to process
:type time: str/DateTime
:param long_format:... | [
"def",
"ulocalized_time",
"(",
"time",
",",
"long_format",
"=",
"None",
",",
"time_only",
"=",
"None",
",",
"context",
"=",
"None",
",",
"request",
"=",
"None",
")",
":",
"# if time is a string, we'll try pass it through strptime with the various",
"# formats defined.",... | This function gets ans string as time or a DateTime objects and returns a
string with the time formatted
:param time: The time to process
:type time: str/DateTime
:param long_format: If True, return time in ling format
:type portal_type: boolean/null
:param time_only: If True, only returns tim... | [
"This",
"function",
"gets",
"ans",
"string",
"as",
"time",
"or",
"a",
"DateTime",
"objects",
"and",
"returns",
"a",
"string",
"with",
"the",
"time",
"formatted"
] | python | train |
josiahcarlson/rom | rom/util.py | https://github.com/josiahcarlson/rom/blob/8b5607a856341df85df33422accc30ba9294dbdb/rom/util.py#L658-L670 | def refresh_all(self, *objects, **kwargs):
'''
This method is an alternate API for refreshing all entities tracked
by the session. You can call::
session.refresh_all()
session.refresh_all(force=True)
And all entities known by the session will be reloaded from Re... | [
"def",
"refresh_all",
"(",
"self",
",",
"*",
"objects",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"refresh",
"(",
"*",
"self",
".",
"known",
".",
"values",
"(",
")",
",",
"force",
"=",
"kwargs",
".",
"get",
"(",
"'force'",
")",
")"
] | This method is an alternate API for refreshing all entities tracked
by the session. You can call::
session.refresh_all()
session.refresh_all(force=True)
And all entities known by the session will be reloaded from Redis.
To force reloading for modified entities, you can... | [
"This",
"method",
"is",
"an",
"alternate",
"API",
"for",
"refreshing",
"all",
"entities",
"tracked",
"by",
"the",
"session",
".",
"You",
"can",
"call",
"::"
] | python | test |
assamite/creamas | creamas/core/simulation.py | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/core/simulation.py#L220-L229 | def async_step(self):
"""Progress simulation by running all agents once asynchronously.
"""
assert len(self._agents_to_act) == 0
self._init_step()
t = time.time()
aiomas.run(until=self.env.trigger_all())
self._agents_to_act = []
self._step_processing_time ... | [
"def",
"async_step",
"(",
"self",
")",
":",
"assert",
"len",
"(",
"self",
".",
"_agents_to_act",
")",
"==",
"0",
"self",
".",
"_init_step",
"(",
")",
"t",
"=",
"time",
".",
"time",
"(",
")",
"aiomas",
".",
"run",
"(",
"until",
"=",
"self",
".",
"... | Progress simulation by running all agents once asynchronously. | [
"Progress",
"simulation",
"by",
"running",
"all",
"agents",
"once",
"asynchronously",
"."
] | python | train |
quantmind/pulsar | examples/snippets/remote.py | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/examples/snippets/remote.py#L8-L19 | def remote_call(request, cls, method, args, kw):
'''Command for executing remote calls on a remote object
'''
actor = request.actor
name = 'remote_%s' % cls.__name__
if not hasattr(actor, name):
object = cls(actor)
setattr(actor, name, object)
else:
object = getattr(actor... | [
"def",
"remote_call",
"(",
"request",
",",
"cls",
",",
"method",
",",
"args",
",",
"kw",
")",
":",
"actor",
"=",
"request",
".",
"actor",
"name",
"=",
"'remote_%s'",
"%",
"cls",
".",
"__name__",
"if",
"not",
"hasattr",
"(",
"actor",
",",
"name",
")",... | Command for executing remote calls on a remote object | [
"Command",
"for",
"executing",
"remote",
"calls",
"on",
"a",
"remote",
"object"
] | python | train |
SheffieldML/GPy | GPy/kern/src/todo/symmetric.py | https://github.com/SheffieldML/GPy/blob/54c32d79d289d622fb18b898aee65a2a431d90cf/GPy/kern/src/todo/symmetric.py#L30-L41 | def K(self,X,X2,target):
"""Compute the covariance matrix between X and X2."""
AX = np.dot(X,self.transform)
if X2 is None:
X2 = X
AX2 = AX
else:
AX2 = np.dot(X2, self.transform)
self.k.K(X,X2,target)
self.k.K(AX,X2,target)
self... | [
"def",
"K",
"(",
"self",
",",
"X",
",",
"X2",
",",
"target",
")",
":",
"AX",
"=",
"np",
".",
"dot",
"(",
"X",
",",
"self",
".",
"transform",
")",
"if",
"X2",
"is",
"None",
":",
"X2",
"=",
"X",
"AX2",
"=",
"AX",
"else",
":",
"AX2",
"=",
"n... | Compute the covariance matrix between X and X2. | [
"Compute",
"the",
"covariance",
"matrix",
"between",
"X",
"and",
"X2",
"."
] | python | train |
Archived-Object/ligament | ligament/buildcontext.py | https://github.com/Archived-Object/ligament/blob/ff3d78130522676a20dc64086dc8a27b197cc20f/ligament/buildcontext.py#L126-L137 | def resolve_dependency_graph(self, target):
""" resolves the build order for interdependent build targets
Assumes no cyclic dependencies
"""
targets = self.deep_dependendants(target)
# print "deep dependants:", targets
return sorted(targets,
cmp... | [
"def",
"resolve_dependency_graph",
"(",
"self",
",",
"target",
")",
":",
"targets",
"=",
"self",
".",
"deep_dependendants",
"(",
"target",
")",
"# print \"deep dependants:\", targets",
"return",
"sorted",
"(",
"targets",
",",
"cmp",
"=",
"lambda",
"a",
",",
"b",... | resolves the build order for interdependent build targets
Assumes no cyclic dependencies | [
"resolves",
"the",
"build",
"order",
"for",
"interdependent",
"build",
"targets"
] | python | train |
bububa/pyTOP | pyTOP/packages/requests/models.py | https://github.com/bububa/pyTOP/blob/1e48009bcfe886be392628244b370e6374e1f2b2/pyTOP/packages/requests/models.py#L260-L282 | def _encode_params(data):
"""Encode parameters in a piece of data.
If the data supplied is a dictionary, encodes each parameter in it, and
returns a list of tuples containing the encoded parameters, and a urlencoded
version of that.
Otherwise, assumes the data is already encode... | [
"def",
"_encode_params",
"(",
"data",
")",
":",
"if",
"hasattr",
"(",
"data",
",",
"'__iter__'",
")",
":",
"data",
"=",
"dict",
"(",
"data",
")",
"if",
"hasattr",
"(",
"data",
",",
"'items'",
")",
":",
"result",
"=",
"[",
"]",
"for",
"k",
",",
"v... | Encode parameters in a piece of data.
If the data supplied is a dictionary, encodes each parameter in it, and
returns a list of tuples containing the encoded parameters, and a urlencoded
version of that.
Otherwise, assumes the data is already encoded appropriately, and
returns ... | [
"Encode",
"parameters",
"in",
"a",
"piece",
"of",
"data",
"."
] | python | train |
ga4gh/ga4gh-common | ga4gh/common/utils.py | https://github.com/ga4gh/ga4gh-common/blob/ea1b562dce5bf088ac4577b838cfac7745f08346/ga4gh/common/utils.py#L182-L197 | def getFilePathsWithExtensionsInDirectory(dirTree, patterns, sort=True):
"""
Returns all file paths that match any one of patterns in a
file tree with its root at dirTree. Sorts the paths by default.
"""
filePaths = []
for root, dirs, files in os.walk(dirTree):
for filePath in files:
... | [
"def",
"getFilePathsWithExtensionsInDirectory",
"(",
"dirTree",
",",
"patterns",
",",
"sort",
"=",
"True",
")",
":",
"filePaths",
"=",
"[",
"]",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"dirTree",
")",
":",
"for",
"filePath... | Returns all file paths that match any one of patterns in a
file tree with its root at dirTree. Sorts the paths by default. | [
"Returns",
"all",
"file",
"paths",
"that",
"match",
"any",
"one",
"of",
"patterns",
"in",
"a",
"file",
"tree",
"with",
"its",
"root",
"at",
"dirTree",
".",
"Sorts",
"the",
"paths",
"by",
"default",
"."
] | python | train |
CxAalto/gtfspy | gtfspy/import_loaders/stop_times_loader.py | https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/import_loaders/stop_times_loader.py#L97-L184 | def calculate_trip_shape_breakpoints(conn):
"""Pre-compute the shape points corresponding to each trip's stop.
Depends: shapes"""
from gtfspy import shapes
cur = conn.cursor()
breakpoints_cache = {}
# Counters for problems - don't print every problem.
count_bad_shape_ordering = 0
coun... | [
"def",
"calculate_trip_shape_breakpoints",
"(",
"conn",
")",
":",
"from",
"gtfspy",
"import",
"shapes",
"cur",
"=",
"conn",
".",
"cursor",
"(",
")",
"breakpoints_cache",
"=",
"{",
"}",
"# Counters for problems - don't print every problem.",
"count_bad_shape_ordering",
"... | Pre-compute the shape points corresponding to each trip's stop.
Depends: shapes | [
"Pre",
"-",
"compute",
"the",
"shape",
"points",
"corresponding",
"to",
"each",
"trip",
"s",
"stop",
"."
] | python | valid |
senaite/senaite.core | bika/lims/content/analysisservice.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/content/analysisservice.py#L557-L566 | def getAvailableInstruments(self):
""" Returns the instruments available for this service.
If the service has the getInstrumentEntryOfResults(), returns
the instruments capable to perform this service. Otherwhise,
returns an empty list.
"""
instruments = self.... | [
"def",
"getAvailableInstruments",
"(",
"self",
")",
":",
"instruments",
"=",
"self",
".",
"getInstruments",
"(",
")",
"if",
"self",
".",
"getInstrumentEntryOfResults",
"(",
")",
"is",
"True",
"else",
"None",
"return",
"instruments",
"if",
"instruments",
"else",
... | Returns the instruments available for this service.
If the service has the getInstrumentEntryOfResults(), returns
the instruments capable to perform this service. Otherwhise,
returns an empty list. | [
"Returns",
"the",
"instruments",
"available",
"for",
"this",
"service",
".",
"If",
"the",
"service",
"has",
"the",
"getInstrumentEntryOfResults",
"()",
"returns",
"the",
"instruments",
"capable",
"to",
"perform",
"this",
"service",
".",
"Otherwhise",
"returns",
"a... | python | train |
brocade/pynos | pynos/versions/base/interface.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/base/interface.py#L4079-L4138 | def create_ve(self, **kwargs):
"""
Add Ve Interface .
Args:
ve_name: Ve name with which the Ve interface needs to be
created.
enable (bool): If vrf fowarding should be enabled
or disabled.Default:``True``.
get (bool) : Get config i... | [
"def",
"create_ve",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"ve_name",
"=",
"kwargs",
".",
"pop",
"(",
"'ve_name'",
",",
"''",
")",
"rbridge_id",
"=",
"kwargs",
".",
"pop",
"(",
"'rbridge_id'",
",",
"'1'",
")",
"enable",
"=",
"kwargs",
".",
... | Add Ve Interface .
Args:
ve_name: Ve name with which the Ve interface needs to be
created.
enable (bool): If vrf fowarding should be enabled
or disabled.Default:``True``.
get (bool) : Get config instead of editing config. (True, False)
... | [
"Add",
"Ve",
"Interface",
".",
"Args",
":",
"ve_name",
":",
"Ve",
"name",
"with",
"which",
"the",
"Ve",
"interface",
"needs",
"to",
"be",
"created",
".",
"enable",
"(",
"bool",
")",
":",
"If",
"vrf",
"fowarding",
"should",
"be",
"enabled",
"or",
"disab... | python | train |
ArchiveTeam/wpull | wpull/protocol/abstract/client.py | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/abstract/client.py#L61-L70 | def recycle(self):
'''Clean up and return connections back to the pool.
Connections should be kept alive if supported.
'''
for connection in self._connections:
self._connection_pool.no_wait_release(connection)
self._connections.clear() | [
"def",
"recycle",
"(",
"self",
")",
":",
"for",
"connection",
"in",
"self",
".",
"_connections",
":",
"self",
".",
"_connection_pool",
".",
"no_wait_release",
"(",
"connection",
")",
"self",
".",
"_connections",
".",
"clear",
"(",
")"
] | Clean up and return connections back to the pool.
Connections should be kept alive if supported. | [
"Clean",
"up",
"and",
"return",
"connections",
"back",
"to",
"the",
"pool",
"."
] | python | train |
Opentrons/opentrons | api/src/opentrons/protocol_api/contexts.py | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/protocol_api/contexts.py#L1716-L1720 | def close(self):
""" Closes the lid"""
self._geometry.lid_status = self._module.close()
self._ctx.deck.recalculate_high_z()
return self._geometry.lid_status | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"_geometry",
".",
"lid_status",
"=",
"self",
".",
"_module",
".",
"close",
"(",
")",
"self",
".",
"_ctx",
".",
"deck",
".",
"recalculate_high_z",
"(",
")",
"return",
"self",
".",
"_geometry",
".",
"... | Closes the lid | [
"Closes",
"the",
"lid"
] | python | train |
KrzyHonk/bpmn-python | bpmn_python/graph/classes/root_element/process_type.py | https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/graph/classes/root_element/process_type.py#L34-L44 | def set_process_type(self, value):
"""
Setter for 'process_type' field.
:param value - a new value of 'process_type' field.
"""
if value is None or not isinstance(value, str):
raise TypeError("ProcessType must be set to a String")
elif value not in Process.__p... | [
"def",
"set_process_type",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
"or",
"not",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"ProcessType must be set to a String\"",
")",
"elif",
"value",
"not",
"in... | Setter for 'process_type' field.
:param value - a new value of 'process_type' field. | [
"Setter",
"for",
"process_type",
"field",
".",
":",
"param",
"value",
"-",
"a",
"new",
"value",
"of",
"process_type",
"field",
"."
] | python | train |
spyder-ide/spyder | spyder/app/mainwindow.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/app/mainwindow.py#L2180-L2204 | def update_search_menu(self):
"""Update search menu"""
# Disabling all actions except the last one
# (which is Find in files) to begin with
for child in self.search_menu.actions()[:-1]:
child.setEnabled(False)
widget, textedit_properties = self.get_focus_widge... | [
"def",
"update_search_menu",
"(",
"self",
")",
":",
"# Disabling all actions except the last one\r",
"# (which is Find in files) to begin with\r",
"for",
"child",
"in",
"self",
".",
"search_menu",
".",
"actions",
"(",
")",
"[",
":",
"-",
"1",
"]",
":",
"child",
".",... | Update search menu | [
"Update",
"search",
"menu"
] | python | train |
Jammy2211/PyAutoLens | autolens/lens/plotters/lens_fit_plotters.py | https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/lens/plotters/lens_fit_plotters.py#L45-L158 | def plot_fit_subplot_lens_plane_only(
fit, should_plot_mask=True, extract_array_from_mask=False, zoom_around_mask=False, positions=None,
should_plot_image_plane_pix=False,
units='arcsec', figsize=None, aspect='square',
cmap='jet', norm='linear', norm_min=None, norm_max=None, linthresh=0.... | [
"def",
"plot_fit_subplot_lens_plane_only",
"(",
"fit",
",",
"should_plot_mask",
"=",
"True",
",",
"extract_array_from_mask",
"=",
"False",
",",
"zoom_around_mask",
"=",
"False",
",",
"positions",
"=",
"None",
",",
"should_plot_image_plane_pix",
"=",
"False",
",",
"u... | Plot the model datas_ of an analysis, using the *Fitter* class object.
The visualization and output type can be fully customized.
Parameters
-----------
fit : autolens.lens.fitting.Fitter
Class containing fit between the model datas_ and observed lens datas_ (including residual_map, chi_square... | [
"Plot",
"the",
"model",
"datas_",
"of",
"an",
"analysis",
"using",
"the",
"*",
"Fitter",
"*",
"class",
"object",
"."
] | python | valid |
apache/spark | python/pyspark/rdd.py | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L922-L955 | def aggregate(self, zeroValue, seqOp, combOp):
"""
Aggregate the elements of each partition, and then the results for all
the partitions, using a given combine functions and a neutral "zero
value."
The functions C{op(t1, t2)} is allowed to modify C{t1} and return it
as i... | [
"def",
"aggregate",
"(",
"self",
",",
"zeroValue",
",",
"seqOp",
",",
"combOp",
")",
":",
"seqOp",
"=",
"fail_on_stopiteration",
"(",
"seqOp",
")",
"combOp",
"=",
"fail_on_stopiteration",
"(",
"combOp",
")",
"def",
"func",
"(",
"iterator",
")",
":",
"acc",... | Aggregate the elements of each partition, and then the results for all
the partitions, using a given combine functions and a neutral "zero
value."
The functions C{op(t1, t2)} is allowed to modify C{t1} and return it
as its result value to avoid object allocation; however, it should not
... | [
"Aggregate",
"the",
"elements",
"of",
"each",
"partition",
"and",
"then",
"the",
"results",
"for",
"all",
"the",
"partitions",
"using",
"a",
"given",
"combine",
"functions",
"and",
"a",
"neutral",
"zero",
"value",
"."
] | python | train |
danielhrisca/asammdf | asammdf/blocks/mdf_v4.py | https://github.com/danielhrisca/asammdf/blob/3c7a1fd19c957ceebe4dcdbb2abf00806c2bdb66/asammdf/blocks/mdf_v4.py#L4915-L5162 | def get_can_signal(
self, name, database=None, db=None, ignore_invalidation_bits=False
):
""" get CAN message signal. You can specify an external CAN database (
*database* argument) or canmatrix databse object that has already been
loaded from a file (*db* argument).
The sig... | [
"def",
"get_can_signal",
"(",
"self",
",",
"name",
",",
"database",
"=",
"None",
",",
"db",
"=",
"None",
",",
"ignore_invalidation_bits",
"=",
"False",
")",
":",
"if",
"database",
"is",
"None",
"and",
"db",
"is",
"None",
":",
"return",
"self",
".",
"ge... | get CAN message signal. You can specify an external CAN database (
*database* argument) or canmatrix databse object that has already been
loaded from a file (*db* argument).
The signal name can be specified in the following ways
* ``CAN<ID>.<MESSAGE_NAME>.<SIGNAL_NAME>`` - the `ID` val... | [
"get",
"CAN",
"message",
"signal",
".",
"You",
"can",
"specify",
"an",
"external",
"CAN",
"database",
"(",
"*",
"database",
"*",
"argument",
")",
"or",
"canmatrix",
"databse",
"object",
"that",
"has",
"already",
"been",
"loaded",
"from",
"a",
"file",
"(",
... | python | train |
bodylabs/lace | lace/meshviewer.py | https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/meshviewer.py#L123-L140 | def MeshViewers(
shape=(1, 1), titlebar="Mesh Viewers", keepalive=False,
window_width=1280, window_height=960
):
"""Allows subplot-style inspection of primitives in multiple subwindows.
Args:
shape: a tuple indicating the number of vertical and horizontal windows requested
Returns:... | [
"def",
"MeshViewers",
"(",
"shape",
"=",
"(",
"1",
",",
"1",
")",
",",
"titlebar",
"=",
"\"Mesh Viewers\"",
",",
"keepalive",
"=",
"False",
",",
"window_width",
"=",
"1280",
",",
"window_height",
"=",
"960",
")",
":",
"if",
"not",
"test_for_opengl",
"(",... | Allows subplot-style inspection of primitives in multiple subwindows.
Args:
shape: a tuple indicating the number of vertical and horizontal windows requested
Returns: a list of lists of MeshViewer objects: one per window requested. | [
"Allows",
"subplot",
"-",
"style",
"inspection",
"of",
"primitives",
"in",
"multiple",
"subwindows",
"."
] | python | train |
blockstack/blockstack-files | blockstack_file/blockstack_file.py | https://github.com/blockstack/blockstack-files/blob/8d88cc48bdf8ed57f17d4bba860e972bde321921/blockstack_file/blockstack_file.py#L497-L560 | def file_put( blockchain_id, hostname, recipient_blockchain_ids, data_name, input_path, passphrase=None, config_path=CONFIG_PATH, wallet_keys=None ):
"""
Send a file to the given recipient, encrypted and signed with the
given blockchain ID.
Allow each recipient to receive the data on each of their hosts... | [
"def",
"file_put",
"(",
"blockchain_id",
",",
"hostname",
",",
"recipient_blockchain_ids",
",",
"data_name",
",",
"input_path",
",",
"passphrase",
"=",
"None",
",",
"config_path",
"=",
"CONFIG_PATH",
",",
"wallet_keys",
"=",
"None",
")",
":",
"fd",
",",
"outpu... | Send a file to the given recipient, encrypted and signed with the
given blockchain ID.
Allow each recipient to receive the data on each of their hosts.
Return {'status': True} on success, and upload to cloud storage
Return {'error': ...} on error | [
"Send",
"a",
"file",
"to",
"the",
"given",
"recipient",
"encrypted",
"and",
"signed",
"with",
"the",
"given",
"blockchain",
"ID",
".",
"Allow",
"each",
"recipient",
"to",
"receive",
"the",
"data",
"on",
"each",
"of",
"their",
"hosts",
".",
"Return",
"{",
... | python | train |
rigetti/quantumflow | quantumflow/states.py | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L131-L147 | def expectation(self, diag_hermitian: bk.TensorLike,
trials: int = None) -> bk.BKTensor:
"""Return the expectation of a measurement. Since we can only measure
our computer in the computational basis, we only require the diagonal
of the Hermitian in that basis.
If the... | [
"def",
"expectation",
"(",
"self",
",",
"diag_hermitian",
":",
"bk",
".",
"TensorLike",
",",
"trials",
":",
"int",
"=",
"None",
")",
"->",
"bk",
".",
"BKTensor",
":",
"if",
"trials",
"is",
"None",
":",
"probs",
"=",
"self",
".",
"probabilities",
"(",
... | Return the expectation of a measurement. Since we can only measure
our computer in the computational basis, we only require the diagonal
of the Hermitian in that basis.
If the number of trials is specified, we sample the given number of
times. Else we return the exact expectation (as if... | [
"Return",
"the",
"expectation",
"of",
"a",
"measurement",
".",
"Since",
"we",
"can",
"only",
"measure",
"our",
"computer",
"in",
"the",
"computational",
"basis",
"we",
"only",
"require",
"the",
"diagonal",
"of",
"the",
"Hermitian",
"in",
"that",
"basis",
"."... | python | train |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_ip_policy.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_ip_policy.py#L1121-L1139 | def hide_routemap_holder_route_map_content_set_origin_origin_igp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hide_routemap_holder = ET.SubElement(config, "hide-routemap-holder", xmlns="urn:brocade.com:mgmt:brocade-ip-policy")
route_map = ET.SubElemen... | [
"def",
"hide_routemap_holder_route_map_content_set_origin_origin_igp",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"hide_routemap_holder",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"hide-ro... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
domainaware/parsedmarc | parsedmarc/__init__.py | https://github.com/domainaware/parsedmarc/blob/ecc9fd434c23d896ccd1f35795ccc047f946ed05/parsedmarc/__init__.py#L519-L633 | def parse_forensic_report(feedback_report, sample, msg_date,
nameservers=None, dns_timeout=2.0,
strip_attachment_payloads=False,
parallel=False):
"""
Converts a DMARC forensic report and sample to a ``OrderedDict``
Args:
... | [
"def",
"parse_forensic_report",
"(",
"feedback_report",
",",
"sample",
",",
"msg_date",
",",
"nameservers",
"=",
"None",
",",
"dns_timeout",
"=",
"2.0",
",",
"strip_attachment_payloads",
"=",
"False",
",",
"parallel",
"=",
"False",
")",
":",
"delivery_results",
... | Converts a DMARC forensic report and sample to a ``OrderedDict``
Args:
feedback_report (str): A message's feedback report as a string
sample (str): The RFC 822 headers or RFC 822 message sample
msg_date (str): The message's date header
nameservers (list): A list of one or more names... | [
"Converts",
"a",
"DMARC",
"forensic",
"report",
"and",
"sample",
"to",
"a",
"OrderedDict"
] | python | test |
brentp/cruzdb | cruzdb/intersecter.py | https://github.com/brentp/cruzdb/blob/9068d46e25952f4a929dde0242beb31fa4c7e89a/cruzdb/intersecter.py#L194-L215 | def right(self, f, n=1):
"""return the nearest n features strictly to the right of a Feature f.
Overlapping features are not considered as to the right.
f: a Feature object
n: the number of features to return
"""
intervals = self.intervals[f.chrom]
ilen = len(int... | [
"def",
"right",
"(",
"self",
",",
"f",
",",
"n",
"=",
"1",
")",
":",
"intervals",
"=",
"self",
".",
"intervals",
"[",
"f",
".",
"chrom",
"]",
"ilen",
"=",
"len",
"(",
"intervals",
")",
"iright",
"=",
"binsearch_right_end",
"(",
"intervals",
",",
"f... | return the nearest n features strictly to the right of a Feature f.
Overlapping features are not considered as to the right.
f: a Feature object
n: the number of features to return | [
"return",
"the",
"nearest",
"n",
"features",
"strictly",
"to",
"the",
"right",
"of",
"a",
"Feature",
"f",
".",
"Overlapping",
"features",
"are",
"not",
"considered",
"as",
"to",
"the",
"right",
"."
] | python | train |
smarie/python-valid8 | valid8/entry_points_annotations.py | https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/entry_points_annotations.py#L714-L769 | def decorate_with_validation(func,
arg_name, # type: str
*validation_func, # type: ValidationFuncs
**kwargs):
# type: (...) -> Callable
"""
This method is the inner method used in `@validate_io`, `@validate_arg`... | [
"def",
"decorate_with_validation",
"(",
"func",
",",
"arg_name",
",",
"# type: str",
"*",
"validation_func",
",",
"# type: ValidationFuncs",
"*",
"*",
"kwargs",
")",
":",
"# type: (...) -> Callable",
"error_type",
",",
"help_msg",
",",
"none_policy",
",",
"_constructo... | This method is the inner method used in `@validate_io`, `@validate_arg` and `@validate_out`.
It can be used if you with to perform decoration manually without a decorator.
:param func:
:param arg_name: the name of the argument to validate or _OUT_KEY for output validation
:param validation_func: the va... | [
"This",
"method",
"is",
"the",
"inner",
"method",
"used",
"in",
"@validate_io",
"@validate_arg",
"and",
"@validate_out",
".",
"It",
"can",
"be",
"used",
"if",
"you",
"with",
"to",
"perform",
"decoration",
"manually",
"without",
"a",
"decorator",
"."
] | python | train |
mathandy/svgpathtools | svgpathtools/path.py | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/path.py#L577-L582 | def ilength(self, s, s_tol=ILENGTH_S_TOL, maxits=ILENGTH_MAXITS,
error=ILENGTH_ERROR, min_depth=ILENGTH_MIN_DEPTH):
"""Returns a float, t, such that self.length(0, t) is approximately s.
See the inv_arclength() docstring for more details."""
return inv_arclength(self, s, s_tol=s_... | [
"def",
"ilength",
"(",
"self",
",",
"s",
",",
"s_tol",
"=",
"ILENGTH_S_TOL",
",",
"maxits",
"=",
"ILENGTH_MAXITS",
",",
"error",
"=",
"ILENGTH_ERROR",
",",
"min_depth",
"=",
"ILENGTH_MIN_DEPTH",
")",
":",
"return",
"inv_arclength",
"(",
"self",
",",
"s",
"... | Returns a float, t, such that self.length(0, t) is approximately s.
See the inv_arclength() docstring for more details. | [
"Returns",
"a",
"float",
"t",
"such",
"that",
"self",
".",
"length",
"(",
"0",
"t",
")",
"is",
"approximately",
"s",
".",
"See",
"the",
"inv_arclength",
"()",
"docstring",
"for",
"more",
"details",
"."
] | python | train |
cloud-custodian/cloud-custodian | tools/c7n_gcp/c7n_gcp/client.py | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_gcp/c7n_gcp/client.py#L394-L418 | def execute_paged_query(self, verb, verb_arguments):
"""Executes query (ex. list) via a dedicated http object.
Args:
verb (str): Method to execute on the component (ex. get, list).
verb_arguments (dict): key-value pairs to be passed to _BuildRequest.
Yields:
... | [
"def",
"execute_paged_query",
"(",
"self",
",",
"verb",
",",
"verb_arguments",
")",
":",
"if",
"not",
"self",
".",
"supports_pagination",
"(",
"verb",
"=",
"verb",
")",
":",
"raise",
"PaginationNotSupported",
"(",
"'{} does not support pagination'",
")",
"request"... | Executes query (ex. list) via a dedicated http object.
Args:
verb (str): Method to execute on the component (ex. get, list).
verb_arguments (dict): key-value pairs to be passed to _BuildRequest.
Yields:
dict: Service Response.
Raises:
Pagination... | [
"Executes",
"query",
"(",
"ex",
".",
"list",
")",
"via",
"a",
"dedicated",
"http",
"object",
"."
] | python | train |
tensorflow/mesh | mesh_tensorflow/beam_search.py | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/beam_search.py#L577-L642 | def greedy_decode(logits_fn,
initial_ids,
temperature=0.0,
initial_states=None,
eos_id=EOS_ID,
forced_ids=None,
use_tpu=True):
"""Greedy decoding.
Args:
logits_fn: Interface to the model, to provide logi... | [
"def",
"greedy_decode",
"(",
"logits_fn",
",",
"initial_ids",
",",
"temperature",
"=",
"0.0",
",",
"initial_states",
"=",
"None",
",",
"eos_id",
"=",
"EOS_ID",
",",
"forced_ids",
"=",
"None",
",",
"use_tpu",
"=",
"True",
")",
":",
"length_dim",
"=",
"initi... | Greedy decoding.
Args:
logits_fn: Interface to the model, to provide logits.
Shoud take:
step_num - mtf Scalar
ids - mtf Tensor with shape [..., length]
states - list of mtf.Tensor
Should return:
logits - [batch, vocab_size]
new_states - list of m... | [
"Greedy",
"decoding",
"."
] | python | train |
google/grumpy | third_party/stdlib/json/decoder.py | https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/json/decoder.py#L362-L371 | def decode(self, s, _w=WHITESPACE.match):
"""Return the Python representation of ``s`` (a ``str`` or ``unicode``
instance containing a JSON document)
"""
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
end = _w(s, end).end()
if end != len(s):
raise ValueErr... | [
"def",
"decode",
"(",
"self",
",",
"s",
",",
"_w",
"=",
"WHITESPACE",
".",
"match",
")",
":",
"obj",
",",
"end",
"=",
"self",
".",
"raw_decode",
"(",
"s",
",",
"idx",
"=",
"_w",
"(",
"s",
",",
"0",
")",
".",
"end",
"(",
")",
")",
"end",
"="... | Return the Python representation of ``s`` (a ``str`` or ``unicode``
instance containing a JSON document) | [
"Return",
"the",
"Python",
"representation",
"of",
"s",
"(",
"a",
"str",
"or",
"unicode",
"instance",
"containing",
"a",
"JSON",
"document",
")"
] | python | valid |
SheffieldML/GPy | GPy/util/univariate_Gaussian.py | https://github.com/SheffieldML/GPy/blob/54c32d79d289d622fb18b898aee65a2a431d90cf/GPy/util/univariate_Gaussian.py#L14-L24 | def inv_std_norm_cdf(x):
"""
Inverse cumulative standard Gaussian distribution
Based on Winitzki, S. (2008)
"""
z = 2*x -1
ln1z2 = np.log(1-z**2)
a = 8*(np.pi -3)/(3*np.pi*(4-np.pi))
b = 2/(np.pi * a) + ln1z2/2
inv_erf = np.sign(z) * np.sqrt( np.sqrt(b**2 - ln1z2/a) - b )
return ... | [
"def",
"inv_std_norm_cdf",
"(",
"x",
")",
":",
"z",
"=",
"2",
"*",
"x",
"-",
"1",
"ln1z2",
"=",
"np",
".",
"log",
"(",
"1",
"-",
"z",
"**",
"2",
")",
"a",
"=",
"8",
"*",
"(",
"np",
".",
"pi",
"-",
"3",
")",
"/",
"(",
"3",
"*",
"np",
"... | Inverse cumulative standard Gaussian distribution
Based on Winitzki, S. (2008) | [
"Inverse",
"cumulative",
"standard",
"Gaussian",
"distribution",
"Based",
"on",
"Winitzki",
"S",
".",
"(",
"2008",
")"
] | python | train |
OpenGov/carpenter | carpenter/carpenter.py | https://github.com/OpenGov/carpenter/blob/0ab3c54c05133b9b0468c63e834a7ce3a6fb575b/carpenter/carpenter.py#L87-L97 | def stitch_block_rows(block_list):
'''
Stitches blocks together into a single block rowwise. These blocks are 2D tables usually
generated from tableproc. The final block will be of dimensions (sum(num_rows), max(num_cols)).
'''
stitched = list(itertools.chain(*block_list))
max_length = max... | [
"def",
"stitch_block_rows",
"(",
"block_list",
")",
":",
"stitched",
"=",
"list",
"(",
"itertools",
".",
"chain",
"(",
"*",
"block_list",
")",
")",
"max_length",
"=",
"max",
"(",
"len",
"(",
"row",
")",
"for",
"row",
"in",
"stitched",
")",
"for",
"row"... | Stitches blocks together into a single block rowwise. These blocks are 2D tables usually
generated from tableproc. The final block will be of dimensions (sum(num_rows), max(num_cols)). | [
"Stitches",
"blocks",
"together",
"into",
"a",
"single",
"block",
"rowwise",
".",
"These",
"blocks",
"are",
"2D",
"tables",
"usually",
"generated",
"from",
"tableproc",
".",
"The",
"final",
"block",
"will",
"be",
"of",
"dimensions",
"(",
"sum",
"(",
"num_row... | python | train |
blazelibs/blazeutils | blazeutils/functional.py | https://github.com/blazelibs/blazeutils/blob/c94476325146007553cbddeeb9ef83394756babf/blazeutils/functional.py#L114-L122 | def unzip(iterable):
"""Unzip/transpose an iterable of tuples into a tuple of lists.
WARNING: When given an empty iterable, this returns an empty list instead of a tuple. If you
need a consistent interface then do something like this:
left, right = unzip(two_columned_list) or ([], [])
"""
... | [
"def",
"unzip",
"(",
"iterable",
")",
":",
"return",
"list",
"(",
"map",
"(",
"list",
",",
"list",
"(",
"six",
".",
"moves",
".",
"zip",
"(",
"*",
"iterable",
")",
")",
")",
")"
] | Unzip/transpose an iterable of tuples into a tuple of lists.
WARNING: When given an empty iterable, this returns an empty list instead of a tuple. If you
need a consistent interface then do something like this:
left, right = unzip(two_columned_list) or ([], []) | [
"Unzip",
"/",
"transpose",
"an",
"iterable",
"of",
"tuples",
"into",
"a",
"tuple",
"of",
"lists",
"."
] | python | train |
bkad/python-stylus | stylus/__init__.py | https://github.com/bkad/python-stylus/blob/3d79145fecd56e6af9fb38d55886c65ce2cac82e/stylus/__init__.py#L31-L38 | def use(self, plugin, arguments={}):
"""Add plugin to use during compilation.
plugin: Plugin to include.
arguments: Dictionary of arguments to pass to the import.
"""
self.plugins[plugin] = dict(arguments)
return self.plugins | [
"def",
"use",
"(",
"self",
",",
"plugin",
",",
"arguments",
"=",
"{",
"}",
")",
":",
"self",
".",
"plugins",
"[",
"plugin",
"]",
"=",
"dict",
"(",
"arguments",
")",
"return",
"self",
".",
"plugins"
] | Add plugin to use during compilation.
plugin: Plugin to include.
arguments: Dictionary of arguments to pass to the import. | [
"Add",
"plugin",
"to",
"use",
"during",
"compilation",
"."
] | python | train |
Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/gather_commands.py | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/gather_commands.py#L35-L68 | def add_new_lines(long_phrase, line_min=None, tolerance=TOLERANCE):
""" not everything fits on the screen, based on the size, add newlines """
if line_min is None:
line_min = math.floor(int(_get_window_columns()) / 2 - 15)
if long_phrase is None:
return long_phrase
line_min = int(line_m... | [
"def",
"add_new_lines",
"(",
"long_phrase",
",",
"line_min",
"=",
"None",
",",
"tolerance",
"=",
"TOLERANCE",
")",
":",
"if",
"line_min",
"is",
"None",
":",
"line_min",
"=",
"math",
".",
"floor",
"(",
"int",
"(",
"_get_window_columns",
"(",
")",
")",
"/"... | not everything fits on the screen, based on the size, add newlines | [
"not",
"everything",
"fits",
"on",
"the",
"screen",
"based",
"on",
"the",
"size",
"add",
"newlines"
] | python | train |
mrcagney/gtfstk | gtfstk/helpers.py | https://github.com/mrcagney/gtfstk/blob/c91494e6fefc02523889655a0dc92d1c0eee8d03/gtfstk/helpers.py#L187-L209 | def get_convert_dist(
dist_units_in: str, dist_units_out: str
) -> Callable[[float], float]:
"""
Return a function of the form
distance in the units ``dist_units_in`` ->
distance in the units ``dist_units_out``
Only supports distance units in :const:`constants.DIST_UNITS`.
"""
di, ... | [
"def",
"get_convert_dist",
"(",
"dist_units_in",
":",
"str",
",",
"dist_units_out",
":",
"str",
")",
"->",
"Callable",
"[",
"[",
"float",
"]",
",",
"float",
"]",
":",
"di",
",",
"do",
"=",
"dist_units_in",
",",
"dist_units_out",
"DU",
"=",
"cs",
".",
"... | Return a function of the form
distance in the units ``dist_units_in`` ->
distance in the units ``dist_units_out``
Only supports distance units in :const:`constants.DIST_UNITS`. | [
"Return",
"a",
"function",
"of",
"the",
"form"
] | python | train |
ThreatConnect-Inc/tcex | tcex/tcex_playbook.py | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_playbook.py#L59-L70 | def _variable_pattern(self):
"""Regex pattern to match and parse a playbook variable."""
variable_pattern = r'#([A-Za-z]+)' # match literal (#App) at beginning of String
variable_pattern += r':([\d]+)' # app id (:7979)
variable_pattern += r':([A-Za-z0-9_\.\-\[\]]+)' # variable name (:... | [
"def",
"_variable_pattern",
"(",
"self",
")",
":",
"variable_pattern",
"=",
"r'#([A-Za-z]+)'",
"# match literal (#App) at beginning of String",
"variable_pattern",
"+=",
"r':([\\d]+)'",
"# app id (:7979)",
"variable_pattern",
"+=",
"r':([A-Za-z0-9_\\.\\-\\[\\]]+)'",
"# variable nam... | Regex pattern to match and parse a playbook variable. | [
"Regex",
"pattern",
"to",
"match",
"and",
"parse",
"a",
"playbook",
"variable",
"."
] | python | train |
sorgerlab/indra | indra/assemblers/english/assembler.py | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/english/assembler.py#L325-L330 | def _assemble_gef(stmt):
"""Assemble Gef statements into text."""
subj_str = _assemble_agent_str(stmt.gef)
obj_str = _assemble_agent_str(stmt.ras)
stmt_str = subj_str + ' is a GEF for ' + obj_str
return _make_sentence(stmt_str) | [
"def",
"_assemble_gef",
"(",
"stmt",
")",
":",
"subj_str",
"=",
"_assemble_agent_str",
"(",
"stmt",
".",
"gef",
")",
"obj_str",
"=",
"_assemble_agent_str",
"(",
"stmt",
".",
"ras",
")",
"stmt_str",
"=",
"subj_str",
"+",
"' is a GEF for '",
"+",
"obj_str",
"r... | Assemble Gef statements into text. | [
"Assemble",
"Gef",
"statements",
"into",
"text",
"."
] | python | train |
brentp/cruzdb | cruzdb/sqlsoup.py | https://github.com/brentp/cruzdb/blob/9068d46e25952f4a929dde0242beb31fa4c7e89a/cruzdb/sqlsoup.py#L229-L238 | def execute(self, stmt, **params):
"""Execute a SQL statement.
The statement may be a string SQL string,
an :func:`sqlalchemy.sql.expression.select` construct, or a
:func:`sqlalchemy.sql.expression.text`
construct.
"""
return self.session.execute(sql.text(stmt... | [
"def",
"execute",
"(",
"self",
",",
"stmt",
",",
"*",
"*",
"params",
")",
":",
"return",
"self",
".",
"session",
".",
"execute",
"(",
"sql",
".",
"text",
"(",
"stmt",
",",
"bind",
"=",
"self",
".",
"bind",
")",
",",
"*",
"*",
"params",
")"
] | Execute a SQL statement.
The statement may be a string SQL string,
an :func:`sqlalchemy.sql.expression.select` construct, or a
:func:`sqlalchemy.sql.expression.text`
construct. | [
"Execute",
"a",
"SQL",
"statement",
"."
] | python | train |
LonamiWebs/Telethon | telethon/extensions/html.py | https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/extensions/html.py#L117-L131 | def parse(html):
"""
Parses the given HTML message and returns its stripped representation
plus a list of the MessageEntity's that were found.
:param message: the message with HTML to be parsed.
:return: a tuple consisting of (clean message, [message entities]).
"""
if not html:
ret... | [
"def",
"parse",
"(",
"html",
")",
":",
"if",
"not",
"html",
":",
"return",
"html",
",",
"[",
"]",
"parser",
"=",
"HTMLToTelegramParser",
"(",
")",
"parser",
".",
"feed",
"(",
"_add_surrogate",
"(",
"html",
")",
")",
"text",
"=",
"helpers",
".",
"stri... | Parses the given HTML message and returns its stripped representation
plus a list of the MessageEntity's that were found.
:param message: the message with HTML to be parsed.
:return: a tuple consisting of (clean message, [message entities]). | [
"Parses",
"the",
"given",
"HTML",
"message",
"and",
"returns",
"its",
"stripped",
"representation",
"plus",
"a",
"list",
"of",
"the",
"MessageEntity",
"s",
"that",
"were",
"found",
"."
] | python | train |
fermiPy/fermipy | fermipy/diffuse/gt_split_and_mktime.py | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/gt_split_and_mktime.py#L38-L63 | def make_full_path(basedir, outkey, origname):
"""Make a full file path by combining tokens
Parameters
-----------
basedir : str
The top level output area
outkey : str
The key for the particular instance of the analysis
origname : str
Template for the output file name... | [
"def",
"make_full_path",
"(",
"basedir",
",",
"outkey",
",",
"origname",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"basedir",
",",
"outkey",
",",
"os",
".",
"path",
".",
"basename",
"(",
"origname",
")",
".",
"replace",
"(",
"'.fits'",
... | Make a full file path by combining tokens
Parameters
-----------
basedir : str
The top level output area
outkey : str
The key for the particular instance of the analysis
origname : str
Template for the output file name
Returns
-------
outpath : str
T... | [
"Make",
"a",
"full",
"file",
"path",
"by",
"combining",
"tokens"
] | python | train |
yyuu/botornado | botornado/sqs/connection.py | https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/botornado/sqs/connection.py#L98-L122 | def get_queue_attributes(self, queue, attribute='All', callback=None):
"""
Gets one or all attributes of a Queue
:type queue: A Queue object
:param queue: The SQS queue to be deleted
:type attribute: str
:type attribute: The specific attribute requested. If not... | [
"def",
"get_queue_attributes",
"(",
"self",
",",
"queue",
",",
"attribute",
"=",
"'All'",
",",
"callback",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'AttributeName'",
":",
"attribute",
"}",
"return",
"self",
".",
"get_object",
"(",
"'GetQueueAttributes'",
... | Gets one or all attributes of a Queue
:type queue: A Queue object
:param queue: The SQS queue to be deleted
:type attribute: str
:type attribute: The specific attribute requested. If not supplied,
the default is to return all attributes.
... | [
"Gets",
"one",
"or",
"all",
"attributes",
"of",
"a",
"Queue",
":",
"type",
"queue",
":",
"A",
"Queue",
"object",
":",
"param",
"queue",
":",
"The",
"SQS",
"queue",
"to",
"be",
"deleted"
] | python | train |
tango-controls/pytango | tango/device_class.py | https://github.com/tango-controls/pytango/blob/9cf78c517c9cdc1081ff6d080a9646a740cc1d36/tango/device_class.py#L190-L206 | def get_property_type(self, prop_name, properties):
"""
get_property_type(self, prop_name, properties) -> CmdArgType
Gets the property type for the given property name using the
information given in properties
Parameters :
... | [
"def",
"get_property_type",
"(",
"self",
",",
"prop_name",
",",
"properties",
")",
":",
"try",
":",
"tg_type",
"=",
"properties",
"[",
"prop_name",
"]",
"[",
"0",
"]",
"except",
":",
"tg_type",
"=",
"CmdArgType",
".",
"DevVoid",
"return",
"tg_type"
] | get_property_type(self, prop_name, properties) -> CmdArgType
Gets the property type for the given property name using the
information given in properties
Parameters :
- prop_name : (str) property name
- properties : (dict<... | [
"get_property_type",
"(",
"self",
"prop_name",
"properties",
")",
"-",
">",
"CmdArgType"
] | python | train |
idank/bashlex | bashlex/parser.py | https://github.com/idank/bashlex/blob/800cb7e3c634eaa3c81f8a8648fd7fd4e27050ac/bashlex/parser.py#L355-L365 | def p_elif_clause(p):
'''elif_clause : ELIF compound_list THEN compound_list
| ELIF compound_list THEN compound_list ELSE compound_list
| ELIF compound_list THEN compound_list elif_clause'''
parts = []
for i in range(1, len(p)):
if isinstance(p[i], ast.node):
... | [
"def",
"p_elif_clause",
"(",
"p",
")",
":",
"parts",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"p",
")",
")",
":",
"if",
"isinstance",
"(",
"p",
"[",
"i",
"]",
",",
"ast",
".",
"node",
")",
":",
"parts",
".",
"app... | elif_clause : ELIF compound_list THEN compound_list
| ELIF compound_list THEN compound_list ELSE compound_list
| ELIF compound_list THEN compound_list elif_clause | [
"elif_clause",
":",
"ELIF",
"compound_list",
"THEN",
"compound_list",
"|",
"ELIF",
"compound_list",
"THEN",
"compound_list",
"ELSE",
"compound_list",
"|",
"ELIF",
"compound_list",
"THEN",
"compound_list",
"elif_clause"
] | python | train |
pyviz/holoviews | examples/gallery/apps/bokeh/mandelbrot.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/examples/gallery/apps/bokeh/mandelbrot.py#L17-L31 | def mandel(x, y, max_iters):
"""
Given the real and imaginary parts of a complex number,
determine if it is a candidate for membership in the Mandelbrot
set given a fixed number of iterations.
"""
i = 0
c = complex(x,y)
z = 0.0j
for i in range(max_iters):
z = z*z + c
... | [
"def",
"mandel",
"(",
"x",
",",
"y",
",",
"max_iters",
")",
":",
"i",
"=",
"0",
"c",
"=",
"complex",
"(",
"x",
",",
"y",
")",
"z",
"=",
"0.0j",
"for",
"i",
"in",
"range",
"(",
"max_iters",
")",
":",
"z",
"=",
"z",
"*",
"z",
"+",
"c",
"if"... | Given the real and imaginary parts of a complex number,
determine if it is a candidate for membership in the Mandelbrot
set given a fixed number of iterations. | [
"Given",
"the",
"real",
"and",
"imaginary",
"parts",
"of",
"a",
"complex",
"number",
"determine",
"if",
"it",
"is",
"a",
"candidate",
"for",
"membership",
"in",
"the",
"Mandelbrot",
"set",
"given",
"a",
"fixed",
"number",
"of",
"iterations",
"."
] | python | train |
LettError/MutatorMath | Lib/mutatorMath/objects/location.py | https://github.com/LettError/MutatorMath/blob/10318fc4e7c9cee9df6130826829baea3054a42b/Lib/mutatorMath/objects/location.py#L606-L644 | def sortLocations(locations):
""" Sort the locations by ranking:
1. all on-axis points
2. all off-axis points which project onto on-axis points
these would be involved in master to master interpolations
necessary for patching. Projecting off-axis masters hav... | [
"def",
"sortLocations",
"(",
"locations",
")",
":",
"onAxis",
"=",
"[",
"]",
"onAxisValues",
"=",
"{",
"}",
"offAxis",
"=",
"[",
"]",
"offAxis_projecting",
"=",
"[",
"]",
"offAxis_wild",
"=",
"[",
"]",
"# first get the on-axis points",
"for",
"l",
"in",
"l... | Sort the locations by ranking:
1. all on-axis points
2. all off-axis points which project onto on-axis points
these would be involved in master to master interpolations
necessary for patching. Projecting off-axis masters have
at least one coordin... | [
"Sort",
"the",
"locations",
"by",
"ranking",
":",
"1",
".",
"all",
"on",
"-",
"axis",
"points",
"2",
".",
"all",
"off",
"-",
"axis",
"points",
"which",
"project",
"onto",
"on",
"-",
"axis",
"points",
"these",
"would",
"be",
"involved",
"in",
"master",
... | python | train |
opendatateam/udata | udata/i18n.py | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/i18n.py#L203-L209 | def redirect_to_lang(*args, **kwargs):
'''Redirect non lang-prefixed urls to default language.'''
endpoint = request.endpoint.replace('_redirect', '')
kwargs = multi_to_dict(request.args)
kwargs.update(request.view_args)
kwargs['lang_code'] = default_lang
return redirect(url_for(endpoint, **kwar... | [
"def",
"redirect_to_lang",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"endpoint",
"=",
"request",
".",
"endpoint",
".",
"replace",
"(",
"'_redirect'",
",",
"''",
")",
"kwargs",
"=",
"multi_to_dict",
"(",
"request",
".",
"args",
")",
"kwargs",
... | Redirect non lang-prefixed urls to default language. | [
"Redirect",
"non",
"lang",
"-",
"prefixed",
"urls",
"to",
"default",
"language",
"."
] | python | train |
inasafe/inasafe | safe/datastore/geopackage.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/datastore/geopackage.py#L103-L117 | def _vector_layers(self):
"""Return a list of vector layers available.
:return: List of vector layers available in the geopackage.
:rtype: list
.. versionadded:: 4.0
"""
layers = []
vector_datasource = self.vector_driver.Open(
self.uri.absoluteFilePa... | [
"def",
"_vector_layers",
"(",
"self",
")",
":",
"layers",
"=",
"[",
"]",
"vector_datasource",
"=",
"self",
".",
"vector_driver",
".",
"Open",
"(",
"self",
".",
"uri",
".",
"absoluteFilePath",
"(",
")",
")",
"if",
"vector_datasource",
":",
"for",
"i",
"in... | Return a list of vector layers available.
:return: List of vector layers available in the geopackage.
:rtype: list
.. versionadded:: 4.0 | [
"Return",
"a",
"list",
"of",
"vector",
"layers",
"available",
"."
] | python | train |
chainside/btcpy | btcpy/lib/base58.py | https://github.com/chainside/btcpy/blob/8e75c630dacf0f997ed0e0e8739bed428a95d7b1/btcpy/lib/base58.py#L37-L54 | def b58decode(v: str) -> bytes:
'''Decode a Base58 encoded string'''
origlen = len(v)
v = v.lstrip(alphabet[0])
newlen = len(v)
p, acc = 1, 0
for c in v[::-1]:
acc += p * alphabet.index(c)
p *= 58
result = []
while acc > 0:
acc, mod = divmod(acc, 256)
r... | [
"def",
"b58decode",
"(",
"v",
":",
"str",
")",
"->",
"bytes",
":",
"origlen",
"=",
"len",
"(",
"v",
")",
"v",
"=",
"v",
".",
"lstrip",
"(",
"alphabet",
"[",
"0",
"]",
")",
"newlen",
"=",
"len",
"(",
"v",
")",
"p",
",",
"acc",
"=",
"1",
",",... | Decode a Base58 encoded string | [
"Decode",
"a",
"Base58",
"encoded",
"string"
] | python | train |
allenai/allennlp | allennlp/semparse/domain_languages/domain_language.py | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/domain_language.py#L315-L333 | def execute_action_sequence(self, action_sequence: List[str], side_arguments: List[Dict] = None):
"""
Executes the program defined by an action sequence directly, without needing the overhead
of translating to a logical form first. For any given program, :func:`execute` and this
functio... | [
"def",
"execute_action_sequence",
"(",
"self",
",",
"action_sequence",
":",
"List",
"[",
"str",
"]",
",",
"side_arguments",
":",
"List",
"[",
"Dict",
"]",
"=",
"None",
")",
":",
"# We'll strip off the first action, because it doesn't matter for execution.",
"first_actio... | Executes the program defined by an action sequence directly, without needing the overhead
of translating to a logical form first. For any given program, :func:`execute` and this
function are equivalent, they just take different representations of the program, so you
can use whichever is more ef... | [
"Executes",
"the",
"program",
"defined",
"by",
"an",
"action",
"sequence",
"directly",
"without",
"needing",
"the",
"overhead",
"of",
"translating",
"to",
"a",
"logical",
"form",
"first",
".",
"For",
"any",
"given",
"program",
":",
"func",
":",
"execute",
"a... | python | train |
aparo/pyes | pyes/managers.py | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/managers.py#L610-L619 | def nodes_info(self, nodes=None):
"""
The cluster :ref:`nodes info <es-guide-reference-api-admin-cluster-state>` API allows to retrieve one or more (or all) of
the cluster nodes information.
"""
parts = ["_cluster", "nodes"]
if nodes:
parts.append(",".join(nod... | [
"def",
"nodes_info",
"(",
"self",
",",
"nodes",
"=",
"None",
")",
":",
"parts",
"=",
"[",
"\"_cluster\"",
",",
"\"nodes\"",
"]",
"if",
"nodes",
":",
"parts",
".",
"append",
"(",
"\",\"",
".",
"join",
"(",
"nodes",
")",
")",
"path",
"=",
"make_path",
... | The cluster :ref:`nodes info <es-guide-reference-api-admin-cluster-state>` API allows to retrieve one or more (or all) of
the cluster nodes information. | [
"The",
"cluster",
":",
"ref",
":",
"nodes",
"info",
"<es",
"-",
"guide",
"-",
"reference",
"-",
"api",
"-",
"admin",
"-",
"cluster",
"-",
"state",
">",
"API",
"allows",
"to",
"retrieve",
"one",
"or",
"more",
"(",
"or",
"all",
")",
"of",
"the",
"clu... | python | train |
gem/oq-engine | openquake/hazardlib/gsim/cauzzi_2014.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/cauzzi_2014.py#L132-L136 | def _get_distance_scaling_term(self, C, mag, rrup):
"""
Returns the distance scaling parameter
"""
return (C["r1"] + C["r2"] * mag) * np.log10(rrup + C["r3"]) | [
"def",
"_get_distance_scaling_term",
"(",
"self",
",",
"C",
",",
"mag",
",",
"rrup",
")",
":",
"return",
"(",
"C",
"[",
"\"r1\"",
"]",
"+",
"C",
"[",
"\"r2\"",
"]",
"*",
"mag",
")",
"*",
"np",
".",
"log10",
"(",
"rrup",
"+",
"C",
"[",
"\"r3\"",
... | Returns the distance scaling parameter | [
"Returns",
"the",
"distance",
"scaling",
"parameter"
] | python | train |
wal-e/wal-e | wal_e/operator/backup.py | https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/operator/backup.py#L248-L291 | def wal_archive(self, wal_path, concurrency=1):
"""
Uploads a WAL file to S3 or Windows Azure Blob Service
This code is intended to typically be called from Postgres's
archive_command feature.
"""
# Upload the segment expressly indicated. It's special
# relativ... | [
"def",
"wal_archive",
"(",
"self",
",",
"wal_path",
",",
"concurrency",
"=",
"1",
")",
":",
"# Upload the segment expressly indicated. It's special",
"# relative to other uploads when parallel wal-push is enabled,",
"# in that it's not desirable to tweak its .ready/.done files",
"# in... | Uploads a WAL file to S3 or Windows Azure Blob Service
This code is intended to typically be called from Postgres's
archive_command feature. | [
"Uploads",
"a",
"WAL",
"file",
"to",
"S3",
"or",
"Windows",
"Azure",
"Blob",
"Service"
] | python | train |
inveniosoftware/invenio-pidrelations | invenio_pidrelations/serializers/schemas.py | https://github.com/inveniosoftware/invenio-pidrelations/blob/a49f3725cf595b663c5b04814280b231f88bc333/invenio_pidrelations/serializers/schemas.py#L68-L71 | def dump_previous(self, obj):
"""Dump the parent of a PID."""
if self._is_child(obj) and obj.index(self.context['pid']) > 0:
return self._dump_relative(obj.previous_child(self.context['pid'])) | [
"def",
"dump_previous",
"(",
"self",
",",
"obj",
")",
":",
"if",
"self",
".",
"_is_child",
"(",
"obj",
")",
"and",
"obj",
".",
"index",
"(",
"self",
".",
"context",
"[",
"'pid'",
"]",
")",
">",
"0",
":",
"return",
"self",
".",
"_dump_relative",
"("... | Dump the parent of a PID. | [
"Dump",
"the",
"parent",
"of",
"a",
"PID",
"."
] | python | train |
audreyr/design | design/clouds.py | https://github.com/audreyr/design/blob/3bc801dceeadfa4935a1a17f4083fbe09a03cbac/design/clouds.py#L22-L31 | def draw_circle(ctx, x, y, radius, cairo_color):
"""
Draw a circle.
:param radius: radius in pixels
:param cairo_color: normalized rgb color
"""
ctx.new_path()
ctx.set_source_rgb(cairo_color.red, cairo_color.green, cairo_color.blue)
ctx.arc(x, y, radius, 0, 2 * pi)
ctx.fill() | [
"def",
"draw_circle",
"(",
"ctx",
",",
"x",
",",
"y",
",",
"radius",
",",
"cairo_color",
")",
":",
"ctx",
".",
"new_path",
"(",
")",
"ctx",
".",
"set_source_rgb",
"(",
"cairo_color",
".",
"red",
",",
"cairo_color",
".",
"green",
",",
"cairo_color",
"."... | Draw a circle.
:param radius: radius in pixels
:param cairo_color: normalized rgb color | [
"Draw",
"a",
"circle",
".",
":",
"param",
"radius",
":",
"radius",
"in",
"pixels",
":",
"param",
"cairo_color",
":",
"normalized",
"rgb",
"color"
] | python | train |
vertexproject/synapse | synapse/lib/link.py | https://github.com/vertexproject/synapse/blob/22e67c5a8f6d7caddbcf34b39ab1bd2d6c4a6e0b/synapse/lib/link.py#L49-L55 | async def unixconnect(path):
'''
Connect to a PF_UNIX server listening on the given path.
'''
reader, writer = await asyncio.open_unix_connection(path=path)
info = {'path': path, 'unix': True}
return await Link.anit(reader, writer, info=info) | [
"async",
"def",
"unixconnect",
"(",
"path",
")",
":",
"reader",
",",
"writer",
"=",
"await",
"asyncio",
".",
"open_unix_connection",
"(",
"path",
"=",
"path",
")",
"info",
"=",
"{",
"'path'",
":",
"path",
",",
"'unix'",
":",
"True",
"}",
"return",
"awa... | Connect to a PF_UNIX server listening on the given path. | [
"Connect",
"to",
"a",
"PF_UNIX",
"server",
"listening",
"on",
"the",
"given",
"path",
"."
] | python | train |
StefanKopieczek/ticker | ticker/ticker_parsers.py | https://github.com/StefanKopieczek/ticker/blob/6dcc1bf8f55bf8612986833097531ecf021b687c/ticker/ticker_parsers.py#L19-L29 | def parse_float(float_str):
"""Parse a string of the form 305.48b into a Python float.
The terminal letter, if present, indicates e.g. billions."""
factor = __get_factor(float_str)
if factor != 1:
float_str = float_str[:-1]
try:
return float(float_str.replace(',', '')) * factor
... | [
"def",
"parse_float",
"(",
"float_str",
")",
":",
"factor",
"=",
"__get_factor",
"(",
"float_str",
")",
"if",
"factor",
"!=",
"1",
":",
"float_str",
"=",
"float_str",
"[",
":",
"-",
"1",
"]",
"try",
":",
"return",
"float",
"(",
"float_str",
".",
"repla... | Parse a string of the form 305.48b into a Python float.
The terminal letter, if present, indicates e.g. billions. | [
"Parse",
"a",
"string",
"of",
"the",
"form",
"305",
".",
"48b",
"into",
"a",
"Python",
"float",
".",
"The",
"terminal",
"letter",
"if",
"present",
"indicates",
"e",
".",
"g",
".",
"billions",
"."
] | python | train |
minio/minio-py | minio/parsers.py | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/parsers.py#L96-L111 | def get_child_text(self, name, strict=True):
"""Extract text of a child element. If strict, and child element is
not present, raises InvalidXMLError and otherwise returns
None.
"""
if strict:
try:
return self.element.find('s3:{}'.format(name), _S3_NS)... | [
"def",
"get_child_text",
"(",
"self",
",",
"name",
",",
"strict",
"=",
"True",
")",
":",
"if",
"strict",
":",
"try",
":",
"return",
"self",
".",
"element",
".",
"find",
"(",
"'s3:{}'",
".",
"format",
"(",
"name",
")",
",",
"_S3_NS",
")",
".",
"text... | Extract text of a child element. If strict, and child element is
not present, raises InvalidXMLError and otherwise returns
None. | [
"Extract",
"text",
"of",
"a",
"child",
"element",
".",
"If",
"strict",
"and",
"child",
"element",
"is",
"not",
"present",
"raises",
"InvalidXMLError",
"and",
"otherwise",
"returns",
"None",
"."
] | python | train |
arteria/django-hijack | hijack/helpers.py | https://github.com/arteria/django-hijack/blob/64a3a1dd0655d9fee9786d62628add132073b946/hijack/helpers.py#L20-L35 | def no_update_last_login():
"""
Disconnect any signals to update_last_login() for the scope of the context
manager, then restore.
"""
kw = {'receiver': update_last_login}
kw_id = {'receiver': update_last_login, 'dispatch_uid': 'update_last_login'}
was_connected = user_logged_in.disconnect(*... | [
"def",
"no_update_last_login",
"(",
")",
":",
"kw",
"=",
"{",
"'receiver'",
":",
"update_last_login",
"}",
"kw_id",
"=",
"{",
"'receiver'",
":",
"update_last_login",
",",
"'dispatch_uid'",
":",
"'update_last_login'",
"}",
"was_connected",
"=",
"user_logged_in",
".... | Disconnect any signals to update_last_login() for the scope of the context
manager, then restore. | [
"Disconnect",
"any",
"signals",
"to",
"update_last_login",
"()",
"for",
"the",
"scope",
"of",
"the",
"context",
"manager",
"then",
"restore",
"."
] | python | train |
coursera-dl/coursera-dl | coursera/network.py | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/network.py#L12-L58 | def get_reply(session, url, post=False, data=None, headers=None, quiet=False):
"""
Download an HTML page using the requests session. Low-level function
that allows for flexible request configuration.
@param session: Requests session.
@type session: requests.Session
@param url: URL pattern with... | [
"def",
"get_reply",
"(",
"session",
",",
"url",
",",
"post",
"=",
"False",
",",
"data",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"quiet",
"=",
"False",
")",
":",
"request_headers",
"=",
"{",
"}",
"if",
"headers",
"is",
"None",
"else",
"headers"... | Download an HTML page using the requests session. Low-level function
that allows for flexible request configuration.
@param session: Requests session.
@type session: requests.Session
@param url: URL pattern with optional keywords to format.
@type url: str
@param post: Flag that indicates whet... | [
"Download",
"an",
"HTML",
"page",
"using",
"the",
"requests",
"session",
".",
"Low",
"-",
"level",
"function",
"that",
"allows",
"for",
"flexible",
"request",
"configuration",
"."
] | python | train |
genialis/resolwe | resolwe/flow/utils/docs/autoprocess.py | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/utils/docs/autoprocess.py#L121-L148 | def make_field(self, field_name, field_body):
"""Fill content into nodes.
:param string field_name: Field name of the field
:param field_name: Field body if the field
:type field_name: str or instance of docutils.nodes
:return: field instance filled with given name and body
... | [
"def",
"make_field",
"(",
"self",
",",
"field_name",
",",
"field_body",
")",
":",
"name",
"=",
"nodes",
".",
"field_name",
"(",
")",
"name",
"+=",
"nodes",
".",
"Text",
"(",
"field_name",
")",
"paragraph",
"=",
"nodes",
".",
"paragraph",
"(",
")",
"if"... | Fill content into nodes.
:param string field_name: Field name of the field
:param field_name: Field body if the field
:type field_name: str or instance of docutils.nodes
:return: field instance filled with given name and body
:rtype: nodes.field | [
"Fill",
"content",
"into",
"nodes",
"."
] | python | train |
xoolive/traffic | traffic/data/adsb/opensky_impala.py | https://github.com/xoolive/traffic/blob/d1a8878098f16759f6b6e0e8d8b8f32e34a680a8/traffic/data/adsb/opensky_impala.py#L263-L399 | def history(
self,
start: timelike,
stop: Optional[timelike] = None,
*args, # more reasonable to be explicit about arguments
date_delta: timedelta = timedelta(hours=1),
callsign: Union[None, str, Iterable[str]] = None,
icao24: Union[None, str, Iterable[str]] = No... | [
"def",
"history",
"(",
"self",
",",
"start",
":",
"timelike",
",",
"stop",
":",
"Optional",
"[",
"timelike",
"]",
"=",
"None",
",",
"*",
"args",
",",
"# more reasonable to be explicit about arguments",
"date_delta",
":",
"timedelta",
"=",
"timedelta",
"(",
"ho... | Get Traffic from the OpenSky Impala shell.
The method builds appropriate SQL requests, caches results and formats
data into a proper pandas DataFrame. Requests are split by hour (by
default) in case the connection fails.
Args:
start: a string, epoch or datetime
... | [
"Get",
"Traffic",
"from",
"the",
"OpenSky",
"Impala",
"shell",
"."
] | python | train |
adaptive-learning/proso-apps | proso_models/models.py | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_models/models.py#L651-L694 | def get_leaves(self, item_ids=None, language=None, forbidden_item_ids=None):
"""
Get mapping of items to their reachable leaves. Leaves having
inactive relations to other items are omitted.
Args:
item_ids (list): items which are taken as roots for the reachability
... | [
"def",
"get_leaves",
"(",
"self",
",",
"item_ids",
"=",
"None",
",",
"language",
"=",
"None",
",",
"forbidden_item_ids",
"=",
"None",
")",
":",
"forbidden_item_ids",
"=",
"set",
"(",
")",
"if",
"forbidden_item_ids",
"is",
"None",
"else",
"set",
"(",
"forbi... | Get mapping of items to their reachable leaves. Leaves having
inactive relations to other items are omitted.
Args:
item_ids (list): items which are taken as roots for the reachability
language (str): if specified, filter out items which are not
available in the g... | [
"Get",
"mapping",
"of",
"items",
"to",
"their",
"reachable",
"leaves",
".",
"Leaves",
"having",
"inactive",
"relations",
"to",
"other",
"items",
"are",
"omitted",
"."
] | python | train |
wmayner/pyphi | pyphi/models/fmt.py | https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/models/fmt.py#L79-L102 | def indent(lines, amount=2, char=' '):
r"""Indent a string.
Prepends whitespace to every line in the passed string. (Lines are
separated by newline characters.)
Args:
lines (str): The string to indent.
Keyword Args:
amount (int): The number of columns to indent by.
char (s... | [
"def",
"indent",
"(",
"lines",
",",
"amount",
"=",
"2",
",",
"char",
"=",
"' '",
")",
":",
"lines",
"=",
"str",
"(",
"lines",
")",
"padding",
"=",
"amount",
"*",
"char",
"return",
"padding",
"+",
"(",
"'\\n'",
"+",
"padding",
")",
".",
"join",
"(... | r"""Indent a string.
Prepends whitespace to every line in the passed string. (Lines are
separated by newline characters.)
Args:
lines (str): The string to indent.
Keyword Args:
amount (int): The number of columns to indent by.
char (str): The character to to use as the indenta... | [
"r",
"Indent",
"a",
"string",
"."
] | python | train |
decryptus/sonicprobe | sonicprobe/helpers.py | https://github.com/decryptus/sonicprobe/blob/72f73f3a40d2982d79ad68686e36aa31d94b76f8/sonicprobe/helpers.py#L357-L423 | def linesubst(line, variables):
"""
In a string, substitute '{{varname}}' occurrences with the value of
variables['varname'], '\\' being an escaping char...
If at first you don't understand this function, draw its finite state
machine and everything will become crystal clear :)
"""
# trivial... | [
"def",
"linesubst",
"(",
"line",
",",
"variables",
")",
":",
"# trivial no substitution early detection:",
"if",
"'{{'",
"not",
"in",
"line",
"and",
"'\\\\'",
"not",
"in",
"line",
":",
"return",
"line",
"st",
"=",
"NORM",
"out",
"=",
"\"\"",
"curvar",
"=",
... | In a string, substitute '{{varname}}' occurrences with the value of
variables['varname'], '\\' being an escaping char...
If at first you don't understand this function, draw its finite state
machine and everything will become crystal clear :) | [
"In",
"a",
"string",
"substitute",
"{{",
"varname",
"}}",
"occurrences",
"with",
"the",
"value",
"of",
"variables",
"[",
"varname",
"]",
"\\\\",
"being",
"an",
"escaping",
"char",
"...",
"If",
"at",
"first",
"you",
"don",
"t",
"understand",
"this",
"functi... | python | train |
mitsei/dlkit | dlkit/json_/assessment/mixins.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/assessment/mixins.py#L222-L232 | def _update_from_database(self):
"""Updates map to latest state in database.
Should be called prior to major object events to assure that an
assessment being taken on multiple devices are reasonably synchronized.
"""
collection = JSONClientValidated('assessment',
... | [
"def",
"_update_from_database",
"(",
"self",
")",
":",
"collection",
"=",
"JSONClientValidated",
"(",
"'assessment'",
",",
"collection",
"=",
"'AssessmentSection'",
",",
"runtime",
"=",
"self",
".",
"_runtime",
")",
"self",
".",
"_my_map",
"=",
"collection",
"."... | Updates map to latest state in database.
Should be called prior to major object events to assure that an
assessment being taken on multiple devices are reasonably synchronized. | [
"Updates",
"map",
"to",
"latest",
"state",
"in",
"database",
"."
] | python | train |
boriel/zxbasic | api/check.py | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/check.py#L414-L463 | def common_type(a, b):
""" Returns a type which is common for both a and b types.
Returns None if no common types allowed.
"""
from symbols.type_ import SymbolBASICTYPE as BASICTYPE
from symbols.type_ import Type as TYPE
from symbols.type_ import SymbolTYPE
if a is None or b is None:
... | [
"def",
"common_type",
"(",
"a",
",",
"b",
")",
":",
"from",
"symbols",
".",
"type_",
"import",
"SymbolBASICTYPE",
"as",
"BASICTYPE",
"from",
"symbols",
".",
"type_",
"import",
"Type",
"as",
"TYPE",
"from",
"symbols",
".",
"type_",
"import",
"SymbolTYPE",
"... | Returns a type which is common for both a and b types.
Returns None if no common types allowed. | [
"Returns",
"a",
"type",
"which",
"is",
"common",
"for",
"both",
"a",
"and",
"b",
"types",
".",
"Returns",
"None",
"if",
"no",
"common",
"types",
"allowed",
"."
] | python | train |
psss/did | did/stats.py | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/stats.py#L74-L88 | def check(self):
""" Check the stats if enabled. """
if not self.enabled():
return
try:
self.fetch()
except (xmlrpclib.Fault, did.base.ConfigError) as error:
log.error(error)
self._error = True
# Raise the exception if debugging... | [
"def",
"check",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"enabled",
"(",
")",
":",
"return",
"try",
":",
"self",
".",
"fetch",
"(",
")",
"except",
"(",
"xmlrpclib",
".",
"Fault",
",",
"did",
".",
"base",
".",
"ConfigError",
")",
"as",
"er... | Check the stats if enabled. | [
"Check",
"the",
"stats",
"if",
"enabled",
"."
] | python | train |
sass/libsass-python | sassutils/builder.py | https://github.com/sass/libsass-python/blob/fde5b18bc761f0253e71685ee5489e4beb8a403e/sassutils/builder.py#L201-L223 | def unresolve_filename(self, package_dir, filename):
"""Retrieves the probable source path from the output filename. Pass
in a .css path to get out a .scss path.
:param package_dir: the path of the package directory
:type package_dir: :class:`str`
:param filename: the css filen... | [
"def",
"unresolve_filename",
"(",
"self",
",",
"package_dir",
",",
"filename",
")",
":",
"filename",
",",
"_",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"if",
"self",
".",
"strip_extension",
":",
"for",
"ext",
"in",
"(",
"'.scss'",
... | Retrieves the probable source path from the output filename. Pass
in a .css path to get out a .scss path.
:param package_dir: the path of the package directory
:type package_dir: :class:`str`
:param filename: the css filename
:type filename: :class:`str`
:returns: the s... | [
"Retrieves",
"the",
"probable",
"source",
"path",
"from",
"the",
"output",
"filename",
".",
"Pass",
"in",
"a",
".",
"css",
"path",
"to",
"get",
"out",
"a",
".",
"scss",
"path",
"."
] | python | train |
ARMmbed/mbed-cloud-sdk-python | src/mbed_cloud/filters.py | https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/filters.py#L61-L95 | def _normalise_key_values(filter_obj, attr_map=None):
"""Converts nested dictionary filters into django-style key value pairs
Map filter operators and aliases to operator-land
Additionally, perform replacements according to attribute map
Automatically assumes __eq if not explicitly defined
"""
... | [
"def",
"_normalise_key_values",
"(",
"filter_obj",
",",
"attr_map",
"=",
"None",
")",
":",
"new_filter",
"=",
"{",
"}",
"for",
"key",
",",
"constraints",
"in",
"filter_obj",
".",
"items",
"(",
")",
":",
"aliased_key",
"=",
"key",
"if",
"attr_map",
"is",
... | Converts nested dictionary filters into django-style key value pairs
Map filter operators and aliases to operator-land
Additionally, perform replacements according to attribute map
Automatically assumes __eq if not explicitly defined | [
"Converts",
"nested",
"dictionary",
"filters",
"into",
"django",
"-",
"style",
"key",
"value",
"pairs"
] | python | train |
Azure/azure-event-hubs-python | azure/eventprocessorhost/partition_context.py | https://github.com/Azure/azure-event-hubs-python/blob/737c5f966557ada2cf10fa0d8f3c19671ae96348/azure/eventprocessorhost/partition_context.py#L76-L100 | async def checkpoint_async_event_data(self, event_data, event_processor_context=None):
"""
Stores the offset and sequenceNumber from the provided received EventData instance,
then writes those values to the checkpoint store via the checkpoint manager.
Optionally stores the state of the E... | [
"async",
"def",
"checkpoint_async_event_data",
"(",
"self",
",",
"event_data",
",",
"event_processor_context",
"=",
"None",
")",
":",
"if",
"not",
"event_data",
":",
"raise",
"ValueError",
"(",
"\"event_data\"",
")",
"if",
"event_data",
".",
"sequence_number",
">"... | Stores the offset and sequenceNumber from the provided received EventData instance,
then writes those values to the checkpoint store via the checkpoint manager.
Optionally stores the state of the Event Processor along the checkpoint.
:param event_data: A received EventData with valid offset and... | [
"Stores",
"the",
"offset",
"and",
"sequenceNumber",
"from",
"the",
"provided",
"received",
"EventData",
"instance",
"then",
"writes",
"those",
"values",
"to",
"the",
"checkpoint",
"store",
"via",
"the",
"checkpoint",
"manager",
".",
"Optionally",
"stores",
"the",
... | python | train |
saltant-org/saltant-py | saltant/models/base_task_instance.py | https://github.com/saltant-org/saltant-py/blob/bf3bdbc4ec9c772c7f621f8bd6a76c5932af68be/saltant/models/base_task_instance.py#L312-L338 | def wait_until_finished(
self, uuid, refresh_period=DEFAULT_TASK_INSTANCE_WAIT_REFRESH_PERIOD
):
"""Wait until a task instance with the given UUID is finished.
Args:
uuid (str): The UUID of the task instance to wait for.
refresh_period (float, optional): How many sec... | [
"def",
"wait_until_finished",
"(",
"self",
",",
"uuid",
",",
"refresh_period",
"=",
"DEFAULT_TASK_INSTANCE_WAIT_REFRESH_PERIOD",
")",
":",
"# Wait for the task to finish",
"task_instance",
"=",
"self",
".",
"get",
"(",
"uuid",
")",
"while",
"task_instance",
".",
"stat... | Wait until a task instance with the given UUID is finished.
Args:
uuid (str): The UUID of the task instance to wait for.
refresh_period (float, optional): How many seconds to wait
in between checking the task's status. Defaults to 5
seconds.
Retu... | [
"Wait",
"until",
"a",
"task",
"instance",
"with",
"the",
"given",
"UUID",
"is",
"finished",
"."
] | python | train |
msmbuilder/msmbuilder | msmbuilder/msm/_metzner_mcmc_slow.py | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/msm/_metzner_mcmc_slow.py#L5-L99 | def metzner_mcmc_slow(Z, n_samples, n_thin=1, random_state=None):
"""Metropolis Markov chain Monte Carlo sampler for reversible transition
matrices
Parameters
----------
Z : np.array, shape=(n_states, n_states)
The effective count matrix, the number of observed transitions
between s... | [
"def",
"metzner_mcmc_slow",
"(",
"Z",
",",
"n_samples",
",",
"n_thin",
"=",
"1",
",",
"random_state",
"=",
"None",
")",
":",
"# Upper and lower bounds on the sum of the K matrix, to ensure proper",
"# proposal weights. See Eq. 17 of [1].",
"K_MINUS",
"=",
"0.9",
"K_PLUS",
... | Metropolis Markov chain Monte Carlo sampler for reversible transition
matrices
Parameters
----------
Z : np.array, shape=(n_states, n_states)
The effective count matrix, the number of observed transitions
between states plus the number of prior counts
n_samples : int
Number ... | [
"Metropolis",
"Markov",
"chain",
"Monte",
"Carlo",
"sampler",
"for",
"reversible",
"transition",
"matrices"
] | python | train |
fastai/fastai | fastai/callback.py | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callback.py#L36-L42 | def new_with_params(self, param_groups:Collection[Collection[nn.Parameter]]):
"Create a new `OptimWrapper` from `self` with another `layer_groups` but the same hyper-parameters."
opt_func = getattr(self, 'opt_func', self.opt.__class__)
opt = opt_func([{'params': p, 'lr':0} for p in param_groups]... | [
"def",
"new_with_params",
"(",
"self",
",",
"param_groups",
":",
"Collection",
"[",
"Collection",
"[",
"nn",
".",
"Parameter",
"]",
"]",
")",
":",
"opt_func",
"=",
"getattr",
"(",
"self",
",",
"'opt_func'",
",",
"self",
".",
"opt",
".",
"__class__",
")",... | Create a new `OptimWrapper` from `self` with another `layer_groups` but the same hyper-parameters. | [
"Create",
"a",
"new",
"OptimWrapper",
"from",
"self",
"with",
"another",
"layer_groups",
"but",
"the",
"same",
"hyper",
"-",
"parameters",
"."
] | python | train |
cocagne/txdbus | doc/examples/fd_server.py | https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/doc/examples/fd_server.py#L46-L53 | def dbus_lenFD(self, fd):
"""
Returns the byte count after reading till EOF.
"""
f = os.fdopen(fd, 'rb')
result = len(f.read())
f.close()
return result | [
"def",
"dbus_lenFD",
"(",
"self",
",",
"fd",
")",
":",
"f",
"=",
"os",
".",
"fdopen",
"(",
"fd",
",",
"'rb'",
")",
"result",
"=",
"len",
"(",
"f",
".",
"read",
"(",
")",
")",
"f",
".",
"close",
"(",
")",
"return",
"result"
] | Returns the byte count after reading till EOF. | [
"Returns",
"the",
"byte",
"count",
"after",
"reading",
"till",
"EOF",
"."
] | python | train |
Autodesk/cryptorito | cryptorito/__init__.py | https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L252-L260 | def has_gpg_key(fingerprint):
"""Checks to see if we have this gpg fingerprint"""
if len(fingerprint) > 8:
fingerprint = fingerprint[-8:]
fingerprint = fingerprint.upper()
cmd = flatten([gnupg_bin(), gnupg_home(), "--list-public-keys"])
lines = stderr_output(cmd).split('\n')
return len(... | [
"def",
"has_gpg_key",
"(",
"fingerprint",
")",
":",
"if",
"len",
"(",
"fingerprint",
")",
">",
"8",
":",
"fingerprint",
"=",
"fingerprint",
"[",
"-",
"8",
":",
"]",
"fingerprint",
"=",
"fingerprint",
".",
"upper",
"(",
")",
"cmd",
"=",
"flatten",
"(",
... | Checks to see if we have this gpg fingerprint | [
"Checks",
"to",
"see",
"if",
"we",
"have",
"this",
"gpg",
"fingerprint"
] | python | train |
openego/ding0 | ding0/core/__init__.py | https://github.com/openego/ding0/blob/e2d6528f96255e4bb22ba15514a4f1883564ed5d/ding0/core/__init__.py#L270-L325 | def get_mvgd_lvla_lvgd_obj_from_id(self):
""" Build dict with mapping from LVLoadAreaDing0 id to LVLoadAreaDing0 object,
MVGridDistrictDing0 id to MVGridDistrictDing0 object,
LVGridDistrictDing0 id to LVGridDistrictDing0 object an... | [
"def",
"get_mvgd_lvla_lvgd_obj_from_id",
"(",
"self",
")",
":",
"mv_grid_districts_dict",
"=",
"{",
"}",
"lv_load_areas_dict",
"=",
"{",
"}",
"lv_grid_districts_dict",
"=",
"{",
"}",
"lv_stations_dict",
"=",
"{",
"}",
"for",
"mv_grid_district",
"in",
"self",
".",
... | Build dict with mapping from LVLoadAreaDing0 id to LVLoadAreaDing0 object,
MVGridDistrictDing0 id to MVGridDistrictDing0 object,
LVGridDistrictDing0 id to LVGridDistrictDing0 object and
LVStationDi... | [
"Build",
"dict",
"with",
"mapping",
"from",
"LVLoadAreaDing0",
"id",
"to",
"LVLoadAreaDing0",
"object",
"MVGridDistrictDing0",
"id",
"to",
"MVGridDistrictDing0",
"object",
"LVGridDistrictDing0",
"id",
"to",
"LVGridDistrictDing0",
"object",
"and",
"LVStationDing0",
"id",
... | python | train |
DarkEnergySurvey/ugali | ugali/scratch/simulation/survey_selection_function.py | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/scratch/simulation/survey_selection_function.py#L117-L132 | def meanFracdet(map_fracdet, lon_population, lat_population, radius_population):
"""
Compute the mean fracdet within circular aperture (radius specified in decimal degrees)
lon, lat, and radius are taken to be arrays of the same length
"""
nside_fracdet = hp.npix2nside(len(map_fracdet))
map_fra... | [
"def",
"meanFracdet",
"(",
"map_fracdet",
",",
"lon_population",
",",
"lat_population",
",",
"radius_population",
")",
":",
"nside_fracdet",
"=",
"hp",
".",
"npix2nside",
"(",
"len",
"(",
"map_fracdet",
")",
")",
"map_fracdet_zero",
"=",
"np",
".",
"where",
"(... | Compute the mean fracdet within circular aperture (radius specified in decimal degrees)
lon, lat, and radius are taken to be arrays of the same length | [
"Compute",
"the",
"mean",
"fracdet",
"within",
"circular",
"aperture",
"(",
"radius",
"specified",
"in",
"decimal",
"degrees",
")"
] | python | train |
kerrickstaley/genanki | genanki/model.py | https://github.com/kerrickstaley/genanki/blob/624a9ffaf2f7868721cf7e7e55f53b238df9a04a/genanki/model.py#L27-L78 | def _req(self):
"""
List of required fields for each template. Format is [tmpl_idx, "all"|"any", [req_field_1, req_field_2, ...]].
Partial reimplementation of req computing logic from Anki. We use pystache instead of Anki's custom mustache
implementation.
The goal is to figure out which fields are... | [
"def",
"_req",
"(",
"self",
")",
":",
"sentinel",
"=",
"'SeNtInEl'",
"field_names",
"=",
"[",
"field",
"[",
"'name'",
"]",
"for",
"field",
"in",
"self",
".",
"fields",
"]",
"req",
"=",
"[",
"]",
"for",
"template_ord",
",",
"template",
"in",
"enumerate"... | List of required fields for each template. Format is [tmpl_idx, "all"|"any", [req_field_1, req_field_2, ...]].
Partial reimplementation of req computing logic from Anki. We use pystache instead of Anki's custom mustache
implementation.
The goal is to figure out which fields are "required", i.e. if they ar... | [
"List",
"of",
"required",
"fields",
"for",
"each",
"template",
".",
"Format",
"is",
"[",
"tmpl_idx",
"all",
"|",
"any",
"[",
"req_field_1",
"req_field_2",
"...",
"]]",
"."
] | python | train |
zomux/deepy | deepy/dataset/padding.py | https://github.com/zomux/deepy/blob/090fbad22a08a809b12951cd0d4984f5bd432698/deepy/dataset/padding.py#L7-L17 | def pad_dataset(subset, side="right", length=-1):
"""
Pad data set to specified length.
Parameters:
length - max length, a just to the max length in the batch if length is -1
"""
assert length == -1 or length > 0
if type(subset[0][0][0]) in [float, int, np.int64, np.int32, np.float32]:
... | [
"def",
"pad_dataset",
"(",
"subset",
",",
"side",
"=",
"\"right\"",
",",
"length",
"=",
"-",
"1",
")",
":",
"assert",
"length",
"==",
"-",
"1",
"or",
"length",
">",
"0",
"if",
"type",
"(",
"subset",
"[",
"0",
"]",
"[",
"0",
"]",
"[",
"0",
"]",
... | Pad data set to specified length.
Parameters:
length - max length, a just to the max length in the batch if length is -1 | [
"Pad",
"data",
"set",
"to",
"specified",
"length",
".",
"Parameters",
":",
"length",
"-",
"max",
"length",
"a",
"just",
"to",
"the",
"max",
"length",
"in",
"the",
"batch",
"if",
"length",
"is",
"-",
"1"
] | python | test |
jopohl/urh | src/urh/controller/GeneratorTabController.py | https://github.com/jopohl/urh/blob/2eb33b125c8407964cd1092843cde5010eb88aae/src/urh/controller/GeneratorTabController.py#L499-L517 | def refresh_existing_encodings(self, encodings_from_file):
"""
Refresh existing encodings for messages, when encoding was changed by user in dialog
:return:
"""
update = False
for msg in self.table_model.protocol.messages:
i = next((i for i, d in enumerate(e... | [
"def",
"refresh_existing_encodings",
"(",
"self",
",",
"encodings_from_file",
")",
":",
"update",
"=",
"False",
"for",
"msg",
"in",
"self",
".",
"table_model",
".",
"protocol",
".",
"messages",
":",
"i",
"=",
"next",
"(",
"(",
"i",
"for",
"i",
",",
"d",
... | Refresh existing encodings for messages, when encoding was changed by user in dialog
:return: | [
"Refresh",
"existing",
"encodings",
"for",
"messages",
"when",
"encoding",
"was",
"changed",
"by",
"user",
"in",
"dialog"
] | python | train |
wmayner/pyphi | pyphi/jsonify.py | https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/jsonify.py#L233-L248 | def _load_model(self, dct):
"""Load a serialized PyPhi model.
The object is memoized for reuse elsewhere in the object graph.
"""
classname, version, _ = _pop_metadata(dct)
_check_version(version)
cls = self._models[classname]
# Use `from_json` if available
... | [
"def",
"_load_model",
"(",
"self",
",",
"dct",
")",
":",
"classname",
",",
"version",
",",
"_",
"=",
"_pop_metadata",
"(",
"dct",
")",
"_check_version",
"(",
"version",
")",
"cls",
"=",
"self",
".",
"_models",
"[",
"classname",
"]",
"# Use `from_json` if a... | Load a serialized PyPhi model.
The object is memoized for reuse elsewhere in the object graph. | [
"Load",
"a",
"serialized",
"PyPhi",
"model",
"."
] | python | train |
Alignak-monitoring/alignak | alignak/dispatcher.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/dispatcher.py#L946-L976 | def stop_request(self, stop_now=False):
"""Send a stop request to all the daemons
:param stop_now: stop now or go to stop wait mode
:type stop_now: bool
:return: True if all daemons are reachable
"""
all_ok = True
for daemon_link in self.all_daemons_links:
... | [
"def",
"stop_request",
"(",
"self",
",",
"stop_now",
"=",
"False",
")",
":",
"all_ok",
"=",
"True",
"for",
"daemon_link",
"in",
"self",
".",
"all_daemons_links",
":",
"logger",
".",
"debug",
"(",
"\"Stopping: %s (%s)\"",
",",
"daemon_link",
",",
"stop_now",
... | Send a stop request to all the daemons
:param stop_now: stop now or go to stop wait mode
:type stop_now: bool
:return: True if all daemons are reachable | [
"Send",
"a",
"stop",
"request",
"to",
"all",
"the",
"daemons"
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.