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 |
|---|---|---|---|---|---|---|---|---|---|
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/property.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/property.py#L542-L551 | def take(attributes, properties):
"""Returns a property set which include all
properties in 'properties' that have any of 'attributes'."""
assert is_iterable_typed(attributes, basestring)
assert is_iterable_typed(properties, basestring)
result = []
for e in properties:
if b2.util.set.int... | [
"def",
"take",
"(",
"attributes",
",",
"properties",
")",
":",
"assert",
"is_iterable_typed",
"(",
"attributes",
",",
"basestring",
")",
"assert",
"is_iterable_typed",
"(",
"properties",
",",
"basestring",
")",
"result",
"=",
"[",
"]",
"for",
"e",
"in",
"pro... | Returns a property set which include all
properties in 'properties' that have any of 'attributes'. | [
"Returns",
"a",
"property",
"set",
"which",
"include",
"all",
"properties",
"in",
"properties",
"that",
"have",
"any",
"of",
"attributes",
"."
] | python | train | 41.4 |
divio/django-filer | filer/utils/zip.py | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/utils/zip.py#L9-L27 | def unzip(file_obj):
"""
Take a path to a zipfile and checks if it is a valid zip file
and returns...
"""
files = []
# TODO: implement try-except here
zip = ZipFile(file_obj)
bad_file = zip.testzip()
if bad_file:
raise Exception('"%s" in the .zip archive is corrupt.' % bad_fi... | [
"def",
"unzip",
"(",
"file_obj",
")",
":",
"files",
"=",
"[",
"]",
"# TODO: implement try-except here",
"zip",
"=",
"ZipFile",
"(",
"file_obj",
")",
"bad_file",
"=",
"zip",
".",
"testzip",
"(",
")",
"if",
"bad_file",
":",
"raise",
"Exception",
"(",
"'\"%s\... | Take a path to a zipfile and checks if it is a valid zip file
and returns... | [
"Take",
"a",
"path",
"to",
"a",
"zipfile",
"and",
"checks",
"if",
"it",
"is",
"a",
"valid",
"zip",
"file",
"and",
"returns",
"..."
] | python | train | 33.263158 |
spyder-ide/spyder | spyder/preferences/shortcuts.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/preferences/shortcuts.py#L142-L152 | def keyPressEvent(self, event):
"""Qt Override."""
key = event.key()
if key in [Qt.Key_Up]:
self._parent.previous_row()
elif key in [Qt.Key_Down]:
self._parent.next_row()
elif key in [Qt.Key_Enter, Qt.Key_Return]:
self._parent.show_edit... | [
"def",
"keyPressEvent",
"(",
"self",
",",
"event",
")",
":",
"key",
"=",
"event",
".",
"key",
"(",
")",
"if",
"key",
"in",
"[",
"Qt",
".",
"Key_Up",
"]",
":",
"self",
".",
"_parent",
".",
"previous_row",
"(",
")",
"elif",
"key",
"in",
"[",
"Qt",
... | Qt Override. | [
"Qt",
"Override",
"."
] | python | train | 35.545455 |
MartinThoma/mpu | mpu/string.py | https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/string.py#L19-L53 | def is_email(potential_email_address):
"""
Check if potential_email_address is a valid e-mail address.
Please note that this function has no false-negatives but many
false-positives. So if it returns that the input is not a valid
e-mail adress, it certainly isn't. If it returns True, it might still... | [
"def",
"is_email",
"(",
"potential_email_address",
")",
":",
"context",
",",
"mail",
"=",
"parseaddr",
"(",
"potential_email_address",
")",
"first_condition",
"=",
"len",
"(",
"context",
")",
"==",
"0",
"and",
"len",
"(",
"mail",
")",
"!=",
"0",
"dot_after_a... | Check if potential_email_address is a valid e-mail address.
Please note that this function has no false-negatives but many
false-positives. So if it returns that the input is not a valid
e-mail adress, it certainly isn't. If it returns True, it might still be
invalid. For example, the domain could not ... | [
"Check",
"if",
"potential_email_address",
"is",
"a",
"valid",
"e",
"-",
"mail",
"address",
"."
] | python | train | 29.285714 |
MolSSI-BSE/basis_set_exchange | basis_set_exchange/printing.py | https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/printing.py#L66-L87 | def electron_shell_str(shell, shellidx=None):
'''Return a string representing the data for an electron shell
If shellidx (index of the shell) is not None, it will also be printed
'''
am = shell['angular_momentum']
amchar = lut.amint_to_char(am)
amchar = amchar.upper()
shellidx_str = ''
... | [
"def",
"electron_shell_str",
"(",
"shell",
",",
"shellidx",
"=",
"None",
")",
":",
"am",
"=",
"shell",
"[",
"'angular_momentum'",
"]",
"amchar",
"=",
"lut",
".",
"amint_to_char",
"(",
"am",
")",
"amchar",
"=",
"amchar",
".",
"upper",
"(",
")",
"shellidx_... | Return a string representing the data for an electron shell
If shellidx (index of the shell) is not None, it will also be printed | [
"Return",
"a",
"string",
"representing",
"the",
"data",
"for",
"an",
"electron",
"shell"
] | python | train | 35.318182 |
bububa/pyTOP | pyTOP/simba.py | https://github.com/bububa/pyTOP/blob/1e48009bcfe886be392628244b370e6374e1f2b2/pyTOP/simba.py#L86-L94 | def get(self, campaign_id, nick=None):
'''xxxxx.xxxxx.campaign.area.get
===================================
取得一个推广计划的投放地域设置'''
request = TOPRequest('xxxxx.xxxxx.campaign.area.get')
request['campaign_id'] = campaign_id
if nick!=None: request['nick'] = nick
self.cre... | [
"def",
"get",
"(",
"self",
",",
"campaign_id",
",",
"nick",
"=",
"None",
")",
":",
"request",
"=",
"TOPRequest",
"(",
"'xxxxx.xxxxx.campaign.area.get'",
")",
"request",
"[",
"'campaign_id'",
"]",
"=",
"campaign_id",
"if",
"nick",
"!=",
"None",
":",
"request"... | xxxxx.xxxxx.campaign.area.get
===================================
取得一个推广计划的投放地域设置 | [
"xxxxx",
".",
"xxxxx",
".",
"campaign",
".",
"area",
".",
"get",
"===================================",
"取得一个推广计划的投放地域设置"
] | python | train | 51.888889 |
ewels/MultiQC | multiqc/modules/slamdunk/slamdunk.py | https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/slamdunk/slamdunk.py#L435-L472 | def slamdunkOverallRatesPlot (self):
""" Generate the overall rates plot """
pconfig = {
'id': 'overallratesplot',
'title': 'Slamdunk: Overall conversion rates in reads',
'cpswitch': False,
'cpswitch_c_active': False,
'ylab': 'Number of reads'... | [
"def",
"slamdunkOverallRatesPlot",
"(",
"self",
")",
":",
"pconfig",
"=",
"{",
"'id'",
":",
"'overallratesplot'",
",",
"'title'",
":",
"'Slamdunk: Overall conversion rates in reads'",
",",
"'cpswitch'",
":",
"False",
",",
"'cpswitch_c_active'",
":",
"False",
",",
"'... | Generate the overall rates plot | [
"Generate",
"the",
"overall",
"rates",
"plot"
] | python | train | 43.368421 |
Sanji-IO/sanji | sanji/core.py | https://github.com/Sanji-IO/sanji/blob/5c54cc2772bdfeae3337f785de1957237b828b34/sanji/core.py#L186-L195 | def _resolve_responses(self):
"""
_resolve_responses
"""
while True:
message = self.res_queue.get()
if message is None:
_logger.debug("_resolve_responses thread is terminated")
return
self.__resolve_responses(message) | [
"def",
"_resolve_responses",
"(",
"self",
")",
":",
"while",
"True",
":",
"message",
"=",
"self",
".",
"res_queue",
".",
"get",
"(",
")",
"if",
"message",
"is",
"None",
":",
"_logger",
".",
"debug",
"(",
"\"_resolve_responses thread is terminated\"",
")",
"r... | _resolve_responses | [
"_resolve_responses"
] | python | train | 30.8 |
bukun/TorCMS | ext_script/autocrud/func_gen_html.py | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/ext_script/autocrud/func_gen_html.py#L152-L166 | def gen_select_list(sig_dic):
'''
For generating List view HTML file for SELECT.
for each item.
'''
view_jushi = '''<span class="label label-primary" style="margin-right:10px">'''
dic_tmp = sig_dic['dic']
for key in dic_tmp.keys():
tmp_str = '''{{% if '{0}' in postinfo.extinfo and p... | [
"def",
"gen_select_list",
"(",
"sig_dic",
")",
":",
"view_jushi",
"=",
"'''<span class=\"label label-primary\" style=\"margin-right:10px\">'''",
"dic_tmp",
"=",
"sig_dic",
"[",
"'dic'",
"]",
"for",
"key",
"in",
"dic_tmp",
".",
"keys",
"(",
")",
":",
"tmp_str",
"=",
... | For generating List view HTML file for SELECT.
for each item. | [
"For",
"generating",
"List",
"view",
"HTML",
"file",
"for",
"SELECT",
".",
"for",
"each",
"item",
"."
] | python | train | 33.2 |
SatelliteQE/nailgun | nailgun/entities.py | https://github.com/SatelliteQE/nailgun/blob/c36d8c20862e87bf6975bd48ac1ca40a9e634eaa/nailgun/entities.py#L3393-L3403 | def create(self, create_missing=None):
"""Do extra work to fetch a complete set of attributes for this entity.
For more information, see `Bugzilla #1235377
<https://bugzilla.redhat.com/show_bug.cgi?id=1235377>`_.
"""
return HostGroup(
self._server_config,
... | [
"def",
"create",
"(",
"self",
",",
"create_missing",
"=",
"None",
")",
":",
"return",
"HostGroup",
"(",
"self",
".",
"_server_config",
",",
"id",
"=",
"self",
".",
"create_json",
"(",
"create_missing",
")",
"[",
"'id'",
"]",
",",
")",
".",
"read",
"(",... | Do extra work to fetch a complete set of attributes for this entity.
For more information, see `Bugzilla #1235377
<https://bugzilla.redhat.com/show_bug.cgi?id=1235377>`_. | [
"Do",
"extra",
"work",
"to",
"fetch",
"a",
"complete",
"set",
"of",
"attributes",
"for",
"this",
"entity",
"."
] | python | train | 33.727273 |
tjvr/kurt | kurt/__init__.py | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L2241-L2252 | def _convert(self, format):
"""Return a new Image instance with the given format.
Returns self if the format is already the same.
"""
if self.format == format:
return self
else:
image = Image(self.pil_image)
image._format = format
... | [
"def",
"_convert",
"(",
"self",
",",
"format",
")",
":",
"if",
"self",
".",
"format",
"==",
"format",
":",
"return",
"self",
"else",
":",
"image",
"=",
"Image",
"(",
"self",
".",
"pil_image",
")",
"image",
".",
"_format",
"=",
"format",
"return",
"im... | Return a new Image instance with the given format.
Returns self if the format is already the same. | [
"Return",
"a",
"new",
"Image",
"instance",
"with",
"the",
"given",
"format",
"."
] | python | train | 26.833333 |
IdentityPython/pyop | src/pyop/authz_state.py | https://github.com/IdentityPython/pyop/blob/7b1385964f079c39752fce5f2dbcf458b8a92e56/src/pyop/authz_state.py#L190-L208 | def create_refresh_token(self, access_token_value):
# type: (str) -> str
"""
Creates an refresh token bound to the specified access token.
"""
if access_token_value not in self.access_tokens:
raise InvalidAccessToken('{} unknown'.format(access_token_value))
i... | [
"def",
"create_refresh_token",
"(",
"self",
",",
"access_token_value",
")",
":",
"# type: (str) -> str",
"if",
"access_token_value",
"not",
"in",
"self",
".",
"access_tokens",
":",
"raise",
"InvalidAccessToken",
"(",
"'{} unknown'",
".",
"format",
"(",
"access_token_v... | Creates an refresh token bound to the specified access token. | [
"Creates",
"an",
"refresh",
"token",
"bound",
"to",
"the",
"specified",
"access",
"token",
"."
] | python | train | 44.526316 |
bububa/pyTOP | pyTOP/user.py | https://github.com/bububa/pyTOP/blob/1e48009bcfe886be392628244b370e6374e1f2b2/pyTOP/user.py#L209-L218 | def get(self, nicks=[], fields=[]):
'''taobao.users.get 获取多个用户信息'''
request = TOPRequest('taobao.users.get')
request['nicks'] = ','.join(nicks)
if not fields:
user = User()
fields = user.fields
request['fields'] = ','.join(fields)
self.create(self.... | [
"def",
"get",
"(",
"self",
",",
"nicks",
"=",
"[",
"]",
",",
"fields",
"=",
"[",
"]",
")",
":",
"request",
"=",
"TOPRequest",
"(",
"'taobao.users.get'",
")",
"request",
"[",
"'nicks'",
"]",
"=",
"','",
".",
"join",
"(",
"nicks",
")",
"if",
"not",
... | taobao.users.get 获取多个用户信息 | [
"taobao",
".",
"users",
".",
"get",
"获取多个用户信息"
] | python | train | 35.4 |
mulkieran/justbases | src/justbases/_display.py | https://github.com/mulkieran/justbases/blob/dd52ff4b3d11609f54b2673599ee4eeb20f9734f/src/justbases/_display.py#L156-L192 | def xform(self, left, right, repeating, base, sign):
"""
Return prefixes for tuple.
:param str left: left of the radix
:param str right: right of the radix
:param str repeating: repeating part
:param int base: the base in which value is displayed
:param int sign:... | [
"def",
"xform",
"(",
"self",
",",
"left",
",",
"right",
",",
"repeating",
",",
"base",
",",
"sign",
")",
":",
"# pylint: disable=too-many-arguments",
"base_prefix",
"=",
"''",
"if",
"self",
".",
"CONFIG",
".",
"use_prefix",
":",
"if",
"base",
"==",
"8",
... | Return prefixes for tuple.
:param str left: left of the radix
:param str right: right of the radix
:param str repeating: repeating part
:param int base: the base in which value is displayed
:param int sign: -1, 0, 1 as appropriate
:returns: the number string
:rty... | [
"Return",
"prefixes",
"for",
"tuple",
"."
] | python | train | 32.324324 |
klen/pylama | pylama/libs/inirama.py | https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/libs/inirama.py#L316-L334 | def write(self, f):
""" Write namespace as INI file.
:param f: File object or path to file.
"""
if isinstance(f, str):
f = io.open(f, 'w', encoding='utf-8')
if not hasattr(f, 'read'):
raise AttributeError("Wrong type of file: {0}".format(type(f)))
... | [
"def",
"write",
"(",
"self",
",",
"f",
")",
":",
"if",
"isinstance",
"(",
"f",
",",
"str",
")",
":",
"f",
"=",
"io",
".",
"open",
"(",
"f",
",",
"'w'",
",",
"encoding",
"=",
"'utf-8'",
")",
"if",
"not",
"hasattr",
"(",
"f",
",",
"'read'",
")"... | Write namespace as INI file.
:param f: File object or path to file. | [
"Write",
"namespace",
"as",
"INI",
"file",
"."
] | python | train | 31.052632 |
amzn/ion-python | amazon/ion/reader_binary.py | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_binary.py#L838-L870 | def raw_reader(queue=None):
"""Returns a raw binary reader co-routine.
Args:
queue (Optional[BufferQueue]): The buffer read data for parsing, if ``None`` a
new one will be created.
Yields:
IonEvent: parse events, will have an event type of ``INCOMPLETE`` if data is needed
... | [
"def",
"raw_reader",
"(",
"queue",
"=",
"None",
")",
":",
"if",
"queue",
"is",
"None",
":",
"queue",
"=",
"BufferQueue",
"(",
")",
"ctx",
"=",
"_HandlerContext",
"(",
"position",
"=",
"0",
",",
"limit",
"=",
"None",
",",
"queue",
"=",
"queue",
",",
... | Returns a raw binary reader co-routine.
Args:
queue (Optional[BufferQueue]): The buffer read data for parsing, if ``None`` a
new one will be created.
Yields:
IonEvent: parse events, will have an event type of ``INCOMPLETE`` if data is needed
in the middle of a value or ... | [
"Returns",
"a",
"raw",
"binary",
"reader",
"co",
"-",
"routine",
"."
] | python | train | 36.939394 |
shaunduncan/giphypop | giphypop.py | https://github.com/shaunduncan/giphypop/blob/21e7f51c4f000ae24be3805b7eeec52bcce3d390/giphypop.py#L256-L268 | def _fetch(self, endpoint_name, **params):
"""
Wrapper for making an api request from giphy
"""
params['api_key'] = self.api_key
resp = requests.get(self._endpoint(endpoint_name), params=params)
resp.raise_for_status()
data = resp.json()
self._check_or_r... | [
"def",
"_fetch",
"(",
"self",
",",
"endpoint_name",
",",
"*",
"*",
"params",
")",
":",
"params",
"[",
"'api_key'",
"]",
"=",
"self",
".",
"api_key",
"resp",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"_endpoint",
"(",
"endpoint_name",
")",
",",
"... | Wrapper for making an api request from giphy | [
"Wrapper",
"for",
"making",
"an",
"api",
"request",
"from",
"giphy"
] | python | test | 27.307692 |
StackStorm/pybind | pybind/slxos/v17s_1_02/brocade_mpls_rpc/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/brocade_mpls_rpc/__init__.py#L2802-L2823 | def _set_clear_mpls_auto_bandwidth_statistics_lsp(self, v, load=False):
"""
Setter method for clear_mpls_auto_bandwidth_statistics_lsp, mapped from YANG variable /brocade_mpls_rpc/clear_mpls_auto_bandwidth_statistics_lsp (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _... | [
"def",
"_set_clear_mpls_auto_bandwidth_statistics_lsp",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass... | Setter method for clear_mpls_auto_bandwidth_statistics_lsp, mapped from YANG variable /brocade_mpls_rpc/clear_mpls_auto_bandwidth_statistics_lsp (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_clear_mpls_auto_bandwidth_statistics_lsp is considered as a private
method. ... | [
"Setter",
"method",
"for",
"clear_mpls_auto_bandwidth_statistics_lsp",
"mapped",
"from",
"YANG",
"variable",
"/",
"brocade_mpls_rpc",
"/",
"clear_mpls_auto_bandwidth_statistics_lsp",
"(",
"rpc",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
... | python | train | 92.318182 |
manns/pyspread | pyspread/src/lib/vlc.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/lib/vlc.py#L4714-L4725 | def libvlc_media_list_index_of_item(p_ml, p_md):
'''Find index position of List media instance in media list.
Warning: the function will return the first matched position.
The L{libvlc_media_list_lock} should be held upon entering this function.
@param p_ml: a media list instance.
@param p_md: media... | [
"def",
"libvlc_media_list_index_of_item",
"(",
"p_ml",
",",
"p_md",
")",
":",
"f",
"=",
"_Cfunctions",
".",
"get",
"(",
"'libvlc_media_list_index_of_item'",
",",
"None",
")",
"or",
"_Cfunction",
"(",
"'libvlc_media_list_index_of_item'",
",",
"(",
"(",
"1",
",",
... | Find index position of List media instance in media list.
Warning: the function will return the first matched position.
The L{libvlc_media_list_lock} should be held upon entering this function.
@param p_ml: a media list instance.
@param p_md: media instance.
@return: position of media instance or -1... | [
"Find",
"index",
"position",
"of",
"List",
"media",
"instance",
"in",
"media",
"list",
".",
"Warning",
":",
"the",
"function",
"will",
"return",
"the",
"first",
"matched",
"position",
".",
"The",
"L",
"{",
"libvlc_media_list_lock",
"}",
"should",
"be",
"held... | python | train | 51.25 |
timknip/pycsg | csg/geom.py | https://github.com/timknip/pycsg/blob/b8f9710fd15c38dcc275d56a2108f604af38dcc8/csg/geom.py#L64-L66 | def times(self, a):
""" Multiply. """
return Vector(self.x*a, self.y*a, self.z*a) | [
"def",
"times",
"(",
"self",
",",
"a",
")",
":",
"return",
"Vector",
"(",
"self",
".",
"x",
"*",
"a",
",",
"self",
".",
"y",
"*",
"a",
",",
"self",
".",
"z",
"*",
"a",
")"
] | Multiply. | [
"Multiply",
"."
] | python | train | 31.666667 |
econ-ark/HARK | HARK/utilities.py | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/utilities.py#L959-L978 | def calcWeightedAvg(data,weights):
'''
Generates a weighted average of simulated data. The Nth row of data is averaged
and then weighted by the Nth element of weights in an aggregate average.
Parameters
----------
data : numpy.array
An array of data with N rows of J floats
weights ... | [
"def",
"calcWeightedAvg",
"(",
"data",
",",
"weights",
")",
":",
"data_avg",
"=",
"np",
".",
"mean",
"(",
"data",
",",
"axis",
"=",
"1",
")",
"weighted_sum",
"=",
"np",
".",
"dot",
"(",
"data_avg",
",",
"weights",
")",
"return",
"weighted_sum"
] | Generates a weighted average of simulated data. The Nth row of data is averaged
and then weighted by the Nth element of weights in an aggregate average.
Parameters
----------
data : numpy.array
An array of data with N rows of J floats
weights : numpy.array
A length N array of weigh... | [
"Generates",
"a",
"weighted",
"average",
"of",
"simulated",
"data",
".",
"The",
"Nth",
"row",
"of",
"data",
"is",
"averaged",
"and",
"then",
"weighted",
"by",
"the",
"Nth",
"element",
"of",
"weights",
"in",
"an",
"aggregate",
"average",
"."
] | python | train | 28.7 |
limodou/uliweb | uliweb/utils/generic.py | https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/utils/generic.py#L3008-L3022 | def _make_like(self, column, format, value):
"""
make like condition
:param column: column object
:param format: '%_' '_%' '%_%'
:param value: column value
:return: condition object
"""
c = []
if format.startswith('%'):
c.appe... | [
"def",
"_make_like",
"(",
"self",
",",
"column",
",",
"format",
",",
"value",
")",
":",
"c",
"=",
"[",
"]",
"if",
"format",
".",
"startswith",
"(",
"'%'",
")",
":",
"c",
".",
"append",
"(",
"'%'",
")",
"c",
".",
"append",
"(",
"value",
")",
"if... | make like condition
:param column: column object
:param format: '%_' '_%' '%_%'
:param value: column value
:return: condition object | [
"make",
"like",
"condition",
":",
"param",
"column",
":",
"column",
"object",
":",
"param",
"format",
":",
"%_",
"_%",
"%_%",
":",
"param",
"value",
":",
"column",
"value",
":",
"return",
":",
"condition",
"object"
] | python | train | 29.266667 |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py#L736-L752 | def build(self, **kw):
"""Actually build the node.
This is called by the Taskmaster after it's decided that the
Node is out-of-date and must be rebuilt, and after the prepare()
method has gotten everything, uh, prepared.
This method is called from multiple threads in a parallel... | [
"def",
"build",
"(",
"self",
",",
"*",
"*",
"kw",
")",
":",
"try",
":",
"self",
".",
"get_executor",
"(",
")",
"(",
"self",
",",
"*",
"*",
"kw",
")",
"except",
"SCons",
".",
"Errors",
".",
"BuildError",
"as",
"e",
":",
"e",
".",
"node",
"=",
... | Actually build the node.
This is called by the Taskmaster after it's decided that the
Node is out-of-date and must be rebuilt, and after the prepare()
method has gotten everything, uh, prepared.
This method is called from multiple threads in a parallel build,
so only do thread ... | [
"Actually",
"build",
"the",
"node",
"."
] | python | train | 32.705882 |
atztogo/phonopy | phonopy/structure/spglib.py | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/spglib.py#L844-L877 | def niggli_reduce(lattice, eps=1e-5):
"""Run Niggli reduction
Args:
lattice: Lattice parameters in the form of
[[a_x, a_y, a_z],
[b_x, b_y, b_z],
[c_x, c_y, c_z]]
eps:
float: Tolerance to check if difference of norms of two basis
... | [
"def",
"niggli_reduce",
"(",
"lattice",
",",
"eps",
"=",
"1e-5",
")",
":",
"_set_no_error",
"(",
")",
"niggli_lattice",
"=",
"np",
".",
"array",
"(",
"np",
".",
"transpose",
"(",
"lattice",
")",
",",
"dtype",
"=",
"'double'",
",",
"order",
"=",
"'C'",
... | Run Niggli reduction
Args:
lattice: Lattice parameters in the form of
[[a_x, a_y, a_z],
[b_x, b_y, b_z],
[c_x, c_y, c_z]]
eps:
float: Tolerance to check if difference of norms of two basis
vectors is close to zero or not and if tw... | [
"Run",
"Niggli",
"reduction"
] | python | train | 33.558824 |
msmbuilder/msmbuilder | msmbuilder/tpt/committor.py | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/tpt/committor.py#L87-L147 | def conditional_committors(source, sink, waypoint, msm):
"""
Computes the conditional committors :math:`q^{ABC^+}` which are is the
probability of starting in one state and visiting state B before A while
also visiting state C at some point.
Note that in the notation of Dickson et. al. this compute... | [
"def",
"conditional_committors",
"(",
"source",
",",
"sink",
",",
"waypoint",
",",
"msm",
")",
":",
"# typecheck",
"for",
"data",
"in",
"[",
"source",
",",
"sink",
",",
"waypoint",
"]",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"int",
")",
":",... | Computes the conditional committors :math:`q^{ABC^+}` which are is the
probability of starting in one state and visiting state B before A while
also visiting state C at some point.
Note that in the notation of Dickson et. al. this computes :math:`h_c(A,B)`,
with ``sources = A``, ``sinks = B``, ``waypoi... | [
"Computes",
"the",
"conditional",
"committors",
":",
"math",
":",
"q^",
"{",
"ABC^",
"+",
"}",
"which",
"are",
"is",
"the",
"probability",
"of",
"starting",
"in",
"one",
"state",
"and",
"visiting",
"state",
"B",
"before",
"A",
"while",
"also",
"visiting",
... | python | train | 33.901639 |
blockstack/virtualchain | virtualchain/lib/blockchain/bitcoin_blockchain/bits.py | https://github.com/blockstack/virtualchain/blob/fcfc970064ca7dfcab26ebd3ab955870a763ea39/virtualchain/lib/blockchain/bitcoin_blockchain/bits.py#L208-L232 | def btc_witness_script_deserialize(_script):
"""
Given a hex-encoded serialized witness script, turn it into a witness stack
(i.e. an array of Nones, ints, and strings)
"""
script = None
if isinstance(_script, str) and re.match('^[0-9a-fA-F]*$', _script):
# convert from hex to bin, safe... | [
"def",
"btc_witness_script_deserialize",
"(",
"_script",
")",
":",
"script",
"=",
"None",
"if",
"isinstance",
"(",
"_script",
",",
"str",
")",
"and",
"re",
".",
"match",
"(",
"'^[0-9a-fA-F]*$'",
",",
"_script",
")",
":",
"# convert from hex to bin, safely",
"scr... | Given a hex-encoded serialized witness script, turn it into a witness stack
(i.e. an array of Nones, ints, and strings) | [
"Given",
"a",
"hex",
"-",
"encoded",
"serialized",
"witness",
"script",
"turn",
"it",
"into",
"a",
"witness",
"stack",
"(",
"i",
".",
"e",
".",
"an",
"array",
"of",
"Nones",
"ints",
"and",
"strings",
")"
] | python | train | 28.56 |
marrabld/planarradpy | gui/gui_mainLayout.py | https://github.com/marrabld/planarradpy/blob/5095d1cb98d4f67a7c3108c9282f2d59253e89a8/gui/gui_mainLayout.py#L863-L871 | def mouse_move(self, event):
"""
The following gets back coordinates of the mouse on the canvas.
"""
if (self.ui.tabWidget.currentIndex() == TabWidget.NORMAL_MODE):
self.posX = event.xdata
self.posY = event.ydata
self.graphic_target(self.posX, self.po... | [
"def",
"mouse_move",
"(",
"self",
",",
"event",
")",
":",
"if",
"(",
"self",
".",
"ui",
".",
"tabWidget",
".",
"currentIndex",
"(",
")",
"==",
"TabWidget",
".",
"NORMAL_MODE",
")",
":",
"self",
".",
"posX",
"=",
"event",
".",
"xdata",
"self",
".",
... | The following gets back coordinates of the mouse on the canvas. | [
"The",
"following",
"gets",
"back",
"coordinates",
"of",
"the",
"mouse",
"on",
"the",
"canvas",
"."
] | python | test | 35 |
googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/query.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/query.py#L939-L970 | def _query_response_to_snapshot(response_pb, collection, expected_prefix):
"""Parse a query response protobuf to a document snapshot.
Args:
response_pb (google.cloud.proto.firestore.v1beta1.\
firestore_pb2.RunQueryResponse): A
collection (~.firestore_v1beta1.collection.CollectionRef... | [
"def",
"_query_response_to_snapshot",
"(",
"response_pb",
",",
"collection",
",",
"expected_prefix",
")",
":",
"if",
"not",
"response_pb",
".",
"HasField",
"(",
"\"document\"",
")",
":",
"return",
"None",
"document_id",
"=",
"_helpers",
".",
"get_doc_id",
"(",
"... | Parse a query response protobuf to a document snapshot.
Args:
response_pb (google.cloud.proto.firestore.v1beta1.\
firestore_pb2.RunQueryResponse): A
collection (~.firestore_v1beta1.collection.CollectionReference): A
reference to the collection that initiated the query.
... | [
"Parse",
"a",
"query",
"response",
"protobuf",
"to",
"a",
"document",
"snapshot",
"."
] | python | train | 41.9375 |
JdeRobot/base | src/drivers/drone/pose3d.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/drone/pose3d.py#L135-L148 | def __callback (self, odom):
'''
Callback function to receive and save Pose3d.
@param odom: ROS Odometry received
@type odom: Odometry
'''
pose = odometry2Pose3D(odom)
self.lock.acquire()
self.data = pose
self.lock.release() | [
"def",
"__callback",
"(",
"self",
",",
"odom",
")",
":",
"pose",
"=",
"odometry2Pose3D",
"(",
"odom",
")",
"self",
".",
"lock",
".",
"acquire",
"(",
")",
"self",
".",
"data",
"=",
"pose",
"self",
".",
"lock",
".",
"release",
"(",
")"
] | Callback function to receive and save Pose3d.
@param odom: ROS Odometry received
@type odom: Odometry | [
"Callback",
"function",
"to",
"receive",
"and",
"save",
"Pose3d",
"."
] | python | train | 21.142857 |
cos-archives/modular-odm | modularodm/cache.py | https://github.com/cos-archives/modular-odm/blob/8a34891892b8af69b21fdc46701c91763a5c1cf9/modularodm/cache.py#L3-L21 | def set_nested(data, value, *keys):
"""Assign to a nested dictionary.
:param dict data: Dictionary to mutate
:param value: Value to set
:param list *keys: List of nested keys
>>> data = {}
>>> set_nested(data, 'hi', 'k0', 'k1', 'k2')
>>> data
{'k0': {'k1': {'k2': 'hi'}}}
"""
i... | [
"def",
"set_nested",
"(",
"data",
",",
"value",
",",
"*",
"keys",
")",
":",
"if",
"len",
"(",
"keys",
")",
"==",
"1",
":",
"data",
"[",
"keys",
"[",
"0",
"]",
"]",
"=",
"value",
"else",
":",
"if",
"keys",
"[",
"0",
"]",
"not",
"in",
"data",
... | Assign to a nested dictionary.
:param dict data: Dictionary to mutate
:param value: Value to set
:param list *keys: List of nested keys
>>> data = {}
>>> set_nested(data, 'hi', 'k0', 'k1', 'k2')
>>> data
{'k0': {'k1': {'k2': 'hi'}}} | [
"Assign",
"to",
"a",
"nested",
"dictionary",
"."
] | python | valid | 24.947368 |
area4lib/area4 | area4/util.py | https://github.com/area4lib/area4/blob/7f71b58d6b44b1a61284a8a01f26afd3138b9b17/area4/util.py#L13-L29 | def get_raw_file():
"""
Get the raw divider file in a string array.
:return: the array
:rtype: str
"""
with open("{0}/dividers.txt".format(
os.path.abspath(
os.path.dirname(__file__)
)
), mode="r") as file_handler:
lines = file_handler.readlines()
... | [
"def",
"get_raw_file",
"(",
")",
":",
"with",
"open",
"(",
"\"{0}/dividers.txt\"",
".",
"format",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
")",
",",
"mode",
"=",
"\"r\"",
")",
"as",
... | Get the raw divider file in a string array.
:return: the array
:rtype: str | [
"Get",
"the",
"raw",
"divider",
"file",
"in",
"a",
"string",
"array",
"."
] | python | train | 23.294118 |
google/transitfeed | misc/import_ch_zurich.py | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/misc/import_ch_zurich.py#L163-L190 | def DemangleName(self, name):
"Applies some simple heuristics to split names into (city, name)."
# Handle special cases where our heuristcs doesn't work.
# Example:"Triemli" --> ("Triemli", "Zurich").
if name in SPECIAL_NAMES:
return SPECIAL_NAMES[name]
# Expand abbreviations.
for abbrev... | [
"def",
"DemangleName",
"(",
"self",
",",
"name",
")",
":",
"# Handle special cases where our heuristcs doesn't work.",
"# Example:\"Triemli\" --> (\"Triemli\", \"Zurich\").",
"if",
"name",
"in",
"SPECIAL_NAMES",
":",
"return",
"SPECIAL_NAMES",
"[",
"name",
"]",
"# Expand abbr... | Applies some simple heuristics to split names into (city, name). | [
"Applies",
"some",
"simple",
"heuristics",
"to",
"split",
"names",
"into",
"(",
"city",
"name",
")",
"."
] | python | train | 31.535714 |
kgori/treeCl | treeCl/distance_matrix.py | https://github.com/kgori/treeCl/blob/fed624b3db1c19cc07175ca04e3eda6905a8d305/treeCl/distance_matrix.py#L147-L156 | def normalise_rows(matrix):
""" Scales all rows to length 1. Fails when row is 0-length, so it
leaves these unchanged """
lengths = np.apply_along_axis(np.linalg.norm, 1, matrix)
if not (lengths > 0).all():
# raise ValueError('Cannot normalise 0 length vector to length 1')
# print(matri... | [
"def",
"normalise_rows",
"(",
"matrix",
")",
":",
"lengths",
"=",
"np",
".",
"apply_along_axis",
"(",
"np",
".",
"linalg",
".",
"norm",
",",
"1",
",",
"matrix",
")",
"if",
"not",
"(",
"lengths",
">",
"0",
")",
".",
"all",
"(",
")",
":",
"# raise Va... | Scales all rows to length 1. Fails when row is 0-length, so it
leaves these unchanged | [
"Scales",
"all",
"rows",
"to",
"length",
"1",
".",
"Fails",
"when",
"row",
"is",
"0",
"-",
"length",
"so",
"it",
"leaves",
"these",
"unchanged"
] | python | train | 39 |
zalando/patroni | patroni/postgresql.py | https://github.com/zalando/patroni/blob/f6d29081c90af52064b981cdd877a07338d86038/patroni/postgresql.py#L892-L961 | def start(self, timeout=None, task=None, block_callbacks=False, role=None):
"""Start PostgreSQL
Waits for postmaster to open ports or terminate so pg_isready can be used to check startup completion
or failure.
:returns: True if start was initiated and postmaster ports are open, False i... | [
"def",
"start",
"(",
"self",
",",
"timeout",
"=",
"None",
",",
"task",
"=",
"None",
",",
"block_callbacks",
"=",
"False",
",",
"role",
"=",
"None",
")",
":",
"# make sure we close all connections established against",
"# the former node, otherwise, we might get a stalle... | Start PostgreSQL
Waits for postmaster to open ports or terminate so pg_isready can be used to check startup completion
or failure.
:returns: True if start was initiated and postmaster ports are open, False if start failed | [
"Start",
"PostgreSQL"
] | python | train | 37.714286 |
bernardopires/django-tenant-schemas | tenant_schemas/utils.py | https://github.com/bernardopires/django-tenant-schemas/blob/75faf00834e1fb7ed017949bfb54531f6329a8dd/tenant_schemas/utils.py#L53-L61 | def clean_tenant_url(url_string):
"""
Removes the TENANT_TOKEN from a particular string
"""
if hasattr(settings, 'PUBLIC_SCHEMA_URLCONF'):
if (settings.PUBLIC_SCHEMA_URLCONF and
url_string.startswith(settings.PUBLIC_SCHEMA_URLCONF)):
url_string = url_string[len(settin... | [
"def",
"clean_tenant_url",
"(",
"url_string",
")",
":",
"if",
"hasattr",
"(",
"settings",
",",
"'PUBLIC_SCHEMA_URLCONF'",
")",
":",
"if",
"(",
"settings",
".",
"PUBLIC_SCHEMA_URLCONF",
"and",
"url_string",
".",
"startswith",
"(",
"settings",
".",
"PUBLIC_SCHEMA_UR... | Removes the TENANT_TOKEN from a particular string | [
"Removes",
"the",
"TENANT_TOKEN",
"from",
"a",
"particular",
"string"
] | python | train | 40.111111 |
DataBiosphere/dsub | dsub/providers/google_v2_operations.py | https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2_operations.py#L167-L179 | def get_last_update(op):
"""Return the most recent timestamp in the operation."""
last_update = get_end_time(op)
if not last_update:
last_event = get_last_event(op)
if last_event:
last_update = last_event['timestamp']
if not last_update:
last_update = get_create_time(op)
return last_updat... | [
"def",
"get_last_update",
"(",
"op",
")",
":",
"last_update",
"=",
"get_end_time",
"(",
"op",
")",
"if",
"not",
"last_update",
":",
"last_event",
"=",
"get_last_event",
"(",
"op",
")",
"if",
"last_event",
":",
"last_update",
"=",
"last_event",
"[",
"'timesta... | Return the most recent timestamp in the operation. | [
"Return",
"the",
"most",
"recent",
"timestamp",
"in",
"the",
"operation",
"."
] | python | valid | 23.769231 |
erdc/RAPIDpy | RAPIDpy/inflow/CreateInflowFileFromGriddedRunoff.py | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/inflow/CreateInflowFileFromGriddedRunoff.py#L52-L86 | def read_in_weight_table(self, in_weight_table):
"""
Read in weight table
"""
print("Reading the weight table...")
with open_csv(in_weight_table, "r") as csvfile:
reader = csv.reader(csvfile)
header_row = next(reader)
# check number of ... | [
"def",
"read_in_weight_table",
"(",
"self",
",",
"in_weight_table",
")",
":",
"print",
"(",
"\"Reading the weight table...\"",
")",
"with",
"open_csv",
"(",
"in_weight_table",
",",
"\"r\"",
")",
"as",
"csvfile",
":",
"reader",
"=",
"csv",
".",
"reader",
"(",
"... | Read in weight table | [
"Read",
"in",
"weight",
"table"
] | python | train | 38.714286 |
ericmjl/polcart | polcart/polcart.py | https://github.com/ericmjl/polcart/blob/1d003987f269c14884726205f871dd91de8610ce/polcart/polcart.py#L5-L20 | def to_cartesian(r, theta, theta_units="radians"):
"""
Converts polar r, theta to cartesian x, y.
"""
assert theta_units in ['radians', 'degrees'],\
"kwarg theta_units must specified in radians or degrees"
# Convert to radians
if theta_units == "degrees":
theta = to_radians(thet... | [
"def",
"to_cartesian",
"(",
"r",
",",
"theta",
",",
"theta_units",
"=",
"\"radians\"",
")",
":",
"assert",
"theta_units",
"in",
"[",
"'radians'",
",",
"'degrees'",
"]",
",",
"\"kwarg theta_units must specified in radians or degrees\"",
"# Convert to radians",
"if",
"t... | Converts polar r, theta to cartesian x, y. | [
"Converts",
"polar",
"r",
"theta",
"to",
"cartesian",
"x",
"y",
"."
] | python | train | 25.5 |
log2timeline/plaso | plaso/storage/interface.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/storage/interface.py#L1737-L1745 | def SetStorageProfiler(self, storage_profiler):
"""Sets the storage profiler.
Args:
storage_profiler (StorageProfiler): storage profiler.
"""
self._storage_profiler = storage_profiler
if self._storage_file:
self._storage_file.SetStorageProfiler(storage_profiler) | [
"def",
"SetStorageProfiler",
"(",
"self",
",",
"storage_profiler",
")",
":",
"self",
".",
"_storage_profiler",
"=",
"storage_profiler",
"if",
"self",
".",
"_storage_file",
":",
"self",
".",
"_storage_file",
".",
"SetStorageProfiler",
"(",
"storage_profiler",
")"
] | Sets the storage profiler.
Args:
storage_profiler (StorageProfiler): storage profiler. | [
"Sets",
"the",
"storage",
"profiler",
"."
] | python | train | 31.888889 |
nickoala/telepot | telepot/aio/__init__.py | https://github.com/nickoala/telepot/blob/3792fde251d0f1d5a6ca16c8ad1a71f89360c41d/telepot/aio/__init__.py#L398-L401 | async def unpinChatMessage(self, chat_id):
""" See: https://core.telegram.org/bots/api#unpinchatmessage """
p = _strip(locals())
return await self._api_request('unpinChatMessage', _rectify(p)) | [
"async",
"def",
"unpinChatMessage",
"(",
"self",
",",
"chat_id",
")",
":",
"p",
"=",
"_strip",
"(",
"locals",
"(",
")",
")",
"return",
"await",
"self",
".",
"_api_request",
"(",
"'unpinChatMessage'",
",",
"_rectify",
"(",
"p",
")",
")"
] | See: https://core.telegram.org/bots/api#unpinchatmessage | [
"See",
":",
"https",
":",
"//",
"core",
".",
"telegram",
".",
"org",
"/",
"bots",
"/",
"api#unpinchatmessage"
] | python | train | 53.25 |
globus/globus-cli | globus_cli/commands/bookmark/rename.py | https://github.com/globus/globus-cli/blob/336675ff24da64c5ee487243f39ae39fc49a7e14/globus_cli/commands/bookmark/rename.py#L13-L23 | def bookmark_rename(bookmark_id_or_name, new_bookmark_name):
"""
Executor for `globus bookmark rename`
"""
client = get_client()
bookmark_id = resolve_id_or_name(client, bookmark_id_or_name)["id"]
submit_data = {"name": new_bookmark_name}
res = client.update_bookmark(bookmark_id, submit_da... | [
"def",
"bookmark_rename",
"(",
"bookmark_id_or_name",
",",
"new_bookmark_name",
")",
":",
"client",
"=",
"get_client",
"(",
")",
"bookmark_id",
"=",
"resolve_id_or_name",
"(",
"client",
",",
"bookmark_id_or_name",
")",
"[",
"\"id\"",
"]",
"submit_data",
"=",
"{",
... | Executor for `globus bookmark rename` | [
"Executor",
"for",
"globus",
"bookmark",
"rename"
] | python | train | 32.818182 |
F5Networks/f5-common-python | f5sdk_plugins/fixtures.py | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5sdk_plugins/fixtures.py#L116-L119 | def peer(opt_peer, opt_username, opt_password, scope="module"):
'''peer bigip fixture'''
p = BigIP(opt_peer, opt_username, opt_password)
return p | [
"def",
"peer",
"(",
"opt_peer",
",",
"opt_username",
",",
"opt_password",
",",
"scope",
"=",
"\"module\"",
")",
":",
"p",
"=",
"BigIP",
"(",
"opt_peer",
",",
"opt_username",
",",
"opt_password",
")",
"return",
"p"
] | peer bigip fixture | [
"peer",
"bigip",
"fixture"
] | python | train | 38.5 |
frmdstryr/enamlx | enamlx/core/middleware.py | https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/core/middleware.py#L65-L95 | def convert_enamldef_def_to_func(token_stream):
""" A token stream processor which processes all enaml declarative functions
to allow using `def` instead of `func`. It does this by transforming DEF
tokens to NAME within enamldef blocks and then changing the token value to
`func`.
Notes
-... | [
"def",
"convert_enamldef_def_to_func",
"(",
"token_stream",
")",
":",
"in_enamldef",
"=",
"False",
"depth",
"=",
"0",
"for",
"tok",
"in",
"token_stream",
":",
"if",
"tok",
".",
"type",
"==",
"'ENAMLDEF'",
":",
"in_enamldef",
"=",
"True",
"elif",
"tok",
".",
... | A token stream processor which processes all enaml declarative functions
to allow using `def` instead of `func`. It does this by transforming DEF
tokens to NAME within enamldef blocks and then changing the token value to
`func`.
Notes
------
Use this at your own risk! This was a feature... | [
"A",
"token",
"stream",
"processor",
"which",
"processes",
"all",
"enaml",
"declarative",
"functions",
"to",
"allow",
"using",
"def",
"instead",
"of",
"func",
".",
"It",
"does",
"this",
"by",
"transforming",
"DEF",
"tokens",
"to",
"NAME",
"within",
"enamldef",... | python | train | 35.806452 |
devopshq/youtrack | youtrack/connection.py | https://github.com/devopshq/youtrack/blob/c4ec19aca253ae30ac8eee7976a2f330e480a73b/youtrack/connection.py#L702-L707 | def create_versions(self, project_id, versions):
""" Accepts result of getVersions()
"""
for v in versions:
self.create_version(project_id, v) | [
"def",
"create_versions",
"(",
"self",
",",
"project_id",
",",
"versions",
")",
":",
"for",
"v",
"in",
"versions",
":",
"self",
".",
"create_version",
"(",
"project_id",
",",
"v",
")"
] | Accepts result of getVersions() | [
"Accepts",
"result",
"of",
"getVersions",
"()"
] | python | train | 29 |
gijzelaerr/python-snap7 | snap7/client.py | https://github.com/gijzelaerr/python-snap7/blob/a6db134c7a3a2ef187b9eca04669221d6fc634c3/snap7/client.py#L99-L106 | def get_cpu_info(self):
"""
Retrieves CPU info from client
"""
info = snap7.snap7types.S7CpuInfo()
result = self.library.Cli_GetCpuInfo(self.pointer, byref(info))
check_error(result, context="client")
return info | [
"def",
"get_cpu_info",
"(",
"self",
")",
":",
"info",
"=",
"snap7",
".",
"snap7types",
".",
"S7CpuInfo",
"(",
")",
"result",
"=",
"self",
".",
"library",
".",
"Cli_GetCpuInfo",
"(",
"self",
".",
"pointer",
",",
"byref",
"(",
"info",
")",
")",
"check_er... | Retrieves CPU info from client | [
"Retrieves",
"CPU",
"info",
"from",
"client"
] | python | train | 32.625 |
mikejarrett/pipcheck | pipcheck/checker.py | https://github.com/mikejarrett/pipcheck/blob/2ff47b9fd8914e1764c6e659ef39b77c1b1a12ad/pipcheck/checker.py#L83-L102 | def write_updates_to_csv(self, updates):
"""
Given a list of updates, write the updates out to the provided CSV
file.
Args:
updates (list): List of Update objects.
"""
with open(self._csv_file_name, 'w') as csvfile:
csvwriter = self.csv_writer(csv... | [
"def",
"write_updates_to_csv",
"(",
"self",
",",
"updates",
")",
":",
"with",
"open",
"(",
"self",
".",
"_csv_file_name",
",",
"'w'",
")",
"as",
"csvfile",
":",
"csvwriter",
"=",
"self",
".",
"csv_writer",
"(",
"csvfile",
")",
"csvwriter",
".",
"writerow",... | Given a list of updates, write the updates out to the provided CSV
file.
Args:
updates (list): List of Update objects. | [
"Given",
"a",
"list",
"of",
"updates",
"write",
"the",
"updates",
"out",
"to",
"the",
"provided",
"CSV",
"file",
"."
] | python | train | 31.45 |
matousc89/padasip | padasip/filters/ap.py | https://github.com/matousc89/padasip/blob/c969eadd7fa181a84da0554d737fc13c6450d16f/padasip/filters/ap.py#L205-L227 | def adapt(self, d, x):
"""
Adapt weights according one desired value and its input.
**Args:**
* `d` : desired value (float)
* `x` : input array (1-dimensional array)
"""
# create input matrix and target vector
self.x_mem[:,1:] = self.x_mem[:,:-1]
... | [
"def",
"adapt",
"(",
"self",
",",
"d",
",",
"x",
")",
":",
"# create input matrix and target vector",
"self",
".",
"x_mem",
"[",
":",
",",
"1",
":",
"]",
"=",
"self",
".",
"x_mem",
"[",
":",
",",
":",
"-",
"1",
"]",
"self",
".",
"x_mem",
"[",
":"... | Adapt weights according one desired value and its input.
**Args:**
* `d` : desired value (float)
* `x` : input array (1-dimensional array) | [
"Adapt",
"weights",
"according",
"one",
"desired",
"value",
"and",
"its",
"input",
"."
] | python | train | 32.565217 |
spyder-ide/spyder | spyder/utils/programs.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/programs.py#L486-L515 | def is_python_interpreter(filename):
"""Evaluate wether a file is a python interpreter or not."""
real_filename = os.path.realpath(filename) # To follow symlink if existent
if (not osp.isfile(real_filename) or
not is_python_interpreter_valid_name(filename)):
return False
elif is_... | [
"def",
"is_python_interpreter",
"(",
"filename",
")",
":",
"real_filename",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"filename",
")",
"# To follow symlink if existent\r",
"if",
"(",
"not",
"osp",
".",
"isfile",
"(",
"real_filename",
")",
"or",
"not",
"is_... | Evaluate wether a file is a python interpreter or not. | [
"Evaluate",
"wether",
"a",
"file",
"is",
"a",
"python",
"interpreter",
"or",
"not",
"."
] | python | train | 38.633333 |
apache/incubator-mxnet | python/mxnet/optimizer/optimizer.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/optimizer/optimizer.py#L1701-L1710 | def get_states(self, dump_optimizer=False):
"""Gets updater states.
Parameters
----------
dump_optimizer : bool, default False
Whether to also save the optimizer itself. This would also save optimizer
information such as learning rate and weight decay schedules.
... | [
"def",
"get_states",
"(",
"self",
",",
"dump_optimizer",
"=",
"False",
")",
":",
"return",
"pickle",
".",
"dumps",
"(",
"(",
"self",
".",
"states",
",",
"self",
".",
"optimizer",
")",
"if",
"dump_optimizer",
"else",
"self",
".",
"states",
")"
] | Gets updater states.
Parameters
----------
dump_optimizer : bool, default False
Whether to also save the optimizer itself. This would also save optimizer
information such as learning rate and weight decay schedules. | [
"Gets",
"updater",
"states",
"."
] | python | train | 41.6 |
pymc-devs/pymc | pymc/distributions.py | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L1939-L1958 | def mv_normal_like(x, mu, tau):
R"""
Multivariate normal log-likelihood
.. math::
f(x \mid \pi, T) = \frac{|T|^{1/2}}{(2\pi)^{1/2}} \exp\left\{ -\frac{1}{2} (x-\mu)^{\prime}T(x-\mu) \right\}
:Parameters:
- `x` : (n,k)
- `mu` : (k) Location parameter sequence.
- `Tau` : (k,k) ... | [
"def",
"mv_normal_like",
"(",
"x",
",",
"mu",
",",
"tau",
")",
":",
"# TODO: Vectorize in Fortran",
"if",
"len",
"(",
"np",
".",
"shape",
"(",
"x",
")",
")",
">",
"1",
":",
"return",
"np",
".",
"sum",
"(",
"[",
"flib",
".",
"prec_mvnorm",
"(",
"r",... | R"""
Multivariate normal log-likelihood
.. math::
f(x \mid \pi, T) = \frac{|T|^{1/2}}{(2\pi)^{1/2}} \exp\left\{ -\frac{1}{2} (x-\mu)^{\prime}T(x-\mu) \right\}
:Parameters:
- `x` : (n,k)
- `mu` : (k) Location parameter sequence.
- `Tau` : (k,k) Positive definite precision matrix.
... | [
"R",
"Multivariate",
"normal",
"log",
"-",
"likelihood"
] | python | train | 30 |
SKA-ScienceDataProcessor/integration-prototype | sip/science_pipeline_workflows/ingest_visibilities/recv/async_recv.py | https://github.com/SKA-ScienceDataProcessor/integration-prototype/blob/8c8006de6ad71dcd44114b0338780738079c87d4/sip/science_pipeline_workflows/ingest_visibilities/recv/async_recv.py#L50-L114 | def process_buffer(self, i_block, receive_buffer):
"""Blocking function to process the received heaps.
This is run in an executor.
"""
self._log.info("Worker thread processing block %i", i_block)
time_overall0 = time.time()
time_unpack = 0.0
time_write = 0.0
... | [
"def",
"process_buffer",
"(",
"self",
",",
"i_block",
",",
"receive_buffer",
")",
":",
"self",
".",
"_log",
".",
"info",
"(",
"\"Worker thread processing block %i\"",
",",
"i_block",
")",
"time_overall0",
"=",
"time",
".",
"time",
"(",
")",
"time_unpack",
"=",... | Blocking function to process the received heaps.
This is run in an executor. | [
"Blocking",
"function",
"to",
"process",
"the",
"received",
"heaps",
".",
"This",
"is",
"run",
"in",
"an",
"executor",
"."
] | python | train | 45.907692 |
gunthercox/ChatterBot | chatterbot/parsing.py | https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/parsing.py#L580-L636 | def date_from_relative_week_year(base_date, time, dow, ordinal=1):
"""
Converts relative day to time
Eg. this tuesday, last tuesday
"""
# If there is an ordinal (next 3 weeks) => return a start and end range
# Reset date to start of the day
relative_date = datetime(base_date.year, base_date.... | [
"def",
"date_from_relative_week_year",
"(",
"base_date",
",",
"time",
",",
"dow",
",",
"ordinal",
"=",
"1",
")",
":",
"# If there is an ordinal (next 3 weeks) => return a start and end range",
"# Reset date to start of the day",
"relative_date",
"=",
"datetime",
"(",
"base_da... | Converts relative day to time
Eg. this tuesday, last tuesday | [
"Converts",
"relative",
"day",
"to",
"time",
"Eg",
".",
"this",
"tuesday",
"last",
"tuesday"
] | python | train | 48.263158 |
mitsei/dlkit | dlkit/json_/utilities.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/utilities.py#L158-L176 | def convert_dict_to_datetime(obj_map):
"""converts dictionary representations of datetime back to datetime obj"""
converted_map = {}
for key, value in obj_map.items():
if isinstance(value, dict) and 'tzinfo' in value.keys():
converted_map[key] = datetime.datetime(**value)
elif is... | [
"def",
"convert_dict_to_datetime",
"(",
"obj_map",
")",
":",
"converted_map",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"obj_map",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
"and",
"'tzinfo'",
"in",
"value",
... | converts dictionary representations of datetime back to datetime obj | [
"converts",
"dictionary",
"representations",
"of",
"datetime",
"back",
"to",
"datetime",
"obj"
] | python | train | 43.736842 |
mitsei/dlkit | dlkit/json_/authorization/objects.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/authorization/objects.py#L137-L149 | def get_trust_id(self):
"""Gets the ``Trust`` ``Id`` for this authorization.
return: (osid.id.Id) - the trust ``Id``
raise: IllegalState - ``has_trust()`` is ``false``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid... | [
"def",
"get_trust_id",
"(",
"self",
")",
":",
"# Implemented from template for osid.resource.Resource.get_avatar_id_template",
"if",
"not",
"bool",
"(",
"self",
".",
"_my_map",
"[",
"'trustId'",
"]",
")",
":",
"raise",
"errors",
".",
"IllegalState",
"(",
"'this Author... | Gets the ``Trust`` ``Id`` for this authorization.
return: (osid.id.Id) - the trust ``Id``
raise: IllegalState - ``has_trust()`` is ``false``
*compliance: mandatory -- This method must be implemented.* | [
"Gets",
"the",
"Trust",
"Id",
"for",
"this",
"authorization",
"."
] | python | train | 40.692308 |
holgern/pyedflib | pyedflib/edfwriter.py | https://github.com/holgern/pyedflib/blob/0f787fc1202b84a6f30d098296acf72666eaeeb4/pyedflib/edfwriter.py#L552-L566 | def setTransducer(self, edfsignal, transducer):
"""
Sets the transducer of signal edfsignal
:param edfsignal: int
:param transducer: str
Notes
-----
This function is optional for every signal and can be called only after opening a file in writemode and before th... | [
"def",
"setTransducer",
"(",
"self",
",",
"edfsignal",
",",
"transducer",
")",
":",
"if",
"(",
"edfsignal",
"<",
"0",
"or",
"edfsignal",
">",
"self",
".",
"n_channels",
")",
":",
"raise",
"ChannelDoesNotExist",
"(",
"edfsignal",
")",
"self",
".",
"channels... | Sets the transducer of signal edfsignal
:param edfsignal: int
:param transducer: str
Notes
-----
This function is optional for every signal and can be called only after opening a file in writemode and before the first sample write action. | [
"Sets",
"the",
"transducer",
"of",
"signal",
"edfsignal"
] | python | train | 36.2 |
log2timeline/dfvfs | dfvfs/helpers/volume_scanner.py | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/volume_scanner.py#L230-L270 | def _NormalizedVolumeIdentifiers(
self, volume_system, volume_identifiers, prefix='v'):
"""Normalizes volume identifiers.
Args:
volume_system (VolumeSystem): volume system.
volume_identifiers (list[int|str]): allowed volume identifiers, formatted
as an integer or string with prefix.... | [
"def",
"_NormalizedVolumeIdentifiers",
"(",
"self",
",",
"volume_system",
",",
"volume_identifiers",
",",
"prefix",
"=",
"'v'",
")",
":",
"normalized_volume_identifiers",
"=",
"[",
"]",
"for",
"volume_identifier",
"in",
"volume_identifiers",
":",
"if",
"isinstance",
... | Normalizes volume identifiers.
Args:
volume_system (VolumeSystem): volume system.
volume_identifiers (list[int|str]): allowed volume identifiers, formatted
as an integer or string with prefix.
prefix (Optional[str]): volume identifier prefix.
Returns:
list[str]: volume identi... | [
"Normalizes",
"volume",
"identifiers",
"."
] | python | train | 33.95122 |
Fantomas42/django-blog-zinnia | zinnia/sitemaps.py | https://github.com/Fantomas42/django-blog-zinnia/blob/b4949304b104a8e1a7a7a0773cbfd024313c3a15/zinnia/sitemaps.py#L50-L59 | def items(self):
"""
Get a queryset, cache infos for standardized access to them later
then compute the maximum of entries to define the priority
of each items.
"""
queryset = self.get_queryset()
self.cache_infos(queryset)
self.set_max_entries()
re... | [
"def",
"items",
"(",
"self",
")",
":",
"queryset",
"=",
"self",
".",
"get_queryset",
"(",
")",
"self",
".",
"cache_infos",
"(",
"queryset",
")",
"self",
".",
"set_max_entries",
"(",
")",
"return",
"queryset"
] | Get a queryset, cache infos for standardized access to them later
then compute the maximum of entries to define the priority
of each items. | [
"Get",
"a",
"queryset",
"cache",
"infos",
"for",
"standardized",
"access",
"to",
"them",
"later",
"then",
"compute",
"the",
"maximum",
"of",
"entries",
"to",
"define",
"the",
"priority",
"of",
"each",
"items",
"."
] | python | train | 32.4 |
IndicoDataSolutions/IndicoIo-python | indicoio/docx/docx_extraction.py | https://github.com/IndicoDataSolutions/IndicoIo-python/blob/6f262a23f09d76fede63d1ccb87f9f7cf2cfc8aa/indicoio/docx/docx_extraction.py#L6-L25 | def docx_extraction(docx, cloud=None, batch=False, api_key=None, version=None, **kwargs):
"""
Given a .docx file, returns the raw text associated with the given .docx file.
The .docx file may be provided as base64 encoded data or as a filepath.
Example usage:
.. code-block:: python
>>> fro... | [
"def",
"docx_extraction",
"(",
"docx",
",",
"cloud",
"=",
"None",
",",
"batch",
"=",
"False",
",",
"api_key",
"=",
"None",
",",
"version",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"docx",
"=",
"docx_preprocess",
"(",
"docx",
",",
"batch",
"=",... | Given a .docx file, returns the raw text associated with the given .docx file.
The .docx file may be provided as base64 encoded data or as a filepath.
Example usage:
.. code-block:: python
>>> from indicoio import docx_extraction
>>> results = docx_extraction(docx_file)
:param docx: Th... | [
"Given",
"a",
".",
"docx",
"file",
"returns",
"the",
"raw",
"text",
"associated",
"with",
"the",
"given",
".",
"docx",
"file",
".",
"The",
".",
"docx",
"file",
"may",
"be",
"provided",
"as",
"base64",
"encoded",
"data",
"or",
"as",
"a",
"filepath",
"."... | python | train | 37.1 |
horazont/aioxmpp | aioxmpp/roster/service.py | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/roster/service.py#L122-L131 | def from_xso_item(cls, xso_item):
"""
Create a :class:`Item` with the :attr:`jid` set to the
:attr:`.xso.Item.jid` obtained from `xso_item`. Then update that
instance with `xso_item` using :meth:`update_from_xso_item` and return
it.
"""
item = cls(xso_item.jid)
... | [
"def",
"from_xso_item",
"(",
"cls",
",",
"xso_item",
")",
":",
"item",
"=",
"cls",
"(",
"xso_item",
".",
"jid",
")",
"item",
".",
"update_from_xso_item",
"(",
"xso_item",
")",
"return",
"item"
] | Create a :class:`Item` with the :attr:`jid` set to the
:attr:`.xso.Item.jid` obtained from `xso_item`. Then update that
instance with `xso_item` using :meth:`update_from_xso_item` and return
it. | [
"Create",
"a",
":",
"class",
":",
"Item",
"with",
"the",
":",
"attr",
":",
"jid",
"set",
"to",
"the",
":",
"attr",
":",
".",
"xso",
".",
"Item",
".",
"jid",
"obtained",
"from",
"xso_item",
".",
"Then",
"update",
"that",
"instance",
"with",
"xso_item"... | python | train | 37.2 |
googleapis/google-cloud-python | datastore/google/cloud/datastore/transaction.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/transaction.py#L246-L262 | def put(self, entity):
"""Adds an entity to be committed.
Ensures the transaction is not marked readonly.
Please see documentation at
:meth:`~google.cloud.datastore.batch.Batch.put`
:type entity: :class:`~google.cloud.datastore.entity.Entity`
:param entity: the entity t... | [
"def",
"put",
"(",
"self",
",",
"entity",
")",
":",
"if",
"self",
".",
"_options",
".",
"HasField",
"(",
"\"read_only\"",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Transaction is read only\"",
")",
"else",
":",
"super",
"(",
"Transaction",
",",
"self",
")... | Adds an entity to be committed.
Ensures the transaction is not marked readonly.
Please see documentation at
:meth:`~google.cloud.datastore.batch.Batch.put`
:type entity: :class:`~google.cloud.datastore.entity.Entity`
:param entity: the entity to be saved.
:raises: :cla... | [
"Adds",
"an",
"entity",
"to",
"be",
"committed",
"."
] | python | train | 34.823529 |
gem/oq-engine | openquake/hazardlib/contexts.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/contexts.py#L323-L368 | def disaggregate(self, sitecol, ruptures, iml4, truncnorm, epsilons,
monitor=Monitor()):
"""
Disaggregate (separate) PoE in different contributions.
:param sitecol: a SiteCollection with N sites
:param ruptures: an iterator over ruptures with the same TRT
:p... | [
"def",
"disaggregate",
"(",
"self",
",",
"sitecol",
",",
"ruptures",
",",
"iml4",
",",
"truncnorm",
",",
"epsilons",
",",
"monitor",
"=",
"Monitor",
"(",
")",
")",
":",
"acc",
"=",
"AccumDict",
"(",
"accum",
"=",
"[",
"]",
")",
"ctx_mon",
"=",
"monit... | Disaggregate (separate) PoE in different contributions.
:param sitecol: a SiteCollection with N sites
:param ruptures: an iterator over ruptures with the same TRT
:param iml4: a 4d array of IMLs of shape (N, R, M, P)
:param truncnorm: an instance of scipy.stats.truncnorm
:param ... | [
"Disaggregate",
"(",
"separate",
")",
"PoE",
"in",
"different",
"contributions",
"."
] | python | train | 49.086957 |
Chilipp/psyplot | psyplot/plotter.py | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/plotter.py#L60-L83 | def format_time(x):
"""Formats date values
This function formats :class:`datetime.datetime` and
:class:`datetime.timedelta` objects (and the corresponding numpy objects)
using the :func:`xarray.core.formatting.format_timestamp` and the
:func:`xarray.core.formatting.format_timedelta` functions.
... | [
"def",
"format_time",
"(",
"x",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"(",
"datetime64",
",",
"datetime",
")",
")",
":",
"return",
"format_timestamp",
"(",
"x",
")",
"elif",
"isinstance",
"(",
"x",
",",
"(",
"timedelta64",
",",
"timedelta",
")",... | Formats date values
This function formats :class:`datetime.datetime` and
:class:`datetime.timedelta` objects (and the corresponding numpy objects)
using the :func:`xarray.core.formatting.format_timestamp` and the
:func:`xarray.core.formatting.format_timedelta` functions.
Parameters
----------
... | [
"Formats",
"date",
"values"
] | python | train | 32.041667 |
niklasf/python-chess | chess/__init__.py | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L1237-L1253 | def copy(self: BaseBoardT) -> BaseBoardT:
"""Creates a copy of the board."""
board = type(self)(None)
board.pawns = self.pawns
board.knights = self.knights
board.bishops = self.bishops
board.rooks = self.rooks
board.queens = self.queens
board.kings = self... | [
"def",
"copy",
"(",
"self",
":",
"BaseBoardT",
")",
"->",
"BaseBoardT",
":",
"board",
"=",
"type",
"(",
"self",
")",
"(",
"None",
")",
"board",
".",
"pawns",
"=",
"self",
".",
"pawns",
"board",
".",
"knights",
"=",
"self",
".",
"knights",
"board",
... | Creates a copy of the board. | [
"Creates",
"a",
"copy",
"of",
"the",
"board",
"."
] | python | train | 31.117647 |
google/grr | grr/server/grr_response_server/export.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/export.py#L817-L823 | def Convert(self, metadata, config, token=None):
"""Converts DNSClientConfiguration to ExportedDNSClientConfiguration."""
result = ExportedDNSClientConfiguration(
metadata=metadata,
dns_servers=" ".join(config.dns_server),
dns_suffixes=" ".join(config.dns_suffix))
yield result | [
"def",
"Convert",
"(",
"self",
",",
"metadata",
",",
"config",
",",
"token",
"=",
"None",
")",
":",
"result",
"=",
"ExportedDNSClientConfiguration",
"(",
"metadata",
"=",
"metadata",
",",
"dns_servers",
"=",
"\" \"",
".",
"join",
"(",
"config",
".",
"dns_s... | Converts DNSClientConfiguration to ExportedDNSClientConfiguration. | [
"Converts",
"DNSClientConfiguration",
"to",
"ExportedDNSClientConfiguration",
"."
] | python | train | 43.857143 |
BenDoan/perform | perform.py | https://github.com/BenDoan/perform/blob/3434c5c68fb7661d74f03404c71bb5fbebe1900f/perform.py#L128-L140 | def get_programs():
"""Returns a generator that yields the available executable programs
:returns: a generator that yields the programs available after a refresh_listing()
:rtype: generator
"""
programs = []
os.environ['PATH'] += os.pathsep + os.getcwd()
for p in os.environ['PATH'].split(os... | [
"def",
"get_programs",
"(",
")",
":",
"programs",
"=",
"[",
"]",
"os",
".",
"environ",
"[",
"'PATH'",
"]",
"+=",
"os",
".",
"pathsep",
"+",
"os",
".",
"getcwd",
"(",
")",
"for",
"p",
"in",
"os",
".",
"environ",
"[",
"'PATH'",
"]",
".",
"split",
... | Returns a generator that yields the available executable programs
:returns: a generator that yields the programs available after a refresh_listing()
:rtype: generator | [
"Returns",
"a",
"generator",
"that",
"yields",
"the",
"available",
"executable",
"programs"
] | python | train | 35.384615 |
saltstack/salt | salt/utils/path.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/path.py#L41-L73 | def islink(path):
'''
Equivalent to os.path.islink()
'''
if six.PY3 or not salt.utils.platform.is_windows():
return os.path.islink(path)
if not HAS_WIN32FILE:
log.error('Cannot check if %s is a link, missing required modules', path)
if not _is_reparse_point(path):
retur... | [
"def",
"islink",
"(",
"path",
")",
":",
"if",
"six",
".",
"PY3",
"or",
"not",
"salt",
".",
"utils",
".",
"platform",
".",
"is_windows",
"(",
")",
":",
"return",
"os",
".",
"path",
".",
"islink",
"(",
"path",
")",
"if",
"not",
"HAS_WIN32FILE",
":",
... | Equivalent to os.path.islink() | [
"Equivalent",
"to",
"os",
".",
"path",
".",
"islink",
"()"
] | python | train | 31.484848 |
cdgriffith/Reusables | reusables/cli.py | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/cli.py#L204-L231 | def cp(src, dst, overwrite=False):
"""
Copy files to a new location.
:param src: list (or string) of paths of files to copy
:param dst: file or folder to copy item(s) to
:param overwrite: IF the file already exists, should I overwrite it?
"""
if not isinstance(src, list):
src = [sr... | [
"def",
"cp",
"(",
"src",
",",
"dst",
",",
"overwrite",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"src",
",",
"list",
")",
":",
"src",
"=",
"[",
"src",
"]",
"dst",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"dst",
")",
"dst_fo... | Copy files to a new location.
:param src: list (or string) of paths of files to copy
:param dst: file or folder to copy item(s) to
:param overwrite: IF the file already exists, should I overwrite it? | [
"Copy",
"files",
"to",
"a",
"new",
"location",
"."
] | python | train | 32.642857 |
5monkeys/django-enumfield | django_enumfield/enum.py | https://github.com/5monkeys/django-enumfield/blob/6cf20c0fba013d39960af0f4d2c9a3b399955eb3/django_enumfield/enum.py#L69-L77 | def choices(cls, blank=False):
""" Choices for Enum
:return: List of tuples (<value>, <human-readable value>)
:rtype: list
"""
choices = sorted([(key, value) for key, value in cls.values.items()], key=lambda x: x[0])
if blank:
choices.insert(0, ('', Enum.Value... | [
"def",
"choices",
"(",
"cls",
",",
"blank",
"=",
"False",
")",
":",
"choices",
"=",
"sorted",
"(",
"[",
"(",
"key",
",",
"value",
")",
"for",
"key",
",",
"value",
"in",
"cls",
".",
"values",
".",
"items",
"(",
")",
"]",
",",
"key",
"=",
"lambda... | Choices for Enum
:return: List of tuples (<value>, <human-readable value>)
:rtype: list | [
"Choices",
"for",
"Enum",
":",
"return",
":",
"List",
"of",
"tuples",
"(",
"<value",
">",
"<human",
"-",
"readable",
"value",
">",
")",
":",
"rtype",
":",
"list"
] | python | train | 39.555556 |
swilson/aqualogic | aqualogic/core.py | https://github.com/swilson/aqualogic/blob/b6e904363efc4f64c70aae127d040079587ecbc6/aqualogic/core.py#L392-L402 | def states(self):
"""Returns a set containing the enabled states."""
state_list = []
for state in States:
if state.value & self._states != 0:
state_list.append(state)
if (self._flashing_states & States.FILTER) != 0:
state_list.append(States.FILTER... | [
"def",
"states",
"(",
"self",
")",
":",
"state_list",
"=",
"[",
"]",
"for",
"state",
"in",
"States",
":",
"if",
"state",
".",
"value",
"&",
"self",
".",
"_states",
"!=",
"0",
":",
"state_list",
".",
"append",
"(",
"state",
")",
"if",
"(",
"self",
... | Returns a set containing the enabled states. | [
"Returns",
"a",
"set",
"containing",
"the",
"enabled",
"states",
"."
] | python | train | 31.636364 |
fracpete/python-weka-wrapper | python/weka/core/tokenizers.py | https://github.com/fracpete/python-weka-wrapper/blob/e865915146faf40d3bbfedb440328d1360541633/python/weka/core/tokenizers.py#L42-L52 | def next(self):
"""
Reads the next dataset row.
:return: the next row
:rtype: Instance
"""
if not self.__has_more():
raise StopIteration()
else:
return javabridge.get_env().get_string(self.__next()) | [
"def",
"next",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"__has_more",
"(",
")",
":",
"raise",
"StopIteration",
"(",
")",
"else",
":",
"return",
"javabridge",
".",
"get_env",
"(",
")",
".",
"get_string",
"(",
"self",
".",
"__next",
"(",
")",
... | Reads the next dataset row.
:return: the next row
:rtype: Instance | [
"Reads",
"the",
"next",
"dataset",
"row",
"."
] | python | train | 24.454545 |
anthill/koala | koala/excellib.py | https://github.com/anthill/koala/blob/393089fe081380506e73235db18a32b4e078d222/koala/excellib.py#L970-L995 | def xirr(values, dates, guess=0):
"""
Function to calculate the internal rate of return (IRR) using payments and non-periodic dates. It resembles the
excel function XIRR().
Excel reference: https://support.office.com/en-ie/article/xirr-function-de1242ec-6477-445b-b11b-a303ad9adc9d
:param values: t... | [
"def",
"xirr",
"(",
"values",
",",
"dates",
",",
"guess",
"=",
"0",
")",
":",
"if",
"isinstance",
"(",
"values",
",",
"Range",
")",
":",
"values",
"=",
"values",
".",
"values",
"if",
"isinstance",
"(",
"dates",
",",
"Range",
")",
":",
"dates",
"=",... | Function to calculate the internal rate of return (IRR) using payments and non-periodic dates. It resembles the
excel function XIRR().
Excel reference: https://support.office.com/en-ie/article/xirr-function-de1242ec-6477-445b-b11b-a303ad9adc9d
:param values: the payments of which at least one has to be ne... | [
"Function",
"to",
"calculate",
"the",
"internal",
"rate",
"of",
"return",
"(",
"IRR",
")",
"using",
"payments",
"and",
"non",
"-",
"periodic",
"dates",
".",
"It",
"resembles",
"the",
"excel",
"function",
"XIRR",
"()",
"."
] | python | train | 41.807692 |
pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/ef09f28b858b7ffcd2627ce6a4dc618183a6bc8a/ffn/core.py#L1058-L1070 | def to_price_index(returns, start=100):
"""
Returns a price index given a series of returns.
Args:
* returns: Expects a return series
* start (number): Starting level
Assumes arithmetic returns.
Formula is: cumprod (1+r)
"""
return (returns.replace(to_replace=np.nan, value... | [
"def",
"to_price_index",
"(",
"returns",
",",
"start",
"=",
"100",
")",
":",
"return",
"(",
"returns",
".",
"replace",
"(",
"to_replace",
"=",
"np",
".",
"nan",
",",
"value",
"=",
"0",
")",
"+",
"1",
")",
".",
"cumprod",
"(",
")",
"*",
"start"
] | Returns a price index given a series of returns.
Args:
* returns: Expects a return series
* start (number): Starting level
Assumes arithmetic returns.
Formula is: cumprod (1+r) | [
"Returns",
"a",
"price",
"index",
"given",
"a",
"series",
"of",
"returns",
"."
] | python | train | 25.692308 |
inveniosoftware-attic/invenio-comments | invenio_comments/api.py | https://github.com/inveniosoftware-attic/invenio-comments/blob/62bb6e07c146baf75bf8de80b5896ab2a01a8423/invenio_comments/api.py#L1217-L1238 | def get_user_subscription_to_discussion(recID, uid):
"""
Returns the type of subscription for the given user to this
discussion. This does not check authorizations (for eg. if user
was subscribed, but is suddenly no longer authorized).
:param recID: record ID
:param uid: user id
:return:
... | [
"def",
"get_user_subscription_to_discussion",
"(",
"recID",
",",
"uid",
")",
":",
"user_email",
"=",
"User",
".",
"query",
".",
"get",
"(",
"uid",
")",
".",
"email",
"(",
"emails1",
",",
"emails2",
")",
"=",
"get_users_subscribed_to_discussion",
"(",
"recID",
... | Returns the type of subscription for the given user to this
discussion. This does not check authorizations (for eg. if user
was subscribed, but is suddenly no longer authorized).
:param recID: record ID
:param uid: user id
:return:
- 0 if user is not subscribed to discussion
... | [
"Returns",
"the",
"type",
"of",
"subscription",
"for",
"the",
"given",
"user",
"to",
"this",
"discussion",
".",
"This",
"does",
"not",
"check",
"authorizations",
"(",
"for",
"eg",
".",
"if",
"user",
"was",
"subscribed",
"but",
"is",
"suddenly",
"no",
"long... | python | train | 35 |
inveniosoftware/invenio-admin | invenio_admin/filters.py | https://github.com/inveniosoftware/invenio-admin/blob/b5ff8f7de66d1d6b67efc9f81ff094eb2428f969/invenio_admin/filters.py#L43-L45 | def conv_uuid(self, column, name, **kwargs):
"""Convert UUID filter."""
return [f(column, name, **kwargs) for f in self.uuid_filters] | [
"def",
"conv_uuid",
"(",
"self",
",",
"column",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"[",
"f",
"(",
"column",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
"for",
"f",
"in",
"self",
".",
"uuid_filters",
"]"
] | Convert UUID filter. | [
"Convert",
"UUID",
"filter",
"."
] | python | train | 49 |
jonbretman/jinja-to-js | jinja_to_js/__init__.py | https://github.com/jonbretman/jinja-to-js/blob/0a784b10a83d37a3171c5797547e9fc460c51289/jinja_to_js/__init__.py#L270-L283 | def _get_depencency_var_name(self, dependency):
"""
Returns the variable name assigned to the given dependency or None if the dependency has
not yet been registered.
Args:
dependency (str): Thet dependency that needs to be imported.
Returns:
str or None
... | [
"def",
"_get_depencency_var_name",
"(",
"self",
",",
"dependency",
")",
":",
"for",
"dep_path",
",",
"var_name",
"in",
"self",
".",
"dependencies",
":",
"if",
"dep_path",
"==",
"dependency",
":",
"return",
"var_name"
] | Returns the variable name assigned to the given dependency or None if the dependency has
not yet been registered.
Args:
dependency (str): Thet dependency that needs to be imported.
Returns:
str or None | [
"Returns",
"the",
"variable",
"name",
"assigned",
"to",
"the",
"given",
"dependency",
"or",
"None",
"if",
"the",
"dependency",
"has",
"not",
"yet",
"been",
"registered",
"."
] | python | train | 31.571429 |
gabstopper/smc-python | smc/base/collection.py | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/base/collection.py#L116-L126 | def get(self, index):
"""
Get the element by index. If index is out of bounds for
the internal list, None is returned. Indexes cannot be
negative.
:param int index: retrieve element by positive index in list
:rtype: SubElement or None
"""
if self ... | [
"def",
"get",
"(",
"self",
",",
"index",
")",
":",
"if",
"self",
"and",
"(",
"index",
"<=",
"len",
"(",
"self",
")",
"-",
"1",
")",
":",
"return",
"self",
".",
"_result_cache",
"[",
"index",
"]"
] | Get the element by index. If index is out of bounds for
the internal list, None is returned. Indexes cannot be
negative.
:param int index: retrieve element by positive index in list
:rtype: SubElement or None | [
"Get",
"the",
"element",
"by",
"index",
".",
"If",
"index",
"is",
"out",
"of",
"bounds",
"for",
"the",
"internal",
"list",
"None",
"is",
"returned",
".",
"Indexes",
"cannot",
"be",
"negative",
".",
":",
"param",
"int",
"index",
":",
"retrieve",
"element"... | python | train | 34.818182 |
mattjj/pyslds | pyslds/states.py | https://github.com/mattjj/pyslds/blob/c505c2bd05a5549d450b518f02493b68ed12e590/pyslds/states.py#L853-L874 | def heldout_log_likelihood(self, test_mask=None):
"""
Compute the log likelihood of the masked data given the latent
discrete and continuous states.
"""
if test_mask is None:
# If a test mask is not supplied, use the negation of this object's mask
if self.... | [
"def",
"heldout_log_likelihood",
"(",
"self",
",",
"test_mask",
"=",
"None",
")",
":",
"if",
"test_mask",
"is",
"None",
":",
"# If a test mask is not supplied, use the negation of this object's mask",
"if",
"self",
".",
"mask",
"is",
"None",
":",
"return",
"0",
"els... | Compute the log likelihood of the masked data given the latent
discrete and continuous states. | [
"Compute",
"the",
"log",
"likelihood",
"of",
"the",
"masked",
"data",
"given",
"the",
"latent",
"discrete",
"and",
"continuous",
"states",
"."
] | python | train | 39.909091 |
gem/oq-engine | openquake/calculators/views.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L51-L91 | def form(value):
"""
Format numbers in a nice way.
>>> form(0)
'0'
>>> form(0.0)
'0.0'
>>> form(0.0001)
'1.000E-04'
>>> form(1003.4)
'1,003'
>>> form(103.4)
'103'
>>> form(9.3)
'9.30000'
>>> form(-1.2)
'-1.2'
"""
if isinstance(value, FLOAT + INT):... | [
"def",
"form",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"FLOAT",
"+",
"INT",
")",
":",
"if",
"value",
"<=",
"0",
":",
"return",
"str",
"(",
"value",
")",
"elif",
"value",
"<",
".001",
":",
"return",
"'%.3E'",
"%",
"value",
"... | Format numbers in a nice way.
>>> form(0)
'0'
>>> form(0.0)
'0.0'
>>> form(0.0001)
'1.000E-04'
>>> form(1003.4)
'1,003'
>>> form(103.4)
'103'
>>> form(9.3)
'9.30000'
>>> form(-1.2)
'-1.2' | [
"Format",
"numbers",
"in",
"a",
"nice",
"way",
"."
] | python | train | 24.365854 |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_policer.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_policer.py#L37-L49 | def police_priority_map_conform_map_pri1_conform(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
police_priority_map = ET.SubElement(config, "police-priority-map", xmlns="urn:brocade.com:mgmt:brocade-policer")
name_key = ET.SubElement(police_priority_map... | [
"def",
"police_priority_map_conform_map_pri1_conform",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"police_priority_map",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"police-priority-map\"",
... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 49.846154 |
frigg/frigg-worker | frigg_worker/deployments.py | https://github.com/frigg/frigg-worker/blob/8c215cd8f5a27ff9f5a4fedafe93d2ef0fbca86c/frigg_worker/deployments.py#L86-L96 | def load_preset(self):
"""
Loads preset if it is specified in the .frigg.yml
"""
if 'preset' in self.settings.preview:
with open(os.path.join(os.path.dirname(__file__), 'presets.yaml')) as f:
presets = yaml.load(f.read())
if self.settings.preview[... | [
"def",
"load_preset",
"(",
"self",
")",
":",
"if",
"'preset'",
"in",
"self",
".",
"settings",
".",
"preview",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'presets.yaml'... | Loads preset if it is specified in the .frigg.yml | [
"Loads",
"preset",
"if",
"it",
"is",
"specified",
"in",
"the",
".",
"frigg",
".",
"yml"
] | python | train | 39.363636 |
saltstack/salt | salt/utils/win_update.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_update.py#L169-L242 | def summary(self):
'''
Create a dictionary with a summary of the updates in the collection.
Returns:
dict: Summary of the contents of the collection
.. code-block:: cfg
Summary of Updates:
{'Total': <total number of updates returned>,
'... | [
"def",
"summary",
"(",
"self",
")",
":",
"# https://msdn.microsoft.com/en-us/library/windows/desktop/aa386099(v=vs.85).aspx",
"if",
"self",
".",
"count",
"(",
")",
"==",
"0",
":",
"return",
"'Nothing to return'",
"# Build a dictionary containing a summary of updates available",
... | Create a dictionary with a summary of the updates in the collection.
Returns:
dict: Summary of the contents of the collection
.. code-block:: cfg
Summary of Updates:
{'Total': <total number of updates returned>,
'Available': <updates that are not downl... | [
"Create",
"a",
"dictionary",
"with",
"a",
"summary",
"of",
"the",
"updates",
"in",
"the",
"collection",
"."
] | python | train | 37.040541 |
dls-controls/pymalcolm | malcolm/core/notifier.py | https://github.com/dls-controls/pymalcolm/blob/80ea667e4da26365a6cebc0249f52fdc744bd983/malcolm/core/notifier.py#L217-L246 | def handle_subscribe(self, request, path):
# type: (Subscribe, List[str]) -> CallbackResponses
"""Add to the list of request to notify, and notify the initial value of
the data held
Args:
request (Subscribe): The subscribe request
path (list): The relative path f... | [
"def",
"handle_subscribe",
"(",
"self",
",",
"request",
",",
"path",
")",
":",
"# type: (Subscribe, List[str]) -> CallbackResponses",
"ret",
"=",
"[",
"]",
"if",
"path",
":",
"# Recurse down",
"name",
"=",
"path",
"[",
"0",
"]",
"if",
"name",
"not",
"in",
"s... | Add to the list of request to notify, and notify the initial value of
the data held
Args:
request (Subscribe): The subscribe request
path (list): The relative path from ourself
Returns:
list: [(callback, Response)] that need to be called | [
"Add",
"to",
"the",
"list",
"of",
"request",
"to",
"notify",
"and",
"notify",
"the",
"initial",
"value",
"of",
"the",
"data",
"held"
] | python | train | 37.133333 |
squaresLab/BugZoo | bugzoo/client/dockerm.py | https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/client/dockerm.py#L18-L28 | def has_image(self, name: str) -> bool:
"""
Determines whether the server has a Docker image with a given name.
"""
path = "docker/images/{}".format(name)
r = self.__api.head(path)
if r.status_code == 204:
return True
elif r.status_code == 404:
... | [
"def",
"has_image",
"(",
"self",
",",
"name",
":",
"str",
")",
"->",
"bool",
":",
"path",
"=",
"\"docker/images/{}\"",
".",
"format",
"(",
"name",
")",
"r",
"=",
"self",
".",
"__api",
".",
"head",
"(",
"path",
")",
"if",
"r",
".",
"status_code",
"=... | Determines whether the server has a Docker image with a given name. | [
"Determines",
"whether",
"the",
"server",
"has",
"a",
"Docker",
"image",
"with",
"a",
"given",
"name",
"."
] | python | train | 34.090909 |
log2timeline/dfvfs | dfvfs/file_io/raw_file_io.py | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/file_io/raw_file_io.py#L33-L41 | def _Close(self):
"""Closes the file-like object."""
# pylint: disable=protected-access
super(RawFile, self)._Close()
for file_object in self._file_objects:
file_object.close()
self._file_objects = [] | [
"def",
"_Close",
"(",
"self",
")",
":",
"# pylint: disable=protected-access",
"super",
"(",
"RawFile",
",",
"self",
")",
".",
"_Close",
"(",
")",
"for",
"file_object",
"in",
"self",
".",
"_file_objects",
":",
"file_object",
".",
"close",
"(",
")",
"self",
... | Closes the file-like object. | [
"Closes",
"the",
"file",
"-",
"like",
"object",
"."
] | python | train | 24.444444 |
notifiers/notifiers | notifiers/utils/schema/formats.py | https://github.com/notifiers/notifiers/blob/6dd8aafff86935dbb4763db9c56f9cdd7fc08b65/notifiers/utils/schema/formats.py#L57-L61 | def is_valid_port(instance: int):
"""Validates data is a valid port"""
if not isinstance(instance, (int, str)):
return True
return int(instance) in range(65535) | [
"def",
"is_valid_port",
"(",
"instance",
":",
"int",
")",
":",
"if",
"not",
"isinstance",
"(",
"instance",
",",
"(",
"int",
",",
"str",
")",
")",
":",
"return",
"True",
"return",
"int",
"(",
"instance",
")",
"in",
"range",
"(",
"65535",
")"
] | Validates data is a valid port | [
"Validates",
"data",
"is",
"a",
"valid",
"port"
] | python | train | 35.2 |
aio-libs/aiohttp-devtools | aiohttp_devtools/start/template/app/settings.py | https://github.com/aio-libs/aiohttp-devtools/blob/e9ea6feb43558e6e64595ea0ea5613f226cba81f/aiohttp_devtools/start/template/app/settings.py#L48-L76 | def substitute_environ(self):
"""
Substitute environment variables into settings.
"""
for attr_name in dir(self):
if attr_name.startswith('_') or attr_name.upper() != attr_name:
continue
orig_value = getattr(self, attr_name)
is_require... | [
"def",
"substitute_environ",
"(",
"self",
")",
":",
"for",
"attr_name",
"in",
"dir",
"(",
"self",
")",
":",
"if",
"attr_name",
".",
"startswith",
"(",
"'_'",
")",
"or",
"attr_name",
".",
"upper",
"(",
")",
"!=",
"attr_name",
":",
"continue",
"orig_value"... | Substitute environment variables into settings. | [
"Substitute",
"environment",
"variables",
"into",
"settings",
"."
] | python | train | 51.448276 |
calmjs/calmjs | src/calmjs/toolchain.py | https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/toolchain.py#L412-L483 | def toolchain_spec_prepare_loaderplugins(
toolchain, spec,
loaderplugin_read_key,
handler_sourcepath_key,
loaderplugin_sourcepath_map_key=LOADERPLUGIN_SOURCEPATH_MAPS):
"""
A standard helper function for combining the filtered (e.g. using
``spec_update_sourcepath_filter_loade... | [
"def",
"toolchain_spec_prepare_loaderplugins",
"(",
"toolchain",
",",
"spec",
",",
"loaderplugin_read_key",
",",
"handler_sourcepath_key",
",",
"loaderplugin_sourcepath_map_key",
"=",
"LOADERPLUGIN_SOURCEPATH_MAPS",
")",
":",
"# ensure the registry is applied to the spec",
"registr... | A standard helper function for combining the filtered (e.g. using
``spec_update_sourcepath_filter_loaderplugins``) loaderplugin
sourcepath mappings back into one that is usable with the standard
``toolchain_spec_compile_entries`` function.
Arguments:
toolchain
The toolchain
spec
... | [
"A",
"standard",
"helper",
"function",
"for",
"combining",
"the",
"filtered",
"(",
"e",
".",
"g",
".",
"using",
"spec_update_sourcepath_filter_loaderplugins",
")",
"loaderplugin",
"sourcepath",
"mappings",
"back",
"into",
"one",
"that",
"is",
"usable",
"with",
"th... | python | train | 39.902778 |
gwpy/gwpy | gwpy/signal/qtransform.py | https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/signal/qtransform.py#L147-L155 | def _iter_qs(self):
"""Iterate over the Q values
"""
# work out how many Qs we need
cumum = log(self.qrange[1] / self.qrange[0]) / 2**(1/2.)
nplanes = int(max(ceil(cumum / self.deltam), 1))
dq = cumum / nplanes # pylint: disable=invalid-name
for i in xrange(nplan... | [
"def",
"_iter_qs",
"(",
"self",
")",
":",
"# work out how many Qs we need",
"cumum",
"=",
"log",
"(",
"self",
".",
"qrange",
"[",
"1",
"]",
"/",
"self",
".",
"qrange",
"[",
"0",
"]",
")",
"/",
"2",
"**",
"(",
"1",
"/",
"2.",
")",
"nplanes",
"=",
... | Iterate over the Q values | [
"Iterate",
"over",
"the",
"Q",
"values"
] | python | train | 42.444444 |
thespacedoctor/rockAtlas | rockAtlas/positions/orbfitPositions.py | https://github.com/thespacedoctor/rockAtlas/blob/062ecaa95ab547efda535aa33165944f13c621de/rockAtlas/positions/orbfitPositions.py#L84-L119 | def get(self,
singleExposure=False):
"""
*get the orbfitPositions object*
**Key Arguments:**
- ``singleExposure`` -- only execute fot a single exposure (useful for debugging)
**Return:**
- None
**Usage:**
See class docstring
... | [
"def",
"get",
"(",
"self",
",",
"singleExposure",
"=",
"False",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'starting the ``get`` method'",
")",
"if",
"singleExposure",
":",
"batchSize",
"=",
"1",
"else",
":",
"batchSize",
"=",
"int",
"(",
"self",
"... | *get the orbfitPositions object*
**Key Arguments:**
- ``singleExposure`` -- only execute fot a single exposure (useful for debugging)
**Return:**
- None
**Usage:**
See class docstring | [
"*",
"get",
"the",
"orbfitPositions",
"object",
"*"
] | python | train | 29.777778 |
flatangle/flatlib | flatlib/ephem/eph.py | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/ephem/eph.py#L68-L72 | def getFixedStar(ID, jd):
""" Returns a fixed star. """
star = swe.sweFixedStar(ID, jd)
_signInfo(star)
return star | [
"def",
"getFixedStar",
"(",
"ID",
",",
"jd",
")",
":",
"star",
"=",
"swe",
".",
"sweFixedStar",
"(",
"ID",
",",
"jd",
")",
"_signInfo",
"(",
"star",
")",
"return",
"star"
] | Returns a fixed star. | [
"Returns",
"a",
"fixed",
"star",
"."
] | python | train | 25.4 |
peri-source/peri | peri/opt/optimize.py | https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L1011-L1023 | def _calc_lm_step(self, damped_JTJ, grad, subblock=None):
"""Calculates a Levenberg-Marquard step w/o acceleration"""
delta0, res, rank, s = np.linalg.lstsq(damped_JTJ, -0.5*grad,
rcond=self.min_eigval)
if self._fresh_JTJ:
CLOG.debug('%d degenerate of %d total directi... | [
"def",
"_calc_lm_step",
"(",
"self",
",",
"damped_JTJ",
",",
"grad",
",",
"subblock",
"=",
"None",
")",
":",
"delta0",
",",
"res",
",",
"rank",
",",
"s",
"=",
"np",
".",
"linalg",
".",
"lstsq",
"(",
"damped_JTJ",
",",
"-",
"0.5",
"*",
"grad",
",",
... | Calculates a Levenberg-Marquard step w/o acceleration | [
"Calculates",
"a",
"Levenberg",
"-",
"Marquard",
"step",
"w",
"/",
"o",
"acceleration"
] | python | valid | 42.538462 |
yfpeng/bioc | bioc/biocjson/decoder.py | https://github.com/yfpeng/bioc/blob/47ddaa010960d9ba673aefe068e7bbaf39f0fff4/bioc/biocjson/decoder.py#L37-L44 | def parse_relation(obj: dict) -> BioCRelation:
"""Deserialize a dict obj to a BioCRelation object"""
rel = BioCRelation()
rel.id = obj['id']
rel.infons = obj['infons']
for node in obj['nodes']:
rel.add_node(BioCNode(node['refid'], node['role']))
return rel | [
"def",
"parse_relation",
"(",
"obj",
":",
"dict",
")",
"->",
"BioCRelation",
":",
"rel",
"=",
"BioCRelation",
"(",
")",
"rel",
".",
"id",
"=",
"obj",
"[",
"'id'",
"]",
"rel",
".",
"infons",
"=",
"obj",
"[",
"'infons'",
"]",
"for",
"node",
"in",
"ob... | Deserialize a dict obj to a BioCRelation object | [
"Deserialize",
"a",
"dict",
"obj",
"to",
"a",
"BioCRelation",
"object"
] | python | train | 36 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/buildtasks_api.py | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildtasks_api.py#L269-L293 | def cancel_bbuild(self, build_execution_configuration_id, **kwargs):
"""
Cancel the build execution defined with given executionConfigurationId.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
... | [
"def",
"cancel_bbuild",
"(",
"self",
",",
"build_execution_configuration_id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"can... | Cancel the build execution defined with given executionConfigurationId.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(respons... | [
"Cancel",
"the",
"build",
"execution",
"defined",
"with",
"given",
"executionConfigurationId",
".",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"define",
... | python | train | 50.04 |
andrenarchy/krypy | krypy/utils.py | https://github.com/andrenarchy/krypy/blob/4883ec9a61d64ea56489e15c35cc40f0633ab2f1/krypy/utils.py#L533-L558 | def apply(self, a, return_Ya=False):
r"""Apply the projection to an array.
The computation is carried out without explicitly forming the
matrix corresponding to the projection (which would be an array with
``shape==(N,N)``).
See also :py:meth:`_apply`.
"""
# is ... | [
"def",
"apply",
"(",
"self",
",",
"a",
",",
"return_Ya",
"=",
"False",
")",
":",
"# is projection the zero operator?",
"if",
"self",
".",
"V",
".",
"shape",
"[",
"1",
"]",
"==",
"0",
":",
"Pa",
"=",
"numpy",
".",
"zeros",
"(",
"a",
".",
"shape",
")... | r"""Apply the projection to an array.
The computation is carried out without explicitly forming the
matrix corresponding to the projection (which would be an array with
``shape==(N,N)``).
See also :py:meth:`_apply`. | [
"r",
"Apply",
"the",
"projection",
"to",
"an",
"array",
"."
] | python | train | 30.923077 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_restserver.py | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_restserver.py#L27-L35 | def mpstatus_to_json(status):
'''Translate MPStatus in json string'''
msg_keys = list(status.msgs.keys())
data = '{'
for key in msg_keys[:-1]:
data += mavlink_to_json(status.msgs[key]) + ','
data += mavlink_to_json(status.msgs[msg_keys[-1]])
data += '}'
return data | [
"def",
"mpstatus_to_json",
"(",
"status",
")",
":",
"msg_keys",
"=",
"list",
"(",
"status",
".",
"msgs",
".",
"keys",
"(",
")",
")",
"data",
"=",
"'{'",
"for",
"key",
"in",
"msg_keys",
"[",
":",
"-",
"1",
"]",
":",
"data",
"+=",
"mavlink_to_json",
... | Translate MPStatus in json string | [
"Translate",
"MPStatus",
"in",
"json",
"string"
] | python | train | 32.555556 |
nfcpy/nfcpy | src/nfc/clf/pn533.py | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/clf/pn533.py#L360-L366 | def send_rsp_recv_cmd(self, target, data, timeout):
"""While operating as *target* send response *data* to the remote
device and return new command data if received within
*timeout* seconds.
"""
return super(Device, self).send_rsp_recv_cmd(target, data, timeout) | [
"def",
"send_rsp_recv_cmd",
"(",
"self",
",",
"target",
",",
"data",
",",
"timeout",
")",
":",
"return",
"super",
"(",
"Device",
",",
"self",
")",
".",
"send_rsp_recv_cmd",
"(",
"target",
",",
"data",
",",
"timeout",
")"
] | While operating as *target* send response *data* to the remote
device and return new command data if received within
*timeout* seconds. | [
"While",
"operating",
"as",
"*",
"target",
"*",
"send",
"response",
"*",
"data",
"*",
"to",
"the",
"remote",
"device",
"and",
"return",
"new",
"command",
"data",
"if",
"received",
"within",
"*",
"timeout",
"*",
"seconds",
"."
] | python | train | 42.428571 |
manns/pyspread | pyspread/src/gui/_grid_cell_editor.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/gui/_grid_cell_editor.py#L194-L212 | def EndEdit(self, row, col, grid, oldVal=None):
"""
End editing the cell. This function must check if the current
value of the editing control is valid and different from the
original value (available as oldval in its string form.) If
it has not changed then simply return None,... | [
"def",
"EndEdit",
"(",
"self",
",",
"row",
",",
"col",
",",
"grid",
",",
"oldVal",
"=",
"None",
")",
":",
"# Mirror our changes onto the main_window's code bar",
"self",
".",
"_tc",
".",
"Unbind",
"(",
"wx",
".",
"EVT_KEY_UP",
")",
"self",
".",
"ApplyEdit",
... | End editing the cell. This function must check if the current
value of the editing control is valid and different from the
original value (available as oldval in its string form.) If
it has not changed then simply return None, otherwise return
the value in its string form.
*Mus... | [
"End",
"editing",
"the",
"cell",
".",
"This",
"function",
"must",
"check",
"if",
"the",
"current",
"value",
"of",
"the",
"editing",
"control",
"is",
"valid",
"and",
"different",
"from",
"the",
"original",
"value",
"(",
"available",
"as",
"oldval",
"in",
"i... | python | train | 31.736842 |
minio/minio-py | minio/api.py | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/api.py#L423-L437 | def get_bucket_notification(self, bucket_name):
"""
Get notifications configured for the given bucket.
:param bucket_name: Bucket name.
"""
is_valid_bucket_name(bucket_name)
response = self._url_open(
"GET",
bucket_name=bucket_name,
q... | [
"def",
"get_bucket_notification",
"(",
"self",
",",
"bucket_name",
")",
":",
"is_valid_bucket_name",
"(",
"bucket_name",
")",
"response",
"=",
"self",
".",
"_url_open",
"(",
"\"GET\"",
",",
"bucket_name",
"=",
"bucket_name",
",",
"query",
"=",
"{",
"\"notificati... | Get notifications configured for the given bucket.
:param bucket_name: Bucket name. | [
"Get",
"notifications",
"configured",
"for",
"the",
"given",
"bucket",
"."
] | python | train | 29.2 |
globality-corp/microcosm-flask | microcosm_flask/swagger/naming.py | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/swagger/naming.py#L11-L26 | def operation_name(operation, ns):
"""
Convert an operation, obj(s) pair into a swagger operation id.
For compatability with Bravado, we want to use underscores instead of dots and
verb-friendly names. Example:
foo.retrieve => client.foo.retrieve()
foo.search_for.bar => client.fo... | [
"def",
"operation_name",
"(",
"operation",
",",
"ns",
")",
":",
"verb",
"=",
"operation",
".",
"value",
".",
"name",
"if",
"ns",
".",
"object_",
":",
"return",
"\"{}_{}\"",
".",
"format",
"(",
"verb",
",",
"pluralize",
"(",
"ns",
".",
"object_name",
")... | Convert an operation, obj(s) pair into a swagger operation id.
For compatability with Bravado, we want to use underscores instead of dots and
verb-friendly names. Example:
foo.retrieve => client.foo.retrieve()
foo.search_for.bar => client.foo.search_for_bars() | [
"Convert",
"an",
"operation",
"obj",
"(",
"s",
")",
"pair",
"into",
"a",
"swagger",
"operation",
"id",
"."
] | python | train | 29.8125 |
DarkEnergySurvey/ugali | ugali/scratch/simulation/survey_selection_function.py | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/scratch/simulation/survey_selection_function.py#L34-L40 | def angToPix(nside, lon, lat, nest=False):
"""
Input (lon, lat) in degrees instead of (theta, phi) in radians
"""
theta = np.radians(90. - lat)
phi = np.radians(lon)
return hp.ang2pix(nside, theta, phi, nest=nest) | [
"def",
"angToPix",
"(",
"nside",
",",
"lon",
",",
"lat",
",",
"nest",
"=",
"False",
")",
":",
"theta",
"=",
"np",
".",
"radians",
"(",
"90.",
"-",
"lat",
")",
"phi",
"=",
"np",
".",
"radians",
"(",
"lon",
")",
"return",
"hp",
".",
"ang2pix",
"(... | Input (lon, lat) in degrees instead of (theta, phi) in radians | [
"Input",
"(",
"lon",
"lat",
")",
"in",
"degrees",
"instead",
"of",
"(",
"theta",
"phi",
")",
"in",
"radians"
] | python | train | 33 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.