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 |
|---|---|---|---|---|---|---|---|---|---|
mikedh/trimesh | trimesh/base.py | https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/base.py#L2014-L2030 | def apply_obb(self):
"""
Apply the oriented bounding box transform to the current mesh.
This will result in a mesh with an AABB centered at the
origin and the same dimensions as the OBB.
Returns
----------
matrix : (4, 4) float
Transformation matrix th... | [
"def",
"apply_obb",
"(",
"self",
")",
":",
"matrix",
"=",
"self",
".",
"bounding_box_oriented",
".",
"primitive",
".",
"transform",
"matrix",
"=",
"np",
".",
"linalg",
".",
"inv",
"(",
"matrix",
")",
"self",
".",
"apply_transform",
"(",
"matrix",
")",
"r... | Apply the oriented bounding box transform to the current mesh.
This will result in a mesh with an AABB centered at the
origin and the same dimensions as the OBB.
Returns
----------
matrix : (4, 4) float
Transformation matrix that was applied
to mesh to move ... | [
"Apply",
"the",
"oriented",
"bounding",
"box",
"transform",
"to",
"the",
"current",
"mesh",
"."
] | python | train | 31.529412 |
senaite/senaite.core | bika/lims/content/contact.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/content/contact.py#L110-L117 | def getUser(self):
"""Returns the linked Plone User or None
"""
username = self.getUsername()
if not username:
return None
user = api.user.get(userid=username)
return user | [
"def",
"getUser",
"(",
"self",
")",
":",
"username",
"=",
"self",
".",
"getUsername",
"(",
")",
"if",
"not",
"username",
":",
"return",
"None",
"user",
"=",
"api",
".",
"user",
".",
"get",
"(",
"userid",
"=",
"username",
")",
"return",
"user"
] | Returns the linked Plone User or None | [
"Returns",
"the",
"linked",
"Plone",
"User",
"or",
"None"
] | python | train | 28 |
theno/utlz | fabfile.py | https://github.com/theno/utlz/blob/bf7d2b53f3e0d35c6f8ded81f3f774a74fcd3389/fabfile.py#L135-L167 | def pythons():
'''Install latest pythons with pyenv.
The python version will be activated in the projects base dir.
Will skip already installed latest python versions.
'''
if not _pyenv_exists():
print('\npyenv is not installed. You can install it with fabsetup '
'(https://gi... | [
"def",
"pythons",
"(",
")",
":",
"if",
"not",
"_pyenv_exists",
"(",
")",
":",
"print",
"(",
"'\\npyenv is not installed. You can install it with fabsetup '",
"'(https://github.com/theno/fabsetup):\\n\\n '",
"+",
"cyan",
"(",
"'mkdir ~/repos && cd ~/repos\\n '",
"'git clon... | Install latest pythons with pyenv.
The python version will be activated in the projects base dir.
Will skip already installed latest python versions. | [
"Install",
"latest",
"pythons",
"with",
"pyenv",
"."
] | python | train | 40.121212 |
Yubico/python-pyhsm | pyhsm/base.py | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/base.py#L294-L312 | def load_secret(self, secret):
"""
Ask YubiHSM to load a pre-existing YubiKey secret.
The data is stored internally in the YubiHSM in temporary memory -
this operation would typically be followed by one or more L{generate_aead}
commands to actually retreive the generated secret ... | [
"def",
"load_secret",
"(",
"self",
",",
"secret",
")",
":",
"if",
"isinstance",
"(",
"secret",
",",
"pyhsm",
".",
"aead_cmd",
".",
"YHSM_YubiKeySecret",
")",
":",
"secret",
"=",
"secret",
".",
"pack",
"(",
")",
"return",
"pyhsm",
".",
"buffer_cmd",
".",
... | Ask YubiHSM to load a pre-existing YubiKey secret.
The data is stored internally in the YubiHSM in temporary memory -
this operation would typically be followed by one or more L{generate_aead}
commands to actually retreive the generated secret (in encrypted form).
@param secret: YubiKe... | [
"Ask",
"YubiHSM",
"to",
"load",
"a",
"pre",
"-",
"existing",
"YubiKey",
"secret",
"."
] | python | train | 41.421053 |
cytoscape/py2cytoscape | py2cytoscape/cyrest/networks.py | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/networks.py#L966-L985 | def updateColumnValues(self, networkId, tableType, columnName, default, body, verbose=None):
"""
Sets the values for cells in the table specified by the `tableType` and `networkId` parameters.
If the 'default` parameter is not specified, the message body should consist of key-value pair... | [
"def",
"updateColumnValues",
"(",
"self",
",",
"networkId",
",",
"tableType",
",",
"columnName",
",",
"default",
",",
"body",
",",
"verbose",
"=",
"None",
")",
":",
"response",
"=",
"api",
"(",
"url",
"=",
"self",
".",
"___url",
"+",
"'networks/'",
"+",
... | Sets the values for cells in the table specified by the `tableType` and `networkId` parameters.
If the 'default` parameter is not specified, the message body should consist of key-value pairs with which to set values.
If the `default` parameter is specified, its value will be used for ... | [
"Sets",
"the",
"values",
"for",
"cells",
"in",
"the",
"table",
"specified",
"by",
"the",
"tableType",
"and",
"networkId",
"parameters",
".",
"If",
"the",
"default",
"parameter",
"is",
"not",
"specified",
"the",
"message",
"body",
"should",
"consist",
"of",
"... | python | train | 56.3 |
theodoregoetz/wernher | wernher/colorline.py | https://github.com/theodoregoetz/wernher/blob/ef5d3aabe24e532b5eab33cd0212b2dbc2c9022e/wernher/colorline.py#L6-L28 | def colorline(ax, x, y, z, **kwargs):
"""
http://nbviewer.ipython.org/github/dpsanders/matplotlib-examples/blob/master/colorline.ipynb
http://matplotlib.org/examples/pylab_examples/multicolored_line.html
Plot a colored line with coordinates x and y
Optionally specify colors in the array z
Option... | [
"def",
"colorline",
"(",
"ax",
",",
"x",
",",
"y",
",",
"z",
",",
"*",
"*",
"kwargs",
")",
":",
"# Special case if a single number:",
"if",
"not",
"hasattr",
"(",
"z",
",",
"\"__iter__\"",
")",
":",
"# to check for numerical input -- this is a hack",
"z",
"=",... | http://nbviewer.ipython.org/github/dpsanders/matplotlib-examples/blob/master/colorline.ipynb
http://matplotlib.org/examples/pylab_examples/multicolored_line.html
Plot a colored line with coordinates x and y
Optionally specify colors in the array z
Optionally specify a colormap, a norm function and a lin... | [
"http",
":",
"//",
"nbviewer",
".",
"ipython",
".",
"org",
"/",
"github",
"/",
"dpsanders",
"/",
"matplotlib",
"-",
"examples",
"/",
"blob",
"/",
"master",
"/",
"colorline",
".",
"ipynb",
"http",
":",
"//",
"matplotlib",
".",
"org",
"/",
"examples",
"/... | python | train | 31.826087 |
giancosta86/Iris | info/gianlucacosta/iris/ioc.py | https://github.com/giancosta86/Iris/blob/b3d92cca5cce3653519bd032346b211c46a57d05/info/gianlucacosta/iris/ioc.py#L151-L158 | def dispose(self):
"""
Disposes every performed registration; the container can then be used again
"""
for registration in self._registrations.values():
registration.dispose()
self._registrations = {} | [
"def",
"dispose",
"(",
"self",
")",
":",
"for",
"registration",
"in",
"self",
".",
"_registrations",
".",
"values",
"(",
")",
":",
"registration",
".",
"dispose",
"(",
")",
"self",
".",
"_registrations",
"=",
"{",
"}"
] | Disposes every performed registration; the container can then be used again | [
"Disposes",
"every",
"performed",
"registration",
";",
"the",
"container",
"can",
"then",
"be",
"used",
"again"
] | python | train | 30.75 |
tradenity/python-sdk | tradenity/resources/store_profile.py | https://github.com/tradenity/python-sdk/blob/d13fbe23f4d6ff22554c6d8d2deaf209371adaf1/tradenity/resources/store_profile.py#L404-L424 | def get_store_profile_by_id(cls, store_profile_id, **kwargs):
"""Find StoreProfile
Return single instance of StoreProfile by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_store_p... | [
"def",
"get_store_profile_by_id",
"(",
"cls",
",",
"store_profile_id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_get_store_pro... | Find StoreProfile
Return single instance of StoreProfile by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_store_profile_by_id(store_profile_id, async=True)
>>> result = thread.ge... | [
"Find",
"StoreProfile"
] | python | train | 44.095238 |
geopy/geopy | geopy/geocoders/mapbox.py | https://github.com/geopy/geopy/blob/02c838d965e76497f3c3d61f53808c86b5c58224/geopy/geocoders/mapbox.py#L161-L197 | def reverse(
self,
query,
exactly_one=True,
timeout=DEFAULT_SENTINEL,
):
"""
Return an address by location point.
:param query: The coordinates for which you wish to obtain the
closest human-readable addresses.
:type query:... | [
"def",
"reverse",
"(",
"self",
",",
"query",
",",
"exactly_one",
"=",
"True",
",",
"timeout",
"=",
"DEFAULT_SENTINEL",
",",
")",
":",
"params",
"=",
"{",
"}",
"params",
"[",
"'access_token'",
"]",
"=",
"self",
".",
"api_key",
"point",
"=",
"self",
".",... | Return an address by location point.
:param query: The coordinates for which you wish to obtain the
closest human-readable addresses.
:type query: :class:`geopy.point.Point`, list or tuple of ``(latitude,
longitude)``, or string as ``"%(latitude)s, %(longitude)s"``.
:pa... | [
"Return",
"an",
"address",
"by",
"location",
"point",
"."
] | python | train | 38.432432 |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/namespacebrowser.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/namespacebrowser.py#L173-L215 | def setup_option_actions(self, exclude_private, exclude_uppercase,
exclude_capitalized, exclude_unsupported):
"""Setup the actions to show in the cog menu."""
self.setup_in_progress = True
self.exclude_private_action = create_action(self,
_("Ex... | [
"def",
"setup_option_actions",
"(",
"self",
",",
"exclude_private",
",",
"exclude_uppercase",
",",
"exclude_capitalized",
",",
"exclude_unsupported",
")",
":",
"self",
".",
"setup_in_progress",
"=",
"True",
"self",
".",
"exclude_private_action",
"=",
"create_action",
... | Setup the actions to show in the cog menu. | [
"Setup",
"the",
"actions",
"to",
"show",
"in",
"the",
"cog",
"menu",
"."
] | python | train | 51.604651 |
couchbase/couchbase-python-client | couchbase/n1ql.py | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/n1ql.py#L247-L262 | def timeout(self):
"""
Optional per-query timeout. If set, this will limit the amount
of time in which the query can be executed and waited for.
.. note::
The effective timeout for the query will be either this property
or the value of :attr:`couchbase.bucket.Bu... | [
"def",
"timeout",
"(",
"self",
")",
":",
"value",
"=",
"self",
".",
"_body",
".",
"get",
"(",
"'timeout'",
",",
"'0s'",
")",
"value",
"=",
"value",
"[",
":",
"-",
"1",
"]",
"return",
"float",
"(",
"value",
")"
] | Optional per-query timeout. If set, this will limit the amount
of time in which the query can be executed and waited for.
.. note::
The effective timeout for the query will be either this property
or the value of :attr:`couchbase.bucket.Bucket.n1ql_timeout`
property... | [
"Optional",
"per",
"-",
"query",
"timeout",
".",
"If",
"set",
"this",
"will",
"limit",
"the",
"amount",
"of",
"time",
"in",
"which",
"the",
"query",
"can",
"be",
"executed",
"and",
"waited",
"for",
"."
] | python | train | 33.8125 |
MacHu-GWU/angora-project | angora/math/img2waveform.py | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/math/img2waveform.py#L44-L69 | def expand_window(center, window_size, array_size):
"""Generate a bounded windows.
maxlength = 2 * window_size + 1, lower bound is 0 and upper bound is
``array_size - 1``.
Example::
>>> expand_window(center=50, window_size=3, max=100)
[47, 48, 49, 50, 51, 52, 53]
>>> expand... | [
"def",
"expand_window",
"(",
"center",
",",
"window_size",
",",
"array_size",
")",
":",
"if",
"center",
"-",
"window_size",
"<",
"0",
":",
"lower",
"=",
"0",
"else",
":",
"lower",
"=",
"center",
"-",
"window_size",
"if",
"center",
"+",
"window_size",
"+"... | Generate a bounded windows.
maxlength = 2 * window_size + 1, lower bound is 0 and upper bound is
``array_size - 1``.
Example::
>>> expand_window(center=50, window_size=3, max=100)
[47, 48, 49, 50, 51, 52, 53]
>>> expand_window(center=2, window_size=3, max=100)
[0, 1, 2,... | [
"Generate",
"a",
"bounded",
"windows",
"."
] | python | train | 27.884615 |
google/grumpy | third_party/stdlib/base64.py | https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/base64.py#L185-L252 | def b32decode(s, casefold=False, map01=None):
"""Decode a Base32 encoded string.
s is the string to decode. Optional casefold is a flag specifying whether
a lowercase alphabet is acceptable as input. For security purposes, the
default is False.
RFC 3548 allows for optional mapping of the digit 0... | [
"def",
"b32decode",
"(",
"s",
",",
"casefold",
"=",
"False",
",",
"map01",
"=",
"None",
")",
":",
"quanta",
",",
"leftover",
"=",
"divmod",
"(",
"len",
"(",
"s",
")",
",",
"8",
")",
"if",
"leftover",
":",
"raise",
"TypeError",
"(",
"'Incorrect paddin... | Decode a Base32 encoded string.
s is the string to decode. Optional casefold is a flag specifying whether
a lowercase alphabet is acceptable as input. For security purposes, the
default is False.
RFC 3548 allows for optional mapping of the digit 0 (zero) to the letter O
(oh), and for optional ma... | [
"Decode",
"a",
"Base32",
"encoded",
"string",
"."
] | python | valid | 35.720588 |
chaoss/grimoirelab-elk | grimoire_elk/enriched/mediawiki.py | https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/mediawiki.py#L67-L80 | def get_identities(self, item):
""" Return the identities from an item """
identities = []
if 'data' not in item:
return identities
if 'revisions' not in item['data']:
return identities
revisions = item['data']['revisions']
for revision in revis... | [
"def",
"get_identities",
"(",
"self",
",",
"item",
")",
":",
"identities",
"=",
"[",
"]",
"if",
"'data'",
"not",
"in",
"item",
":",
"return",
"identities",
"if",
"'revisions'",
"not",
"in",
"item",
"[",
"'data'",
"]",
":",
"return",
"identities",
"revisi... | Return the identities from an item | [
"Return",
"the",
"identities",
"from",
"an",
"item"
] | python | train | 27.5 |
galaxyproject/gravity | gravity/config_manager.py | https://github.com/galaxyproject/gravity/blob/2f792497fc60874f881c9ef74a5905a286a9ce3e/gravity/config_manager.py#L190-L198 | def _register_config_file(self, key, val):
""" Persist a newly added config file, or update (overwrite) the value
of a previously persisted config.
"""
state = self.__load_state()
if 'config_files' not in state:
state['config_files'] = {}
state['config_files']... | [
"def",
"_register_config_file",
"(",
"self",
",",
"key",
",",
"val",
")",
":",
"state",
"=",
"self",
".",
"__load_state",
"(",
")",
"if",
"'config_files'",
"not",
"in",
"state",
":",
"state",
"[",
"'config_files'",
"]",
"=",
"{",
"}",
"state",
"[",
"'c... | Persist a newly added config file, or update (overwrite) the value
of a previously persisted config. | [
"Persist",
"a",
"newly",
"added",
"config",
"file",
"or",
"update",
"(",
"overwrite",
")",
"the",
"value",
"of",
"a",
"previously",
"persisted",
"config",
"."
] | python | train | 39.555556 |
facelessuser/pyspelling | pyspelling/__init__.py | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/__init__.py#L471-L482 | def setup_dictionary(self, task):
"""Setup dictionary."""
dictionary_options = task.get('dictionary', {})
output = os.path.abspath(dictionary_options.get('output', self.dict_bin))
lang = dictionary_options.get('lang', 'en_US')
wordlists = dictionary_options.get('wordlists', [])
... | [
"def",
"setup_dictionary",
"(",
"self",
",",
"task",
")",
":",
"dictionary_options",
"=",
"task",
".",
"get",
"(",
"'dictionary'",
",",
"{",
"}",
")",
"output",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"dictionary_options",
".",
"get",
"(",
"'output'... | Setup dictionary. | [
"Setup",
"dictionary",
"."
] | python | train | 41.5 |
django-fluent/django-fluent-blogs | fluent_blogs/models/query.py | https://github.com/django-fluent/django-fluent-blogs/blob/86b148549a010eaca9a2ea987fe43be250e06c50/fluent_blogs/models/query.py#L198-L220 | def get_date_range(year=None, month=None, day=None):
"""
Return a start..end range to query for a specific month, day or year.
"""
if year is None:
return None
if month is None:
# year only
start = datetime(year, 1, 1, 0, 0, 0, tzinfo=utc)
end = datetime(year, 12, 31... | [
"def",
"get_date_range",
"(",
"year",
"=",
"None",
",",
"month",
"=",
"None",
",",
"day",
"=",
"None",
")",
":",
"if",
"year",
"is",
"None",
":",
"return",
"None",
"if",
"month",
"is",
"None",
":",
"# year only",
"start",
"=",
"datetime",
"(",
"year"... | Return a start..end range to query for a specific month, day or year. | [
"Return",
"a",
"start",
"..",
"end",
"range",
"to",
"query",
"for",
"a",
"specific",
"month",
"day",
"or",
"year",
"."
] | python | train | 32.869565 |
tdryer/hangups | hangups/auth.py | https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/auth.py#L145-L158 | def get(self):
"""Get cached refresh token.
Returns:
Cached refresh token, or ``None`` on failure.
"""
logger.info(
'Loading refresh_token from %s', repr(self._filename)
)
try:
with open(self._filename) as f:
return f.r... | [
"def",
"get",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"'Loading refresh_token from %s'",
",",
"repr",
"(",
"self",
".",
"_filename",
")",
")",
"try",
":",
"with",
"open",
"(",
"self",
".",
"_filename",
")",
"as",
"f",
":",
"return",
"f",
"... | Get cached refresh token.
Returns:
Cached refresh token, or ``None`` on failure. | [
"Get",
"cached",
"refresh",
"token",
"."
] | python | valid | 28.857143 |
openthread/openthread | tools/harness-thci/OpenThread.py | https://github.com/openthread/openthread/blob/0208d10563aa21c518092985c78ecf9cd223ab74/tools/harness-thci/OpenThread.py#L671-L689 | def setNetworkName(self, networkName='GRL'):
"""set Thread Network name
Args:
networkName: the networkname string to be set
Returns:
True: successful to set the Thread Networkname
False: fail to set the Thread Networkname
"""
print '%s call s... | [
"def",
"setNetworkName",
"(",
"self",
",",
"networkName",
"=",
"'GRL'",
")",
":",
"print",
"'%s call setNetworkName'",
"%",
"self",
".",
"port",
"print",
"networkName",
"try",
":",
"cmd",
"=",
"'networkname %s'",
"%",
"networkName",
"datasetCmd",
"=",
"'dataset ... | set Thread Network name
Args:
networkName: the networkname string to be set
Returns:
True: successful to set the Thread Networkname
False: fail to set the Thread Networkname | [
"set",
"Thread",
"Network",
"name"
] | python | train | 39.210526 |
APSL/transmanager | transmanager/manager.py | https://github.com/APSL/transmanager/blob/79157085840008e146b264521681913090197ed1/transmanager/manager.py#L680-L711 | def delete_translations_for_item_and_its_children(self, item, languages=None):
"""
deletes the translations task of an item and its children
used when a model is not enabled anymore
:param item:
:param languages:
:return:
"""
self.log('--- Deleting transl... | [
"def",
"delete_translations_for_item_and_its_children",
"(",
"self",
",",
"item",
",",
"languages",
"=",
"None",
")",
":",
"self",
".",
"log",
"(",
"'--- Deleting translations ---'",
")",
"if",
"not",
"self",
".",
"master",
":",
"self",
".",
"set_master",
"(",
... | deletes the translations task of an item and its children
used when a model is not enabled anymore
:param item:
:param languages:
:return: | [
"deletes",
"the",
"translations",
"task",
"of",
"an",
"item",
"and",
"its",
"children",
"used",
"when",
"a",
"model",
"is",
"not",
"enabled",
"anymore",
":",
"param",
"item",
":",
":",
"param",
"languages",
":",
":",
"return",
":"
] | python | train | 33.375 |
saltstack/salt | salt/cloud/clouds/aliyun.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/aliyun.py#L223-L238 | def list_availability_zones(call=None):
'''
List all availability zones in the current region
'''
ret = {}
params = {'Action': 'DescribeZones',
'RegionId': get_location()}
items = query(params)
for zone in items['Zones']['Zone']:
ret[zone['ZoneId']] = {}
for i... | [
"def",
"list_availability_zones",
"(",
"call",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"}",
"params",
"=",
"{",
"'Action'",
":",
"'DescribeZones'",
",",
"'RegionId'",
":",
"get_location",
"(",
")",
"}",
"items",
"=",
"query",
"(",
"params",
")",
"for",
... | List all availability zones in the current region | [
"List",
"all",
"availability",
"zones",
"in",
"the",
"current",
"region"
] | python | train | 24.9375 |
agoragames/chai | chai/stub.py | https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/stub.py#L568-L574 | def call_orig(self, *args, **kwargs):
'''
Calls the original function. Simulates __new__ and __init__ together.
'''
rval = super(StubNew, self).call_orig(self._type)
rval.__init__(*args, **kwargs)
return rval | [
"def",
"call_orig",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"rval",
"=",
"super",
"(",
"StubNew",
",",
"self",
")",
".",
"call_orig",
"(",
"self",
".",
"_type",
")",
"rval",
".",
"__init__",
"(",
"*",
"args",
",",
"*",
... | Calls the original function. Simulates __new__ and __init__ together. | [
"Calls",
"the",
"original",
"function",
".",
"Simulates",
"__new__",
"and",
"__init__",
"together",
"."
] | python | train | 35.714286 |
gwpy/gwpy | gwpy/io/nds2.py | https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/io/nds2.py#L355-L367 | def parse_nds2_enums(func):
"""Decorate a function to translate a type string into an integer
"""
@wraps(func)
def wrapped_func(*args, **kwargs): # pylint: disable=missing-docstring
for kwd, enum_ in (('type', Nds2ChannelType),
('dtype', Nds2DataType)):
if... | [
"def",
"parse_nds2_enums",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapped_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=missing-docstring",
"for",
"kwd",
",",
"enum_",
"in",
"(",
"(",
"'type'",
","... | Decorate a function to translate a type string into an integer | [
"Decorate",
"a",
"function",
"to",
"translate",
"a",
"type",
"string",
"into",
"an",
"integer"
] | python | train | 42.538462 |
blockstack/virtualchain | virtualchain/lib/blockchain/address.py | https://github.com/blockstack/virtualchain/blob/fcfc970064ca7dfcab26ebd3ab955870a763ea39/virtualchain/lib/blockchain/address.py#L25-L32 | def address_reencode(address, blockchain='bitcoin', **blockchain_opts):
"""
Reencode an address
"""
if blockchain == 'bitcoin':
return btc_address_reencode(address, **blockchain_opts)
else:
raise ValueError("Unknown blockchain '{}'".format(blockchain)) | [
"def",
"address_reencode",
"(",
"address",
",",
"blockchain",
"=",
"'bitcoin'",
",",
"*",
"*",
"blockchain_opts",
")",
":",
"if",
"blockchain",
"==",
"'bitcoin'",
":",
"return",
"btc_address_reencode",
"(",
"address",
",",
"*",
"*",
"blockchain_opts",
")",
"el... | Reencode an address | [
"Reencode",
"an",
"address"
] | python | train | 35.125 |
newfies-dialer/python-msspeak | msspeak/msspeak.py | https://github.com/newfies-dialer/python-msspeak/blob/106475122be73df152865c4fe6e9388caf974085/msspeak/msspeak.py#L193-L210 | def speak(self, textstr, lang='en-US', gender='female', format='riff-16khz-16bit-mono-pcm'):
"""
Run will call Microsoft Translate API and and produce audio
"""
# print("speak(textstr=%s, lang=%s, gender=%s, format=%s)" % (textstr, lang, gender, format))
concatkey = '%s-%s-%s-%s'... | [
"def",
"speak",
"(",
"self",
",",
"textstr",
",",
"lang",
"=",
"'en-US'",
",",
"gender",
"=",
"'female'",
",",
"format",
"=",
"'riff-16khz-16bit-mono-pcm'",
")",
":",
"# print(\"speak(textstr=%s, lang=%s, gender=%s, format=%s)\" % (textstr, lang, gender, format))",
"concatk... | Run will call Microsoft Translate API and and produce audio | [
"Run",
"will",
"call",
"Microsoft",
"Translate",
"API",
"and",
"and",
"produce",
"audio"
] | python | train | 46.888889 |
saltstack/salt | salt/modules/inspectlib/dbhandle.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspectlib/dbhandle.py#L46-L51 | def _run_init_queries(self):
'''
Initialization queries
'''
for obj in (Package, PackageCfgFile, PayloadFile, IgnoredDir, AllowedDir):
self._db.create_table_from_object(obj()) | [
"def",
"_run_init_queries",
"(",
"self",
")",
":",
"for",
"obj",
"in",
"(",
"Package",
",",
"PackageCfgFile",
",",
"PayloadFile",
",",
"IgnoredDir",
",",
"AllowedDir",
")",
":",
"self",
".",
"_db",
".",
"create_table_from_object",
"(",
"obj",
"(",
")",
")"... | Initialization queries | [
"Initialization",
"queries"
] | python | train | 35.666667 |
awslabs/aws-serverlessrepo-python | serverlessrepo/parser.py | https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/parser.py#L98-L113 | def get_app_metadata(template_dict):
"""
Get the application metadata from a SAM template.
:param template_dict: SAM template as a dictionary
:type template_dict: dict
:return: Application metadata as defined in the template
:rtype: ApplicationMetadata
:raises ApplicationMetadataNotFoundErr... | [
"def",
"get_app_metadata",
"(",
"template_dict",
")",
":",
"if",
"SERVERLESS_REPO_APPLICATION",
"in",
"template_dict",
".",
"get",
"(",
"METADATA",
",",
"{",
"}",
")",
":",
"app_metadata_dict",
"=",
"template_dict",
".",
"get",
"(",
"METADATA",
")",
".",
"get"... | Get the application metadata from a SAM template.
:param template_dict: SAM template as a dictionary
:type template_dict: dict
:return: Application metadata as defined in the template
:rtype: ApplicationMetadata
:raises ApplicationMetadataNotFoundError | [
"Get",
"the",
"application",
"metadata",
"from",
"a",
"SAM",
"template",
"."
] | python | train | 42.1875 |
SpikeInterface/spiketoolkit | spiketoolkit/comparison/sortingcomparison.py | https://github.com/SpikeInterface/spiketoolkit/blob/f7c054383d1ebca640966b057c087fa187955d13/spiketoolkit/comparison/sortingcomparison.py#L279-L325 | def compute_performance(SC, verbose=True, output='dict'):
"""
Return some performance value for comparison.
Parameters
-------
SC: SortingComparison instance
The SortingComparison
verbose: bool
Display on console or not
output: dict or pandas
Returns
----------
... | [
"def",
"compute_performance",
"(",
"SC",
",",
"verbose",
"=",
"True",
",",
"output",
"=",
"'dict'",
")",
":",
"counts",
"=",
"SC",
".",
"_counts",
"tp_rate",
"=",
"float",
"(",
"counts",
"[",
"'TP'",
"]",
")",
"/",
"counts",
"[",
"'TOT_ST1'",
"]",
"*... | Return some performance value for comparison.
Parameters
-------
SC: SortingComparison instance
The SortingComparison
verbose: bool
Display on console or not
output: dict or pandas
Returns
----------
performance: dict or pandas.Serie depending output param | [
"Return",
"some",
"performance",
"value",
"for",
"comparison",
"."
] | python | train | 30.468085 |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_fcoe_ext.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_fcoe_ext.py#L672-L686 | def fcoe_get_login_output_fcoe_login_list_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fcoe_get_login = ET.Element("fcoe_get_login")
config = fcoe_get_login
output = ET.SubElement(fcoe_get_login, "output")
fcoe_login_lis... | [
"def",
"fcoe_get_login_output_fcoe_login_list_interface_type",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"fcoe_get_login",
"=",
"ET",
".",
"Element",
"(",
"\"fcoe_get_login\"",
")",
"config",
"="... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 49.8 |
SKA-ScienceDataProcessor/integration-prototype | sip/tango_control/tango_master/app/sdp_master_device.py | https://github.com/SKA-ScienceDataProcessor/integration-prototype/blob/8c8006de6ad71dcd44114b0338780738079c87d4/sip/tango_control/tango_master/app/sdp_master_device.py#L247-L255 | def _set_master_state(self, state):
"""Set the state of the SDPMaster."""
if state == 'init':
self._service_state.update_current_state('init', force=True)
self.set_state(DevState.INIT)
elif state == 'on':
self.set_state(DevState.ON)
self._service_... | [
"def",
"_set_master_state",
"(",
"self",
",",
"state",
")",
":",
"if",
"state",
"==",
"'init'",
":",
"self",
".",
"_service_state",
".",
"update_current_state",
"(",
"'init'",
",",
"force",
"=",
"True",
")",
"self",
".",
"set_state",
"(",
"DevState",
".",
... | Set the state of the SDPMaster. | [
"Set",
"the",
"state",
"of",
"the",
"SDPMaster",
"."
] | python | train | 38.222222 |
datastax/python-driver | cassandra/cluster.py | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cluster.py#L4492-L4516 | def was_applied(self):
"""
For LWT results, returns whether the transaction was applied.
Result is indeterminate if called on a result that was not an LWT request or on
a :class:`.query.BatchStatement` containing LWT. In the latter case either all the batch
succeeds or fails.
... | [
"def",
"was_applied",
"(",
"self",
")",
":",
"if",
"self",
".",
"response_future",
".",
"row_factory",
"not",
"in",
"(",
"named_tuple_factory",
",",
"dict_factory",
",",
"tuple_factory",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Cannot determine LWT result with row... | For LWT results, returns whether the transaction was applied.
Result is indeterminate if called on a result that was not an LWT request or on
a :class:`.query.BatchStatement` containing LWT. In the latter case either all the batch
succeeds or fails.
Only valid when one of the of the in... | [
"For",
"LWT",
"results",
"returns",
"whether",
"the",
"transaction",
"was",
"applied",
"."
] | python | train | 47.72 |
rootpy/rootpy | rootpy/utils/extras.py | https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/utils/extras.py#L90-L136 | def izip_exact(*iterables):
"""
A lazy izip() that ensures that all iterables have the same length.
A LengthMismatch exception is raised if the iterables' lengths differ.
Examples
--------
>>> list(zip_exc([]))
[]
>>> list(zip_exc((), (), ()))
[]
>>> list(zi... | [
"def",
"izip_exact",
"(",
"*",
"iterables",
")",
":",
"rest",
"=",
"[",
"chain",
"(",
"i",
",",
"_throw",
"(",
")",
")",
"for",
"i",
"in",
"iterables",
"[",
"1",
":",
"]",
"]",
"first",
"=",
"chain",
"(",
"iterables",
"[",
"0",
"]",
",",
"_chec... | A lazy izip() that ensures that all iterables have the same length.
A LengthMismatch exception is raised if the iterables' lengths differ.
Examples
--------
>>> list(zip_exc([]))
[]
>>> list(zip_exc((), (), ()))
[]
>>> list(zip_exc("abc", range(3)))
[('a', 0... | [
"A",
"lazy",
"izip",
"()",
"that",
"ensures",
"that",
"all",
"iterables",
"have",
"the",
"same",
"length",
".",
"A",
"LengthMismatch",
"exception",
"is",
"raised",
"if",
"the",
"iterables",
"lengths",
"differ",
"."
] | python | train | 27.808511 |
mfcloud/python-zvm-sdk | smtLayer/vmUtils.py | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/smtLayer/vmUtils.py#L206-L269 | def getPerfInfo(rh, useridlist):
"""
Get the performance information for a userid
Input:
Request Handle
Userid to query <- may change this to a list later.
Output:
Dictionary containing the following:
overallRC - overall return code, 0: success, non-zero: failure
... | [
"def",
"getPerfInfo",
"(",
"rh",
",",
"useridlist",
")",
":",
"rh",
".",
"printSysLog",
"(",
"\"Enter vmUtils.getPerfInfo, userid: \"",
"+",
"useridlist",
")",
"parms",
"=",
"[",
"\"-T\"",
",",
"rh",
".",
"userid",
",",
"\"-c\"",
",",
"\"1\"",
"]",
"results"... | Get the performance information for a userid
Input:
Request Handle
Userid to query <- may change this to a list later.
Output:
Dictionary containing the following:
overallRC - overall return code, 0: success, non-zero: failure
rc - RC returned from SMCLI if over... | [
"Get",
"the",
"performance",
"information",
"for",
"a",
"userid"
] | python | train | 37.34375 |
mkouhei/tonicdnscli | src/tonicdnscli/command.py | https://github.com/mkouhei/tonicdnscli/blob/df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c/src/tonicdnscli/command.py#L604-L616 | def parse_create(prs, conn):
"""Create record.
Arguments:
prs: parser object of argparse
conn: dictionary of connection information
"""
prs_create = prs.add_parser(
'create', help='create record of specific zone')
set_option(prs_create, 'domain')
conn_options(prs_creat... | [
"def",
"parse_create",
"(",
"prs",
",",
"conn",
")",
":",
"prs_create",
"=",
"prs",
".",
"add_parser",
"(",
"'create'",
",",
"help",
"=",
"'create record of specific zone'",
")",
"set_option",
"(",
"prs_create",
",",
"'domain'",
")",
"conn_options",
"(",
"prs_... | Create record.
Arguments:
prs: parser object of argparse
conn: dictionary of connection information | [
"Create",
"record",
"."
] | python | train | 27.461538 |
tomplus/kubernetes_asyncio | kubernetes_asyncio/client/api/batch_v1_api.py | https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/client/api/batch_v1_api.py#L623-L652 | def list_namespaced_job(self, namespace, **kwargs): # noqa: E501
"""list_namespaced_job # noqa: E501
list or watch objects of kind Job # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> th... | [
"def",
"list_namespaced_job",
"(",
"self",
",",
"namespace",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"l... | list_namespaced_job # noqa: E501
list or watch objects of kind Job # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_job(namespace, async_req=True)
>>> result ... | [
"list_namespaced_job",
"#",
"noqa",
":",
"E501"
] | python | train | 161 |
gem/oq-engine | openquake/hmtk/seismicity/completeness/comp_stepp_1971.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/completeness/comp_stepp_1971.py#L62-L89 | def get_bilinear_residuals_stepp(input_params, xvals, yvals, slope1_fit):
'''
Returns the residual sum-of-squares value of a bilinear fit to a data
set - with a segment - 1 gradient fixed by an input value (slope_1_fit)
:param list input_params:
Input parameters for the bilinear model [slope2, ... | [
"def",
"get_bilinear_residuals_stepp",
"(",
"input_params",
",",
"xvals",
",",
"yvals",
",",
"slope1_fit",
")",
":",
"params",
"=",
"np",
".",
"hstack",
"(",
"[",
"slope1_fit",
",",
"input_params",
"]",
")",
"num_x",
"=",
"len",
"(",
"xvals",
")",
"y_model... | Returns the residual sum-of-squares value of a bilinear fit to a data
set - with a segment - 1 gradient fixed by an input value (slope_1_fit)
:param list input_params:
Input parameters for the bilinear model [slope2, crossover_point,
intercept]
:para... | [
"Returns",
"the",
"residual",
"sum",
"-",
"of",
"-",
"squares",
"value",
"of",
"a",
"bilinear",
"fit",
"to",
"a",
"data",
"set",
"-",
"with",
"a",
"segment",
"-",
"1",
"gradient",
"fixed",
"by",
"an",
"input",
"value",
"(",
"slope_1_fit",
")"
] | python | train | 35.571429 |
aouyar/PyMunin | pymunin/plugins/diskiostats.py | https://github.com/aouyar/PyMunin/blob/4f58a64b6b37c85a84cc7e1e07aafaa0321b249d/pymunin/plugins/diskiostats.py#L226-L246 | def _fetchDevAll(self, namestr, devlist, statsfunc):
"""Initialize I/O stats for devices.
@param namestr: Field name component indicating device type.
@param devlist: List of devices.
@param statsfunc: Function for retrieving stats for device.
"""
fo... | [
"def",
"_fetchDevAll",
"(",
"self",
",",
"namestr",
",",
"devlist",
",",
"statsfunc",
")",
":",
"for",
"dev",
"in",
"devlist",
":",
"stats",
"=",
"statsfunc",
"(",
"dev",
")",
"name",
"=",
"'diskio_%s_requests'",
"%",
"namestr",
"if",
"self",
".",
"hasGr... | Initialize I/O stats for devices.
@param namestr: Field name component indicating device type.
@param devlist: List of devices.
@param statsfunc: Function for retrieving stats for device. | [
"Initialize",
"I",
"/",
"O",
"stats",
"for",
"devices",
"."
] | python | train | 45.333333 |
senaite/senaite.core | bika/lims/workflow/__init__.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/workflow/__init__.py#L144-L165 | def call_workflow_event(instance, event, after=True):
"""Calls the instance's workflow event
"""
if not event.transition:
return False
portal_type = instance.portal_type
wf_module = _load_wf_module('{}.events'.format(portal_type.lower()))
if not wf_module:
return False
# In... | [
"def",
"call_workflow_event",
"(",
"instance",
",",
"event",
",",
"after",
"=",
"True",
")",
":",
"if",
"not",
"event",
".",
"transition",
":",
"return",
"False",
"portal_type",
"=",
"instance",
".",
"portal_type",
"wf_module",
"=",
"_load_wf_module",
"(",
"... | Calls the instance's workflow event | [
"Calls",
"the",
"instance",
"s",
"workflow",
"event"
] | python | train | 31.090909 |
puiterwijk/flask-oidc | flask_oidc/__init__.py | https://github.com/puiterwijk/flask-oidc/blob/7f16e27b926fc12953d6b2ae78a9b9cc9b8d1769/flask_oidc/__init__.py#L296-L336 | def _retrieve_userinfo(self, access_token=None):
"""
Requests extra user information from the Provider's UserInfo and
returns the result.
:returns: The contents of the UserInfo endpoint.
:rtype: dict
"""
if 'userinfo_uri' not in self.client_secrets:
l... | [
"def",
"_retrieve_userinfo",
"(",
"self",
",",
"access_token",
"=",
"None",
")",
":",
"if",
"'userinfo_uri'",
"not",
"in",
"self",
".",
"client_secrets",
":",
"logger",
".",
"debug",
"(",
"'Userinfo uri not specified'",
")",
"raise",
"AssertionError",
"(",
"'Use... | Requests extra user information from the Provider's UserInfo and
returns the result.
:returns: The contents of the UserInfo endpoint.
:rtype: dict | [
"Requests",
"extra",
"user",
"information",
"from",
"the",
"Provider",
"s",
"UserInfo",
"and",
"returns",
"the",
"result",
"."
] | python | train | 36.292683 |
GoogleCloudPlatform/appengine-gcs-client | python/src/cloudstorage/cloudstorage_api.py | https://github.com/GoogleCloudPlatform/appengine-gcs-client/blob/d11078331ecd915d753c886e96a80133599f3f98/python/src/cloudstorage/cloudstorage_api.py#L47-L107 | def open(filename,
mode='r',
content_type=None,
options=None,
read_buffer_size=storage_api.ReadBuffer.DEFAULT_BUFFER_SIZE,
retry_params=None,
_account_id=None,
offset=0):
"""Opens a Google Cloud Storage file and returns it as a File-like object.
Args:
... | [
"def",
"open",
"(",
"filename",
",",
"mode",
"=",
"'r'",
",",
"content_type",
"=",
"None",
",",
"options",
"=",
"None",
",",
"read_buffer_size",
"=",
"storage_api",
".",
"ReadBuffer",
".",
"DEFAULT_BUFFER_SIZE",
",",
"retry_params",
"=",
"None",
",",
"_accou... | Opens a Google Cloud Storage file and returns it as a File-like object.
Args:
filename: A Google Cloud Storage filename of form '/bucket/filename'.
mode: 'r' for reading mode. 'w' for writing mode.
In reading mode, the file must exist. In writing mode, a file will
be created or be overrode.
c... | [
"Opens",
"a",
"Google",
"Cloud",
"Storage",
"file",
"and",
"returns",
"it",
"as",
"a",
"File",
"-",
"like",
"object",
"."
] | python | train | 43.327869 |
shoebot/shoebot | lib/graph/__init__.py | https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/__init__.py#L551-L554 | def nodes_by_category(self, category):
""" Returns nodes with the given category attribute.
"""
return [n for n in self.nodes if n.category == category] | [
"def",
"nodes_by_category",
"(",
"self",
",",
"category",
")",
":",
"return",
"[",
"n",
"for",
"n",
"in",
"self",
".",
"nodes",
"if",
"n",
".",
"category",
"==",
"category",
"]"
] | Returns nodes with the given category attribute. | [
"Returns",
"nodes",
"with",
"the",
"given",
"category",
"attribute",
"."
] | python | valid | 43.25 |
shakefu/pyconfig | pyconfig/scripts.py | https://github.com/shakefu/pyconfig/blob/000cb127db51e03cb4070aae6943e956193cbad5/pyconfig/scripts.py#L156-L170 | def get_key(self):
"""
Return the call key, even if it has to be parsed from the source.
"""
if not isinstance(self.key, Unparseable):
return self.key
line = self.source[self.col_offset:]
regex = re.compile('''pyconfig\.[eginst]+\(([^,]+).*?\)''')
ma... | [
"def",
"get_key",
"(",
"self",
")",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"key",
",",
"Unparseable",
")",
":",
"return",
"self",
".",
"key",
"line",
"=",
"self",
".",
"source",
"[",
"self",
".",
"col_offset",
":",
"]",
"regex",
"=",
"re... | Return the call key, even if it has to be parsed from the source. | [
"Return",
"the",
"call",
"key",
"even",
"if",
"it",
"has",
"to",
"be",
"parsed",
"from",
"the",
"source",
"."
] | python | valid | 28.266667 |
JnyJny/Geometry | Geometry/rectangle.py | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/rectangle.py#L41-L54 | def randomSize(cls, widthLimits, heightLimits, origin=None):
'''
:param: widthLimits - iterable of integers with length >= 2
:param: heightLimits - iterable of integers with length >= 2
:param: origin - optional Point subclass
:return: Rectangle
'''
r = cl... | [
"def",
"randomSize",
"(",
"cls",
",",
"widthLimits",
",",
"heightLimits",
",",
"origin",
"=",
"None",
")",
":",
"r",
"=",
"cls",
"(",
"0",
",",
"0",
",",
"origin",
")",
"r",
".",
"w",
"=",
"random",
".",
"randint",
"(",
"widthLimits",
"[",
"0",
"... | :param: widthLimits - iterable of integers with length >= 2
:param: heightLimits - iterable of integers with length >= 2
:param: origin - optional Point subclass
:return: Rectangle | [
":",
"param",
":",
"widthLimits",
"-",
"iterable",
"of",
"integers",
"with",
"length",
">",
"=",
"2",
":",
"param",
":",
"heightLimits",
"-",
"iterable",
"of",
"integers",
"with",
"length",
">",
"=",
"2",
":",
"param",
":",
"origin",
"-",
"optional",
"... | python | train | 33.214286 |
dwavesystems/dwave-cloud-client | dwave/cloud/client.py | https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/client.py#L1214-L1313 | def _do_poll_problems(self):
"""Poll the server for the status of a set of problems.
Note:
This method is always run inside of a daemon thread.
"""
try:
# grouped futures (all scheduled within _POLL_GROUP_TIMEFRAME)
frame_futures = {}
def... | [
"def",
"_do_poll_problems",
"(",
"self",
")",
":",
"try",
":",
"# grouped futures (all scheduled within _POLL_GROUP_TIMEFRAME)",
"frame_futures",
"=",
"{",
"}",
"def",
"task_done",
"(",
")",
":",
"self",
".",
"_poll_queue",
".",
"task_done",
"(",
")",
"def",
"add"... | Poll the server for the status of a set of problems.
Note:
This method is always run inside of a daemon thread. | [
"Poll",
"the",
"server",
"for",
"the",
"status",
"of",
"a",
"set",
"of",
"problems",
"."
] | python | train | 36.02 |
tensorflow/tensor2tensor | tensor2tensor/models/resnet.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/resnet.py#L427-L511 | def resnet_v2(inputs,
block_fn,
layer_blocks,
filters,
data_format="channels_first",
is_training=False,
is_cifar=False,
use_td=False,
targeting_rate=None,
keep_prob=None):
"""Resnet model.
... | [
"def",
"resnet_v2",
"(",
"inputs",
",",
"block_fn",
",",
"layer_blocks",
",",
"filters",
",",
"data_format",
"=",
"\"channels_first\"",
",",
"is_training",
"=",
"False",
",",
"is_cifar",
"=",
"False",
",",
"use_td",
"=",
"False",
",",
"targeting_rate",
"=",
... | Resnet model.
Args:
inputs: `Tensor` images.
block_fn: `function` for the block to use within the model. Either
`residual_block` or `bottleneck_block`.
layer_blocks: list of 3 or 4 `int`s denoting the number of blocks to include
in each of the 3 or 4 block groups. Each group consists of blo... | [
"Resnet",
"model",
"."
] | python | train | 30.011765 |
hmpf/dataporten-auth | src/dataporten/psa.py | https://github.com/hmpf/dataporten-auth/blob/bc2ff5e11a1fce2c3d7bffe3f2b513bd7e2c0fcc/src/dataporten/psa.py#L95-L108 | def get_user_details(self, response):
"""
Return user details from Dataporten
Set username to eduPersonPrincipalName
"""
user = super(DataportenFeideOAuth2, self).get_user_details(response)
sec_userids = user['userid_sec']
for userid in sec_userids:
u... | [
"def",
"get_user_details",
"(",
"self",
",",
"response",
")",
":",
"user",
"=",
"super",
"(",
"DataportenFeideOAuth2",
",",
"self",
")",
".",
"get_user_details",
"(",
"response",
")",
"sec_userids",
"=",
"user",
"[",
"'userid_sec'",
"]",
"for",
"userid",
"in... | Return user details from Dataporten
Set username to eduPersonPrincipalName | [
"Return",
"user",
"details",
"from",
"Dataporten"
] | python | train | 33.285714 |
PmagPy/PmagPy | programs/conversion_scripts/iodp_samples_magic.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/conversion_scripts/iodp_samples_magic.py#L7-L28 | def main():
"""
iodp_samples_magic.py
OPTIONS:
-f FILE, input csv file
-Fsa FILE, output samples file for updating, default is to overwrite existing samples file
"""
if "-h" in sys.argv:
print(main.__doc__)
sys.exit()
dataframe = extractor.command_line_dataframe(... | [
"def",
"main",
"(",
")",
":",
"if",
"\"-h\"",
"in",
"sys",
".",
"argv",
":",
"print",
"(",
"main",
".",
"__doc__",
")",
"sys",
".",
"exit",
"(",
")",
"dataframe",
"=",
"extractor",
".",
"command_line_dataframe",
"(",
"[",
"[",
"'WD'",
",",
"False",
... | iodp_samples_magic.py
OPTIONS:
-f FILE, input csv file
-Fsa FILE, output samples file for updating, default is to overwrite existing samples file | [
"iodp_samples_magic",
".",
"py",
"OPTIONS",
":",
"-",
"f",
"FILE",
"input",
"csv",
"file",
"-",
"Fsa",
"FILE",
"output",
"samples",
"file",
"for",
"updating",
"default",
"is",
"to",
"overwrite",
"existing",
"samples",
"file"
] | python | train | 45.5 |
waqasbhatti/astrobase | astrobase/varbase/autocorr.py | https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/varbase/autocorr.py#L61-L106 | def _autocorr_func2(mags, lag, maglen, magmed, magstd):
'''
This is an alternative function to calculate the autocorrelation.
This version is from (first definition):
https://en.wikipedia.org/wiki/Correlogram#Estimation_of_autocorrelations
Parameters
----------
mags : np.array
Th... | [
"def",
"_autocorr_func2",
"(",
"mags",
",",
"lag",
",",
"maglen",
",",
"magmed",
",",
"magstd",
")",
":",
"lagindex",
"=",
"nparange",
"(",
"0",
",",
"maglen",
"-",
"lag",
")",
"products",
"=",
"(",
"mags",
"[",
"lagindex",
"]",
"-",
"magmed",
")",
... | This is an alternative function to calculate the autocorrelation.
This version is from (first definition):
https://en.wikipedia.org/wiki/Correlogram#Estimation_of_autocorrelations
Parameters
----------
mags : np.array
This is the magnitudes array. MUST NOT have any nans.
lag : float... | [
"This",
"is",
"an",
"alternative",
"function",
"to",
"calculate",
"the",
"autocorrelation",
"."
] | python | valid | 23.978261 |
LukeB42/Window | window.py | https://github.com/LukeB42/Window/blob/6d91c5ff94b8127e9c60f6eb78b7f9026d2faf62/window.py#L719-L750 | def palette(fg, bg=-1):
"""
Since curses only supports a finite amount of initialised colour pairs
we memoise any selections you've made as an attribute on this function
"""
if not hasattr(palette, "counter"):
palette.counter = 1
if not hasattr(palette, "selections"):
palette.s... | [
"def",
"palette",
"(",
"fg",
",",
"bg",
"=",
"-",
"1",
")",
":",
"if",
"not",
"hasattr",
"(",
"palette",
",",
"\"counter\"",
")",
":",
"palette",
".",
"counter",
"=",
"1",
"if",
"not",
"hasattr",
"(",
"palette",
",",
"\"selections\"",
")",
":",
"pa... | Since curses only supports a finite amount of initialised colour pairs
we memoise any selections you've made as an attribute on this function | [
"Since",
"curses",
"only",
"supports",
"a",
"finite",
"amount",
"of",
"initialised",
"colour",
"pairs",
"we",
"memoise",
"any",
"selections",
"you",
"ve",
"made",
"as",
"an",
"attribute",
"on",
"this",
"function"
] | python | train | 31.84375 |
Microsoft/azure-devops-python-api | azure-devops/azure/devops/v5_0/tfvc/tfvc_client.py | https://github.com/Microsoft/azure-devops-python-api/blob/4777ffda2f5052fabbaddb2abe9cb434e0cf1aa8/azure-devops/azure/devops/v5_0/tfvc/tfvc_client.py#L553-L574 | def get_label_items(self, label_id, top=None, skip=None):
"""GetLabelItems.
Get items under a label.
:param str label_id: Unique identifier of label
:param int top: Max number of items to return
:param int skip: Number of items to skip
:rtype: [TfvcItem]
"""
... | [
"def",
"get_label_items",
"(",
"self",
",",
"label_id",
",",
"top",
"=",
"None",
",",
"skip",
"=",
"None",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"label_id",
"is",
"not",
"None",
":",
"route_values",
"[",
"'labelId'",
"]",
"=",
"self",
".",
"... | GetLabelItems.
Get items under a label.
:param str label_id: Unique identifier of label
:param int top: Max number of items to return
:param int skip: Number of items to skip
:rtype: [TfvcItem] | [
"GetLabelItems",
".",
"Get",
"items",
"under",
"a",
"label",
".",
":",
"param",
"str",
"label_id",
":",
"Unique",
"identifier",
"of",
"label",
":",
"param",
"int",
"top",
":",
"Max",
"number",
"of",
"items",
"to",
"return",
":",
"param",
"int",
"skip",
... | python | train | 48.590909 |
uchicago-cs/deepdish | deepdish/io/ls.py | https://github.com/uchicago-cs/deepdish/blob/01af93621fe082a3972fe53ba7375388c02b0085/deepdish/io/ls.py#L117-L140 | def abbreviate(s, maxlength=25):
"""Color-aware abbreviator"""
assert maxlength >= 4
skip = False
abbrv = None
i = 0
for j, c in enumerate(s):
if c == '\033':
skip = True
elif skip:
if c == 'm':
skip = False
else:
i += 1... | [
"def",
"abbreviate",
"(",
"s",
",",
"maxlength",
"=",
"25",
")",
":",
"assert",
"maxlength",
">=",
"4",
"skip",
"=",
"False",
"abbrv",
"=",
"None",
"i",
"=",
"0",
"for",
"j",
",",
"c",
"in",
"enumerate",
"(",
"s",
")",
":",
"if",
"c",
"==",
"'\... | Color-aware abbreviator | [
"Color",
"-",
"aware",
"abbreviator"
] | python | train | 20.333333 |
by46/simplekit | simplekit/config/__init__.py | https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/config/__init__.py#L161-L194 | def get_namespace(self, namespace, lowercase=True, trim_namespace=True):
"""Returns a dictionary containing a subset of configuration options
that match the specified namespace/prefix. Example usage:
app.config['IMAGE_STORE_TYPE']='fs'
app.config['IMAGE_STORE_PATH']='/var/app... | [
"def",
"get_namespace",
"(",
"self",
",",
"namespace",
",",
"lowercase",
"=",
"True",
",",
"trim_namespace",
"=",
"True",
")",
":",
"rv",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"six",
".",
"iteritems",
"(",
"self",
")",
":",
"if",
"not",
... | Returns a dictionary containing a subset of configuration options
that match the specified namespace/prefix. Example usage:
app.config['IMAGE_STORE_TYPE']='fs'
app.config['IMAGE_STORE_PATH']='/var/app/images'
app.config['IMAGE_STORE_BASE_URL']='http://img.website.com'
... | [
"Returns",
"a",
"dictionary",
"containing",
"a",
"subset",
"of",
"configuration",
"options",
"that",
"match",
"the",
"specified",
"namespace",
"/",
"prefix",
".",
"Example",
"usage",
":",
"app",
".",
"config",
"[",
"IMAGE_STORE_TYPE",
"]",
"=",
"fs",
"app",
... | python | train | 42.147059 |
openego/ding0 | ding0/core/structure/regions.py | https://github.com/openego/ding0/blob/e2d6528f96255e4bb22ba15514a4f1883564ed5d/ding0/core/structure/regions.py#L236-L248 | def add_lv_grid_district(self, lv_grid_district):
# TODO: check docstring
"""Adds a LV grid district to _lv_grid_districts if not already existing
Args
----
lv_grid_district: :shapely:`Shapely Polygon object<polygons>`
Descr
"""
if lv_grid_di... | [
"def",
"add_lv_grid_district",
"(",
"self",
",",
"lv_grid_district",
")",
":",
"# TODO: check docstring",
"if",
"lv_grid_district",
"not",
"in",
"self",
".",
"_lv_grid_districts",
"and",
"isinstance",
"(",
"lv_grid_district",
",",
"LVGridDistrictDing0",
")",
":",
"sel... | Adds a LV grid district to _lv_grid_districts if not already existing
Args
----
lv_grid_district: :shapely:`Shapely Polygon object<polygons>`
Descr | [
"Adds",
"a",
"LV",
"grid",
"district",
"to",
"_lv_grid_districts",
"if",
"not",
"already",
"existing",
"Args",
"----",
"lv_grid_district",
":",
":",
"shapely",
":",
"Shapely",
"Polygon",
"object<polygons",
">",
"Descr"
] | python | train | 36.846154 |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/external/path/_path.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/external/path/_path.py#L478-L487 | def glob(self, pattern):
""" Return a list of path objects that match the pattern.
pattern - a path relative to this directory, with wildcards.
For example, path('/users').glob('*/bin/*') returns a list
of all the files users have in their bin directories.
"""
cls = sel... | [
"def",
"glob",
"(",
"self",
",",
"pattern",
")",
":",
"cls",
"=",
"self",
".",
"__class__",
"return",
"[",
"cls",
"(",
"s",
")",
"for",
"s",
"in",
"glob",
".",
"glob",
"(",
"unicode",
"(",
"self",
"/",
"pattern",
")",
")",
"]"
] | Return a list of path objects that match the pattern.
pattern - a path relative to this directory, with wildcards.
For example, path('/users').glob('*/bin/*') returns a list
of all the files users have in their bin directories. | [
"Return",
"a",
"list",
"of",
"path",
"objects",
"that",
"match",
"the",
"pattern",
"."
] | python | test | 39 |
matousc89/padasip | padasip/filters/__init__.py | https://github.com/matousc89/padasip/blob/c969eadd7fa181a84da0554d737fc13c6450d16f/padasip/filters/__init__.py#L230-L281 | def AdaptiveFilter(model="lms", **kwargs):
"""
Function that filter data with selected adaptive filter.
**Args:**
* `d` : desired value (1 dimensional array)
* `x` : input matrix (2-dimensional array). Rows are samples, columns are
input arrays.
**Kwargs:**
* Any ... | [
"def",
"AdaptiveFilter",
"(",
"model",
"=",
"\"lms\"",
",",
"*",
"*",
"kwargs",
")",
":",
"# check if the filter size was specified",
"if",
"not",
"\"n\"",
"in",
"kwargs",
":",
"raise",
"ValueError",
"(",
"'Filter size is not defined (n=?).'",
")",
"# create filter ac... | Function that filter data with selected adaptive filter.
**Args:**
* `d` : desired value (1 dimensional array)
* `x` : input matrix (2-dimensional array). Rows are samples, columns are
input arrays.
**Kwargs:**
* Any key argument that can be accepted with selected filter ... | [
"Function",
"that",
"filter",
"data",
"with",
"selected",
"adaptive",
"filter",
".",
"**",
"Args",
":",
"**"
] | python | train | 30.192308 |
log2timeline/plaso | plaso/cli/helpers/status_view.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/cli/helpers/status_view.py#L37-L56 | def ParseOptions(cls, options, configuration_object):
"""Parses and validates options.
Args:
options (argparse.Namespace): parser options.
configuration_object (CLITool): object to be configured by the argument
helper.
Raises:
BadConfigObject: when the configuration object is o... | [
"def",
"ParseOptions",
"(",
"cls",
",",
"options",
",",
"configuration_object",
")",
":",
"if",
"not",
"isinstance",
"(",
"configuration_object",
",",
"tools",
".",
"CLITool",
")",
":",
"raise",
"errors",
".",
"BadConfigObject",
"(",
"'Configuration object is not ... | Parses and validates options.
Args:
options (argparse.Namespace): parser options.
configuration_object (CLITool): object to be configured by the argument
helper.
Raises:
BadConfigObject: when the configuration object is of the wrong type. | [
"Parses",
"and",
"validates",
"options",
"."
] | python | train | 35.15 |
openvax/isovar | isovar/variant_sequences.py | https://github.com/openvax/isovar/blob/b39b684920e3f6b344851d6598a1a1c67bce913b/isovar/variant_sequences.py#L339-L352 | def filter_variant_sequences(
variant_sequences,
preferred_sequence_length,
min_variant_sequence_coverage=MIN_VARIANT_SEQUENCE_COVERAGE,):
"""
Drop variant sequences which are shorter than request or don't have
enough supporting reads.
"""
variant_sequences = trim_variant_seq... | [
"def",
"filter_variant_sequences",
"(",
"variant_sequences",
",",
"preferred_sequence_length",
",",
"min_variant_sequence_coverage",
"=",
"MIN_VARIANT_SEQUENCE_COVERAGE",
",",
")",
":",
"variant_sequences",
"=",
"trim_variant_sequences",
"(",
"variant_sequences",
",",
"min_vari... | Drop variant sequences which are shorter than request or don't have
enough supporting reads. | [
"Drop",
"variant",
"sequences",
"which",
"are",
"shorter",
"than",
"request",
"or",
"don",
"t",
"have",
"enough",
"supporting",
"reads",
"."
] | python | train | 37.571429 |
gwpy/gwpy | gwpy/types/array.py | https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/types/array.py#L307-L318 | def epoch(self):
"""GPS epoch associated with these data
:type: `~astropy.time.Time`
"""
try:
if self._epoch is None:
return None
return Time(*modf(self._epoch)[::-1], format='gps', scale='utc')
except AttributeError:
self._epo... | [
"def",
"epoch",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"_epoch",
"is",
"None",
":",
"return",
"None",
"return",
"Time",
"(",
"*",
"modf",
"(",
"self",
".",
"_epoch",
")",
"[",
":",
":",
"-",
"1",
"]",
",",
"format",
"=",
"'gps'",... | GPS epoch associated with these data
:type: `~astropy.time.Time` | [
"GPS",
"epoch",
"associated",
"with",
"these",
"data"
] | python | train | 29.083333 |
dshean/pygeotools | pygeotools/lib/geolib.py | https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/geolib.py#L1288-L1314 | def ds_IsEmpty(ds):
"""Check to see if dataset is empty after warp
"""
out = False
b = ds.GetRasterBand(1)
#Looks like this throws:
#ERROR 1: Failed to compute min/max, no valid pixels found in sampling.
#Should just catch this rater than bothering with logic below
try:
mm = b.C... | [
"def",
"ds_IsEmpty",
"(",
"ds",
")",
":",
"out",
"=",
"False",
"b",
"=",
"ds",
".",
"GetRasterBand",
"(",
"1",
")",
"#Looks like this throws:",
"#ERROR 1: Failed to compute min/max, no valid pixels found in sampling.",
"#Should just catch this rater than bothering with logic be... | Check to see if dataset is empty after warp | [
"Check",
"to",
"see",
"if",
"dataset",
"is",
"empty",
"after",
"warp"
] | python | train | 27.592593 |
glue-viz/glue-vispy-viewers | glue_vispy_viewers/extern/vispy/gloo/wrappers.py | https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/gloo/wrappers.py#L533-L545 | def finish(self):
"""Wait for GL commands to to finish
This creates a GLIR command for glFinish and then processes the
GLIR commands. If the GLIR interpreter is remote (e.g. WebGL), this
function will return before GL has finished processing the commands.
"""
if ... | [
"def",
"finish",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'flush_commands'",
")",
":",
"context",
"=",
"self",
"else",
":",
"context",
"=",
"get_current_canvas",
"(",
")",
".",
"context",
"context",
".",
"glir",
".",
"command",
"(",
"... | Wait for GL commands to to finish
This creates a GLIR command for glFinish and then processes the
GLIR commands. If the GLIR interpreter is remote (e.g. WebGL), this
function will return before GL has finished processing the commands. | [
"Wait",
"for",
"GL",
"commands",
"to",
"to",
"finish",
"This",
"creates",
"a",
"GLIR",
"command",
"for",
"glFinish",
"and",
"then",
"processes",
"the",
"GLIR",
"commands",
".",
"If",
"the",
"GLIR",
"interpreter",
"is",
"remote",
"(",
"e",
".",
"g",
".",
... | python | train | 39.538462 |
howie6879/ruia | ruia/spider.py | https://github.com/howie6879/ruia/blob/2dc5262fc9c3e902a8faa7d5fa2f046f9d9ee1fa/ruia/spider.py#L315-L325 | async def handle_callback(self, aws_callback: typing.Coroutine, response):
"""Process coroutine callback function"""
callback_result = None
try:
callback_result = await aws_callback
except NothingMatchedError as e:
self.logger.error(f'<Item: {str(e).lower()}>')
... | [
"async",
"def",
"handle_callback",
"(",
"self",
",",
"aws_callback",
":",
"typing",
".",
"Coroutine",
",",
"response",
")",
":",
"callback_result",
"=",
"None",
"try",
":",
"callback_result",
"=",
"await",
"aws_callback",
"except",
"NothingMatchedError",
"as",
"... | Process coroutine callback function | [
"Process",
"coroutine",
"callback",
"function"
] | python | test | 41.272727 |
ShadowBlip/Neteria | neteria/core.py | https://github.com/ShadowBlip/Neteria/blob/1a8c976eb2beeca0a5a272a34ac58b2c114495a4/neteria/core.py#L244-L267 | def scheduler(self, sleep_time=0.2):
"""Starts the scheduler to check for scheduled calls and execute them
at the correct time.
Args:
sleep_time (float): The amount of time to wait in seconds between
each loop iteration. This prevents the scheduler from consuming
... | [
"def",
"scheduler",
"(",
"self",
",",
"sleep_time",
"=",
"0.2",
")",
":",
"while",
"self",
".",
"listening",
":",
"# If we have any scheduled calls, execute them and remove them from",
"# our list of scheduled calls.",
"if",
"self",
".",
"scheduled_calls",
":",
"timestamp... | Starts the scheduler to check for scheduled calls and execute them
at the correct time.
Args:
sleep_time (float): The amount of time to wait in seconds between
each loop iteration. This prevents the scheduler from consuming
100% of the host's CPU. Defaults to 0.2 secon... | [
"Starts",
"the",
"scheduler",
"to",
"check",
"for",
"scheduled",
"calls",
"and",
"execute",
"them",
"at",
"the",
"correct",
"time",
"."
] | python | train | 36.958333 |
django-parler/django-parler | parler/models.py | https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/models.py#L349-L357 | def set_current_language(self, language_code, initialize=False):
"""
Switch the currently activate language of the object.
"""
self._current_language = normalize_language_code(language_code or get_language())
# Ensure the translation is present for __get__ queries.
if in... | [
"def",
"set_current_language",
"(",
"self",
",",
"language_code",
",",
"initialize",
"=",
"False",
")",
":",
"self",
".",
"_current_language",
"=",
"normalize_language_code",
"(",
"language_code",
"or",
"get_language",
"(",
")",
")",
"# Ensure the translation is prese... | Switch the currently activate language of the object. | [
"Switch",
"the",
"currently",
"activate",
"language",
"of",
"the",
"object",
"."
] | python | train | 44.222222 |
ikegami-yukino/madoka-python | madoka/madoka.py | https://github.com/ikegami-yukino/madoka-python/blob/a9a1efecbc85ac4a24a78cbb19f9aed77b7162d3/madoka/madoka.py#L346-L359 | def set(self, key, value, key_length=0):
"""Set value to key-value
Params:
<str> key
<int> value
<int> key_length
Return:
<int> key_value
"""
if key_length < 1:
key_length = len(key)
if self.k:
self._... | [
"def",
"set",
"(",
"self",
",",
"key",
",",
"value",
",",
"key_length",
"=",
"0",
")",
":",
"if",
"key_length",
"<",
"1",
":",
"key_length",
"=",
"len",
"(",
"key",
")",
"if",
"self",
".",
"k",
":",
"self",
".",
"_update",
"(",
"key",
",",
"val... | Set value to key-value
Params:
<str> key
<int> value
<int> key_length
Return:
<int> key_value | [
"Set",
"value",
"to",
"key",
"-",
"value",
"Params",
":",
"<str",
">",
"key",
"<int",
">",
"value",
"<int",
">",
"key_length",
"Return",
":",
"<int",
">",
"key_value"
] | python | train | 27.571429 |
abarker/pdfCropMargins | src/pdfCropMargins/main_pdfCropMargins.py | https://github.com/abarker/pdfCropMargins/blob/55aca874613750ebf4ae69fd8851bdbb7696d6ac/src/pdfCropMargins/main_pdfCropMargins.py#L207-L236 | def get_full_page_box_list_assigning_media_and_crop(input_doc, quiet=False):
"""Get a list of all the full-page box values for each page. The argument
input_doc should be a PdfFileReader object. The boxes on the list are in the
simple 4-float list format used by this program, not RectangleObject format.""... | [
"def",
"get_full_page_box_list_assigning_media_and_crop",
"(",
"input_doc",
",",
"quiet",
"=",
"False",
")",
":",
"full_page_box_list",
"=",
"[",
"]",
"rotation_list",
"=",
"[",
"]",
"if",
"args",
".",
"verbose",
"and",
"not",
"quiet",
":",
"print",
"(",
"\"\\... | Get a list of all the full-page box values for each page. The argument
input_doc should be a PdfFileReader object. The boxes on the list are in the
simple 4-float list format used by this program, not RectangleObject format. | [
"Get",
"a",
"list",
"of",
"all",
"the",
"full",
"-",
"page",
"box",
"values",
"for",
"each",
"page",
".",
"The",
"argument",
"input_doc",
"should",
"be",
"a",
"PdfFileReader",
"object",
".",
"The",
"boxes",
"on",
"the",
"list",
"are",
"in",
"the",
"sim... | python | train | 41.8 |
ladybug-tools/ladybug | ladybug/psychrometrics.py | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/psychrometrics.py#L8-L40 | def saturated_vapor_pressure(t_kelvin):
"""Saturated Vapor Pressure (Pa) at t_kelvin (K).
This function accounts for the different behaviour above vs. below
the freezing point of water.
Note:
[1] W. Wagner and A. Pru:" The IAPWS Formulation 1995 for the Thermodynamic
Properties of Ordi... | [
"def",
"saturated_vapor_pressure",
"(",
"t_kelvin",
")",
":",
"if",
"t_kelvin",
">=",
"273.15",
":",
"# Calculate saturation vapor pressure above freezing",
"sig",
"=",
"1",
"-",
"(",
"t_kelvin",
"/",
"647.096",
")",
"sig_polynomial",
"=",
"(",
"-",
"7.85951783",
... | Saturated Vapor Pressure (Pa) at t_kelvin (K).
This function accounts for the different behaviour above vs. below
the freezing point of water.
Note:
[1] W. Wagner and A. Pru:" The IAPWS Formulation 1995 for the Thermodynamic
Properties of Ordinary Water Substance for General and Scientific... | [
"Saturated",
"Vapor",
"Pressure",
"(",
"Pa",
")",
"at",
"t_kelvin",
"(",
"K",
")",
"."
] | python | train | 42.515152 |
major/supernova | supernova/credentials.py | https://github.com/major/supernova/blob/4a217ae53c1c05567014b047c0b6b9dea2d383b3/supernova/credentials.py#L53-L70 | def pull_env_credential(env, param, value):
"""
Dissects a keyring credential lookup string from the supernova config file
and returns the username/password combo
"""
rex = "USE_KEYRING\[([\x27\x22])(.*)\\1\]"
# This is the old-style, per-environment keyring credential
if value == "USE_KEYR... | [
"def",
"pull_env_credential",
"(",
"env",
",",
"param",
",",
"value",
")",
":",
"rex",
"=",
"\"USE_KEYRING\\[([\\x27\\x22])(.*)\\\\1\\]\"",
"# This is the old-style, per-environment keyring credential",
"if",
"value",
"==",
"\"USE_KEYRING\"",
":",
"username",
"=",
"utils",
... | Dissects a keyring credential lookup string from the supernova config file
and returns the username/password combo | [
"Dissects",
"a",
"keyring",
"credential",
"lookup",
"string",
"from",
"the",
"supernova",
"config",
"file",
"and",
"returns",
"the",
"username",
"/",
"password",
"combo"
] | python | train | 36.5 |
dereneaton/ipyrad | ipyrad/core/assembly.py | https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/core/assembly.py#L560-L620 | def _link_barcodes(self):
"""
Private function. Links Sample barcodes in a dictionary as
[Assembly].barcodes, with barcodes parsed from the 'barcodes_path'
parameter. This function is called during set_params() when setting
the barcodes_path.
"""
## parse barcode... | [
"def",
"_link_barcodes",
"(",
"self",
")",
":",
"## parse barcodefile",
"try",
":",
"## allows fuzzy match to barcodefile name",
"barcodefile",
"=",
"glob",
".",
"glob",
"(",
"self",
".",
"paramsdict",
"[",
"\"barcodes_path\"",
"]",
")",
"[",
"0",
"]",
"## read in... | Private function. Links Sample barcodes in a dictionary as
[Assembly].barcodes, with barcodes parsed from the 'barcodes_path'
parameter. This function is called during set_params() when setting
the barcodes_path. | [
"Private",
"function",
".",
"Links",
"Sample",
"barcodes",
"in",
"a",
"dictionary",
"as",
"[",
"Assembly",
"]",
".",
"barcodes",
"with",
"barcodes",
"parsed",
"from",
"the",
"barcodes_path",
"parameter",
".",
"This",
"function",
"is",
"called",
"during",
"set_... | python | valid | 42.540984 |
danielperna84/pyhomematic | pyhomematic/devicetypes/helper.py | https://github.com/danielperna84/pyhomematic/blob/8b91f3e84c83f05d289c740d507293a0d6759d8e/pyhomematic/devicetypes/helper.py#L158-L166 | def set_level(self, position, channel=None):
"""Seek a specific value by specifying a float() from 0.0 to 1.0."""
try:
position = float(position)
except Exception as err:
LOG.debug("HelperLevel.set_level: Exception %s" % (err,))
return False
self.writ... | [
"def",
"set_level",
"(",
"self",
",",
"position",
",",
"channel",
"=",
"None",
")",
":",
"try",
":",
"position",
"=",
"float",
"(",
"position",
")",
"except",
"Exception",
"as",
"err",
":",
"LOG",
".",
"debug",
"(",
"\"HelperLevel.set_level: Exception %s\"",... | Seek a specific value by specifying a float() from 0.0 to 1.0. | [
"Seek",
"a",
"specific",
"value",
"by",
"specifying",
"a",
"float",
"()",
"from",
"0",
".",
"0",
"to",
"1",
".",
"0",
"."
] | python | train | 38.777778 |
Cognexa/cxflow | cxflow/cli/ls.py | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/ls.py#L35-L40 | def humanize_filesize(filesize: int) -> Tuple[str, str]:
"""Return human readable pair of size and unit from the given filesize in bytes."""
for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:
if filesize < 1024.0:
return '{:3.1f}'.format(filesize), unit+'B'
filesize /= 1024.0 | [
"def",
"humanize_filesize",
"(",
"filesize",
":",
"int",
")",
"->",
"Tuple",
"[",
"str",
",",
"str",
"]",
":",
"for",
"unit",
"in",
"[",
"''",
",",
"'K'",
",",
"'M'",
",",
"'G'",
",",
"'T'",
",",
"'P'",
",",
"'E'",
",",
"'Z'",
"]",
":",
"if",
... | Return human readable pair of size and unit from the given filesize in bytes. | [
"Return",
"human",
"readable",
"pair",
"of",
"size",
"and",
"unit",
"from",
"the",
"given",
"filesize",
"in",
"bytes",
"."
] | python | train | 51.5 |
zetaops/zengine | zengine/auth/permissions.py | https://github.com/zetaops/zengine/blob/b5bc32d3b37bca799f8985be916f04528ac79e4a/zengine/auth/permissions.py#L95-L106 | def _get_object_menu_models():
"""
we need to create basic permissions
for only CRUD enabled models
"""
from pyoko.conf import settings
enabled_models = []
for entry in settings.OBJECT_MENU.values():
for mdl in entry:
if 'wf' not in mdl:
enabled_models.app... | [
"def",
"_get_object_menu_models",
"(",
")",
":",
"from",
"pyoko",
".",
"conf",
"import",
"settings",
"enabled_models",
"=",
"[",
"]",
"for",
"entry",
"in",
"settings",
".",
"OBJECT_MENU",
".",
"values",
"(",
")",
":",
"for",
"mdl",
"in",
"entry",
":",
"i... | we need to create basic permissions
for only CRUD enabled models | [
"we",
"need",
"to",
"create",
"basic",
"permissions",
"for",
"only",
"CRUD",
"enabled",
"models"
] | python | train | 29.25 |
abilian/abilian-core | abilian/web/errors.py | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/errors.py#L141-L151 | def install_default_handler(self, http_error_code):
"""Install a default error handler for `http_error_code`.
The default error handler renders a template named error404.html
for http_error_code 404.
"""
logger.debug(
"Set Default HTTP error handler for status code %... | [
"def",
"install_default_handler",
"(",
"self",
",",
"http_error_code",
")",
":",
"logger",
".",
"debug",
"(",
"\"Set Default HTTP error handler for status code %d\"",
",",
"http_error_code",
")",
"handler",
"=",
"partial",
"(",
"self",
".",
"handle_http_error",
",",
"... | Install a default error handler for `http_error_code`.
The default error handler renders a template named error404.html
for http_error_code 404. | [
"Install",
"a",
"default",
"error",
"handler",
"for",
"http_error_code",
"."
] | python | train | 41.636364 |
berndca/xmodels | xmodels/models.py | https://github.com/berndca/xmodels/blob/8265522229a1ce482a2866cdbd1938293a74bb67/xmodels/models.py#L252-L259 | def from_dict(cls, raw_data, **kwargs):
"""
This factory for :class:`Model` creates a Model from a dict object.
"""
instance = cls()
instance.populate(raw_data, **kwargs)
instance.validate(**kwargs)
return instance | [
"def",
"from_dict",
"(",
"cls",
",",
"raw_data",
",",
"*",
"*",
"kwargs",
")",
":",
"instance",
"=",
"cls",
"(",
")",
"instance",
".",
"populate",
"(",
"raw_data",
",",
"*",
"*",
"kwargs",
")",
"instance",
".",
"validate",
"(",
"*",
"*",
"kwargs",
... | This factory for :class:`Model` creates a Model from a dict object. | [
"This",
"factory",
"for",
":",
"class",
":",
"Model",
"creates",
"a",
"Model",
"from",
"a",
"dict",
"object",
"."
] | python | train | 32.875 |
olitheolix/qtmacs | qtmacs/auxiliary.py | https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/auxiliary.py#L694-L721 | def appendQKeyEvent(self, keyEvent: QtGui.QKeyEvent):
"""
Append another key to the key sequence represented by this object.
|Args|
* ``keyEvent`` (**QKeyEvent**): the key to add.
|Returns|
**None**
|Raises|
* **QtmacsArgumentError** if at least one ... | [
"def",
"appendQKeyEvent",
"(",
"self",
",",
"keyEvent",
":",
"QtGui",
".",
"QKeyEvent",
")",
":",
"# Store the QKeyEvent.",
"self",
".",
"keylistKeyEvent",
".",
"append",
"(",
"keyEvent",
")",
"# Convenience shortcuts.",
"mod",
"=",
"keyEvent",
".",
"modifiers",
... | Append another key to the key sequence represented by this object.
|Args|
* ``keyEvent`` (**QKeyEvent**): the key to add.
|Returns|
**None**
|Raises|
* **QtmacsArgumentError** if at least one argument has an invalid type. | [
"Append",
"another",
"key",
"to",
"the",
"key",
"sequence",
"represented",
"by",
"this",
"object",
"."
] | python | train | 28.892857 |
tdryer/hangups | hangups/conversation.py | https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L337-L352 | def _wrap_event(event_):
"""Wrap hangouts_pb2.Event in ConversationEvent subclass."""
cls = conversation_event.ConversationEvent
if event_.HasField('chat_message'):
cls = conversation_event.ChatMessageEvent
elif event_.HasField('otr_modification'):
cls = conversat... | [
"def",
"_wrap_event",
"(",
"event_",
")",
":",
"cls",
"=",
"conversation_event",
".",
"ConversationEvent",
"if",
"event_",
".",
"HasField",
"(",
"'chat_message'",
")",
":",
"cls",
"=",
"conversation_event",
".",
"ChatMessageEvent",
"elif",
"event_",
".",
"HasFie... | Wrap hangouts_pb2.Event in ConversationEvent subclass. | [
"Wrap",
"hangouts_pb2",
".",
"Event",
"in",
"ConversationEvent",
"subclass",
"."
] | python | valid | 49.6875 |
hammerlab/cohorts | cohorts/varcode_utils.py | https://github.com/hammerlab/cohorts/blob/278b05e609e6c4d4a77c57d49446460be53ea33e/cohorts/varcode_utils.py#L79-L105 | def filter_variants(variant_collection, patient, filter_fn, **kwargs):
"""Filter variants from the Variant Collection
Parameters
----------
variant_collection : varcode.VariantCollection
patient : cohorts.Patient
filter_fn: function
Takes a FilterableVariant and returns a boolean. Only ... | [
"def",
"filter_variants",
"(",
"variant_collection",
",",
"patient",
",",
"filter_fn",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"filter_fn",
":",
"return",
"variant_collection",
".",
"clone_with_new_elements",
"(",
"[",
"variant",
"for",
"variant",
"in",
"varian... | Filter variants from the Variant Collection
Parameters
----------
variant_collection : varcode.VariantCollection
patient : cohorts.Patient
filter_fn: function
Takes a FilterableVariant and returns a boolean. Only variants returning True are preserved.
Returns
-------
varcode.Va... | [
"Filter",
"variants",
"from",
"the",
"Variant",
"Collection"
] | python | train | 33.296296 |
Kozea/pygal | pygal/graph/graph.py | https://github.com/Kozea/pygal/blob/5e25c98a59a0642eecd9fcc5dbfeeb2190fbb5e7/pygal/graph/graph.py#L861-L868 | def _secondary_min(self):
"""Getter for the minimum series value"""
return (
self.secondary_range[0]
if (self.secondary_range
and self.secondary_range[0] is not None) else
(min(self._secondary_values) if self._secondary_values else None)
) | [
"def",
"_secondary_min",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"secondary_range",
"[",
"0",
"]",
"if",
"(",
"self",
".",
"secondary_range",
"and",
"self",
".",
"secondary_range",
"[",
"0",
"]",
"is",
"not",
"None",
")",
"else",
"(",
"min",... | Getter for the minimum series value | [
"Getter",
"for",
"the",
"minimum",
"series",
"value"
] | python | train | 38.5 |
shoyer/cyordereddict | python3/cyordereddict/benchmark/magic_timeit.py | https://github.com/shoyer/cyordereddict/blob/248e3e8616441554c87175820204e269a3afb32a/python3/cyordereddict/benchmark/magic_timeit.py#L7-L77 | def magic_timeit(setup, stmt, ncalls=None, repeat=3, force_ms=False):
"""Time execution of a Python statement or expression
Usage:\\
%timeit [-n<N> -r<R> [-t|-c]] statement
Time execution of a Python statement or expression using the timeit
module.
Options:
-n<N>: execute the given stateme... | [
"def",
"magic_timeit",
"(",
"setup",
",",
"stmt",
",",
"ncalls",
"=",
"None",
",",
"repeat",
"=",
"3",
",",
"force_ms",
"=",
"False",
")",
":",
"import",
"timeit",
"import",
"math",
"units",
"=",
"[",
"\"s\"",
",",
"\"ms\"",
",",
"'us'",
",",
"\"ns\"... | Time execution of a Python statement or expression
Usage:\\
%timeit [-n<N> -r<R> [-t|-c]] statement
Time execution of a Python statement or expression using the timeit
module.
Options:
-n<N>: execute the given statement <N> times in a loop. If this value
is not given, a fitting value is ch... | [
"Time",
"execution",
"of",
"a",
"Python",
"statement",
"or",
"expression",
"Usage",
":",
"\\\\",
"%timeit",
"[",
"-",
"n<N",
">",
"-",
"r<R",
">",
"[",
"-",
"t|",
"-",
"c",
"]]",
"statement",
"Time",
"execution",
"of",
"a",
"Python",
"statement",
"or",... | python | train | 34.971831 |
ajenhl/tacl | tacl/data_store.py | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L266-L291 | def _csv(self, cursor, fieldnames, output_fh):
"""Writes the rows of `cursor` in CSV format to `output_fh`
and returns it.
:param cursor: database cursor containing data to be output
:type cursor: `sqlite3.Cursor`
:param fieldnames: row headings
:type fieldnames: `list`
... | [
"def",
"_csv",
"(",
"self",
",",
"cursor",
",",
"fieldnames",
",",
"output_fh",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'Finished query; outputting results in CSV format'",
")",
"# Specify a lineterminator to avoid an extra \\r being added on",
"# Windows; see"... | Writes the rows of `cursor` in CSV format to `output_fh`
and returns it.
:param cursor: database cursor containing data to be output
:type cursor: `sqlite3.Cursor`
:param fieldnames: row headings
:type fieldnames: `list`
:param output_fh: file to write data to
:t... | [
"Writes",
"the",
"rows",
"of",
"cursor",
"in",
"CSV",
"format",
"to",
"output_fh",
"and",
"returns",
"it",
"."
] | python | train | 40.923077 |
KeplerGO/K2fov | K2fov/fov.py | https://github.com/KeplerGO/K2fov/blob/fb122b35687340e0357cba9e0dd47b3be0760693/K2fov/fov.py#L756-L770 | def draw(self, **kwargs):
"""Draw the polygon
Optional Inputs:
------------
All optional inputs are passed to ``matplotlib.patches.Polygon``
Notes:
---------
Does not accept maptype as an argument.
"""
ax = mp.gca()
shape = matplotlib.pa... | [
"def",
"draw",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"ax",
"=",
"mp",
".",
"gca",
"(",
")",
"shape",
"=",
"matplotlib",
".",
"patches",
".",
"Polygon",
"(",
"self",
".",
"polygon",
",",
"*",
"*",
"kwargs",
")",
"ax",
".",
"add_artist",
... | Draw the polygon
Optional Inputs:
------------
All optional inputs are passed to ``matplotlib.patches.Polygon``
Notes:
---------
Does not accept maptype as an argument. | [
"Draw",
"the",
"polygon"
] | python | train | 24.8 |
olsoneric/pedemath | pedemath/vec2.py | https://github.com/olsoneric/pedemath/blob/4bffcfe7089e421d603eb0a9708b84789c2d16be/pedemath/vec2.py#L80-L86 | def cross_v2(vec1, vec2):
"""Return the crossproduct of the two vectors as a Vec2.
Cross product doesn't really make sense in 2D, but return the Z component
of the 3d result.
"""
return vec1.y * vec2.x - vec1.x * vec2.y | [
"def",
"cross_v2",
"(",
"vec1",
",",
"vec2",
")",
":",
"return",
"vec1",
".",
"y",
"*",
"vec2",
".",
"x",
"-",
"vec1",
".",
"x",
"*",
"vec2",
".",
"y"
] | Return the crossproduct of the two vectors as a Vec2.
Cross product doesn't really make sense in 2D, but return the Z component
of the 3d result. | [
"Return",
"the",
"crossproduct",
"of",
"the",
"two",
"vectors",
"as",
"a",
"Vec2",
".",
"Cross",
"product",
"doesn",
"t",
"really",
"make",
"sense",
"in",
"2D",
"but",
"return",
"the",
"Z",
"component",
"of",
"the",
"3d",
"result",
"."
] | python | train | 33.428571 |
apache/incubator-mxnet | tools/coreml/converter/_layers.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/tools/coreml/converter/_layers.py#L188-L220 | def convert_activation(net, node, module, builder):
"""Convert an activation layer from mxnet to coreml.
Parameters
----------
network: net
A mxnet network object.
layer: node
Node to convert.
module: module
An module for MXNet
builder: NeuralNetworkBuilder
... | [
"def",
"convert_activation",
"(",
"net",
",",
"node",
",",
"module",
",",
"builder",
")",
":",
"input_name",
",",
"output_name",
"=",
"_get_input_output_name",
"(",
"net",
",",
"node",
")",
"name",
"=",
"node",
"[",
"'name'",
"]",
"mx_non_linearity",
"=",
... | Convert an activation layer from mxnet to coreml.
Parameters
----------
network: net
A mxnet network object.
layer: node
Node to convert.
module: module
An module for MXNet
builder: NeuralNetworkBuilder
A neural network builder object. | [
"Convert",
"an",
"activation",
"layer",
"from",
"mxnet",
"to",
"coreml",
"."
] | python | train | 33.121212 |
log2timeline/dfvfs | dfvfs/vfs/cpio_file_entry.py | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/cpio_file_entry.py#L108-L116 | def _GetDirectory(self):
"""Retrieves a directory.
Returns:
CPIODirectory: a directory or None if not available.
"""
if self.entry_type != definitions.FILE_ENTRY_TYPE_DIRECTORY:
return None
return CPIODirectory(self._file_system, self.path_spec) | [
"def",
"_GetDirectory",
"(",
"self",
")",
":",
"if",
"self",
".",
"entry_type",
"!=",
"definitions",
".",
"FILE_ENTRY_TYPE_DIRECTORY",
":",
"return",
"None",
"return",
"CPIODirectory",
"(",
"self",
".",
"_file_system",
",",
"self",
".",
"path_spec",
")"
] | Retrieves a directory.
Returns:
CPIODirectory: a directory or None if not available. | [
"Retrieves",
"a",
"directory",
"."
] | python | train | 30 |
PyHDI/Pyverilog | pyverilog/vparser/parser.py | https://github.com/PyHDI/Pyverilog/blob/b852cc5ed6a7a2712e33639f9d9782d0d1587a53/pyverilog/vparser/parser.py#L107-L111 | def p_pragma_assign(self, p):
'pragma : LPAREN TIMES ID EQUALS expression TIMES RPAREN'
p[0] = Pragma(PragmaEntry(p[3], p[5], lineno=p.lineno(1)),
lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | [
"def",
"p_pragma_assign",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"Pragma",
"(",
"PragmaEntry",
"(",
"p",
"[",
"3",
"]",
",",
"p",
"[",
"5",
"]",
",",
"lineno",
"=",
"p",
".",
"lineno",
"(",
"1",
")",
")",
",",
"lineno",
"... | pragma : LPAREN TIMES ID EQUALS expression TIMES RPAREN | [
"pragma",
":",
"LPAREN",
"TIMES",
"ID",
"EQUALS",
"expression",
"TIMES",
"RPAREN"
] | python | train | 47.4 |
googledatalab/pydatalab | google/datalab/contrib/mlworkbench/_prediction_explainer.py | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/mlworkbench/_prediction_explainer.py#L56-L71 | def _make_text_predict_fn(self, labels, instance, column_to_explain):
"""Create a predict_fn that can be used by LIME text explainer. """
def _predict_fn(perturbed_text):
predict_input = []
for x in perturbed_text:
instance_copy = dict(instance)
i... | [
"def",
"_make_text_predict_fn",
"(",
"self",
",",
"labels",
",",
"instance",
",",
"column_to_explain",
")",
":",
"def",
"_predict_fn",
"(",
"perturbed_text",
")",
":",
"predict_input",
"=",
"[",
"]",
"for",
"x",
"in",
"perturbed_text",
":",
"instance_copy",
"=... | Create a predict_fn that can be used by LIME text explainer. | [
"Create",
"a",
"predict_fn",
"that",
"can",
"be",
"used",
"by",
"LIME",
"text",
"explainer",
"."
] | python | train | 43.875 |
Fantomas42/mots-vides | mots_vides/factory.py | https://github.com/Fantomas42/mots-vides/blob/eaeccf73bdb415d0c5559ccd74de360b37a2bbac/mots_vides/factory.py#L111-L118 | def write_collection(self, filename, collection):
"""
Writes a collection of stop words into a file.
"""
collection = sorted(list(collection))
with open(filename, 'wb+') as fd:
fd.truncate()
fd.write('\n'.join(collection).encode('utf-8')) | [
"def",
"write_collection",
"(",
"self",
",",
"filename",
",",
"collection",
")",
":",
"collection",
"=",
"sorted",
"(",
"list",
"(",
"collection",
")",
")",
"with",
"open",
"(",
"filename",
",",
"'wb+'",
")",
"as",
"fd",
":",
"fd",
".",
"truncate",
"("... | Writes a collection of stop words into a file. | [
"Writes",
"a",
"collection",
"of",
"stop",
"words",
"into",
"a",
"file",
"."
] | python | train | 36.875 |
dacut/python-aws-sig | awssig/sigv4.py | https://github.com/dacut/python-aws-sig/blob/7f6054dca4b32e67ca3d39db31c1b4be5efe54bd/awssig/sigv4.py#L302-L325 | def canonical_request(self):
"""
The AWS SigV4 canonical request given parameters from an HTTP request.
This process is outlined here:
http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
The canonical request is:
request_method + '\n' +
... | [
"def",
"canonical_request",
"(",
"self",
")",
":",
"signed_headers",
"=",
"self",
".",
"signed_headers",
"header_lines",
"=",
"\"\"",
".",
"join",
"(",
"[",
"\"%s:%s\\n\"",
"%",
"item",
"for",
"item",
"in",
"iteritems",
"(",
"signed_headers",
")",
"]",
")",
... | The AWS SigV4 canonical request given parameters from an HTTP request.
This process is outlined here:
http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
The canonical request is:
request_method + '\n' +
canonical_uri_path + '\n' +
... | [
"The",
"AWS",
"SigV4",
"canonical",
"request",
"given",
"parameters",
"from",
"an",
"HTTP",
"request",
".",
"This",
"process",
"is",
"outlined",
"here",
":",
"http",
":",
"//",
"docs",
".",
"aws",
".",
"amazon",
".",
"com",
"/",
"general",
"/",
"latest",... | python | train | 40.333333 |
bukun/TorCMS | torcms/handlers/log_handler.py | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/log_handler.py#L151-L183 | def pageview(self, cur_p=''):
'''
View the list of the Log.
'''
if cur_p == '':
current_page_number = 1
else:
current_page_number = int(cur_p)
current_page_number = 1 if current_page_number < 1 else current_page_number
pager_num = int(ML... | [
"def",
"pageview",
"(",
"self",
",",
"cur_p",
"=",
"''",
")",
":",
"if",
"cur_p",
"==",
"''",
":",
"current_page_number",
"=",
"1",
"else",
":",
"current_page_number",
"=",
"int",
"(",
"cur_p",
")",
"current_page_number",
"=",
"1",
"if",
"current_page_numb... | View the list of the Log. | [
"View",
"the",
"list",
"of",
"the",
"Log",
"."
] | python | train | 29.878788 |
google/prettytensor | prettytensor/tutorial/data_utils.py | https://github.com/google/prettytensor/blob/75daa0b11252590f548da5647addc0ea610c4c45/prettytensor/tutorial/data_utils.py#L37-L46 | def maybe_download(url, filename):
"""Download the data from Yann's website, unless it's already here."""
if not os.path.exists(WORK_DIRECTORY):
os.mkdir(WORK_DIRECTORY)
filepath = os.path.join(WORK_DIRECTORY, filename)
if not os.path.exists(filepath):
filepath, _ = request.urlretrieve(url + filename, f... | [
"def",
"maybe_download",
"(",
"url",
",",
"filename",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"WORK_DIRECTORY",
")",
":",
"os",
".",
"mkdir",
"(",
"WORK_DIRECTORY",
")",
"filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"WOR... | Download the data from Yann's website, unless it's already here. | [
"Download",
"the",
"data",
"from",
"Yann",
"s",
"website",
"unless",
"it",
"s",
"already",
"here",
"."
] | python | train | 44.5 |
dshean/pygeotools | pygeotools/lib/geolib.py | https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/geolib.py#L422-L434 | def pixelToMap(pX, pY, geoTransform):
"""Convert pixel coordinates to map coordinates based on geotransform
Accepts float or NumPy arrays
GDAL model used here - upper left corner of upper left pixel for mX, mY (and in GeoTransform)
"""
pX = np.asarray(pX, dtype=float)
pY = np.asarray(pY, d... | [
"def",
"pixelToMap",
"(",
"pX",
",",
"pY",
",",
"geoTransform",
")",
":",
"pX",
"=",
"np",
".",
"asarray",
"(",
"pX",
",",
"dtype",
"=",
"float",
")",
"pY",
"=",
"np",
".",
"asarray",
"(",
"pY",
",",
"dtype",
"=",
"float",
")",
"pX",
"+=",
"0.5... | Convert pixel coordinates to map coordinates based on geotransform
Accepts float or NumPy arrays
GDAL model used here - upper left corner of upper left pixel for mX, mY (and in GeoTransform) | [
"Convert",
"pixel",
"coordinates",
"to",
"map",
"coordinates",
"based",
"on",
"geotransform",
"Accepts",
"float",
"or",
"NumPy",
"arrays"
] | python | train | 32.153846 |
mitsei/dlkit | dlkit/services/cataloging.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/services/cataloging.py#L100-L111 | def _set_catalog_view(self, session):
"""Sets the underlying catalog view to match current view"""
if self._catalog_view == COMPARATIVE:
try:
session.use_comparative_catalog_view()
except AttributeError:
pass
else:
try:
... | [
"def",
"_set_catalog_view",
"(",
"self",
",",
"session",
")",
":",
"if",
"self",
".",
"_catalog_view",
"==",
"COMPARATIVE",
":",
"try",
":",
"session",
".",
"use_comparative_catalog_view",
"(",
")",
"except",
"AttributeError",
":",
"pass",
"else",
":",
"try",
... | Sets the underlying catalog view to match current view | [
"Sets",
"the",
"underlying",
"catalog",
"view",
"to",
"match",
"current",
"view"
] | python | train | 33.916667 |
thespacedoctor/sherlock | sherlock/imports/ned_d.py | https://github.com/thespacedoctor/sherlock/blob/2c80fb6fa31b04e7820e6928e3d437a21e692dd3/sherlock/imports/ned_d.py#L276-L323 | def _clean_up_columns(
self):
"""clean up columns of the NED table
.. todo ::
- update key arguments values and definitions with defaults
- update return values and definitions
- update usage examples and text
- update docstring text
... | [
"def",
"_clean_up_columns",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'starting the ``_clean_up_columns`` method'",
")",
"tableName",
"=",
"self",
".",
"dbTableName",
"print",
"\"cleaning up %(tableName)s columns\"",
"%",
"locals",
"(",
")",
"sq... | clean up columns of the NED table
.. todo ::
- update key arguments values and definitions with defaults
- update return values and definitions
- update usage examples and text
- update docstring text
- check sublime snippet exists
- clip... | [
"clean",
"up",
"columns",
"of",
"the",
"NED",
"table"
] | python | train | 42.395833 |
jeffh/rpi_courses | rpi_courses/parser/features.py | https://github.com/jeffh/rpi_courses/blob/c97176f73f866f112c785910ebf3ff8a790e8e9a/rpi_courses/parser/features.py#L14-L19 | def timestamp_feature(catalog, soup):
"""The datetime the xml file was last modified.
"""
catalog.timestamp = int(soup.coursedb['timestamp'])
catalog.datetime = datetime.datetime.fromtimestamp(catalog.timestamp)
logger.info('Catalog last updated on %s' % catalog.datetime) | [
"def",
"timestamp_feature",
"(",
"catalog",
",",
"soup",
")",
":",
"catalog",
".",
"timestamp",
"=",
"int",
"(",
"soup",
".",
"coursedb",
"[",
"'timestamp'",
"]",
")",
"catalog",
".",
"datetime",
"=",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",... | The datetime the xml file was last modified. | [
"The",
"datetime",
"the",
"xml",
"file",
"was",
"last",
"modified",
"."
] | python | train | 47.833333 |
twilio/twilio-python | twilio/rest/taskrouter/v1/workspace/worker/__init__.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/taskrouter/v1/workspace/worker/__init__.py#L87-L123 | def list(self, activity_name=values.unset, activity_sid=values.unset,
available=values.unset, friendly_name=values.unset,
target_workers_expression=values.unset, task_queue_name=values.unset,
task_queue_sid=values.unset, limit=None, page_size=None):
"""
Lists Worke... | [
"def",
"list",
"(",
"self",
",",
"activity_name",
"=",
"values",
".",
"unset",
",",
"activity_sid",
"=",
"values",
".",
"unset",
",",
"available",
"=",
"values",
".",
"unset",
",",
"friendly_name",
"=",
"values",
".",
"unset",
",",
"target_workers_expression... | Lists WorkerInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param unicode activity_name: Filter by workers that are in a particular Activity by Friendly Name
:param unicode activity_sid: Filte... | [
"Lists",
"WorkerInstance",
"records",
"from",
"the",
"API",
"as",
"a",
"list",
".",
"Unlike",
"stream",
"()",
"this",
"operation",
"is",
"eager",
"and",
"will",
"load",
"limit",
"records",
"into",
"memory",
"before",
"returning",
"."
] | python | train | 60.243243 |
alecthomas/voluptuous | voluptuous/validators.py | https://github.com/alecthomas/voluptuous/blob/36c8c11e2b7eb402c24866fa558473661ede9403/voluptuous/validators.py#L451-L466 | def IsDir(v):
"""Verify the directory exists.
>>> IsDir()('/')
'/'
>>> with raises(DirInvalid, 'Not a directory'):
... IsDir()(None)
"""
try:
if v:
v = str(v)
return os.path.isdir(v)
else:
raise DirInvalid("Not a directory")
except T... | [
"def",
"IsDir",
"(",
"v",
")",
":",
"try",
":",
"if",
"v",
":",
"v",
"=",
"str",
"(",
"v",
")",
"return",
"os",
".",
"path",
".",
"isdir",
"(",
"v",
")",
"else",
":",
"raise",
"DirInvalid",
"(",
"\"Not a directory\"",
")",
"except",
"TypeError",
... | Verify the directory exists.
>>> IsDir()('/')
'/'
>>> with raises(DirInvalid, 'Not a directory'):
... IsDir()(None) | [
"Verify",
"the",
"directory",
"exists",
"."
] | python | train | 22.375 |
mitsei/dlkit | dlkit/authz_adapter/assessment/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/authz_adapter/assessment/sessions.py#L725-L731 | def get_items_by_search(self, item_query, item_search):
"""Pass through to provider ItemSearchSession.get_items_by_search"""
# Implemented from azosid template for -
# osid.resource.ResourceSearchSession.get_resources_by_search_template
if not self._can('search'):
raise Permi... | [
"def",
"get_items_by_search",
"(",
"self",
",",
"item_query",
",",
"item_search",
")",
":",
"# Implemented from azosid template for -",
"# osid.resource.ResourceSearchSession.get_resources_by_search_template",
"if",
"not",
"self",
".",
"_can",
"(",
"'search'",
")",
":",
"ra... | Pass through to provider ItemSearchSession.get_items_by_search | [
"Pass",
"through",
"to",
"provider",
"ItemSearchSession",
".",
"get_items_by_search"
] | python | train | 58.571429 |
saltstack/salt | salt/modules/win_lgpo.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_lgpo.py#L5465-L5472 | def _getRightsAssignments(user_right):
'''
helper function to return all the user rights assignments/users
'''
sids = []
polHandle = win32security.LsaOpenPolicy(None, win32security.POLICY_ALL_ACCESS)
sids = win32security.LsaEnumerateAccountsWithUserRight(polHandle, user_right)
return sids | [
"def",
"_getRightsAssignments",
"(",
"user_right",
")",
":",
"sids",
"=",
"[",
"]",
"polHandle",
"=",
"win32security",
".",
"LsaOpenPolicy",
"(",
"None",
",",
"win32security",
".",
"POLICY_ALL_ACCESS",
")",
"sids",
"=",
"win32security",
".",
"LsaEnumerateAccountsW... | helper function to return all the user rights assignments/users | [
"helper",
"function",
"to",
"return",
"all",
"the",
"user",
"rights",
"assignments",
"/",
"users"
] | python | train | 38.75 |
openvax/varcode | varcode/reference.py | https://github.com/openvax/varcode/blob/981633db45ca2b31f76c06894a7360ea5d70a9b8/varcode/reference.py#L45-L56 | def _most_recent_assembly(assembly_names):
"""
Given list of (in this case, matched) assemblies, identify the most recent
("recency" here is determined by sorting based on the numeric element of the assembly name)
"""
match_recency = [
int(re.search('\d+', assembly_name).group())
... | [
"def",
"_most_recent_assembly",
"(",
"assembly_names",
")",
":",
"match_recency",
"=",
"[",
"int",
"(",
"re",
".",
"search",
"(",
"'\\d+'",
",",
"assembly_name",
")",
".",
"group",
"(",
")",
")",
"for",
"assembly_name",
"in",
"assembly_names",
"]",
"most_rec... | Given list of (in this case, matched) assemblies, identify the most recent
("recency" here is determined by sorting based on the numeric element of the assembly name) | [
"Given",
"list",
"of",
"(",
"in",
"this",
"case",
"matched",
")",
"assemblies",
"identify",
"the",
"most",
"recent",
"(",
"recency",
"here",
"is",
"determined",
"by",
"sorting",
"based",
"on",
"the",
"numeric",
"element",
"of",
"the",
"assembly",
"name",
"... | python | train | 39.833333 |
Yubico/yubikey-manager | ykman/cli/piv.py | https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/piv.py#L619-L627 | def delete_certificate(ctx, slot, management_key, pin):
"""
Delete a certificate.
Delete a certificate from a slot on the YubiKey.
"""
controller = ctx.obj['controller']
_ensure_authenticated(ctx, controller, pin, management_key)
controller.delete_certificate(slot) | [
"def",
"delete_certificate",
"(",
"ctx",
",",
"slot",
",",
"management_key",
",",
"pin",
")",
":",
"controller",
"=",
"ctx",
".",
"obj",
"[",
"'controller'",
"]",
"_ensure_authenticated",
"(",
"ctx",
",",
"controller",
",",
"pin",
",",
"management_key",
")",... | Delete a certificate.
Delete a certificate from a slot on the YubiKey. | [
"Delete",
"a",
"certificate",
"."
] | python | train | 31.777778 |
mlperf/training | translation/tensorflow/transformer/data_download.py | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/data_download.py#L210-L214 | def txt_line_iterator(path):
"""Iterate through lines of file."""
with tf.gfile.Open(path) as f:
for line in f:
yield line.strip() | [
"def",
"txt_line_iterator",
"(",
"path",
")",
":",
"with",
"tf",
".",
"gfile",
".",
"Open",
"(",
"path",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"yield",
"line",
".",
"strip",
"(",
")"
] | Iterate through lines of file. | [
"Iterate",
"through",
"lines",
"of",
"file",
"."
] | python | train | 28 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.