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 |
|---|---|---|---|---|---|---|---|---|
singularityhub/singularity-cli | spython/oci/cmd/actions.py | https://github.com/singularityhub/singularity-cli/blob/cb36b4504812ca87e29c6a40b222a545d1865799/spython/oci/cmd/actions.py#L12-L37 | def run(self, bundle,
container_id=None,
log_path=None,
pid_file=None,
log_format="kubernetes"):
''' run is a wrapper to create, start, attach, and delete a container.
Equivalent command line example:
singularity oci run -b ~/bundle m... | [
"def",
"run",
"(",
"self",
",",
"bundle",
",",
"container_id",
"=",
"None",
",",
"log_path",
"=",
"None",
",",
"pid_file",
"=",
"None",
",",
"log_format",
"=",
"\"kubernetes\"",
")",
":",
"return",
"self",
".",
"_run",
"(",
"bundle",
",",
"container_id",... | run is a wrapper to create, start, attach, and delete a container.
Equivalent command line example:
singularity oci run -b ~/bundle mycontainer
Parameters
==========
bundle: the full path to the bundle folder
container_id: an optional container_id. If not provid... | [
"run",
"is",
"a",
"wrapper",
"to",
"create",
"start",
"attach",
"and",
"delete",
"a",
"container",
"."
] | python | train |
tjcsl/cslbot | cslbot/commands/tjbash.py | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/tjbash.py#L29-L63 | def cmd(send, msg, _):
"""Finds a random quote from tjbash.org given search criteria.
Syntax: {command} [searchstring]
"""
if not msg:
url = 'http://tjbash.org/random1.html'
params = {}
else:
targs = msg.split()
if len(targs) == 1 and targs[0].isnumeric():
... | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"_",
")",
":",
"if",
"not",
"msg",
":",
"url",
"=",
"'http://tjbash.org/random1.html'",
"params",
"=",
"{",
"}",
"else",
":",
"targs",
"=",
"msg",
".",
"split",
"(",
")",
"if",
"len",
"(",
"targs",
")",
... | Finds a random quote from tjbash.org given search criteria.
Syntax: {command} [searchstring] | [
"Finds",
"a",
"random",
"quote",
"from",
"tjbash",
".",
"org",
"given",
"search",
"criteria",
"."
] | python | train |
numenta/nupic | src/nupic/regions/tm_region.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/regions/tm_region.py#L721-L743 | def setParameter(self, parameterName, index, parameterValue):
"""
Overrides :meth:`~nupic.bindings.regions.PyRegion.PyRegion.setParameter`.
"""
if parameterName in self._temporalArgNames:
setattr(self._tfdr, parameterName, parameterValue)
elif parameterName == "logPathOutput":
self.logP... | [
"def",
"setParameter",
"(",
"self",
",",
"parameterName",
",",
"index",
",",
"parameterValue",
")",
":",
"if",
"parameterName",
"in",
"self",
".",
"_temporalArgNames",
":",
"setattr",
"(",
"self",
".",
"_tfdr",
",",
"parameterName",
",",
"parameterValue",
")",... | Overrides :meth:`~nupic.bindings.regions.PyRegion.PyRegion.setParameter`. | [
"Overrides",
":",
"meth",
":",
"~nupic",
".",
"bindings",
".",
"regions",
".",
"PyRegion",
".",
"PyRegion",
".",
"setParameter",
"."
] | python | valid |
minhhoit/yacms | yacms/utils/models.py | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/utils/models.py#L81-L91 | def upload_to(field_path, default):
"""
Used as the ``upload_to`` arg for file fields - allows for custom
handlers to be implemented on a per field basis defined by the
``UPLOAD_TO_HANDLERS`` setting.
"""
from yacms.conf import settings
for k, v in settings.UPLOAD_TO_HANDLERS.items():
... | [
"def",
"upload_to",
"(",
"field_path",
",",
"default",
")",
":",
"from",
"yacms",
".",
"conf",
"import",
"settings",
"for",
"k",
",",
"v",
"in",
"settings",
".",
"UPLOAD_TO_HANDLERS",
".",
"items",
"(",
")",
":",
"if",
"k",
".",
"lower",
"(",
")",
"=... | Used as the ``upload_to`` arg for file fields - allows for custom
handlers to be implemented on a per field basis defined by the
``UPLOAD_TO_HANDLERS`` setting. | [
"Used",
"as",
"the",
"upload_to",
"arg",
"for",
"file",
"fields",
"-",
"allows",
"for",
"custom",
"handlers",
"to",
"be",
"implemented",
"on",
"a",
"per",
"field",
"basis",
"defined",
"by",
"the",
"UPLOAD_TO_HANDLERS",
"setting",
"."
] | python | train |
jameslyons/pycipher | pycipher/m209.py | https://github.com/jameslyons/pycipher/blob/8f1d7cf3cba4e12171e27d9ce723ad890194de19/pycipher/m209.py#L59-L90 | def encipher(self,message):
"""Encipher string using M209 cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example (continuing from the example above)::
ciphertext = m.encipher(plaintext)
:param string: The str... | [
"def",
"encipher",
"(",
"self",
",",
"message",
")",
":",
"message",
"=",
"self",
".",
"remove_punctuation",
"(",
"message",
")",
"effective_ch",
"=",
"[",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
"]",
"# these are the wheels ... | Encipher string using M209 cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example (continuing from the example above)::
ciphertext = m.encipher(plaintext)
:param string: The string to encipher.
:returns: The ... | [
"Encipher",
"string",
"using",
"M209",
"cipher",
"according",
"to",
"initialised",
"key",
".",
"Punctuation",
"and",
"whitespace",
"are",
"removed",
"from",
"the",
"input",
"."
] | python | train |
lowandrew/OLCTools | coreGenome/annotate.py | https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/coreGenome/annotate.py#L89-L106 | def headerthreads(self):
"""
The contig ID must be twenty characters or fewer. The names of the headers created following SPAdes assembly
are usually far too long. This renames them as the sample name
"""
# Create and start threads
for i in range(self.cpus):
#... | [
"def",
"headerthreads",
"(",
"self",
")",
":",
"# Create and start threads",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"cpus",
")",
":",
"# Send the threads to the appropriate destination function",
"threads",
"=",
"Thread",
"(",
"target",
"=",
"self",
".",
"he... | The contig ID must be twenty characters or fewer. The names of the headers created following SPAdes assembly
are usually far too long. This renames them as the sample name | [
"The",
"contig",
"ID",
"must",
"be",
"twenty",
"characters",
"or",
"fewer",
".",
"The",
"names",
"of",
"the",
"headers",
"created",
"following",
"SPAdes",
"assembly",
"are",
"usually",
"far",
"too",
"long",
".",
"This",
"renames",
"them",
"as",
"the",
"sam... | python | train |
spacetelescope/pysynphot | pysynphot/units.py | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/units.py#L1717-L1725 | def unitResponse(self,band):
"""This is used internally for :ref:`pysynphot-formula-effstim`
calculations."""
#sumfilt(wave,-1,band)
# SUMFILT = Sum [ FILT(I) * WAVE(I) ** NPOW * DWAVE(I) ]
wave=band.wave
total = band.trapezoidIntegration(wave,band.throughput/wave)
... | [
"def",
"unitResponse",
"(",
"self",
",",
"band",
")",
":",
"#sumfilt(wave,-1,band)",
"# SUMFILT = Sum [ FILT(I) * WAVE(I) ** NPOW * DWAVE(I) ]",
"wave",
"=",
"band",
".",
"wave",
"total",
"=",
"band",
".",
"trapezoidIntegration",
"(",
"wave",
",",
"band",
".",
"thro... | This is used internally for :ref:`pysynphot-formula-effstim`
calculations. | [
"This",
"is",
"used",
"internally",
"for",
":",
"ref",
":",
"pysynphot",
"-",
"formula",
"-",
"effstim",
"calculations",
"."
] | python | train |
johnnoone/aioconsul | aioconsul/client/services_endpoint.py | https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/services_endpoint.py#L118-L133 | async def deregister(self, service):
"""Deregisters a local service
Parameters:
service (ObjectID): Service ID
Returns:
bool: ``True`` on success
The deregister endpoint is used to remove a service from the local
agent. The agent will take care of deregi... | [
"async",
"def",
"deregister",
"(",
"self",
",",
"service",
")",
":",
"service_id",
"=",
"extract_attr",
"(",
"service",
",",
"keys",
"=",
"[",
"\"ServiceID\"",
",",
"\"ID\"",
"]",
")",
"response",
"=",
"await",
"self",
".",
"_api",
".",
"get",
"(",
"\"... | Deregisters a local service
Parameters:
service (ObjectID): Service ID
Returns:
bool: ``True`` on success
The deregister endpoint is used to remove a service from the local
agent. The agent will take care of deregistering the service with the
Catalog. If... | [
"Deregisters",
"a",
"local",
"service"
] | python | train |
numenta/nupic | src/nupic/swarming/model_chooser.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/model_chooser.py#L66-L111 | def updateResultsForJob(self, forceUpdate=True):
""" Chooses the best model for a given job.
Parameters
-----------------------------------------------------------------------
forceUpdate: (True/False). If True, the update will ignore all the
restrictions on the minimum time to updat... | [
"def",
"updateResultsForJob",
"(",
"self",
",",
"forceUpdate",
"=",
"True",
")",
":",
"updateInterval",
"=",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"_lastUpdateAttemptTime",
"if",
"updateInterval",
"<",
"self",
".",
"_MIN_UPDATE_INTERVAL",
"and",
"no... | Chooses the best model for a given job.
Parameters
-----------------------------------------------------------------------
forceUpdate: (True/False). If True, the update will ignore all the
restrictions on the minimum time to update and the minimum
number of records to ... | [
"Chooses",
"the",
"best",
"model",
"for",
"a",
"given",
"job",
"."
] | python | valid |
twisted/mantissa | xmantissa/webapp.py | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/webapp.py#L216-L223 | def render_applicationNavigation(self, ctx, data):
"""
Add primary application navigation to the given tag.
@see L{xmantissa.webnav.applicationNavigation}
"""
return applicationNavigation(
ctx, self.translator, self.pageComponents.navigation) | [
"def",
"render_applicationNavigation",
"(",
"self",
",",
"ctx",
",",
"data",
")",
":",
"return",
"applicationNavigation",
"(",
"ctx",
",",
"self",
".",
"translator",
",",
"self",
".",
"pageComponents",
".",
"navigation",
")"
] | Add primary application navigation to the given tag.
@see L{xmantissa.webnav.applicationNavigation} | [
"Add",
"primary",
"application",
"navigation",
"to",
"the",
"given",
"tag",
"."
] | python | train |
sixty-north/python-transducers | transducer/transducers.py | https://github.com/sixty-north/python-transducers/blob/575357e3a17ff3b4c757967afd396bf0ea042c08/transducer/transducers.py#L486-L495 | def element_at(index):
"""Create a transducer which obtains the item at the specified index."""
if index < 0:
raise IndexError("element_at used with illegal index {}".format(index))
def element_at_transducer(reducer):
return ElementAt(reducer, index)
return element_at_transducer | [
"def",
"element_at",
"(",
"index",
")",
":",
"if",
"index",
"<",
"0",
":",
"raise",
"IndexError",
"(",
"\"element_at used with illegal index {}\"",
".",
"format",
"(",
"index",
")",
")",
"def",
"element_at_transducer",
"(",
"reducer",
")",
":",
"return",
"Elem... | Create a transducer which obtains the item at the specified index. | [
"Create",
"a",
"transducer",
"which",
"obtains",
"the",
"item",
"at",
"the",
"specified",
"index",
"."
] | python | train |
viniciuschiele/flask-apscheduler | flask_apscheduler/api.py | https://github.com/viniciuschiele/flask-apscheduler/blob/cc52c39e1948c4e8de5da0d01db45f1779f61997/flask_apscheduler/api.py#L113-L123 | def resume_job(job_id):
"""Resumes a job."""
try:
current_app.apscheduler.resume_job(job_id)
job = current_app.apscheduler.get_job(job_id)
return jsonify(job)
except JobLookupError:
return jsonify(dict(error_message='Job %s not found' % job_id), status=404)
except Except... | [
"def",
"resume_job",
"(",
"job_id",
")",
":",
"try",
":",
"current_app",
".",
"apscheduler",
".",
"resume_job",
"(",
"job_id",
")",
"job",
"=",
"current_app",
".",
"apscheduler",
".",
"get_job",
"(",
"job_id",
")",
"return",
"jsonify",
"(",
"job",
")",
"... | Resumes a job. | [
"Resumes",
"a",
"job",
"."
] | python | train |
quantopian/pyfolio | pyfolio/plotting.py | https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/plotting.py#L1672-L1725 | def plot_monthly_returns_timeseries(returns, ax=None, **kwargs):
"""
Plots monthly returns as a timeseries.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
ax : matplotlib.Axes, opti... | [
"def",
"plot_monthly_returns_timeseries",
"(",
"returns",
",",
"ax",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"cumulate_returns",
"(",
"x",
")",
":",
"return",
"ep",
".",
"cum_returns",
"(",
"x",
")",
"[",
"-",
"1",
"]",
"if",
"ax",
"is... | Plots monthly returns as a timeseries.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
ax : matplotlib.Axes, optional
Axes upon which to plot.
**kwargs, optional
Passed t... | [
"Plots",
"monthly",
"returns",
"as",
"a",
"timeseries",
"."
] | python | valid |
awslabs/sockeye | sockeye/inference.py | https://github.com/awslabs/sockeye/blob/5d64a1ee1ef3cbba17c6d1d94bc061020c43f6ab/sockeye/inference.py#L681-L708 | def chunks(self, chunk_size: int) -> Generator['TranslatorInput', None, None]:
"""
Takes a TranslatorInput (itself) and yields TranslatorInputs for chunks of size chunk_size.
:param chunk_size: The maximum size of a chunk.
:return: A generator of TranslatorInputs, one for each chunk cre... | [
"def",
"chunks",
"(",
"self",
",",
"chunk_size",
":",
"int",
")",
"->",
"Generator",
"[",
"'TranslatorInput'",
",",
"None",
",",
"None",
"]",
":",
"if",
"len",
"(",
"self",
".",
"tokens",
")",
">",
"chunk_size",
"and",
"self",
".",
"constraints",
"is",... | Takes a TranslatorInput (itself) and yields TranslatorInputs for chunks of size chunk_size.
:param chunk_size: The maximum size of a chunk.
:return: A generator of TranslatorInputs, one for each chunk created. | [
"Takes",
"a",
"TranslatorInput",
"(",
"itself",
")",
"and",
"yields",
"TranslatorInputs",
"for",
"chunks",
"of",
"size",
"chunk_size",
"."
] | python | train |
mitsei/dlkit | dlkit/json_/learning/managers.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/learning/managers.py#L2240-L2260 | def get_proficiency_objective_bank_assignment_session(self, proxy):
"""Gets the ``OsidSession`` associated with assigning proficiencies to objective banks.
arg: proxy (osid.proxy.Proxy): a proxy
return:
(osid.learning.ProficiencyObjectiveBankAssignmentSession
... | [
"def",
"get_proficiency_objective_bank_assignment_session",
"(",
"self",
",",
"proxy",
")",
":",
"if",
"not",
"self",
".",
"supports_proficiency_objective_bank_assignment",
"(",
")",
":",
"raise",
"errors",
".",
"Unimplemented",
"(",
")",
"# pylint: disable=no-member",
... | Gets the ``OsidSession`` associated with assigning proficiencies to objective banks.
arg: proxy (osid.proxy.Proxy): a proxy
return:
(osid.learning.ProficiencyObjectiveBankAssignmentSession
) - a ``ProficiencyObjectiveBankAssignmentSession``
raise: NullArgumen... | [
"Gets",
"the",
"OsidSession",
"associated",
"with",
"assigning",
"proficiencies",
"to",
"objective",
"banks",
"."
] | python | train |
matllubos/django-is-core | is_core/generic_views/__init__.py | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/generic_views/__init__.py#L23-L35 | def redirect_to_login(next, redirect_field_name=REDIRECT_FIELD_NAME):
"""
Redirects the user to the login page, passing the given 'next' page
"""
resolved_url = reverse('IS:login')
login_url_parts = list(urlparse(resolved_url))
if redirect_field_name:
querystring = QueryDict(login_url_p... | [
"def",
"redirect_to_login",
"(",
"next",
",",
"redirect_field_name",
"=",
"REDIRECT_FIELD_NAME",
")",
":",
"resolved_url",
"=",
"reverse",
"(",
"'IS:login'",
")",
"login_url_parts",
"=",
"list",
"(",
"urlparse",
"(",
"resolved_url",
")",
")",
"if",
"redirect_field... | Redirects the user to the login page, passing the given 'next' page | [
"Redirects",
"the",
"user",
"to",
"the",
"login",
"page",
"passing",
"the",
"given",
"next",
"page"
] | python | train |
bykof/billomapy | billomapy/billomapy.py | https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L1281-L1296 | def get_all_invoice_payments(self, params=None):
"""
Get all invoice payments
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param params: search params
:return: list
... | [
"def",
"get_all_invoice_payments",
"(",
"self",
",",
"params",
"=",
"None",
")",
":",
"if",
"not",
"params",
":",
"params",
"=",
"{",
"}",
"return",
"self",
".",
"_iterate_through_pages",
"(",
"get_function",
"=",
"self",
".",
"get_invoice_payments_per_page",
... | Get all invoice payments
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param params: search params
:return: list | [
"Get",
"all",
"invoice",
"payments",
"This",
"will",
"iterate",
"over",
"all",
"pages",
"until",
"it",
"gets",
"all",
"elements",
".",
"So",
"if",
"the",
"rate",
"limit",
"exceeded",
"it",
"will",
"throw",
"an",
"Exception",
"and",
"you",
"will",
"get",
... | python | train |
adafruit/Adafruit_Python_GPIO | Adafruit_GPIO/GPIO.py | https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/GPIO.py#L341-L348 | def cleanup(self, pin=None):
"""Clean up GPIO event detection for specific pin, or all pins if none
is specified.
"""
if pin is None:
self.bbio_gpio.cleanup()
else:
self.bbio_gpio.cleanup(pin) | [
"def",
"cleanup",
"(",
"self",
",",
"pin",
"=",
"None",
")",
":",
"if",
"pin",
"is",
"None",
":",
"self",
".",
"bbio_gpio",
".",
"cleanup",
"(",
")",
"else",
":",
"self",
".",
"bbio_gpio",
".",
"cleanup",
"(",
"pin",
")"
] | Clean up GPIO event detection for specific pin, or all pins if none
is specified. | [
"Clean",
"up",
"GPIO",
"event",
"detection",
"for",
"specific",
"pin",
"or",
"all",
"pins",
"if",
"none",
"is",
"specified",
"."
] | python | valid |
arve0/microscopestitching | microscopestitching/stitching.py | https://github.com/arve0/microscopestitching/blob/381a78a1d1dca711e1732193e09d6ff7dce23baa/microscopestitching/stitching.py#L16-L37 | def calc_translations_parallel(images):
"""Calculate image translations in parallel.
Parameters
----------
images : ImageCollection
Images as instance of ImageCollection.
Returns
-------
2d array, (ty, tx)
ty and tx is translation to previous image in respectively
x... | [
"def",
"calc_translations_parallel",
"(",
"images",
")",
":",
"w",
"=",
"Parallel",
"(",
"n_jobs",
"=",
"_CPUS",
")",
"res",
"=",
"w",
"(",
"delayed",
"(",
"images",
".",
"translation",
")",
"(",
"img",
")",
"for",
"img",
"in",
"images",
")",
"# save r... | Calculate image translations in parallel.
Parameters
----------
images : ImageCollection
Images as instance of ImageCollection.
Returns
-------
2d array, (ty, tx)
ty and tx is translation to previous image in respectively
x or y direction. | [
"Calculate",
"image",
"translations",
"in",
"parallel",
"."
] | python | test |
taskcluster/taskcluster-client.py | taskcluster/queue.py | https://github.com/taskcluster/taskcluster-client.py/blob/bcc95217f8bf80bed2ae5885a19fa0035da7ebc9/taskcluster/queue.py#L654-L674 | def listProvisioners(self, *args, **kwargs):
"""
Get a list of all active provisioners
Get all active provisioners.
The term "provisioner" is taken broadly to mean anything with a provisionerId.
This does not necessarily mean there is an associated service performing any
... | [
"def",
"listProvisioners",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_makeApiCall",
"(",
"self",
".",
"funcinfo",
"[",
"\"listProvisioners\"",
"]",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Get a list of all active provisioners
Get all active provisioners.
The term "provisioner" is taken broadly to mean anything with a provisionerId.
This does not necessarily mean there is an associated service performing any
provisioning activity.
The response is paged. If this ... | [
"Get",
"a",
"list",
"of",
"all",
"active",
"provisioners"
] | python | train |
google/grumpy | benchmarks/concurrent.py | https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/benchmarks/concurrent.py#L38-L55 | def _MakeParallelBenchmark(p, work_func, *args):
"""Create and return a benchmark that runs work_func p times in parallel."""
def Benchmark(b): # pylint: disable=missing-docstring
e = threading.Event()
def Target():
e.wait()
for _ in xrange(b.N / p):
work_func(*args)
threads = []
... | [
"def",
"_MakeParallelBenchmark",
"(",
"p",
",",
"work_func",
",",
"*",
"args",
")",
":",
"def",
"Benchmark",
"(",
"b",
")",
":",
"# pylint: disable=missing-docstring",
"e",
"=",
"threading",
".",
"Event",
"(",
")",
"def",
"Target",
"(",
")",
":",
"e",
".... | Create and return a benchmark that runs work_func p times in parallel. | [
"Create",
"and",
"return",
"a",
"benchmark",
"that",
"runs",
"work_func",
"p",
"times",
"in",
"parallel",
"."
] | python | valid |
Phyks/libbmc | libbmc/bibtex.py | https://github.com/Phyks/libbmc/blob/9ef1a29d2514157d1edd6c13ecbd61b07ae9315e/libbmc/bibtex.py#L65-L83 | def edit(filename, identifier, data):
"""
Update an entry in a BibTeX file.
:param filename: The name of the BibTeX file to edit.
:param identifier: The id of the entry to update, in the BibTeX file.
:param data: A dict associating fields and updated values. Fields present \
in the BibT... | [
"def",
"edit",
"(",
"filename",
",",
"identifier",
",",
"data",
")",
":",
"# Get current bibtex",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"fh",
":",
"bibtex",
"=",
"bibtexparser",
".",
"load",
"(",
"fh",
")",
"# Update it",
"# TODO: Not wor... | Update an entry in a BibTeX file.
:param filename: The name of the BibTeX file to edit.
:param identifier: The id of the entry to update, in the BibTeX file.
:param data: A dict associating fields and updated values. Fields present \
in the BibTeX file but not in this dict will be kept as is. | [
"Update",
"an",
"entry",
"in",
"a",
"BibTeX",
"file",
"."
] | python | train |
Kronuz/pyScss | yapps2.py | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/yapps2.py#L875-L885 | def _scan(self, type):
"""
Returns the matched text, and moves to the next token
"""
tok = self._scanner.token(self._pos, frozenset([type]))
if tok[2] != type:
err = SyntaxError("SyntaxError[@ char %s: %s]" % (repr(tok[0]), "Trying to find " + type))
err.p... | [
"def",
"_scan",
"(",
"self",
",",
"type",
")",
":",
"tok",
"=",
"self",
".",
"_scanner",
".",
"token",
"(",
"self",
".",
"_pos",
",",
"frozenset",
"(",
"[",
"type",
"]",
")",
")",
"if",
"tok",
"[",
"2",
"]",
"!=",
"type",
":",
"err",
"=",
"Sy... | Returns the matched text, and moves to the next token | [
"Returns",
"the",
"matched",
"text",
"and",
"moves",
"to",
"the",
"next",
"token"
] | python | train |
bcbio/bcbio-nextgen | bcbio/upload/__init__.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/upload/__init__.py#L56-L74 | def _get_files(sample):
"""Retrieve files for the sample, dispatching by analysis type.
Each file is a dictionary containing the path plus associated
metadata about the file and pipeline versions.
"""
analysis = sample.get("analysis")
if analysis.lower() in ["variant", "snp calling", "variant2"... | [
"def",
"_get_files",
"(",
"sample",
")",
":",
"analysis",
"=",
"sample",
".",
"get",
"(",
"\"analysis\"",
")",
"if",
"analysis",
".",
"lower",
"(",
")",
"in",
"[",
"\"variant\"",
",",
"\"snp calling\"",
",",
"\"variant2\"",
",",
"\"standard\"",
"]",
":",
... | Retrieve files for the sample, dispatching by analysis type.
Each file is a dictionary containing the path plus associated
metadata about the file and pipeline versions. | [
"Retrieve",
"files",
"for",
"the",
"sample",
"dispatching",
"by",
"analysis",
"type",
"."
] | python | train |
tdsmith/eleven | eleven/eleven.py | https://github.com/tdsmith/eleven/blob/c79b7e784f6d4a76eb4371e69d5ee6f471fe56e1/eleven/eleven.py#L47-L68 | def censor_background(sample_frame, ntc_samples=['NTC'], margin=log2(10)):
"""Selects rows from the sample data frame that fall `margin` or greater
cycles earlier than the NTC for that target. NTC wells are recognized by
string matching against the Sample column.
:param DataFrame sample_frame: A sample... | [
"def",
"censor_background",
"(",
"sample_frame",
",",
"ntc_samples",
"=",
"[",
"'NTC'",
"]",
",",
"margin",
"=",
"log2",
"(",
"10",
")",
")",
":",
"ntcs",
"=",
"sample_frame",
".",
"loc",
"[",
"sample_frame",
"[",
"'Sample'",
"]",
".",
"apply",
"(",
"l... | Selects rows from the sample data frame that fall `margin` or greater
cycles earlier than the NTC for that target. NTC wells are recognized by
string matching against the Sample column.
:param DataFrame sample_frame: A sample data frame.
:param iterable ntc_samples: A sequence of strings giving the sam... | [
"Selects",
"rows",
"from",
"the",
"sample",
"data",
"frame",
"that",
"fall",
"margin",
"or",
"greater",
"cycles",
"earlier",
"than",
"the",
"NTC",
"for",
"that",
"target",
".",
"NTC",
"wells",
"are",
"recognized",
"by",
"string",
"matching",
"against",
"the"... | python | train |
rigetti/pyquil | pyquil/noise.py | https://github.com/rigetti/pyquil/blob/ec98e453084b0037d69d8c3245f6822a5422593d/pyquil/noise.py#L317-L345 | def damping_after_dephasing(T1, T2, gate_time):
"""
Generate the Kraus map corresponding to the composition
of a dephasing channel followed by an amplitude damping channel.
:param float T1: The amplitude damping time
:param float T2: The dephasing time
:param float gate_time: The gate duration.... | [
"def",
"damping_after_dephasing",
"(",
"T1",
",",
"T2",
",",
"gate_time",
")",
":",
"assert",
"T1",
">=",
"0",
"assert",
"T2",
">=",
"0",
"if",
"T1",
"!=",
"INFINITY",
":",
"damping",
"=",
"damping_kraus_map",
"(",
"p",
"=",
"1",
"-",
"np",
".",
"exp... | Generate the Kraus map corresponding to the composition
of a dephasing channel followed by an amplitude damping channel.
:param float T1: The amplitude damping time
:param float T2: The dephasing time
:param float gate_time: The gate duration.
:return: A list of Kraus operators. | [
"Generate",
"the",
"Kraus",
"map",
"corresponding",
"to",
"the",
"composition",
"of",
"a",
"dephasing",
"channel",
"followed",
"by",
"an",
"amplitude",
"damping",
"channel",
"."
] | python | train |
daviddrysdale/python-phonenumbers | python/phonenumbers/phonenumberutil.py | https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L638-L701 | def length_of_geographical_area_code(numobj):
"""Return length of the geographical area code for a number.
Gets the length of the geographical area code from the PhoneNumber object
passed in, so that clients could use it to split a national significant
number into geographical area code and subscriber ... | [
"def",
"length_of_geographical_area_code",
"(",
"numobj",
")",
":",
"metadata",
"=",
"PhoneMetadata",
".",
"metadata_for_region",
"(",
"region_code_for_number",
"(",
"numobj",
")",
",",
"None",
")",
"if",
"metadata",
"is",
"None",
":",
"return",
"0",
"# If a count... | Return length of the geographical area code for a number.
Gets the length of the geographical area code from the PhoneNumber object
passed in, so that clients could use it to split a national significant
number into geographical area code and subscriber number. It works in such
a way that the resultant... | [
"Return",
"length",
"of",
"the",
"geographical",
"area",
"code",
"for",
"a",
"number",
"."
] | python | train |
Parsl/parsl | parsl/executors/swift_t.py | https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/swift_t.py#L205-L272 | def _queue_management_worker(self):
"""Listen to the queue for task status messages and handle them.
Depending on the message, tasks will be updated with results, exceptions,
or updates. It expects the following messages:
.. code:: python
{
"task_id" : <task... | [
"def",
"_queue_management_worker",
"(",
"self",
")",
":",
"while",
"True",
":",
"logger",
".",
"debug",
"(",
"\"[MTHREAD] Management thread active\"",
")",
"try",
":",
"msg",
"=",
"self",
".",
"incoming_q",
".",
"get",
"(",
"block",
"=",
"True",
",",
"timeou... | Listen to the queue for task status messages and handle them.
Depending on the message, tasks will be updated with results, exceptions,
or updates. It expects the following messages:
.. code:: python
{
"task_id" : <task_id>
"result" : serialized resu... | [
"Listen",
"to",
"the",
"queue",
"for",
"task",
"status",
"messages",
"and",
"handle",
"them",
"."
] | python | valid |
kejbaly2/metrique | metrique/sqlalchemy.py | https://github.com/kejbaly2/metrique/blob/a10b076097441b7dde687949139f702f5c1e1b35/metrique/sqlalchemy.py#L666-L692 | def deptree(self, field, oids, date=None, level=None, table=None):
'''
Dependency tree builder. Recursively fetchs objects that
are children of the initial set of parent object ids provided.
:param field: Field that contains the 'parent of' data
:param oids: Object oids to build... | [
"def",
"deptree",
"(",
"self",
",",
"field",
",",
"oids",
",",
"date",
"=",
"None",
",",
"level",
"=",
"None",
",",
"table",
"=",
"None",
")",
":",
"table",
"=",
"self",
".",
"get_table",
"(",
"table",
")",
"fringe",
"=",
"str2list",
"(",
"oids",
... | Dependency tree builder. Recursively fetchs objects that
are children of the initial set of parent object ids provided.
:param field: Field that contains the 'parent of' data
:param oids: Object oids to build depedency tree for
:param date: date (metrique date range) that should be quer... | [
"Dependency",
"tree",
"builder",
".",
"Recursively",
"fetchs",
"objects",
"that",
"are",
"children",
"of",
"the",
"initial",
"set",
"of",
"parent",
"object",
"ids",
"provided",
"."
] | python | train |
tanghaibao/jcvi | jcvi/formats/fasta.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/fasta.py#L1934-L1958 | def uniq(args):
"""
%prog uniq fasta uniq.fasta
remove fasta records that are the same
"""
p = OptionParser(uniq.__doc__)
p.add_option("--seq", default=False, action="store_true",
help="Uniqify the sequences [default: %default]")
p.add_option("-t", "--trimname", dest="trimname",... | [
"def",
"uniq",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"uniq",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--seq\"",
",",
"default",
"=",
"False",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Uniqify the sequences [defa... | %prog uniq fasta uniq.fasta
remove fasta records that are the same | [
"%prog",
"uniq",
"fasta",
"uniq",
".",
"fasta"
] | python | train |
sorgerlab/indra | rest_api/api.py | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/rest_api/api.py#L615-L627 | def filter_grounded_only():
"""Filter to grounded Statements only."""
if request.method == 'OPTIONS':
return {}
response = request.body.read().decode('utf-8')
body = json.loads(response)
stmts_json = body.get('statements')
score_threshold = body.get('score_threshold')
if score_thresh... | [
"def",
"filter_grounded_only",
"(",
")",
":",
"if",
"request",
".",
"method",
"==",
"'OPTIONS'",
":",
"return",
"{",
"}",
"response",
"=",
"request",
".",
"body",
".",
"read",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"body",
"=",
"json",
".",
"l... | Filter to grounded Statements only. | [
"Filter",
"to",
"grounded",
"Statements",
"only",
"."
] | python | train |
henzk/django-productline | django_productline/features/multilanguage/settings.py | https://github.com/henzk/django-productline/blob/24ff156924c1a8c07b99cbb8a1de0a42b8d81f60/django_productline/features/multilanguage/settings.py#L18-L33 | def refine_MIDDLEWARE_CLASSES(original):
"""
Django docs say that the LocaleMiddleware should come after the SessionMiddleware.
Here, we make sure that the SessionMiddleware is enabled and then place the
LocaleMiddleware at the correct position.
Be careful with the order when refining the Middleware... | [
"def",
"refine_MIDDLEWARE_CLASSES",
"(",
"original",
")",
":",
"try",
":",
"session_middleware_index",
"=",
"original",
".",
"index",
"(",
"'django.contrib.sessions.middleware.SessionMiddleware'",
")",
"original",
".",
"insert",
"(",
"session_middleware_index",
"+",
"1",
... | Django docs say that the LocaleMiddleware should come after the SessionMiddleware.
Here, we make sure that the SessionMiddleware is enabled and then place the
LocaleMiddleware at the correct position.
Be careful with the order when refining the MiddlewareClasses with following features.
:param original:... | [
"Django",
"docs",
"say",
"that",
"the",
"LocaleMiddleware",
"should",
"come",
"after",
"the",
"SessionMiddleware",
".",
"Here",
"we",
"make",
"sure",
"that",
"the",
"SessionMiddleware",
"is",
"enabled",
"and",
"then",
"place",
"the",
"LocaleMiddleware",
"at",
"t... | python | train |
f3at/feat | tools/pep8.py | https://github.com/f3at/feat/blob/15da93fc9d6ec8154f52a9172824e25821195ef8/tools/pep8.py#L799-L848 | def process_options(arglist=None):
"""
Process options passed either via arglist or via command line args.
"""
global options, args
usage = "%prog [options] input ..."
parser = OptionParser(usage)
parser.add_option('-v', '--verbose', default=0, action='count',
help="pri... | [
"def",
"process_options",
"(",
"arglist",
"=",
"None",
")",
":",
"global",
"options",
",",
"args",
"usage",
"=",
"\"%prog [options] input ...\"",
"parser",
"=",
"OptionParser",
"(",
"usage",
")",
"parser",
".",
"add_option",
"(",
"'-v'",
",",
"'--verbose'",
",... | Process options passed either via arglist or via command line args. | [
"Process",
"options",
"passed",
"either",
"via",
"arglist",
"or",
"via",
"command",
"line",
"args",
"."
] | python | train |
raiden-network/raiden | raiden/network/proxies/token_network.py | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token_network.py#L355-L380 | def _detail_participant(
self,
channel_identifier: ChannelID,
participant: Address,
partner: Address,
block_identifier: BlockSpecification,
) -> ParticipantDetails:
""" Returns a dictionary with the channel participant information. """
dat... | [
"def",
"_detail_participant",
"(",
"self",
",",
"channel_identifier",
":",
"ChannelID",
",",
"participant",
":",
"Address",
",",
"partner",
":",
"Address",
",",
"block_identifier",
":",
"BlockSpecification",
",",
")",
"->",
"ParticipantDetails",
":",
"data",
"=",
... | Returns a dictionary with the channel participant information. | [
"Returns",
"a",
"dictionary",
"with",
"the",
"channel",
"participant",
"information",
"."
] | python | train |
amelchio/pysonos | pysonos/events.py | https://github.com/amelchio/pysonos/blob/23527c445a00e198fbb94d44b92f7f99d139e325/pysonos/events.py#L37-L170 | def parse_event_xml(xml_event):
"""Parse the body of a UPnP event.
Args:
xml_event (bytes): bytes containing the body of the event encoded
with utf-8.
Returns:
dict: A dict with keys representing the evented variables. The
relevant value will usually be a string rep... | [
"def",
"parse_event_xml",
"(",
"xml_event",
")",
":",
"result",
"=",
"{",
"}",
"tree",
"=",
"XML",
".",
"fromstring",
"(",
"xml_event",
")",
"# property values are just under the propertyset, which",
"# uses this namespace",
"properties",
"=",
"tree",
".",
"findall",
... | Parse the body of a UPnP event.
Args:
xml_event (bytes): bytes containing the body of the event encoded
with utf-8.
Returns:
dict: A dict with keys representing the evented variables. The
relevant value will usually be a string representation of the
variable... | [
"Parse",
"the",
"body",
"of",
"a",
"UPnP",
"event",
"."
] | python | train |
titusjan/argos | argos/repo/rtiplugins/hdf5.py | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/rtiplugins/hdf5.py#L519-L524 | def _closeResources(self):
""" Closes the root Dataset.
"""
logger.info("Closing: {}".format(self._fileName))
self._h5Group.close()
self._h5Group = None | [
"def",
"_closeResources",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"Closing: {}\"",
".",
"format",
"(",
"self",
".",
"_fileName",
")",
")",
"self",
".",
"_h5Group",
".",
"close",
"(",
")",
"self",
".",
"_h5Group",
"=",
"None"
] | Closes the root Dataset. | [
"Closes",
"the",
"root",
"Dataset",
"."
] | python | train |
fudge-py/fudge | fudge/__init__.py | https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/__init__.py#L1245-L1283 | def with_matching_args(self, *args, **kwargs):
"""Set the last call to expect specific argument values if those arguments exist.
Unlike :func:`fudge.Fake.with_args` use this if you want to only declare
expectations about matching arguments. Any unknown keyword arguments
used by the app... | [
"def",
"with_matching_args",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"exp",
"=",
"self",
".",
"_get_current_call",
"(",
")",
"if",
"args",
":",
"exp",
".",
"expected_matching_args",
"=",
"args",
"if",
"kwargs",
":",
"exp",
"."... | Set the last call to expect specific argument values if those arguments exist.
Unlike :func:`fudge.Fake.with_args` use this if you want to only declare
expectations about matching arguments. Any unknown keyword arguments
used by the app under test will be allowed.
For example, you can... | [
"Set",
"the",
"last",
"call",
"to",
"expect",
"specific",
"argument",
"values",
"if",
"those",
"arguments",
"exist",
"."
] | python | train |
moonso/ped_parser | ped_parser/log.py | https://github.com/moonso/ped_parser/blob/a7393e47139532782ea3c821aabea33d46f94323/ped_parser/log.py#L5-L40 | def init_log(logger, filename=None, loglevel=None):
"""
Initializes the log file in the proper format.
Arguments:
filename (str): Path to a file. Or None if logging is to
be disabled.
loglevel (str): Determines the level of the log output.
"""
... | [
"def",
"init_log",
"(",
"logger",
",",
"filename",
"=",
"None",
",",
"loglevel",
"=",
"None",
")",
":",
"formatter",
"=",
"logging",
".",
"Formatter",
"(",
"'[%(asctime)s] %(levelname)s: %(name)s: %(message)s'",
")",
"if",
"loglevel",
":",
"logger",
".",
"setLev... | Initializes the log file in the proper format.
Arguments:
filename (str): Path to a file. Or None if logging is to
be disabled.
loglevel (str): Determines the level of the log output. | [
"Initializes",
"the",
"log",
"file",
"in",
"the",
"proper",
"format",
".",
"Arguments",
":",
"filename",
"(",
"str",
")",
":",
"Path",
"to",
"a",
"file",
".",
"Or",
"None",
"if",
"logging",
"is",
"to",
"be",
"disabled",
".",
"loglevel",
"(",
"str",
"... | python | train |
vertexproject/synapse | synapse/lib/dyndeps.py | https://github.com/vertexproject/synapse/blob/22e67c5a8f6d7caddbcf34b39ab1bd2d6c4a6e0b/synapse/lib/dyndeps.py#L81-L93 | def runDynTask(task):
'''
Run a dynamic task and return the result.
Example:
foo = runDynTask( ('baz.faz.Foo', (), {} ) )
'''
func = getDynLocal(task[0])
if func is None:
raise s_exc.NoSuchFunc(name=task[0])
return func(*task[1], **task[2]) | [
"def",
"runDynTask",
"(",
"task",
")",
":",
"func",
"=",
"getDynLocal",
"(",
"task",
"[",
"0",
"]",
")",
"if",
"func",
"is",
"None",
":",
"raise",
"s_exc",
".",
"NoSuchFunc",
"(",
"name",
"=",
"task",
"[",
"0",
"]",
")",
"return",
"func",
"(",
"*... | Run a dynamic task and return the result.
Example:
foo = runDynTask( ('baz.faz.Foo', (), {} ) ) | [
"Run",
"a",
"dynamic",
"task",
"and",
"return",
"the",
"result",
"."
] | python | train |
Utagai/spice | spice_api/spice.py | https://github.com/Utagai/spice/blob/00b2c9e80ef338f4daef7643d99e8c7a0750b57c/spice_api/spice.py#L100-L113 | def init_auth(username, password):
"""Initializes the auth settings for accessing MyAnimeList
through its official API from a given username and password.
:param username Your MyAnimeList account username.
:param password Your MyAnimeList account password.
:return A tuple containing your credentials... | [
"def",
"init_auth",
"(",
"username",
",",
"password",
")",
":",
"username",
"=",
"username",
".",
"strip",
"(",
")",
"password",
"=",
"password",
".",
"strip",
"(",
")",
"credentials",
"=",
"(",
"username",
",",
"password",
")",
"if",
"helpers",
".",
"... | Initializes the auth settings for accessing MyAnimeList
through its official API from a given username and password.
:param username Your MyAnimeList account username.
:param password Your MyAnimeList account password.
:return A tuple containing your credentials. | [
"Initializes",
"the",
"auth",
"settings",
"for",
"accessing",
"MyAnimeList",
"through",
"its",
"official",
"API",
"from",
"a",
"given",
"username",
"and",
"password",
".",
":",
"param",
"username",
"Your",
"MyAnimeList",
"account",
"username",
".",
":",
"param",... | python | train |
CEA-COSMIC/ModOpt | modopt/opt/algorithms.py | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/algorithms.py#L790-L824 | def _update(self):
r"""Update
This method updates the current reconstruction
Notes
-----
Implements algorithm 1 from [R2012]_
"""
# Calculate gradient for current iteration.
self._grad.get_grad(self._x_old)
# Update z values.
for i in ... | [
"def",
"_update",
"(",
"self",
")",
":",
"# Calculate gradient for current iteration.",
"self",
".",
"_grad",
".",
"get_grad",
"(",
"self",
".",
"_x_old",
")",
"# Update z values.",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"_prox_list",
".",
"size",
")",
... | r"""Update
This method updates the current reconstruction
Notes
-----
Implements algorithm 1 from [R2012]_ | [
"r",
"Update"
] | python | train |
santosjorge/cufflinks | cufflinks/plotlytools.py | https://github.com/santosjorge/cufflinks/blob/ca1cbf93998dc793d0b1f8ac30fe1f2bd105f63a/cufflinks/plotlytools.py#L1321-L1463 | def iplot(figure,validate=True,sharing=None,filename='',
online=None,asImage=False,asUrl=False,asPlot=False,
dimensions=None,display_image=True,**kwargs):
"""
Plots a figure in IPython, creates an HTML or generates an Image
figure : figure
Plotly figure to be charted
validate : bool
If True then all va... | [
"def",
"iplot",
"(",
"figure",
",",
"validate",
"=",
"True",
",",
"sharing",
"=",
"None",
",",
"filename",
"=",
"''",
",",
"online",
"=",
"None",
",",
"asImage",
"=",
"False",
",",
"asUrl",
"=",
"False",
",",
"asPlot",
"=",
"False",
",",
"dimensions"... | Plots a figure in IPython, creates an HTML or generates an Image
figure : figure
Plotly figure to be charted
validate : bool
If True then all values are validated before
it is charted
sharing : string
Sets the sharing level permission
public - anyone can see this chart
private - only you can see this... | [
"Plots",
"a",
"figure",
"in",
"IPython",
"creates",
"an",
"HTML",
"or",
"generates",
"an",
"Image"
] | python | train |
flaviogrossi/sockjs-cyclone | sockjs/cyclone/session.py | https://github.com/flaviogrossi/sockjs-cyclone/blob/d3ca053ec1aa1e85f652347bff562c2319be37a2/sockjs/cyclone/session.py#L192-L195 | def _random_key(self):
""" Return random session key """
hashstr = '%s%s' % (random.random(), self.time_module.time())
return hashlib.md5(hashstr).hexdigest() | [
"def",
"_random_key",
"(",
"self",
")",
":",
"hashstr",
"=",
"'%s%s'",
"%",
"(",
"random",
".",
"random",
"(",
")",
",",
"self",
".",
"time_module",
".",
"time",
"(",
")",
")",
"return",
"hashlib",
".",
"md5",
"(",
"hashstr",
")",
".",
"hexdigest",
... | Return random session key | [
"Return",
"random",
"session",
"key"
] | python | train |
solvebio/solvebio-python | solvebio/annotate.py | https://github.com/solvebio/solvebio-python/blob/b29614643043afd19c1d8074e8f25c6700d51a73/solvebio/annotate.py#L39-L64 | def annotate(self, records, **kwargs):
"""Annotate a set of records with stored fields.
Args:
records: A list or iterator (can be a Query object)
chunk_size: The number of records to annotate at once (max 500).
Returns:
A generator that yields one annotated ... | [
"def",
"annotate",
"(",
"self",
",",
"records",
",",
"*",
"*",
"kwargs",
")",
":",
"# Update annotator_params with any kwargs",
"self",
".",
"annotator_params",
".",
"update",
"(",
"*",
"*",
"kwargs",
")",
"chunk_size",
"=",
"self",
".",
"annotator_params",
".... | Annotate a set of records with stored fields.
Args:
records: A list or iterator (can be a Query object)
chunk_size: The number of records to annotate at once (max 500).
Returns:
A generator that yields one annotated record at a time. | [
"Annotate",
"a",
"set",
"of",
"records",
"with",
"stored",
"fields",
"."
] | python | test |
NeuroML/pyNeuroML | pyneuroml/pynml.py | https://github.com/NeuroML/pyNeuroML/blob/aeba2e3040b360bb26556f643cccbfb3dac3b8fb/pyneuroml/pynml.py#L1181-L1239 | def execute_command_in_dir(command, directory, verbose=DEFAULTS['v'],
prefix="Output: ", env=None):
"""Execute a command in specific working directory"""
if os.name == 'nt':
directory = os.path.normpath(directory)
print_comment("Executing: (%s) in direc... | [
"def",
"execute_command_in_dir",
"(",
"command",
",",
"directory",
",",
"verbose",
"=",
"DEFAULTS",
"[",
"'v'",
"]",
",",
"prefix",
"=",
"\"Output: \"",
",",
"env",
"=",
"None",
")",
":",
"if",
"os",
".",
"name",
"==",
"'nt'",
":",
"directory",
"=",
"o... | Execute a command in specific working directory | [
"Execute",
"a",
"command",
"in",
"specific",
"working",
"directory"
] | python | train |
alecthomas/injector | injector/__init__.py | https://github.com/alecthomas/injector/blob/07c7200166dcf5abc3bd425607f6c20206b8fe65/injector/__init__.py#L655-L703 | def get(self, interface: Type[T], scope=None) -> T:
"""Get an instance of the given interface.
.. note::
Although this method is part of :class:`Injector`'s public interface
it's meant to be used in limited set of circumstances.
For example, to create some kind of ... | [
"def",
"get",
"(",
"self",
",",
"interface",
":",
"Type",
"[",
"T",
"]",
",",
"scope",
"=",
"None",
")",
"->",
"T",
":",
"key",
"=",
"BindingKey",
".",
"create",
"(",
"interface",
")",
"binding",
",",
"binder",
"=",
"self",
".",
"binder",
".",
"g... | Get an instance of the given interface.
.. note::
Although this method is part of :class:`Injector`'s public interface
it's meant to be used in limited set of circumstances.
For example, to create some kind of root object (application object)
of your applicatio... | [
"Get",
"an",
"instance",
"of",
"the",
"given",
"interface",
"."
] | python | train |
yaz/yaz | yaz/task.py | https://github.com/yaz/yaz/blob/48c842fe053bf9cd6446c4b33fb081c65339aa48/yaz/task.py#L130-L135 | def get_configuration(self, key, default=None):
"""Returns the configuration for KEY"""
if key in self.config:
return self.config.get(key)
else:
return default | [
"def",
"get_configuration",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"if",
"key",
"in",
"self",
".",
"config",
":",
"return",
"self",
".",
"config",
".",
"get",
"(",
"key",
")",
"else",
":",
"return",
"default"
] | Returns the configuration for KEY | [
"Returns",
"the",
"configuration",
"for",
"KEY"
] | python | valid |
Parisson/TimeSide | timeside/core/grapher.py | https://github.com/Parisson/TimeSide/blob/0618d75cd2f16021afcfd3d5b77f692adad76ea5/timeside/core/grapher.py#L226-L249 | def draw_anti_aliased_pixels(self, x, y1, y2, color):
""" vertical anti-aliasing at y1 and y2 """
y_max = max(y1, y2)
y_max_int = int(y_max)
alpha = y_max - y_max_int
if alpha > 0.0 and alpha < 1.0 and y_max_int + 1 < self.image_height:
current_pix = self.pixel[int(... | [
"def",
"draw_anti_aliased_pixels",
"(",
"self",
",",
"x",
",",
"y1",
",",
"y2",
",",
"color",
")",
":",
"y_max",
"=",
"max",
"(",
"y1",
",",
"y2",
")",
"y_max_int",
"=",
"int",
"(",
"y_max",
")",
"alpha",
"=",
"y_max",
"-",
"y_max_int",
"if",
"alph... | vertical anti-aliasing at y1 and y2 | [
"vertical",
"anti",
"-",
"aliasing",
"at",
"y1",
"and",
"y2"
] | python | train |
Azure/azure-cosmos-table-python | azure-cosmosdb-table/samples/table/table_usage.py | https://github.com/Azure/azure-cosmos-table-python/blob/a7b618f6bddc465c9fdf899ea2971dfe4d04fcf0/azure-cosmosdb-table/samples/table/table_usage.py#L203-L225 | def create_entity_class(self):
'''
Creates a class-based entity with fixed values, using all of the supported data types.
'''
entity = Entity()
# Partition key and row key must be strings and are required
entity.PartitionKey = 'pk{}'.format(str(uuid.uuid4()).replace('-',... | [
"def",
"create_entity_class",
"(",
"self",
")",
":",
"entity",
"=",
"Entity",
"(",
")",
"# Partition key and row key must be strings and are required",
"entity",
".",
"PartitionKey",
"=",
"'pk{}'",
".",
"format",
"(",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
... | Creates a class-based entity with fixed values, using all of the supported data types. | [
"Creates",
"a",
"class",
"-",
"based",
"entity",
"with",
"fixed",
"values",
"using",
"all",
"of",
"the",
"supported",
"data",
"types",
"."
] | python | train |
bitesofcode/projexui | projexui/widgets/xorbtreewidget/xorbtreewidget.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbtreewidget/xorbtreewidget.py#L1806-L1836 | def setCheckedRecords(self, records, column=0, parent=None):
"""
Sets the checked items based on the inputed list of records.
:param records | [<orb.Table>, ..]
parent | <QTreeWidgetItem> || None
"""
if parent is None:
for i ... | [
"def",
"setCheckedRecords",
"(",
"self",
",",
"records",
",",
"column",
"=",
"0",
",",
"parent",
"=",
"None",
")",
":",
"if",
"parent",
"is",
"None",
":",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"topLevelItemCount",
"(",
")",
")",
":",
"item",
... | Sets the checked items based on the inputed list of records.
:param records | [<orb.Table>, ..]
parent | <QTreeWidgetItem> || None | [
"Sets",
"the",
"checked",
"items",
"based",
"on",
"the",
"inputed",
"list",
"of",
"records",
".",
":",
"param",
"records",
"|",
"[",
"<orb",
".",
"Table",
">",
"..",
"]",
"parent",
"|",
"<QTreeWidgetItem",
">",
"||",
"None"
] | python | train |
ambitioninc/django-query-builder | querybuilder/query.py | https://github.com/ambitioninc/django-query-builder/blob/113a7d845d3ddc6a45621b9880308e756f87c5bf/querybuilder/query.py#L912-L935 | def where(self, q=None, where_type='AND', **kwargs):
"""
Adds a where condition as a Q object to the query's ``Where`` instance.
:type q: :class:`Q <django:django.db.models.Q>`
:param q: A django ``Q`` instance. This will be added to the query's ``Where`` object. If no
Q obj... | [
"def",
"where",
"(",
"self",
",",
"q",
"=",
"None",
",",
"where_type",
"=",
"'AND'",
",",
"*",
"*",
"kwargs",
")",
":",
"# self.mark_dirty()",
"if",
"q",
"is",
"not",
"None",
":",
"self",
".",
"_where",
".",
"wheres",
".",
"add",
"(",
"q",
",",
"... | Adds a where condition as a Q object to the query's ``Where`` instance.
:type q: :class:`Q <django:django.db.models.Q>`
:param q: A django ``Q`` instance. This will be added to the query's ``Where`` object. If no
Q object is passed, the kwargs will be examined for params to be added to Q ob... | [
"Adds",
"a",
"where",
"condition",
"as",
"a",
"Q",
"object",
"to",
"the",
"query",
"s",
"Where",
"instance",
"."
] | python | train |
Qiskit/qiskit-terra | qiskit/tools/jupyter/backend_monitor.py | https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/jupyter/backend_monitor.py#L73-L170 | def config_tab(backend):
"""The backend configuration widget.
Args:
backend (IBMQbackend): The backend.
Returns:
grid: A GridBox widget.
"""
status = backend.status().to_dict()
config = backend.configuration().to_dict()
config_dict = {**status, **config}
upper_list = ... | [
"def",
"config_tab",
"(",
"backend",
")",
":",
"status",
"=",
"backend",
".",
"status",
"(",
")",
".",
"to_dict",
"(",
")",
"config",
"=",
"backend",
".",
"configuration",
"(",
")",
".",
"to_dict",
"(",
")",
"config_dict",
"=",
"{",
"*",
"*",
"status... | The backend configuration widget.
Args:
backend (IBMQbackend): The backend.
Returns:
grid: A GridBox widget. | [
"The",
"backend",
"configuration",
"widget",
"."
] | python | test |
TurboGears/backlash | backlash/tbtools.py | https://github.com/TurboGears/backlash/blob/b8c73a6c8a203843f5a52c43b858ae5907fb2a4f/backlash/tbtools.py#L451-L454 | def render_source(self):
"""Render the sourcecode."""
return SOURCE_TABLE_HTML % text_('\n'.join(line.render() for line in
self.get_annotated_lines())) | [
"def",
"render_source",
"(",
"self",
")",
":",
"return",
"SOURCE_TABLE_HTML",
"%",
"text_",
"(",
"'\\n'",
".",
"join",
"(",
"line",
".",
"render",
"(",
")",
"for",
"line",
"in",
"self",
".",
"get_annotated_lines",
"(",
")",
")",
")"
] | Render the sourcecode. | [
"Render",
"the",
"sourcecode",
"."
] | python | train |
pilosus/ForgeryPy3 | forgery_py/forgery/russian_tax.py | https://github.com/pilosus/ForgeryPy3/blob/e15f2e59538deb4cbfceaac314f5ea897f2d5450/forgery_py/forgery/russian_tax.py#L53-L57 | def bik():
"""Return a random bank identification number."""
return '04' + \
''.join([str(random.randint(1, 9)) for _ in range(5)]) + \
str(random.randint(0, 49) + 50) | [
"def",
"bik",
"(",
")",
":",
"return",
"'04'",
"+",
"''",
".",
"join",
"(",
"[",
"str",
"(",
"random",
".",
"randint",
"(",
"1",
",",
"9",
")",
")",
"for",
"_",
"in",
"range",
"(",
"5",
")",
"]",
")",
"+",
"str",
"(",
"random",
".",
"randin... | Return a random bank identification number. | [
"Return",
"a",
"random",
"bank",
"identification",
"number",
"."
] | python | valid |
PythonCharmers/python-future | src/future/backports/urllib/parse.py | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/urllib/parse.py#L930-L949 | def splitnport(host, defport=-1):
"""Split host and port, returning numeric port.
Return given default port if no ':' found; defaults to -1.
Return numerical port if a valid number are found after ':'.
Return None if ':' but not a valid number."""
global _nportprog
if _nportprog is None:
... | [
"def",
"splitnport",
"(",
"host",
",",
"defport",
"=",
"-",
"1",
")",
":",
"global",
"_nportprog",
"if",
"_nportprog",
"is",
"None",
":",
"import",
"re",
"_nportprog",
"=",
"re",
".",
"compile",
"(",
"'^(.*):(.*)$'",
")",
"match",
"=",
"_nportprog",
".",... | Split host and port, returning numeric port.
Return given default port if no ':' found; defaults to -1.
Return numerical port if a valid number are found after ':'.
Return None if ':' but not a valid number. | [
"Split",
"host",
"and",
"port",
"returning",
"numeric",
"port",
".",
"Return",
"given",
"default",
"port",
"if",
"no",
":",
"found",
";",
"defaults",
"to",
"-",
"1",
".",
"Return",
"numerical",
"port",
"if",
"a",
"valid",
"number",
"are",
"found",
"after... | python | train |
kxepal/viivakoodi | barcode/writer.py | https://github.com/kxepal/viivakoodi/blob/79f5e866465f481982f9870c31f49a815e921c28/barcode/writer.py#L158-L192 | def render(self, code):
"""Renders the barcode to whatever the inheriting writer provides,
using the registered callbacks.
:parameters:
code : List
List of strings matching the writer spec
(only contain 0 or 1).
"""
if self._callbacks[... | [
"def",
"render",
"(",
"self",
",",
"code",
")",
":",
"if",
"self",
".",
"_callbacks",
"[",
"'initialize'",
"]",
"is",
"not",
"None",
":",
"self",
".",
"_callbacks",
"[",
"'initialize'",
"]",
"(",
"code",
")",
"ypos",
"=",
"1.0",
"for",
"line",
"in",
... | Renders the barcode to whatever the inheriting writer provides,
using the registered callbacks.
:parameters:
code : List
List of strings matching the writer spec
(only contain 0 or 1). | [
"Renders",
"the",
"barcode",
"to",
"whatever",
"the",
"inheriting",
"writer",
"provides",
"using",
"the",
"registered",
"callbacks",
"."
] | python | test |
sorgerlab/indra | indra/preassembler/__init__.py | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/__init__.py#L78-L93 | def _get_stmt_matching_groups(stmts):
"""Use the matches_key method to get sets of matching statements."""
def match_func(x): return x.matches_key()
# Remove exact duplicates using a set() call, then make copies:
logger.debug('%d statements before removing object duplicates.' %
... | [
"def",
"_get_stmt_matching_groups",
"(",
"stmts",
")",
":",
"def",
"match_func",
"(",
"x",
")",
":",
"return",
"x",
".",
"matches_key",
"(",
")",
"# Remove exact duplicates using a set() call, then make copies:",
"logger",
".",
"debug",
"(",
"'%d statements before remov... | Use the matches_key method to get sets of matching statements. | [
"Use",
"the",
"matches_key",
"method",
"to",
"get",
"sets",
"of",
"matching",
"statements",
"."
] | python | train |
joeferraro/mm | mm/project.py | https://github.com/joeferraro/mm/blob/43dce48a2249faab4d872c228ada9fbdbeec147b/mm/project.py#L483-L574 | def index_apex_symbols(self, apex_class_name_or_names=None):
'''
Writes out symbol tables to project's config/.symbols directory
'''
try:
if not os.path.exists(os.path.join(self.location,"config",".symbols")):
os.makedirs(os.path.join(self.locatio... | [
"def",
"index_apex_symbols",
"(",
"self",
",",
"apex_class_name_or_names",
"=",
"None",
")",
":",
"try",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"location",
",",
"\"config\"",
",",
"\".... | Writes out symbol tables to project's config/.symbols directory | [
"Writes",
"out",
"symbol",
"tables",
"to",
"project",
"s",
"config",
"/",
".",
"symbols",
"directory"
] | python | train |
ehansis/ozelot | examples/eurominder/eurominder/pipeline.py | https://github.com/ehansis/ozelot/blob/948675e02eb6fca940450f5cb814f53e97159e5b/examples/eurominder/eurominder/pipeline.py#L133-L136 | def input_file(self):
"""Returns the input file name, with a default relative path
"""
return path.join(path.dirname(__file__), 'data', 'tgs{:s}.tsv'.format(self.number)) | [
"def",
"input_file",
"(",
"self",
")",
":",
"return",
"path",
".",
"join",
"(",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'data'",
",",
"'tgs{:s}.tsv'",
".",
"format",
"(",
"self",
".",
"number",
")",
")"
] | Returns the input file name, with a default relative path | [
"Returns",
"the",
"input",
"file",
"name",
"with",
"a",
"default",
"relative",
"path"
] | python | train |
aio-libs/aioredis | aioredis/commands/string.py | https://github.com/aio-libs/aioredis/blob/e8c33e39558d4cc91cf70dde490d8b330c97dc2e/aioredis/commands/string.py#L99-L108 | def getrange(self, key, start, end, *, encoding=_NOTSET):
"""Get a substring of the string stored at a key.
:raises TypeError: if start or end is not int
"""
if not isinstance(start, int):
raise TypeError("start argument must be int")
if not isinstance(end, int):
... | [
"def",
"getrange",
"(",
"self",
",",
"key",
",",
"start",
",",
"end",
",",
"*",
",",
"encoding",
"=",
"_NOTSET",
")",
":",
"if",
"not",
"isinstance",
"(",
"start",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"\"start argument must be int\"",
")",
... | Get a substring of the string stored at a key.
:raises TypeError: if start or end is not int | [
"Get",
"a",
"substring",
"of",
"the",
"string",
"stored",
"at",
"a",
"key",
"."
] | python | train |
NoviceLive/intellicoder | intellicoder/utils.py | https://github.com/NoviceLive/intellicoder/blob/6cac5ebfce65c370dbebe47756a1789b120ef982/intellicoder/utils.py#L271-L276 | def group_by(iterable, key_func):
"""Wrap itertools.groupby to make life easier."""
groups = (
list(sub) for key, sub in groupby(iterable, key_func)
)
return zip(groups, groups) | [
"def",
"group_by",
"(",
"iterable",
",",
"key_func",
")",
":",
"groups",
"=",
"(",
"list",
"(",
"sub",
")",
"for",
"key",
",",
"sub",
"in",
"groupby",
"(",
"iterable",
",",
"key_func",
")",
")",
"return",
"zip",
"(",
"groups",
",",
"groups",
")"
] | Wrap itertools.groupby to make life easier. | [
"Wrap",
"itertools",
".",
"groupby",
"to",
"make",
"life",
"easier",
"."
] | python | train |
lacava/few | few/population.py | https://github.com/lacava/few/blob/5c72044425e9a5d73b8dc2cbb9b96e873dcb5b4a/few/population.py#L190-L197 | def stack_2_eqn(self,p):
"""returns equation string for program stack"""
stack_eqn = []
if p: # if stack is not empty
for n in p.stack:
self.eval_eqn(n,stack_eqn)
return stack_eqn[-1]
return [] | [
"def",
"stack_2_eqn",
"(",
"self",
",",
"p",
")",
":",
"stack_eqn",
"=",
"[",
"]",
"if",
"p",
":",
"# if stack is not empty",
"for",
"n",
"in",
"p",
".",
"stack",
":",
"self",
".",
"eval_eqn",
"(",
"n",
",",
"stack_eqn",
")",
"return",
"stack_eqn",
"... | returns equation string for program stack | [
"returns",
"equation",
"string",
"for",
"program",
"stack"
] | python | train |
ArchiveTeam/wpull | wpull/processor/coprocessor/phantomjs.py | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/coprocessor/phantomjs.py#L90-L122 | def process(self, item_session: ItemSession, request, response, file_writer_session):
'''Process PhantomJS.
Coroutine.
'''
if response.status_code != 200:
return
if not HTMLReader.is_supported(request=request, response=response):
return
_logger.... | [
"def",
"process",
"(",
"self",
",",
"item_session",
":",
"ItemSession",
",",
"request",
",",
"response",
",",
"file_writer_session",
")",
":",
"if",
"response",
".",
"status_code",
"!=",
"200",
":",
"return",
"if",
"not",
"HTMLReader",
".",
"is_supported",
"... | Process PhantomJS.
Coroutine. | [
"Process",
"PhantomJS",
"."
] | python | train |
tensorlayer/tensorlayer | tensorlayer/layers/utils.py | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/layers/utils.py#L271-L313 | def merge_networks(layers=None):
"""Merge all parameters, layers and dropout probabilities to a :class:`Layer`.
The output of return network is the first network in the list.
Parameters
----------
layers : list of :class:`Layer`
Merge all parameters, layers and dropout probabilities to the ... | [
"def",
"merge_networks",
"(",
"layers",
"=",
"None",
")",
":",
"if",
"layers",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"layers should be a list of TensorLayer's Layers.\"",
")",
"layer",
"=",
"layers",
"[",
"0",
"]",
"all_params",
"=",
"[",
"]",
"all_l... | Merge all parameters, layers and dropout probabilities to a :class:`Layer`.
The output of return network is the first network in the list.
Parameters
----------
layers : list of :class:`Layer`
Merge all parameters, layers and dropout probabilities to the first layer in the list.
Returns
... | [
"Merge",
"all",
"parameters",
"layers",
"and",
"dropout",
"probabilities",
"to",
"a",
":",
"class",
":",
"Layer",
".",
"The",
"output",
"of",
"return",
"network",
"is",
"the",
"first",
"network",
"in",
"the",
"list",
"."
] | python | valid |
spyder-ide/spyder | spyder/plugins/base.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/base.py#L187-L200 | def create_toggle_view_action(self):
"""Associate a toggle view action with each plugin"""
title = self.get_plugin_title()
if self.CONF_SECTION == 'editor':
title = _('Editor')
if self.shortcut is not None:
action = create_action(self, title,
... | [
"def",
"create_toggle_view_action",
"(",
"self",
")",
":",
"title",
"=",
"self",
".",
"get_plugin_title",
"(",
")",
"if",
"self",
".",
"CONF_SECTION",
"==",
"'editor'",
":",
"title",
"=",
"_",
"(",
"'Editor'",
")",
"if",
"self",
".",
"shortcut",
"is",
"n... | Associate a toggle view action with each plugin | [
"Associate",
"a",
"toggle",
"view",
"action",
"with",
"each",
"plugin"
] | python | train |
mikeywaites/flask-arrested | arrested/endpoint.py | https://github.com/mikeywaites/flask-arrested/blob/6b97ce2ad2765f9acab10f4726e310258aa51de0/arrested/endpoint.py#L156-L177 | def make_response(self, rv, status=200, headers=None, mime='application/json'):
"""Create a response object using the :class:`flask.Response` class.
:param rv: Response value. If the value is not an instance
of :class:`werkzeug.wrappers.Response` it will be converted
into a Res... | [
"def",
"make_response",
"(",
"self",
",",
"rv",
",",
"status",
"=",
"200",
",",
"headers",
"=",
"None",
",",
"mime",
"=",
"'application/json'",
")",
":",
"if",
"not",
"isinstance",
"(",
"rv",
",",
"Response",
")",
":",
"resp",
"=",
"Response",
"(",
"... | Create a response object using the :class:`flask.Response` class.
:param rv: Response value. If the value is not an instance
of :class:`werkzeug.wrappers.Response` it will be converted
into a Response object.
:param status: specify the HTTP status code for this response.
... | [
"Create",
"a",
"response",
"object",
"using",
"the",
":",
"class",
":",
"flask",
".",
"Response",
"class",
"."
] | python | train |
acorg/dark-matter | dark/orfs.py | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/orfs.py#L25-L50 | def addORFs(fig, seq, minX, maxX, offsetAdjuster):
"""
fig is a matplotlib figure.
seq is a Bio.Seq.Seq.
minX: the smallest x coordinate.
maxX: the largest x coordinate.
featureEndpoints: an array of features as returned by addFeatures (may be
empty).
offsetAdjuster: a function to ad... | [
"def",
"addORFs",
"(",
"fig",
",",
"seq",
",",
"minX",
",",
"maxX",
",",
"offsetAdjuster",
")",
":",
"for",
"frame",
"in",
"range",
"(",
"3",
")",
":",
"target",
"=",
"seq",
"[",
"frame",
":",
"]",
"for",
"(",
"codons",
",",
"codonType",
",",
"co... | fig is a matplotlib figure.
seq is a Bio.Seq.Seq.
minX: the smallest x coordinate.
maxX: the largest x coordinate.
featureEndpoints: an array of features as returned by addFeatures (may be
empty).
offsetAdjuster: a function to adjust feature X axis offsets for plotting. | [
"fig",
"is",
"a",
"matplotlib",
"figure",
".",
"seq",
"is",
"a",
"Bio",
".",
"Seq",
".",
"Seq",
".",
"minX",
":",
"the",
"smallest",
"x",
"coordinate",
".",
"maxX",
":",
"the",
"largest",
"x",
"coordinate",
".",
"featureEndpoints",
":",
"an",
"array",
... | python | train |
iotile/coretools | iotilecore/iotile/core/hw/reports/utc_assigner.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/reports/utc_assigner.py#L43-L45 | def copy(self):
"""Return a copy of this _TimeAnchor."""
return _TimeAnchor(self.reading_id, self.uptime, self.utc, self.is_break, self.exact) | [
"def",
"copy",
"(",
"self",
")",
":",
"return",
"_TimeAnchor",
"(",
"self",
".",
"reading_id",
",",
"self",
".",
"uptime",
",",
"self",
".",
"utc",
",",
"self",
".",
"is_break",
",",
"self",
".",
"exact",
")"
] | Return a copy of this _TimeAnchor. | [
"Return",
"a",
"copy",
"of",
"this",
"_TimeAnchor",
"."
] | python | train |
pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L1218-L1241 | def _warn_unsafe_extraction_path(path):
"""
If the default extraction path is overridden and set to an insecure
location, such as /tmp, it opens up an opportunity for an attacker to
replace an extracted file with an unauthorized payload. Warn the user
if a known insecure location... | [
"def",
"_warn_unsafe_extraction_path",
"(",
"path",
")",
":",
"if",
"os",
".",
"name",
"==",
"'nt'",
"and",
"not",
"path",
".",
"startswith",
"(",
"os",
".",
"environ",
"[",
"'windir'",
"]",
")",
":",
"# On Windows, permissions are generally restrictive by default... | If the default extraction path is overridden and set to an insecure
location, such as /tmp, it opens up an opportunity for an attacker to
replace an extracted file with an unauthorized payload. Warn the user
if a known insecure location is used.
See Distribute #375 for more details. | [
"If",
"the",
"default",
"extraction",
"path",
"is",
"overridden",
"and",
"set",
"to",
"an",
"insecure",
"location",
"such",
"as",
"/",
"tmp",
"it",
"opens",
"up",
"an",
"opportunity",
"for",
"an",
"attacker",
"to",
"replace",
"an",
"extracted",
"file",
"wi... | python | train |
pgjones/hypercorn | hypercorn/asgi/wsproto.py | https://github.com/pgjones/hypercorn/blob/ef93d741fe246846a127f9318b54505ac65f1ae7/hypercorn/asgi/wsproto.py#L108-L151 | async def asgi_send(self, message: dict) -> None:
"""Called by the ASGI instance to send a message."""
if message["type"] == "websocket.accept" and self.state == ASGIWebsocketState.HANDSHAKE:
headers = build_and_validate_headers(message.get("headers", []))
raise_if_subprotocol_pr... | [
"async",
"def",
"asgi_send",
"(",
"self",
",",
"message",
":",
"dict",
")",
"->",
"None",
":",
"if",
"message",
"[",
"\"type\"",
"]",
"==",
"\"websocket.accept\"",
"and",
"self",
".",
"state",
"==",
"ASGIWebsocketState",
".",
"HANDSHAKE",
":",
"headers",
"... | Called by the ASGI instance to send a message. | [
"Called",
"by",
"the",
"ASGI",
"instance",
"to",
"send",
"a",
"message",
"."
] | python | test |
openstax/cnx-publishing | cnxpublishing/views/user_actions.py | https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/views/user_actions.py#L218-L229 | def delete_roles_request(request):
"""Submission to remove a role acceptance request."""
uuid_ = request.matchdict['uuid']
posted_roles = request.json
with db_connect() as db_conn:
with db_conn.cursor() as cursor:
remove_role_requests(cursor, uuid_, posted_roles)
resp = request... | [
"def",
"delete_roles_request",
"(",
"request",
")",
":",
"uuid_",
"=",
"request",
".",
"matchdict",
"[",
"'uuid'",
"]",
"posted_roles",
"=",
"request",
".",
"json",
"with",
"db_connect",
"(",
")",
"as",
"db_conn",
":",
"with",
"db_conn",
".",
"cursor",
"("... | Submission to remove a role acceptance request. | [
"Submission",
"to",
"remove",
"a",
"role",
"acceptance",
"request",
"."
] | python | valid |
mbj4668/pyang | pyang/plugins/restconf.py | https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/plugins/restconf.py#L21-L49 | def pyang_plugin_init():
"""Called by pyang plugin framework at to initialize the plugin."""
# Register the plugin
plugin.register_plugin(RESTCONFPlugin())
# Register that we handle extensions from the YANG module 'ietf-restconf'
grammar.register_extension_module(restconf_module_name)
yd = (r... | [
"def",
"pyang_plugin_init",
"(",
")",
":",
"# Register the plugin",
"plugin",
".",
"register_plugin",
"(",
"RESTCONFPlugin",
"(",
")",
")",
"# Register that we handle extensions from the YANG module 'ietf-restconf'",
"grammar",
".",
"register_extension_module",
"(",
"restconf_m... | Called by pyang plugin framework at to initialize the plugin. | [
"Called",
"by",
"pyang",
"plugin",
"framework",
"at",
"to",
"initialize",
"the",
"plugin",
"."
] | python | train |
BernardFW/bernard | src/bernard/server/views.py | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/server/views.py#L99-L108 | async def postback_send(msg: BaseMessage, platform: Platform) -> Response:
"""
Injects the POST body into the FSM as a Postback message.
"""
await platform.inject_message(msg)
return json_response({
'status': 'ok',
}) | [
"async",
"def",
"postback_send",
"(",
"msg",
":",
"BaseMessage",
",",
"platform",
":",
"Platform",
")",
"->",
"Response",
":",
"await",
"platform",
".",
"inject_message",
"(",
"msg",
")",
"return",
"json_response",
"(",
"{",
"'status'",
":",
"'ok'",
",",
"... | Injects the POST body into the FSM as a Postback message. | [
"Injects",
"the",
"POST",
"body",
"into",
"the",
"FSM",
"as",
"a",
"Postback",
"message",
"."
] | python | train |
sdispater/orator | orator/orm/builder.py | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/builder.py#L804-L832 | def _add_has_where(self, has_query, relation, operator, count, boolean):
"""
Add the "has" condition where clause to the query.
:param has_query: The has query
:type has_query: Builder
:param relation: The relation to count
:type relation: orator.orm.relations.Relation
... | [
"def",
"_add_has_where",
"(",
"self",
",",
"has_query",
",",
"relation",
",",
"operator",
",",
"count",
",",
"boolean",
")",
":",
"self",
".",
"_merge_model_defined_relation_wheres_to_has_query",
"(",
"has_query",
",",
"relation",
")",
"if",
"isinstance",
"(",
"... | Add the "has" condition where clause to the query.
:param has_query: The has query
:type has_query: Builder
:param relation: The relation to count
:type relation: orator.orm.relations.Relation
:param operator: The operator
:type operator: str
:param count: The... | [
"Add",
"the",
"has",
"condition",
"where",
"clause",
"to",
"the",
"query",
"."
] | python | train |
tanghaibao/jcvi | jcvi/utils/range.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/utils/range.py#L172-L200 | def range_closest(ranges, b, left=True):
"""
Returns the range that's closest to the given position. Notice that the
behavior is to return ONE closest range to the left end (if left is True).
This is a SLOW method.
>>> ranges = [("1", 30, 40), ("1", 33, 35), ("1", 10, 20)]
>>> b = ("1", 22, 25)... | [
"def",
"range_closest",
"(",
"ranges",
",",
"b",
",",
"left",
"=",
"True",
")",
":",
"from",
"jcvi",
".",
"utils",
".",
"orderedcollections",
"import",
"SortedCollection",
"key",
"=",
"(",
"lambda",
"x",
":",
"x",
")",
"if",
"left",
"else",
"(",
"lambd... | Returns the range that's closest to the given position. Notice that the
behavior is to return ONE closest range to the left end (if left is True).
This is a SLOW method.
>>> ranges = [("1", 30, 40), ("1", 33, 35), ("1", 10, 20)]
>>> b = ("1", 22, 25)
>>> range_closest(ranges, b)
('1', 10, 20)
... | [
"Returns",
"the",
"range",
"that",
"s",
"closest",
"to",
"the",
"given",
"position",
".",
"Notice",
"that",
"the",
"behavior",
"is",
"to",
"return",
"ONE",
"closest",
"range",
"to",
"the",
"left",
"end",
"(",
"if",
"left",
"is",
"True",
")",
".",
"This... | python | train |
scidash/sciunit | sciunit/utils.py | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/utils.py#L143-L157 | def fix_display(self):
"""If this is being run on a headless system the Matplotlib
backend must be changed to one that doesn't need a display.
"""
try:
tkinter.Tk()
except (tkinter.TclError, NameError): # If there is no display.
try:
impor... | [
"def",
"fix_display",
"(",
"self",
")",
":",
"try",
":",
"tkinter",
".",
"Tk",
"(",
")",
"except",
"(",
"tkinter",
".",
"TclError",
",",
"NameError",
")",
":",
"# If there is no display.",
"try",
":",
"import",
"matplotlib",
"as",
"mpl",
"except",
"ImportE... | If this is being run on a headless system the Matplotlib
backend must be changed to one that doesn't need a display. | [
"If",
"this",
"is",
"being",
"run",
"on",
"a",
"headless",
"system",
"the",
"Matplotlib",
"backend",
"must",
"be",
"changed",
"to",
"one",
"that",
"doesn",
"t",
"need",
"a",
"display",
"."
] | python | train |
thingful/hypercat-py | hypercat/hypercat.py | https://github.com/thingful/hypercat-py/blob/db24ef66ec92d74fbea90afbeadc3a268f18f6e3/hypercat/hypercat.py#L79-L84 | def rels(self):
"""Returns a LIST of all the metadata relations"""
r = []
for i in self.metadata:
r = r + i[REL]
return [] | [
"def",
"rels",
"(",
"self",
")",
":",
"r",
"=",
"[",
"]",
"for",
"i",
"in",
"self",
".",
"metadata",
":",
"r",
"=",
"r",
"+",
"i",
"[",
"REL",
"]",
"return",
"[",
"]"
] | Returns a LIST of all the metadata relations | [
"Returns",
"a",
"LIST",
"of",
"all",
"the",
"metadata",
"relations"
] | python | train |
7sDream/zhihu-py3 | zhihu/me.py | https://github.com/7sDream/zhihu-py3/blob/bcb4aa8325f8b54d3b44bd0bdc959edd9761fcfc/zhihu/me.py#L157-L178 | def add_comment(self, answer, content):
"""给指定答案添加评论
:param Answer answer: 答案对象
:param string content: 评论内容
:return: 成功返回 True,失败返回 False
:rtype: bool
"""
from .answer import Answer
if isinstance(answer, Answer) is False:
raise ValueError('ar... | [
"def",
"add_comment",
"(",
"self",
",",
"answer",
",",
"content",
")",
":",
"from",
".",
"answer",
"import",
"Answer",
"if",
"isinstance",
"(",
"answer",
",",
"Answer",
")",
"is",
"False",
":",
"raise",
"ValueError",
"(",
"'argument answer need to be Zhihu.Ans... | 给指定答案添加评论
:param Answer answer: 答案对象
:param string content: 评论内容
:return: 成功返回 True,失败返回 False
:rtype: bool | [
"给指定答案添加评论"
] | python | train |
ktbyers/netmiko | netmiko/ssh_dispatcher.py | https://github.com/ktbyers/netmiko/blob/54e6116c0b4664de2123081937e0a9a27bdfdfea/netmiko/ssh_dispatcher.py#L239-L249 | def redispatch(obj, device_type, session_prep=True):
"""Dynamically change Netmiko object's class to proper class.
Generally used with terminal_server device_type when you need to redispatch after interacting
with terminal server.
"""
new_class = ssh_dispatcher(device_type)
obj.device_type = de... | [
"def",
"redispatch",
"(",
"obj",
",",
"device_type",
",",
"session_prep",
"=",
"True",
")",
":",
"new_class",
"=",
"ssh_dispatcher",
"(",
"device_type",
")",
"obj",
".",
"device_type",
"=",
"device_type",
"obj",
".",
"__class__",
"=",
"new_class",
"if",
"ses... | Dynamically change Netmiko object's class to proper class.
Generally used with terminal_server device_type when you need to redispatch after interacting
with terminal server. | [
"Dynamically",
"change",
"Netmiko",
"object",
"s",
"class",
"to",
"proper",
"class",
"."
] | python | train |
knowmalware/camcrypt | camcrypt/utils.py | https://github.com/knowmalware/camcrypt/blob/40c9ebbbd33ebfbb3a564ee5768cfe7a1815f6a3/camcrypt/utils.py#L38-L53 | def _get_data(filenames):
"""Read data from file(s) or STDIN.
Args:
filenames (list): List of files to read to get data. If empty or
None, read from STDIN.
"""
if filenames:
data = ""
for filename in filenames:
with open(filename, "rb") as f:
... | [
"def",
"_get_data",
"(",
"filenames",
")",
":",
"if",
"filenames",
":",
"data",
"=",
"\"\"",
"for",
"filename",
"in",
"filenames",
":",
"with",
"open",
"(",
"filename",
",",
"\"rb\"",
")",
"as",
"f",
":",
"data",
"+=",
"f",
".",
"read",
"(",
")",
"... | Read data from file(s) or STDIN.
Args:
filenames (list): List of files to read to get data. If empty or
None, read from STDIN. | [
"Read",
"data",
"from",
"file",
"(",
"s",
")",
"or",
"STDIN",
"."
] | python | train |
Erotemic/utool | utool/util_grabdata.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_grabdata.py#L627-L675 | def grab_selenium_chromedriver(redownload=False):
r"""
Automatically download selenium chrome driver if needed
CommandLine:
python -m utool.util_grabdata --test-grab_selenium_chromedriver:1
Example:
>>> # DISABLE_DOCTEST
>>> ut.grab_selenium_chromedriver()
>>> import se... | [
"def",
"grab_selenium_chromedriver",
"(",
"redownload",
"=",
"False",
")",
":",
"import",
"utool",
"as",
"ut",
"import",
"os",
"import",
"stat",
"# TODO: use a better download dir (but it must be in the PATh or selenium freaks out)",
"chromedriver_dpath",
"=",
"ut",
".",
"e... | r"""
Automatically download selenium chrome driver if needed
CommandLine:
python -m utool.util_grabdata --test-grab_selenium_chromedriver:1
Example:
>>> # DISABLE_DOCTEST
>>> ut.grab_selenium_chromedriver()
>>> import selenium.webdriver
>>> driver = selenium.webdriv... | [
"r",
"Automatically",
"download",
"selenium",
"chrome",
"driver",
"if",
"needed"
] | python | train |
aetros/aetros-cli | aetros/utils/pilutil.py | https://github.com/aetros/aetros-cli/blob/a2a1f38d6af1660e1e2680c7d413ec2aef45faab/aetros/utils/pilutil.py#L88-L157 | def bytescale(data, cmin=None, cmax=None, high=255, low=0):
"""
Byte scales an array (image).
Byte scaling means converting the input image to uint8 dtype and scaling
the range to ``(low, high)`` (default 0-255).
If the input image already has dtype uint8, no scaling is done.
Parameters
--... | [
"def",
"bytescale",
"(",
"data",
",",
"cmin",
"=",
"None",
",",
"cmax",
"=",
"None",
",",
"high",
"=",
"255",
",",
"low",
"=",
"0",
")",
":",
"if",
"data",
".",
"dtype",
"==",
"uint8",
":",
"return",
"data",
"if",
"high",
">",
"255",
":",
"rais... | Byte scales an array (image).
Byte scaling means converting the input image to uint8 dtype and scaling
the range to ``(low, high)`` (default 0-255).
If the input image already has dtype uint8, no scaling is done.
Parameters
----------
data : ndarray
PIL image data array.
cmin : sca... | [
"Byte",
"scales",
"an",
"array",
"(",
"image",
")",
"."
] | python | train |
phn/lineid_plot | lineid_plot/utils.py | https://github.com/phn/lineid_plot/blob/7c7a1af53fe439b3a7c5a57f01680575837fb978/lineid_plot/utils.py#L14-L40 | def get_boxes_and_lines(ax, labels):
"""Get boxes and lines using labels as id."""
labels_u, labels_u_line = get_labels(labels)
boxes = ax.findobj(mpl.text.Annotation)
lines = ax.findobj(mpl.lines.Line2D)
lineid_boxes = []
lineid_lines = []
for box in boxes:
l = box.get_label()
... | [
"def",
"get_boxes_and_lines",
"(",
"ax",
",",
"labels",
")",
":",
"labels_u",
",",
"labels_u_line",
"=",
"get_labels",
"(",
"labels",
")",
"boxes",
"=",
"ax",
".",
"findobj",
"(",
"mpl",
".",
"text",
".",
"Annotation",
")",
"lines",
"=",
"ax",
".",
"fi... | Get boxes and lines using labels as id. | [
"Get",
"boxes",
"and",
"lines",
"using",
"labels",
"as",
"id",
"."
] | python | train |
olitheolix/qtmacs | qtmacs/extensions/qtmacstextedit_macros.py | https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/extensions/qtmacstextedit_macros.py#L899-L991 | def cursorPositionChangedEvent(self):
"""
Update the highlighting.
This is an overloaded version of the native Qt slot of
``QTextEdit``.
In this class, the purpose of this slot is to check if the
character to the right of the cursor needs highlighting,
assuming ... | [
"def",
"cursorPositionChangedEvent",
"(",
"self",
")",
":",
"# Determine the sender and cursor position.",
"qteWidget",
"=",
"self",
".",
"sender",
"(",
")",
"tc",
"=",
"qteWidget",
".",
"textCursor",
"(",
")",
"origin",
"=",
"tc",
".",
"position",
"(",
")",
"... | Update the highlighting.
This is an overloaded version of the native Qt slot of
``QTextEdit``.
In this class, the purpose of this slot is to check if the
character to the right of the cursor needs highlighting,
assuming there is a second character to pair with it.
|Arg... | [
"Update",
"the",
"highlighting",
"."
] | python | train |
Clinical-Genomics/scout | scout/server/blueprints/variants/controllers.py | https://github.com/Clinical-Genomics/scout/blob/90a551e2e1653a319e654c2405c2866f93d0ebb9/scout/server/blueprints/variants/controllers.py#L722-L746 | def clinsig_human(variant_obj):
"""Convert to human readable version of CLINSIG evaluation."""
for clinsig_obj in variant_obj['clnsig']:
# The clinsig objects allways have a accession
if isinstance(clinsig_obj['accession'], int):
# New version
link = "https://www.ncbi.nlm... | [
"def",
"clinsig_human",
"(",
"variant_obj",
")",
":",
"for",
"clinsig_obj",
"in",
"variant_obj",
"[",
"'clnsig'",
"]",
":",
"# The clinsig objects allways have a accession",
"if",
"isinstance",
"(",
"clinsig_obj",
"[",
"'accession'",
"]",
",",
"int",
")",
":",
"# ... | Convert to human readable version of CLINSIG evaluation. | [
"Convert",
"to",
"human",
"readable",
"version",
"of",
"CLINSIG",
"evaluation",
"."
] | python | test |
SmokinCaterpillar/pypet | pypet/storageservice.py | https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/storageservice.py#L3656-L3720 | def _prm_meta_add_summary(self, instance):
"""Adds data to the summary tables and returns if `instance`s comment has to be stored.
Also moves comments upwards in the hierarchy if purge_duplicate_comments is true
and a lower index run has completed. Only necessary for *multiprocessing*.
... | [
"def",
"_prm_meta_add_summary",
"(",
"self",
",",
"instance",
")",
":",
"if",
"instance",
".",
"v_comment",
"==",
"''",
":",
"return",
"False",
"where",
"=",
"instance",
".",
"v_branch",
"definitely_store_comment",
"=",
"True",
"# Get the hexdigest of the comment to... | Adds data to the summary tables and returns if `instance`s comment has to be stored.
Also moves comments upwards in the hierarchy if purge_duplicate_comments is true
and a lower index run has completed. Only necessary for *multiprocessing*.
:return: Tuple
* String specifying the s... | [
"Adds",
"data",
"to",
"the",
"summary",
"tables",
"and",
"returns",
"if",
"instance",
"s",
"comment",
"has",
"to",
"be",
"stored",
"."
] | python | test |
glue-viz/glue-vispy-viewers | glue_vispy_viewers/extern/vispy/color/colormap.py | https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/color/colormap.py#L49-L65 | def _normalize(x, cmin=None, cmax=None, clip=True):
"""Normalize an array from the range [cmin, cmax] to [0,1],
with optional clipping."""
if not isinstance(x, np.ndarray):
x = np.array(x)
if cmin is None:
cmin = x.min()
if cmax is None:
cmax = x.max()
if cmin == cmax:
... | [
"def",
"_normalize",
"(",
"x",
",",
"cmin",
"=",
"None",
",",
"cmax",
"=",
"None",
",",
"clip",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"x",
",",
"np",
".",
"ndarray",
")",
":",
"x",
"=",
"np",
".",
"array",
"(",
"x",
")",
"if"... | Normalize an array from the range [cmin, cmax] to [0,1],
with optional clipping. | [
"Normalize",
"an",
"array",
"from",
"the",
"range",
"[",
"cmin",
"cmax",
"]",
"to",
"[",
"0",
"1",
"]",
"with",
"optional",
"clipping",
"."
] | python | train |
tryolabs/requestium | requestium/requestium.py | https://github.com/tryolabs/requestium/blob/9533932ae688da26f3fb78b97b3c0b05c6f24934/requestium/requestium.py#L138-L144 | def copy_user_agent_from_driver(self):
""" Updates requests' session user-agent with the driver's user agent
This method will start the browser process if its not already running.
"""
selenium_user_agent = self.driver.execute_script("return navigator.userAgent;")
self.headers.up... | [
"def",
"copy_user_agent_from_driver",
"(",
"self",
")",
":",
"selenium_user_agent",
"=",
"self",
".",
"driver",
".",
"execute_script",
"(",
"\"return navigator.userAgent;\"",
")",
"self",
".",
"headers",
".",
"update",
"(",
"{",
"\"user-agent\"",
":",
"selenium_user... | Updates requests' session user-agent with the driver's user agent
This method will start the browser process if its not already running. | [
"Updates",
"requests",
"session",
"user",
"-",
"agent",
"with",
"the",
"driver",
"s",
"user",
"agent"
] | python | train |
google/openhtf | openhtf/plugs/usb/shell_service.py | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/shell_service.py#L145-L149 | def _reader_thread_proc(self, timeout):
"""Read until the stream is closed."""
for data in self.stream.read_until_close(timeout_ms=timeout):
if self.stdout is not None:
self.stdout.write(data) | [
"def",
"_reader_thread_proc",
"(",
"self",
",",
"timeout",
")",
":",
"for",
"data",
"in",
"self",
".",
"stream",
".",
"read_until_close",
"(",
"timeout_ms",
"=",
"timeout",
")",
":",
"if",
"self",
".",
"stdout",
"is",
"not",
"None",
":",
"self",
".",
"... | Read until the stream is closed. | [
"Read",
"until",
"the",
"stream",
"is",
"closed",
"."
] | python | train |
koalalorenzo/python-digitalocean | digitalocean/Droplet.py | https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Droplet.py#L579-L593 | def get_actions(self):
"""
Returns a list of Action objects
This actions can be used to check the droplet's status
"""
answer = self.get_data("droplets/%s/actions/" % self.id, type=GET)
actions = []
for action_dict in answer['actions']:
action... | [
"def",
"get_actions",
"(",
"self",
")",
":",
"answer",
"=",
"self",
".",
"get_data",
"(",
"\"droplets/%s/actions/\"",
"%",
"self",
".",
"id",
",",
"type",
"=",
"GET",
")",
"actions",
"=",
"[",
"]",
"for",
"action_dict",
"in",
"answer",
"[",
"'actions'",
... | Returns a list of Action objects
This actions can be used to check the droplet's status | [
"Returns",
"a",
"list",
"of",
"Action",
"objects",
"This",
"actions",
"can",
"be",
"used",
"to",
"check",
"the",
"droplet",
"s",
"status"
] | python | valid |
quantopian/pyfolio | pyfolio/bayesian.py | https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/bayesian.py#L169-L251 | def model_best(y1, y2, samples=1000, progressbar=True):
"""
Bayesian Estimation Supersedes the T-Test
This model runs a Bayesian hypothesis comparing if y1 and y2 come
from the same distribution. Returns are assumed to be T-distributed.
In addition, computes annual volatility and Sharpe of in and
... | [
"def",
"model_best",
"(",
"y1",
",",
"y2",
",",
"samples",
"=",
"1000",
",",
"progressbar",
"=",
"True",
")",
":",
"y",
"=",
"np",
".",
"concatenate",
"(",
"(",
"y1",
",",
"y2",
")",
")",
"mu_m",
"=",
"np",
".",
"mean",
"(",
"y",
")",
"mu_p",
... | Bayesian Estimation Supersedes the T-Test
This model runs a Bayesian hypothesis comparing if y1 and y2 come
from the same distribution. Returns are assumed to be T-distributed.
In addition, computes annual volatility and Sharpe of in and
out-of-sample periods.
This model replicates the example us... | [
"Bayesian",
"Estimation",
"Supersedes",
"the",
"T",
"-",
"Test"
] | python | valid |
numenta/nupic | src/nupic/swarming/permutations_runner.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/permutations_runner.py#L1271-L1289 | def finalize(self):
"""Close file and print report/backup csv file paths
Parameters:
----------------------------------------------------------------------
retval: nothing
"""
if self.__csvFileObj is not None:
# Done with file
self.__csvFileObj.close()
self.__csvFileOb... | [
"def",
"finalize",
"(",
"self",
")",
":",
"if",
"self",
".",
"__csvFileObj",
"is",
"not",
"None",
":",
"# Done with file",
"self",
".",
"__csvFileObj",
".",
"close",
"(",
")",
"self",
".",
"__csvFileObj",
"=",
"None",
"print",
"\"Report csv saved in %s\"",
"... | Close file and print report/backup csv file paths
Parameters:
----------------------------------------------------------------------
retval: nothing | [
"Close",
"file",
"and",
"print",
"report",
"/",
"backup",
"csv",
"file",
"paths"
] | python | valid |
inveniosoftware/invenio-accounts | invenio_accounts/hash.py | https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/hash.py#L126-L134 | def _calc_checksum(self, secret):
"""Calculate string.
:param secret: The secret key.
:returns: The checksum.
"""
return str_to_uascii(
hashlib.sha256(mysql_aes_encrypt(self.salt, secret)).hexdigest()
) | [
"def",
"_calc_checksum",
"(",
"self",
",",
"secret",
")",
":",
"return",
"str_to_uascii",
"(",
"hashlib",
".",
"sha256",
"(",
"mysql_aes_encrypt",
"(",
"self",
".",
"salt",
",",
"secret",
")",
")",
".",
"hexdigest",
"(",
")",
")"
] | Calculate string.
:param secret: The secret key.
:returns: The checksum. | [
"Calculate",
"string",
"."
] | python | train |
bcbio/bcbio-nextgen | bcbio/qc/multiqc.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/qc/multiqc.py#L486-L511 | def _merge_fastqc(samples):
"""
merge all fastqc samples into one by module
"""
fastqc_list = collections.defaultdict(list)
seen = set()
for data in samples:
name = dd.get_sample_name(data)
if name in seen:
continue
seen.add(name)
fns = glob.glob(os.pa... | [
"def",
"_merge_fastqc",
"(",
"samples",
")",
":",
"fastqc_list",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"seen",
"=",
"set",
"(",
")",
"for",
"data",
"in",
"samples",
":",
"name",
"=",
"dd",
".",
"get_sample_name",
"(",
"data",
")",
"... | merge all fastqc samples into one by module | [
"merge",
"all",
"fastqc",
"samples",
"into",
"one",
"by",
"module"
] | python | train |
quantopian/zipline | zipline/pipeline/engine.py | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/engine.py#L674-L752 | def _validate_compute_chunk_params(self,
graph,
dates,
sids,
initial_workspace):
"""
Verify that the values passed to compute_chunk are well-formed.... | [
"def",
"_validate_compute_chunk_params",
"(",
"self",
",",
"graph",
",",
"dates",
",",
"sids",
",",
"initial_workspace",
")",
":",
"root",
"=",
"self",
".",
"_root_mask_term",
"clsname",
"=",
"type",
"(",
"self",
")",
".",
"__name__",
"# Writing this out explici... | Verify that the values passed to compute_chunk are well-formed. | [
"Verify",
"that",
"the",
"values",
"passed",
"to",
"compute_chunk",
"are",
"well",
"-",
"formed",
"."
] | python | train |
biocore/deblur | deblur/workflow.py | https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/workflow.py#L922-L965 | def _system_call(cmd, stdoutfilename=None):
"""Execute the command `cmd`
Parameters
----------
cmd : str
The string containing the command to be run.
stdoutfilename : str
Name of the file to save stdout to or None
(default) to not save to file
stderrfilename : str
... | [
"def",
"_system_call",
"(",
"cmd",
",",
"stdoutfilename",
"=",
"None",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"debug",
"(",
"'system call: %s'",
"%",
"cmd",
")",
"if",
"stdoutfilename",
":",
"with",
"open... | Execute the command `cmd`
Parameters
----------
cmd : str
The string containing the command to be run.
stdoutfilename : str
Name of the file to save stdout to or None
(default) to not save to file
stderrfilename : str
Name of the file to save stderr to or None
... | [
"Execute",
"the",
"command",
"cmd",
"Parameters",
"----------",
"cmd",
":",
"str",
"The",
"string",
"containing",
"the",
"command",
"to",
"be",
"run",
".",
"stdoutfilename",
":",
"str",
"Name",
"of",
"the",
"file",
"to",
"save",
"stdout",
"to",
"or",
"None... | python | train |
PureStorage-OpenConnect/rest-client | purestorage/purestorage.py | https://github.com/PureStorage-OpenConnect/rest-client/blob/097d5f2bc6facf607d7e4a92567b09fb8cf5cb34/purestorage/purestorage.py#L3017-L3038 | def clone_pod(self, source, dest, **kwargs):
"""Clone an existing pod to a new one.
:param source: Name of the pod the be cloned.
:type source: str
:param dest: Name of the target pod to clone into
:type dest: str
:param \*\*kwargs: See the REST API Guide on your array f... | [
"def",
"clone_pod",
"(",
"self",
",",
"source",
",",
"dest",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"{",
"\"source\"",
":",
"source",
"}",
"data",
".",
"update",
"(",
"kwargs",
")",
"return",
"self",
".",
"_request",
"(",
"\"POST\"",
",",
... | Clone an existing pod to a new one.
:param source: Name of the pod the be cloned.
:type source: str
:param dest: Name of the target pod to clone into
:type dest: str
:param \*\*kwargs: See the REST API Guide on your array for the
documentation on the r... | [
"Clone",
"an",
"existing",
"pod",
"to",
"a",
"new",
"one",
"."
] | python | train |
cloudmesh/cloudmesh-common | cloudmesh/common/BaseConfigDict.py | https://github.com/cloudmesh/cloudmesh-common/blob/ae4fae09cd78205d179ea692dc58f0b0c8fea2b8/cloudmesh/common/BaseConfigDict.py#L284-L307 | def load(self, filename):
"""
Loads the yaml file with the given filename.
:param filename: the name of the yaml file
"""
self._set_filename(filename)
if os.path.isfile(self['location']):
# d = OrderedDict(read_yaml_config(self['location'], check=True))
... | [
"def",
"load",
"(",
"self",
",",
"filename",
")",
":",
"self",
".",
"_set_filename",
"(",
"filename",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"self",
"[",
"'location'",
"]",
")",
":",
"# d = OrderedDict(read_yaml_config(self['location'], check=True))",... | Loads the yaml file with the given filename.
:param filename: the name of the yaml file | [
"Loads",
"the",
"yaml",
"file",
"with",
"the",
"given",
"filename",
"."
] | python | train |
log2timeline/dfvfs | dfvfs/encoding/manager.py | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/encoding/manager.py#L31-L45 | def GetDecoder(cls, encoding_method):
"""Retrieves the decoder object for a specific encoding method.
Args:
encoding_method (str): encoding method identifier.
Returns:
Decoder: decoder or None if the encoding method does not exists.
"""
encoding_method = encoding_method.lower()
dec... | [
"def",
"GetDecoder",
"(",
"cls",
",",
"encoding_method",
")",
":",
"encoding_method",
"=",
"encoding_method",
".",
"lower",
"(",
")",
"decoder",
"=",
"cls",
".",
"_decoders",
".",
"get",
"(",
"encoding_method",
",",
"None",
")",
"if",
"not",
"decoder",
":"... | Retrieves the decoder object for a specific encoding method.
Args:
encoding_method (str): encoding method identifier.
Returns:
Decoder: decoder or None if the encoding method does not exists. | [
"Retrieves",
"the",
"decoder",
"object",
"for",
"a",
"specific",
"encoding",
"method",
"."
] | python | train |
bbengfort/confire | confire/config.py | https://github.com/bbengfort/confire/blob/0879aea2516b39a438e202dcc0c6882ca64eb613/confire/config.py#L149-L164 | def configure(self, conf={}):
"""
Allows updating of the configuration via a dictionary of
configuration terms or a configuration object. Generally speaking,
this method is utilized to configure the object from a JSON or
YAML parsing.
"""
if not conf: return
... | [
"def",
"configure",
"(",
"self",
",",
"conf",
"=",
"{",
"}",
")",
":",
"if",
"not",
"conf",
":",
"return",
"if",
"isinstance",
"(",
"conf",
",",
"Configuration",
")",
":",
"conf",
"=",
"dict",
"(",
"conf",
".",
"options",
"(",
")",
")",
"for",
"k... | Allows updating of the configuration via a dictionary of
configuration terms or a configuration object. Generally speaking,
this method is utilized to configure the object from a JSON or
YAML parsing. | [
"Allows",
"updating",
"of",
"the",
"configuration",
"via",
"a",
"dictionary",
"of",
"configuration",
"terms",
"or",
"a",
"configuration",
"object",
".",
"Generally",
"speaking",
"this",
"method",
"is",
"utilized",
"to",
"configure",
"the",
"object",
"from",
"a",... | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.