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 |
|---|---|---|---|---|---|---|---|---|
bcbio/bcbio-nextgen | bcbio/rnaseq/ericscript.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/ericscript.py#L125-L129 | def _get_ericscript_path(self):
"""Retrieve PATH to the isolated eriscript anaconda environment.
"""
es = utils.which(os.path.join(utils.get_bcbio_bin(), self.EXECUTABLE))
return os.path.dirname(os.path.realpath(es)) | [
"def",
"_get_ericscript_path",
"(",
"self",
")",
":",
"es",
"=",
"utils",
".",
"which",
"(",
"os",
".",
"path",
".",
"join",
"(",
"utils",
".",
"get_bcbio_bin",
"(",
")",
",",
"self",
".",
"EXECUTABLE",
")",
")",
"return",
"os",
".",
"path",
".",
"... | Retrieve PATH to the isolated eriscript anaconda environment. | [
"Retrieve",
"PATH",
"to",
"the",
"isolated",
"eriscript",
"anaconda",
"environment",
"."
] | python | train |
skorokithakis/shortuuid | shortuuid/main.py | https://github.com/skorokithakis/shortuuid/blob/4da632a986c3a43f75c7df64f27a90bbf7ff8039/shortuuid/main.py#L123-L128 | def encoded_length(self, num_bytes=16):
"""
Returns the string length of the shortened UUID.
"""
factor = math.log(256) / math.log(self._alpha_len)
return int(math.ceil(factor * num_bytes)) | [
"def",
"encoded_length",
"(",
"self",
",",
"num_bytes",
"=",
"16",
")",
":",
"factor",
"=",
"math",
".",
"log",
"(",
"256",
")",
"/",
"math",
".",
"log",
"(",
"self",
".",
"_alpha_len",
")",
"return",
"int",
"(",
"math",
".",
"ceil",
"(",
"factor",... | Returns the string length of the shortened UUID. | [
"Returns",
"the",
"string",
"length",
"of",
"the",
"shortened",
"UUID",
"."
] | python | train |
gagneurlab/concise | concise/preprocessing/sequence.py | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/preprocessing/sequence.py#L32-L38 | def one_hot2string(arr, vocab):
"""Convert a one-hot encoded array back to string
"""
tokens = one_hot2token(arr)
indexToLetter = _get_index_dict(vocab)
return [''.join([indexToLetter[x] for x in row]) for row in tokens] | [
"def",
"one_hot2string",
"(",
"arr",
",",
"vocab",
")",
":",
"tokens",
"=",
"one_hot2token",
"(",
"arr",
")",
"indexToLetter",
"=",
"_get_index_dict",
"(",
"vocab",
")",
"return",
"[",
"''",
".",
"join",
"(",
"[",
"indexToLetter",
"[",
"x",
"]",
"for",
... | Convert a one-hot encoded array back to string | [
"Convert",
"a",
"one",
"-",
"hot",
"encoded",
"array",
"back",
"to",
"string"
] | python | train |
proycon/pynlpl | pynlpl/formats/folia.py | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L6527-L6535 | def alias(self, annotationtype, set, fallback=False):
"""Return the alias for a set (if applicable, returns the unaltered set otherwise iff fallback is enabled)"""
if inspect.isclass(annotationtype): annotationtype = annotationtype.ANNOTATIONTYPE
if annotationtype in self.set_alias and set in se... | [
"def",
"alias",
"(",
"self",
",",
"annotationtype",
",",
"set",
",",
"fallback",
"=",
"False",
")",
":",
"if",
"inspect",
".",
"isclass",
"(",
"annotationtype",
")",
":",
"annotationtype",
"=",
"annotationtype",
".",
"ANNOTATIONTYPE",
"if",
"annotationtype",
... | Return the alias for a set (if applicable, returns the unaltered set otherwise iff fallback is enabled) | [
"Return",
"the",
"alias",
"for",
"a",
"set",
"(",
"if",
"applicable",
"returns",
"the",
"unaltered",
"set",
"otherwise",
"iff",
"fallback",
"is",
"enabled",
")"
] | python | train |
googleapis/google-cloud-python | storage/google/cloud/storage/bucket.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/bucket.py#L1670-L1699 | def get_iam_policy(self, client=None):
"""Retrieve the IAM policy for the bucket.
See
https://cloud.google.com/storage/docs/json_api/v1/buckets/getIamPolicy
If :attr:`user_project` is set, bills the API request to that project.
:type client: :class:`~google.cloud.storage.clien... | [
"def",
"get_iam_policy",
"(",
"self",
",",
"client",
"=",
"None",
")",
":",
"client",
"=",
"self",
".",
"_require_client",
"(",
"client",
")",
"query_params",
"=",
"{",
"}",
"if",
"self",
".",
"user_project",
"is",
"not",
"None",
":",
"query_params",
"["... | Retrieve the IAM policy for the bucket.
See
https://cloud.google.com/storage/docs/json_api/v1/buckets/getIamPolicy
If :attr:`user_project` is set, bills the API request to that project.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
... | [
"Retrieve",
"the",
"IAM",
"policy",
"for",
"the",
"bucket",
"."
] | python | train |
watson-developer-cloud/python-sdk | ibm_watson/speech_to_text_v1.py | https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/speech_to_text_v1.py#L3039-L3046 | def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'customizations') and self.customizations is not None:
_dict['customizations'] = [
x._to_dict() for x in self.customizations
]
return _dict | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'customizations'",
")",
"and",
"self",
".",
"customizations",
"is",
"not",
"None",
":",
"_dict",
"[",
"'customizations'",
"]",
"=",
"[",
"x",
".",
"... | Return a json dictionary representing this model. | [
"Return",
"a",
"json",
"dictionary",
"representing",
"this",
"model",
"."
] | python | train |
esheldon/fitsio | fitsio/hdu/table.py | https://github.com/esheldon/fitsio/blob/a6f07919f457a282fe240adad9d2c30906b71a15/fitsio/hdu/table.py#L515-L560 | def resize(self, nrows, front=False):
"""
Resize the table to the given size, removing or adding rows as
necessary. Note if expanding the table at the end, it is more
efficient to use the append function than resizing and then
writing.
New added rows are zerod, except f... | [
"def",
"resize",
"(",
"self",
",",
"nrows",
",",
"front",
"=",
"False",
")",
":",
"nrows_current",
"=",
"self",
".",
"get_nrows",
"(",
")",
"if",
"nrows",
"==",
"nrows_current",
":",
"return",
"if",
"nrows",
"<",
"nrows_current",
":",
"rowdiff",
"=",
"... | Resize the table to the given size, removing or adding rows as
necessary. Note if expanding the table at the end, it is more
efficient to use the append function than resizing and then
writing.
New added rows are zerod, except for 'i1', 'u2' and 'u4' data types
which get -128,3... | [
"Resize",
"the",
"table",
"to",
"the",
"given",
"size",
"removing",
"or",
"adding",
"rows",
"as",
"necessary",
".",
"Note",
"if",
"expanding",
"the",
"table",
"at",
"the",
"end",
"it",
"is",
"more",
"efficient",
"to",
"use",
"the",
"append",
"function",
... | python | train |
tonybaloney/wily | wily/commands/report.py | https://github.com/tonybaloney/wily/blob/bae259354a91b57d56603f0ca7403186f086a84c/wily/commands/report.py#L19-L188 | def report(
config, path, metrics, n, output, include_message=False, format=ReportFormat.CONSOLE, console_format=None,
):
"""
Show information about the cache and runtime.
:param config: The configuration
:type config: :class:`wily.config.WilyConfig`
:param path: The path to the file
:typ... | [
"def",
"report",
"(",
"config",
",",
"path",
",",
"metrics",
",",
"n",
",",
"output",
",",
"include_message",
"=",
"False",
",",
"format",
"=",
"ReportFormat",
".",
"CONSOLE",
",",
"console_format",
"=",
"None",
",",
")",
":",
"logger",
".",
"debug",
"... | Show information about the cache and runtime.
:param config: The configuration
:type config: :class:`wily.config.WilyConfig`
:param path: The path to the file
:type path: ``str``
:param metrics: Name of the metric to report on
:type metrics: ``str``
:param n: Number of items to list
... | [
"Show",
"information",
"about",
"the",
"cache",
"and",
"runtime",
"."
] | python | train |
boriel/zxbasic | arch/zx48k/optimizer.py | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L1635-L1652 | def goes_requires(self, regs):
""" Returns whether any of the goes_to block requires any of
the given registers.
"""
if len(self) and self.mem[-1].inst == 'call' and self.mem[-1].condition_flag is None:
for block in self.calls:
if block.is_used(regs, 0):
... | [
"def",
"goes_requires",
"(",
"self",
",",
"regs",
")",
":",
"if",
"len",
"(",
"self",
")",
"and",
"self",
".",
"mem",
"[",
"-",
"1",
"]",
".",
"inst",
"==",
"'call'",
"and",
"self",
".",
"mem",
"[",
"-",
"1",
"]",
".",
"condition_flag",
"is",
"... | Returns whether any of the goes_to block requires any of
the given registers. | [
"Returns",
"whether",
"any",
"of",
"the",
"goes_to",
"block",
"requires",
"any",
"of",
"the",
"given",
"registers",
"."
] | python | train |
juju/charm-helpers | charmhelpers/contrib/storage/linux/ceph.py | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L958-L967 | def image_mapped(name):
"""Determine whether a RADOS block device is mapped locally."""
try:
out = check_output(['rbd', 'showmapped'])
if six.PY3:
out = out.decode('UTF-8')
except CalledProcessError:
return False
return name in out | [
"def",
"image_mapped",
"(",
"name",
")",
":",
"try",
":",
"out",
"=",
"check_output",
"(",
"[",
"'rbd'",
",",
"'showmapped'",
"]",
")",
"if",
"six",
".",
"PY3",
":",
"out",
"=",
"out",
".",
"decode",
"(",
"'UTF-8'",
")",
"except",
"CalledProcessError",... | Determine whether a RADOS block device is mapped locally. | [
"Determine",
"whether",
"a",
"RADOS",
"block",
"device",
"is",
"mapped",
"locally",
"."
] | python | train |
SchroterQuentin/django-search-listview | search_listview/list.py | https://github.com/SchroterQuentin/django-search-listview/blob/8b027a6908dc30c6ebc613bb4fde6b1ba40124a3/search_listview/list.py#L192-L201 | def associate_model(model, field):
"""
Return the model associate to the ForeignKey or ManyToMany
relation
"""
class_field = model._meta.get_field(field)
if hasattr(class_field, "field"):
return class_field.field.related.related_model
else:
return class_field.related_model | [
"def",
"associate_model",
"(",
"model",
",",
"field",
")",
":",
"class_field",
"=",
"model",
".",
"_meta",
".",
"get_field",
"(",
"field",
")",
"if",
"hasattr",
"(",
"class_field",
",",
"\"field\"",
")",
":",
"return",
"class_field",
".",
"field",
".",
"... | Return the model associate to the ForeignKey or ManyToMany
relation | [
"Return",
"the",
"model",
"associate",
"to",
"the",
"ForeignKey",
"or",
"ManyToMany",
"relation"
] | python | train |
yyuu/botornado | boto/ec2/connection.py | https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/ec2/connection.py#L1371-L1406 | def detach_volume(self, volume_id, instance_id=None,
device=None, force=False):
"""
Detach an EBS volume from an EC2 instance.
:type volume_id: str
:param volume_id: The ID of the EBS volume to be attached.
:type instance_id: str
:param instance_id... | [
"def",
"detach_volume",
"(",
"self",
",",
"volume_id",
",",
"instance_id",
"=",
"None",
",",
"device",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"params",
"=",
"{",
"'VolumeId'",
":",
"volume_id",
"}",
"if",
"instance_id",
":",
"params",
"[",
... | Detach an EBS volume from an EC2 instance.
:type volume_id: str
:param volume_id: The ID of the EBS volume to be attached.
:type instance_id: str
:param instance_id: The ID of the EC2 instance from which it will
be detached.
:type device: str
... | [
"Detach",
"an",
"EBS",
"volume",
"from",
"an",
"EC2",
"instance",
"."
] | python | train |
arista-eosplus/pyeapi | pyeapi/api/switchports.py | https://github.com/arista-eosplus/pyeapi/blob/96a74faef1fe3bd79c4e900aed29c9956a0587d6/pyeapi/api/switchports.py#L344-L377 | def set_trunk_groups(self, intf, value=None, default=False, disable=False):
"""Configures the switchport trunk group value
Args:
intf (str): The interface identifier to configure.
value (str): The set of values to configure the trunk group
default (bool): Configures ... | [
"def",
"set_trunk_groups",
"(",
"self",
",",
"intf",
",",
"value",
"=",
"None",
",",
"default",
"=",
"False",
",",
"disable",
"=",
"False",
")",
":",
"if",
"default",
":",
"cmd",
"=",
"'default switchport trunk group'",
"return",
"self",
".",
"configure_inte... | Configures the switchport trunk group value
Args:
intf (str): The interface identifier to configure.
value (str): The set of values to configure the trunk group
default (bool): Configures the trunk group default value
disable (bool): Negates all trunk group setti... | [
"Configures",
"the",
"switchport",
"trunk",
"group",
"value"
] | python | train |
scarface-4711/denonavr | denonavr/denonavr.py | https://github.com/scarface-4711/denonavr/blob/59a136e27b43cb1d1e140cf67705087b3aa377cd/denonavr/denonavr.py#L1439-L1471 | def set_sound_mode(self, sound_mode):
"""
Set sound_mode of device.
Valid values depend on the device and should be taken from
"sound_mode_list".
Return "True" on success and "False" on fail.
"""
if sound_mode == ALL_ZONE_STEREO:
if self._set_all_zone... | [
"def",
"set_sound_mode",
"(",
"self",
",",
"sound_mode",
")",
":",
"if",
"sound_mode",
"==",
"ALL_ZONE_STEREO",
":",
"if",
"self",
".",
"_set_all_zone_stereo",
"(",
"True",
")",
":",
"self",
".",
"_sound_mode_raw",
"=",
"ALL_ZONE_STEREO",
"return",
"True",
"el... | Set sound_mode of device.
Valid values depend on the device and should be taken from
"sound_mode_list".
Return "True" on success and "False" on fail. | [
"Set",
"sound_mode",
"of",
"device",
"."
] | python | train |
dmbee/seglearn | seglearn/transform.py | https://github.com/dmbee/seglearn/blob/d8d7039e92c4c6571a70350c03298aceab8dbeec/seglearn/transform.py#L1301-L1319 | def _retrieve_indices(cols):
'''
Retrieve a list of indices corresponding to the provided column specification.
'''
if isinstance(cols, int):
return [cols]
elif isinstance(cols, slice):
start = cols.start if cols.start else 0
stop = cols.stop
... | [
"def",
"_retrieve_indices",
"(",
"cols",
")",
":",
"if",
"isinstance",
"(",
"cols",
",",
"int",
")",
":",
"return",
"[",
"cols",
"]",
"elif",
"isinstance",
"(",
"cols",
",",
"slice",
")",
":",
"start",
"=",
"cols",
".",
"start",
"if",
"cols",
".",
... | Retrieve a list of indices corresponding to the provided column specification. | [
"Retrieve",
"a",
"list",
"of",
"indices",
"corresponding",
"to",
"the",
"provided",
"column",
"specification",
"."
] | python | train |
mitsei/dlkit | dlkit/services/assessment.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/services/assessment.py#L397-L408 | def _set_bank_view(self, session):
"""Sets the underlying bank view to match current view"""
if self._bank_view == COMPARATIVE:
try:
session.use_comparative_bank_view()
except AttributeError:
pass
else:
try:
sess... | [
"def",
"_set_bank_view",
"(",
"self",
",",
"session",
")",
":",
"if",
"self",
".",
"_bank_view",
"==",
"COMPARATIVE",
":",
"try",
":",
"session",
".",
"use_comparative_bank_view",
"(",
")",
"except",
"AttributeError",
":",
"pass",
"else",
":",
"try",
":",
... | Sets the underlying bank view to match current view | [
"Sets",
"the",
"underlying",
"bank",
"view",
"to",
"match",
"current",
"view"
] | python | train |
pandas-dev/pandas | pandas/core/resample.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/resample.py#L1334-L1373 | def _get_resampler(self, obj, kind=None):
"""
Return my resampler or raise if we have an invalid axis.
Parameters
----------
obj : input object
kind : string, optional
'period','timestamp','timedelta' are valid
Returns
-------
a Resam... | [
"def",
"_get_resampler",
"(",
"self",
",",
"obj",
",",
"kind",
"=",
"None",
")",
":",
"self",
".",
"_set_grouper",
"(",
"obj",
")",
"ax",
"=",
"self",
".",
"ax",
"if",
"isinstance",
"(",
"ax",
",",
"DatetimeIndex",
")",
":",
"return",
"DatetimeIndexRes... | Return my resampler or raise if we have an invalid axis.
Parameters
----------
obj : input object
kind : string, optional
'period','timestamp','timedelta' are valid
Returns
-------
a Resampler
Raises
------
TypeError if incom... | [
"Return",
"my",
"resampler",
"or",
"raise",
"if",
"we",
"have",
"an",
"invalid",
"axis",
"."
] | python | train |
tradenity/python-sdk | tradenity/resources/free_shipping.py | https://github.com/tradenity/python-sdk/blob/d13fbe23f4d6ff22554c6d8d2deaf209371adaf1/tradenity/resources/free_shipping.py#L728-L750 | def list_all_free_shippings(cls, **kwargs):
"""List FreeShippings
Return a list of FreeShippings
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_free_shippings(async=True)
>>>... | [
"def",
"list_all_free_shippings",
"(",
"cls",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_list_all_free_shippings_with_http_info",
... | List FreeShippings
Return a list of FreeShippings
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_free_shippings(async=True)
>>> result = thread.get()
:param async bool
... | [
"List",
"FreeShippings"
] | python | train |
projectshift/shift-boiler | boiler/user/session_interface.py | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/session_interface.py#L45-L59 | def save_session(self, *args, **kwargs):
"""
Save session
Skip setting session cookie if requested via g.stateless_sessions
"""
# do not send session cookie
if g.get('stateless_sessions'):
return
# send cookie
return super(BoilerSessionInterf... | [
"def",
"save_session",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# do not send session cookie",
"if",
"g",
".",
"get",
"(",
"'stateless_sessions'",
")",
":",
"return",
"# send cookie",
"return",
"super",
"(",
"BoilerSessionInterface",
... | Save session
Skip setting session cookie if requested via g.stateless_sessions | [
"Save",
"session",
"Skip",
"setting",
"session",
"cookie",
"if",
"requested",
"via",
"g",
".",
"stateless_sessions"
] | python | train |
tensorflow/tensorboard | tensorboard/backend/event_processing/event_accumulator.py | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/backend/event_processing/event_accumulator.py#L675-L716 | def _Purge(self, event, by_tags):
"""Purge all events that have occurred after the given event.step.
If by_tags is True, purge all events that occurred after the given
event.step, but only for the tags that the event has. Non-sequential
event.steps suggest that a TensorFlow restart occurred, and we dis... | [
"def",
"_Purge",
"(",
"self",
",",
"event",
",",
"by_tags",
")",
":",
"## Keep data in reservoirs that has a step less than event.step",
"_NotExpired",
"=",
"lambda",
"x",
":",
"x",
".",
"step",
"<",
"event",
".",
"step",
"if",
"by_tags",
":",
"def",
"_ExpiredPe... | Purge all events that have occurred after the given event.step.
If by_tags is True, purge all events that occurred after the given
event.step, but only for the tags that the event has. Non-sequential
event.steps suggest that a TensorFlow restart occurred, and we discard
the out-of-order events to displ... | [
"Purge",
"all",
"events",
"that",
"have",
"occurred",
"after",
"the",
"given",
"event",
".",
"step",
"."
] | python | train |
fedora-infra/fedora-messaging | fedora_messaging/twisted/protocol.py | https://github.com/fedora-infra/fedora-messaging/blob/be3e88534e2b15d579bcd24f9c4b7e795cb7e0b7/fedora_messaging/twisted/protocol.py#L915-L931 | def pauseProducing(self):
"""
Pause the reception of messages by canceling all existing consumers.
This does not disconnect from the server.
Message reception can be resumed with :meth:`resumeProducing`.
Returns:
Deferred: fired when the production is paused.
... | [
"def",
"pauseProducing",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_running",
":",
"return",
"# Exit the read loop and cancel the consumer on the server.",
"self",
".",
"_running",
"=",
"False",
"for",
"consumer",
"in",
"self",
".",
"_consumers",
".",
"val... | Pause the reception of messages by canceling all existing consumers.
This does not disconnect from the server.
Message reception can be resumed with :meth:`resumeProducing`.
Returns:
Deferred: fired when the production is paused. | [
"Pause",
"the",
"reception",
"of",
"messages",
"by",
"canceling",
"all",
"existing",
"consumers",
".",
"This",
"does",
"not",
"disconnect",
"from",
"the",
"server",
"."
] | python | train |
thiagopbueno/tf-rddlsim | tfrddlsim/simulation/policy_simulator.py | https://github.com/thiagopbueno/tf-rddlsim/blob/d7102a0ad37d179dbb23141640254ea383d3b43f/tfrddlsim/simulation/policy_simulator.py#L226-L272 | def trajectory(self,
horizon: int,
initial_state: Optional[StateTensor] = None) -> TrajectoryOutput:
'''Returns the ops for the trajectory generation with given `horizon`
and `initial_state`.
The simulation returns states, actions and interms as a
sequence of ten... | [
"def",
"trajectory",
"(",
"self",
",",
"horizon",
":",
"int",
",",
"initial_state",
":",
"Optional",
"[",
"StateTensor",
"]",
"=",
"None",
")",
"->",
"TrajectoryOutput",
":",
"if",
"initial_state",
"is",
"None",
":",
"initial_state",
"=",
"self",
".",
"_ce... | Returns the ops for the trajectory generation with given `horizon`
and `initial_state`.
The simulation returns states, actions and interms as a
sequence of tensors (i.e., all representations are factored).
The reward is a batch sized tensor.
The trajectoty output is a tuple: (in... | [
"Returns",
"the",
"ops",
"for",
"the",
"trajectory",
"generation",
"with",
"given",
"horizon",
"and",
"initial_state",
"."
] | python | train |
bernii/querystring-parser | querystring_parser/parser.py | https://github.com/bernii/querystring-parser/blob/1d3b652512d55622a37b5f5712909ea41490454b/querystring_parser/parser.py#L55-L68 | def get_key(s):
'''
Get data between [ and ] remove ' if exist
@param s: string to process
'''
start = s.find("[")
end = s.find("]")
if start == -1 or end == -1:
return None
if s[start + 1] == "'":
start += 1
if s[end - 1] == "'":
end -= 1
ret... | [
"def",
"get_key",
"(",
"s",
")",
":",
"start",
"=",
"s",
".",
"find",
"(",
"\"[\"",
")",
"end",
"=",
"s",
".",
"find",
"(",
"\"]\"",
")",
"if",
"start",
"==",
"-",
"1",
"or",
"end",
"==",
"-",
"1",
":",
"return",
"None",
"if",
"s",
"[",
"st... | Get data between [ and ] remove ' if exist
@param s: string to process | [
"Get",
"data",
"between",
"[",
"and",
"]",
"remove",
"if",
"exist"
] | python | train |
spacetelescope/synphot_refactor | synphot/observation.py | https://github.com/spacetelescope/synphot_refactor/blob/9c064f3cff0c41dd8acadc0f67c6350931275b9f/synphot/observation.py#L142-L196 | def _init_bins(self, binset):
"""Calculated binned wavelength centers, edges, and flux.
By contrast, the native waveset and flux should be considered
samples of a continuous function.
Thus, it makes sense to interpolate ``self.waveset`` and
``self(self.waveset)``, but not `bins... | [
"def",
"_init_bins",
"(",
"self",
",",
"binset",
")",
":",
"if",
"binset",
"is",
"None",
":",
"if",
"self",
".",
"bandpass",
".",
"waveset",
"is",
"not",
"None",
":",
"self",
".",
"_binset",
"=",
"self",
".",
"bandpass",
".",
"waveset",
"elif",
"self... | Calculated binned wavelength centers, edges, and flux.
By contrast, the native waveset and flux should be considered
samples of a continuous function.
Thus, it makes sense to interpolate ``self.waveset`` and
``self(self.waveset)``, but not `binset` and `binflux`. | [
"Calculated",
"binned",
"wavelength",
"centers",
"edges",
"and",
"flux",
"."
] | python | train |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_rally.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_rally.py#L116-L138 | def cmd_rally_alt(self, args):
'''handle rally alt change'''
if (len(args) < 2):
print("Usage: rally alt RALLYNUM newAlt <newBreakAlt>")
return
if not self.have_list:
print("Please list rally points first")
return
idx = int(args[0])
... | [
"def",
"cmd_rally_alt",
"(",
"self",
",",
"args",
")",
":",
"if",
"(",
"len",
"(",
"args",
")",
"<",
"2",
")",
":",
"print",
"(",
"\"Usage: rally alt RALLYNUM newAlt <newBreakAlt>\"",
")",
"return",
"if",
"not",
"self",
".",
"have_list",
":",
"print",
"(",... | handle rally alt change | [
"handle",
"rally",
"alt",
"change"
] | python | train |
dotzero/tilda-api-python | tilda/base.py | https://github.com/dotzero/tilda-api-python/blob/0ab984e0236cbfb676b0fbddc1ab37202d92e0a8/tilda/base.py#L54-L70 | def to_json(self):
"""
Returns:
str:
"""
data = dict()
for key, value in self.__dict__.items():
if value:
if hasattr(value, 'to_dict'):
data[key] = value.to_dict()
elif isinstance(value, datetime):
... | [
"def",
"to_json",
"(",
"self",
")",
":",
"data",
"=",
"dict",
"(",
")",
"for",
"key",
",",
"value",
"in",
"self",
".",
"__dict__",
".",
"items",
"(",
")",
":",
"if",
"value",
":",
"if",
"hasattr",
"(",
"value",
",",
"'to_dict'",
")",
":",
"data",... | Returns:
str: | [
"Returns",
":",
"str",
":"
] | python | train |
madjar/pyramid_persona | pyramid_persona/views.py | https://github.com/madjar/pyramid_persona/blob/b8cc34780e399904bfb8ec907bb11589ac52d9fa/pyramid_persona/views.py#L12-L23 | def verify_login(request):
"""Verifies the assertion and the csrf token in the given request.
Returns the email of the user if everything is valid, otherwise raises
a HTTPBadRequest"""
verifier = request.registry['persona.verifier']
try:
data = verifier.verify(request.POST['assertion'])
... | [
"def",
"verify_login",
"(",
"request",
")",
":",
"verifier",
"=",
"request",
".",
"registry",
"[",
"'persona.verifier'",
"]",
"try",
":",
"data",
"=",
"verifier",
".",
"verify",
"(",
"request",
".",
"POST",
"[",
"'assertion'",
"]",
")",
"except",
"(",
"V... | Verifies the assertion and the csrf token in the given request.
Returns the email of the user if everything is valid, otherwise raises
a HTTPBadRequest | [
"Verifies",
"the",
"assertion",
"and",
"the",
"csrf",
"token",
"in",
"the",
"given",
"request",
"."
] | python | train |
belbio/bel | bel/utils.py | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/utils.py#L245-L259 | def elapsed(self):
""" Return the current elapsed time since start
If the `elapsed` property is called in the context manager scope,
the elapsed time bewteen start and property access is returned.
However, if it is accessed outside of the context manager scope,
it returns the ela... | [
"def",
"elapsed",
"(",
"self",
")",
":",
"if",
"self",
".",
"end",
"is",
"None",
":",
"# if elapsed is called in the context manager scope",
"return",
"(",
"self",
"(",
")",
"-",
"self",
".",
"start",
")",
"*",
"self",
".",
"factor",
"else",
":",
"# if ela... | Return the current elapsed time since start
If the `elapsed` property is called in the context manager scope,
the elapsed time bewteen start and property access is returned.
However, if it is accessed outside of the context manager scope,
it returns the elapsed time bewteen entering and ... | [
"Return",
"the",
"current",
"elapsed",
"time",
"since",
"start",
"If",
"the",
"elapsed",
"property",
"is",
"called",
"in",
"the",
"context",
"manager",
"scope",
"the",
"elapsed",
"time",
"bewteen",
"start",
"and",
"property",
"access",
"is",
"returned",
".",
... | python | train |
botswana-harvard/edc-registration | edc_registration/model_mixins/updates_or_creates_registered_subject_model_mixin.py | https://github.com/botswana-harvard/edc-registration/blob/3daca624a496945fd4536488f6f80790bbecc081/edc_registration/model_mixins/updates_or_creates_registered_subject_model_mixin.py#L82-L100 | def registration_options(self):
"""Gathers values for common attributes between the
registration model and this instance.
"""
registration_options = {}
rs = self.registration_model()
for k, v in self.__dict__.items():
if k not in DEFAULT_BASE_FIELDS + ['_state... | [
"def",
"registration_options",
"(",
"self",
")",
":",
"registration_options",
"=",
"{",
"}",
"rs",
"=",
"self",
".",
"registration_model",
"(",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"__dict__",
".",
"items",
"(",
")",
":",
"if",
"k",
"not",
"... | Gathers values for common attributes between the
registration model and this instance. | [
"Gathers",
"values",
"for",
"common",
"attributes",
"between",
"the",
"registration",
"model",
"and",
"this",
"instance",
"."
] | python | train |
jeffknupp/sandman | sandman/model/utils.py | https://github.com/jeffknupp/sandman/blob/253ea4d15cbccd9f0016d66fedd7478614cc0b2f/sandman/model/utils.py#L110-L125 | def register_internal_data(cls):
"""Register a new class, *cls*, with various internal data structures.
:params `sandman.model.Model` cls: class to register
"""
with app.app_context():
if getattr(cls, 'endpoint', None) is None:
orig_class = cls
cls = type('Sandman' + cl... | [
"def",
"register_internal_data",
"(",
"cls",
")",
":",
"with",
"app",
".",
"app_context",
"(",
")",
":",
"if",
"getattr",
"(",
"cls",
",",
"'endpoint'",
",",
"None",
")",
"is",
"None",
":",
"orig_class",
"=",
"cls",
"cls",
"=",
"type",
"(",
"'Sandman'"... | Register a new class, *cls*, with various internal data structures.
:params `sandman.model.Model` cls: class to register | [
"Register",
"a",
"new",
"class",
"*",
"cls",
"*",
"with",
"various",
"internal",
"data",
"structures",
"."
] | python | train |
steder/pundler | pundler/core.py | https://github.com/steder/pundler/blob/68d730b08e46d5f7b8781017c9bba87c7378509d/pundler/core.py#L34-L44 | def get_requirement_files(args=None):
"""
Get the "best" requirements file we can find
"""
if args and args.input_filename:
return [args.input_filename]
paths = []
for regex in settings.REQUIREMENTS_SOURCE_GLOBS:
paths.extend(glob.glob(regex))
return paths | [
"def",
"get_requirement_files",
"(",
"args",
"=",
"None",
")",
":",
"if",
"args",
"and",
"args",
".",
"input_filename",
":",
"return",
"[",
"args",
".",
"input_filename",
"]",
"paths",
"=",
"[",
"]",
"for",
"regex",
"in",
"settings",
".",
"REQUIREMENTS_SOU... | Get the "best" requirements file we can find | [
"Get",
"the",
"best",
"requirements",
"file",
"we",
"can",
"find"
] | python | train |
fhs/pyhdf | pyhdf/VS.py | https://github.com/fhs/pyhdf/blob/dbdc1810a74a38df50dcad81fe903e239d2b388d/pyhdf/VS.py#L1062-L1159 | def storedata(self, fieldName, values, data_type, vName, vClass):
"""Create and initialize a single field vdata, returning
the vdata reference number.
Args::
fieldName Name of the single field in the vadata to create
values Sequence of values to store in the field;. ... | [
"def",
"storedata",
"(",
"self",
",",
"fieldName",
",",
"values",
",",
"data_type",
",",
"vName",
",",
"vClass",
")",
":",
"# See if the field is multi-valued.",
"nrecs",
"=",
"len",
"(",
"values",
")",
"if",
"type",
"(",
"values",
"[",
"0",
"]",
")",
"i... | Create and initialize a single field vdata, returning
the vdata reference number.
Args::
fieldName Name of the single field in the vadata to create
values Sequence of values to store in the field;. Each value can
itself be a sequence, in which case the ... | [
"Create",
"and",
"initialize",
"a",
"single",
"field",
"vdata",
"returning",
"the",
"vdata",
"reference",
"number",
"."
] | python | train |
UpCloudLtd/upcloud-python-api | upcloud_api/cloud_manager/tag_mixin.py | https://github.com/UpCloudLtd/upcloud-python-api/blob/954b0ad7c4b932b2be31a95d88975f6b0eeac8ed/upcloud_api/cloud_manager/tag_mixin.py#L28-L38 | def create_tag(self, name, description=None, servers=[]):
"""
Create a new Tag. Only name is mandatory.
Returns the created Tag object.
"""
servers = [str(server) for server in servers]
body = {'tag': Tag(name, description, servers).to_dict()}
res = self.request(... | [
"def",
"create_tag",
"(",
"self",
",",
"name",
",",
"description",
"=",
"None",
",",
"servers",
"=",
"[",
"]",
")",
":",
"servers",
"=",
"[",
"str",
"(",
"server",
")",
"for",
"server",
"in",
"servers",
"]",
"body",
"=",
"{",
"'tag'",
":",
"Tag",
... | Create a new Tag. Only name is mandatory.
Returns the created Tag object. | [
"Create",
"a",
"new",
"Tag",
".",
"Only",
"name",
"is",
"mandatory",
"."
] | python | train |
pachyderm/python-pachyderm | src/python_pachyderm/pfs_client.py | https://github.com/pachyderm/python-pachyderm/blob/1c58cf91d30e03716a4f45213989e890f7b8a78c/src/python_pachyderm/pfs_client.py#L177-L200 | def list_commit(self, repo_name, to_commit=None, from_commit=None, number=0):
"""
Gets a list of CommitInfo objects.
Params:
* repo_name: If only `repo_name` is given, all commits in the repo are
returned.
* to_commit: Optional. Only the ancestors of `to`, including `to`... | [
"def",
"list_commit",
"(",
"self",
",",
"repo_name",
",",
"to_commit",
"=",
"None",
",",
"from_commit",
"=",
"None",
",",
"number",
"=",
"0",
")",
":",
"req",
"=",
"proto",
".",
"ListCommitRequest",
"(",
"repo",
"=",
"proto",
".",
"Repo",
"(",
"name",
... | Gets a list of CommitInfo objects.
Params:
* repo_name: If only `repo_name` is given, all commits in the repo are
returned.
* to_commit: Optional. Only the ancestors of `to`, including `to`
itself, are considered.
* from_commit: Optional. Only the descendants of `from`, ... | [
"Gets",
"a",
"list",
"of",
"CommitInfo",
"objects",
"."
] | python | train |
raiden-network/raiden-contracts | raiden_contracts/utils/private_key.py | https://github.com/raiden-network/raiden-contracts/blob/a7e72a9477f2204b03f3706360ea8d9c0a8e7063/raiden_contracts/utils/private_key.py#L27-L68 | def get_private_key(key_path, password_path=None):
"""Open a JSON-encoded private key and return it
If a password file is provided, uses it to decrypt the key. If not, the
password is asked interactively. Raw hex-encoded private keys are supported,
but deprecated."""
assert key_path, key_path
... | [
"def",
"get_private_key",
"(",
"key_path",
",",
"password_path",
"=",
"None",
")",
":",
"assert",
"key_path",
",",
"key_path",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"key_path",
")",
":",
"log",
".",
"fatal",
"(",
"'%s: no such file'",
",",
... | Open a JSON-encoded private key and return it
If a password file is provided, uses it to decrypt the key. If not, the
password is asked interactively. Raw hex-encoded private keys are supported,
but deprecated. | [
"Open",
"a",
"JSON",
"-",
"encoded",
"private",
"key",
"and",
"return",
"it"
] | python | train |
ncolony/ncolony | ncolony/httpcheck.py | https://github.com/ncolony/ncolony/blob/6ac71bda1de6706fb34244ae4972e36db5f062d3/ncolony/httpcheck.py#L197-L213 | def makeService(opt):
"""Make a service
:params opt: dictionary-like object with 'freq', 'config' and 'messages'
:returns: twisted.application.internet.TimerService that at opt['freq']
checks for stale processes in opt['config'], and sends
restart messages through opt['messages'... | [
"def",
"makeService",
"(",
"opt",
")",
":",
"restarter",
",",
"path",
"=",
"beatcheck",
".",
"parseConfig",
"(",
"opt",
")",
"pool",
"=",
"client",
".",
"HTTPConnectionPool",
"(",
"reactor",
")",
"agent",
"=",
"client",
".",
"Agent",
"(",
"reactor",
"=",... | Make a service
:params opt: dictionary-like object with 'freq', 'config' and 'messages'
:returns: twisted.application.internet.TimerService that at opt['freq']
checks for stale processes in opt['config'], and sends
restart messages through opt['messages'] | [
"Make",
"a",
"service"
] | python | test |
cloud-custodian/cloud-custodian | tools/c7n_gcp/c7n_gcp/mu.py | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_gcp/c7n_gcp/mu.py#L658-L680 | def ensure_sink(self):
"""Ensure the log sink and its pub sub topic exist."""
topic_info = self.pubsub.ensure_topic()
scope, sink_path, sink_info = self.get_sink(topic_info)
client = self.session.client('logging', 'v2', '%s.sinks' % scope)
try:
sink = client.execute_c... | [
"def",
"ensure_sink",
"(",
"self",
")",
":",
"topic_info",
"=",
"self",
".",
"pubsub",
".",
"ensure_topic",
"(",
")",
"scope",
",",
"sink_path",
",",
"sink_info",
"=",
"self",
".",
"get_sink",
"(",
"topic_info",
")",
"client",
"=",
"self",
".",
"session"... | Ensure the log sink and its pub sub topic exist. | [
"Ensure",
"the",
"log",
"sink",
"and",
"its",
"pub",
"sub",
"topic",
"exist",
"."
] | python | train |
NicolasLM/spinach | spinach/contrib/spinachd/mail.py | https://github.com/NicolasLM/spinach/blob/0122f916643101eab5cdc1f3da662b9446e372aa/spinach/contrib/spinachd/mail.py#L38-L43 | def deserialize_email_messages(messages: List[str]):
"""Deserialize EmailMessages passed as task argument."""
return [
pickle.loads(zlib.decompress(base64.b64decode(m)))
for m in messages
] | [
"def",
"deserialize_email_messages",
"(",
"messages",
":",
"List",
"[",
"str",
"]",
")",
":",
"return",
"[",
"pickle",
".",
"loads",
"(",
"zlib",
".",
"decompress",
"(",
"base64",
".",
"b64decode",
"(",
"m",
")",
")",
")",
"for",
"m",
"in",
"messages",... | Deserialize EmailMessages passed as task argument. | [
"Deserialize",
"EmailMessages",
"passed",
"as",
"task",
"argument",
"."
] | python | train |
inasafe/inasafe | extras/xml_tools.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/extras/xml_tools.py#L219-L256 | def xml2object(xml, verbose=False):
"""Generate XML object model from XML file or XML text
This is the inverse operation to the __str__ representation
(up to whitespace).
Input xml can be either an
* xml file
* open xml file object
Return XML_document instance.
"""
# FIXME - can ... | [
"def",
"xml2object",
"(",
"xml",
",",
"verbose",
"=",
"False",
")",
":",
"# FIXME - can we allow xml to be string?",
"# This would depend on minidom's parse function",
"# Input tests",
"if",
"isinstance",
"(",
"xml",
",",
"basestring",
")",
":",
"fid",
"=",
"open",
"(... | Generate XML object model from XML file or XML text
This is the inverse operation to the __str__ representation
(up to whitespace).
Input xml can be either an
* xml file
* open xml file object
Return XML_document instance. | [
"Generate",
"XML",
"object",
"model",
"from",
"XML",
"file",
"or",
"XML",
"text"
] | python | train |
saltstack/salt | salt/modules/bridge.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bridge.py#L290-L305 | def _bsd_stp(br, state, iface):
'''
Internal, sets STP state. On BSD-like, it is required to specify the
STP physical interface
'''
kernel = __grains__['kernel']
if kernel == 'NetBSD':
cmd = _tool_path('brconfig')
else:
cmd = _tool_path('ifconfig')
if not br or not iface... | [
"def",
"_bsd_stp",
"(",
"br",
",",
"state",
",",
"iface",
")",
":",
"kernel",
"=",
"__grains__",
"[",
"'kernel'",
"]",
"if",
"kernel",
"==",
"'NetBSD'",
":",
"cmd",
"=",
"_tool_path",
"(",
"'brconfig'",
")",
"else",
":",
"cmd",
"=",
"_tool_path",
"(",
... | Internal, sets STP state. On BSD-like, it is required to specify the
STP physical interface | [
"Internal",
"sets",
"STP",
"state",
".",
"On",
"BSD",
"-",
"like",
"it",
"is",
"required",
"to",
"specify",
"the",
"STP",
"physical",
"interface"
] | python | train |
diefans/objective | src/objective/core.py | https://github.com/diefans/objective/blob/e2de37f1cd4f5ad147ab3a5dee7dffd6806f2f88/src/objective/core.py#L283-L309 | def _resolve_value(self, value, environment=None):
"""Resolve the value.
Either apply missing or leave the value as is.
:param value: the value either from deserialize or serialize
:param environment: an optional environment
"""
# here we care about Undefined values
... | [
"def",
"_resolve_value",
"(",
"self",
",",
"value",
",",
"environment",
"=",
"None",
")",
":",
"# here we care about Undefined values",
"if",
"value",
"==",
"values",
".",
"Undefined",
":",
"if",
"isinstance",
"(",
"self",
".",
"_missing",
",",
"type",
")",
... | Resolve the value.
Either apply missing or leave the value as is.
:param value: the value either from deserialize or serialize
:param environment: an optional environment | [
"Resolve",
"the",
"value",
"."
] | python | train |
osrg/ryu | ryu/lib/ovs/bridge.py | https://github.com/osrg/ryu/blob/6f906e72c92e10bd0264c9b91a2f7bb85b97780c/ryu/lib/ovs/bridge.py#L164-L175 | def get_controller(self):
"""
Gets the configured OpenFlow controller address.
This method is corresponding to the following ovs-vsctl command::
$ ovs-vsctl get-controller <bridge>
"""
command = ovs_vsctl.VSCtlCommand('get-controller', [self.br_name])
self.r... | [
"def",
"get_controller",
"(",
"self",
")",
":",
"command",
"=",
"ovs_vsctl",
".",
"VSCtlCommand",
"(",
"'get-controller'",
",",
"[",
"self",
".",
"br_name",
"]",
")",
"self",
".",
"run_command",
"(",
"[",
"command",
"]",
")",
"result",
"=",
"command",
".... | Gets the configured OpenFlow controller address.
This method is corresponding to the following ovs-vsctl command::
$ ovs-vsctl get-controller <bridge> | [
"Gets",
"the",
"configured",
"OpenFlow",
"controller",
"address",
"."
] | python | train |
Shapeways/coyote_framework | coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py | https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py#L827-L851 | def wait_until_text_is_not_empty(self, locator, timeout=None):
"""
Waits for an element's text to not be empty
@type locator: webdriverwrapper.support.locator.Locator
@param locator: locator used to find element
@type timeout: int
@param timeout... | [
"def",
"wait_until_text_is_not_empty",
"(",
"self",
",",
"locator",
",",
"timeout",
"=",
"None",
")",
":",
"timeout",
"=",
"timeout",
"if",
"timeout",
"is",
"not",
"None",
"else",
"self",
".",
"timeout",
"self",
".",
"wait_for",
"(",
"locator",
")",
"# fir... | Waits for an element's text to not be empty
@type locator: webdriverwrapper.support.locator.Locator
@param locator: locator used to find element
@type timeout: int
@param timeout: the maximum number of seconds the driver will wait before timing out
... | [
"Waits",
"for",
"an",
"element",
"s",
"text",
"to",
"not",
"be",
"empty"
] | python | train |
fracpete/python-weka-wrapper3 | python/weka/flow/source.py | https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/flow/source.py#L173-L183 | def quickinfo(self):
"""
Returns a short string describing some of the options of the actor.
:return: the info, None if not available
:rtype: str
"""
return "dir: " + str(self.config["dir"]) \
+ ", files: " + str(self.config["list_files"]) \
... | [
"def",
"quickinfo",
"(",
"self",
")",
":",
"return",
"\"dir: \"",
"+",
"str",
"(",
"self",
".",
"config",
"[",
"\"dir\"",
"]",
")",
"+",
"\", files: \"",
"+",
"str",
"(",
"self",
".",
"config",
"[",
"\"list_files\"",
"]",
")",
"+",
"\", dirs: \"",
"+",... | Returns a short string describing some of the options of the actor.
:return: the info, None if not available
:rtype: str | [
"Returns",
"a",
"short",
"string",
"describing",
"some",
"of",
"the",
"options",
"of",
"the",
"actor",
"."
] | python | train |
Alveo/pyalveo | pyalveo/pyalveo.py | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L1509-L1518 | def get_contribution(self, url):
"""Get the details of a particular contribution given it's
url"""
result = self.api_request(url)
# add the contrib id into the metadata
result['id'] = os.path.split(result['url'])[1]
return result | [
"def",
"get_contribution",
"(",
"self",
",",
"url",
")",
":",
"result",
"=",
"self",
".",
"api_request",
"(",
"url",
")",
"# add the contrib id into the metadata",
"result",
"[",
"'id'",
"]",
"=",
"os",
".",
"path",
".",
"split",
"(",
"result",
"[",
"'url'... | Get the details of a particular contribution given it's
url | [
"Get",
"the",
"details",
"of",
"a",
"particular",
"contribution",
"given",
"it",
"s",
"url"
] | python | train |
sveetch/py-css-styleguide | py_css_styleguide/parser.py | https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/parser.py#L29-L52 | def digest_prelude(self, rule):
"""
Walk on rule prelude (aka CSS selector) tokens to return a string of
the value name (from css selector).
Actually only simple selector and selector with descendant combinator
are supported. Using any other selector kind may leads to unexpected... | [
"def",
"digest_prelude",
"(",
"self",
",",
"rule",
")",
":",
"name",
"=",
"[",
"]",
"for",
"token",
"in",
"rule",
".",
"prelude",
":",
"if",
"token",
".",
"type",
"==",
"'ident'",
":",
"name",
".",
"append",
"(",
"token",
".",
"value",
")",
"return... | Walk on rule prelude (aka CSS selector) tokens to return a string of
the value name (from css selector).
Actually only simple selector and selector with descendant combinator
are supported. Using any other selector kind may leads to unexpected
issues.
Arguments:
rul... | [
"Walk",
"on",
"rule",
"prelude",
"(",
"aka",
"CSS",
"selector",
")",
"tokens",
"to",
"return",
"a",
"string",
"of",
"the",
"value",
"name",
"(",
"from",
"css",
"selector",
")",
"."
] | python | train |
cloudendpoints/endpoints-python | endpoints/openapi_generator.py | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/openapi_generator.py#L576-L611 | def __request_message_descriptor(self, request_kind, message_type, method_id,
path):
"""Describes the parameters and body of the request.
Args:
request_kind: The type of request being made.
message_type: messages.Message or ResourceContainer class. The message to
... | [
"def",
"__request_message_descriptor",
"(",
"self",
",",
"request_kind",
",",
"message_type",
",",
"method_id",
",",
"path",
")",
":",
"if",
"isinstance",
"(",
"message_type",
",",
"resource_container",
".",
"ResourceContainer",
")",
":",
"base_message_type",
"=",
... | Describes the parameters and body of the request.
Args:
request_kind: The type of request being made.
message_type: messages.Message or ResourceContainer class. The message to
describe.
method_id: string, Unique method identifier (e.g. 'myapi.items.method')
path: string, HTTP path... | [
"Describes",
"the",
"parameters",
"and",
"body",
"of",
"the",
"request",
"."
] | python | train |
foobarbecue/afterflight | afterflight/logbrowse/views.py | https://github.com/foobarbecue/afterflight/blob/7085f719593f88999dce93f35caec5f15d2991b6/afterflight/logbrowse/views.py#L40-L58 | def upload_progress(request):
"""
AJAX view adapted from django-progressbarupload
Return the upload progress and total length values
"""
if 'X-Progress-ID' in request.GET:
progress_id = request.GET['X-Progress-ID']
elif 'X-Progress-ID' in request.META:
progress_id = request.META... | [
"def",
"upload_progress",
"(",
"request",
")",
":",
"if",
"'X-Progress-ID'",
"in",
"request",
".",
"GET",
":",
"progress_id",
"=",
"request",
".",
"GET",
"[",
"'X-Progress-ID'",
"]",
"elif",
"'X-Progress-ID'",
"in",
"request",
".",
"META",
":",
"progress_id",
... | AJAX view adapted from django-progressbarupload
Return the upload progress and total length values | [
"AJAX",
"view",
"adapted",
"from",
"django",
"-",
"progressbarupload"
] | python | train |
Miserlou/Zappa | zappa/core.py | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/core.py#L1320-L1432 | def deploy_lambda_alb( self,
lambda_arn,
lambda_name,
alb_vpc_config,
timeout
):
"""
The `zappa deploy` functionality for ALB infrastructure.
"""
if n... | [
"def",
"deploy_lambda_alb",
"(",
"self",
",",
"lambda_arn",
",",
"lambda_name",
",",
"alb_vpc_config",
",",
"timeout",
")",
":",
"if",
"not",
"alb_vpc_config",
":",
"raise",
"EnvironmentError",
"(",
"'When creating an ALB, alb_vpc_config must be filled out in zappa_settings... | The `zappa deploy` functionality for ALB infrastructure. | [
"The",
"zappa",
"deploy",
"functionality",
"for",
"ALB",
"infrastructure",
"."
] | python | train |
pypa/pipenv | pipenv/vendor/pexpect/spawnbase.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/spawnbase.py#L192-L238 | def compile_pattern_list(self, patterns):
'''This compiles a pattern-string or a list of pattern-strings.
Patterns must be a StringType, EOF, TIMEOUT, SRE_Pattern, or a list of
those. Patterns may also be None which results in an empty list (you
might do this if waiting for an EOF or TIM... | [
"def",
"compile_pattern_list",
"(",
"self",
",",
"patterns",
")",
":",
"if",
"patterns",
"is",
"None",
":",
"return",
"[",
"]",
"if",
"not",
"isinstance",
"(",
"patterns",
",",
"list",
")",
":",
"patterns",
"=",
"[",
"patterns",
"]",
"# Allow dot to match ... | This compiles a pattern-string or a list of pattern-strings.
Patterns must be a StringType, EOF, TIMEOUT, SRE_Pattern, or a list of
those. Patterns may also be None which results in an empty list (you
might do this if waiting for an EOF or TIMEOUT condition without
expecting any pattern)... | [
"This",
"compiles",
"a",
"pattern",
"-",
"string",
"or",
"a",
"list",
"of",
"pattern",
"-",
"strings",
".",
"Patterns",
"must",
"be",
"a",
"StringType",
"EOF",
"TIMEOUT",
"SRE_Pattern",
"or",
"a",
"list",
"of",
"those",
".",
"Patterns",
"may",
"also",
"b... | python | train |
tjvr/skip | skip/__init__.py | https://github.com/tjvr/skip/blob/ac84f7198079732bf22c3b8cbc0dc1a073b1d539/skip/__init__.py#L134-L141 | def push_script(self, scriptable, script, callback=None):
"""Run the script and add it to the list of threads."""
if script in self.threads:
self.threads[script].finish()
thread = Thread(self.run_script(scriptable, script),
scriptable, callback)
... | [
"def",
"push_script",
"(",
"self",
",",
"scriptable",
",",
"script",
",",
"callback",
"=",
"None",
")",
":",
"if",
"script",
"in",
"self",
".",
"threads",
":",
"self",
".",
"threads",
"[",
"script",
"]",
".",
"finish",
"(",
")",
"thread",
"=",
"Threa... | Run the script and add it to the list of threads. | [
"Run",
"the",
"script",
"and",
"add",
"it",
"to",
"the",
"list",
"of",
"threads",
"."
] | python | train |
suds-community/suds | suds/mx/literal.py | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/mx/literal.py#L207-L226 | def skip(self, content):
"""
Get whether to skip this I{content}.
Should be skipped when the content is optional and value is either None
or an empty list.
@param content: Content to skip.
@type content: L{Object}
@return: True if content is to be skipped.
... | [
"def",
"skip",
"(",
"self",
",",
"content",
")",
":",
"if",
"self",
".",
"optional",
"(",
"content",
")",
":",
"v",
"=",
"content",
".",
"value",
"if",
"v",
"is",
"None",
":",
"return",
"True",
"if",
"isinstance",
"(",
"v",
",",
"(",
"list",
",",... | Get whether to skip this I{content}.
Should be skipped when the content is optional and value is either None
or an empty list.
@param content: Content to skip.
@type content: L{Object}
@return: True if content is to be skipped.
@rtype: bool | [
"Get",
"whether",
"to",
"skip",
"this",
"I",
"{",
"content",
"}",
"."
] | python | train |
seomoz/qless-py | qless/job.py | https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/job.py#L215-L235 | def fail(self, group, message):
'''Mark the particular job as failed, with the provided type, and a
more specific message. By `type`, we mean some phrase that might be
one of several categorical modes of failure. The `message` is
something more job-specific, like perhaps a traceback.
... | [
"def",
"fail",
"(",
"self",
",",
"group",
",",
"message",
")",
":",
"logger",
".",
"warn",
"(",
"'Failing %s (%s): %s'",
",",
"self",
".",
"jid",
",",
"group",
",",
"message",
")",
"return",
"self",
".",
"client",
"(",
"'fail'",
",",
"self",
".",
"ji... | Mark the particular job as failed, with the provided type, and a
more specific message. By `type`, we mean some phrase that might be
one of several categorical modes of failure. The `message` is
something more job-specific, like perhaps a traceback.
This method should __not__ be used to... | [
"Mark",
"the",
"particular",
"job",
"as",
"failed",
"with",
"the",
"provided",
"type",
"and",
"a",
"more",
"specific",
"message",
".",
"By",
"type",
"we",
"mean",
"some",
"phrase",
"that",
"might",
"be",
"one",
"of",
"several",
"categorical",
"modes",
"of"... | python | train |
rduplain/jeni-python | jeni.py | https://github.com/rduplain/jeni-python/blob/feca12ce5e4f0438ae5d7bec59d61826063594f1/jeni.py#L850-L860 | def class_in_progress(stack=None):
"""True if currently inside a class definition, else False."""
if stack is None:
stack = inspect.stack()
for frame in stack:
statement_list = frame[4]
if statement_list is None:
continue
if statement_list[0].strip().startswith('c... | [
"def",
"class_in_progress",
"(",
"stack",
"=",
"None",
")",
":",
"if",
"stack",
"is",
"None",
":",
"stack",
"=",
"inspect",
".",
"stack",
"(",
")",
"for",
"frame",
"in",
"stack",
":",
"statement_list",
"=",
"frame",
"[",
"4",
"]",
"if",
"statement_list... | True if currently inside a class definition, else False. | [
"True",
"if",
"currently",
"inside",
"a",
"class",
"definition",
"else",
"False",
"."
] | python | train |
jay-johnson/network-pipeline | network_pipeline/build_training_request.py | https://github.com/jay-johnson/network-pipeline/blob/4e53ae13fe12085e0cf2e5e1aff947368f4f1ffa/network_pipeline/build_training_request.py#L17-L216 | def build_training_request(
csv_file=ev(
"CSV_FILE",
"/tmp/cleaned_attack_scans.csv"),
meta_file=ev(
"CSV_META_FILE",
"/tmp/cleaned_metadata.json"),
predict_feature=ev(
"PREDICT_FEATURE",
"label_value"),
ignore_featu... | [
"def",
"build_training_request",
"(",
"csv_file",
"=",
"ev",
"(",
"\"CSV_FILE\"",
",",
"\"/tmp/cleaned_attack_scans.csv\"",
")",
",",
"meta_file",
"=",
"ev",
"(",
"\"CSV_META_FILE\"",
",",
"\"/tmp/cleaned_metadata.json\"",
")",
",",
"predict_feature",
"=",
"ev",
"(",
... | build_training_request
:param csv_file: csv file built with prepare_dataset.py
:param meta_file: metadata file built with prepare_dataset.py
:param predict_feature: feature (column) to predict
:param ignore_features: features to remove from the csv
before the split of test +... | [
"build_training_request"
] | python | train |
gwpy/gwpy | gwpy/segments/io/hdf5.py | https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/segments/io/hdf5.py#L105-L128 | def _get_flag_group(h5f, path):
"""Determine the group to use in order to read a flag
"""
# if user chose the path, just use it
if path:
return h5f[path]
# if the user gave us the group directly, use it
if _is_flag_group(h5f):
return h5f
# otherwise try and find a single gr... | [
"def",
"_get_flag_group",
"(",
"h5f",
",",
"path",
")",
":",
"# if user chose the path, just use it",
"if",
"path",
":",
"return",
"h5f",
"[",
"path",
"]",
"# if the user gave us the group directly, use it",
"if",
"_is_flag_group",
"(",
"h5f",
")",
":",
"return",
"h... | Determine the group to use in order to read a flag | [
"Determine",
"the",
"group",
"to",
"use",
"in",
"order",
"to",
"read",
"a",
"flag"
] | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py#L943-L968 | def unregister_engine(self, ident, msg):
"""Unregister an engine that explicitly requested to leave."""
try:
eid = msg['content']['id']
except:
self.log.error("registration::bad engine id for unregistration: %r", ident, exc_info=True)
return
self.log.i... | [
"def",
"unregister_engine",
"(",
"self",
",",
"ident",
",",
"msg",
")",
":",
"try",
":",
"eid",
"=",
"msg",
"[",
"'content'",
"]",
"[",
"'id'",
"]",
"except",
":",
"self",
".",
"log",
".",
"error",
"(",
"\"registration::bad engine id for unregistration: %r\"... | Unregister an engine that explicitly requested to leave. | [
"Unregister",
"an",
"engine",
"that",
"explicitly",
"requested",
"to",
"leave",
"."
] | python | test |
useblocks/groundwork | groundwork/patterns/gw_recipes_pattern.py | https://github.com/useblocks/groundwork/blob/d34fce43f54246ca4db0f7b89e450dcdc847c68c/groundwork/patterns/gw_recipes_pattern.py#L82-L89 | def get(self, name=None):
"""
Gets a list of all recipes, which are registered by the current plugin.
If a name is provided, only the requested recipe is returned or None.
:param: name: Name of the recipe
"""
return self.__app.recipes.get(name, self._plugin) | [
"def",
"get",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"return",
"self",
".",
"__app",
".",
"recipes",
".",
"get",
"(",
"name",
",",
"self",
".",
"_plugin",
")"
] | Gets a list of all recipes, which are registered by the current plugin.
If a name is provided, only the requested recipe is returned or None.
:param: name: Name of the recipe | [
"Gets",
"a",
"list",
"of",
"all",
"recipes",
"which",
"are",
"registered",
"by",
"the",
"current",
"plugin",
".",
"If",
"a",
"name",
"is",
"provided",
"only",
"the",
"requested",
"recipe",
"is",
"returned",
"or",
"None",
"."
] | python | train |
F-Secure/see | plugins/agent.py | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/plugins/agent.py#L85-L95 | def respond(self, output):
"""Generates server response."""
response = {'exit_code': output.code,
'command_output': output.log}
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(bytes(js... | [
"def",
"respond",
"(",
"self",
",",
"output",
")",
":",
"response",
"=",
"{",
"'exit_code'",
":",
"output",
".",
"code",
",",
"'command_output'",
":",
"output",
".",
"log",
"}",
"self",
".",
"send_response",
"(",
"200",
")",
"self",
".",
"send_header",
... | Generates server response. | [
"Generates",
"server",
"response",
"."
] | python | train |
tcalmant/ipopo | pelix/rsa/remoteserviceadmin.py | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/remoteserviceadmin.py#L970-L982 | def get_exception(self):
# type: () -> Optional[Tuple[Any, Any, Any]]
"""
Returns the exception associated to the export
:return: An exception tuple, if any
"""
with self.__lock:
return (
self.__updateexception
if self.__update... | [
"def",
"get_exception",
"(",
"self",
")",
":",
"# type: () -> Optional[Tuple[Any, Any, Any]]",
"with",
"self",
".",
"__lock",
":",
"return",
"(",
"self",
".",
"__updateexception",
"if",
"self",
".",
"__updateexception",
"or",
"self",
".",
"__closed",
"else",
"self... | Returns the exception associated to the export
:return: An exception tuple, if any | [
"Returns",
"the",
"exception",
"associated",
"to",
"the",
"export"
] | python | train |
ouroboroscoding/format-oc-python | FormatOC/__init__.py | https://github.com/ouroboroscoding/format-oc-python/blob/c160b46fe4ff2c92333c776991c712de23991225/FormatOC/__init__.py#L1956-L1983 | def clean(self, value):
"""Clean
Uses the valid method to check which type the value is, and then calls
the correct version of clean on that node
Arguments:
value {mixed} -- The value to clean
Returns:
mixed
"""
# If the value is None and it's optional, return as is
if value is None and self._... | [
"def",
"clean",
"(",
"self",
",",
"value",
")",
":",
"# If the value is None and it's optional, return as is",
"if",
"value",
"is",
"None",
"and",
"self",
".",
"_optional",
":",
"return",
"None",
"# Go through each of the nodes",
"for",
"i",
"in",
"range",
"(",
"l... | Clean
Uses the valid method to check which type the value is, and then calls
the correct version of clean on that node
Arguments:
value {mixed} -- The value to clean
Returns:
mixed | [
"Clean"
] | python | train |
henzk/django-productline | django_productline/tasks.py | https://github.com/henzk/django-productline/blob/24ff156924c1a8c07b99cbb8a1de0a42b8d81f60/django_productline/tasks.py#L270-L279 | def import_context(target_zip):
"""
Overwrite old context.json, use context.json from target_zip
:param target_zip:
:return:
"""
context_path = tasks.get_context_path()
with zipfile.ZipFile(target_zip) as unzipped_data:
with open(context_path, 'w') as context:
context.wri... | [
"def",
"import_context",
"(",
"target_zip",
")",
":",
"context_path",
"=",
"tasks",
".",
"get_context_path",
"(",
")",
"with",
"zipfile",
".",
"ZipFile",
"(",
"target_zip",
")",
"as",
"unzipped_data",
":",
"with",
"open",
"(",
"context_path",
",",
"'w'",
")"... | Overwrite old context.json, use context.json from target_zip
:param target_zip:
:return: | [
"Overwrite",
"old",
"context",
".",
"json",
"use",
"context",
".",
"json",
"from",
"target_zip",
":",
"param",
"target_zip",
":",
":",
"return",
":"
] | python | train |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L290-L338 | def clear_tc(self, owner, data, clear_type):
"""Delete threat intel from ThreatConnect platform.
Args:
owner (str): The ThreatConnect owner.
data (dict): The data for the threat intel to clear.
clear_type (str): The type of clear action.
"""
batch = s... | [
"def",
"clear_tc",
"(",
"self",
",",
"owner",
",",
"data",
",",
"clear_type",
")",
":",
"batch",
"=",
"self",
".",
"tcex",
".",
"batch",
"(",
"owner",
",",
"action",
"=",
"'Delete'",
")",
"tc_type",
"=",
"data",
".",
"get",
"(",
"'type'",
")",
"pat... | Delete threat intel from ThreatConnect platform.
Args:
owner (str): The ThreatConnect owner.
data (dict): The data for the threat intel to clear.
clear_type (str): The type of clear action. | [
"Delete",
"threat",
"intel",
"from",
"ThreatConnect",
"platform",
"."
] | python | train |
rkhleics/wagtailmenus | wagtailmenus/templatetags/menu_tags.py | https://github.com/rkhleics/wagtailmenus/blob/a41f240bed0d362e0d4dd4ef04a230f2b1827a93/wagtailmenus/templatetags/menu_tags.py#L147-L200 | def sub_menu(
context, menuitem_or_page, use_specific=None, allow_repeating_parents=None,
apply_active_classes=None, template='', use_absolute_page_urls=None,
add_sub_menus_inline=None, **kwargs
):
"""
Retrieve the children pages for the `menuitem_or_page` provided, turn them
into menu items, an... | [
"def",
"sub_menu",
"(",
"context",
",",
"menuitem_or_page",
",",
"use_specific",
"=",
"None",
",",
"allow_repeating_parents",
"=",
"None",
",",
"apply_active_classes",
"=",
"None",
",",
"template",
"=",
"''",
",",
"use_absolute_page_urls",
"=",
"None",
",",
"add... | Retrieve the children pages for the `menuitem_or_page` provided, turn them
into menu items, and render them to a template. | [
"Retrieve",
"the",
"children",
"pages",
"for",
"the",
"menuitem_or_page",
"provided",
"turn",
"them",
"into",
"menu",
"items",
"and",
"render",
"them",
"to",
"a",
"template",
"."
] | python | train |
arve0/leicaexperiment | leicaexperiment/experiment.py | https://github.com/arve0/leicaexperiment/blob/c0393c4d51984a506f813319efb66e54c4f2a426/leicaexperiment/experiment.py#L719-L758 | def attributes(path):
"""Get attributes from path based on format --[A-Z]. Returns namedtuple
with upper case attributes equal to what found in path (string) and lower
case as int. If path holds several occurrences of same character, only the
last one is kept.
>>> attrs = attributes('/folder/fi... | [
"def",
"attributes",
"(",
"path",
")",
":",
"# number of charcters set to numbers have changed in LAS AF X !!",
"matches",
"=",
"re",
".",
"findall",
"(",
"'--([A-Z]{1})([0-9]{2,4})'",
",",
"path",
")",
"keys",
"=",
"[",
"]",
"values",
"=",
"[",
"]",
"for",
"k",
... | Get attributes from path based on format --[A-Z]. Returns namedtuple
with upper case attributes equal to what found in path (string) and lower
case as int. If path holds several occurrences of same character, only the
last one is kept.
>>> attrs = attributes('/folder/file--X00-X01.tif')
>>>... | [
"Get",
"attributes",
"from",
"path",
"based",
"on",
"format",
"--",
"[",
"A",
"-",
"Z",
"]",
".",
"Returns",
"namedtuple",
"with",
"upper",
"case",
"attributes",
"equal",
"to",
"what",
"found",
"in",
"path",
"(",
"string",
")",
"and",
"lower",
"case",
... | python | valid |
zhanglab/psamm | psamm/datasource/native.py | https://github.com/zhanglab/psamm/blob/dc427848c4f9d109ca590f0afa024c63b685b3f4/psamm/datasource/native.py#L1487-L1497 | def write_reactions(self, stream, reactions, properties=None):
"""Write iterable of reactions as YAML object to stream.
Args:
stream: File-like object.
compounds: Iterable of reaction entries.
properties: Set of reaction properties to output (or None to output
... | [
"def",
"write_reactions",
"(",
"self",
",",
"stream",
",",
"reactions",
",",
"properties",
"=",
"None",
")",
":",
"self",
".",
"_write_entries",
"(",
"stream",
",",
"reactions",
",",
"self",
".",
"convert_reaction_entry",
",",
"properties",
")"
] | Write iterable of reactions as YAML object to stream.
Args:
stream: File-like object.
compounds: Iterable of reaction entries.
properties: Set of reaction properties to output (or None to output
all). | [
"Write",
"iterable",
"of",
"reactions",
"as",
"YAML",
"object",
"to",
"stream",
"."
] | python | train |
econ-ark/HARK | HARK/cAndCwithStickyE/StickyEmodel.py | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/cAndCwithStickyE/StickyEmodel.py#L98-L131 | def getShocks(self):
'''
Gets permanent and transitory shocks (combining idiosyncratic and aggregate shocks), but
only consumers who update their macroeconomic beliefs this period incorporate all pre-
viously unnoticed aggregate permanent shocks. Agents correctly observe the level of al... | [
"def",
"getShocks",
"(",
"self",
")",
":",
"# The strange syntax here is so that both StickyEconsumerType and StickyEmarkovConsumerType",
"# run the getShocks method of their first superclass: AggShockConsumerType and",
"# AggShockMarkovConsumerType respectively. This will be simplified in Python 3... | Gets permanent and transitory shocks (combining idiosyncratic and aggregate shocks), but
only consumers who update their macroeconomic beliefs this period incorporate all pre-
viously unnoticed aggregate permanent shocks. Agents correctly observe the level of all
real variables (market resource... | [
"Gets",
"permanent",
"and",
"transitory",
"shocks",
"(",
"combining",
"idiosyncratic",
"and",
"aggregate",
"shocks",
")",
"but",
"only",
"consumers",
"who",
"update",
"their",
"macroeconomic",
"beliefs",
"this",
"period",
"incorporate",
"all",
"pre",
"-",
"viously... | python | train |
eng-tools/sfsimodels | sfsimodels/loader.py | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/loader.py#L33-L53 | def load_soil_sample_data(sp):
"""
Sample data for the Soil object
:param sp: Soil Object
:return:
"""
# soil
sp.g_mod = 60.0e6 # [Pa]
sp.phi = 30 # [degrees]
sp.relative_density = .40 # [decimal]
sp.gwl = 2. # [m], ground water level
sp.unit_dry_weight = 17000 # [N/m3]
... | [
"def",
"load_soil_sample_data",
"(",
"sp",
")",
":",
"# soil",
"sp",
".",
"g_mod",
"=",
"60.0e6",
"# [Pa]",
"sp",
".",
"phi",
"=",
"30",
"# [degrees]",
"sp",
".",
"relative_density",
"=",
".40",
"# [decimal]",
"sp",
".",
"gwl",
"=",
"2.",
"# [m], ground wa... | Sample data for the Soil object
:param sp: Soil Object
:return: | [
"Sample",
"data",
"for",
"the",
"Soil",
"object",
":",
"param",
"sp",
":",
"Soil",
"Object",
":",
"return",
":"
] | python | train |
ayust/kitnirc | kitnirc/modular.py | https://github.com/ayust/kitnirc/blob/cf19fe39219da75f053e1a3976bf21331b6fefea/kitnirc/modular.py#L73-L83 | def handle_event(self, event, client, args):
"""Dispatch an event to its handler.
Note: the handler does not receive the event which triggered its call.
If you want to handle more than one event, it's recommended to put the
shared handling in a separate function, and create wrapper hand... | [
"def",
"handle_event",
"(",
"self",
",",
"event",
",",
"client",
",",
"args",
")",
":",
"handler",
"=",
"self",
".",
"event_handlers",
".",
"get",
"(",
"event",
")",
"if",
"handler",
":",
"return",
"handler",
"(",
"client",
",",
"*",
"args",
")"
] | Dispatch an event to its handler.
Note: the handler does not receive the event which triggered its call.
If you want to handle more than one event, it's recommended to put the
shared handling in a separate function, and create wrapper handlers
that call the shared function. | [
"Dispatch",
"an",
"event",
"to",
"its",
"handler",
"."
] | python | train |
gem/oq-engine | openquake/hazardlib/gsim/munson_thurber_1997.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/munson_thurber_1997.py#L111-L151 | def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
# assign constant
log10e = np.log10(np.e)
# Distance... | [
"def",
"get_mean_and_stddevs",
"(",
"self",
",",
"sites",
",",
"rup",
",",
"dists",
",",
"imt",
",",
"stddev_types",
")",
":",
"# assign constant",
"log10e",
"=",
"np",
".",
"log10",
"(",
"np",
".",
"e",
")",
"# Distance term",
"R",
"=",
"np",
".",
"sq... | See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values. | [
"See",
":",
"meth",
":",
"superclass",
"method",
"<",
".",
"base",
".",
"GroundShakingIntensityModel",
".",
"get_mean_and_stddevs",
">",
"for",
"spec",
"of",
"input",
"and",
"result",
"values",
"."
] | python | train |
pycontribs/pyrax | pyrax/object_storage.py | https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/object_storage.py#L1446-L1465 | def copy_object(self, container, obj, new_container, new_obj_name=None,
content_type=None):
"""
Copies the object to the new container, optionally giving it a new name.
If you copy to the same container, you must supply a different name.
Returns the etag of the newly-copied ... | [
"def",
"copy_object",
"(",
"self",
",",
"container",
",",
"obj",
",",
"new_container",
",",
"new_obj_name",
"=",
"None",
",",
"content_type",
"=",
"None",
")",
":",
"nm",
"=",
"new_obj_name",
"or",
"utils",
".",
"get_name",
"(",
"obj",
")",
"uri",
"=",
... | Copies the object to the new container, optionally giving it a new name.
If you copy to the same container, you must supply a different name.
Returns the etag of the newly-copied object.
You can optionally change the content_type of the object by supplying
that in the 'content_type' pa... | [
"Copies",
"the",
"object",
"to",
"the",
"new",
"container",
"optionally",
"giving",
"it",
"a",
"new",
"name",
".",
"If",
"you",
"copy",
"to",
"the",
"same",
"container",
"you",
"must",
"supply",
"a",
"different",
"name",
"."
] | python | train |
dnanexus/dx-toolkit | src/python/dxpy/bindings/dxfile_functions.py | https://github.com/dnanexus/dx-toolkit/blob/74befb53ad90fcf902d8983ae6d74580f402d619/src/python/dxpy/bindings/dxfile_functions.py#L97-L135 | def download_dxfile(dxid, filename, chunksize=dxfile.DEFAULT_BUFFER_SIZE, append=False, show_progress=False,
project=None, describe_output=None, **kwargs):
'''
:param dxid: DNAnexus file ID or DXFile (file handler) object
:type dxid: string or DXFile
:param filename: Local filename
... | [
"def",
"download_dxfile",
"(",
"dxid",
",",
"filename",
",",
"chunksize",
"=",
"dxfile",
".",
"DEFAULT_BUFFER_SIZE",
",",
"append",
"=",
"False",
",",
"show_progress",
"=",
"False",
",",
"project",
"=",
"None",
",",
"describe_output",
"=",
"None",
",",
"*",
... | :param dxid: DNAnexus file ID or DXFile (file handler) object
:type dxid: string or DXFile
:param filename: Local filename
:type filename: string
:param append: If True, appends to the local file (default is to truncate local file if it exists)
:type append: boolean
:param project: project to us... | [
":",
"param",
"dxid",
":",
"DNAnexus",
"file",
"ID",
"or",
"DXFile",
"(",
"file",
"handler",
")",
"object",
":",
"type",
"dxid",
":",
"string",
"or",
"DXFile",
":",
"param",
"filename",
":",
"Local",
"filename",
":",
"type",
"filename",
":",
"string",
... | python | train |
knipknap/SpiffWorkflow | SpiffWorkflow/serializer/prettyxml.py | https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/serializer/prettyxml.py#L100-L129 | def deserialize_logical(self, node):
"""
Reads the logical tag from the given node, returns a Condition object.
node -- the xml node (xml.dom.minidom.Node)
"""
term1_attrib = node.getAttribute('left-field')
term1_value = node.getAttribute('left-value')
op = node.... | [
"def",
"deserialize_logical",
"(",
"self",
",",
"node",
")",
":",
"term1_attrib",
"=",
"node",
".",
"getAttribute",
"(",
"'left-field'",
")",
"term1_value",
"=",
"node",
".",
"getAttribute",
"(",
"'left-value'",
")",
"op",
"=",
"node",
".",
"nodeName",
".",
... | Reads the logical tag from the given node, returns a Condition object.
node -- the xml node (xml.dom.minidom.Node) | [
"Reads",
"the",
"logical",
"tag",
"from",
"the",
"given",
"node",
"returns",
"a",
"Condition",
"object",
"."
] | python | valid |
SBRG/ssbio | ssbio/protein/sequence/properties/tmhmm.py | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/sequence/properties/tmhmm.py#L101-L169 | def label_TM_tmhmm_residue_numbers_and_leaflets(tmhmm_seq):
"""Determine the residue numbers of the TM-helix residues that cross the membrane and label them by leaflet.
Args:
tmhmm_seq: g.protein.representative_sequence.seq_record.letter_annotations['TM-tmhmm']
Returns:
leaflet_dict: a dic... | [
"def",
"label_TM_tmhmm_residue_numbers_and_leaflets",
"(",
"tmhmm_seq",
")",
":",
"TM_number_dict",
"=",
"{",
"}",
"T_index",
"=",
"[",
"]",
"T_residue",
"=",
"[",
"]",
"residue_count",
"=",
"1",
"for",
"residue_label",
"in",
"tmhmm_seq",
":",
"if",
"residue_lab... | Determine the residue numbers of the TM-helix residues that cross the membrane and label them by leaflet.
Args:
tmhmm_seq: g.protein.representative_sequence.seq_record.letter_annotations['TM-tmhmm']
Returns:
leaflet_dict: a dictionary with leaflet_variable : [residue list] where the variable i... | [
"Determine",
"the",
"residue",
"numbers",
"of",
"the",
"TM",
"-",
"helix",
"residues",
"that",
"cross",
"the",
"membrane",
"and",
"label",
"them",
"by",
"leaflet",
"."
] | python | train |
cqparts/cqparts | src/cqparts/search.py | https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/search.py#L151-L220 | def common_criteria(**common):
"""
Wrap a function to always call with the given ``common`` named parameters.
:property common: criteria common to your function call
:return: decorator function
:rtype: :class:`function`
.. doctest::
>>> import cqparts
>>> from cqparts.search i... | [
"def",
"common_criteria",
"(",
"*",
"*",
"common",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"def",
"inner",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"merged_kwargs",
"=",
"copy",
"(",
"common",
")",
"merged_kwargs",
".",
"upda... | Wrap a function to always call with the given ``common`` named parameters.
:property common: criteria common to your function call
:return: decorator function
:rtype: :class:`function`
.. doctest::
>>> import cqparts
>>> from cqparts.search import register, search, find
>>> fr... | [
"Wrap",
"a",
"function",
"to",
"always",
"call",
"with",
"the",
"given",
"common",
"named",
"parameters",
"."
] | python | train |
CartoDB/cartoframes | cartoframes/datasets.py | https://github.com/CartoDB/cartoframes/blob/c94238a545f3dec45963dac3892540942b6f0df8/cartoframes/datasets.py#L313-L324 | def _encode_decode_decorator(func):
"""decorator for encoding and decoding geoms"""
def wrapper(*args):
"""error catching"""
try:
processed_geom = func(*args)
return processed_geom
except ImportError as err:
raise ImportError('The Python package `shape... | [
"def",
"_encode_decode_decorator",
"(",
"func",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
")",
":",
"\"\"\"error catching\"\"\"",
"try",
":",
"processed_geom",
"=",
"func",
"(",
"*",
"args",
")",
"return",
"processed_geom",
"except",
"ImportError",
"as",
"... | decorator for encoding and decoding geoms | [
"decorator",
"for",
"encoding",
"and",
"decoding",
"geoms"
] | python | train |
cltl/KafNafParserPy | KafNafParserPy/feature_extractor/constituency.py | https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/feature_extractor/constituency.py#L218-L248 | def get_deepest_subsumer(self,list_terms):
'''
Returns the labels of the deepest node that subsumes all the terms in the list of terms id's provided
'''
#To store with how many terms every nonterminal appears
count_per_no_terminal = defaultdict(int)
#To ... | [
"def",
"get_deepest_subsumer",
"(",
"self",
",",
"list_terms",
")",
":",
"#To store with how many terms every nonterminal appears",
"count_per_no_terminal",
"=",
"defaultdict",
"(",
"int",
")",
"#To store the total deep of each noter for all the term ides (as we want the deepest)",
"... | Returns the labels of the deepest node that subsumes all the terms in the list of terms id's provided | [
"Returns",
"the",
"labels",
"of",
"the",
"deepest",
"node",
"that",
"subsumes",
"all",
"the",
"terms",
"in",
"the",
"list",
"of",
"terms",
"id",
"s",
"provided"
] | python | train |
pyviz/holoviews | holoviews/core/util.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/core/util.py#L733-L746 | def _process_underscores(self, tokens):
"Strip underscores to make sure the number is correct after join"
groups = [[str(''.join(el))] if b else list(el)
for (b,el) in itertools.groupby(tokens, lambda k: k=='_')]
flattened = [el for group in groups for el in group]
proc... | [
"def",
"_process_underscores",
"(",
"self",
",",
"tokens",
")",
":",
"groups",
"=",
"[",
"[",
"str",
"(",
"''",
".",
"join",
"(",
"el",
")",
")",
"]",
"if",
"b",
"else",
"list",
"(",
"el",
")",
"for",
"(",
"b",
",",
"el",
")",
"in",
"itertools"... | Strip underscores to make sure the number is correct after join | [
"Strip",
"underscores",
"to",
"make",
"sure",
"the",
"number",
"is",
"correct",
"after",
"join"
] | python | train |
nens/turn | turn/tools.py | https://github.com/nens/turn/blob/98e806a0749ada0ddfd04b3c29fb04c15bf5ac18/turn/tools.py#L56-L83 | def lock(resources, *args, **kwargs):
""" Lock resources from the command line, for example for maintenance. """
# all resources are locked if nothing is specified
if not resources:
client = redis.Redis(decode_responses=True, **kwargs)
resources = find_resources(client)
if not resources... | [
"def",
"lock",
"(",
"resources",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# all resources are locked if nothing is specified",
"if",
"not",
"resources",
":",
"client",
"=",
"redis",
".",
"Redis",
"(",
"decode_responses",
"=",
"True",
",",
"*",
"... | Lock resources from the command line, for example for maintenance. | [
"Lock",
"resources",
"from",
"the",
"command",
"line",
"for",
"example",
"for",
"maintenance",
"."
] | python | train |
alvinwan/TexSoup | TexSoup/data.py | https://github.com/alvinwan/TexSoup/blob/63323ed71510fd2351102b8c36660a3b7703cead/TexSoup/data.py#L413-L433 | def find(self, name=None, **attrs):
r"""First descendant node matching criteria.
Returns None if no descendant node found.
:return: descendant node matching criteria
:rtype: Union[None,TexExpr]
>>> from TexSoup import TexSoup
>>> soup = TexSoup(r'''
... \sectio... | [
"def",
"find",
"(",
"self",
",",
"name",
"=",
"None",
",",
"*",
"*",
"attrs",
")",
":",
"try",
":",
"return",
"next",
"(",
"self",
".",
"find_all",
"(",
"name",
",",
"*",
"*",
"attrs",
")",
")",
"except",
"StopIteration",
":",
"return",
"None"
] | r"""First descendant node matching criteria.
Returns None if no descendant node found.
:return: descendant node matching criteria
:rtype: Union[None,TexExpr]
>>> from TexSoup import TexSoup
>>> soup = TexSoup(r'''
... \section{Ooo}
... \textit{eee}
... ... | [
"r",
"First",
"descendant",
"node",
"matching",
"criteria",
"."
] | python | train |
bunq/sdk_python | bunq/sdk/json/adapters.py | https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/json/adapters.py#L260-L285 | def deserialize(cls, target_class, obj):
"""
:type target_class: context.InstallationContext|type
:type obj: dict
:rtype: context.InstallationContext
"""
installation_context = target_class.__new__(target_class)
private_key_client = security.rsa_key_from_string(... | [
"def",
"deserialize",
"(",
"cls",
",",
"target_class",
",",
"obj",
")",
":",
"installation_context",
"=",
"target_class",
".",
"__new__",
"(",
"target_class",
")",
"private_key_client",
"=",
"security",
".",
"rsa_key_from_string",
"(",
"obj",
"[",
"cls",
".",
... | :type target_class: context.InstallationContext|type
:type obj: dict
:rtype: context.InstallationContext | [
":",
"type",
"target_class",
":",
"context",
".",
"InstallationContext|type",
":",
"type",
"obj",
":",
"dict"
] | python | train |
krischer/mtspec | mtspec/multitaper.py | https://github.com/krischer/mtspec/blob/06561b6370f13fcb2e731470ba0f7314f4b2362d/mtspec/multitaper.py#L623-L749 | def mt_deconvolve(data_a, data_b, delta, nfft=None, time_bandwidth=None,
number_of_tapers=None, weights="adaptive", demean=True,
fmax=0.0):
"""
Deconvolve two time series using multitapers.
This uses the eigencoefficients and the weights from the multitaper
spectral ... | [
"def",
"mt_deconvolve",
"(",
"data_a",
",",
"data_b",
",",
"delta",
",",
"nfft",
"=",
"None",
",",
"time_bandwidth",
"=",
"None",
",",
"number_of_tapers",
"=",
"None",
",",
"weights",
"=",
"\"adaptive\"",
",",
"demean",
"=",
"True",
",",
"fmax",
"=",
"0.... | Deconvolve two time series using multitapers.
This uses the eigencoefficients and the weights from the multitaper
spectral estimations and more or less follows this paper:
.. |br| raw:: html
<br />
**Receiver Functions from Multiple-Taper Spectral Correlation Estimates**
*Jeffrey Park, V... | [
"Deconvolve",
"two",
"time",
"series",
"using",
"multitapers",
"."
] | python | train |
dpkp/kafka-python | kafka/client_async.py | https://github.com/dpkp/kafka-python/blob/f6a8a38937688ea2cc5dc13d3d1039493be5c9b5/kafka/client_async.py#L440-L457 | def is_disconnected(self, node_id):
"""Check whether the node connection has been disconnected or failed.
A disconnected node has either been closed or has failed. Connection
failures are usually transient and can be resumed in the next ready()
call, but there are cases where transient ... | [
"def",
"is_disconnected",
"(",
"self",
",",
"node_id",
")",
":",
"conn",
"=",
"self",
".",
"_conns",
".",
"get",
"(",
"node_id",
")",
"if",
"conn",
"is",
"None",
":",
"return",
"False",
"return",
"conn",
".",
"disconnected",
"(",
")"
] | Check whether the node connection has been disconnected or failed.
A disconnected node has either been closed or has failed. Connection
failures are usually transient and can be resumed in the next ready()
call, but there are cases where transient failures need to be caught
and re-acted... | [
"Check",
"whether",
"the",
"node",
"connection",
"has",
"been",
"disconnected",
"or",
"failed",
"."
] | python | train |
hellock/icrawler | icrawler/utils/proxy_pool.py | https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/proxy_pool.py#L177-L189 | def add_proxy(self, proxy):
"""Add a valid proxy into pool
You must call `add_proxy` method to add a proxy into pool instead of
directly operate the `proxies` variable.
"""
protocol = proxy.protocol
addr = proxy.addr
if addr in self.proxies:
self.prox... | [
"def",
"add_proxy",
"(",
"self",
",",
"proxy",
")",
":",
"protocol",
"=",
"proxy",
".",
"protocol",
"addr",
"=",
"proxy",
".",
"addr",
"if",
"addr",
"in",
"self",
".",
"proxies",
":",
"self",
".",
"proxies",
"[",
"protocol",
"]",
"[",
"addr",
"]",
... | Add a valid proxy into pool
You must call `add_proxy` method to add a proxy into pool instead of
directly operate the `proxies` variable. | [
"Add",
"a",
"valid",
"proxy",
"into",
"pool"
] | python | train |
vmlaker/mpipe | src/Stage.py | https://github.com/vmlaker/mpipe/blob/5a1804cf64271931f0cd3e4fff3e2b38291212dd/src/Stage.py#L42-L55 | def get(self, timeout=None):
"""Retrieve results from all the output tubes."""
valid = False
result = None
for tube in self._output_tubes:
if timeout:
valid, result = tube.get(timeout)
if valid:
result = result[0]
... | [
"def",
"get",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"valid",
"=",
"False",
"result",
"=",
"None",
"for",
"tube",
"in",
"self",
".",
"_output_tubes",
":",
"if",
"timeout",
":",
"valid",
",",
"result",
"=",
"tube",
".",
"get",
"(",
"tim... | Retrieve results from all the output tubes. | [
"Retrieve",
"results",
"from",
"all",
"the",
"output",
"tubes",
"."
] | python | train |
mitsei/dlkit | dlkit/json_/grading/objects.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/grading/objects.py#L659-L677 | def set_lowest_numeric_score(self, score):
"""Sets the lowest numeric score.
arg: score (decimal): the lowest numeric score
raise: InvalidArgument - ``score`` is invalid
raise: NoAccess - ``score`` cannot be modified
*compliance: mandatory -- This method must be implemented... | [
"def",
"set_lowest_numeric_score",
"(",
"self",
",",
"score",
")",
":",
"# Implemented from template for osid.grading.GradeSystemForm.set_lowest_numeric_score",
"if",
"self",
".",
"get_lowest_numeric_score_metadata",
"(",
")",
".",
"is_read_only",
"(",
")",
":",
"raise",
"e... | Sets the lowest numeric score.
arg: score (decimal): the lowest numeric score
raise: InvalidArgument - ``score`` is invalid
raise: NoAccess - ``score`` cannot be modified
*compliance: mandatory -- This method must be implemented.* | [
"Sets",
"the",
"lowest",
"numeric",
"score",
"."
] | python | train |
ninuxorg/nodeshot | nodeshot/core/metrics/signals.py | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/metrics/signals.py#L17-L25 | def user_loggedin(sender, **kwargs):
""" collect metrics about user logins """
values = {
'value': 1,
'path': kwargs['request'].path,
'user_id': str(kwargs['user'].pk),
'username': kwargs['user'].username,
}
write('user_logins', values=values) | [
"def",
"user_loggedin",
"(",
"sender",
",",
"*",
"*",
"kwargs",
")",
":",
"values",
"=",
"{",
"'value'",
":",
"1",
",",
"'path'",
":",
"kwargs",
"[",
"'request'",
"]",
".",
"path",
",",
"'user_id'",
":",
"str",
"(",
"kwargs",
"[",
"'user'",
"]",
".... | collect metrics about user logins | [
"collect",
"metrics",
"about",
"user",
"logins"
] | python | train |
pypa/pipenv | pipenv/vendor/requirementslib/models/requirements.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/requirements.py#L483-L493 | def parse_hashes(self):
# type: () -> None
"""
Parse hashes from *self.line* and set them on the current object.
:returns: Nothing
:rtype: None
"""
line, hashes = self.split_hashes(self.line)
self.hashes = hashes
self.line = line | [
"def",
"parse_hashes",
"(",
"self",
")",
":",
"# type: () -> None",
"line",
",",
"hashes",
"=",
"self",
".",
"split_hashes",
"(",
"self",
".",
"line",
")",
"self",
".",
"hashes",
"=",
"hashes",
"self",
".",
"line",
"=",
"line"
] | Parse hashes from *self.line* and set them on the current object.
:returns: Nothing
:rtype: None | [
"Parse",
"hashes",
"from",
"*",
"self",
".",
"line",
"*",
"and",
"set",
"them",
"on",
"the",
"current",
"object",
".",
":",
"returns",
":",
"Nothing",
":",
"rtype",
":",
"None"
] | python | train |
StagPython/StagPy | stagpy/time_series.py | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/time_series.py#L55-L93 | def get_time_series(sdat, var, tstart, tend):
"""Extract or compute and rescale a time series.
Args:
sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance.
var (str): time series name, a key of :data:`stagpy.phyvars.TIME`
or :data:`stagpy.phyvars.TIME_EXTRA`.
... | [
"def",
"get_time_series",
"(",
"sdat",
",",
"var",
",",
"tstart",
",",
"tend",
")",
":",
"tseries",
"=",
"sdat",
".",
"tseries_between",
"(",
"tstart",
",",
"tend",
")",
"if",
"var",
"in",
"tseries",
".",
"columns",
":",
"series",
"=",
"tseries",
"[",
... | Extract or compute and rescale a time series.
Args:
sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance.
var (str): time series name, a key of :data:`stagpy.phyvars.TIME`
or :data:`stagpy.phyvars.TIME_EXTRA`.
tstart (float): starting time of desired series. Set ... | [
"Extract",
"or",
"compute",
"and",
"rescale",
"a",
"time",
"series",
"."
] | python | train |
CivicSpleen/ambry | ambry/identity.py | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/identity.py#L1597-L1603 | def add_partition(self, p):
"""Add a partition identity as a child of a dataset identity."""
if not self.partitions:
self.partitions = {}
self.partitions[p.vid] = p | [
"def",
"add_partition",
"(",
"self",
",",
"p",
")",
":",
"if",
"not",
"self",
".",
"partitions",
":",
"self",
".",
"partitions",
"=",
"{",
"}",
"self",
".",
"partitions",
"[",
"p",
".",
"vid",
"]",
"=",
"p"
] | Add a partition identity as a child of a dataset identity. | [
"Add",
"a",
"partition",
"identity",
"as",
"a",
"child",
"of",
"a",
"dataset",
"identity",
"."
] | python | train |
greenbender/pynntp | nntp/nntp.py | https://github.com/greenbender/pynntp/blob/991a76331cdf5d8f9dbf5b18f6e29adc80749a2f/nntp/nntp.py#L254-L301 | def __info_gzip_gen(self):
"""Generator for the lines of a compressed info (textual) response.
Compressed responses are an extension to the NNTP protocol supported by
some usenet servers to reduce the bandwidth of heavily used range style
commands that can return large amounts of textua... | [
"def",
"__info_gzip_gen",
"(",
"self",
")",
":",
"self",
".",
"__generating",
"=",
"True",
"inflate",
"=",
"zlib",
".",
"decompressobj",
"(",
"15",
"+",
"32",
")",
"done",
",",
"buf",
"=",
"False",
",",
"fifo",
".",
"Fifo",
"(",
")",
"while",
"not",
... | Generator for the lines of a compressed info (textual) response.
Compressed responses are an extension to the NNTP protocol supported by
some usenet servers to reduce the bandwidth of heavily used range style
commands that can return large amounts of textual data.
This function handles... | [
"Generator",
"for",
"the",
"lines",
"of",
"a",
"compressed",
"info",
"(",
"textual",
")",
"response",
"."
] | python | test |
chaoss/grimoirelab-elk | grimoire_elk/enriched/jira.py | https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/jira.py#L159-L178 | def get_identities(self, item):
"""Return the identities from an item"""
item = item['data']
for field in ["assignee", "reporter", "creator"]:
if field not in item["fields"]:
continue
if item["fields"][field]:
user = self.get_sh_identity(... | [
"def",
"get_identities",
"(",
"self",
",",
"item",
")",
":",
"item",
"=",
"item",
"[",
"'data'",
"]",
"for",
"field",
"in",
"[",
"\"assignee\"",
",",
"\"reporter\"",
",",
"\"creator\"",
"]",
":",
"if",
"field",
"not",
"in",
"item",
"[",
"\"fields\"",
"... | Return the identities from an item | [
"Return",
"the",
"identities",
"from",
"an",
"item"
] | python | train |
Robpol86/libnl | libnl/genl/genl.py | https://github.com/Robpol86/libnl/blob/274e9fdaa39822d06ef70b799ed4a95937a4d923/libnl/genl/genl.py#L44-L64 | def genl_send_simple(sk, family, cmd, version, flags):
"""Send a Generic Netlink message consisting only of a header.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/genl.c#L84
This function is a shortcut for sending a Generic Netlink message without any message payload. The message will only
... | [
"def",
"genl_send_simple",
"(",
"sk",
",",
"family",
",",
"cmd",
",",
"version",
",",
"flags",
")",
":",
"hdr",
"=",
"genlmsghdr",
"(",
"cmd",
"=",
"cmd",
",",
"version",
"=",
"version",
")",
"return",
"int",
"(",
"nl_send_simple",
"(",
"sk",
",",
"f... | Send a Generic Netlink message consisting only of a header.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/genl.c#L84
This function is a shortcut for sending a Generic Netlink message without any message payload. The message will only
consist of the Netlink and Generic Netlink headers. The hea... | [
"Send",
"a",
"Generic",
"Netlink",
"message",
"consisting",
"only",
"of",
"a",
"header",
"."
] | python | train |
quasipedia/simpleactors | simpleactors.py | https://github.com/quasipedia/simpleactors/blob/4253da2d10b3df080b5e7b3fbee03aa6dd10db07/simpleactors.py#L115-L121 | def run(self):
'''Run until there are no events to be processed.'''
# We left-append rather than emit (right-append) because some message
# may have been already queued for execution before the director runs.
global_event_queue.appendleft((INITIATE, self, (), {}))
while global_ev... | [
"def",
"run",
"(",
"self",
")",
":",
"# We left-append rather than emit (right-append) because some message",
"# may have been already queued for execution before the director runs.",
"global_event_queue",
".",
"appendleft",
"(",
"(",
"INITIATE",
",",
"self",
",",
"(",
")",
","... | Run until there are no events to be processed. | [
"Run",
"until",
"there",
"are",
"no",
"events",
"to",
"be",
"processed",
"."
] | python | train |
project-rig/rig | rig/machine_control/machine_controller.py | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/machine_control/machine_controller.py#L1373-L1491 | def load_application(self, *args, **kwargs):
"""Load an application to a set of application cores.
This method guarantees that once it returns, all required cores will
have been loaded. If this is not possible after a small number of
attempts, a :py:exc:`.SpiNNakerLoadingError` will be ... | [
"def",
"load_application",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Get keyword arguments",
"app_id",
"=",
"kwargs",
".",
"pop",
"(",
"\"app_id\"",
")",
"wait",
"=",
"kwargs",
".",
"pop",
"(",
"\"wait\"",
")",
"n_tries",
"=",
... | Load an application to a set of application cores.
This method guarantees that once it returns, all required cores will
have been loaded. If this is not possible after a small number of
attempts, a :py:exc:`.SpiNNakerLoadingError` will be raised.
This method can be called in either of ... | [
"Load",
"an",
"application",
"to",
"a",
"set",
"of",
"application",
"cores",
"."
] | python | train |
dmlc/gluon-nlp | scripts/parsing/common/data.py | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/data.py#L288-L303 | def rel2id(self, xs):
"""Map relation(s) to id(s)
Parameters
----------
xs : str or list
relation
Returns
-------
int or list
id(s) of relation
"""
if isinstance(xs, list):
return [self._rel2id[x] for x in xs]
... | [
"def",
"rel2id",
"(",
"self",
",",
"xs",
")",
":",
"if",
"isinstance",
"(",
"xs",
",",
"list",
")",
":",
"return",
"[",
"self",
".",
"_rel2id",
"[",
"x",
"]",
"for",
"x",
"in",
"xs",
"]",
"return",
"self",
".",
"_rel2id",
"[",
"xs",
"]"
] | Map relation(s) to id(s)
Parameters
----------
xs : str or list
relation
Returns
-------
int or list
id(s) of relation | [
"Map",
"relation",
"(",
"s",
")",
"to",
"id",
"(",
"s",
")"
] | python | train |
saltstack/salt | salt/modules/btrfs.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/btrfs.py#L894-L1031 | def subvolume_list(path, parent_id=False, absolute=False,
ogeneration=False, generation=False,
subvolumes=False, uuid=False, parent_uuid=False,
sent_subvolume_uuid=False, snapshots=False,
readonly=False, deleted=False, generation_cmp=None,
... | [
"def",
"subvolume_list",
"(",
"path",
",",
"parent_id",
"=",
"False",
",",
"absolute",
"=",
"False",
",",
"ogeneration",
"=",
"False",
",",
"generation",
"=",
"False",
",",
"subvolumes",
"=",
"False",
",",
"uuid",
"=",
"False",
",",
"parent_uuid",
"=",
"... | List the subvolumes present in the filesystem.
path
Mount point for the subvolume
parent_id
Print parent ID
absolute
Print all the subvolumes in the filesystem and distinguish
between absolute and relative path with respect to the given
<path>
ogeneration
... | [
"List",
"the",
"subvolumes",
"present",
"in",
"the",
"filesystem",
"."
] | python | train |
thomasdelaet/python-velbus | velbus/messages/temp_sensor_status.py | https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/messages/temp_sensor_status.py#L42-L88 | def populate(self, priority, address, rtr, data):
"""
-DB1 last bit = local_control
-DB1 bit 2+3 = status_mode
-DB1 bit 4 = auto send
-DB1 bit 5+6+7 = mode
-DB1 bit 8 = cool
-DB2 = program ... | [
"def",
"populate",
"(",
"self",
",",
"priority",
",",
"address",
",",
"rtr",
",",
"data",
")",
":",
"assert",
"isinstance",
"(",
"data",
",",
"bytes",
")",
"self",
".",
"needs_no_rtr",
"(",
"rtr",
")",
"self",
".",
"needs_data",
"(",
"data",
",",
"7"... | -DB1 last bit = local_control
-DB1 bit 2+3 = status_mode
-DB1 bit 4 = auto send
-DB1 bit 5+6+7 = mode
-DB1 bit 8 = cool
-DB2 = program (not used)
-DB3 last bit = heater
-DB3 bi... | [
"-",
"DB1",
"last",
"bit",
"=",
"local_control",
"-",
"DB1",
"bit",
"2",
"+",
"3",
"=",
"status_mode",
"-",
"DB1",
"bit",
"4",
"=",
"auto",
"send",
"-",
"DB1",
"bit",
"5",
"+",
"6",
"+",
"7",
"=",
"mode",
"-",
"DB1",
"bit",
"8",
"=",
"cool",
... | python | train |
zhanglab/psamm | psamm/fluxanalysis.py | https://github.com/zhanglab/psamm/blob/dc427848c4f9d109ca590f0afa024c63b685b3f4/psamm/fluxanalysis.py#L226-L251 | def max_min_l1(self, reaction, weights={}):
"""Maximize flux of reaction then minimize the L1 norm.
During minimization the given reaction will be fixed at the maximum
obtained from the first solution. If reaction is a dictionary object,
each entry is interpreted as a weight on the obje... | [
"def",
"max_min_l1",
"(",
"self",
",",
"reaction",
",",
"weights",
"=",
"{",
"}",
")",
":",
"self",
".",
"maximize",
"(",
"reaction",
")",
"if",
"isinstance",
"(",
"reaction",
",",
"dict",
")",
":",
"reactions",
"=",
"list",
"(",
"reaction",
")",
"el... | Maximize flux of reaction then minimize the L1 norm.
During minimization the given reaction will be fixed at the maximum
obtained from the first solution. If reaction is a dictionary object,
each entry is interpreted as a weight on the objective for that
reaction (non-existent reaction ... | [
"Maximize",
"flux",
"of",
"reaction",
"then",
"minimize",
"the",
"L1",
"norm",
"."
] | python | train |
rikrd/inspire | inspirespeech/common.py | https://github.com/rikrd/inspire/blob/e281c0266a9a9633f34ab70f9c3ad58036c19b59/inspirespeech/common.py#L989-L1061 | def recognise_model(feature_filename,
symbollist_filename,
model_directory,
recognition_filename,
pronunciation_dictionary_filename,
list_words_filename='',
cmllr_directory=None,
t... | [
"def",
"recognise_model",
"(",
"feature_filename",
",",
"symbollist_filename",
",",
"model_directory",
",",
"recognition_filename",
",",
"pronunciation_dictionary_filename",
",",
"list_words_filename",
"=",
"''",
",",
"cmllr_directory",
"=",
"None",
",",
"tokens_count",
"... | Perform recognition using a model and assuming a single word language.
If the list_words_filename is == '' then all the words in the dictionary are used as language words. | [
"Perform",
"recognition",
"using",
"a",
"model",
"and",
"assuming",
"a",
"single",
"word",
"language",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.