repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
stephantul/somber | somber/plsom.py | https://github.com/stephantul/somber/blob/b7a13e646239500cc393668c01a7169c3e50b7b5/somber/plsom.py#L139-L147 | def _update_params(self, constants):
"""Update the params."""
constants = np.max(np.min(constants, 1))
self.params['r']['value'] = max([self.params['r']['value'],
constants])
epsilon = constants / self.params['r']['value']
influence = self... | [
"def",
"_update_params",
"(",
"self",
",",
"constants",
")",
":",
"constants",
"=",
"np",
".",
"max",
"(",
"np",
".",
"min",
"(",
"constants",
",",
"1",
")",
")",
"self",
".",
"params",
"[",
"'r'",
"]",
"[",
"'value'",
"]",
"=",
"max",
"(",
"[",
... | Update the params. | [
"Update",
"the",
"params",
"."
] | python | train | 45.888889 |
AkihikoITOH/capybara | capybara/virtualenv/lib/python2.7/site-packages/setuptools/command/easy_install.py | https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/setuptools/command/easy_install.py#L769-L781 | def _load_template(dev_path):
"""
There are a couple of template scripts in the package. This
function loads one of them and prepares it for use.
"""
# See https://bitbucket.org/pypa/setuptools/issue/134 for info
# on script file naming and downstream issues with SVR4
... | [
"def",
"_load_template",
"(",
"dev_path",
")",
":",
"# See https://bitbucket.org/pypa/setuptools/issue/134 for info",
"# on script file naming and downstream issues with SVR4",
"name",
"=",
"'script.tmpl'",
"if",
"dev_path",
":",
"name",
"=",
"name",
".",
"replace",
"(",
"'.t... | There are a couple of template scripts in the package. This
function loads one of them and prepares it for use. | [
"There",
"are",
"a",
"couple",
"of",
"template",
"scripts",
"in",
"the",
"package",
".",
"This",
"function",
"loads",
"one",
"of",
"them",
"and",
"prepares",
"it",
"for",
"use",
"."
] | python | test | 39.076923 |
dw/mitogen | ansible_mitogen/runner.py | https://github.com/dw/mitogen/blob/a7fdb55e1300a7e0a5e404b09eb730cf9a525da7/ansible_mitogen/runner.py#L574-L585 | def _setup_program(self):
"""
Create a temporary file containing the program code. The code is
fetched via :meth:`_get_program`.
"""
filename = self._get_program_filename()
path = os.path.join(self.get_temp_dir(), filename)
self.program_fp = open(path, 'wb')
... | [
"def",
"_setup_program",
"(",
"self",
")",
":",
"filename",
"=",
"self",
".",
"_get_program_filename",
"(",
")",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"get_temp_dir",
"(",
")",
",",
"filename",
")",
"self",
".",
"program_fp",
"... | Create a temporary file containing the program code. The code is
fetched via :meth:`_get_program`. | [
"Create",
"a",
"temporary",
"file",
"containing",
"the",
"program",
"code",
".",
"The",
"code",
"is",
"fetched",
"via",
":",
"meth",
":",
"_get_program",
"."
] | python | train | 40.166667 |
dongying/dear | dear/spectrum/_base.py | https://github.com/dongying/dear/blob/6f9a4f63bf3ee197dc03d7d2bd0451a83906d2ba/dear/spectrum/_base.py#L33-L42 | def _read_header(self):
'''
Little-endian
|... 4 bytes unsigned int ...|... 4 bytes unsigned int ...|
| frames count | dimensions count |
'''
self._fh.seek(0)
buf = self._fh.read(4*2)
fc, dc = struct.unpack("<II", buf)
retur... | [
"def",
"_read_header",
"(",
"self",
")",
":",
"self",
".",
"_fh",
".",
"seek",
"(",
"0",
")",
"buf",
"=",
"self",
".",
"_fh",
".",
"read",
"(",
"4",
"*",
"2",
")",
"fc",
",",
"dc",
"=",
"struct",
".",
"unpack",
"(",
"\"<II\"",
",",
"buf",
")"... | Little-endian
|... 4 bytes unsigned int ...|... 4 bytes unsigned int ...|
| frames count | dimensions count | | [
"Little",
"-",
"endian",
"|",
"...",
"4",
"bytes",
"unsigned",
"int",
"...",
"|",
"...",
"4",
"bytes",
"unsigned",
"int",
"...",
"|",
"|",
"frames",
"count",
"|",
"dimensions",
"count",
"|"
] | python | train | 31.9 |
Clarify/clarify_python | clarify_python/clarify.py | https://github.com/Clarify/clarify_python/blob/1a00a5e39f77af9ad7f2e08480a3ab14e7d72aeb/clarify_python/clarify.py#L456-L500 | def create_track(self, href=None, media_url=None, label=None,
audio_channel=None):
"""Add a new track to a bundle. Note that the total number of
allowable tracks is limited. See the API documentation for
details.
'href' the relative href to the tracks list. May not... | [
"def",
"create_track",
"(",
"self",
",",
"href",
"=",
"None",
",",
"media_url",
"=",
"None",
",",
"label",
"=",
"None",
",",
"audio_channel",
"=",
"None",
")",
":",
"# Argument error checking.",
"assert",
"href",
"is",
"not",
"None",
"assert",
"media_url",
... | Add a new track to a bundle. Note that the total number of
allowable tracks is limited. See the API documentation for
details.
'href' the relative href to the tracks list. May not be None.
'media_url' public URL to media file. May not be None.
'label' short name for the track. ... | [
"Add",
"a",
"new",
"track",
"to",
"a",
"bundle",
".",
"Note",
"that",
"the",
"total",
"number",
"of",
"allowable",
"tracks",
"is",
"limited",
".",
"See",
"the",
"API",
"documentation",
"for",
"details",
"."
] | python | train | 34.711111 |
jaraco/path.py | path/__init__.py | https://github.com/jaraco/path.py/blob/bbe7d99e7a64a004f866ace9ec12bd9b296908f5/path/__init__.py#L860-L869 | def _hash(self, hash_name):
""" Returns a hash object for the file at the current path.
`hash_name` should be a hash algo name (such as ``'md5'``
or ``'sha1'``) that's available in the :mod:`hashlib` module.
"""
m = hashlib.new(hash_name)
for chunk in self.chunks(8192, m... | [
"def",
"_hash",
"(",
"self",
",",
"hash_name",
")",
":",
"m",
"=",
"hashlib",
".",
"new",
"(",
"hash_name",
")",
"for",
"chunk",
"in",
"self",
".",
"chunks",
"(",
"8192",
",",
"mode",
"=",
"\"rb\"",
")",
":",
"m",
".",
"update",
"(",
"chunk",
")"... | Returns a hash object for the file at the current path.
`hash_name` should be a hash algo name (such as ``'md5'``
or ``'sha1'``) that's available in the :mod:`hashlib` module. | [
"Returns",
"a",
"hash",
"object",
"for",
"the",
"file",
"at",
"the",
"current",
"path",
"."
] | python | train | 36.6 |
lsst-sqre/lsst-projectmeta-kit | lsstprojectmeta/tex/lsstbib.py | https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/tex/lsstbib.py#L22-L42 | async def _download_text(url, session):
"""Asynchronously request a URL and get the encoded text content of the
body.
Parameters
----------
url : `str`
URL to download.
session : `aiohttp.ClientSession`
An open aiohttp session.
Returns
-------
content : `str`
... | [
"async",
"def",
"_download_text",
"(",
"url",
",",
"session",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"async",
"with",
"session",
".",
"get",
"(",
"url",
")",
"as",
"response",
":",
"# aiohttp decodes the content to a Python... | Asynchronously request a URL and get the encoded text content of the
body.
Parameters
----------
url : `str`
URL to download.
session : `aiohttp.ClientSession`
An open aiohttp session.
Returns
-------
content : `str`
Content downloaded from the URL. | [
"Asynchronously",
"request",
"a",
"URL",
"and",
"get",
"the",
"encoded",
"text",
"content",
"of",
"the",
"body",
"."
] | python | valid | 26.904762 |
apache/incubator-mxnet | python/mxnet/gluon/trainer.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/trainer.py#L159-L167 | def _reset_kvstore(self):
"""Reset kvstore."""
if self._kvstore and 'dist' in self._kvstore.type:
raise RuntimeError("Cannot reset distributed KVStore.")
self._kv_initialized = False
self._kvstore = None
self._distributed = None
self._update_on_kvstore = None
... | [
"def",
"_reset_kvstore",
"(",
"self",
")",
":",
"if",
"self",
".",
"_kvstore",
"and",
"'dist'",
"in",
"self",
".",
"_kvstore",
".",
"type",
":",
"raise",
"RuntimeError",
"(",
"\"Cannot reset distributed KVStore.\"",
")",
"self",
".",
"_kv_initialized",
"=",
"F... | Reset kvstore. | [
"Reset",
"kvstore",
"."
] | python | train | 41.777778 |
apache/incubator-mxnet | tools/coreml/converter/utils.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/tools/coreml/converter/utils.py#L68-L117 | def create_module(sym, data_shapes, label_shapes, label_names, gpus=''):
"""Creates a new MXNet module.
Parameters
----------
sym : Symbol
An MXNet symbol.
input_shape: tuple
The shape of the input data in the form of (batch_size, channels, height, width)
files: list of string... | [
"def",
"create_module",
"(",
"sym",
",",
"data_shapes",
",",
"label_shapes",
",",
"label_names",
",",
"gpus",
"=",
"''",
")",
":",
"if",
"gpus",
"==",
"''",
":",
"devices",
"=",
"mx",
".",
"cpu",
"(",
")",
"else",
":",
"devices",
"=",
"[",
"mx",
".... | Creates a new MXNet module.
Parameters
----------
sym : Symbol
An MXNet symbol.
input_shape: tuple
The shape of the input data in the form of (batch_size, channels, height, width)
files: list of strings
List of URLs pertaining to files that need to be downloaded in order t... | [
"Creates",
"a",
"new",
"MXNet",
"module",
"."
] | python | train | 26.72 |
binux/pyspider | pyspider/run.py | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/run.py#L237-L269 | def fetcher(ctx, xmlrpc, xmlrpc_host, xmlrpc_port, poolsize, proxy, user_agent,
timeout, phantomjs_endpoint, puppeteer_endpoint, splash_endpoint, fetcher_cls,
async_mode=True, get_object=False, no_input=False):
"""
Run Fetcher.
"""
g = ctx.obj
Fetcher = load_cls(None, None, f... | [
"def",
"fetcher",
"(",
"ctx",
",",
"xmlrpc",
",",
"xmlrpc_host",
",",
"xmlrpc_port",
",",
"poolsize",
",",
"proxy",
",",
"user_agent",
",",
"timeout",
",",
"phantomjs_endpoint",
",",
"puppeteer_endpoint",
",",
"splash_endpoint",
",",
"fetcher_cls",
",",
"async_m... | Run Fetcher. | [
"Run",
"Fetcher",
"."
] | python | train | 36.090909 |
adafruit/Adafruit_Python_PlatformDetect | adafruit_platformdetect/board.py | https://github.com/adafruit/Adafruit_Python_PlatformDetect/blob/cddd4d47e530026778dc4e3c3ccabad14e6eac46/adafruit_platformdetect/board.py#L379-L382 | def any_embedded_linux(self):
"""Check whether the current board is any embedded Linux device."""
return self.any_raspberry_pi or self.any_beaglebone or \
self.any_orange_pi or self.any_giant_board or self.any_jetson_board | [
"def",
"any_embedded_linux",
"(",
"self",
")",
":",
"return",
"self",
".",
"any_raspberry_pi",
"or",
"self",
".",
"any_beaglebone",
"or",
"self",
".",
"any_orange_pi",
"or",
"self",
".",
"any_giant_board",
"or",
"self",
".",
"any_jetson_board"
] | Check whether the current board is any embedded Linux device. | [
"Check",
"whether",
"the",
"current",
"board",
"is",
"any",
"embedded",
"Linux",
"device",
"."
] | python | train | 61 |
blazelibs/blazeutils | blazeutils/importing.py | https://github.com/blazelibs/blazeutils/blob/c94476325146007553cbddeeb9ef83394756babf/blazeutils/importing.py#L12-L45 | def prependsitedir(projdir, *args):
"""
like sys.addsitedir() but gives the added directory preference
over system directories. The paths will be normalized for dots and
slash direction before being added to the path.
projdir: the path you want to add to sys.path. If its a
... | [
"def",
"prependsitedir",
"(",
"projdir",
",",
"*",
"args",
")",
":",
"# let the user be lazy and send a file, we will convert to parent directory",
"# of file",
"if",
"path",
".",
"isfile",
"(",
"projdir",
")",
":",
"projdir",
"=",
"path",
".",
"dirname",
"(",
"proj... | like sys.addsitedir() but gives the added directory preference
over system directories. The paths will be normalized for dots and
slash direction before being added to the path.
projdir: the path you want to add to sys.path. If its a
a file, the parent directory will be added
... | [
"like",
"sys",
".",
"addsitedir",
"()",
"but",
"gives",
"the",
"added",
"directory",
"preference",
"over",
"system",
"directories",
".",
"The",
"paths",
"will",
"be",
"normalized",
"for",
"dots",
"and",
"slash",
"direction",
"before",
"being",
"added",
"to",
... | python | train | 35.676471 |
scott-griffiths/bitstring | bitstring.py | https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2704-L2717 | def endswith(self, suffix, start=None, end=None):
"""Return whether the current bitstring ends with suffix.
suffix -- The bitstring to search for.
start -- The bit position to start from. Defaults to 0.
end -- The bit position to end at. Defaults to self.len.
"""
suffix... | [
"def",
"endswith",
"(",
"self",
",",
"suffix",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"suffix",
"=",
"Bits",
"(",
"suffix",
")",
"start",
",",
"end",
"=",
"self",
".",
"_validate_slice",
"(",
"start",
",",
"end",
")",
"if",
... | Return whether the current bitstring ends with suffix.
suffix -- The bitstring to search for.
start -- The bit position to start from. Defaults to 0.
end -- The bit position to end at. Defaults to self.len. | [
"Return",
"whether",
"the",
"current",
"bitstring",
"ends",
"with",
"suffix",
"."
] | python | train | 37.142857 |
chaoss/grimoirelab-manuscripts | manuscripts/esquery.py | https://github.com/chaoss/grimoirelab-manuscripts/blob/94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9/manuscripts/esquery.py#L41-L68 | def __get_query_filters(cls, filters={}, inverse=False):
"""
Convert a dict with the filters to be applied ({"name1":"value1", "name2":"value2"})
to a list of query objects which can be used together in a query using boolean
combination logic.
:param filters: dict with the filte... | [
"def",
"__get_query_filters",
"(",
"cls",
",",
"filters",
"=",
"{",
"}",
",",
"inverse",
"=",
"False",
")",
":",
"query_filters",
"=",
"[",
"]",
"for",
"name",
"in",
"filters",
":",
"if",
"name",
"[",
"0",
"]",
"==",
"'*'",
"and",
"not",
"inverse",
... | Convert a dict with the filters to be applied ({"name1":"value1", "name2":"value2"})
to a list of query objects which can be used together in a query using boolean
combination logic.
:param filters: dict with the filters to be applied
:param inverse: if True include all the inverse filt... | [
"Convert",
"a",
"dict",
"with",
"the",
"filters",
"to",
"be",
"applied",
"(",
"{",
"name1",
":",
"value1",
"name2",
":",
"value2",
"}",
")",
"to",
"a",
"list",
"of",
"query",
"objects",
"which",
"can",
"be",
"used",
"together",
"in",
"a",
"query",
"u... | python | train | 43.928571 |
realitix/vulkan | generator/generate.py | https://github.com/realitix/vulkan/blob/07285387092aaa61d2d71fa2913d60a73f022cbe/generator/generate.py#L534-L554 | def generate_cdef():
"""Generate the cdef output file"""
include_libc_path = path.join(HERE, 'fake_libc_include')
include_vulkan_path = path.join(HERE, 'vulkan_include')
out_file = path.join(HERE, path.pardir, 'vulkan', 'vulkan.cdef.h')
header = path.join(include_vulkan_path, 'vulkan.h')
comman... | [
"def",
"generate_cdef",
"(",
")",
":",
"include_libc_path",
"=",
"path",
".",
"join",
"(",
"HERE",
",",
"'fake_libc_include'",
")",
"include_vulkan_path",
"=",
"path",
".",
"join",
"(",
"HERE",
",",
"'vulkan_include'",
")",
"out_file",
"=",
"path",
".",
"joi... | Generate the cdef output file | [
"Generate",
"the",
"cdef",
"output",
"file"
] | python | train | 37.952381 |
lingthio/Flask-User | flask_user/email_adapters/sendmail_email_adapter.py | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/email_adapters/sendmail_email_adapter.py#L34-L55 | def send_email_message(self, recipient, subject, html_message, text_message, sender_email, sender_name):
""" Send email message via Flask-Sendmail.
Args:
recipient: Email address or tuple of (Name, Email-address).
subject: Subject line.
html_message: The message body... | [
"def",
"send_email_message",
"(",
"self",
",",
"recipient",
",",
"subject",
",",
"html_message",
",",
"text_message",
",",
"sender_email",
",",
"sender_name",
")",
":",
"if",
"not",
"current_app",
".",
"testing",
":",
"# pragma: no cover",
"# Prepare email message",... | Send email message via Flask-Sendmail.
Args:
recipient: Email address or tuple of (Name, Email-address).
subject: Subject line.
html_message: The message body in HTML.
text_message: The message body in plain text. | [
"Send",
"email",
"message",
"via",
"Flask",
"-",
"Sendmail",
"."
] | python | train | 34.318182 |
ktdreyer/txkoji | txkoji/task.py | https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/task.py#L169-L194 | def estimate_duration(self):
"""
Estimate duration (timedelta) for this task.
Estimate the average length of time we expect between this task's
start and end times.
:returns: deferred that when fired returns a timedelta object for the
estimated timedelta, or t... | [
"def",
"estimate_duration",
"(",
"self",
")",
":",
"if",
"self",
".",
"completion_ts",
":",
"# Task is already complete. Return the exact duration timedelta.",
"return",
"defer",
".",
"succeed",
"(",
"self",
".",
"duration",
")",
"if",
"not",
"self",
".",
"package",... | Estimate duration (timedelta) for this task.
Estimate the average length of time we expect between this task's
start and end times.
:returns: deferred that when fired returns a timedelta object for the
estimated timedelta, or the actual timedelta, or None if we
... | [
"Estimate",
"duration",
"(",
"timedelta",
")",
"for",
"this",
"task",
"."
] | python | train | 47.076923 |
roclark/sportsreference | sportsreference/ncaab/roster.py | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/ncaab/roster.py#L278-L300 | def _parse_conference(self, stats):
"""
Parse the conference abbreviation for the player's team.
The conference abbreviation is embedded within the conference name tag
and should be special-parsed to extract it.
Parameters
----------
stats : PyQuery object
... | [
"def",
"_parse_conference",
"(",
"self",
",",
"stats",
")",
":",
"conference_tag",
"=",
"stats",
"(",
"PLAYER_SCHEME",
"[",
"'conference'",
"]",
")",
"conference",
"=",
"re",
".",
"sub",
"(",
"r'.*/cbb/conferences/'",
",",
"''",
",",
"str",
"(",
"conference_... | Parse the conference abbreviation for the player's team.
The conference abbreviation is embedded within the conference name tag
and should be special-parsed to extract it.
Parameters
----------
stats : PyQuery object
A PyQuery object containing the HTML from the pla... | [
"Parse",
"the",
"conference",
"abbreviation",
"for",
"the",
"player",
"s",
"team",
"."
] | python | train | 34.173913 |
rameshg87/pyremotevbox | pyremotevbox/ZSI/address.py | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/address.py#L221-L229 | def serialize(self, sw, **kw):
'''
sw -- SoapWriter instance, add WS-Address header.
'''
for pyobj in self.header_pyobjs:
if hasattr(pyobj, 'typecode') is False:
raise RuntimeError, 'all header pyobjs must have a typecode attribute'
sw.serialize_h... | [
"def",
"serialize",
"(",
"self",
",",
"sw",
",",
"*",
"*",
"kw",
")",
":",
"for",
"pyobj",
"in",
"self",
".",
"header_pyobjs",
":",
"if",
"hasattr",
"(",
"pyobj",
",",
"'typecode'",
")",
"is",
"False",
":",
"raise",
"RuntimeError",
",",
"'all header py... | sw -- SoapWriter instance, add WS-Address header. | [
"sw",
"--",
"SoapWriter",
"instance",
"add",
"WS",
"-",
"Address",
"header",
"."
] | python | train | 36.666667 |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py#L7865-L7875 | def flexifunction_read_req_encode(self, target_system, target_component, read_req_type, data_index):
'''
Reqest reading of flexifunction data
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
... | [
"def",
"flexifunction_read_req_encode",
"(",
"self",
",",
"target_system",
",",
"target_component",
",",
"read_req_type",
",",
"data_index",
")",
":",
"return",
"MAVLink_flexifunction_read_req_message",
"(",
"target_system",
",",
"target_component",
",",
"read_req_type",
... | Reqest reading of flexifunction data
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
read_req_type : Type of flexifunction data requested (int16_t)
data_index : index into data ... | [
"Reqest",
"reading",
"of",
"flexifunction",
"data"
] | python | train | 55.636364 |
ismms-himc/clustergrammer2 | clustergrammer2/clustergrammer_fun/__init__.py | https://github.com/ismms-himc/clustergrammer2/blob/5acea9bff7eda546cf0647b9e3647f631eb6f5f5/clustergrammer2/clustergrammer_fun/__init__.py#L453-L551 | def load_gene_exp_to_df(inst_path):
'''
Loads gene expression data from 10x in sparse matrix format and returns a
Pandas dataframe
'''
import pandas as pd
from scipy import io
from scipy import sparse
from ast import literal_eval as make_tuple
# matrix
Matrix = io.mmread( inst_... | [
"def",
"load_gene_exp_to_df",
"(",
"inst_path",
")",
":",
"import",
"pandas",
"as",
"pd",
"from",
"scipy",
"import",
"io",
"from",
"scipy",
"import",
"sparse",
"from",
"ast",
"import",
"literal_eval",
"as",
"make_tuple",
"# matrix",
"Matrix",
"=",
"io",
".",
... | Loads gene expression data from 10x in sparse matrix format and returns a
Pandas dataframe | [
"Loads",
"gene",
"expression",
"data",
"from",
"10x",
"in",
"sparse",
"matrix",
"format",
"and",
"returns",
"a",
"Pandas",
"dataframe"
] | python | train | 23.545455 |
pavelsof/ipatok | ipatok/ipa.py | https://github.com/pavelsof/ipatok/blob/fde3c334b8573315fd1073f14341b71f50f7f006/ipatok/ipa.py#L175-L190 | def is_tone(char, strict=True):
"""
Check whether the character is a tone or word accent symbol. In strict mode
return True only for the symbols listed in the last group of the chart. If
strict=False, also accept symbols that belong to the Modifier Tone Letters
Unicode block [1].
[1]: http://www.unicode.org/char... | [
"def",
"is_tone",
"(",
"char",
",",
"strict",
"=",
"True",
")",
":",
"if",
"char",
"in",
"chart",
".",
"tones",
":",
"return",
"True",
"if",
"not",
"strict",
":",
"return",
"0xA700",
"<=",
"ord",
"(",
"char",
")",
"<=",
"0xA71F",
"return",
"False"
] | Check whether the character is a tone or word accent symbol. In strict mode
return True only for the symbols listed in the last group of the chart. If
strict=False, also accept symbols that belong to the Modifier Tone Letters
Unicode block [1].
[1]: http://www.unicode.org/charts/PDF/UA700.pdf | [
"Check",
"whether",
"the",
"character",
"is",
"a",
"tone",
"or",
"word",
"accent",
"symbol",
".",
"In",
"strict",
"mode",
"return",
"True",
"only",
"for",
"the",
"symbols",
"listed",
"in",
"the",
"last",
"group",
"of",
"the",
"chart",
".",
"If",
"strict"... | python | train | 27.25 |
GNS3/gns3-server | gns3server/compute/dynamips/nios/nio.py | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nios/nio.py#L72-L82 | def rename(self, new_name):
"""
Renames this NIO
:param new_name: new NIO name
"""
yield from self._hypervisor.send("nio rename {name} {new_name}".format(name=self._name, new_name=new_name))
log.info("NIO {name} renamed to {new_name}".format(name=self._name, new_name=n... | [
"def",
"rename",
"(",
"self",
",",
"new_name",
")",
":",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"send",
"(",
"\"nio rename {name} {new_name}\"",
".",
"format",
"(",
"name",
"=",
"self",
".",
"_name",
",",
"new_name",
"=",
"new_name",
")",
")",
... | Renames this NIO
:param new_name: new NIO name | [
"Renames",
"this",
"NIO"
] | python | train | 31.727273 |
wbond/pybars3 | pybars/_compiler.py | https://github.com/wbond/pybars3/blob/71f13d1012d3746e76099d8db141c43fc769cfed/pybars/_compiler.py#L779-L797 | def _extract_word(self, source, position):
"""
Extracts the word that falls at or around a specific position
:param source:
The template source as a unicode string
:param position:
The position where the word falls
:return:
The word
"... | [
"def",
"_extract_word",
"(",
"self",
",",
"source",
",",
"position",
")",
":",
"boundry",
"=",
"re",
".",
"search",
"(",
"'{{|{|\\s|$'",
",",
"source",
"[",
":",
"position",
"]",
"[",
":",
":",
"-",
"1",
"]",
")",
"start_offset",
"=",
"boundry",
".",... | Extracts the word that falls at or around a specific position
:param source:
The template source as a unicode string
:param position:
The position where the word falls
:return:
The word | [
"Extracts",
"the",
"word",
"that",
"falls",
"at",
"or",
"around",
"a",
"specific",
"position"
] | python | train | 36.157895 |
Shapeways/coyote_framework | coyote_framework/drivers/coyote_driver.py | https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/drivers/coyote_driver.py#L8-L16 | def visit(self, url=''):
"""Visit the url, checking for rr errors in the response
@param url: URL
@return: Visit result
"""
result = super(CoyoteDriver, self).visit(url)
source = self.page_source()
return result | [
"def",
"visit",
"(",
"self",
",",
"url",
"=",
"''",
")",
":",
"result",
"=",
"super",
"(",
"CoyoteDriver",
",",
"self",
")",
".",
"visit",
"(",
"url",
")",
"source",
"=",
"self",
".",
"page_source",
"(",
")",
"return",
"result"
] | Visit the url, checking for rr errors in the response
@param url: URL
@return: Visit result | [
"Visit",
"the",
"url",
"checking",
"for",
"rr",
"errors",
"in",
"the",
"response"
] | python | train | 28.888889 |
markomanninen/abnum | abnum/search.py | https://github.com/markomanninen/abnum/blob/9bfc8f06f34d9a51aab038638f87e2bb5f9f4c99/abnum/search.py#L5-L22 | def find_cumulative_indices(list_of_numbers, search_sum):
"""
find_cumulative_indices([70, 58, 81, 909, 70, 215, 70, 1022, 580, 930, 898], 285) ->
[[4, 5],[5, 6]]
"""
u = 0
y = 0
result = []
for idx, val in enumerate(list_of_numbers):
y += list_of_numbers[idx]
while y >=... | [
"def",
"find_cumulative_indices",
"(",
"list_of_numbers",
",",
"search_sum",
")",
":",
"u",
"=",
"0",
"y",
"=",
"0",
"result",
"=",
"[",
"]",
"for",
"idx",
",",
"val",
"in",
"enumerate",
"(",
"list_of_numbers",
")",
":",
"y",
"+=",
"list_of_numbers",
"["... | find_cumulative_indices([70, 58, 81, 909, 70, 215, 70, 1022, 580, 930, 898], 285) ->
[[4, 5],[5, 6]] | [
"find_cumulative_indices",
"(",
"[",
"70",
"58",
"81",
"909",
"70",
"215",
"70",
"1022",
"580",
"930",
"898",
"]",
"285",
")",
"-",
">",
"[[",
"4",
"5",
"]",
"[",
"5",
"6",
"]]"
] | python | train | 32.555556 |
google/grr | grr/client_builder/grr_response_client_builder/build.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/client_builder/grr_response_client_builder/build.py#L552-L648 | def MakeSelfExtractingZip(self, payload_data, output_path):
"""Repack the installer into the payload.
Args:
payload_data: data payload for zip file
output_path: filename for the zip output
Raises:
RuntimeError: if the ClientBuilder.unzipsfx_stub doesn't require admin.
Returns:
... | [
"def",
"MakeSelfExtractingZip",
"(",
"self",
",",
"payload_data",
",",
"output_path",
")",
":",
"context",
"=",
"self",
".",
"context",
"+",
"[",
"\"Client Context\"",
"]",
"src_zip",
"=",
"zipfile",
".",
"ZipFile",
"(",
"io",
".",
"BytesIO",
"(",
"payload_d... | Repack the installer into the payload.
Args:
payload_data: data payload for zip file
output_path: filename for the zip output
Raises:
RuntimeError: if the ClientBuilder.unzipsfx_stub doesn't require admin.
Returns:
output_path: filename string of zip output file | [
"Repack",
"the",
"installer",
"into",
"the",
"payload",
"."
] | python | train | 38.505155 |
scikit-learn-contrib/categorical-encoding | category_encoders/utils.py | https://github.com/scikit-learn-contrib/categorical-encoding/blob/5e9e803c9131b377af305d5302723ba2415001da/category_encoders/utils.py#L27-L36 | def get_obj_cols(df):
"""
Returns names of 'object' columns in the DataFrame.
"""
obj_cols = []
for idx, dt in enumerate(df.dtypes):
if dt == 'object' or is_category(dt):
obj_cols.append(df.columns.values[idx])
return obj_cols | [
"def",
"get_obj_cols",
"(",
"df",
")",
":",
"obj_cols",
"=",
"[",
"]",
"for",
"idx",
",",
"dt",
"in",
"enumerate",
"(",
"df",
".",
"dtypes",
")",
":",
"if",
"dt",
"==",
"'object'",
"or",
"is_category",
"(",
"dt",
")",
":",
"obj_cols",
".",
"append"... | Returns names of 'object' columns in the DataFrame. | [
"Returns",
"names",
"of",
"object",
"columns",
"in",
"the",
"DataFrame",
"."
] | python | valid | 26.2 |
pandas-dev/pandas | pandas/tseries/offsets.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/tseries/offsets.py#L342-L349 | def rollforward(self, dt):
"""
Roll provided date forward to next offset only if not on offset.
"""
dt = as_timestamp(dt)
if not self.onOffset(dt):
dt = dt + self.__class__(1, normalize=self.normalize, **self.kwds)
return dt | [
"def",
"rollforward",
"(",
"self",
",",
"dt",
")",
":",
"dt",
"=",
"as_timestamp",
"(",
"dt",
")",
"if",
"not",
"self",
".",
"onOffset",
"(",
"dt",
")",
":",
"dt",
"=",
"dt",
"+",
"self",
".",
"__class__",
"(",
"1",
",",
"normalize",
"=",
"self",... | Roll provided date forward to next offset only if not on offset. | [
"Roll",
"provided",
"date",
"forward",
"to",
"next",
"offset",
"only",
"if",
"not",
"on",
"offset",
"."
] | python | train | 34.625 |
ddorn/GUI | GUI/text.py | https://github.com/ddorn/GUI/blob/e1fcb5286d24e0995f280d5180222e51895c368c/GUI/text.py#L97-L109 | def _render(self):
"""
Render the text.
Avoid using this fonction too many time as it is slow as it is low to render text and blit it.
"""
self._last_text = self.text
self._surface = self.font.render(self.text, True, self.color, self.bg_color)
rect = self._surf... | [
"def",
"_render",
"(",
"self",
")",
":",
"self",
".",
"_last_text",
"=",
"self",
".",
"text",
"self",
".",
"_surface",
"=",
"self",
".",
"font",
".",
"render",
"(",
"self",
".",
"text",
",",
"True",
",",
"self",
".",
"color",
",",
"self",
".",
"b... | Render the text.
Avoid using this fonction too many time as it is slow as it is low to render text and blit it. | [
"Render",
"the",
"text",
"."
] | python | train | 27.153846 |
broadinstitute/fiss | firecloud/fiss.py | https://github.com/broadinstitute/fiss/blob/dddf91547479506dbbafb69ec84d44dcc4a94ab4/firecloud/fiss.py#L641-L648 | def config_get(args):
""" Retrieve a method config from a workspace, send stdout """
r = fapi.get_workspace_config(args.project, args.workspace,
args.namespace, args.config)
fapi._check_response_code(r, 200)
# Setting ensure_ascii to False ensures unicode string r... | [
"def",
"config_get",
"(",
"args",
")",
":",
"r",
"=",
"fapi",
".",
"get_workspace_config",
"(",
"args",
".",
"project",
",",
"args",
".",
"workspace",
",",
"args",
".",
"namespace",
",",
"args",
".",
"config",
")",
"fapi",
".",
"_check_response_code",
"(... | Retrieve a method config from a workspace, send stdout | [
"Retrieve",
"a",
"method",
"config",
"from",
"a",
"workspace",
"send",
"stdout"
] | python | train | 55.375 |
Yelp/venv-update | pip_faster.py | https://github.com/Yelp/venv-update/blob/6feae7ab09ee870c582b97443cfa8f0dc8626ba7/pip_faster.py#L312-L359 | def trace_requirements(requirements):
"""given an iterable of pip InstallRequirements,
return the set of required packages, given their transitive requirements.
"""
requirements = tuple(pretty_req(r) for r in requirements)
working_set = fresh_working_set()
# breadth-first traversal:
from co... | [
"def",
"trace_requirements",
"(",
"requirements",
")",
":",
"requirements",
"=",
"tuple",
"(",
"pretty_req",
"(",
"r",
")",
"for",
"r",
"in",
"requirements",
")",
"working_set",
"=",
"fresh_working_set",
"(",
")",
"# breadth-first traversal:",
"from",
"collections... | given an iterable of pip InstallRequirements,
return the set of required packages, given their transitive requirements. | [
"given",
"an",
"iterable",
"of",
"pip",
"InstallRequirements",
"return",
"the",
"set",
"of",
"required",
"packages",
"given",
"their",
"transitive",
"requirements",
"."
] | python | train | 36.541667 |
bodylabs/lace | lace/topology.py | https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/topology.py#L110-L124 | def keep_segments(self, segments_to_keep, preserve_segmentation=True):
'''
Keep the faces and vertices for given segments, discarding all others.
When preserve_segmentation is false self.segm is discarded for speed.
'''
v_ind, f_ind = self.vertex_indices_in_segments(segments_to_k... | [
"def",
"keep_segments",
"(",
"self",
",",
"segments_to_keep",
",",
"preserve_segmentation",
"=",
"True",
")",
":",
"v_ind",
",",
"f_ind",
"=",
"self",
".",
"vertex_indices_in_segments",
"(",
"segments_to_keep",
",",
"ret_face_indices",
"=",
"True",
")",
"self",
... | Keep the faces and vertices for given segments, discarding all others.
When preserve_segmentation is false self.segm is discarded for speed. | [
"Keep",
"the",
"faces",
"and",
"vertices",
"for",
"given",
"segments",
"discarding",
"all",
"others",
".",
"When",
"preserve_segmentation",
"is",
"false",
"self",
".",
"segm",
"is",
"discarded",
"for",
"speed",
"."
] | python | train | 41.4 |
pybel/pybel | src/pybel/io/extras.py | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/io/extras.py#L24-L43 | def to_graphml(graph: BELGraph, path: Union[str, BinaryIO]) -> None:
"""Write this graph to GraphML XML file using :func:`networkx.write_graphml`.
The .graphml file extension is suggested so Cytoscape can recognize it.
"""
rv = nx.MultiDiGraph()
for node in graph:
rv.add_node(node.as_bel()... | [
"def",
"to_graphml",
"(",
"graph",
":",
"BELGraph",
",",
"path",
":",
"Union",
"[",
"str",
",",
"BinaryIO",
"]",
")",
"->",
"None",
":",
"rv",
"=",
"nx",
".",
"MultiDiGraph",
"(",
")",
"for",
"node",
"in",
"graph",
":",
"rv",
".",
"add_node",
"(",
... | Write this graph to GraphML XML file using :func:`networkx.write_graphml`.
The .graphml file extension is suggested so Cytoscape can recognize it. | [
"Write",
"this",
"graph",
"to",
"GraphML",
"XML",
"file",
"using",
":",
"func",
":",
"networkx",
".",
"write_graphml",
"."
] | python | train | 31.15 |
openstack/proliantutils | proliantutils/ilo/client.py | https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/ilo/client.py#L438-L445 | def set_vm_status(self, device='FLOPPY',
boot_option='BOOT_ONCE', write_protect='YES'):
"""Sets the Virtual Media drive status and allows the
boot options for booting from the virtual media.
"""
return self._call_method('set_vm_status', device, boot_option,
... | [
"def",
"set_vm_status",
"(",
"self",
",",
"device",
"=",
"'FLOPPY'",
",",
"boot_option",
"=",
"'BOOT_ONCE'",
",",
"write_protect",
"=",
"'YES'",
")",
":",
"return",
"self",
".",
"_call_method",
"(",
"'set_vm_status'",
",",
"device",
",",
"boot_option",
",",
... | Sets the Virtual Media drive status and allows the
boot options for booting from the virtual media. | [
"Sets",
"the",
"Virtual",
"Media",
"drive",
"status",
"and",
"allows",
"the"
] | python | train | 44.125 |
manahl/arctic | arctic/store/bson_store.py | https://github.com/manahl/arctic/blob/57e110b6e182dbab00e7e214dc26f7d9ec47c120/arctic/store/bson_store.py#L158-L166 | def bulk_write(self, requests, **kwargs):
"""
See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.bulk_write
Warning: this is wrapped in mongo_retry, and is therefore potentially unsafe if the write you want to execute
isn't idempotent.
... | [
"def",
"bulk_write",
"(",
"self",
",",
"requests",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_arctic_lib",
".",
"check_quota",
"(",
")",
"return",
"self",
".",
"_collection",
".",
"bulk_write",
"(",
"requests",
",",
"*",
"*",
"kwargs",
")"
] | See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.bulk_write
Warning: this is wrapped in mongo_retry, and is therefore potentially unsafe if the write you want to execute
isn't idempotent. | [
"See",
"http",
":",
"//",
"api",
".",
"mongodb",
".",
"com",
"/",
"python",
"/",
"current",
"/",
"api",
"/",
"pymongo",
"/",
"collection",
".",
"html#pymongo",
".",
"collection",
".",
"Collection",
".",
"bulk_write"
] | python | train | 47 |
funilrys/PyFunceble | PyFunceble/logs.py | https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/logs.py#L118-L153 | def whois(self, record):
"""
Logs the WHOIS record if needed.
:param record: The record to log.
:type record: str
"""
if PyFunceble.CONFIGURATION["debug"] and PyFunceble.CONFIGURATION["logs"]:
# The debug and the logs subsystem are activated.
if... | [
"def",
"whois",
"(",
"self",
",",
"record",
")",
":",
"if",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"debug\"",
"]",
"and",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"logs\"",
"]",
":",
"# The debug and the logs subsystem are activated.",
"if",
"PyFunceble",
".... | Logs the WHOIS record if needed.
:param record: The record to log.
:type record: str | [
"Logs",
"the",
"WHOIS",
"record",
"if",
"needed",
"."
] | python | test | 32.416667 |
spaam/swedbank-cli | pyswedbank/wrapper.py | https://github.com/spaam/swedbank-cli/blob/a33702d5a7de424f1f93137dc5be65d2eedbf824/pyswedbank/wrapper.py#L83-L115 | def request(self, url, post=None, method="GET"):
""" Make the request"""
dsid = self.get_dsid()
baseurl = "https://auth.api.swedbank.se/TDE_DAP_Portal_REST_WEB/api/v1/%s?dsid=%s" % (
url, dsid)
if self.pch is None:
self.pch = build_opener(HTTPCookieProcessor(self... | [
"def",
"request",
"(",
"self",
",",
"url",
",",
"post",
"=",
"None",
",",
"method",
"=",
"\"GET\"",
")",
":",
"dsid",
"=",
"self",
".",
"get_dsid",
"(",
")",
"baseurl",
"=",
"\"https://auth.api.swedbank.se/TDE_DAP_Portal_REST_WEB/api/v1/%s?dsid=%s\"",
"%",
"(",
... | Make the request | [
"Make",
"the",
"request"
] | python | train | 44.575758 |
rigetti/quantumflow | quantumflow/forest/__init__.py | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/forest/__init__.py#L160-L168 | def pyquil_to_image(program: pyquil.Program) -> PIL.Image: # pragma: no cover
"""Returns an image of a pyquil circuit.
See circuit_to_latex() for more details.
"""
circ = pyquil_to_circuit(program)
latex = circuit_to_latex(circ)
img = render_latex(latex)
return img | [
"def",
"pyquil_to_image",
"(",
"program",
":",
"pyquil",
".",
"Program",
")",
"->",
"PIL",
".",
"Image",
":",
"# pragma: no cover",
"circ",
"=",
"pyquil_to_circuit",
"(",
"program",
")",
"latex",
"=",
"circuit_to_latex",
"(",
"circ",
")",
"img",
"=",
"render... | Returns an image of a pyquil circuit.
See circuit_to_latex() for more details. | [
"Returns",
"an",
"image",
"of",
"a",
"pyquil",
"circuit",
"."
] | python | train | 31.888889 |
saltstack/salt | salt/modules/alternatives.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/alternatives.py#L125-L143 | def check_exists(name, path):
'''
Check if the given path is an alternative for a name.
.. versionadded:: 2015.8.4
CLI Example:
.. code-block:: bash
salt '*' alternatives.check_exists name path
'''
cmd = [_get_cmd(), '--display', name]
out = __salt__['cmd.run_all'](cmd, pytho... | [
"def",
"check_exists",
"(",
"name",
",",
"path",
")",
":",
"cmd",
"=",
"[",
"_get_cmd",
"(",
")",
",",
"'--display'",
",",
"name",
"]",
"out",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"cmd",
",",
"python_shell",
"=",
"False",
")",
"if",
"out"... | Check if the given path is an alternative for a name.
.. versionadded:: 2015.8.4
CLI Example:
.. code-block:: bash
salt '*' alternatives.check_exists name path | [
"Check",
"if",
"the",
"given",
"path",
"is",
"an",
"alternative",
"for",
"a",
"name",
"."
] | python | train | 24.684211 |
InspectorMustache/base16-builder-python | pybase16_builder/builder.py | https://github.com/InspectorMustache/base16-builder-python/blob/586f1f87ee9f70696ab19c542af6ef55c6548a2e/pybase16_builder/builder.py#L18-L31 | def get_templates(self):
"""
Return a list of template_dicts based on the config.yaml in
$self.base_path. Keys correspond to templates and values represent
further settings regarding each template. A pystache object containing
the parsed corresponding mustache file is added to th... | [
"def",
"get_templates",
"(",
"self",
")",
":",
"config_path",
"=",
"rel_to_cwd",
"(",
"self",
".",
"base_path",
",",
"'templates'",
",",
"'config.yaml'",
")",
"templates",
"=",
"get_yaml_dict",
"(",
"config_path",
")",
"for",
"temp",
",",
"sub",
"in",
"templ... | Return a list of template_dicts based on the config.yaml in
$self.base_path. Keys correspond to templates and values represent
further settings regarding each template. A pystache object containing
the parsed corresponding mustache file is added to the sub-dictionary. | [
"Return",
"a",
"list",
"of",
"template_dicts",
"based",
"on",
"the",
"config",
".",
"yaml",
"in",
"$self",
".",
"base_path",
".",
"Keys",
"correspond",
"to",
"templates",
"and",
"values",
"represent",
"further",
"settings",
"regarding",
"each",
"template",
"."... | python | train | 52.214286 |
google/pyringe | pyringe/payload/libpython.py | https://github.com/google/pyringe/blob/76dff5d1ac29cd5e7bf32677654a83291a15ad8a/pyringe/payload/libpython.py#L1173-L1183 | def select(self):
'''If supported, select this frame and return True; return False if unsupported
Not all builds have a gdb.Frame.select method; seems to be present on Fedora 12
onwards, but absent on Ubuntu buildbot'''
if not hasattr(self._gdbframe, 'select'):
print ('Unabl... | [
"def",
"select",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
".",
"_gdbframe",
",",
"'select'",
")",
":",
"print",
"(",
"'Unable to select frame: '",
"'this build of gdb does not expose a gdb.Frame.select method'",
")",
"return",
"False",
"self",
"."... | If supported, select this frame and return True; return False if unsupported
Not all builds have a gdb.Frame.select method; seems to be present on Fedora 12
onwards, but absent on Ubuntu buildbot | [
"If",
"supported",
"select",
"this",
"frame",
"and",
"return",
"True",
";",
"return",
"False",
"if",
"unsupported"
] | python | train | 44.454545 |
apache/airflow | airflow/contrib/hooks/sagemaker_hook.py | https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/sagemaker_hook.py#L519-L572 | def describe_training_job_with_log(self, job_name, positions, stream_names,
instance_count, state, last_description,
last_describe_job_call):
"""
Return the training job info associated with job_name and print CloudWatch logs
... | [
"def",
"describe_training_job_with_log",
"(",
"self",
",",
"job_name",
",",
"positions",
",",
"stream_names",
",",
"instance_count",
",",
"state",
",",
"last_description",
",",
"last_describe_job_call",
")",
":",
"log_group",
"=",
"'/aws/sagemaker/TrainingJobs'",
"if",
... | Return the training job info associated with job_name and print CloudWatch logs | [
"Return",
"the",
"training",
"job",
"info",
"associated",
"with",
"job_name",
"and",
"print",
"CloudWatch",
"logs"
] | python | test | 49.314815 |
saltstack/salt | salt/client/ssh/wrapper/state.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/wrapper/state.py#L180-L267 | def sls(mods, saltenv='base', test=None, exclude=None, **kwargs):
'''
Create the seed file for a state.sls run
'''
st_kwargs = __salt__.kwargs
__opts__['grains'] = __grains__
__pillar__.update(kwargs.get('pillar', {}))
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
st_ = salt.c... | [
"def",
"sls",
"(",
"mods",
",",
"saltenv",
"=",
"'base'",
",",
"test",
"=",
"None",
",",
"exclude",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"st_kwargs",
"=",
"__salt__",
".",
"kwargs",
"__opts__",
"[",
"'grains'",
"]",
"=",
"__grains__",
"__p... | Create the seed file for a state.sls run | [
"Create",
"the",
"seed",
"file",
"for",
"a",
"state",
".",
"sls",
"run"
] | python | train | 33.568182 |
pyQode/pyqode.core | pyqode/core/widgets/_pty.py | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/_pty.py#L33-L47 | def master_open():
"""master_open() -> (master_fd, slave_name)
Open a pty master and return the fd, and the filename of the slave end.
Deprecated, use openpty() instead."""
try:
master_fd, slave_fd = os.openpty()
except (AttributeError, OSError):
pass
else:
slave_name = ... | [
"def",
"master_open",
"(",
")",
":",
"try",
":",
"master_fd",
",",
"slave_fd",
"=",
"os",
".",
"openpty",
"(",
")",
"except",
"(",
"AttributeError",
",",
"OSError",
")",
":",
"pass",
"else",
":",
"slave_name",
"=",
"os",
".",
"ttyname",
"(",
"slave_fd"... | master_open() -> (master_fd, slave_name)
Open a pty master and return the fd, and the filename of the slave end.
Deprecated, use openpty() instead. | [
"master_open",
"()",
"-",
">",
"(",
"master_fd",
"slave_name",
")",
"Open",
"a",
"pty",
"master",
"and",
"return",
"the",
"fd",
"and",
"the",
"filename",
"of",
"the",
"slave",
"end",
".",
"Deprecated",
"use",
"openpty",
"()",
"instead",
"."
] | python | train | 27.933333 |
SeleniumHQ/selenium | py/selenium/webdriver/firefox/options.py | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/firefox/options.py#L52-L59 | def binary(self, new_binary):
"""Sets location of the browser binary, either by string or
``FirefoxBinary`` instance.
"""
if not isinstance(new_binary, FirefoxBinary):
new_binary = FirefoxBinary(new_binary)
self._binary = new_binary | [
"def",
"binary",
"(",
"self",
",",
"new_binary",
")",
":",
"if",
"not",
"isinstance",
"(",
"new_binary",
",",
"FirefoxBinary",
")",
":",
"new_binary",
"=",
"FirefoxBinary",
"(",
"new_binary",
")",
"self",
".",
"_binary",
"=",
"new_binary"
] | Sets location of the browser binary, either by string or
``FirefoxBinary`` instance. | [
"Sets",
"location",
"of",
"the",
"browser",
"binary",
"either",
"by",
"string",
"or",
"FirefoxBinary",
"instance",
"."
] | python | train | 34.75 |
RedHatInsights/insights-core | insights/formats/text.py | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/formats/text.py#L133-L158 | def show_description(self):
""" Prints the formatted response for the matching return type """
def printit(c, v):
underline = "-" * len(dr.get_name(c))
resp = self.responses[v["type"]]
name = "%s[%s] %s%s" % (resp.color, resp.label, dr.get_name(c), Style.RESET_ALL)
... | [
"def",
"show_description",
"(",
"self",
")",
":",
"def",
"printit",
"(",
"c",
",",
"v",
")",
":",
"underline",
"=",
"\"-\"",
"*",
"len",
"(",
"dr",
".",
"get_name",
"(",
"c",
")",
")",
"resp",
"=",
"self",
".",
"responses",
"[",
"v",
"[",
"\"type... | Prints the formatted response for the matching return type | [
"Prints",
"the",
"formatted",
"response",
"for",
"the",
"matching",
"return",
"type"
] | python | train | 45.230769 |
robertpeteuil/aws-shortcuts | awss/core.py | https://github.com/robertpeteuil/aws-shortcuts/blob/cf453ca996978a4d88015d1cf6125bce8ca4873b/awss/core.py#L176-L201 | def cmd_startstop(options):
"""Start or Stop the specified instance.
Finds instances that match args and instance-state expected by the
command. Then, the target instance is determined, the action is
performed on the instance, and the eturn information is displayed.
Args:
options (object)... | [
"def",
"cmd_startstop",
"(",
"options",
")",
":",
"statelu",
"=",
"{",
"\"start\"",
":",
"\"stopped\"",
",",
"\"stop\"",
":",
"\"running\"",
"}",
"options",
".",
"inst_state",
"=",
"statelu",
"[",
"options",
".",
"command",
"]",
"debg",
".",
"dprint",
"(",... | Start or Stop the specified instance.
Finds instances that match args and instance-state expected by the
command. Then, the target instance is determined, the action is
performed on the instance, and the eturn information is displayed.
Args:
options (object): contains args and data from parse... | [
"Start",
"or",
"Stop",
"the",
"specified",
"instance",
"."
] | python | train | 44.076923 |
chaoss/grimoirelab-perceval | perceval/backends/core/github.py | https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/github.py#L235-L265 | def __fetch_issues(self, from_date, to_date):
"""Fetch the issues"""
issues_groups = self.client.issues(from_date=from_date)
for raw_issues in issues_groups:
issues = json.loads(raw_issues)
for issue in issues:
if str_to_datetime(issue['updated_at']) > ... | [
"def",
"__fetch_issues",
"(",
"self",
",",
"from_date",
",",
"to_date",
")",
":",
"issues_groups",
"=",
"self",
".",
"client",
".",
"issues",
"(",
"from_date",
"=",
"from_date",
")",
"for",
"raw_issues",
"in",
"issues_groups",
":",
"issues",
"=",
"json",
"... | Fetch the issues | [
"Fetch",
"the",
"issues"
] | python | test | 41.225806 |
icometrix/dicom2nifti | dicom2nifti/convert_philips.py | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_philips.py#L356-L390 | def _get_grouped_dicoms(dicom_input):
"""
Search all dicoms in the dicom directory, sort and validate them
fast_read = True will only read the headers not the data
"""
# if all dicoms have an instance number try sorting by instance number else by position
if [d for d in dicom_input if 'Instance... | [
"def",
"_get_grouped_dicoms",
"(",
"dicom_input",
")",
":",
"# if all dicoms have an instance number try sorting by instance number else by position",
"if",
"[",
"d",
"for",
"d",
"in",
"dicom_input",
"if",
"'InstanceNumber'",
"in",
"d",
"]",
":",
"dicoms",
"=",
"sorted",
... | Search all dicoms in the dicom directory, sort and validate them
fast_read = True will only read the headers not the data | [
"Search",
"all",
"dicoms",
"in",
"the",
"dicom",
"directory",
"sort",
"and",
"validate",
"them"
] | python | train | 40.6 |
PyCQA/pylint-django | pylint_django/augmentations/__init__.py | https://github.com/PyCQA/pylint-django/blob/0bbee433519f48134df4a797341c4196546a454e/pylint_django/augmentations/__init__.py#L621-L625 | def generic_is_view_attribute(parents, attrs):
"""Generates is_X_attribute function for given parents and attrs."""
def is_attribute(node):
return _attribute_is_magic(node, attrs, parents)
return is_attribute | [
"def",
"generic_is_view_attribute",
"(",
"parents",
",",
"attrs",
")",
":",
"def",
"is_attribute",
"(",
"node",
")",
":",
"return",
"_attribute_is_magic",
"(",
"node",
",",
"attrs",
",",
"parents",
")",
"return",
"is_attribute"
] | Generates is_X_attribute function for given parents and attrs. | [
"Generates",
"is_X_attribute",
"function",
"for",
"given",
"parents",
"and",
"attrs",
"."
] | python | train | 44.8 |
wonambi-python/wonambi | wonambi/attr/annotations.py | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/attr/annotations.py#L1844-L1889 | def export_events(self, filename, evt_type):
"""Export events to CSV
Parameters
----------
filename : str
path of export file
evt_type : list of str
event types to export
"""
filename = splitext(filename)[0] + '.csv'
headin... | [
"def",
"export_events",
"(",
"self",
",",
"filename",
",",
"evt_type",
")",
":",
"filename",
"=",
"splitext",
"(",
"filename",
")",
"[",
"0",
"]",
"+",
"'.csv'",
"headings_row",
"=",
"[",
"'Index'",
",",
"'Start time'",
",",
"'End time'",
",",
"'Stitches'"... | Export events to CSV
Parameters
----------
filename : str
path of export file
evt_type : list of str
event types to export | [
"Export",
"events",
"to",
"CSV",
"Parameters",
"----------",
"filename",
":",
"str",
"path",
"of",
"export",
"file",
"evt_type",
":",
"list",
"of",
"str",
"event",
"types",
"to",
"export"
] | python | train | 33.26087 |
tmacwill/stellata | stellata/database.py | https://github.com/tmacwill/stellata/blob/9519c170397740eb6faf5d8a96b9a77f0d909b92/stellata/database.py#L49-L55 | def query(self, sql: str, args: tuple = None):
"""Execute a SQL query with a return value."""
with self._cursor() as cursor:
log.debug('Running SQL: ' + str((sql, args)))
cursor.execute(sql, args)
return cursor.fetchall() | [
"def",
"query",
"(",
"self",
",",
"sql",
":",
"str",
",",
"args",
":",
"tuple",
"=",
"None",
")",
":",
"with",
"self",
".",
"_cursor",
"(",
")",
"as",
"cursor",
":",
"log",
".",
"debug",
"(",
"'Running SQL: '",
"+",
"str",
"(",
"(",
"sql",
",",
... | Execute a SQL query with a return value. | [
"Execute",
"a",
"SQL",
"query",
"with",
"a",
"return",
"value",
"."
] | python | train | 38.285714 |
CalebBell/fluids | fluids/two_phase.py | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/two_phase.py#L419-L563 | def Chisholm(m, x, rhol, rhog, mul, mug, D, roughness=0, L=1,
rough_correction=False):
r'''Calculates two-phase pressure drop with the Chisholm (1973) correlation
from [1]_, also in [2]_ and [3]_.
.. math::
\frac{\Delta P_{tp}}{\Delta P_{lo}} = \phi_{ch}^2
.. math::
\phi_{... | [
"def",
"Chisholm",
"(",
"m",
",",
"x",
",",
"rhol",
",",
"rhog",
",",
"mul",
",",
"mug",
",",
"D",
",",
"roughness",
"=",
"0",
",",
"L",
"=",
"1",
",",
"rough_correction",
"=",
"False",
")",
":",
"G_tp",
"=",
"m",
"/",
"(",
"pi",
"/",
"4",
... | r'''Calculates two-phase pressure drop with the Chisholm (1973) correlation
from [1]_, also in [2]_ and [3]_.
.. math::
\frac{\Delta P_{tp}}{\Delta P_{lo}} = \phi_{ch}^2
.. math::
\phi_{ch}^2 = 1 + (\Gamma^2 -1)\left\{B x^{(2-n)/2} (1-x)^{(2-n)/2}
+ x^{2-n} \right\}
.. math::
... | [
"r",
"Calculates",
"two",
"-",
"phase",
"pressure",
"drop",
"with",
"the",
"Chisholm",
"(",
"1973",
")",
"correlation",
"from",
"[",
"1",
"]",
"_",
"also",
"in",
"[",
"2",
"]",
"_",
"and",
"[",
"3",
"]",
"_",
"."
] | python | train | 31.758621 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_ppp.py | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_ppp.py#L93-L97 | def mavlink_packet(self, m):
'''handle an incoming mavlink packet'''
if m.get_type() == 'PPP' and self.ppp_fd != -1:
print("got ppp mavlink pkt len=%u" % m.length)
os.write(self.ppp_fd, m.data[:m.length]) | [
"def",
"mavlink_packet",
"(",
"self",
",",
"m",
")",
":",
"if",
"m",
".",
"get_type",
"(",
")",
"==",
"'PPP'",
"and",
"self",
".",
"ppp_fd",
"!=",
"-",
"1",
":",
"print",
"(",
"\"got ppp mavlink pkt len=%u\"",
"%",
"m",
".",
"length",
")",
"os",
".",... | handle an incoming mavlink packet | [
"handle",
"an",
"incoming",
"mavlink",
"packet"
] | python | train | 48 |
delph-in/pydelphin | delphin/mrs/path.py | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/path.py#L432-L450 | def _prepare_axes(node, sort_key):
"""
Sort axes and combine those that point to the same target and go
in the same direction.
"""
links = node.links
o_links = node._overlapping_links
overlap = {ax2 for ax in links for ax2 in o_links.get(ax, [])}
axes = []
for axis in sorted(links.ke... | [
"def",
"_prepare_axes",
"(",
"node",
",",
"sort_key",
")",
":",
"links",
"=",
"node",
".",
"links",
"o_links",
"=",
"node",
".",
"_overlapping_links",
"overlap",
"=",
"{",
"ax2",
"for",
"ax",
"in",
"links",
"for",
"ax2",
"in",
"o_links",
".",
"get",
"(... | Sort axes and combine those that point to the same target and go
in the same direction. | [
"Sort",
"axes",
"and",
"combine",
"those",
"that",
"point",
"to",
"the",
"same",
"target",
"and",
"go",
"in",
"the",
"same",
"direction",
"."
] | python | train | 32.473684 |
chriso/gauged | gauged/drivers/postgresql.py | https://github.com/chriso/gauged/blob/cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976/gauged/drivers/postgresql.py#L249-L268 | def add_cache(self, namespace, key, query_hash, length, cache):
"""Add cached values for the specified date range and query"""
start = 0
bulk_insert = self.bulk_insert
cache_len = len(cache)
row = '(%s,%s,%s,%s,%s,%s)'
query = 'INSERT INTO gauged_cache ' \
'(n... | [
"def",
"add_cache",
"(",
"self",
",",
"namespace",
",",
"key",
",",
"query_hash",
",",
"length",
",",
"cache",
")",
":",
"start",
"=",
"0",
"bulk_insert",
"=",
"self",
".",
"bulk_insert",
"cache_len",
"=",
"len",
"(",
"cache",
")",
"row",
"=",
"'(%s,%s... | Add cached values for the specified date range and query | [
"Add",
"cached",
"values",
"for",
"the",
"specified",
"date",
"range",
"and",
"query"
] | python | train | 43.55 |
log2timeline/plaso | plaso/storage/interface.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/storage/interface.py#L68-L80 | def PopAttributeContainer(self):
"""Pops a serialized attribute container from the list.
Returns:
bytes: serialized attribute container data.
"""
try:
serialized_data = self._list.pop(0)
self.data_size -= len(serialized_data)
return serialized_data
except IndexError:
... | [
"def",
"PopAttributeContainer",
"(",
"self",
")",
":",
"try",
":",
"serialized_data",
"=",
"self",
".",
"_list",
".",
"pop",
"(",
"0",
")",
"self",
".",
"data_size",
"-=",
"len",
"(",
"serialized_data",
")",
"return",
"serialized_data",
"except",
"IndexError... | Pops a serialized attribute container from the list.
Returns:
bytes: serialized attribute container data. | [
"Pops",
"a",
"serialized",
"attribute",
"container",
"from",
"the",
"list",
"."
] | python | train | 24.538462 |
kolypto/py-good | good/schema/util.py | https://github.com/kolypto/py-good/blob/192ef19e79f6fd95c1cbd7c378a3074c7ad7a6d4/good/schema/util.py#L213-L215 | def commajoin_as_strings(iterable):
""" Join the given iterable with ',' """
return _(u',').join((six.text_type(i) for i in iterable)) | [
"def",
"commajoin_as_strings",
"(",
"iterable",
")",
":",
"return",
"_",
"(",
"u','",
")",
".",
"join",
"(",
"(",
"six",
".",
"text_type",
"(",
"i",
")",
"for",
"i",
"in",
"iterable",
")",
")"
] | Join the given iterable with ',' | [
"Join",
"the",
"given",
"iterable",
"with"
] | python | train | 46.666667 |
CalebBell/fluids | fluids/geometry.py | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/geometry.py#L2163-L2171 | def plate_exchanger_identifier(self):
'''Method to create an identifying string in format 'L' + wavelength +
'A' + amplitude + 'B' + chevron angle-chevron angle. Wavelength and
amplitude are specified in units of mm and rounded to two decimal places.
'''
s = ('L' + str(round(se... | [
"def",
"plate_exchanger_identifier",
"(",
"self",
")",
":",
"s",
"=",
"(",
"'L'",
"+",
"str",
"(",
"round",
"(",
"self",
".",
"wavelength",
"*",
"1000",
",",
"2",
")",
")",
"+",
"'A'",
"+",
"str",
"(",
"round",
"(",
"self",
".",
"amplitude",
"*",
... | Method to create an identifying string in format 'L' + wavelength +
'A' + amplitude + 'B' + chevron angle-chevron angle. Wavelength and
amplitude are specified in units of mm and rounded to two decimal places. | [
"Method",
"to",
"create",
"an",
"identifying",
"string",
"in",
"format",
"L",
"+",
"wavelength",
"+",
"A",
"+",
"amplitude",
"+",
"B",
"+",
"chevron",
"angle",
"-",
"chevron",
"angle",
".",
"Wavelength",
"and",
"amplitude",
"are",
"specified",
"in",
"units... | python | train | 53.111111 |
fabioz/PyDev.Debugger | _pydevd_bundle/pydevd_comm.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydevd_bundle/pydevd_comm.py#L458-L461 | def can_be_executed_by(self, thread_id):
'''By default, it must be in the same thread to be executed
'''
return self.thread_id == thread_id or self.thread_id.endswith('|' + thread_id) | [
"def",
"can_be_executed_by",
"(",
"self",
",",
"thread_id",
")",
":",
"return",
"self",
".",
"thread_id",
"==",
"thread_id",
"or",
"self",
".",
"thread_id",
".",
"endswith",
"(",
"'|'",
"+",
"thread_id",
")"
] | By default, it must be in the same thread to be executed | [
"By",
"default",
"it",
"must",
"be",
"in",
"the",
"same",
"thread",
"to",
"be",
"executed"
] | python | train | 51 |
pandas-dev/pandas | pandas/core/series.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/series.py#L2420-L2501 | def append(self, to_append, ignore_index=False, verify_integrity=False):
"""
Concatenate two or more Series.
Parameters
----------
to_append : Series or list/tuple of Series
Series to append with self.
ignore_index : bool, default False
If True, d... | [
"def",
"append",
"(",
"self",
",",
"to_append",
",",
"ignore_index",
"=",
"False",
",",
"verify_integrity",
"=",
"False",
")",
":",
"from",
"pandas",
".",
"core",
".",
"reshape",
".",
"concat",
"import",
"concat",
"if",
"isinstance",
"(",
"to_append",
",",... | Concatenate two or more Series.
Parameters
----------
to_append : Series or list/tuple of Series
Series to append with self.
ignore_index : bool, default False
If True, do not use the index labels.
.. versionadded:: 0.19.0
verify_integrity :... | [
"Concatenate",
"two",
"or",
"more",
"Series",
"."
] | python | train | 25.597561 |
ray-project/ray | python/ray/autoscaler/gcp/config.py | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/autoscaler/gcp/config.py#L147-L183 | def _configure_iam_role(config):
"""Setup a gcp service account with IAM roles.
Creates a gcp service acconut and binds IAM roles which allow it to control
control storage/compute services. Specifically, the head node needs to have
an IAM role that allows it to create further gce instances and store it... | [
"def",
"_configure_iam_role",
"(",
"config",
")",
":",
"email",
"=",
"SERVICE_ACCOUNT_EMAIL_TEMPLATE",
".",
"format",
"(",
"account_id",
"=",
"DEFAULT_SERVICE_ACCOUNT_ID",
",",
"project_id",
"=",
"config",
"[",
"\"provider\"",
"]",
"[",
"\"project_id\"",
"]",
")",
... | Setup a gcp service account with IAM roles.
Creates a gcp service acconut and binds IAM roles which allow it to control
control storage/compute services. Specifically, the head node needs to have
an IAM role that allows it to create further gce instances and store items
in google cloud storage.
TO... | [
"Setup",
"a",
"gcp",
"service",
"account",
"with",
"IAM",
"roles",
"."
] | python | train | 41.72973 |
sander76/aio-powerview-api | aiopvapi/shades.py | https://github.com/sander76/aio-powerview-api/blob/08b6ac747aba9de19842359a981a7ff1292f5a6c/aiopvapi/shades.py#L25-L39 | def sanitize_resources(resource: dict):
"""Cleans up incoming scene data
:param resource: The dict with scene data to be sanitized.
:returns: Cleaned up scene dict.
"""
try:
for shade in resource[ATTR_SHADE_DATA]:
_name = shade.get(ATTR_NAME)
... | [
"def",
"sanitize_resources",
"(",
"resource",
":",
"dict",
")",
":",
"try",
":",
"for",
"shade",
"in",
"resource",
"[",
"ATTR_SHADE_DATA",
"]",
":",
"_name",
"=",
"shade",
".",
"get",
"(",
"ATTR_NAME",
")",
"if",
"_name",
":",
"shade",
"[",
"ATTR_NAME_UN... | Cleans up incoming scene data
:param resource: The dict with scene data to be sanitized.
:returns: Cleaned up scene dict. | [
"Cleans",
"up",
"incoming",
"scene",
"data"
] | python | train | 35.8 |
Yelp/detect-secrets | detect_secrets/plugins/common/initialize.py | https://github.com/Yelp/detect-secrets/blob/473923ea71f1ac2b5ea1eacc49b98f97967e3d05/detect_secrets/plugins/common/initialize.py#L41-L57 | def _get_prioritized_parameters(plugins_dict, is_using_default_value_map, prefer_default=True):
"""
:type plugins_dict: dict(plugin_name => plugin_params)
:param plugin_dict: mapping of plugin name to all plugin params
:type is_using_default_value_map: dict(str => bool)
:param is_using_default_valu... | [
"def",
"_get_prioritized_parameters",
"(",
"plugins_dict",
",",
"is_using_default_value_map",
",",
"prefer_default",
"=",
"True",
")",
":",
"for",
"plugin_name",
",",
"plugin_params",
"in",
"plugins_dict",
".",
"items",
"(",
")",
":",
"for",
"param_name",
",",
"pa... | :type plugins_dict: dict(plugin_name => plugin_params)
:param plugin_dict: mapping of plugin name to all plugin params
:type is_using_default_value_map: dict(str => bool)
:param is_using_default_value_map: mapping of parameter name to whether its value is derived
from a default value.
:param p... | [
":",
"type",
"plugins_dict",
":",
"dict",
"(",
"plugin_name",
"=",
">",
"plugin_params",
")",
":",
"param",
"plugin_dict",
":",
"mapping",
"of",
"plugin",
"name",
"to",
"all",
"plugin",
"params"
] | python | train | 52.647059 |
globocom/GloboNetworkAPI-client-python | networkapiclient/ApiGenericClient.py | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/ApiGenericClient.py#L270-L288 | def prepare_url(self, uri, kwargs):
"""Convert dict for URL params
"""
params = dict()
for key in kwargs:
if key in ('include', 'exclude', 'fields'):
params.update({
key: ','.join(kwargs.get(key))
})
elif key in ... | [
"def",
"prepare_url",
"(",
"self",
",",
"uri",
",",
"kwargs",
")",
":",
"params",
"=",
"dict",
"(",
")",
"for",
"key",
"in",
"kwargs",
":",
"if",
"key",
"in",
"(",
"'include'",
",",
"'exclude'",
",",
"'fields'",
")",
":",
"params",
".",
"update",
"... | Convert dict for URL params | [
"Convert",
"dict",
"for",
"URL",
"params"
] | python | train | 28.105263 |
vaexio/vaex | packages/vaex-core/vaex/dataframe.py | https://github.com/vaexio/vaex/blob/a45b672f8287afca2ada8e36b74b604b9b28dd85/packages/vaex-core/vaex/dataframe.py#L894-L960 | def correlation(self, x, y=None, binby=[], limits=None, shape=default_shape, sort=False, sort_key=np.abs, selection=False, delay=False, progress=None):
"""Calculate the correlation coefficient cov[x,y]/(std[x]*std[y]) between and x and y, possibly on a grid defined by binby.
Example:
>>> df.co... | [
"def",
"correlation",
"(",
"self",
",",
"x",
",",
"y",
"=",
"None",
",",
"binby",
"=",
"[",
"]",
",",
"limits",
"=",
"None",
",",
"shape",
"=",
"default_shape",
",",
"sort",
"=",
"False",
",",
"sort_key",
"=",
"np",
".",
"abs",
",",
"selection",
... | Calculate the correlation coefficient cov[x,y]/(std[x]*std[y]) between and x and y, possibly on a grid defined by binby.
Example:
>>> df.correlation("x**2+y**2+z**2", "-log(-E+1)")
array(0.6366637382215669)
>>> df.correlation("x**2+y**2+z**2", "-log(-E+1)", binby="Lz", shape=4)
... | [
"Calculate",
"the",
"correlation",
"coefficient",
"cov",
"[",
"x",
"y",
"]",
"/",
"(",
"std",
"[",
"x",
"]",
"*",
"std",
"[",
"y",
"]",
")",
"between",
"and",
"x",
"and",
"y",
"possibly",
"on",
"a",
"grid",
"defined",
"by",
"binby",
"."
] | python | test | 43.253731 |
Blueqat/Blueqat | blueqat/circuit.py | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/circuit.py#L267-L295 | def register_macro(name: str, func: Callable, allow_overwrite: bool = False) -> None:
"""Register new macro to Circuit.
Args:
name (str): The name of macro.
func (callable): The function to be called.
allow_overwrite (bool, optional): If True, allow to overwrite the ... | [
"def",
"register_macro",
"(",
"name",
":",
"str",
",",
"func",
":",
"Callable",
",",
"allow_overwrite",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"if",
"hasattr",
"(",
"Circuit",
",",
"name",
")",
":",
"if",
"allow_overwrite",
":",
"warnings",
... | Register new macro to Circuit.
Args:
name (str): The name of macro.
func (callable): The function to be called.
allow_overwrite (bool, optional): If True, allow to overwrite the existing macro.
Otherwise, raise the ValueError.
Raises:
Val... | [
"Register",
"new",
"macro",
"to",
"Circuit",
"."
] | python | train | 45.482759 |
PMEAL/OpenPNM | openpnm/io/MAT.py | https://github.com/PMEAL/OpenPNM/blob/0547b5724ffedc0a593aae48639d36fe10e0baed/openpnm/io/MAT.py#L29-L60 | def save(cls, network, phases=[], filename=''):
r"""
Write Network to a Mat file for exporting to Matlab.
Parameters
----------
network : OpenPNM Network Object
filename : string
Desired file name, defaults to network name if not given
phases : list... | [
"def",
"save",
"(",
"cls",
",",
"network",
",",
"phases",
"=",
"[",
"]",
",",
"filename",
"=",
"''",
")",
":",
"project",
",",
"network",
",",
"phases",
"=",
"cls",
".",
"_parse_args",
"(",
"network",
"=",
"network",
",",
"phases",
"=",
"phases",
"... | r"""
Write Network to a Mat file for exporting to Matlab.
Parameters
----------
network : OpenPNM Network Object
filename : string
Desired file name, defaults to network name if not given
phases : list of phase objects ([])
Phases that have prop... | [
"r",
"Write",
"Network",
"to",
"a",
"Mat",
"file",
"for",
"exporting",
"to",
"Matlab",
"."
] | python | train | 33.1875 |
jrief/django-websocket-redis | ws4redis/websocket.py | https://github.com/jrief/django-websocket-redis/blob/abcddaad2f579d71dbf375e5e34bc35eef795a81/ws4redis/websocket.py#L88-L113 | def handle_close(self, header, payload):
"""
Called when a close frame has been decoded from the stream.
:param header: The decoded `Header`.
:param payload: The bytestring payload associated with the close frame.
"""
if not payload:
self.close(1000, None)
... | [
"def",
"handle_close",
"(",
"self",
",",
"header",
",",
"payload",
")",
":",
"if",
"not",
"payload",
":",
"self",
".",
"close",
"(",
"1000",
",",
"None",
")",
"return",
"if",
"len",
"(",
"payload",
")",
"<",
"2",
":",
"raise",
"WebSocketError",
"(",
... | Called when a close frame has been decoded from the stream.
:param header: The decoded `Header`.
:param payload: The bytestring payload associated with the close frame. | [
"Called",
"when",
"a",
"close",
"frame",
"has",
"been",
"decoded",
"from",
"the",
"stream",
"."
] | python | train | 36.307692 |
inasafe/inasafe | safe/gui/tools/wizard/step_fc00_functions1.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_fc00_functions1.py#L82-L100 | def on_tblFunctions1_itemSelectionChanged(self):
"""Choose selected hazard x exposure combination.
.. note:: This is an automatic Qt slot
executed when the category selection changes.
"""
# Clear the selection on the 2nd matrix
self.parent.step_fc_functions2.tblFuncti... | [
"def",
"on_tblFunctions1_itemSelectionChanged",
"(",
"self",
")",
":",
"# Clear the selection on the 2nd matrix",
"self",
".",
"parent",
".",
"step_fc_functions2",
".",
"tblFunctions2",
".",
"clearContents",
"(",
")",
"self",
".",
"parent",
".",
"step_fc_functions2",
".... | Choose selected hazard x exposure combination.
.. note:: This is an automatic Qt slot
executed when the category selection changes. | [
"Choose",
"selected",
"hazard",
"x",
"exposure",
"combination",
"."
] | python | train | 49.052632 |
glitchassassin/lackey | lackey/RegionMatching.py | https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L1193-L1197 | def setRows(self, rows):
""" Sets the number of rows in the raster (if columns have not been initialized, set to 1 as well) """
self._raster[0] = rows
if self._raster[1] == 0:
self._raster[1] = 1 | [
"def",
"setRows",
"(",
"self",
",",
"rows",
")",
":",
"self",
".",
"_raster",
"[",
"0",
"]",
"=",
"rows",
"if",
"self",
".",
"_raster",
"[",
"1",
"]",
"==",
"0",
":",
"self",
".",
"_raster",
"[",
"1",
"]",
"=",
"1"
] | Sets the number of rows in the raster (if columns have not been initialized, set to 1 as well) | [
"Sets",
"the",
"number",
"of",
"rows",
"in",
"the",
"raster",
"(",
"if",
"columns",
"have",
"not",
"been",
"initialized",
"set",
"to",
"1",
"as",
"well",
")"
] | python | train | 45.4 |
saltstack/salt | salt/modules/infoblox.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L470-L487 | def get_network(ipv4addr=None, network=None, return_fields=None, **api_opts):
'''
Get list of all networks. This is helpful when looking up subnets to use
with func:nextavailableip
This call is offen slow and not cached!
some return_fields
comment,network,network_view,ddns_domainname,disable,e... | [
"def",
"get_network",
"(",
"ipv4addr",
"=",
"None",
",",
"network",
"=",
"None",
",",
"return_fields",
"=",
"None",
",",
"*",
"*",
"api_opts",
")",
":",
"infoblox",
"=",
"_get_infoblox",
"(",
"*",
"*",
"api_opts",
")",
"return",
"infoblox",
".",
"get_net... | Get list of all networks. This is helpful when looking up subnets to use
with func:nextavailableip
This call is offen slow and not cached!
some return_fields
comment,network,network_view,ddns_domainname,disable,enable_ddns
CLI Example:
.. code-block:: bash
salt-call infoblox.get_net... | [
"Get",
"list",
"of",
"all",
"networks",
".",
"This",
"is",
"helpful",
"when",
"looking",
"up",
"subnets",
"to",
"use",
"with",
"func",
":",
"nextavailableip"
] | python | train | 30.166667 |
numenta/htmresearch | htmresearch/frameworks/layers/continuous_location_object_machine.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/layers/continuous_location_object_machine.py#L99-L184 | def provideObjectsToLearn(self, learningConfig, plot=False):
"""
Returns the objects in a canonical format to be sent to an experiment.
The input, learningConfig, should have the following format. It is a
mapping from object to a list of features to sample locations from, and
the number of points t... | [
"def",
"provideObjectsToLearn",
"(",
"self",
",",
"learningConfig",
",",
"plot",
"=",
"False",
")",
":",
"objects",
"=",
"{",
"}",
"for",
"objectName",
",",
"locationList",
"in",
"learningConfig",
".",
"iteritems",
"(",
")",
":",
"sensationList",
"=",
"[",
... | Returns the objects in a canonical format to be sent to an experiment.
The input, learningConfig, should have the following format. It is a
mapping from object to a list of features to sample locations from, and
the number of points to sample from each feature. Note that these objects
should be first a... | [
"Returns",
"the",
"objects",
"in",
"a",
"canonical",
"format",
"to",
"be",
"sent",
"to",
"an",
"experiment",
"."
] | python | train | 34.023256 |
gopalkoduri/intonation | intonation/recording.py | https://github.com/gopalkoduri/intonation/blob/7f50d2b572755840be960ea990416a7b27f20312/intonation/recording.py#L80-L166 | def parametrize_peaks(self, intervals, max_peakwidth=50, min_peakwidth=25, symmetric_bounds=True):
"""
Computes and stores the intonation profile of an audio recording.
:param intervals: these will be the reference set of intervals to which peak positions
correspond to. For each interv... | [
"def",
"parametrize_peaks",
"(",
"self",
",",
"intervals",
",",
"max_peakwidth",
"=",
"50",
",",
"min_peakwidth",
"=",
"25",
",",
"symmetric_bounds",
"=",
"True",
")",
":",
"assert",
"isinstance",
"(",
"self",
".",
"pitch_obj",
".",
"pitch",
",",
"np",
"."... | Computes and stores the intonation profile of an audio recording.
:param intervals: these will be the reference set of intervals to which peak positions
correspond to. For each interval, the properties of corresponding peak, if exists,
will be computed and stored as intonation profile.
... | [
"Computes",
"and",
"stores",
"the",
"intonation",
"profile",
"of",
"an",
"audio",
"recording",
"."
] | python | train | 54.195402 |
assemblerflow/flowcraft | flowcraft/templates/trimmomatic_report.py | https://github.com/assemblerflow/flowcraft/blob/fc3f4bddded1efc76006600016dc71a06dd908c0/flowcraft/templates/trimmomatic_report.py#L164-L185 | def main(log_files):
""" Main executor of the trimmomatic_report template.
Parameters
----------
log_files : list
List of paths to the trimmomatic log files.
"""
log_storage = OrderedDict()
for log in log_files:
log_id = log.rstrip("_trimlog.txt")
# Populate stor... | [
"def",
"main",
"(",
"log_files",
")",
":",
"log_storage",
"=",
"OrderedDict",
"(",
")",
"for",
"log",
"in",
"log_files",
":",
"log_id",
"=",
"log",
".",
"rstrip",
"(",
"\"_trimlog.txt\"",
")",
"# Populate storage of current sample",
"log_storage",
"[",
"log_id",... | Main executor of the trimmomatic_report template.
Parameters
----------
log_files : list
List of paths to the trimmomatic log files. | [
"Main",
"executor",
"of",
"the",
"trimmomatic_report",
"template",
"."
] | python | test | 22.5 |
PmagPy/PmagPy | programs/deprecated/umich_magic.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/deprecated/umich_magic.py#L7-L244 | def main():
"""
NAME
umich_magic.py
DESCRIPTION
converts UMICH .mag format files to magic_measurements format files
SYNTAX
umich_magic.py [command line options]
OPTIONS
-h: prints the help message and quits.
-usr USER: identify user, default is ""
... | [
"def",
"main",
"(",
")",
":",
"# initialize some stuff",
"dir_path",
"=",
"'.'",
"infile_type",
"=",
"\"mag\"",
"noave",
"=",
"0",
"methcode",
",",
"inst",
"=",
"\"\"",
",",
"\"\"",
"phi",
",",
"theta",
",",
"peakfield",
",",
"labfield",
"=",
"0",
",",
... | NAME
umich_magic.py
DESCRIPTION
converts UMICH .mag format files to magic_measurements format files
SYNTAX
umich_magic.py [command line options]
OPTIONS
-h: prints the help message and quits.
-usr USER: identify user, default is ""
-f FILE: specify .mag ... | [
"NAME",
"umich_magic",
".",
"py",
"DESCRIPTION",
"converts",
"UMICH",
".",
"mag",
"format",
"files",
"to",
"magic_measurements",
"format",
"files"
] | python | train | 41.054622 |
elliterate/capybara.py | capybara/node/document_matchers.py | https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/document_matchers.py#L76-L92 | def has_no_title(self, title, **kwargs):
"""
Checks if the page doesn't have the given title.
Args:
title (str | RegexObject): The string that the title should include.
**kwargs: Arbitrary keyword arguments for :class:`TitleQuery`.
Returns:
bool: Whe... | [
"def",
"has_no_title",
"(",
"self",
",",
"title",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"self",
".",
"assert_no_title",
"(",
"title",
",",
"*",
"*",
"kwargs",
")",
"return",
"True",
"except",
"ExpectationNotMet",
":",
"return",
"False"
] | Checks if the page doesn't have the given title.
Args:
title (str | RegexObject): The string that the title should include.
**kwargs: Arbitrary keyword arguments for :class:`TitleQuery`.
Returns:
bool: Whether it doesn't match. | [
"Checks",
"if",
"the",
"page",
"doesn",
"t",
"have",
"the",
"given",
"title",
"."
] | python | test | 28.529412 |
jgillick/LendingClub | lendingclub/filters.py | https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/filters.py#L209-L219 | def __normalize_progress(self):
"""
Adjust the funding progress filter to be a factor of 10
"""
progress = self['funding_progress']
if progress % 10 != 0:
progress = round(float(progress) / 10)
progress = int(progress) * 10
self['funding_prog... | [
"def",
"__normalize_progress",
"(",
"self",
")",
":",
"progress",
"=",
"self",
"[",
"'funding_progress'",
"]",
"if",
"progress",
"%",
"10",
"!=",
"0",
":",
"progress",
"=",
"round",
"(",
"float",
"(",
"progress",
")",
"/",
"10",
")",
"progress",
"=",
"... | Adjust the funding progress filter to be a factor of 10 | [
"Adjust",
"the",
"funding",
"progress",
"filter",
"to",
"be",
"a",
"factor",
"of",
"10"
] | python | train | 29.727273 |
apache/incubator-heron | heron/instance/src/python/basics/bolt_instance.py | https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/basics/bolt_instance.py#L161-L173 | def process_incoming_tuples(self):
"""Should be called when tuple was buffered into in_stream
This method is equivalent to ``addBoltTasks()`` but
is designed for event-driven single-thread bolt.
"""
# back-pressure
if self.output_helper.is_out_queue_available():
self._read_tuples_and_exec... | [
"def",
"process_incoming_tuples",
"(",
"self",
")",
":",
"# back-pressure",
"if",
"self",
".",
"output_helper",
".",
"is_out_queue_available",
"(",
")",
":",
"self",
".",
"_read_tuples_and_execute",
"(",
")",
"self",
".",
"output_helper",
".",
"send_out_tuples",
"... | Should be called when tuple was buffered into in_stream
This method is equivalent to ``addBoltTasks()`` but
is designed for event-driven single-thread bolt. | [
"Should",
"be",
"called",
"when",
"tuple",
"was",
"buffered",
"into",
"in_stream"
] | python | valid | 35 |
vertexproject/synapse | synapse/daemon.py | https://github.com/vertexproject/synapse/blob/22e67c5a8f6d7caddbcf34b39ab1bd2d6c4a6e0b/synapse/daemon.py#L175-L192 | def share(self, name, item):
'''
Share an object via the telepath protocol.
Args:
name (str): Name of the shared object
item (object): The object to share over telepath.
'''
try:
if isinstance(item, s_telepath.Aware):
item.on... | [
"def",
"share",
"(",
"self",
",",
"name",
",",
"item",
")",
":",
"try",
":",
"if",
"isinstance",
"(",
"item",
",",
"s_telepath",
".",
"Aware",
")",
":",
"item",
".",
"onTeleShare",
"(",
"self",
",",
"name",
")",
"self",
".",
"shared",
"[",
"name",
... | Share an object via the telepath protocol.
Args:
name (str): Name of the shared object
item (object): The object to share over telepath. | [
"Share",
"an",
"object",
"via",
"the",
"telepath",
"protocol",
"."
] | python | train | 25.222222 |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L10944-L10964 | def scencd(sc, sclkch, MXPART=None):
"""
Encode character representation of spacecraft clock time into a
double precision number.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/scencd_c.html
:param sc: NAIF spacecraft identification code.
:type sc: int
:param sclkch: Character rep... | [
"def",
"scencd",
"(",
"sc",
",",
"sclkch",
",",
"MXPART",
"=",
"None",
")",
":",
"sc",
"=",
"ctypes",
".",
"c_int",
"(",
"sc",
")",
"sclkch",
"=",
"stypes",
".",
"stringToCharP",
"(",
"sclkch",
")",
"sclkdp",
"=",
"ctypes",
".",
"c_double",
"(",
")... | Encode character representation of spacecraft clock time into a
double precision number.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/scencd_c.html
:param sc: NAIF spacecraft identification code.
:type sc: int
:param sclkch: Character representation of a spacecraft clock.
:type sclk... | [
"Encode",
"character",
"representation",
"of",
"spacecraft",
"clock",
"time",
"into",
"a",
"double",
"precision",
"number",
"."
] | python | train | 33.571429 |
horazont/aioxmpp | aioxmpp/service.py | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/service.py#L1408-L1426 | def is_iq_handler(type_, payload_cls, coro, *, with_send_reply=False):
"""
Return true if `coro` has been decorated with :func:`iq_handler` for the
given `type_` and `payload_cls` and the specified keyword arguments.
"""
try:
handlers = get_magic_attr(coro)
except AttributeError:
... | [
"def",
"is_iq_handler",
"(",
"type_",
",",
"payload_cls",
",",
"coro",
",",
"*",
",",
"with_send_reply",
"=",
"False",
")",
":",
"try",
":",
"handlers",
"=",
"get_magic_attr",
"(",
"coro",
")",
"except",
"AttributeError",
":",
"return",
"False",
"hs",
"=",... | Return true if `coro` has been decorated with :func:`iq_handler` for the
given `type_` and `payload_cls` and the specified keyword arguments. | [
"Return",
"true",
"if",
"coro",
"has",
"been",
"decorated",
"with",
":",
"func",
":",
"iq_handler",
"for",
"the",
"given",
"type_",
"and",
"payload_cls",
"and",
"the",
"specified",
"keyword",
"arguments",
"."
] | python | train | 27.210526 |
scanny/python-pptx | pptx/shapes/shapetree.py | https://github.com/scanny/python-pptx/blob/d6ab8234f8b03953d2f831ff9394b1852db34130/pptx/shapes/shapetree.py#L359-L371 | def _add_chart_graphicFrame(self, rId, x, y, cx, cy):
"""Return new `p:graphicFrame` element appended to this shape tree.
The `p:graphicFrame` element has the specified position and size and
refers to the chart part identified by *rId*.
"""
shape_id = self._next_shape_id
... | [
"def",
"_add_chart_graphicFrame",
"(",
"self",
",",
"rId",
",",
"x",
",",
"y",
",",
"cx",
",",
"cy",
")",
":",
"shape_id",
"=",
"self",
".",
"_next_shape_id",
"name",
"=",
"'Chart %d'",
"%",
"(",
"shape_id",
"-",
"1",
")",
"graphicFrame",
"=",
"CT_Grap... | Return new `p:graphicFrame` element appended to this shape tree.
The `p:graphicFrame` element has the specified position and size and
refers to the chart part identified by *rId*. | [
"Return",
"new",
"p",
":",
"graphicFrame",
"element",
"appended",
"to",
"this",
"shape",
"tree",
"."
] | python | train | 41.384615 |
monarch-initiative/dipper | dipper/utils/CurieUtil.py | https://github.com/monarch-initiative/dipper/blob/24cc80db355bbe15776edc5c7b41e0886959ba41/dipper/utils/CurieUtil.py#L31-L37 | def get_curie(self, uri):
'''Get a CURIE from a URI '''
prefix = self.get_curie_prefix(uri)
if prefix is not None:
key = self.curie_map[prefix]
return '%s:%s' % (prefix, uri[len(key):len(uri)])
return None | [
"def",
"get_curie",
"(",
"self",
",",
"uri",
")",
":",
"prefix",
"=",
"self",
".",
"get_curie_prefix",
"(",
"uri",
")",
"if",
"prefix",
"is",
"not",
"None",
":",
"key",
"=",
"self",
".",
"curie_map",
"[",
"prefix",
"]",
"return",
"'%s:%s'",
"%",
"(",... | Get a CURIE from a URI | [
"Get",
"a",
"CURIE",
"from",
"a",
"URI"
] | python | train | 36.428571 |
Parsl/parsl | parsl/dataflow/flow_control.py | https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/dataflow/flow_control.py#L123-L129 | def notify(self, event_id):
"""Let the FlowControl system know that there is an event."""
self._event_buffer.extend([event_id])
self._event_count += 1
if self._event_count >= self.threshold:
logger.debug("Eventcount >= threshold")
self.make_callback(kind="event") | [
"def",
"notify",
"(",
"self",
",",
"event_id",
")",
":",
"self",
".",
"_event_buffer",
".",
"extend",
"(",
"[",
"event_id",
"]",
")",
"self",
".",
"_event_count",
"+=",
"1",
"if",
"self",
".",
"_event_count",
">=",
"self",
".",
"threshold",
":",
"logge... | Let the FlowControl system know that there is an event. | [
"Let",
"the",
"FlowControl",
"system",
"know",
"that",
"there",
"is",
"an",
"event",
"."
] | python | valid | 44.714286 |
bwohlberg/sporco | sporco/admm/ccmodmd.py | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/ccmodmd.py#L966-L974 | def obfn_dfd(self):
r"""Compute data fidelity term :math:`(1/2) \| W \left( \sum_m
\mathbf{d}_m * \mathbf{x}_m - \mathbf{s} \right) \|_2^2`.
"""
Ef = sl.inner(self.Zf, self.obfn_fvarf(), axis=self.cri.axisM) \
- self.Sf
return (np.linalg.norm(self.W * sl.irfftn(Ef, sel... | [
"def",
"obfn_dfd",
"(",
"self",
")",
":",
"Ef",
"=",
"sl",
".",
"inner",
"(",
"self",
".",
"Zf",
",",
"self",
".",
"obfn_fvarf",
"(",
")",
",",
"axis",
"=",
"self",
".",
"cri",
".",
"axisM",
")",
"-",
"self",
".",
"Sf",
"return",
"(",
"np",
"... | r"""Compute data fidelity term :math:`(1/2) \| W \left( \sum_m
\mathbf{d}_m * \mathbf{x}_m - \mathbf{s} \right) \|_2^2`. | [
"r",
"Compute",
"data",
"fidelity",
"term",
":",
"math",
":",
"(",
"1",
"/",
"2",
")",
"\\",
"|",
"W",
"\\",
"left",
"(",
"\\",
"sum_m",
"\\",
"mathbf",
"{",
"d",
"}",
"_m",
"*",
"\\",
"mathbf",
"{",
"x",
"}",
"_m",
"-",
"\\",
"mathbf",
"{",
... | python | train | 44.222222 |
tjcsl/ion | intranet/apps/eighth/models.py | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L846-L852 | def is_almost_full(self):
"""Return whether the activity is almost full (>90%)."""
capacity = self.get_true_capacity()
if capacity != -1:
num_signed_up = self.eighthsignup_set.count()
return num_signed_up >= (0.9 * capacity)
return False | [
"def",
"is_almost_full",
"(",
"self",
")",
":",
"capacity",
"=",
"self",
".",
"get_true_capacity",
"(",
")",
"if",
"capacity",
"!=",
"-",
"1",
":",
"num_signed_up",
"=",
"self",
".",
"eighthsignup_set",
".",
"count",
"(",
")",
"return",
"num_signed_up",
">... | Return whether the activity is almost full (>90%). | [
"Return",
"whether",
"the",
"activity",
"is",
"almost",
"full",
"(",
">",
"90%",
")",
"."
] | python | train | 41 |
cltk/cltk | cltk/lemmatize/french/lemma.py | https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/lemmatize/french/lemma.py#L46-L74 | def lemmatize(self, tokens):
"""define list of lemmas"""
entries = self.entries
forms_and_lemmas = self.forms_and_lemmas
lemma_list = [x[0] for x in entries]
"""Provide a lemma for each token"""
lemmatized = []
for token in tokens:
"""check for a matc... | [
"def",
"lemmatize",
"(",
"self",
",",
"tokens",
")",
":",
"entries",
"=",
"self",
".",
"entries",
"forms_and_lemmas",
"=",
"self",
".",
"forms_and_lemmas",
"lemma_list",
"=",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"entries",
"]",
"\"\"\"Provide a lemma... | define list of lemmas | [
"define",
"list",
"of",
"lemmas"
] | python | train | 43.068966 |
resync/resync | resync/client.py | https://github.com/resync/resync/blob/98292c17b2c00f2d6f5191c6ab51fef8c292a018/resync/client.py#L476-L546 | def update_resource(self, resource, filename, change=None):
"""Update resource from uri to filename on local system.
Update means three things:
1. GET resources
2. set mtime in local time to be equal to timestamp in UTC (should perhaps
or at least warn if different from LastModi... | [
"def",
"update_resource",
"(",
"self",
",",
"resource",
",",
"filename",
",",
"change",
"=",
"None",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"filename",
")",
"distutils",
".",
"dir_util",
".",
"mkpath",
"(",
"path",
")",
"num_upd... | Update resource from uri to filename on local system.
Update means three things:
1. GET resources
2. set mtime in local time to be equal to timestamp in UTC (should perhaps
or at least warn if different from LastModified from the GET response instead
but maybe warn if different ... | [
"Update",
"resource",
"from",
"uri",
"to",
"filename",
"on",
"local",
"system",
"."
] | python | train | 46.830986 |
utiasSTARS/pykitti | pykitti/tracking.py | https://github.com/utiasSTARS/pykitti/blob/d3e1bb81676e831886726cc5ed79ce1f049aef2c/pykitti/tracking.py#L291-L304 | def bbox(self):
bbox = self._df[['id', 'x1', 'y1', 'x2', 'y2']].copy()
# TODO: Fix this to become x, y, w, h
if self.bbox_with_size:
bbox['y2'] -= bbox['y1']
bbox['x2'] -= bbox['x1']
"""Converts a dataframe to a list of arrays
:param df:
:param le... | [
"def",
"bbox",
"(",
"self",
")",
":",
"bbox",
"=",
"self",
".",
"_df",
"[",
"[",
"'id'",
",",
"'x1'",
",",
"'y1'",
",",
"'x2'",
",",
"'y2'",
"]",
"]",
".",
"copy",
"(",
")",
"# TODO: Fix this to become x, y, w, h",
"if",
"self",
".",
"bbox_with_size",
... | Converts a dataframe to a list of arrays
:param df:
:param length:
:return: | [
"Converts",
"a",
"dataframe",
"to",
"a",
"list",
"of",
"arrays",
":",
"param",
"df",
":",
":",
"param",
"length",
":",
":",
"return",
":"
] | python | train | 26.928571 |
SatelliteQE/nailgun | nailgun/entities.py | https://github.com/SatelliteQE/nailgun/blob/c36d8c20862e87bf6975bd48ac1ca40a9e634eaa/nailgun/entities.py#L6289-L6307 | def available_repositories(self, **kwargs):
"""Lists available repositories for the repository set
:param synchronous: What should happen if the server returns an HTTP
202 (accepted) status code? Wait for the task to complete if
``True``. Immediately return the server's response... | [
"def",
"available_repositories",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'data'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'data'",
"]",
"=",
"dict",
"(",
")",
"kwargs",
"[",
"'data'",
"]",
"[",
"'product_id'",
"]",
"=",
"self",
"."... | Lists available repositories for the repository set
:param synchronous: What should happen if the server returns an HTTP
202 (accepted) status code? Wait for the task to complete if
``True``. Immediately return the server's response otherwise.
:param kwargs: Arguments to pass to... | [
"Lists",
"available",
"repositories",
"for",
"the",
"repository",
"set"
] | python | train | 50.315789 |
apple/turicreate | src/unity/python/turicreate/toolkits/_mps_utils.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_mps_utils.py#L188-L202 | def mps_device_name():
"""
Returns name of MPS device that will be used, else None.
"""
lib = _load_tcmps_lib()
if lib is None:
return None
n = 256
c_name = (_ctypes.c_char * n)()
ret = lib.TCMPSMetalDeviceName(_ctypes.byref(c_name), _ctypes.c_int32(n))
if ret == 0:
... | [
"def",
"mps_device_name",
"(",
")",
":",
"lib",
"=",
"_load_tcmps_lib",
"(",
")",
"if",
"lib",
"is",
"None",
":",
"return",
"None",
"n",
"=",
"256",
"c_name",
"=",
"(",
"_ctypes",
".",
"c_char",
"*",
"n",
")",
"(",
")",
"ret",
"=",
"lib",
".",
"T... | Returns name of MPS device that will be used, else None. | [
"Returns",
"name",
"of",
"MPS",
"device",
"that",
"will",
"be",
"used",
"else",
"None",
"."
] | python | train | 25.8 |
pywbem/pywbem | attic/cim_provider2.py | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/attic/cim_provider2.py#L638-L705 | def MI_associators(self,
env,
objectName,
assocClassName,
resultClassName,
role,
resultRole,
propertyList):
# pylint: disable=invalid-name
"""R... | [
"def",
"MI_associators",
"(",
"self",
",",
"env",
",",
"objectName",
",",
"assocClassName",
",",
"resultClassName",
",",
"role",
",",
"resultRole",
",",
"propertyList",
")",
":",
"# pylint: disable=invalid-name",
"# NOTE: This should honor the parameters resultClassName, ro... | Return instances associated to a given object.
Implements the WBEM operation Associators in terms
of the references method. A derived class will not normally
override this method. | [
"Return",
"instances",
"associated",
"to",
"a",
"given",
"object",
"."
] | python | train | 42.426471 |
Robpol86/libnl | libnl/nl80211/iw_scan.py | https://github.com/Robpol86/libnl/blob/274e9fdaa39822d06ef70b799ed4a95937a4d923/libnl/nl80211/iw_scan.py#L156-L171 | def get_cipher(data):
"""http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n336.
Positional arguments:
data -- bytearray data to read.
Returns:
WiFi stream cipher used by the access point (string).
"""
legend = {0: 'Use group cipher suite', 1: 'WEP-40', 2: 'TKIP... | [
"def",
"get_cipher",
"(",
"data",
")",
":",
"legend",
"=",
"{",
"0",
":",
"'Use group cipher suite'",
",",
"1",
":",
"'WEP-40'",
",",
"2",
":",
"'TKIP'",
",",
"4",
":",
"'CCMP'",
",",
"5",
":",
"'WEP-104'",
",",
"}",
"key",
"=",
"data",
"[",
"3",
... | http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n336.
Positional arguments:
data -- bytearray data to read.
Returns:
WiFi stream cipher used by the access point (string). | [
"http",
":",
"//",
"git",
".",
"kernel",
".",
"org",
"/",
"cgit",
"/",
"linux",
"/",
"kernel",
"/",
"git",
"/",
"jberg",
"/",
"iw",
".",
"git",
"/",
"tree",
"/",
"scan",
".",
"c?id",
"=",
"v3",
".",
"17#n336",
"."
] | python | train | 37.8125 |
pypa/pipenv | pipenv/patched/notpip/_internal/req/req_file.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_file.py#L357-L382 | def expand_env_variables(lines_enum):
# type: (ReqFileLines) -> ReqFileLines
"""Replace all environment variables that can be retrieved via `os.getenv`.
The only allowed format for environment variables defined in the
requirement file is `${MY_VARIABLE_1}` to ensure two things:
1. Strings that con... | [
"def",
"expand_env_variables",
"(",
"lines_enum",
")",
":",
"# type: (ReqFileLines) -> ReqFileLines",
"for",
"line_number",
",",
"line",
"in",
"lines_enum",
":",
"for",
"env_var",
",",
"var_name",
"in",
"ENV_VAR_RE",
".",
"findall",
"(",
"line",
")",
":",
"value",... | Replace all environment variables that can be retrieved via `os.getenv`.
The only allowed format for environment variables defined in the
requirement file is `${MY_VARIABLE_1}` to ensure two things:
1. Strings that contain a `$` aren't accidentally (partially) expanded.
2. Ensure consistency across pl... | [
"Replace",
"all",
"environment",
"variables",
"that",
"can",
"be",
"retrieved",
"via",
"os",
".",
"getenv",
"."
] | python | train | 39.346154 |
bunq/sdk_python | bunq/sdk/model/generated/endpoint.py | https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/model/generated/endpoint.py#L28331-L28360 | def get(cls, whitelist_id, whitelist_result_id,
note_text_whitelist_result_id, monetary_account_id=None,
custom_headers=None):
"""
:type api_context: context.ApiContext
:type user_id: int
:type monetary_account_id: int
:type whitelist_id: int
:type... | [
"def",
"get",
"(",
"cls",
",",
"whitelist_id",
",",
"whitelist_result_id",
",",
"note_text_whitelist_result_id",
",",
"monetary_account_id",
"=",
"None",
",",
"custom_headers",
"=",
"None",
")",
":",
"if",
"custom_headers",
"is",
"None",
":",
"custom_headers",
"="... | :type api_context: context.ApiContext
:type user_id: int
:type monetary_account_id: int
:type whitelist_id: int
:type whitelist_result_id: int
:type note_text_whitelist_result_id: int
:type custom_headers: dict[str, str]|None
:rtype: BunqResponseNoteTextWhitelist... | [
":",
"type",
"api_context",
":",
"context",
".",
"ApiContext",
":",
"type",
"user_id",
":",
"int",
":",
"type",
"monetary_account_id",
":",
"int",
":",
"type",
"whitelist_id",
":",
"int",
":",
"type",
"whitelist_result_id",
":",
"int",
":",
"type",
"note_tex... | python | train | 43.5 |
robinandeer/puzzle | setup.py | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/setup.py#L38-L46 | def parse_readme():
"""Parse contents of the README."""
# Get the long description from the relevant file
here = os.path.abspath(os.path.dirname(__file__))
readme_path = os.path.join(here, 'README.md')
with codecs.open(readme_path, encoding='utf-8') as handle:
long_description = handle.read(... | [
"def",
"parse_readme",
"(",
")",
":",
"# Get the long description from the relevant file",
"here",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
"readme_path",
"=",
"os",
".",
"path",
".",
"join",
... | Parse contents of the README. | [
"Parse",
"contents",
"of",
"the",
"README",
"."
] | python | train | 38 |
MonashBI/arcana | arcana/repository/base.py | https://github.com/MonashBI/arcana/blob/d6271a29d13733d00422d11417af8d200be62acc/arcana/repository/base.py#L192-L236 | def cached_tree(self, subject_ids=None, visit_ids=None, fill=False):
"""
Access the repository tree and caches it for subsequent
accesses
Parameters
----------
subject_ids : list(str)
List of subject IDs with which to filter the tree with. If
None... | [
"def",
"cached_tree",
"(",
"self",
",",
"subject_ids",
"=",
"None",
",",
"visit_ids",
"=",
"None",
",",
"fill",
"=",
"False",
")",
":",
"if",
"subject_ids",
"is",
"not",
"None",
":",
"subject_ids",
"=",
"frozenset",
"(",
"subject_ids",
")",
"if",
"visit_... | Access the repository tree and caches it for subsequent
accesses
Parameters
----------
subject_ids : list(str)
List of subject IDs with which to filter the tree with. If
None all are returned
visit_ids : list(str)
List of visit IDs with which ... | [
"Access",
"the",
"repository",
"tree",
"and",
"caches",
"it",
"for",
"subsequent",
"accesses"
] | python | train | 40.622222 |
jgm/pandocfilters | examples/gabc.py | https://github.com/jgm/pandocfilters/blob/0d6b4f9be9d8e54b18b8a97e6120dd85ece53de5/examples/gabc.py#L83-L116 | def latex2png(snippet, outfile):
"""Compiles a LaTeX snippet to png"""
pngimage = os.path.join(IMAGEDIR, outfile + '.png')
texdocument = os.path.join(IMAGEDIR, 'tmp.tex')
with open(texdocument, 'w') as doc:
doc.write(LATEX_DOC % (snippet))
environment = os.environ
environment['shell_esca... | [
"def",
"latex2png",
"(",
"snippet",
",",
"outfile",
")",
":",
"pngimage",
"=",
"os",
".",
"path",
".",
"join",
"(",
"IMAGEDIR",
",",
"outfile",
"+",
"'.png'",
")",
"texdocument",
"=",
"os",
".",
"path",
".",
"join",
"(",
"IMAGEDIR",
",",
"'tmp.tex'",
... | Compiles a LaTeX snippet to png | [
"Compiles",
"a",
"LaTeX",
"snippet",
"to",
"png"
] | python | train | 32.323529 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.