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 |
|---|---|---|---|---|---|---|---|---|
aloetesting/aloe_django | aloe_django/steps/models.py | https://github.com/aloetesting/aloe_django/blob/672eac97c97644bfe334e70696a6dc5ddf4ced02/aloe_django/steps/models.py#L478-L518 | def _create_m2m_links_step(self, rel_model_name,
rel_key, rel_value, relation_name):
"""
Link many-to-many models together.
Syntax:
And `model` with `field` "`value`" is linked to `other model` in the
database:
Example:
.. code-block:: gherkin
... | [
"def",
"_create_m2m_links_step",
"(",
"self",
",",
"rel_model_name",
",",
"rel_key",
",",
"rel_value",
",",
"relation_name",
")",
":",
"lookup",
"=",
"{",
"rel_key",
":",
"rel_value",
"}",
"rel_model",
"=",
"get_model",
"(",
"rel_model_name",
")",
".",
"object... | Link many-to-many models together.
Syntax:
And `model` with `field` "`value`" is linked to `other model` in the
database:
Example:
.. code-block:: gherkin
And article with name "Guidelines" is linked to tags in the database:
| name |
| coding |
... | [
"Link",
"many",
"-",
"to",
"-",
"many",
"models",
"together",
"."
] | python | train |
bradmontgomery/django-querycount | querycount/middleware.py | https://github.com/bradmontgomery/django-querycount/blob/61a380d98bc55e926c011367ecc2031102c3484c/querycount/middleware.py#L142-L150 | def _duplicate_queries(self, output):
"""Appends the most common duplicate queries to the given output."""
if QC_SETTINGS['DISPLAY_DUPLICATES']:
for query, count in self.queries.most_common(QC_SETTINGS['DISPLAY_DUPLICATES']):
lines = ['\nRepeated {0} times.'.format(count)]
... | [
"def",
"_duplicate_queries",
"(",
"self",
",",
"output",
")",
":",
"if",
"QC_SETTINGS",
"[",
"'DISPLAY_DUPLICATES'",
"]",
":",
"for",
"query",
",",
"count",
"in",
"self",
".",
"queries",
".",
"most_common",
"(",
"QC_SETTINGS",
"[",
"'DISPLAY_DUPLICATES'",
"]",... | Appends the most common duplicate queries to the given output. | [
"Appends",
"the",
"most",
"common",
"duplicate",
"queries",
"to",
"the",
"given",
"output",
"."
] | python | train |
carlthome/python-audio-effects | pysndfx/dsp.py | https://github.com/carlthome/python-audio-effects/blob/b2d85c166720c549c6ef3c382b561edd09229722/pysndfx/dsp.py#L308-L328 | def phaser(self,
gain_in=0.9,
gain_out=0.8,
delay=1,
decay=0.25,
speed=2,
triangular=False):
"""phaser takes 6 parameters: input gain (max 1.0), output gain (max
1.0), delay, decay, speed and LFO shape=trianglar (w... | [
"def",
"phaser",
"(",
"self",
",",
"gain_in",
"=",
"0.9",
",",
"gain_out",
"=",
"0.8",
",",
"delay",
"=",
"1",
",",
"decay",
"=",
"0.25",
",",
"speed",
"=",
"2",
",",
"triangular",
"=",
"False",
")",
":",
"self",
".",
"command",
".",
"append",
"(... | phaser takes 6 parameters: input gain (max 1.0), output gain (max
1.0), delay, decay, speed and LFO shape=trianglar (which must be set to
True or False) | [
"phaser",
"takes",
"6",
"parameters",
":",
"input",
"gain",
"(",
"max",
"1",
".",
"0",
")",
"output",
"gain",
"(",
"max",
"1",
".",
"0",
")",
"delay",
"decay",
"speed",
"and",
"LFO",
"shape",
"=",
"trianglar",
"(",
"which",
"must",
"be",
"set",
"to... | python | train |
PyCQA/astroid | astroid/node_classes.py | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/node_classes.py#L3008-L3022 | def postinit(self, expr=None, globals=None, locals=None):
"""Do some setup after initialisation.
:param expr: The expression to be executed.
:type expr: NodeNG or None
:param globals:The globals dictionary to execute with.
:type globals: NodeNG or None
:param locals: T... | [
"def",
"postinit",
"(",
"self",
",",
"expr",
"=",
"None",
",",
"globals",
"=",
"None",
",",
"locals",
"=",
"None",
")",
":",
"self",
".",
"expr",
"=",
"expr",
"self",
".",
"globals",
"=",
"globals",
"self",
".",
"locals",
"=",
"locals"
] | Do some setup after initialisation.
:param expr: The expression to be executed.
:type expr: NodeNG or None
:param globals:The globals dictionary to execute with.
:type globals: NodeNG or None
:param locals: The locals dictionary to execute with.
:type locals: NodeNG or... | [
"Do",
"some",
"setup",
"after",
"initialisation",
"."
] | python | train |
GeospatialPython/pyshp | shapefile.py | https://github.com/GeospatialPython/pyshp/blob/71231ddc5aa54f155d4f0563c56006fffbfc84e7/shapefile.py#L678-L689 | def load_dbf(self, shapefile_name):
"""
Attempts to load file with .dbf extension as both lower and upper case
"""
dbf_ext = 'dbf'
try:
self.dbf = open("%s.%s" % (shapefile_name, dbf_ext), "rb")
except IOError:
try:
self.db... | [
"def",
"load_dbf",
"(",
"self",
",",
"shapefile_name",
")",
":",
"dbf_ext",
"=",
"'dbf'",
"try",
":",
"self",
".",
"dbf",
"=",
"open",
"(",
"\"%s.%s\"",
"%",
"(",
"shapefile_name",
",",
"dbf_ext",
")",
",",
"\"rb\"",
")",
"except",
"IOError",
":",
"try... | Attempts to load file with .dbf extension as both lower and upper case | [
"Attempts",
"to",
"load",
"file",
"with",
".",
"dbf",
"extension",
"as",
"both",
"lower",
"and",
"upper",
"case"
] | python | train |
python-xlib/python-xlib | Xlib/rdb.py | https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/rdb.py#L320-L330 | def update(self, db):
"""update(db)
Update this database with all resources entries in the resource
database DB.
"""
self.lock.acquire()
update_db(self.db, db.db)
self.lock.release() | [
"def",
"update",
"(",
"self",
",",
"db",
")",
":",
"self",
".",
"lock",
".",
"acquire",
"(",
")",
"update_db",
"(",
"self",
".",
"db",
",",
"db",
".",
"db",
")",
"self",
".",
"lock",
".",
"release",
"(",
")"
] | update(db)
Update this database with all resources entries in the resource
database DB. | [
"update",
"(",
"db",
")"
] | python | train |
getsentry/raven-python | raven/transport/registry.py | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/transport/registry.py#L40-L49 | def register_scheme(self, scheme, cls):
"""
It is possible to inject new schemes at runtime
"""
if scheme in self._schemes:
raise DuplicateScheme()
urlparse.register_scheme(scheme)
# TODO (vng): verify the interface of the new class
self._schemes[sche... | [
"def",
"register_scheme",
"(",
"self",
",",
"scheme",
",",
"cls",
")",
":",
"if",
"scheme",
"in",
"self",
".",
"_schemes",
":",
"raise",
"DuplicateScheme",
"(",
")",
"urlparse",
".",
"register_scheme",
"(",
"scheme",
")",
"# TODO (vng): verify the interface of t... | It is possible to inject new schemes at runtime | [
"It",
"is",
"possible",
"to",
"inject",
"new",
"schemes",
"at",
"runtime"
] | python | train |
junzis/pyModeS | pyModeS/decoder/bds/bds45.py | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/bds/bds45.py#L97-L112 | def ws45(msg):
"""Wind shear.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
int: Wind shear level. 0=NIL, 1=Light, 2=Moderate, 3=Severe
"""
d = hex2bin(data(msg))
if d[3] == '0':
return None
ws = bin2int(d[4:6])
return ws | [
"def",
"ws45",
"(",
"msg",
")",
":",
"d",
"=",
"hex2bin",
"(",
"data",
"(",
"msg",
")",
")",
"if",
"d",
"[",
"3",
"]",
"==",
"'0'",
":",
"return",
"None",
"ws",
"=",
"bin2int",
"(",
"d",
"[",
"4",
":",
"6",
"]",
")",
"return",
"ws"
] | Wind shear.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
int: Wind shear level. 0=NIL, 1=Light, 2=Moderate, 3=Severe | [
"Wind",
"shear",
"."
] | python | train |
willhardy/django-seo | rollyourown/seo/base.py | https://github.com/willhardy/django-seo/blob/3089686a3c490091315860979ad15ef2527c3e3e/rollyourown/seo/base.py#L217-L219 | def _get_formatted_data(cls, path, context=None, site=None, language=None):
""" Return an object to conveniently access the appropriate values. """
return FormattedMetadata(cls(), cls._get_instances(path, context, site, language), path, site, language) | [
"def",
"_get_formatted_data",
"(",
"cls",
",",
"path",
",",
"context",
"=",
"None",
",",
"site",
"=",
"None",
",",
"language",
"=",
"None",
")",
":",
"return",
"FormattedMetadata",
"(",
"cls",
"(",
")",
",",
"cls",
".",
"_get_instances",
"(",
"path",
"... | Return an object to conveniently access the appropriate values. | [
"Return",
"an",
"object",
"to",
"conveniently",
"access",
"the",
"appropriate",
"values",
"."
] | python | train |
saltstack/salt | salt/grains/esxi.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/esxi.py#L83-L102 | def _grains():
'''
Get the grains from the proxied device.
'''
try:
host = __pillar__['proxy']['host']
if host:
username, password = _find_credentials(host)
protocol = __pillar__['proxy'].get('protocol')
port = __pillar__['proxy'].get('port')
... | [
"def",
"_grains",
"(",
")",
":",
"try",
":",
"host",
"=",
"__pillar__",
"[",
"'proxy'",
"]",
"[",
"'host'",
"]",
"if",
"host",
":",
"username",
",",
"password",
"=",
"_find_credentials",
"(",
"host",
")",
"protocol",
"=",
"__pillar__",
"[",
"'proxy'",
... | Get the grains from the proxied device. | [
"Get",
"the",
"grains",
"from",
"the",
"proxied",
"device",
"."
] | python | train |
rsheftel/raccoon | raccoon/series.py | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/series.py#L158-L168 | def get_locations(self, locations, as_list=False):
"""
For list of locations return a Series or list of the values.
:param locations: list of index locations
:param as_list: True to return a list of values
:return: Series or list
"""
indexes = [self._index[x] fo... | [
"def",
"get_locations",
"(",
"self",
",",
"locations",
",",
"as_list",
"=",
"False",
")",
":",
"indexes",
"=",
"[",
"self",
".",
"_index",
"[",
"x",
"]",
"for",
"x",
"in",
"locations",
"]",
"return",
"self",
".",
"get",
"(",
"indexes",
",",
"as_list"... | For list of locations return a Series or list of the values.
:param locations: list of index locations
:param as_list: True to return a list of values
:return: Series or list | [
"For",
"list",
"of",
"locations",
"return",
"a",
"Series",
"or",
"list",
"of",
"the",
"values",
"."
] | python | train |
insilichem/pychimera | pychimera/core.py | https://github.com/insilichem/pychimera/blob/5227d1c0e9e1ce165fc68157eda788cd0843842b/pychimera/core.py#L193-L241 | def _search_chimera(binary, directories, prefix, search_all=False):
"""
Try running ``chimera --root`` if Chimera happens to be in PATH, otherwise
traverse usual installation locations to find the Chimera root path.
Parameters
----------
binary : str
Name of the chimera executable in th... | [
"def",
"_search_chimera",
"(",
"binary",
",",
"directories",
",",
"prefix",
",",
"search_all",
"=",
"False",
")",
":",
"# First, check if environment variable is already present",
"try",
":",
"return",
"os",
".",
"path",
".",
"expanduser",
"(",
"os",
".",
"environ... | Try running ``chimera --root`` if Chimera happens to be in PATH, otherwise
traverse usual installation locations to find the Chimera root path.
Parameters
----------
binary : str
Name of the chimera executable in this platform
directories: list of str
Usual installation locations in... | [
"Try",
"running",
"chimera",
"--",
"root",
"if",
"Chimera",
"happens",
"to",
"be",
"in",
"PATH",
"otherwise",
"traverse",
"usual",
"installation",
"locations",
"to",
"find",
"the",
"Chimera",
"root",
"path",
"."
] | python | train |
iotile/coretools | iotilegateway/iotilegateway/gateway.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/gateway.py#L49-L57 | async def start(self):
"""Start the gateway."""
self._logger.info("Starting all device adapters")
await self.device_manager.start()
self._logger.info("Starting all servers")
for server in self.servers:
await server.start() | [
"async",
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"\"Starting all device adapters\"",
")",
"await",
"self",
".",
"device_manager",
".",
"start",
"(",
")",
"self",
".",
"_logger",
".",
"info",
"(",
"\"Starting all serve... | Start the gateway. | [
"Start",
"the",
"gateway",
"."
] | python | train |
developmentseed/landsat-util | landsat/utils.py | https://github.com/developmentseed/landsat-util/blob/92dc81771ddaa64a8a9124a89a6516b52485374b/landsat/utils.py#L57-L79 | def exit(message, code=0):
""" output a message to stdout and terminates the process.
:param message:
Message to be outputed.
:type message:
String
:param code:
The termination code. Default is 0
:type code:
int
:returns:
void
"""
v = VerbosityM... | [
"def",
"exit",
"(",
"message",
",",
"code",
"=",
"0",
")",
":",
"v",
"=",
"VerbosityMixin",
"(",
")",
"if",
"code",
"==",
"0",
":",
"v",
".",
"output",
"(",
"message",
",",
"normal",
"=",
"True",
",",
"arrow",
"=",
"True",
")",
"v",
".",
"outpu... | output a message to stdout and terminates the process.
:param message:
Message to be outputed.
:type message:
String
:param code:
The termination code. Default is 0
:type code:
int
:returns:
void | [
"output",
"a",
"message",
"to",
"stdout",
"and",
"terminates",
"the",
"process",
"."
] | python | train |
glue-viz/glue-vispy-viewers | glue_vispy_viewers/extern/vispy/util/transforms.py | https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/util/transforms.py#L15-L36 | def translate(offset, dtype=None):
"""Translate by an offset (x, y, z) .
Parameters
----------
offset : array-like, shape (3,)
Translation in x, y, z.
dtype : dtype | None
Output type (if None, don't cast).
Returns
-------
M : ndarray
Transformation matrix descr... | [
"def",
"translate",
"(",
"offset",
",",
"dtype",
"=",
"None",
")",
":",
"assert",
"len",
"(",
"offset",
")",
"==",
"3",
"x",
",",
"y",
",",
"z",
"=",
"offset",
"M",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"1.",
",",
"0.",
",",
"0.",
",",
"0... | Translate by an offset (x, y, z) .
Parameters
----------
offset : array-like, shape (3,)
Translation in x, y, z.
dtype : dtype | None
Output type (if None, don't cast).
Returns
-------
M : ndarray
Transformation matrix describing the translation. | [
"Translate",
"by",
"an",
"offset",
"(",
"x",
"y",
"z",
")",
"."
] | python | train |
NaturalHistoryMuseum/pyzbar | pyzbar/pyzbar.py | https://github.com/NaturalHistoryMuseum/pyzbar/blob/833b375c0e84077943b7100cc9dc22a7bd48754b/pyzbar/pyzbar.py#L170-L210 | def decode(image, symbols=None):
"""Decodes datamatrix barcodes in `image`.
Args:
image: `numpy.ndarray`, `PIL.Image` or tuple (pixels, width, height)
symbols: iter(ZBarSymbol) the symbol types to decode; if `None`, uses
`zbar`'s default behaviour, which is to decode all symbol type... | [
"def",
"decode",
"(",
"image",
",",
"symbols",
"=",
"None",
")",
":",
"pixels",
",",
"width",
",",
"height",
"=",
"_pixel_data",
"(",
"image",
")",
"results",
"=",
"[",
"]",
"with",
"_image_scanner",
"(",
")",
"as",
"scanner",
":",
"if",
"symbols",
"... | Decodes datamatrix barcodes in `image`.
Args:
image: `numpy.ndarray`, `PIL.Image` or tuple (pixels, width, height)
symbols: iter(ZBarSymbol) the symbol types to decode; if `None`, uses
`zbar`'s default behaviour, which is to decode all symbol types.
Returns:
:obj:`list` of ... | [
"Decodes",
"datamatrix",
"barcodes",
"in",
"image",
"."
] | python | train |
ewels/MultiQC | multiqc/modules/picard/OxoGMetrics.py | https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/picard/OxoGMetrics.py#L13-L112 | def parse_reports(self):
""" Find Picard OxoGMetrics reports and parse their data """
# Set up vars
self.picard_OxoGMetrics_data = dict()
# Go through logs and find Metrics
for f in self.find_log_files('picard/oxogmetrics', filehandles=True):
# We use lists to make sure that we don't overw... | [
"def",
"parse_reports",
"(",
"self",
")",
":",
"# Set up vars",
"self",
".",
"picard_OxoGMetrics_data",
"=",
"dict",
"(",
")",
"# Go through logs and find Metrics",
"for",
"f",
"in",
"self",
".",
"find_log_files",
"(",
"'picard/oxogmetrics'",
",",
"filehandles",
"="... | Find Picard OxoGMetrics reports and parse their data | [
"Find",
"Picard",
"OxoGMetrics",
"reports",
"and",
"parse",
"their",
"data"
] | python | train |
JukeboxPipeline/jukeboxmaya | src/jukeboxmaya/commands.py | https://github.com/JukeboxPipeline/jukeboxmaya/blob/c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c/src/jukeboxmaya/commands.py#L11-L34 | def open_scene(f, kwargs=None):
"""Opens the given JB_File
:param f: the file to open
:type f: :class:`jukeboxcore.filesys.JB_File`
:param kwargs: keyword arguments for the command maya.cmds file.
defaultflags that are always used:
:open: ``True``
... | [
"def",
"open_scene",
"(",
"f",
",",
"kwargs",
"=",
"None",
")",
":",
"defaultkwargs",
"=",
"{",
"'open'",
":",
"True",
"}",
"if",
"kwargs",
"is",
"None",
":",
"kwargs",
"=",
"{",
"}",
"kwargs",
".",
"update",
"(",
"defaultkwargs",
")",
"fp",
"=",
"... | Opens the given JB_File
:param f: the file to open
:type f: :class:`jukeboxcore.filesys.JB_File`
:param kwargs: keyword arguments for the command maya.cmds file.
defaultflags that are always used:
:open: ``True``
e.g. to force the open command us... | [
"Opens",
"the",
"given",
"JB_File"
] | python | train |
happyleavesaoc/python-limitlessled | limitlessled/group/dimmer.py | https://github.com/happyleavesaoc/python-limitlessled/blob/70307c2bf8c91430a99579d2ad18b228ec7a8488/limitlessled/group/dimmer.py#L113-L120 | def _to_brightness(self, brightness):
""" Step to a given brightness.
:param brightness: Get to this brightness.
"""
self._to_value(self._brightness, brightness,
self.command_set.brightness_steps,
self._dimmer, self._brighter) | [
"def",
"_to_brightness",
"(",
"self",
",",
"brightness",
")",
":",
"self",
".",
"_to_value",
"(",
"self",
".",
"_brightness",
",",
"brightness",
",",
"self",
".",
"command_set",
".",
"brightness_steps",
",",
"self",
".",
"_dimmer",
",",
"self",
".",
"_brig... | Step to a given brightness.
:param brightness: Get to this brightness. | [
"Step",
"to",
"a",
"given",
"brightness",
"."
] | python | train |
wandb/client | wandb/vendor/prompt_toolkit/key_binding/bindings/scroll.py | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/key_binding/bindings/scroll.py#L151-L164 | def scroll_page_down(event):
"""
Scroll page down. (Prefer the cursor at the top of the page, after scrolling.)
"""
w = _current_window_for_event(event)
b = event.cli.current_buffer
if w and w.render_info:
# Scroll down one page.
line_index = max(w.render_info.last_visible_line(... | [
"def",
"scroll_page_down",
"(",
"event",
")",
":",
"w",
"=",
"_current_window_for_event",
"(",
"event",
")",
"b",
"=",
"event",
".",
"cli",
".",
"current_buffer",
"if",
"w",
"and",
"w",
".",
"render_info",
":",
"# Scroll down one page.",
"line_index",
"=",
"... | Scroll page down. (Prefer the cursor at the top of the page, after scrolling.) | [
"Scroll",
"page",
"down",
".",
"(",
"Prefer",
"the",
"cursor",
"at",
"the",
"top",
"of",
"the",
"page",
"after",
"scrolling",
".",
")"
] | python | train |
wavefrontHQ/python-client | wavefront_api_client/api/maintenance_window_api.py | https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/api/maintenance_window_api.py#L226-L247 | def get_all_maintenance_window(self, **kwargs): # noqa: E501
"""Get all maintenance windows for a customer # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get... | [
"def",
"get_all_maintenance_window",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"get_all_maintena... | Get all maintenance windows for a customer # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_all_maintenance_window(async_req=True)
>>> result = thread.get()... | [
"Get",
"all",
"maintenance",
"windows",
"for",
"a",
"customer",
"#",
"noqa",
":",
"E501"
] | python | train |
pantsbuild/pants | src/python/pants/invalidation/build_invalidator.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/invalidation/build_invalidator.py#L177-L187 | def needs_update(self, cache_key):
"""Check if the given cached item is invalid.
:param cache_key: A CacheKey object (as returned by CacheKeyGenerator.key_for().
:returns: True if the cached version of the item is out of date.
"""
if not self.cacheable(cache_key):
# An uncacheable CacheKey is... | [
"def",
"needs_update",
"(",
"self",
",",
"cache_key",
")",
":",
"if",
"not",
"self",
".",
"cacheable",
"(",
"cache_key",
")",
":",
"# An uncacheable CacheKey is always out of date.",
"return",
"True",
"return",
"self",
".",
"_read_sha",
"(",
"cache_key",
")",
"!... | Check if the given cached item is invalid.
:param cache_key: A CacheKey object (as returned by CacheKeyGenerator.key_for().
:returns: True if the cached version of the item is out of date. | [
"Check",
"if",
"the",
"given",
"cached",
"item",
"is",
"invalid",
"."
] | python | train |
hfaran/Tornado-JSON | tornado_json/utils.py | https://github.com/hfaran/Tornado-JSON/blob/8d8b35ff77f13cb3ab1a606bd2083b26cc69c54f/tornado_json/utils.py#L7-L22 | def deep_update(source, overrides):
"""Update a nested dictionary or similar mapping.
Modify ``source`` in place.
:type source: collections.Mapping
:type overrides: collections.Mapping
:rtype: collections.Mapping
"""
for key, value in overrides.items():
if isinstance(value, collect... | [
"def",
"deep_update",
"(",
"source",
",",
"overrides",
")",
":",
"for",
"key",
",",
"value",
"in",
"overrides",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"collections",
".",
"Mapping",
")",
"and",
"value",
":",
"returned",
"="... | Update a nested dictionary or similar mapping.
Modify ``source`` in place.
:type source: collections.Mapping
:type overrides: collections.Mapping
:rtype: collections.Mapping | [
"Update",
"a",
"nested",
"dictionary",
"or",
"similar",
"mapping",
"."
] | python | train |
azogue/i2csense | i2csense/bh1750.py | https://github.com/azogue/i2csense/blob/ecc6806dcee9de827a5414a9e836d271fedca9b9/i2csense/bh1750.py#L123-L126 | def _wait_for_result(self):
"""Wait for the sensor to be ready for measurement."""
basetime = 0.018 if self._low_res else 0.128
sleep(basetime * (self._mtreg / 69.0) + self._delay) | [
"def",
"_wait_for_result",
"(",
"self",
")",
":",
"basetime",
"=",
"0.018",
"if",
"self",
".",
"_low_res",
"else",
"0.128",
"sleep",
"(",
"basetime",
"*",
"(",
"self",
".",
"_mtreg",
"/",
"69.0",
")",
"+",
"self",
".",
"_delay",
")"
] | Wait for the sensor to be ready for measurement. | [
"Wait",
"for",
"the",
"sensor",
"to",
"be",
"ready",
"for",
"measurement",
"."
] | python | train |
postlund/pyatv | pyatv/mrp/messages.py | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/mrp/messages.py#L85-L99 | def send_packed_virtual_touch_event(xpos, ypos, phase, device_id, finger):
"""Create a new WAKE_DEVICE_MESSAGE."""
message = create(protobuf.SEND_PACKED_VIRTUAL_TOUCH_EVENT_MESSAGE)
event = message.inner()
# The packed version of VirtualTouchEvent contains X, Y, phase, deviceID
# and finger stored ... | [
"def",
"send_packed_virtual_touch_event",
"(",
"xpos",
",",
"ypos",
",",
"phase",
",",
"device_id",
",",
"finger",
")",
":",
"message",
"=",
"create",
"(",
"protobuf",
".",
"SEND_PACKED_VIRTUAL_TOUCH_EVENT_MESSAGE",
")",
"event",
"=",
"message",
".",
"inner",
"(... | Create a new WAKE_DEVICE_MESSAGE. | [
"Create",
"a",
"new",
"WAKE_DEVICE_MESSAGE",
"."
] | python | train |
twosigma/marbles | marbles/mixins/marbles/mixins/mixins.py | https://github.com/twosigma/marbles/blob/f0c668be8344c70d4d63bc57e82c6f2da43c6925/marbles/mixins/marbles/mixins/mixins.py#L664-L683 | def assertFileNameEqual(self, filename, name, msg=None):
'''Fail if ``filename`` does not have the given ``name`` as
determined by the ``==`` operator.
Parameters
----------
filename : str, bytes, file-like
name : str, byes
msg : str
If not provided, ... | [
"def",
"assertFileNameEqual",
"(",
"self",
",",
"filename",
",",
"name",
",",
"msg",
"=",
"None",
")",
":",
"fname",
"=",
"self",
".",
"_get_file_name",
"(",
"filename",
")",
"self",
".",
"assertEqual",
"(",
"fname",
",",
"name",
",",
"msg",
"=",
"msg"... | Fail if ``filename`` does not have the given ``name`` as
determined by the ``==`` operator.
Parameters
----------
filename : str, bytes, file-like
name : str, byes
msg : str
If not provided, the :mod:`marbles.mixins` or
:mod:`unittest` standard me... | [
"Fail",
"if",
"filename",
"does",
"not",
"have",
"the",
"given",
"name",
"as",
"determined",
"by",
"the",
"==",
"operator",
"."
] | python | train |
noxdafox/vminspect | vminspect/vtscan.py | https://github.com/noxdafox/vminspect/blob/e685282564877e2d1950f1e09b292f4f4db1dbcd/vminspect/vtscan.py#L164-L169 | def chunks(iterable, size=1):
"""Splits iterator in chunks."""
iterator = iter(iterable)
for element in iterator:
yield chain([element], islice(iterator, size - 1)) | [
"def",
"chunks",
"(",
"iterable",
",",
"size",
"=",
"1",
")",
":",
"iterator",
"=",
"iter",
"(",
"iterable",
")",
"for",
"element",
"in",
"iterator",
":",
"yield",
"chain",
"(",
"[",
"element",
"]",
",",
"islice",
"(",
"iterator",
",",
"size",
"-",
... | Splits iterator in chunks. | [
"Splits",
"iterator",
"in",
"chunks",
"."
] | python | train |
brentp/cyvcf2 | cyvcf2/cli.py | https://github.com/brentp/cyvcf2/blob/57f2c0e58ae64d2ec5673d833233834a1157c665/cyvcf2/cli.py#L44-L66 | def print_variant(variant, include, exclude):
"""Print a vcf variant
Parameters
----------
variant: cyvcf2.Variant
include: tuple
set of strings with info fields that should be included
include: tuple
set of strings with info fields that should be included
"""
if inc... | [
"def",
"print_variant",
"(",
"variant",
",",
"include",
",",
"exclude",
")",
":",
"if",
"include",
":",
"for",
"info",
"in",
"variant",
".",
"INFO",
":",
"key",
"=",
"info",
"[",
"0",
"]",
"if",
"not",
"key",
"in",
"include",
":",
"del",
"variant",
... | Print a vcf variant
Parameters
----------
variant: cyvcf2.Variant
include: tuple
set of strings with info fields that should be included
include: tuple
set of strings with info fields that should be included | [
"Print",
"a",
"vcf",
"variant",
"Parameters",
"----------",
"variant",
":",
"cyvcf2",
".",
"Variant",
"include",
":",
"tuple",
"set",
"of",
"strings",
"with",
"info",
"fields",
"that",
"should",
"be",
"included",
"include",
":",
"tuple",
"set",
"of",
"string... | python | train |
geophysics-ubonn/reda | lib/reda/containers/ERT.py | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/containers/ERT.py#L118-L135 | def import_bert(self, filename, **kwargs):
"""BERT .ohm file import"""
timestep = kwargs.get('timestep', None)
if 'timestep' in kwargs:
del (kwargs['timestep'])
self.logger.info('Unified data format (BERT/pyGIMLi) file import')
with LogDataChanges(self, filter_action... | [
"def",
"import_bert",
"(",
"self",
",",
"filename",
",",
"*",
"*",
"kwargs",
")",
":",
"timestep",
"=",
"kwargs",
".",
"get",
"(",
"'timestep'",
",",
"None",
")",
"if",
"'timestep'",
"in",
"kwargs",
":",
"del",
"(",
"kwargs",
"[",
"'timestep'",
"]",
... | BERT .ohm file import | [
"BERT",
".",
"ohm",
"file",
"import"
] | python | train |
tradenity/python-sdk | tradenity/resources/state.py | https://github.com/tradenity/python-sdk/blob/d13fbe23f4d6ff22554c6d8d2deaf209371adaf1/tradenity/resources/state.py#L645-L666 | def replace_state_by_id(cls, state_id, state, **kwargs):
"""Replace State
Replace all attributes of State
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.replace_state_by_id(state_id, state, a... | [
"def",
"replace_state_by_id",
"(",
"cls",
",",
"state_id",
",",
"state",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_replace... | Replace State
Replace all attributes of State
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.replace_state_by_id(state_id, state, async=True)
>>> result = thread.get()
:param async b... | [
"Replace",
"State"
] | python | train |
fracpete/python-weka-wrapper3 | python/weka/core/classes.py | https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/core/classes.py#L1708-L1732 | def complete_classname(classname):
"""
Attempts to complete a partial classname like '.J48' and returns the full
classname if a single match was found, otherwise an exception is raised.
:param classname: the partial classname to expand
:type classname: str
:return: the full classname
:rtype... | [
"def",
"complete_classname",
"(",
"classname",
")",
":",
"result",
"=",
"javabridge",
".",
"get_collection_wrapper",
"(",
"javabridge",
".",
"static_call",
"(",
"\"Lweka/Run;\"",
",",
"\"findSchemeMatch\"",
",",
"\"(Ljava/lang/String;Z)Ljava/util/List;\"",
",",
"classname... | Attempts to complete a partial classname like '.J48' and returns the full
classname if a single match was found, otherwise an exception is raised.
:param classname: the partial classname to expand
:type classname: str
:return: the full classname
:rtype: str | [
"Attempts",
"to",
"complete",
"a",
"partial",
"classname",
"like",
".",
"J48",
"and",
"returns",
"the",
"full",
"classname",
"if",
"a",
"single",
"match",
"was",
"found",
"otherwise",
"an",
"exception",
"is",
"raised",
"."
] | python | train |
MoseleyBioinformaticsLab/nmrstarlib | nmrstarlib/nmrstarlib.py | https://github.com/MoseleyBioinformaticsLab/nmrstarlib/blob/f2adabbca04d5a134ce6ba3211099d1457787ff2/nmrstarlib/nmrstarlib.py#L54-L99 | def update_constants(nmrstar2cfg="", nmrstar3cfg="", resonance_classes_cfg="", spectrum_descriptions_cfg=""):
"""Update constant variables.
:return: None
:rtype: :py:obj:`None`
"""
nmrstar_constants = {}
resonance_classes = {}
spectrum_descriptions = {}
this_directory = os.path.dirname... | [
"def",
"update_constants",
"(",
"nmrstar2cfg",
"=",
"\"\"",
",",
"nmrstar3cfg",
"=",
"\"\"",
",",
"resonance_classes_cfg",
"=",
"\"\"",
",",
"spectrum_descriptions_cfg",
"=",
"\"\"",
")",
":",
"nmrstar_constants",
"=",
"{",
"}",
"resonance_classes",
"=",
"{",
"}... | Update constant variables.
:return: None
:rtype: :py:obj:`None` | [
"Update",
"constant",
"variables",
"."
] | python | train |
roclark/sportsreference | sportsreference/nhl/boxscore.py | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nhl/boxscore.py#L307-L357 | def _parse_game_date_and_location(self, boxscore):
"""
Retrieve the game's date and location.
The game's meta information, such as date, location, attendance, and
duration, follow a complex parsing scheme that changes based on the
layout of the page. The information should be ab... | [
"def",
"_parse_game_date_and_location",
"(",
"self",
",",
"boxscore",
")",
":",
"scheme",
"=",
"BOXSCORE_SCHEME",
"[",
"\"game_info\"",
"]",
"items",
"=",
"[",
"i",
".",
"text",
"(",
")",
"for",
"i",
"in",
"boxscore",
"(",
"scheme",
")",
".",
"items",
"(... | Retrieve the game's date and location.
The game's meta information, such as date, location, attendance, and
duration, follow a complex parsing scheme that changes based on the
layout of the page. The information should be able to be parsed and set
regardless of the order and how much in... | [
"Retrieve",
"the",
"game",
"s",
"date",
"and",
"location",
"."
] | python | train |
oseledets/ttpy | tt/core/tools.py | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/core/tools.py#L200-L212 | def zkronv(ttA, ttB):
"""
Do kronecker product between vectors ttA and ttB.
Look about kronecker at: https://en.wikipedia.org/wiki/Kronecker_product
For details about operation refer: https://arxiv.org/abs/1802.02839
:param ttA: first TT-vector;
:param ttB: second TT-vector;
:return: operati... | [
"def",
"zkronv",
"(",
"ttA",
",",
"ttB",
")",
":",
"Al",
"=",
"_vector",
".",
"vector",
".",
"to_list",
"(",
"ttA",
")",
"Bl",
"=",
"_vector",
".",
"vector",
".",
"to_list",
"(",
"ttB",
")",
"Hl",
"=",
"[",
"_np",
".",
"kron",
"(",
"B",
",",
... | Do kronecker product between vectors ttA and ttB.
Look about kronecker at: https://en.wikipedia.org/wiki/Kronecker_product
For details about operation refer: https://arxiv.org/abs/1802.02839
:param ttA: first TT-vector;
:param ttB: second TT-vector;
:return: operation result in z-order | [
"Do",
"kronecker",
"product",
"between",
"vectors",
"ttA",
"and",
"ttB",
".",
"Look",
"about",
"kronecker",
"at",
":",
"https",
":",
"//",
"en",
".",
"wikipedia",
".",
"org",
"/",
"wiki",
"/",
"Kronecker_product",
"For",
"details",
"about",
"operation",
"r... | python | train |
google/grr | grr/server/grr_response_server/gui/api_plugins/flow.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/gui/api_plugins/flow.py#L936-L975 | def GetOutputPluginIndex(
plugin_descriptors,
plugin_id):
"""Gets an output plugin index for a plugin with a given id.
Historically output plugins descriptors were stored in dicts-like
structures with unique identifiers as keys. In REL_DB-based implementation,
however, both plugin descriptors and their... | [
"def",
"GetOutputPluginIndex",
"(",
"plugin_descriptors",
",",
"plugin_id",
")",
":",
"used_names",
"=",
"collections",
".",
"Counter",
"(",
")",
"for",
"(",
"index",
",",
"desc",
")",
"in",
"enumerate",
"(",
"plugin_descriptors",
")",
":",
"cur_plugin_id",
"=... | Gets an output plugin index for a plugin with a given id.
Historically output plugins descriptors were stored in dicts-like
structures with unique identifiers as keys. In REL_DB-based implementation,
however, both plugin descriptors and their states are stored in flat
lists (see Flow definition in flows.proto)... | [
"Gets",
"an",
"output",
"plugin",
"index",
"for",
"a",
"plugin",
"with",
"a",
"given",
"id",
"."
] | python | train |
Riffstation/flask-philo | flask_philo/db/redis/connection.py | https://github.com/Riffstation/flask-philo/blob/76c9d562edb4a77010c8da6dfdb6489fa29cbc9e/flask_philo/db/redis/connection.py#L74-L101 | def initialize(g, app):
"""
If redis connection parameters are defined in configuration params a
session will be created
"""
if 'DATABASES' in app.config and 'REDIS' in app.config['DATABASES']:
# Initialize connections for console commands
for k, v in app.config['DATABASES']['REDIS... | [
"def",
"initialize",
"(",
"g",
",",
"app",
")",
":",
"if",
"'DATABASES'",
"in",
"app",
".",
"config",
"and",
"'REDIS'",
"in",
"app",
".",
"config",
"[",
"'DATABASES'",
"]",
":",
"# Initialize connections for console commands",
"for",
"k",
",",
"v",
"in",
"... | If redis connection parameters are defined in configuration params a
session will be created | [
"If",
"redis",
"connection",
"parameters",
"are",
"defined",
"in",
"configuration",
"params",
"a",
"session",
"will",
"be",
"created"
] | python | train |
secdev/scapy | scapy/layers/dot15d4.py | https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/layers/dot15d4.py#L40-L46 | def i2repr(self, pkt, x):
"""Convert internal value to a nice representation"""
if len(hex(self.i2m(pkt, x))) < 7: # short address
return hex(self.i2m(pkt, x))
else: # long address
x = "%016x" % self.i2m(pkt, x)
return ":".join(["%s%s" % (x[i], x[i + 1]) for... | [
"def",
"i2repr",
"(",
"self",
",",
"pkt",
",",
"x",
")",
":",
"if",
"len",
"(",
"hex",
"(",
"self",
".",
"i2m",
"(",
"pkt",
",",
"x",
")",
")",
")",
"<",
"7",
":",
"# short address",
"return",
"hex",
"(",
"self",
".",
"i2m",
"(",
"pkt",
",",
... | Convert internal value to a nice representation | [
"Convert",
"internal",
"value",
"to",
"a",
"nice",
"representation"
] | python | train |
domainaware/parsedmarc | parsedmarc/splunk.py | https://github.com/domainaware/parsedmarc/blob/ecc9fd434c23d896ccd1f35795ccc047f946ed05/parsedmarc/splunk.py#L125-L159 | def save_forensic_reports_to_splunk(self, forensic_reports):
"""
Saves forensic DMARC reports to Splunk
Args:
forensic_reports (list): A list of forensic report dictionaries
to save in Splunk
"""
logger.debug("Saving forensic reports to Splunk")
... | [
"def",
"save_forensic_reports_to_splunk",
"(",
"self",
",",
"forensic_reports",
")",
":",
"logger",
".",
"debug",
"(",
"\"Saving forensic reports to Splunk\"",
")",
"if",
"type",
"(",
"forensic_reports",
")",
"==",
"dict",
":",
"forensic_reports",
"=",
"[",
"forensi... | Saves forensic DMARC reports to Splunk
Args:
forensic_reports (list): A list of forensic report dictionaries
to save in Splunk | [
"Saves",
"forensic",
"DMARC",
"reports",
"to",
"Splunk"
] | python | test |
tradenity/python-sdk | tradenity/resources/payment_transaction.py | https://github.com/tradenity/python-sdk/blob/d13fbe23f4d6ff22554c6d8d2deaf209371adaf1/tradenity/resources/payment_transaction.py#L281-L301 | def create_payment_transaction(cls, payment_transaction, **kwargs):
"""Create PaymentTransaction
Create a new PaymentTransaction
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_payment_... | [
"def",
"create_payment_transaction",
"(",
"cls",
",",
"payment_transaction",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_create_... | Create PaymentTransaction
Create a new PaymentTransaction
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_payment_transaction(payment_transaction, async=True)
>>> result = thread.get()
... | [
"Create",
"PaymentTransaction"
] | python | train |
zhmcclient/python-zhmcclient | zhmcclient_mock/_urihandler.py | https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient_mock/_urihandler.py#L1163-L1205 | def post(method, hmc, uri, uri_parms, body, logon_required,
wait_for_completion):
"""Operation: Export WWPN List (requires DPM mode)."""
assert wait_for_completion is True # this operation is always synchr.
cpc_oid = uri_parms[0]
try:
cpc = hmc.cpcs.lookup_by_oi... | [
"def",
"post",
"(",
"method",
",",
"hmc",
",",
"uri",
",",
"uri_parms",
",",
"body",
",",
"logon_required",
",",
"wait_for_completion",
")",
":",
"assert",
"wait_for_completion",
"is",
"True",
"# this operation is always synchr.",
"cpc_oid",
"=",
"uri_parms",
"[",... | Operation: Export WWPN List (requires DPM mode). | [
"Operation",
":",
"Export",
"WWPN",
"List",
"(",
"requires",
"DPM",
"mode",
")",
"."
] | python | train |
bcbio/bcbio-nextgen | bcbio/server/main.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/server/main.py#L29-L41 | def add_subparser(subparsers):
"""Add command line arguments as server subparser.
"""
parser = subparsers.add_parser("server", help="Run a bcbio-nextgen server allowing remote job execution.")
parser.add_argument("-c", "--config", help=("Global YAML configuration file specifying system details."
... | [
"def",
"add_subparser",
"(",
"subparsers",
")",
":",
"parser",
"=",
"subparsers",
".",
"add_parser",
"(",
"\"server\"",
",",
"help",
"=",
"\"Run a bcbio-nextgen server allowing remote job execution.\"",
")",
"parser",
".",
"add_argument",
"(",
"\"-c\"",
",",
"\"--conf... | Add command line arguments as server subparser. | [
"Add",
"command",
"line",
"arguments",
"as",
"server",
"subparser",
"."
] | python | train |
ajenhl/tacl | tacl/report.py | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/report.py#L56-L87 | def _write(self, context, report_dir, report_name, assets_dir=None,
template=None):
"""Writes the data in `context` in the report's template to
`report_name` in `report_dir`.
If `assets_dir` is supplied, copies all assets for this report
to the specified directory.
... | [
"def",
"_write",
"(",
"self",
",",
"context",
",",
"report_dir",
",",
"report_name",
",",
"assets_dir",
"=",
"None",
",",
"template",
"=",
"None",
")",
":",
"if",
"template",
"is",
"None",
":",
"template",
"=",
"self",
".",
"_get_template",
"(",
")",
"... | Writes the data in `context` in the report's template to
`report_name` in `report_dir`.
If `assets_dir` is supplied, copies all assets for this report
to the specified directory.
If `template` is supplied, uses that template instead of
automatically finding it. This is useful i... | [
"Writes",
"the",
"data",
"in",
"context",
"in",
"the",
"report",
"s",
"template",
"to",
"report_name",
"in",
"report_dir",
"."
] | python | train |
LonamiWebs/Telethon | telethon_generator/parsers/tlobject/parser.py | https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon_generator/parsers/tlobject/parser.py#L137-L144 | def find_layer(file_path):
"""Finds the layer used on the specified scheme.tl file."""
layer_regex = re.compile(r'^//\s*LAYER\s*(\d+)$')
with file_path.open('r') as file:
for line in file:
match = layer_regex.match(line)
if match:
return int(match.group(1)) | [
"def",
"find_layer",
"(",
"file_path",
")",
":",
"layer_regex",
"=",
"re",
".",
"compile",
"(",
"r'^//\\s*LAYER\\s*(\\d+)$'",
")",
"with",
"file_path",
".",
"open",
"(",
"'r'",
")",
"as",
"file",
":",
"for",
"line",
"in",
"file",
":",
"match",
"=",
"laye... | Finds the layer used on the specified scheme.tl file. | [
"Finds",
"the",
"layer",
"used",
"on",
"the",
"specified",
"scheme",
".",
"tl",
"file",
"."
] | python | train |
pyviz/holoviews | holoviews/core/spaces.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/core/spaces.py#L1391-L1400 | def _cache(self, key, val):
"""
Request that a key/value pair be considered for caching.
"""
cache_size = (1 if util.dimensionless_contents(self.streams, self.kdims)
else self.cache_size)
if len(self) >= cache_size:
first_key = next(k for k in se... | [
"def",
"_cache",
"(",
"self",
",",
"key",
",",
"val",
")",
":",
"cache_size",
"=",
"(",
"1",
"if",
"util",
".",
"dimensionless_contents",
"(",
"self",
".",
"streams",
",",
"self",
".",
"kdims",
")",
"else",
"self",
".",
"cache_size",
")",
"if",
"len"... | Request that a key/value pair be considered for caching. | [
"Request",
"that",
"a",
"key",
"/",
"value",
"pair",
"be",
"considered",
"for",
"caching",
"."
] | python | train |
genialis/resolwe | resolwe/elastic/builder.py | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/builder.py#L365-L370 | def process(self, obj, pk_set=None, action=None, update_fields=None, **kwargs):
"""Process signals from dependencies."""
build_kwargs = self._get_build_kwargs(obj, pk_set, action, update_fields, **kwargs)
if build_kwargs:
self.index.build(**build_kwargs) | [
"def",
"process",
"(",
"self",
",",
"obj",
",",
"pk_set",
"=",
"None",
",",
"action",
"=",
"None",
",",
"update_fields",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"build_kwargs",
"=",
"self",
".",
"_get_build_kwargs",
"(",
"obj",
",",
"pk_set",
... | Process signals from dependencies. | [
"Process",
"signals",
"from",
"dependencies",
"."
] | python | train |
DLR-RM/RAFCON | source/rafcon/utils/execution_log.py | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/utils/execution_log.py#L305-L370 | def log_to_DataFrame(execution_history_items, data_in_columns=[], data_out_columns=[], scoped_in_columns=[],
scoped_out_columns=[], semantic_data_columns=[], throw_on_pickle_error=True):
"""
Returns all collapsed items in a table-like structure (pandas.DataFrame) with one row per executed
... | [
"def",
"log_to_DataFrame",
"(",
"execution_history_items",
",",
"data_in_columns",
"=",
"[",
"]",
",",
"data_out_columns",
"=",
"[",
"]",
",",
"scoped_in_columns",
"=",
"[",
"]",
",",
"scoped_out_columns",
"=",
"[",
"]",
",",
"semantic_data_columns",
"=",
"[",
... | Returns all collapsed items in a table-like structure (pandas.DataFrame) with one row per executed
state and a set of properties resp. columns (e.g. state_name, outcome, run_id) for this state.
The data flow (data_in/out, scoped_data_in/out, semantic_data) is omitted from this table
representation by defau... | [
"Returns",
"all",
"collapsed",
"items",
"in",
"a",
"table",
"-",
"like",
"structure",
"(",
"pandas",
".",
"DataFrame",
")",
"with",
"one",
"row",
"per",
"executed",
"state",
"and",
"a",
"set",
"of",
"properties",
"resp",
".",
"columns",
"(",
"e",
".",
... | python | train |
Bogdanp/dramatiq | dramatiq/actor.py | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/actor.py#L72-L99 | def message_with_options(self, *, args=None, kwargs=None, **options):
"""Build a message with an arbitray set of processing options.
This method is useful if you want to compose actors. See the
actor composition documentation for details.
Parameters:
args(tuple): Positional a... | [
"def",
"message_with_options",
"(",
"self",
",",
"*",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"for",
"name",
"in",
"[",
"\"on_failure\"",
",",
"\"on_success\"",
"]",
":",
"callback",
"=",
"options",
"."... | Build a message with an arbitray set of processing options.
This method is useful if you want to compose actors. See the
actor composition documentation for details.
Parameters:
args(tuple): Positional arguments that are passed to the actor.
kwargs(dict): Keyword arguments ... | [
"Build",
"a",
"message",
"with",
"an",
"arbitray",
"set",
"of",
"processing",
"options",
".",
"This",
"method",
"is",
"useful",
"if",
"you",
"want",
"to",
"compose",
"actors",
".",
"See",
"the",
"actor",
"composition",
"documentation",
"for",
"details",
"."
... | python | train |
offu/WeRoBot | werobot/robot.py | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/robot.py#L467-L484 | def key_click(self, key):
"""
为自定义菜单 ``(click)`` 事件添加 handler 的简便方法。
**@key_click('KEYNAME')** 用来为特定 key 的点击事件添加 handler 方法。
"""
def wraps(f):
argc = len(signature(f).parameters.keys())
@self.click
def onclick(message, session=None):
... | [
"def",
"key_click",
"(",
"self",
",",
"key",
")",
":",
"def",
"wraps",
"(",
"f",
")",
":",
"argc",
"=",
"len",
"(",
"signature",
"(",
"f",
")",
".",
"parameters",
".",
"keys",
"(",
")",
")",
"@",
"self",
".",
"click",
"def",
"onclick",
"(",
"me... | 为自定义菜单 ``(click)`` 事件添加 handler 的简便方法。
**@key_click('KEYNAME')** 用来为特定 key 的点击事件添加 handler 方法。 | [
"为自定义菜单",
"(",
"click",
")",
"事件添加",
"handler",
"的简便方法。"
] | python | train |
rbuffat/pyepw | pyepw/epw.py | https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L2580-L2601 | def en020(self, value=None):
""" Corresponds to IDD Field `en020`
mean coincident dry-bulb temperature to
Enthalpy corresponding to 2.0% annual cumulative frequency of occurrence
Args:
value (float): value for IDD Field `en020`
Unit: kJ/kg
if... | [
"def",
"en020",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"try",
":",
"value",
"=",
"float",
"(",
"value",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'value {} need to be of type float '"... | Corresponds to IDD Field `en020`
mean coincident dry-bulb temperature to
Enthalpy corresponding to 2.0% annual cumulative frequency of occurrence
Args:
value (float): value for IDD Field `en020`
Unit: kJ/kg
if `value` is None it will not be checked ag... | [
"Corresponds",
"to",
"IDD",
"Field",
"en020",
"mean",
"coincident",
"dry",
"-",
"bulb",
"temperature",
"to",
"Enthalpy",
"corresponding",
"to",
"2",
".",
"0%",
"annual",
"cumulative",
"frequency",
"of",
"occurrence"
] | python | train |
tanghaibao/jcvi | jcvi/formats/vcf.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/vcf.py#L603-L626 | def encode_genotype(s, mindepth=3, depth_index=2, nohet=False):
"""
>>> encode_genotype("1/1:128,18,0:6:18") # homozygote B
'B'
>>> encode_genotype("0/1:0,0,0:0:3") # missing data
'-'
>>> encode_genotype("0/1:128,0,26:7:22") # heterozygous A/B
'X'
"""
atoms = s.split(":")
... | [
"def",
"encode_genotype",
"(",
"s",
",",
"mindepth",
"=",
"3",
",",
"depth_index",
"=",
"2",
",",
"nohet",
"=",
"False",
")",
":",
"atoms",
"=",
"s",
".",
"split",
"(",
"\":\"",
")",
"if",
"len",
"(",
"atoms",
")",
"<",
"3",
":",
"return",
"g2x",... | >>> encode_genotype("1/1:128,18,0:6:18") # homozygote B
'B'
>>> encode_genotype("0/1:0,0,0:0:3") # missing data
'-'
>>> encode_genotype("0/1:128,0,26:7:22") # heterozygous A/B
'X' | [
">>>",
"encode_genotype",
"(",
"1",
"/",
"1",
":",
"128",
"18",
"0",
":",
"6",
":",
"18",
")",
"#",
"homozygote",
"B",
"B",
">>>",
"encode_genotype",
"(",
"0",
"/",
"1",
":",
"0",
"0",
"0",
":",
"0",
":",
"3",
")",
"#",
"missing",
"data",
"-"... | python | train |
gear11/pypelogs | pypein/flickr.py | https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypein/flickr.py#L58-L66 | def photo(self, args):
"""
Retrieves metadata for a specific photo.
flickr:(credsfile),photo,(photo_id)
"""
rsp = self._load_rsp(self.flickr.photos_getInfo(photo_id=args[0]))
p = rsp['photo']
yield self._prep(p) | [
"def",
"photo",
"(",
"self",
",",
"args",
")",
":",
"rsp",
"=",
"self",
".",
"_load_rsp",
"(",
"self",
".",
"flickr",
".",
"photos_getInfo",
"(",
"photo_id",
"=",
"args",
"[",
"0",
"]",
")",
")",
"p",
"=",
"rsp",
"[",
"'photo'",
"]",
"yield",
"se... | Retrieves metadata for a specific photo.
flickr:(credsfile),photo,(photo_id) | [
"Retrieves",
"metadata",
"for",
"a",
"specific",
"photo",
"."
] | python | train |
crs4/pydoop | pydoop/hdfs/__init__.py | https://github.com/crs4/pydoop/blob/f375be2a06f9c67eaae3ce6f605195dbca143b2b/pydoop/hdfs/__init__.py#L313-L321 | def ls(hdfs_path, user=None, recursive=False):
"""
Return a list of hdfs paths.
Works in the same way as :func:`lsl`, except for the fact that list
items are hdfs paths instead of dictionaries of properties.
"""
dir_list = lsl(hdfs_path, user, recursive)
return [d["name"] for d in dir_list] | [
"def",
"ls",
"(",
"hdfs_path",
",",
"user",
"=",
"None",
",",
"recursive",
"=",
"False",
")",
":",
"dir_list",
"=",
"lsl",
"(",
"hdfs_path",
",",
"user",
",",
"recursive",
")",
"return",
"[",
"d",
"[",
"\"name\"",
"]",
"for",
"d",
"in",
"dir_list",
... | Return a list of hdfs paths.
Works in the same way as :func:`lsl`, except for the fact that list
items are hdfs paths instead of dictionaries of properties. | [
"Return",
"a",
"list",
"of",
"hdfs",
"paths",
"."
] | python | train |
tensorflow/probability | tensorflow_probability/python/internal/distribution_util.py | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/distribution_util.py#L354-L375 | def get_broadcast_shape(*tensors):
"""Get broadcast shape as a Python list of integers (preferred) or `Tensor`.
Args:
*tensors: One or more `Tensor` objects (already converted!).
Returns:
broadcast shape: Python list (if shapes determined statically), otherwise
an `int32` `Tensor`.
"""
# Try... | [
"def",
"get_broadcast_shape",
"(",
"*",
"tensors",
")",
":",
"# Try static.",
"s_shape",
"=",
"tensors",
"[",
"0",
"]",
".",
"shape",
"for",
"t",
"in",
"tensors",
"[",
"1",
":",
"]",
":",
"s_shape",
"=",
"tf",
".",
"broadcast_static_shape",
"(",
"s_shape... | Get broadcast shape as a Python list of integers (preferred) or `Tensor`.
Args:
*tensors: One or more `Tensor` objects (already converted!).
Returns:
broadcast shape: Python list (if shapes determined statically), otherwise
an `int32` `Tensor`. | [
"Get",
"broadcast",
"shape",
"as",
"a",
"Python",
"list",
"of",
"integers",
"(",
"preferred",
")",
"or",
"Tensor",
"."
] | python | test |
mitsei/dlkit | dlkit/json_/logging_/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/logging_/sessions.py#L2762-L2780 | def add_child_log(self, log_id, child_id):
"""Adds a child to a log.
arg: log_id (osid.id.Id): the ``Id`` of a log
arg: child_id (osid.id.Id): the ``Id`` of the new child
raise: AlreadyExists - ``log_id`` is already a parent of
``child_id``
raise: NotFoun... | [
"def",
"add_child_log",
"(",
"self",
",",
"log_id",
",",
"child_id",
")",
":",
"# Implemented from template for",
"# osid.resource.BinHierarchyDesignSession.add_child_bin_template",
"if",
"self",
".",
"_catalog_session",
"is",
"not",
"None",
":",
"return",
"self",
".",
... | Adds a child to a log.
arg: log_id (osid.id.Id): the ``Id`` of a log
arg: child_id (osid.id.Id): the ``Id`` of the new child
raise: AlreadyExists - ``log_id`` is already a parent of
``child_id``
raise: NotFound - ``log_id`` or ``child_id`` not found
raise... | [
"Adds",
"a",
"child",
"to",
"a",
"log",
"."
] | python | train |
appknox/google-chartwrapper | GChartWrapper/GChart.py | https://github.com/appknox/google-chartwrapper/blob/3769aecbef6c83b6cd93ee72ece478ffe433ac57/GChartWrapper/GChart.py#L362-L376 | def grid(self, *args):
"""
Apply a grid to your chart
args are of the form::
<x axis step size>,
<y axis step size>,
<length of line segment>,
<length of blank segment>
<x offset>,
<y offset>
APIPARAM: chg
""... | [
"def",
"grid",
"(",
"self",
",",
"*",
"args",
")",
":",
"grids",
"=",
"map",
"(",
"str",
",",
"map",
"(",
"float",
",",
"args",
")",
")",
"self",
"[",
"'chg'",
"]",
"=",
"','",
".",
"join",
"(",
"grids",
")",
".",
"replace",
"(",
"'None'",
",... | Apply a grid to your chart
args are of the form::
<x axis step size>,
<y axis step size>,
<length of line segment>,
<length of blank segment>
<x offset>,
<y offset>
APIPARAM: chg | [
"Apply",
"a",
"grid",
"to",
"your",
"chart",
"args",
"are",
"of",
"the",
"form",
"::",
"<x",
"axis",
"step",
"size",
">",
"<y",
"axis",
"step",
"size",
">",
"<length",
"of",
"line",
"segment",
">",
"<length",
"of",
"blank",
"segment",
">",
"<x",
"off... | python | test |
J535D165/recordlinkage | recordlinkage/api.py | https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/api.py#L163-L177 | def string(self, *args, **kwargs):
"""Compare attributes of pairs with string algorithm.
Shortcut of :class:`recordlinkage.compare.String`::
from recordlinkage.compare import String
indexer = recordlinkage.Compare()
indexer.add(String())
"""
compar... | [
"def",
"string",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"compare",
"=",
"String",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"add",
"(",
"compare",
")",
"return",
"self"
] | Compare attributes of pairs with string algorithm.
Shortcut of :class:`recordlinkage.compare.String`::
from recordlinkage.compare import String
indexer = recordlinkage.Compare()
indexer.add(String()) | [
"Compare",
"attributes",
"of",
"pairs",
"with",
"string",
"algorithm",
"."
] | python | train |
Fantomas42/django-blog-zinnia | zinnia/views/mixins/entry_protection.py | https://github.com/Fantomas42/django-blog-zinnia/blob/b4949304b104a8e1a7a7a0773cbfd024313c3a15/zinnia/views/mixins/entry_protection.py#L27-L33 | def password(self):
"""
Return the password view.
"""
return self.response_class(request=self.request,
template='zinnia/password.html',
context={'error': self.error}) | [
"def",
"password",
"(",
"self",
")",
":",
"return",
"self",
".",
"response_class",
"(",
"request",
"=",
"self",
".",
"request",
",",
"template",
"=",
"'zinnia/password.html'",
",",
"context",
"=",
"{",
"'error'",
":",
"self",
".",
"error",
"}",
")"
] | Return the password view. | [
"Return",
"the",
"password",
"view",
"."
] | python | train |
mitsei/dlkit | dlkit/json_/repository/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/repository/sessions.py#L3656-L3700 | def get_compositions_by_search(self, composition_query, composition_search):
"""Gets the search results matching the given search query using the given search.
arg: composition_query (osid.repository.CompositionQuery):
the composition query
arg: composition_search (osid.re... | [
"def",
"get_compositions_by_search",
"(",
"self",
",",
"composition_query",
",",
"composition_search",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceSearchSession.get_resources_by_search_template",
"# Copied from osid.resource.ResourceQuerySession.get_resources_by_que... | Gets the search results matching the given search query using the given search.
arg: composition_query (osid.repository.CompositionQuery):
the composition query
arg: composition_search (osid.repository.CompositionSearch):
the composition search
return: (osi... | [
"Gets",
"the",
"search",
"results",
"matching",
"the",
"given",
"search",
"query",
"using",
"the",
"given",
"search",
"."
] | python | train |
wonambi-python/wonambi | wonambi/trans/select.py | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/select.py#L63-L176 | def read_data(self, chan=[], ref_chan=[], grp_name=None, concat_chan=False,
max_s_freq=30000, parent=None):
"""Read data for analysis. Adds data as 'data' in each dict.
Parameters
----------
chan : list of str
active channel names as they appear in record,... | [
"def",
"read_data",
"(",
"self",
",",
"chan",
"=",
"[",
"]",
",",
"ref_chan",
"=",
"[",
"]",
",",
"grp_name",
"=",
"None",
",",
"concat_chan",
"=",
"False",
",",
"max_s_freq",
"=",
"30000",
",",
"parent",
"=",
"None",
")",
":",
"output",
"=",
"[",
... | Read data for analysis. Adds data as 'data' in each dict.
Parameters
----------
chan : list of str
active channel names as they appear in record, without ref or group
If given an empty list, the channel specified in seg['chan'] will
be read for each segment
... | [
"Read",
"data",
"for",
"analysis",
".",
"Adds",
"data",
"as",
"data",
"in",
"each",
"dict",
"."
] | python | train |
couchbase/couchbase-python-client | couchbase/subdocument.py | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/subdocument.py#L132-L141 | def replace(path, value, **kwargs):
"""
Replace an existing path. This works on any valid path if the path already
exists. Valid only in :cb_bmeth:`mutate_in`
:param path: The path to replace
:param value: The new value
"""
return _gen_4spec(LCB_SDCMD_REPLACE, path, value,
... | [
"def",
"replace",
"(",
"path",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gen_4spec",
"(",
"LCB_SDCMD_REPLACE",
",",
"path",
",",
"value",
",",
"create_path",
"=",
"False",
",",
"*",
"*",
"kwargs",
")"
] | Replace an existing path. This works on any valid path if the path already
exists. Valid only in :cb_bmeth:`mutate_in`
:param path: The path to replace
:param value: The new value | [
"Replace",
"an",
"existing",
"path",
".",
"This",
"works",
"on",
"any",
"valid",
"path",
"if",
"the",
"path",
"already",
"exists",
".",
"Valid",
"only",
"in",
":",
"cb_bmeth",
":",
"mutate_in"
] | python | train |
jwass/mplleaflet | mplleaflet/utils.py | https://github.com/jwass/mplleaflet/blob/a83d7b69c56d5507dd7c17f5be377d23a31e84ab/mplleaflet/utils.py#L27-L80 | def iterencode(self, o, _one_shot=False):
"""Encode the given object and yield each string
representation as available.
For example::
for chunk in JSONEncoder().iterencode(bigobject):
mysocket.write(chunk)
"""
c_make_encoder_original = json.encoder.c_m... | [
"def",
"iterencode",
"(",
"self",
",",
"o",
",",
"_one_shot",
"=",
"False",
")",
":",
"c_make_encoder_original",
"=",
"json",
".",
"encoder",
".",
"c_make_encoder",
"json",
".",
"encoder",
".",
"c_make_encoder",
"=",
"None",
"if",
"self",
".",
"check_circula... | Encode the given object and yield each string
representation as available.
For example::
for chunk in JSONEncoder().iterencode(bigobject):
mysocket.write(chunk) | [
"Encode",
"the",
"given",
"object",
"and",
"yield",
"each",
"string",
"representation",
"as",
"available",
".",
"For",
"example",
"::",
"for",
"chunk",
"in",
"JSONEncoder",
"()",
".",
"iterencode",
"(",
"bigobject",
")",
":",
"mysocket",
".",
"write",
"(",
... | python | train |
mbedmicro/pyOCD | pyocd/coresight/ap.py | https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/coresight/ap.py#L369-L386 | def hprot(self, value):
"""! @brief Setter for current HPROT value used for memory transactions.
The bits of HPROT have the following meaning. Not all bits are implemented in all
MEM-APs. AHB-Lite only implements HPROT[3:0].
HPROT[0] = 1 data access, 0 instr fetch<br/>
... | [
"def",
"hprot",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_hprot",
"=",
"value",
"&",
"(",
"CSW_HPROT_MASK",
">>",
"CSW_HPROT_SHIFT",
")",
"self",
".",
"_csw",
"=",
"(",
"(",
"self",
".",
"_csw",
"&",
"~",
"CSW_HPROT_MASK",
")",
"|",
"(",
... | ! @brief Setter for current HPROT value used for memory transactions.
The bits of HPROT have the following meaning. Not all bits are implemented in all
MEM-APs. AHB-Lite only implements HPROT[3:0].
HPROT[0] = 1 data access, 0 instr fetch<br/>
HPROT[1] = 1 priviledge, 0 user... | [
"!"
] | python | train |
bearyinnovative/bearychat.py | bearychat/incoming.py | https://github.com/bearyinnovative/bearychat.py/blob/6c7af2d215c2ff7135bb5af66ca333d0ea1089fd/bearychat/incoming.py#L43-L55 | def send(url, data):
"""Sends an incoming message
Args:
url(str): the incoming hook url
data(dict): the sending data
Returns:
requests.Response
"""
validate(data)
return requests.post(url, json=data) | [
"def",
"send",
"(",
"url",
",",
"data",
")",
":",
"validate",
"(",
"data",
")",
"return",
"requests",
".",
"post",
"(",
"url",
",",
"json",
"=",
"data",
")"
] | Sends an incoming message
Args:
url(str): the incoming hook url
data(dict): the sending data
Returns:
requests.Response | [
"Sends",
"an",
"incoming",
"message"
] | python | train |
materialsproject/pymatgen-db | matgendb/creator.py | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/creator.py#L202-L241 | def get_task_doc(self, path):
"""
Get the entire task doc for a path, including any post-processing.
"""
logger.info("Getting task doc for base dir :{}".format(path))
files = os.listdir(path)
vasprun_files = OrderedDict()
if "STOPCAR" in files:
#Stoppe... | [
"def",
"get_task_doc",
"(",
"self",
",",
"path",
")",
":",
"logger",
".",
"info",
"(",
"\"Getting task doc for base dir :{}\"",
".",
"format",
"(",
"path",
")",
")",
"files",
"=",
"os",
".",
"listdir",
"(",
"path",
")",
"vasprun_files",
"=",
"OrderedDict",
... | Get the entire task doc for a path, including any post-processing. | [
"Get",
"the",
"entire",
"task",
"doc",
"for",
"a",
"path",
"including",
"any",
"post",
"-",
"processing",
"."
] | python | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/SConsign.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/SConsign.py#L406-L419 | def File(name, dbm_module=None):
"""
Arrange for all signatures to be stored in a global .sconsign.db*
file.
"""
global ForDirectory, DB_Name, DB_Module
if name is None:
ForDirectory = DirFile
DB_Module = None
else:
ForDirectory = DB
DB_Name = name
if ... | [
"def",
"File",
"(",
"name",
",",
"dbm_module",
"=",
"None",
")",
":",
"global",
"ForDirectory",
",",
"DB_Name",
",",
"DB_Module",
"if",
"name",
"is",
"None",
":",
"ForDirectory",
"=",
"DirFile",
"DB_Module",
"=",
"None",
"else",
":",
"ForDirectory",
"=",
... | Arrange for all signatures to be stored in a global .sconsign.db*
file. | [
"Arrange",
"for",
"all",
"signatures",
"to",
"be",
"stored",
"in",
"a",
"global",
".",
"sconsign",
".",
"db",
"*",
"file",
"."
] | python | train |
emilydolson/avida-spatial-tools | avidaspatial/visualizations.py | https://github.com/emilydolson/avida-spatial-tools/blob/7beb0166ccefad5fa722215b030ac2a53d62b59e/avidaspatial/visualizations.py#L230-L249 | def plot_phens_blits(phen_grid, patches, **kwargs):
"""
A version of plot_phens designed to be used in animations. Takes a 2D array
of phenotypes and a list of matplotlib patch objects that have already
been added to the current axes and recolors the patches based on the array.
"""
denom, palet... | [
"def",
"plot_phens_blits",
"(",
"phen_grid",
",",
"patches",
",",
"*",
"*",
"kwargs",
")",
":",
"denom",
",",
"palette",
"=",
"get_kwargs",
"(",
"phen_grid",
",",
"kwargs",
")",
"grid",
"=",
"color_grid",
"(",
"phen_grid",
",",
"palette",
",",
"denom",
"... | A version of plot_phens designed to be used in animations. Takes a 2D array
of phenotypes and a list of matplotlib patch objects that have already
been added to the current axes and recolors the patches based on the array. | [
"A",
"version",
"of",
"plot_phens",
"designed",
"to",
"be",
"used",
"in",
"animations",
".",
"Takes",
"a",
"2D",
"array",
"of",
"phenotypes",
"and",
"a",
"list",
"of",
"matplotlib",
"patch",
"objects",
"that",
"have",
"already",
"been",
"added",
"to",
"the... | python | train |
Contraz/demosys-py | demosys/management/commands/createeffect.py | https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/management/commands/createeffect.py#L75-L78 | def root_path():
"""Get the absolute path to the root of the demosys package"""
module_dir = os.path.dirname(globals()['__file__'])
return os.path.dirname(os.path.dirname(module_dir)) | [
"def",
"root_path",
"(",
")",
":",
"module_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"globals",
"(",
")",
"[",
"'__file__'",
"]",
")",
"return",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"module_dir",
... | Get the absolute path to the root of the demosys package | [
"Get",
"the",
"absolute",
"path",
"to",
"the",
"root",
"of",
"the",
"demosys",
"package"
] | python | valid |
rbw/pysnow | pysnow/client.py | https://github.com/rbw/pysnow/blob/87c8ce0d3a089c2f59247f30efbd545fcdb8e985/pysnow/client.py#L91-L115 | def _get_session(self, session):
"""Creates a new session with basic auth, unless one was provided, and sets headers.
:param session: (optional) Session to re-use
:return:
- :class:`requests.Session` object
"""
if not session:
logger.debug('(SESSION_CREA... | [
"def",
"_get_session",
"(",
"self",
",",
"session",
")",
":",
"if",
"not",
"session",
":",
"logger",
".",
"debug",
"(",
"'(SESSION_CREATE) User: %s'",
"%",
"self",
".",
"_user",
")",
"s",
"=",
"requests",
".",
"Session",
"(",
")",
"s",
".",
"auth",
"="... | Creates a new session with basic auth, unless one was provided, and sets headers.
:param session: (optional) Session to re-use
:return:
- :class:`requests.Session` object | [
"Creates",
"a",
"new",
"session",
"with",
"basic",
"auth",
"unless",
"one",
"was",
"provided",
"and",
"sets",
"headers",
"."
] | python | train |
redodo/formats | formats/banks.py | https://github.com/redodo/formats/blob/5bc7a79a2c93ef895534edbbf83f1efe2f62e081/formats/banks.py#L110-L120 | def compose(self, type, data):
"""Compose text as a format.
:param type: The unique name of the format
:param data: The text to compose as the format
"""
try:
return self.registered_formats[type]['composer'](data)
except KeyError:
raise NotImpleme... | [
"def",
"compose",
"(",
"self",
",",
"type",
",",
"data",
")",
":",
"try",
":",
"return",
"self",
".",
"registered_formats",
"[",
"type",
"]",
"[",
"'composer'",
"]",
"(",
"data",
")",
"except",
"KeyError",
":",
"raise",
"NotImplementedError",
"(",
"\"No ... | Compose text as a format.
:param type: The unique name of the format
:param data: The text to compose as the format | [
"Compose",
"text",
"as",
"a",
"format",
"."
] | python | train |
Akrog/cinderlib | cinderlib/nos_brick.py | https://github.com/Akrog/cinderlib/blob/6481cd9a34744f80bdba130fe9089f1b8b7cb327/cinderlib/nos_brick.py#L114-L130 | def check_valid_device(self, path, run_as_root=True):
"""Verify an existing RBD handle is connected and valid."""
if self.im_root:
try:
with open(path, 'r') as f:
f.read(4096)
except Exception:
return False
return Tr... | [
"def",
"check_valid_device",
"(",
"self",
",",
"path",
",",
"run_as_root",
"=",
"True",
")",
":",
"if",
"self",
".",
"im_root",
":",
"try",
":",
"with",
"open",
"(",
"path",
",",
"'r'",
")",
"as",
"f",
":",
"f",
".",
"read",
"(",
"4096",
")",
"ex... | Verify an existing RBD handle is connected and valid. | [
"Verify",
"an",
"existing",
"RBD",
"handle",
"is",
"connected",
"and",
"valid",
"."
] | python | train |
alex-kostirin/pyatomac | atomac/ldtpd/mouse.py | https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/mouse.py#L73-L94 | def mouseleftclick(self, window_name, object_name):
"""
Mouse left click on an object.
@param window_name: Window name to look for, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to look for, ei... | [
"def",
"mouseleftclick",
"(",
"self",
",",
"window_name",
",",
"object_name",
")",
":",
"object_handle",
"=",
"self",
".",
"_get_object_handle",
"(",
"window_name",
",",
"object_name",
")",
"if",
"not",
"object_handle",
".",
"AXEnabled",
":",
"raise",
"LdtpServe... | Mouse left click on an object.
@param window_name: Window name to look for, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to look for, either full name,
LDTP's name convention, or a Unix glob. Or menu ... | [
"Mouse",
"left",
"click",
"on",
"an",
"object",
".",
"@param",
"window_name",
":",
"Window",
"name",
"to",
"look",
"for",
"either",
"full",
"name",
"LDTP",
"s",
"name",
"convention",
"or",
"a",
"Unix",
"glob",
".",
"@type",
"window_name",
":",
"string",
... | python | valid |
intel-analytics/BigDL | pyspark/bigdl/transform/vision/image.py | https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/transform/vision/image.py#L200-L207 | def random_split(self, weights):
"""
Random split imageframes according to weights
:param weights: weights for each ImageFrame
:return:
"""
jvalues = self.image_frame.random_split(weights)
return [ImageFrame(jvalue) for jvalue in jvalues] | [
"def",
"random_split",
"(",
"self",
",",
"weights",
")",
":",
"jvalues",
"=",
"self",
".",
"image_frame",
".",
"random_split",
"(",
"weights",
")",
"return",
"[",
"ImageFrame",
"(",
"jvalue",
")",
"for",
"jvalue",
"in",
"jvalues",
"]"
] | Random split imageframes according to weights
:param weights: weights for each ImageFrame
:return: | [
"Random",
"split",
"imageframes",
"according",
"to",
"weights",
":",
"param",
"weights",
":",
"weights",
"for",
"each",
"ImageFrame",
":",
"return",
":"
] | python | test |
Toilal/rebulk | rebulk/match.py | https://github.com/Toilal/rebulk/blob/7511a4671f2fd9493e3df1e5177b7656789069e8/rebulk/match.py#L500-L535 | def to_dict(self, details=False, first_value=False, enforce_list=False):
"""
Converts matches to a dict object.
:param details if True, values will be complete Match object, else it will be only string Match.value property
:type details: bool
:param first_value if True, only the ... | [
"def",
"to_dict",
"(",
"self",
",",
"details",
"=",
"False",
",",
"first_value",
"=",
"False",
",",
"enforce_list",
"=",
"False",
")",
":",
"ret",
"=",
"MatchesDict",
"(",
")",
"for",
"match",
"in",
"sorted",
"(",
"self",
")",
":",
"value",
"=",
"mat... | Converts matches to a dict object.
:param details if True, values will be complete Match object, else it will be only string Match.value property
:type details: bool
:param first_value if True, only the first value will be kept. Else, multiple values will be set as a list in
the dict.
... | [
"Converts",
"matches",
"to",
"a",
"dict",
"object",
".",
":",
"param",
"details",
"if",
"True",
"values",
"will",
"be",
"complete",
"Match",
"object",
"else",
"it",
"will",
"be",
"only",
"string",
"Match",
".",
"value",
"property",
":",
"type",
"details",
... | python | train |
klis87/django-cloudinary-storage | cloudinary_storage/storage.py | https://github.com/klis87/django-cloudinary-storage/blob/b8cabd2ebbf67b9cfbbf4defee1a750fea5950a9/cloudinary_storage/storage.py#L200-L212 | def _remove_extension_for_non_raw_file(self, name):
"""
Implemented as image and video files' Cloudinary public id
shouldn't contain file extensions, otherwise Cloudinary url
would contain doubled extension - Cloudinary adds extension to url
to allow file conversion to arbitrary ... | [
"def",
"_remove_extension_for_non_raw_file",
"(",
"self",
",",
"name",
")",
":",
"file_resource_type",
"=",
"self",
".",
"_get_resource_type",
"(",
"name",
")",
"if",
"file_resource_type",
"is",
"None",
"or",
"file_resource_type",
"==",
"self",
".",
"RESOURCE_TYPE",... | Implemented as image and video files' Cloudinary public id
shouldn't contain file extensions, otherwise Cloudinary url
would contain doubled extension - Cloudinary adds extension to url
to allow file conversion to arbitrary file, like png to jpg. | [
"Implemented",
"as",
"image",
"and",
"video",
"files",
"Cloudinary",
"public",
"id",
"shouldn",
"t",
"contain",
"file",
"extensions",
"otherwise",
"Cloudinary",
"url",
"would",
"contain",
"doubled",
"extension",
"-",
"Cloudinary",
"adds",
"extension",
"to",
"url",... | python | train |
bmcfee/muda | muda/core.py | https://github.com/bmcfee/muda/blob/ff82efdfaeb98da0a9f9124845826eb20536a9ba/muda/core.py#L68-L119 | def load_jam_audio(jam_in, audio_file,
validate=True,
strict=True,
fmt='auto',
**kwargs):
'''Load a jam and pack it with audio.
Parameters
----------
jam_in : str, file descriptor, or jams.JAMS
JAMS filename, open file-... | [
"def",
"load_jam_audio",
"(",
"jam_in",
",",
"audio_file",
",",
"validate",
"=",
"True",
",",
"strict",
"=",
"True",
",",
"fmt",
"=",
"'auto'",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"jam_in",
",",
"jams",
".",
"JAMS",
")",
":",
... | Load a jam and pack it with audio.
Parameters
----------
jam_in : str, file descriptor, or jams.JAMS
JAMS filename, open file-descriptor, or object to load.
See ``jams.load`` for acceptable formats.
audio_file : str
Audio filename to load
validate : bool
strict : bool
... | [
"Load",
"a",
"jam",
"and",
"pack",
"it",
"with",
"audio",
"."
] | python | valid |
pennlabs/penncoursereview-sdk-python | penncoursereview/api.py | https://github.com/pennlabs/penncoursereview-sdk-python/blob/f9f2f1bfcadf0aff50133e35d761f6d1cf85b564/penncoursereview/api.py#L47-L56 | def _update(self, data):
"""Update the object with new data."""
for k, v in six.iteritems(data):
new_value = v
if isinstance(v, dict):
new_value = type(self)(v)
elif isinstance(v, list):
new_value = [(type(self)(e) if isinstance(e, dict... | [
"def",
"_update",
"(",
"self",
",",
"data",
")",
":",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"data",
")",
":",
"new_value",
"=",
"v",
"if",
"isinstance",
"(",
"v",
",",
"dict",
")",
":",
"new_value",
"=",
"type",
"(",
"self",
... | Update the object with new data. | [
"Update",
"the",
"object",
"with",
"new",
"data",
"."
] | python | train |
SmokinCaterpillar/pypet | examples/example_24_large_scale_brian2_simulation/clusternet.py | https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/examples/example_24_large_scale_brian2_simulation/clusternet.py#L363-L473 | def _build_connections(self, traj, brian_list, network_dict):
"""Connects neuron groups `neurons_i` and `neurons_e`.
Adds all connections to `brian_list` and adds a list of connections
with the key 'connections' to the `network_dict`.
"""
connections = traj.connections
... | [
"def",
"_build_connections",
"(",
"self",
",",
"traj",
",",
"brian_list",
",",
"network_dict",
")",
":",
"connections",
"=",
"traj",
".",
"connections",
"neurons_i",
"=",
"network_dict",
"[",
"'neurons_i'",
"]",
"neurons_e",
"=",
"network_dict",
"[",
"'neurons_e... | Connects neuron groups `neurons_i` and `neurons_e`.
Adds all connections to `brian_list` and adds a list of connections
with the key 'connections' to the `network_dict`. | [
"Connects",
"neuron",
"groups",
"neurons_i",
"and",
"neurons_e",
"."
] | python | test |
chrisjrn/registrasion | registrasion/controllers/cart.py | https://github.com/chrisjrn/registrasion/blob/461d5846c6f9f3b7099322a94f5d9911564448e4/registrasion/controllers/cart.py#L271-L284 | def apply_voucher(self, voucher_code):
''' Applies the voucher with the given code to this cart. '''
# Try and find the voucher
voucher = inventory.Voucher.objects.get(code=voucher_code.upper())
# Re-applying vouchers should be idempotent
if voucher in self.cart.vouchers.all():... | [
"def",
"apply_voucher",
"(",
"self",
",",
"voucher_code",
")",
":",
"# Try and find the voucher",
"voucher",
"=",
"inventory",
".",
"Voucher",
".",
"objects",
".",
"get",
"(",
"code",
"=",
"voucher_code",
".",
"upper",
"(",
")",
")",
"# Re-applying vouchers shou... | Applies the voucher with the given code to this cart. | [
"Applies",
"the",
"voucher",
"with",
"the",
"given",
"code",
"to",
"this",
"cart",
"."
] | python | test |
facetoe/zenpy | zenpy/lib/api_objects/help_centre_objects.py | https://github.com/facetoe/zenpy/blob/34c54c7e408b9ed01604ddf8b3422204c8bf31ea/zenpy/lib/api_objects/help_centre_objects.py#L878-L883 | def topic(self):
"""
| Comment: The id of the topic that the post belongs to
"""
if self.api and self.topic_id:
return self.api._get_topic(self.topic_id) | [
"def",
"topic",
"(",
"self",
")",
":",
"if",
"self",
".",
"api",
"and",
"self",
".",
"topic_id",
":",
"return",
"self",
".",
"api",
".",
"_get_topic",
"(",
"self",
".",
"topic_id",
")"
] | | Comment: The id of the topic that the post belongs to | [
"|",
"Comment",
":",
"The",
"id",
"of",
"the",
"topic",
"that",
"the",
"post",
"belongs",
"to"
] | python | train |
oscarlazoarjona/fast | fast/inhomo.py | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/inhomo.py#L985-L1129 | def fast_inhomo_sweep_time_evolution(Ep, epsilonp, gamma,
omega_level, rm, xi, theta,
inhomogeneity,
semi_analytic=True,
file_name=None, return_code=False):
r"""Return ... | [
"def",
"fast_inhomo_sweep_time_evolution",
"(",
"Ep",
",",
"epsilonp",
",",
"gamma",
",",
"omega_level",
",",
"rm",
",",
"xi",
",",
"theta",
",",
"inhomogeneity",
",",
"semi_analytic",
"=",
"True",
",",
"file_name",
"=",
"None",
",",
"return_code",
"=",
"Fal... | r"""Return a spectrum of time evolutions of the density matrix.
We test a basic two-level system.
>>> from fast.bloch import phase_transformation
>>> from fast import PlaneWave, electric_field_amplitude_top, Atom
>>> Ne = 2
>>> Nl = 1
>>> a0 = physical_constants["Bohr radius"][0]
>>> rm = ... | [
"r",
"Return",
"a",
"spectrum",
"of",
"time",
"evolutions",
"of",
"the",
"density",
"matrix",
"."
] | python | train |
ahwillia/tensortools | tensortools/optimize/ncp_hals.py | https://github.com/ahwillia/tensortools/blob/f375633ec621caa96665a56205dcf932590d4a6e/tensortools/optimize/ncp_hals.py#L18-L130 | def ncp_hals(X, rank, random_state=None, init='rand', **options):
"""
Fits nonnegtaive CP Decomposition using the Hierarcial Alternating Least
Squares (HALS) Method.
Parameters
----------
X : (I_1, ..., I_N) array_like
A real array with nonnegative entries and ``X.ndim >= 3``.
rank... | [
"def",
"ncp_hals",
"(",
"X",
",",
"rank",
",",
"random_state",
"=",
"None",
",",
"init",
"=",
"'rand'",
",",
"*",
"*",
"options",
")",
":",
"# Check inputs.",
"optim_utils",
".",
"_check_cpd_inputs",
"(",
"X",
",",
"rank",
")",
"# Initialize problem.",
"U"... | Fits nonnegtaive CP Decomposition using the Hierarcial Alternating Least
Squares (HALS) Method.
Parameters
----------
X : (I_1, ..., I_N) array_like
A real array with nonnegative entries and ``X.ndim >= 3``.
rank : integer
The `rank` sets the number of components to be computed.
... | [
"Fits",
"nonnegtaive",
"CP",
"Decomposition",
"using",
"the",
"Hierarcial",
"Alternating",
"Least",
"Squares",
"(",
"HALS",
")",
"Method",
"."
] | python | train |
digidotcom/python-devicecloud | devicecloud/__init__.py | https://github.com/digidotcom/python-devicecloud/blob/32529684a348a7830a269c32601604c78036bcb8/devicecloud/__init__.py#L131-L134 | def hostname(self):
"""Get the hostname that this connection is associated with"""
from six.moves.urllib.parse import urlparse
return urlparse(self._base_url).netloc.split(':', 1)[0] | [
"def",
"hostname",
"(",
"self",
")",
":",
"from",
"six",
".",
"moves",
".",
"urllib",
".",
"parse",
"import",
"urlparse",
"return",
"urlparse",
"(",
"self",
".",
"_base_url",
")",
".",
"netloc",
".",
"split",
"(",
"':'",
",",
"1",
")",
"[",
"0",
"]... | Get the hostname that this connection is associated with | [
"Get",
"the",
"hostname",
"that",
"this",
"connection",
"is",
"associated",
"with"
] | python | train |
cloudant/python-cloudant | src/cloudant/client.py | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/client.py#L802-L821 | def _write_cors_configuration(self, config):
"""
Overwrites the entire CORS config with the values updated in
update_cors_configuration.
:param dict config: Dictionary containing the updated CORS
configuration.
:returns: CORS configuration update status in JSON form... | [
"def",
"_write_cors_configuration",
"(",
"self",
",",
"config",
")",
":",
"endpoint",
"=",
"'/'",
".",
"join",
"(",
"(",
"self",
".",
"server_url",
",",
"'_api'",
",",
"'v2'",
",",
"'user'",
",",
"'config'",
",",
"'cors'",
")",
")",
"resp",
"=",
"self"... | Overwrites the entire CORS config with the values updated in
update_cors_configuration.
:param dict config: Dictionary containing the updated CORS
configuration.
:returns: CORS configuration update status in JSON format | [
"Overwrites",
"the",
"entire",
"CORS",
"config",
"with",
"the",
"values",
"updated",
"in",
"update_cors_configuration",
"."
] | python | train |
saltstack/salt | salt/wheel/pillar_roots.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/wheel/pillar_roots.py#L98-L117 | def write(data, path, saltenv='base', index=0):
'''
Write the named file, by default the first file found is written, but the
index of the file can be specified to write to a lower priority file root
'''
if saltenv not in __opts__['pillar_roots']:
return 'Named environment {0} is not present... | [
"def",
"write",
"(",
"data",
",",
"path",
",",
"saltenv",
"=",
"'base'",
",",
"index",
"=",
"0",
")",
":",
"if",
"saltenv",
"not",
"in",
"__opts__",
"[",
"'pillar_roots'",
"]",
":",
"return",
"'Named environment {0} is not present'",
".",
"format",
"(",
"s... | Write the named file, by default the first file found is written, but the
index of the file can be specified to write to a lower priority file root | [
"Write",
"the",
"named",
"file",
"by",
"default",
"the",
"first",
"file",
"found",
"is",
"written",
"but",
"the",
"index",
"of",
"the",
"file",
"can",
"be",
"specified",
"to",
"write",
"to",
"a",
"lower",
"priority",
"file",
"root"
] | python | train |
wtsi-hgi/python-hgijson | hgijson/json_converters/_converters.py | https://github.com/wtsi-hgi/python-hgijson/blob/6e8ccb562eabcaa816a136268a16504c2e0d4664/hgijson/json_converters/_converters.py#L94-L108 | def json_decoder_to_deserializer(decoder_cls: Union[Type[JSONDecoder], Callable[[], Type[JSONDecoder]]]) \
-> Type[Deserializer]:
"""
Converts a `JSONDecoder` class into an equivalent `Deserializer` class.
:param decoder_cls: the decoder class type or a function that returns the type
:return: th... | [
"def",
"json_decoder_to_deserializer",
"(",
"decoder_cls",
":",
"Union",
"[",
"Type",
"[",
"JSONDecoder",
"]",
",",
"Callable",
"[",
"[",
"]",
",",
"Type",
"[",
"JSONDecoder",
"]",
"]",
"]",
")",
"->",
"Type",
"[",
"Deserializer",
"]",
":",
"name",
"=",
... | Converts a `JSONDecoder` class into an equivalent `Deserializer` class.
:param decoder_cls: the decoder class type or a function that returns the type
:return: the equivalent `Deserializer` class | [
"Converts",
"a",
"JSONDecoder",
"class",
"into",
"an",
"equivalent",
"Deserializer",
"class",
".",
":",
"param",
"decoder_cls",
":",
"the",
"decoder",
"class",
"type",
"or",
"a",
"function",
"that",
"returns",
"the",
"type",
":",
"return",
":",
"the",
"equiv... | python | train |
UCL-INGI/INGInious | inginious/frontend/pages/course_admin/task_edit_file.py | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/course_admin/task_edit_file.py#L235-L251 | def action_download(self, courseid, taskid, path):
""" Download a file or a directory """
wanted_path = self.verify_path(courseid, taskid, path)
if wanted_path is None:
raise web.notfound()
task_fs = self.task_factory.get_task_fs(courseid, taskid)
(method, mimetype_... | [
"def",
"action_download",
"(",
"self",
",",
"courseid",
",",
"taskid",
",",
"path",
")",
":",
"wanted_path",
"=",
"self",
".",
"verify_path",
"(",
"courseid",
",",
"taskid",
",",
"path",
")",
"if",
"wanted_path",
"is",
"None",
":",
"raise",
"web",
".",
... | Download a file or a directory | [
"Download",
"a",
"file",
"or",
"a",
"directory"
] | python | train |
bcbio/bcbio-nextgen | scripts/utils/hla_loh_comparison.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/scripts/utils/hla_loh_comparison.py#L328-L342 | def prep_ploidy(work_dir, sample, bam_file, cromwell_dir, sv_glob):
"""Create LOHHLA compatible input ploidy file from PureCN output.
"""
purecn_file = _get_cromwell_file(cromwell_dir, sv_glob, dict(sample=sample, method="purecn", ext="purecn.csv"))
work_dir = utils.safe_makedir(os.path.join(work_dir, s... | [
"def",
"prep_ploidy",
"(",
"work_dir",
",",
"sample",
",",
"bam_file",
",",
"cromwell_dir",
",",
"sv_glob",
")",
":",
"purecn_file",
"=",
"_get_cromwell_file",
"(",
"cromwell_dir",
",",
"sv_glob",
",",
"dict",
"(",
"sample",
"=",
"sample",
",",
"method",
"="... | Create LOHHLA compatible input ploidy file from PureCN output. | [
"Create",
"LOHHLA",
"compatible",
"input",
"ploidy",
"file",
"from",
"PureCN",
"output",
"."
] | python | train |
samghelms/mathviz | examples/utils.py | https://github.com/samghelms/mathviz/blob/30fe89537379faea4de8c8b568ac6e52e4d15353/examples/utils.py#L14-L35 | def get_next_token(string):
'''
"eats" up the string until it hits an ending character to get valid leaf expressions.
For example, given \\Phi_{z}(L) = \\sum_{i=1}^{N} \\frac{1}{C_{i} \\times V_{\\rm max, i}},
this function would pull out \\Phi, stopping at _
@ string: str
returns a tuple of (ex... | [
"def",
"get_next_token",
"(",
"string",
")",
":",
"STOP_CHARS",
"=",
"\"_ {}^ \\n ,()=\"",
"UNARY_CHARS",
"=",
"\"^_\"",
"# ^ and _ are valid leaf expressions--just ones that should be handled on their own",
"if",
"string",
"[",
"0",
"]",
"in",
"STOP_CHARS",
":",
"return",
... | "eats" up the string until it hits an ending character to get valid leaf expressions.
For example, given \\Phi_{z}(L) = \\sum_{i=1}^{N} \\frac{1}{C_{i} \\times V_{\\rm max, i}},
this function would pull out \\Phi, stopping at _
@ string: str
returns a tuple of (expression [ex: \\Phi], remaining_chars [e... | [
"eats",
"up",
"the",
"string",
"until",
"it",
"hits",
"an",
"ending",
"character",
"to",
"get",
"valid",
"leaf",
"expressions",
".",
"For",
"example",
"given",
"\\\\",
"Phi_",
"{",
"z",
"}",
"(",
"L",
")",
"=",
"\\\\",
"sum_",
"{",
"i",
"=",
"1",
"... | python | train |
rackerlabs/rackspace-python-neutronclient | neutronclient/neutron/client.py | https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/neutron/client.py#L55-L65 | def Client(api_version, *args, **kwargs):
"""Return an neutron client.
@param api_version: only 2.0 is supported now
"""
neutron_client = utils.get_client_class(
API_NAME,
api_version,
API_VERSIONS,
)
return neutron_client(*args, **kwargs) | [
"def",
"Client",
"(",
"api_version",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"neutron_client",
"=",
"utils",
".",
"get_client_class",
"(",
"API_NAME",
",",
"api_version",
",",
"API_VERSIONS",
",",
")",
"return",
"neutron_client",
"(",
"*",
"ar... | Return an neutron client.
@param api_version: only 2.0 is supported now | [
"Return",
"an",
"neutron",
"client",
"."
] | python | train |
OpenTreeOfLife/peyotl | peyotl/api/oti.py | https://github.com/OpenTreeOfLife/peyotl/blob/5e4e52a0fdbd17f490aa644ad79fda6ea2eda7c0/peyotl/api/oti.py#L119-L127 | def find_nodes(self, query_dict=None, exact=False, verbose=False, **kwargs):
"""Query on node properties. See documentation for _OTIWrapper class."""
assert self.use_v1
return self._do_query('{p}/singlePropertySearchForTreeNodes'.format(p=self.query_prefix),
query_d... | [
"def",
"find_nodes",
"(",
"self",
",",
"query_dict",
"=",
"None",
",",
"exact",
"=",
"False",
",",
"verbose",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"self",
".",
"use_v1",
"return",
"self",
".",
"_do_query",
"(",
"'{p}/singlePropertyS... | Query on node properties. See documentation for _OTIWrapper class. | [
"Query",
"on",
"node",
"properties",
".",
"See",
"documentation",
"for",
"_OTIWrapper",
"class",
"."
] | python | train |
mathandy/svgpathtools | svgpathtools/path.py | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/path.py#L916-L924 | def reversed(self):
"""returns a copy of the QuadraticBezier object with its orientation
reversed."""
new_quad = QuadraticBezier(self.end, self.control, self.start)
if self._length_info['length']:
new_quad._length_info = self._length_info
new_quad._length_info['bp... | [
"def",
"reversed",
"(",
"self",
")",
":",
"new_quad",
"=",
"QuadraticBezier",
"(",
"self",
".",
"end",
",",
"self",
".",
"control",
",",
"self",
".",
"start",
")",
"if",
"self",
".",
"_length_info",
"[",
"'length'",
"]",
":",
"new_quad",
".",
"_length_... | returns a copy of the QuadraticBezier object with its orientation
reversed. | [
"returns",
"a",
"copy",
"of",
"the",
"QuadraticBezier",
"object",
"with",
"its",
"orientation",
"reversed",
"."
] | python | train |
saltstack/salt | salt/config/__init__.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L1995-L2009 | def _expand_glob_path(file_roots):
'''
Applies shell globbing to a set of directories and returns
the expanded paths
'''
unglobbed_path = []
for path in file_roots:
try:
if glob.has_magic(path):
unglobbed_path.extend(glob.glob(path))
else:
... | [
"def",
"_expand_glob_path",
"(",
"file_roots",
")",
":",
"unglobbed_path",
"=",
"[",
"]",
"for",
"path",
"in",
"file_roots",
":",
"try",
":",
"if",
"glob",
".",
"has_magic",
"(",
"path",
")",
":",
"unglobbed_path",
".",
"extend",
"(",
"glob",
".",
"glob"... | Applies shell globbing to a set of directories and returns
the expanded paths | [
"Applies",
"shell",
"globbing",
"to",
"a",
"set",
"of",
"directories",
"and",
"returns",
"the",
"expanded",
"paths"
] | python | train |
Cadasta/django-tutelary | tutelary/wildtree.py | https://github.com/Cadasta/django-tutelary/blob/66bb05de7098777c0a383410c287bf48433cde87/tutelary/wildtree.py#L159-L184 | def find_in_tree(tree, key, perfect=False):
"""
Helper to perform find in dictionary tree.
"""
if len(key) == 0:
if tree['item'] is not None:
return tree['item'], ()
else:
for i in range(len(tree['subtrees'])):
if not perfect and tree['subtrees'][i... | [
"def",
"find_in_tree",
"(",
"tree",
",",
"key",
",",
"perfect",
"=",
"False",
")",
":",
"if",
"len",
"(",
"key",
")",
"==",
"0",
":",
"if",
"tree",
"[",
"'item'",
"]",
"is",
"not",
"None",
":",
"return",
"tree",
"[",
"'item'",
"]",
",",
"(",
")... | Helper to perform find in dictionary tree. | [
"Helper",
"to",
"perform",
"find",
"in",
"dictionary",
"tree",
"."
] | python | train |
Scoppio/RagnarokEngine3 | RagnarokEngine3/RE3.py | https://github.com/Scoppio/RagnarokEngine3/blob/4395d419ccd64fe9327c41f200b72ee0176ad896/RagnarokEngine3/RE3.py#L958-L967 | def translate(translationAmt):
"""Create a translation matrix."""
if not isinstance(translationAmt, Vector3):
raise ValueError("translationAmt must be a Vector3")
ma4 = Matrix4((1, 0, 0, translationAmt.x),
(0, 1, 0, translationAmt.y),
(0, ... | [
"def",
"translate",
"(",
"translationAmt",
")",
":",
"if",
"not",
"isinstance",
"(",
"translationAmt",
",",
"Vector3",
")",
":",
"raise",
"ValueError",
"(",
"\"translationAmt must be a Vector3\"",
")",
"ma4",
"=",
"Matrix4",
"(",
"(",
"1",
",",
"0",
",",
"0"... | Create a translation matrix. | [
"Create",
"a",
"translation",
"matrix",
"."
] | python | train |
bovee/Aston | aston/peak/peak_fitting.py | https://github.com/bovee/Aston/blob/007630fdf074690373d03398fe818260d3d3cf5a/aston/peak/peak_fitting.py#L46-L85 | def guess_initc(ts, f, rts=[]):
"""
ts - An AstonSeries that's being fitted with peaks
f - The functional form of the peaks (e.g. gaussian)
rts - peak maxima to fit; each number corresponds to one peak
"""
def find_side(y, loc=None):
if loc is None:
loc = y.argmax()
d... | [
"def",
"guess_initc",
"(",
"ts",
",",
"f",
",",
"rts",
"=",
"[",
"]",
")",
":",
"def",
"find_side",
"(",
"y",
",",
"loc",
"=",
"None",
")",
":",
"if",
"loc",
"is",
"None",
":",
"loc",
"=",
"y",
".",
"argmax",
"(",
")",
"ddy",
"=",
"np",
"."... | ts - An AstonSeries that's being fitted with peaks
f - The functional form of the peaks (e.g. gaussian)
rts - peak maxima to fit; each number corresponds to one peak | [
"ts",
"-",
"An",
"AstonSeries",
"that",
"s",
"being",
"fitted",
"with",
"peaks",
"f",
"-",
"The",
"functional",
"form",
"of",
"the",
"peaks",
"(",
"e",
".",
"g",
".",
"gaussian",
")",
"rts",
"-",
"peak",
"maxima",
"to",
"fit",
";",
"each",
"number",
... | python | train |
bitesofcode/projexui | projexui/widgets/xviewwidget/xviewpanel.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewpanel.py#L911-L933 | def closeView(self, view=None):
"""
Closes the inputed view.
:param view | <int> || <XView> || None
"""
if type(view) == int:
view = self.widget(view)
elif view == None:
view = self.currentView()
index = self.indexOf(... | [
"def",
"closeView",
"(",
"self",
",",
"view",
"=",
"None",
")",
":",
"if",
"type",
"(",
"view",
")",
"==",
"int",
":",
"view",
"=",
"self",
".",
"widget",
"(",
"view",
")",
"elif",
"view",
"==",
"None",
":",
"view",
"=",
"self",
".",
"currentView... | Closes the inputed view.
:param view | <int> || <XView> || None | [
"Closes",
"the",
"inputed",
"view",
".",
":",
"param",
"view",
"|",
"<int",
">",
"||",
"<XView",
">",
"||",
"None"
] | python | train |
juju/charm-helpers | charmhelpers/contrib/openstack/amulet/utils.py | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L1122-L1141 | def validate_ceph_pool_samples(self, samples, sample_type="resource pool"):
"""Validate ceph pool samples taken over time, such as pool
object counts or pool kb used, before adding, after adding, and
after deleting items which affect those pool attributes. The
2nd element is expected to... | [
"def",
"validate_ceph_pool_samples",
"(",
"self",
",",
"samples",
",",
"sample_type",
"=",
"\"resource pool\"",
")",
":",
"original",
",",
"created",
",",
"deleted",
"=",
"range",
"(",
"3",
")",
"if",
"samples",
"[",
"created",
"]",
"<=",
"samples",
"[",
"... | Validate ceph pool samples taken over time, such as pool
object counts or pool kb used, before adding, after adding, and
after deleting items which affect those pool attributes. The
2nd element is expected to be greater than the 1st; 3rd is expected
to be less than the 2nd.
:pa... | [
"Validate",
"ceph",
"pool",
"samples",
"taken",
"over",
"time",
"such",
"as",
"pool",
"object",
"counts",
"or",
"pool",
"kb",
"used",
"before",
"adding",
"after",
"adding",
"and",
"after",
"deleting",
"items",
"which",
"affect",
"those",
"pool",
"attributes",
... | python | train |
mathiasertl/django-ca | ca/django_ca/profiles.py | https://github.com/mathiasertl/django-ca/blob/976d7ea05276320f20daed2a6d59c8f5660fe976/ca/django_ca/profiles.py#L25-L49 | def get_cert_profile_kwargs(name=None):
"""Get kwargs suitable for get_cert X509 keyword arguments from the given profile."""
if name is None:
name = ca_settings.CA_DEFAULT_PROFILE
profile = deepcopy(ca_settings.CA_PROFILES[name])
kwargs = {
'cn_in_san': profile['cn_in_san'],
'... | [
"def",
"get_cert_profile_kwargs",
"(",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"ca_settings",
".",
"CA_DEFAULT_PROFILE",
"profile",
"=",
"deepcopy",
"(",
"ca_settings",
".",
"CA_PROFILES",
"[",
"name",
"]",
")",
"kwargs",... | Get kwargs suitable for get_cert X509 keyword arguments from the given profile. | [
"Get",
"kwargs",
"suitable",
"for",
"get_cert",
"X509",
"keyword",
"arguments",
"from",
"the",
"given",
"profile",
"."
] | python | train |
newville/asteval | asteval/asteval.py | https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/asteval.py#L697-L699 | def on_excepthandler(self, node): # ('type', 'name', 'body')
"""Exception handler..."""
return (self.run(node.type), node.name, node.body) | [
"def",
"on_excepthandler",
"(",
"self",
",",
"node",
")",
":",
"# ('type', 'name', 'body')",
"return",
"(",
"self",
".",
"run",
"(",
"node",
".",
"type",
")",
",",
"node",
".",
"name",
",",
"node",
".",
"body",
")"
] | Exception handler... | [
"Exception",
"handler",
"..."
] | python | train |
bcbio/bcbio-nextgen | bcbio/structural/manta.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/manta.py#L19-L51 | def run(items):
"""Perform detection of structural variations with Manta.
"""
paired = vcfutils.get_paired(items)
data = paired.tumor_data if paired else items[0]
work_dir = _sv_workdir(data)
variant_file = _get_out_file(work_dir, paired)
if not utils.file_exists(variant_file):
with ... | [
"def",
"run",
"(",
"items",
")",
":",
"paired",
"=",
"vcfutils",
".",
"get_paired",
"(",
"items",
")",
"data",
"=",
"paired",
".",
"tumor_data",
"if",
"paired",
"else",
"items",
"[",
"0",
"]",
"work_dir",
"=",
"_sv_workdir",
"(",
"data",
")",
"variant_... | Perform detection of structural variations with Manta. | [
"Perform",
"detection",
"of",
"structural",
"variations",
"with",
"Manta",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.