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 |
|---|---|---|---|---|---|---|---|---|---|
ungarj/s2reader | s2reader/s2reader.py | https://github.com/ungarj/s2reader/blob/376fd7ee1d15cce0849709c149d694663a7bc0ef/s2reader/s2reader.py#L291-L307 | def tci_path(self):
"""Return the path to the granules TrueColorImage."""
tci_paths = [
path for path in self.dataset._product_metadata.xpath(
".//Granule[@granuleIdentifier='%s']/IMAGE_FILE/text()"
% self.granule_identifier
) if path.endswith('TCI... | [
"def",
"tci_path",
"(",
"self",
")",
":",
"tci_paths",
"=",
"[",
"path",
"for",
"path",
"in",
"self",
".",
"dataset",
".",
"_product_metadata",
".",
"xpath",
"(",
"\".//Granule[@granuleIdentifier='%s']/IMAGE_FILE/text()\"",
"%",
"self",
".",
"granule_identifier",
... | Return the path to the granules TrueColorImage. | [
"Return",
"the",
"path",
"to",
"the",
"granules",
"TrueColorImage",
"."
] | python | train | 33.411765 |
carljm/django-adminfiles | adminfiles/flickr.py | https://github.com/carljm/django-adminfiles/blob/b01dc7be266305d575c11d5ff9a37ccac04a78c2/adminfiles/flickr.py#L741-L750 | def contacts_getPublicList(user_id):
"""Gets the contacts (Users) for the user_id"""
method = 'flickr.contacts.getPublicList'
data = _doget(method, auth=False, user_id=user_id)
if isinstance(data.rsp.contacts.contact, list):
return [User(user.nsid, username=user.username) \
for u... | [
"def",
"contacts_getPublicList",
"(",
"user_id",
")",
":",
"method",
"=",
"'flickr.contacts.getPublicList'",
"data",
"=",
"_doget",
"(",
"method",
",",
"auth",
"=",
"False",
",",
"user_id",
"=",
"user_id",
")",
"if",
"isinstance",
"(",
"data",
".",
"rsp",
".... | Gets the contacts (Users) for the user_id | [
"Gets",
"the",
"contacts",
"(",
"Users",
")",
"for",
"the",
"user_id"
] | python | train | 45.2 |
LISE-B26/pylabcontrol | build/lib/pylabcontrol/src/core/scripts.py | https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/build/lib/pylabcontrol/src/core/scripts.py#L1233-L1250 | def get_script_module(script_information, package='pylabcontrol', verbose=False):
"""
wrapper to get the module for a script
Args:
script_information: information of the script. This can be
- a dictionary
- a Script instance
- name of ... | [
"def",
"get_script_module",
"(",
"script_information",
",",
"package",
"=",
"'pylabcontrol'",
",",
"verbose",
"=",
"False",
")",
":",
"module",
",",
"_",
",",
"_",
",",
"_",
",",
"_",
",",
"_",
",",
"_",
"=",
"Script",
".",
"get_script_information",
"(",... | wrapper to get the module for a script
Args:
script_information: information of the script. This can be
- a dictionary
- a Script instance
- name of Script class
package (optional): name of the package to which the script belongs, i.e. pyl... | [
"wrapper",
"to",
"get",
"the",
"module",
"for",
"a",
"script"
] | python | train | 38.055556 |
raiden-network/raiden | raiden/connection_manager.py | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/connection_manager.py#L375-L435 | def _open_channels(self) -> bool:
""" Open channels until there are `self.initial_channel_target`
channels open. Do nothing if there are enough channels open already.
Note:
- This method must be called with the lock held.
Return:
- False if no channels could be o... | [
"def",
"_open_channels",
"(",
"self",
")",
"->",
"bool",
":",
"open_channels",
"=",
"views",
".",
"get_channelstate_open",
"(",
"chain_state",
"=",
"views",
".",
"state_from_raiden",
"(",
"self",
".",
"raiden",
")",
",",
"payment_network_id",
"=",
"self",
".",... | Open channels until there are `self.initial_channel_target`
channels open. Do nothing if there are enough channels open already.
Note:
- This method must be called with the lock held.
Return:
- False if no channels could be opened | [
"Open",
"channels",
"until",
"there",
"are",
"self",
".",
"initial_channel_target",
"channels",
"open",
".",
"Do",
"nothing",
"if",
"there",
"are",
"enough",
"channels",
"open",
"already",
"."
] | python | train | 38.836066 |
google/grr | grr/server/grr_response_server/gui/wsgiapp.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/gui/wsgiapp.py#L212-L224 | def _BuildToken(self, request, execution_time):
"""Build an ACLToken from the request."""
token = access_control.ACLToken(
username=request.user,
reason=request.args.get("reason", ""),
process="GRRAdminUI",
expiry=rdfvalue.RDFDatetime.Now() + execution_time)
for field in ["R... | [
"def",
"_BuildToken",
"(",
"self",
",",
"request",
",",
"execution_time",
")",
":",
"token",
"=",
"access_control",
".",
"ACLToken",
"(",
"username",
"=",
"request",
".",
"user",
",",
"reason",
"=",
"request",
".",
"args",
".",
"get",
"(",
"\"reason\"",
... | Build an ACLToken from the request. | [
"Build",
"an",
"ACLToken",
"from",
"the",
"request",
"."
] | python | train | 36.538462 |
inveniosoftware/invenio-userprofiles | invenio_userprofiles/views.py | https://github.com/inveniosoftware/invenio-userprofiles/blob/4c682e7d67a4cab8dc38472a31fa1c34cbba03dd/invenio_userprofiles/views.py#L44-L51 | def init_common(app):
"""Post initialization."""
if app.config['USERPROFILES_EXTEND_SECURITY_FORMS']:
security_ext = app.extensions['security']
security_ext.confirm_register_form = confirm_register_form_factory(
security_ext.confirm_register_form)
security_ext.register_form =... | [
"def",
"init_common",
"(",
"app",
")",
":",
"if",
"app",
".",
"config",
"[",
"'USERPROFILES_EXTEND_SECURITY_FORMS'",
"]",
":",
"security_ext",
"=",
"app",
".",
"extensions",
"[",
"'security'",
"]",
"security_ext",
".",
"confirm_register_form",
"=",
"confirm_regist... | Post initialization. | [
"Post",
"initialization",
"."
] | python | train | 47 |
Telefonica/toolium | toolium/utils.py | https://github.com/Telefonica/toolium/blob/56847c243b3a98876df74c184b75e43f8810e475/toolium/utils.py#L339-L356 | def wait_until_first_element_is_found(self, elements, timeout=None):
"""Search list of elements and wait until one of them is found
:param elements: list of PageElements or element locators as a tuple (locator_type, locator_value) to be found
sequentially
:param timeout... | [
"def",
"wait_until_first_element_is_found",
"(",
"self",
",",
"elements",
",",
"timeout",
"=",
"None",
")",
":",
"try",
":",
"return",
"self",
".",
"_wait_until",
"(",
"self",
".",
"_expected_condition_find_first_element",
",",
"elements",
",",
"timeout",
")",
"... | Search list of elements and wait until one of them is found
:param elements: list of PageElements or element locators as a tuple (locator_type, locator_value) to be found
sequentially
:param timeout: max time to wait
:returns: first element found
:rtype: toolium... | [
"Search",
"list",
"of",
"elements",
"and",
"wait",
"until",
"one",
"of",
"them",
"is",
"found"
] | python | train | 53.222222 |
docker/docker-py | docker/api/image.py | https://github.com/docker/docker-py/blob/613d6aad83acc9931ff2ecfd6a6c7bd8061dc125/docker/api/image.py#L421-L480 | def push(self, repository, tag=None, stream=False, auth_config=None,
decode=False):
"""
Push an image or a repository to the registry. Similar to the ``docker
push`` command.
Args:
repository (str): The repository to push to
tag (str): An optional ta... | [
"def",
"push",
"(",
"self",
",",
"repository",
",",
"tag",
"=",
"None",
",",
"stream",
"=",
"False",
",",
"auth_config",
"=",
"None",
",",
"decode",
"=",
"False",
")",
":",
"if",
"not",
"tag",
":",
"repository",
",",
"tag",
"=",
"utils",
".",
"pars... | Push an image or a repository to the registry. Similar to the ``docker
push`` command.
Args:
repository (str): The repository to push to
tag (str): An optional tag to push
stream (bool): Stream the output as a blocking generator
auth_config (dict): Overri... | [
"Push",
"an",
"image",
"or",
"a",
"repository",
"to",
"the",
"registry",
".",
"Similar",
"to",
"the",
"docker",
"push",
"command",
"."
] | python | train | 36.066667 |
DataDog/integrations-core | tokumx/datadog_checks/tokumx/vendor/pymongo/bulk.py | https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/tokumx/datadog_checks/tokumx/vendor/pymongo/bulk.py#L241-L252 | def add_replace(self, selector, replacement, upsert=False,
collation=None):
"""Create a replace document and add it to the list of ops.
"""
validate_ok_for_replace(replacement)
cmd = SON([('q', selector), ('u', replacement),
('multi', False), ('upse... | [
"def",
"add_replace",
"(",
"self",
",",
"selector",
",",
"replacement",
",",
"upsert",
"=",
"False",
",",
"collation",
"=",
"None",
")",
":",
"validate_ok_for_replace",
"(",
"replacement",
")",
"cmd",
"=",
"SON",
"(",
"[",
"(",
"'q'",
",",
"selector",
")... | Create a replace document and add it to the list of ops. | [
"Create",
"a",
"replace",
"document",
"and",
"add",
"it",
"to",
"the",
"list",
"of",
"ops",
"."
] | python | train | 44.583333 |
orbingol/NURBS-Python | geomdl/helpers.py | https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/helpers.py#L173-L190 | def basis_functions(degree, knot_vector, spans, knots):
""" Computes the non-vanishing basis functions for a list of parameters.
:param degree: degree, :math:`p`
:type degree: int
:param knot_vector: knot vector, :math:`U`
:type knot_vector: list, tuple
:param spans: list of knot spans
:typ... | [
"def",
"basis_functions",
"(",
"degree",
",",
"knot_vector",
",",
"spans",
",",
"knots",
")",
":",
"basis",
"=",
"[",
"]",
"for",
"span",
",",
"knot",
"in",
"zip",
"(",
"spans",
",",
"knots",
")",
":",
"basis",
".",
"append",
"(",
"basis_function",
"... | Computes the non-vanishing basis functions for a list of parameters.
:param degree: degree, :math:`p`
:type degree: int
:param knot_vector: knot vector, :math:`U`
:type knot_vector: list, tuple
:param spans: list of knot spans
:type spans: list, tuple
:param knots: list of knots or paramet... | [
"Computes",
"the",
"non",
"-",
"vanishing",
"basis",
"functions",
"for",
"a",
"list",
"of",
"parameters",
"."
] | python | train | 33.111111 |
mwickert/scikit-dsp-comm | sk_dsp_comm/fec_conv.py | https://github.com/mwickert/scikit-dsp-comm/blob/5c1353412a4d81a8d7da169057564ecf940f8b5b/sk_dsp_comm/fec_conv.py#L621-L708 | def depuncture(self,soft_bits,puncture_pattern = ('110','101'),
erase_value = 3.5):
"""
Apply de-puncturing to the soft bits coming from the channel. Erasure bits
are inserted to return the soft bit values back to a form that can be
Viterbi decoded.
:pa... | [
"def",
"depuncture",
"(",
"self",
",",
"soft_bits",
",",
"puncture_pattern",
"=",
"(",
"'110'",
",",
"'101'",
")",
",",
"erase_value",
"=",
"3.5",
")",
":",
"# Check to see that the length of soft_bits is consistent with a rate\r",
"# 1/2 code.\r",
"L_pp",
"=",
"len",... | Apply de-puncturing to the soft bits coming from the channel. Erasure bits
are inserted to return the soft bit values back to a form that can be
Viterbi decoded.
:param soft_bits:
:param puncture_pattern:
:param erase_value:
:return:
Examples
-... | [
"Apply",
"de",
"-",
"puncturing",
"to",
"the",
"soft",
"bits",
"coming",
"from",
"the",
"channel",
".",
"Erasure",
"bits",
"are",
"inserted",
"to",
"return",
"the",
"soft",
"bit",
"values",
"back",
"to",
"a",
"form",
"that",
"can",
"be",
"Viterbi",
"deco... | python | valid | 48.556818 |
pymupdf/PyMuPDF | fitz/fitz.py | https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L3202-L3209 | def tintWith(self, red, green, blue):
"""tintWith(self, red, green, blue)"""
if not self.colorspace or self.colorspace.n > 3:
print("warning: colorspace invalid for function")
return
return _fitz.Pixmap_tintWith(self, red, green, blue) | [
"def",
"tintWith",
"(",
"self",
",",
"red",
",",
"green",
",",
"blue",
")",
":",
"if",
"not",
"self",
".",
"colorspace",
"or",
"self",
".",
"colorspace",
".",
"n",
">",
"3",
":",
"print",
"(",
"\"warning: colorspace invalid for function\"",
")",
"return",
... | tintWith(self, red, green, blue) | [
"tintWith",
"(",
"self",
"red",
"green",
"blue",
")"
] | python | train | 34.75 |
fprimex/zdesk | zdesk/zdesk_api.py | https://github.com/fprimex/zdesk/blob/851611c13b4d530e9df31390b3ec709baf0a0188/zdesk/zdesk_api.py#L4002-L4006 | def user_organization_memberships(self, user_id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/organization_memberships#list-memberships"
api_path = "/api/v2/users/{user_id}/organization_memberships.json"
api_path = api_path.format(user_id=user_id)
return self.call(api_pat... | [
"def",
"user_organization_memberships",
"(",
"self",
",",
"user_id",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/users/{user_id}/organization_memberships.json\"",
"api_path",
"=",
"api_path",
".",
"format",
"(",
"user_id",
"=",
"user_id",
")",
"re... | https://developer.zendesk.com/rest_api/docs/core/organization_memberships#list-memberships | [
"https",
":",
"//",
"developer",
".",
"zendesk",
".",
"com",
"/",
"rest_api",
"/",
"docs",
"/",
"core",
"/",
"organization_memberships#list",
"-",
"memberships"
] | python | train | 65.6 |
NetworkAutomation/jaide | jaide/core.py | https://github.com/NetworkAutomation/jaide/blob/8571b987a8c24c246dc09f1bcc11cb0f045ec33f/jaide/core.py#L780-L832 | def op_cmd(self, command, req_format='text', xpath_expr=""):
""" Execute an operational mode command.
Purpose: Used to send an operational mode command to the connected
| device. This requires and uses a paramiko.SSHClient() as
| the handler so that we can easily pass and ... | [
"def",
"op_cmd",
"(",
"self",
",",
"command",
",",
"req_format",
"=",
"'text'",
",",
"xpath_expr",
"=",
"\"\"",
")",
":",
"if",
"not",
"command",
":",
"raise",
"InvalidCommandError",
"(",
"\"Parameter 'command' cannot be empty\"",
")",
"if",
"req_format",
".",
... | Execute an operational mode command.
Purpose: Used to send an operational mode command to the connected
| device. This requires and uses a paramiko.SSHClient() as
| the handler so that we can easily pass and allow all pipe
| commands to be used.
|
... | [
"Execute",
"an",
"operational",
"mode",
"command",
"."
] | python | train | 46 |
IntegralDefense/critsapi | critsapi/critsapi.py | https://github.com/IntegralDefense/critsapi/blob/e770bd81e124eaaeb5f1134ba95f4a35ff345c5a/critsapi/critsapi.py#L682-L721 | def status_update(self, crits_id, crits_type, status):
"""
Update the status of the TLO. By default, the options are:
- New
- In Progress
- Analyzed
- Deprecated
Args:
crits_id: The object id of the TLO
crits_type: The type of TLO. This mu... | [
"def",
"status_update",
"(",
"self",
",",
"crits_id",
",",
"crits_type",
",",
"status",
")",
":",
"obj_type",
"=",
"self",
".",
"_type_translation",
"(",
"crits_type",
")",
"patch_url",
"=",
"\"{0}/{1}/{2}/\"",
".",
"format",
"(",
"self",
".",
"url",
",",
... | Update the status of the TLO. By default, the options are:
- New
- In Progress
- Analyzed
- Deprecated
Args:
crits_id: The object id of the TLO
crits_type: The type of TLO. This must be 'Indicator', ''
status: The status to change.
Ret... | [
"Update",
"the",
"status",
"of",
"the",
"TLO",
".",
"By",
"default",
"the",
"options",
"are",
":",
"-",
"New",
"-",
"In",
"Progress",
"-",
"Analyzed",
"-",
"Deprecated"
] | python | train | 33.375 |
django-parler/django-parler | parler/admin.py | https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/admin.py#L295-L303 | def get_form(self, request, obj=None, **kwargs):
"""
Pass the current language to the form.
"""
form_class = super(TranslatableAdmin, self).get_form(request, obj, **kwargs)
if self._has_translatable_model():
form_class.language_code = self.get_form_language(request, o... | [
"def",
"get_form",
"(",
"self",
",",
"request",
",",
"obj",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"form_class",
"=",
"super",
"(",
"TranslatableAdmin",
",",
"self",
")",
".",
"get_form",
"(",
"request",
",",
"obj",
",",
"*",
"*",
"kwargs",
... | Pass the current language to the form. | [
"Pass",
"the",
"current",
"language",
"to",
"the",
"form",
"."
] | python | train | 38 |
Cymmetria/honeycomb | honeycomb/integrationmanager/registration.py | https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/integrationmanager/registration.py#L25-L45 | def get_integration_module(integration_path):
"""Add custom paths to sys and import integration module.
:param integration_path: Path to integration folder
"""
# add custom paths so imports would work
paths = [
os.path.join(__file__, "..", ".."), # to import integrationmanager
os.p... | [
"def",
"get_integration_module",
"(",
"integration_path",
")",
":",
"# add custom paths so imports would work",
"paths",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"__file__",
",",
"\"..\"",
",",
"\"..\"",
")",
",",
"# to import integrationmanager",
"os",
".",
... | Add custom paths to sys and import integration module.
:param integration_path: Path to integration folder | [
"Add",
"custom",
"paths",
"to",
"sys",
"and",
"import",
"integration",
"module",
"."
] | python | train | 40.380952 |
rocky/python-xdis | xdis/bytecode.py | https://github.com/rocky/python-xdis/blob/46a2902ae8f5d8eee495eed67ac0690fd545453d/xdis/bytecode.py#L172-L188 | def _get_const_info(const_index, const_list):
"""Helper to get optional details about const references
Returns the dereferenced constant and its repr if the constant
list is defined.
Otherwise returns the constant index and its repr().
"""
argval = const_index
if const_list is not ... | [
"def",
"_get_const_info",
"(",
"const_index",
",",
"const_list",
")",
":",
"argval",
"=",
"const_index",
"if",
"const_list",
"is",
"not",
"None",
":",
"argval",
"=",
"const_list",
"[",
"const_index",
"]",
"# float values nan and inf are not directly representable in Pyt... | Helper to get optional details about const references
Returns the dereferenced constant and its repr if the constant
list is defined.
Otherwise returns the constant index and its repr(). | [
"Helper",
"to",
"get",
"optional",
"details",
"about",
"const",
"references"
] | python | train | 44.176471 |
danielhrisca/asammdf | asammdf/blocks/mdf_v3.py | https://github.com/danielhrisca/asammdf/blob/3c7a1fd19c957ceebe4dcdbb2abf00806c2bdb66/asammdf/blocks/mdf_v3.py#L2453-L2902 | def get(
self,
name=None,
group=None,
index=None,
raster=None,
samples_only=False,
data=None,
raw=False,
ignore_invalidation_bits=False,
source=None,
record_offset=0,
record_count=None,
copy_master=True,
):
... | [
"def",
"get",
"(",
"self",
",",
"name",
"=",
"None",
",",
"group",
"=",
"None",
",",
"index",
"=",
"None",
",",
"raster",
"=",
"None",
",",
"samples_only",
"=",
"False",
",",
"data",
"=",
"None",
",",
"raw",
"=",
"False",
",",
"ignore_invalidation_bi... | Gets channel samples.
Channel can be specified in two ways:
* using the first positional argument *name*
* if *source* is given this will be first used to validate the
channel selection
* if there are multiple occurances for this channel then the
*gr... | [
"Gets",
"channel",
"samples",
".",
"Channel",
"can",
"be",
"specified",
"in",
"two",
"ways",
":"
] | python | train | 34.744444 |
libtcod/python-tcod | tcod/bsp.py | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/bsp.py#L228-L242 | def inverted_level_order(self) -> Iterator["BSP"]:
"""Iterate over this BSP's hierarchy in inverse level order.
.. versionadded:: 8.3
"""
levels = [] # type: List[List['BSP']]
next = [self] # type: List['BSP']
while next:
levels.append(next)
lev... | [
"def",
"inverted_level_order",
"(",
"self",
")",
"->",
"Iterator",
"[",
"\"BSP\"",
"]",
":",
"levels",
"=",
"[",
"]",
"# type: List[List['BSP']]",
"next",
"=",
"[",
"self",
"]",
"# type: List['BSP']",
"while",
"next",
":",
"levels",
".",
"append",
"(",
"next... | Iterate over this BSP's hierarchy in inverse level order.
.. versionadded:: 8.3 | [
"Iterate",
"over",
"this",
"BSP",
"s",
"hierarchy",
"in",
"inverse",
"level",
"order",
"."
] | python | train | 32.666667 |
avalente/appmetrics | appmetrics/statistics.py | https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/statistics.py#L369-L379 | def pstdev(data, mu=None):
"""Return the square root of the population variance.
See ``pvariance`` for arguments and other details.
"""
var = pvariance(data, mu)
try:
return var.sqrt()
except AttributeError:
return math.sqrt(var) | [
"def",
"pstdev",
"(",
"data",
",",
"mu",
"=",
"None",
")",
":",
"var",
"=",
"pvariance",
"(",
"data",
",",
"mu",
")",
"try",
":",
"return",
"var",
".",
"sqrt",
"(",
")",
"except",
"AttributeError",
":",
"return",
"math",
".",
"sqrt",
"(",
"var",
... | Return the square root of the population variance.
See ``pvariance`` for arguments and other details. | [
"Return",
"the",
"square",
"root",
"of",
"the",
"population",
"variance",
"."
] | python | train | 23.727273 |
driftx/Telephus | telephus/pool.py | https://github.com/driftx/Telephus/blob/860a03a0fafe71605e1a4316dfdd8d0c29094703/telephus/pool.py#L1002-L1038 | def fill_pool(self):
"""
Add connections as necessary to meet the target pool size. If there
are no nodes to connect to (because we maxed out connections-per-node
on all active connections and any unconnected nodes have pending
reconnect timers), call the on_insufficient_nodes ca... | [
"def",
"fill_pool",
"(",
"self",
")",
":",
"time_since_last_called",
"=",
"self",
".",
"fill_pool_throttle",
"if",
"self",
".",
"fill_pool_last_called",
"is",
"not",
"None",
":",
"time_since_last_called",
"=",
"time",
"(",
")",
"-",
"self",
".",
"fill_pool_last_... | Add connections as necessary to meet the target pool size. If there
are no nodes to connect to (because we maxed out connections-per-node
on all active connections and any unconnected nodes have pending
reconnect timers), call the on_insufficient_nodes callback. | [
"Add",
"connections",
"as",
"necessary",
"to",
"meet",
"the",
"target",
"pool",
"size",
".",
"If",
"there",
"are",
"no",
"nodes",
"to",
"connect",
"to",
"(",
"because",
"we",
"maxed",
"out",
"connections",
"-",
"per",
"-",
"node",
"on",
"all",
"active",
... | python | train | 51.675676 |
pycontribs/pyrax | pyrax/autoscale.py | https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/autoscale.py#L172-L176 | def execute_policy(self, policy):
"""
Executes the specified policy for this scaling group.
"""
return self.manager.execute_policy(scaling_group=self, policy=policy) | [
"def",
"execute_policy",
"(",
"self",
",",
"policy",
")",
":",
"return",
"self",
".",
"manager",
".",
"execute_policy",
"(",
"scaling_group",
"=",
"self",
",",
"policy",
"=",
"policy",
")"
] | Executes the specified policy for this scaling group. | [
"Executes",
"the",
"specified",
"policy",
"for",
"this",
"scaling",
"group",
"."
] | python | train | 38.6 |
AlexandreDecan/python-intervals | intervals.py | https://github.com/AlexandreDecan/python-intervals/blob/eda4da7dd39afabab2c1689e0b5158abae08c831/intervals.py#L355-L364 | def is_empty(self):
"""
Test interval emptiness.
:return: True if interval is empty, False otherwise.
"""
return (
self._lower > self._upper or
(self._lower == self._upper and (self._left == OPEN or self._right == OPEN))
) | [
"def",
"is_empty",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"_lower",
">",
"self",
".",
"_upper",
"or",
"(",
"self",
".",
"_lower",
"==",
"self",
".",
"_upper",
"and",
"(",
"self",
".",
"_left",
"==",
"OPEN",
"or",
"self",
".",
"_right",
... | Test interval emptiness.
:return: True if interval is empty, False otherwise. | [
"Test",
"interval",
"emptiness",
"."
] | python | train | 28.6 |
rsgalloway/grit | grit/server/cherrypy/__init__.py | https://github.com/rsgalloway/grit/blob/e6434ad8a1f4ac5d0903ebad630c81f8a5164d78/grit/server/cherrypy/__init__.py#L1327-L1333 | def format_exc(limit=None):
"""Like print_exc() but return a string. Backport for Python 2.3."""
try:
etype, value, tb = sys.exc_info()
return ''.join(traceback.format_exception(etype, value, tb, limit))
finally:
etype = value = tb = None | [
"def",
"format_exc",
"(",
"limit",
"=",
"None",
")",
":",
"try",
":",
"etype",
",",
"value",
",",
"tb",
"=",
"sys",
".",
"exc_info",
"(",
")",
"return",
"''",
".",
"join",
"(",
"traceback",
".",
"format_exception",
"(",
"etype",
",",
"value",
",",
... | Like print_exc() but return a string. Backport for Python 2.3. | [
"Like",
"print_exc",
"()",
"but",
"return",
"a",
"string",
".",
"Backport",
"for",
"Python",
"2",
".",
"3",
"."
] | python | train | 38.285714 |
PmagPy/PmagPy | pmagpy/pmag.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmag.py#L9618-L9634 | def squish(incs, f):
"""
returns 'flattened' inclination, assuming factor, f and King (1955) formula:
tan (I_o) = f tan (I_f)
Parameters
__________
incs : array of inclination (I_f) data to flatten
f : flattening factor
Returns
_______
I_o : inclinations after flattening
... | [
"def",
"squish",
"(",
"incs",
",",
"f",
")",
":",
"incs",
"=",
"np",
".",
"radians",
"(",
"incs",
")",
"I_o",
"=",
"f",
"*",
"np",
".",
"tan",
"(",
"incs",
")",
"# multiply tangent by flattening factor",
"return",
"np",
".",
"degrees",
"(",
"np",
"."... | returns 'flattened' inclination, assuming factor, f and King (1955) formula:
tan (I_o) = f tan (I_f)
Parameters
__________
incs : array of inclination (I_f) data to flatten
f : flattening factor
Returns
_______
I_o : inclinations after flattening | [
"returns",
"flattened",
"inclination",
"assuming",
"factor",
"f",
"and",
"King",
"(",
"1955",
")",
"formula",
":",
"tan",
"(",
"I_o",
")",
"=",
"f",
"tan",
"(",
"I_f",
")"
] | python | train | 25.941176 |
a-tal/kezmenu3 | kezmenu3/kezmenu.py | https://github.com/a-tal/kezmenu3/blob/3b06f9cb67fdc98a73928f877eea86692f832fa4/kezmenu3/kezmenu.py#L154-L166 | def _checkMousePositionForFocus(self):
"""Check the mouse position to know if move focus on a option"""
i = 0
cur_pos = pygame.mouse.get_pos()
ml, mt = self.position
for o in self.options:
rect = o.get('label_rect')
if rect:
if rect.collide... | [
"def",
"_checkMousePositionForFocus",
"(",
"self",
")",
":",
"i",
"=",
"0",
"cur_pos",
"=",
"pygame",
".",
"mouse",
".",
"get_pos",
"(",
")",
"ml",
",",
"mt",
"=",
"self",
".",
"position",
"for",
"o",
"in",
"self",
".",
"options",
":",
"rect",
"=",
... | Check the mouse position to know if move focus on a option | [
"Check",
"the",
"mouse",
"position",
"to",
"know",
"if",
"move",
"focus",
"on",
"a",
"option"
] | python | train | 36.846154 |
arviz-devs/arviz | arviz/stats/stats.py | https://github.com/arviz-devs/arviz/blob/d04d8da07f029fd2931f48d2f7f324cf393e5277/arviz/stats/stats.py#L909-L954 | def _mc_error(x, batches=5, circular=False):
"""Calculate the simulation standard error, accounting for non-independent samples.
The trace is divided into batches, and the standard deviation of the batch
means is calculated.
Parameters
----------
x : Numpy array
An array containing MCM... | [
"def",
"_mc_error",
"(",
"x",
",",
"batches",
"=",
"5",
",",
"circular",
"=",
"False",
")",
":",
"if",
"x",
".",
"ndim",
">",
"1",
":",
"dims",
"=",
"np",
".",
"shape",
"(",
"x",
")",
"trace",
"=",
"np",
".",
"transpose",
"(",
"[",
"t",
".",
... | Calculate the simulation standard error, accounting for non-independent samples.
The trace is divided into batches, and the standard deviation of the batch
means is calculated.
Parameters
----------
x : Numpy array
An array containing MCMC samples
batches : integer
Number of ba... | [
"Calculate",
"the",
"simulation",
"standard",
"error",
"accounting",
"for",
"non",
"-",
"independent",
"samples",
"."
] | python | train | 29.891304 |
dropbox/stone | stone/ir/data_types.py | https://github.com/dropbox/stone/blob/2e95cbcd1c48e05cca68c919fd8d24adec6b0f58/stone/ir/data_types.py#L1370-L1384 | def set_attributes(self, doc, fields, # pylint: disable=arguments-differ
parent_type=None, catch_all_field=None):
"""
:param UnionField catch_all_field: The field designated as the
catch-all. This field should be a member of the list of fields.
See :meth:`Composite.set_... | [
"def",
"set_attributes",
"(",
"self",
",",
"doc",
",",
"fields",
",",
"# pylint: disable=arguments-differ",
"parent_type",
"=",
"None",
",",
"catch_all_field",
"=",
"None",
")",
":",
"if",
"parent_type",
":",
"assert",
"isinstance",
"(",
"parent_type",
",",
"Uni... | :param UnionField catch_all_field: The field designated as the
catch-all. This field should be a member of the list of fields.
See :meth:`Composite.set_attributes` for parameter definitions. | [
":",
"param",
"UnionField",
"catch_all_field",
":",
"The",
"field",
"designated",
"as",
"the",
"catch",
"-",
"all",
".",
"This",
"field",
"should",
"be",
"a",
"member",
"of",
"the",
"list",
"of",
"fields",
"."
] | python | train | 39.066667 |
WebarchivCZ/WA-KAT | src/wa_kat/templates/static/js/Lib/site-packages/components/keyword_handler.py | https://github.com/WebarchivCZ/WA-KAT/blob/16d064a3a775dc1d2713debda7847ded52dd2a06/src/wa_kat/templates/static/js/Lib/site-packages/components/keyword_handler.py#L144-L157 | def set_kw_typeahead_input(cls):
"""
Map the typeahead input to remote dataset.
"""
# get reference to parent element
parent_id = cls.intput_el.parent.id
if "typeahead" not in parent_id.lower():
parent_id = cls.intput_el.parent.parent.id
window.make_k... | [
"def",
"set_kw_typeahead_input",
"(",
"cls",
")",
":",
"# get reference to parent element",
"parent_id",
"=",
"cls",
".",
"intput_el",
".",
"parent",
".",
"id",
"if",
"\"typeahead\"",
"not",
"in",
"parent_id",
".",
"lower",
"(",
")",
":",
"parent_id",
"=",
"cl... | Map the typeahead input to remote dataset. | [
"Map",
"the",
"typeahead",
"input",
"to",
"remote",
"dataset",
"."
] | python | train | 32.571429 |
BD2KGenomics/protect | src/protect/mutation_calling/somaticsniper.py | https://github.com/BD2KGenomics/protect/blob/06310682c50dcf8917b912c8e551299ff7ee41ce/src/protect/mutation_calling/somaticsniper.py#L50-L64 | def run_somaticsniper_with_merge(job, tumor_bam, normal_bam, univ_options, somaticsniper_options):
"""
A wrapper for the the entire SomaticSniper sub-graph.
:param dict tumor_bam: Dict of bam and bai for tumor DNA-Seq
:param dict normal_bam: Dict of bam and bai for normal DNA-Seq
:param dict univ_o... | [
"def",
"run_somaticsniper_with_merge",
"(",
"job",
",",
"tumor_bam",
",",
"normal_bam",
",",
"univ_options",
",",
"somaticsniper_options",
")",
":",
"spawn",
"=",
"job",
".",
"wrapJobFn",
"(",
"run_somaticsniper",
",",
"tumor_bam",
",",
"normal_bam",
",",
"univ_op... | A wrapper for the the entire SomaticSniper sub-graph.
:param dict tumor_bam: Dict of bam and bai for tumor DNA-Seq
:param dict normal_bam: Dict of bam and bai for normal DNA-Seq
:param dict univ_options: Dict of universal options used by almost all tools
:param dict somaticsniper_options: Options speci... | [
"A",
"wrapper",
"for",
"the",
"the",
"entire",
"SomaticSniper",
"sub",
"-",
"graph",
"."
] | python | train | 49 |
fprimex/zdesk | zdesk/zdesk_api.py | https://github.com/fprimex/zdesk/blob/851611c13b4d530e9df31390b3ec709baf0a0188/zdesk/zdesk_api.py#L4349-L4353 | def view_tickets(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/views#list-tickets-from-a-view"
api_path = "/api/v2/views/{id}/tickets.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | [
"def",
"view_tickets",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/views/{id}/tickets.json\"",
"api_path",
"=",
"api_path",
".",
"format",
"(",
"id",
"=",
"id",
")",
"return",
"self",
".",
"call",
"(",
"api_path",... | https://developer.zendesk.com/rest_api/docs/core/views#list-tickets-from-a-view | [
"https",
":",
"//",
"developer",
".",
"zendesk",
".",
"com",
"/",
"rest_api",
"/",
"docs",
"/",
"core",
"/",
"views#list",
"-",
"tickets",
"-",
"from",
"-",
"a",
"-",
"view"
] | python | train | 52.6 |
cons3rt/pycons3rt | pycons3rt/bash.py | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/bash.py#L1226-L1262 | def run_remote_command(host, command, timeout_sec=5.0):
"""Retrieves the value of an environment variable of a
remote host over SSH
:param host: (str) host to query
:param command: (str) command
:param timeout_sec (float) seconds to wait before killing the command.
:return: (str) command output... | [
"def",
"run_remote_command",
"(",
"host",
",",
"command",
",",
"timeout_sec",
"=",
"5.0",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.run_remote_command'",
")",
"if",
"not",
"isinstance",
"(",
"host",
",",
"basestring",
")",... | Retrieves the value of an environment variable of a
remote host over SSH
:param host: (str) host to query
:param command: (str) command
:param timeout_sec (float) seconds to wait before killing the command.
:return: (str) command output
:raises: TypeError, CommandError | [
"Retrieves",
"the",
"value",
"of",
"an",
"environment",
"variable",
"of",
"a",
"remote",
"host",
"over",
"SSH"
] | python | train | 40.189189 |
lemieuxl/pyGenClean | pyGenClean/SampleMissingness/sample_missingness.py | https://github.com/lemieuxl/pyGenClean/blob/6173a48ccc0cf3a3bd711b1f2a1fa16248b8bf55/pyGenClean/SampleMissingness/sample_missingness.py#L56-L83 | def runPlink(options):
"""Run Plink with the ``mind`` option.
:param options: the options.
:type options: argparse.Namespace
"""
# The plink command
plinkCommand = [
"plink",
"--noweb",
"--bfile" if options.is_bfile else "--tfile",
options.ifile,
"--min... | [
"def",
"runPlink",
"(",
"options",
")",
":",
"# The plink command",
"plinkCommand",
"=",
"[",
"\"plink\"",
",",
"\"--noweb\"",
",",
"\"--bfile\"",
"if",
"options",
".",
"is_bfile",
"else",
"\"--tfile\"",
",",
"options",
".",
"ifile",
",",
"\"--mind\"",
",",
"s... | Run Plink with the ``mind`` option.
:param options: the options.
:type options: argparse.Namespace | [
"Run",
"Plink",
"with",
"the",
"mind",
"option",
"."
] | python | train | 23.857143 |
brocade/pynos | pynos/versions/base/interface.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/base/interface.py#L67-L95 | def add_vlan_int(self, vlan_id):
"""
Add VLAN Interface. VLAN interfaces are required for VLANs even when
not wanting to use the interface for any L3 features.
Args:
vlan_id: ID for the VLAN interface being created. Value of 2-4096.
Returns:
True if comm... | [
"def",
"add_vlan_int",
"(",
"self",
",",
"vlan_id",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"'config'",
")",
"vlinterface",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"'interface-vlan'",
",",
"xmlns",
"=",
"(",
"\"urn:brocade.com:mgmt:\"",... | Add VLAN Interface. VLAN interfaces are required for VLANs even when
not wanting to use the interface for any L3 features.
Args:
vlan_id: ID for the VLAN interface being created. Value of 2-4096.
Returns:
True if command completes successfully or False if not.
... | [
"Add",
"VLAN",
"Interface",
".",
"VLAN",
"interfaces",
"are",
"required",
"for",
"VLANs",
"even",
"when",
"not",
"wanting",
"to",
"use",
"the",
"interface",
"for",
"any",
"L3",
"features",
"."
] | python | train | 34.931034 |
infothrill/python-dyndnsc | dyndnsc/updater/afraid.py | https://github.com/infothrill/python-dyndnsc/blob/2196d48aa6098da9835a7611fbdb0b5f0fbf51e4/dyndnsc/updater/afraid.py#L60-L74 | def compute_auth_key(userid, password):
"""
Compute the authentication key for freedns.afraid.org.
This is the SHA1 hash of the string b'userid|password'.
:param userid: ascii username
:param password: ascii password
:return: ascii authentication key (SHA1 at this point)
"""
import sys... | [
"def",
"compute_auth_key",
"(",
"userid",
",",
"password",
")",
":",
"import",
"sys",
"if",
"sys",
".",
"version_info",
">=",
"(",
"3",
",",
"0",
")",
":",
"return",
"hashlib",
".",
"sha1",
"(",
"b\"|\"",
".",
"join",
"(",
"(",
"userid",
".",
"encode... | Compute the authentication key for freedns.afraid.org.
This is the SHA1 hash of the string b'userid|password'.
:param userid: ascii username
:param password: ascii password
:return: ascii authentication key (SHA1 at this point) | [
"Compute",
"the",
"authentication",
"key",
"for",
"freedns",
".",
"afraid",
".",
"org",
"."
] | python | train | 37.533333 |
Gandi/gandi.cli | gandi/cli/commands/docker.py | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/docker.py#L15-L46 | def docker(gandi, vm, args):
"""
Manage docker instance
"""
if not [basedir for basedir in os.getenv('PATH', '.:/usr/bin').split(':')
if os.path.exists('%s/docker' % basedir)]:
gandi.echo("""'docker' not found in $PATH, required for this command \
to work
See https://docs.docker.com/... | [
"def",
"docker",
"(",
"gandi",
",",
"vm",
",",
"args",
")",
":",
"if",
"not",
"[",
"basedir",
"for",
"basedir",
"in",
"os",
".",
"getenv",
"(",
"'PATH'",
",",
"'.:/usr/bin'",
")",
".",
"split",
"(",
"':'",
")",
"if",
"os",
".",
"path",
".",
"exis... | Manage docker instance | [
"Manage",
"docker",
"instance"
] | python | train | 30.46875 |
brechtm/rinohtype | src/rinoh/paragraph.py | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/paragraph.py#L608-L696 | def render(self, container, descender, state, space_below=0,
first_line_only=False):
"""Typeset the paragraph
The paragraph is typeset in the given container starting below the
current cursor position of the container. When the end of the container
is reached, the renderi... | [
"def",
"render",
"(",
"self",
",",
"container",
",",
"descender",
",",
"state",
",",
"space_below",
"=",
"0",
",",
"first_line_only",
"=",
"False",
")",
":",
"indent_first",
"=",
"(",
"float",
"(",
"self",
".",
"get_style",
"(",
"'indent_first'",
",",
"c... | Typeset the paragraph
The paragraph is typeset in the given container starting below the
current cursor position of the container. When the end of the container
is reached, the rendering state is preserved to continue setting the
rest of the paragraph when this method is called with a n... | [
"Typeset",
"the",
"paragraph"
] | python | train | 46.41573 |
zhmcclient/python-zhmcclient | zhmcclient_mock/_urihandler.py | https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient_mock/_urihandler.py#L847-L862 | def get(method, hmc, uri, uri_parms, logon_required):
"""Operation: List Password Rules."""
query_str = uri_parms[0]
try:
console = hmc.consoles.lookup_by_oid(None)
except KeyError:
raise InvalidResourceError(method, uri)
result_password_rules = []
... | [
"def",
"get",
"(",
"method",
",",
"hmc",
",",
"uri",
",",
"uri_parms",
",",
"logon_required",
")",
":",
"query_str",
"=",
"uri_parms",
"[",
"0",
"]",
"try",
":",
"console",
"=",
"hmc",
".",
"consoles",
".",
"lookup_by_oid",
"(",
"None",
")",
"except",
... | Operation: List Password Rules. | [
"Operation",
":",
"List",
"Password",
"Rules",
"."
] | python | train | 48.75 |
kislyuk/aegea | aegea/packages/github3/session.py | https://github.com/kislyuk/aegea/blob/94957e9dba036eae3052e2662c208b259c08399a/aegea/packages/github3/session.py#L90-L97 | def retrieve_client_credentials(self):
"""Return the client credentials.
:returns: tuple(client_id, client_secret)
"""
client_id = self.params.get('client_id')
client_secret = self.params.get('client_secret')
return (client_id, client_secret) | [
"def",
"retrieve_client_credentials",
"(",
"self",
")",
":",
"client_id",
"=",
"self",
".",
"params",
".",
"get",
"(",
"'client_id'",
")",
"client_secret",
"=",
"self",
".",
"params",
".",
"get",
"(",
"'client_secret'",
")",
"return",
"(",
"client_id",
",",
... | Return the client credentials.
:returns: tuple(client_id, client_secret) | [
"Return",
"the",
"client",
"credentials",
"."
] | python | train | 35.5 |
ZELLMECHANIK-DRESDEN/fcswrite | fcswrite/fcswrite.py | https://github.com/ZELLMECHANIK-DRESDEN/fcswrite/blob/5584983aa1eb927660183252039e73285c0724b3/fcswrite/fcswrite.py#L13-L201 | def write_fcs(filename, chn_names, data,
endianness="big",
compat_chn_names=True,
compat_copy=True,
compat_negative=True,
compat_percent=True,
compat_max_int16=10000):
"""Write numpy data to an .fcs file (FCS3.0 file format)
P... | [
"def",
"write_fcs",
"(",
"filename",
",",
"chn_names",
",",
"data",
",",
"endianness",
"=",
"\"big\"",
",",
"compat_chn_names",
"=",
"True",
",",
"compat_copy",
"=",
"True",
",",
"compat_negative",
"=",
"True",
",",
"compat_percent",
"=",
"True",
",",
"compa... | Write numpy data to an .fcs file (FCS3.0 file format)
Parameters
----------
filename: str or pathlib.Path
Path to the output .fcs file
ch_names: list of str, length C
Names of the output channels
data: 2d ndarray of shape (N,C)
The numpy array data to store as .fcs file for... | [
"Write",
"numpy",
"data",
"to",
"an",
".",
"fcs",
"file",
"(",
"FCS3",
".",
"0",
"file",
"format",
")"
] | python | test | 34.708995 |
iotile/coretools | iotilecore/iotile/core/hw/transport/adapter/legacy.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/legacy.py#L189-L212 | def disconnect_sync(self, conn_id):
"""Synchronously disconnect from a connected device
Args:
conn_id (int): A unique identifier that will refer to this connection
Returns:
dict: A dictionary with two elements
'success': a bool with the result of the con... | [
"def",
"disconnect_sync",
"(",
"self",
",",
"conn_id",
")",
":",
"done",
"=",
"threading",
".",
"Event",
"(",
")",
"result",
"=",
"{",
"}",
"def",
"disconnect_done",
"(",
"conn_id",
",",
"adapter_id",
",",
"status",
",",
"reason",
")",
":",
"result",
"... | Synchronously disconnect from a connected device
Args:
conn_id (int): A unique identifier that will refer to this connection
Returns:
dict: A dictionary with two elements
'success': a bool with the result of the connection attempt
'failure_reason... | [
"Synchronously",
"disconnect",
"from",
"a",
"connected",
"device"
] | python | train | 30.875 |
AgeOfLearning/coeus-unity-python-framework | coeus_unity/transform.py | https://github.com/AgeOfLearning/coeus-unity-python-framework/blob/cf8ca6800ace1425d917ea2628dbd05ed959fdd7/coeus_unity/transform.py#L53-L67 | def get_rendered_transform_path_relative(self, relative_transform_ref):
"""
Generates a rendered transform path relative to
parent.
:param relative_transform_ref:
:return:
"""
path = self.transform_path
parent = self.parent
while parent is not Non... | [
"def",
"get_rendered_transform_path_relative",
"(",
"self",
",",
"relative_transform_ref",
")",
":",
"path",
"=",
"self",
".",
"transform_path",
"parent",
"=",
"self",
".",
"parent",
"while",
"parent",
"is",
"not",
"None",
"and",
"parent",
"is",
"not",
"relative... | Generates a rendered transform path relative to
parent.
:param relative_transform_ref:
:return: | [
"Generates",
"a",
"rendered",
"transform",
"path",
"relative",
"to",
"parent",
".",
":",
"param",
"relative_transform_ref",
":",
":",
"return",
":"
] | python | train | 31.333333 |
annoviko/pyclustering | pyclustering/cluster/kmedoids.py | https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/cluster/kmedoids.py#L212-L229 | def __create_distance_calculator(self):
"""!
@brief Creates distance calculator in line with algorithms parameters.
@return (callable) Distance calculator.
"""
if self.__data_type == 'points':
return lambda index1, index2: self.__metric(self.__pointer_data[i... | [
"def",
"__create_distance_calculator",
"(",
"self",
")",
":",
"if",
"self",
".",
"__data_type",
"==",
"'points'",
":",
"return",
"lambda",
"index1",
",",
"index2",
":",
"self",
".",
"__metric",
"(",
"self",
".",
"__pointer_data",
"[",
"index1",
"]",
",",
"... | !
@brief Creates distance calculator in line with algorithms parameters.
@return (callable) Distance calculator. | [
"!"
] | python | valid | 40.833333 |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/core/hooks.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/hooks.py#L213-L230 | def clipboard_get(self):
""" Get text from the clipboard.
"""
from IPython.lib.clipboard import (
osx_clipboard_get, tkinter_clipboard_get,
win32_clipboard_get
)
if sys.platform == 'win32':
chain = [win32_clipboard_get, tkinter_clipboard_get]
elif sys.platform == 'darwin'... | [
"def",
"clipboard_get",
"(",
"self",
")",
":",
"from",
"IPython",
".",
"lib",
".",
"clipboard",
"import",
"(",
"osx_clipboard_get",
",",
"tkinter_clipboard_get",
",",
"win32_clipboard_get",
")",
"if",
"sys",
".",
"platform",
"==",
"'win32'",
":",
"chain",
"=",... | Get text from the clipboard. | [
"Get",
"text",
"from",
"the",
"clipboard",
"."
] | python | test | 30.388889 |
SBRG/ssbio | ssbio/protein/sequence/seqprop.py | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/sequence/seqprop.py#L573-L604 | def get_subsequence(self, resnums, new_id=None, copy_letter_annotations=True):
"""Get a subsequence as a new SeqProp object given a list of residue numbers"""
# XTODO: documentation
biop_compound_list = []
for resnum in resnums:
# XTODO can be sped up by separating into range... | [
"def",
"get_subsequence",
"(",
"self",
",",
"resnums",
",",
"new_id",
"=",
"None",
",",
"copy_letter_annotations",
"=",
"True",
")",
":",
"# XTODO: documentation",
"biop_compound_list",
"=",
"[",
"]",
"for",
"resnum",
"in",
"resnums",
":",
"# XTODO can be sped up ... | Get a subsequence as a new SeqProp object given a list of residue numbers | [
"Get",
"a",
"subsequence",
"as",
"a",
"new",
"SeqProp",
"object",
"given",
"a",
"list",
"of",
"residue",
"numbers"
] | python | train | 42.6875 |
titusjan/argos | argos/config/qtctis.py | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/qtctis.py#L269-L279 | def data(self, data):
""" Sets the font data of this item.
Does type conversion to ensure data is always of the correct type.
Also updates the children (which is the reason for this property to be overloaded.
"""
self._data = self._enforceDataType(data) # Enforce self._d... | [
"def",
"data",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_data",
"=",
"self",
".",
"_enforceDataType",
"(",
"data",
")",
"# Enforce self._data to be a QFont",
"self",
".",
"familyCti",
".",
"data",
"=",
"fontFamilyIndex",
"(",
"self",
".",
"data",
... | Sets the font data of this item.
Does type conversion to ensure data is always of the correct type.
Also updates the children (which is the reason for this property to be overloaded. | [
"Sets",
"the",
"font",
"data",
"of",
"this",
"item",
".",
"Does",
"type",
"conversion",
"to",
"ensure",
"data",
"is",
"always",
"of",
"the",
"correct",
"type",
"."
] | python | train | 56.636364 |
andreikop/qutepart | qutepart/rectangularselection.py | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/rectangularselection.py#L154-L169 | def selections(self):
"""Build list of extra selections for rectangular selection"""
selections = []
cursors = self.cursors()
if cursors:
background = self._qpart.palette().color(QPalette.Highlight)
foreground = self._qpart.palette().color(QPalette.HighlightedText... | [
"def",
"selections",
"(",
"self",
")",
":",
"selections",
"=",
"[",
"]",
"cursors",
"=",
"self",
".",
"cursors",
"(",
")",
"if",
"cursors",
":",
"background",
"=",
"self",
".",
"_qpart",
".",
"palette",
"(",
")",
".",
"color",
"(",
"QPalette",
".",
... | Build list of extra selections for rectangular selection | [
"Build",
"list",
"of",
"extra",
"selections",
"for",
"rectangular",
"selection"
] | python | train | 39.3125 |
apache/incubator-mxnet | python/mxnet/gluon/utils.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/utils.py#L176-L199 | def check_sha1(filename, sha1_hash):
"""Check whether the sha1 hash of the file content matches the expected hash.
Parameters
----------
filename : str
Path to the file.
sha1_hash : str
Expected sha1 hash in hexadecimal digits.
Returns
-------
bool
Whether the f... | [
"def",
"check_sha1",
"(",
"filename",
",",
"sha1_hash",
")",
":",
"sha1",
"=",
"hashlib",
".",
"sha1",
"(",
")",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"f",
":",
"while",
"True",
":",
"data",
"=",
"f",
".",
"read",
"(",
"1048576",... | Check whether the sha1 hash of the file content matches the expected hash.
Parameters
----------
filename : str
Path to the file.
sha1_hash : str
Expected sha1 hash in hexadecimal digits.
Returns
-------
bool
Whether the file content matches the expected hash. | [
"Check",
"whether",
"the",
"sha1",
"hash",
"of",
"the",
"file",
"content",
"matches",
"the",
"expected",
"hash",
"."
] | python | train | 24.125 |
mathandy/svgpathtools | svgpathtools/path.py | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/path.py#L1031-L1044 | def is_smooth_from(self, previous, warning_on=True):
"""[Warning: The name of this method is somewhat misleading (yet kept
for compatibility with scripts created using svg.path 2.0). This
method is meant only for d string creation and should not be used to
check for kinks. To check a s... | [
"def",
"is_smooth_from",
"(",
"self",
",",
"previous",
",",
"warning_on",
"=",
"True",
")",
":",
"if",
"warning_on",
":",
"warn",
"(",
"_is_smooth_from_warning",
")",
"if",
"isinstance",
"(",
"previous",
",",
"CubicBezier",
")",
":",
"return",
"(",
"self",
... | [Warning: The name of this method is somewhat misleading (yet kept
for compatibility with scripts created using svg.path 2.0). This
method is meant only for d string creation and should not be used to
check for kinks. To check a segment for differentiability, use the
joins_smoothly_wit... | [
"[",
"Warning",
":",
"The",
"name",
"of",
"this",
"method",
"is",
"somewhat",
"misleading",
"(",
"yet",
"kept",
"for",
"compatibility",
"with",
"scripts",
"created",
"using",
"svg",
".",
"path",
"2",
".",
"0",
")",
".",
"This",
"method",
"is",
"meant",
... | python | train | 52.142857 |
reanahub/reana-db | reana_db/utils.py | https://github.com/reanahub/reana-db/blob/4efcb46d23af035689964d8c25a804c5a8f1dfc3/reana_db/utils.py#L152-L170 | def _get_workflow_by_uuid(workflow_uuid):
"""Get Workflow with UUIDv4.
:param workflow_uuid: UUIDv4 of a Workflow.
:type workflow_uuid: String representing a valid UUIDv4.
:rtype: reana-db.models.Workflow
"""
from reana_db.models import Workflow
workflow = Workflow.query.filter(Workflow.id... | [
"def",
"_get_workflow_by_uuid",
"(",
"workflow_uuid",
")",
":",
"from",
"reana_db",
".",
"models",
"import",
"Workflow",
"workflow",
"=",
"Workflow",
".",
"query",
".",
"filter",
"(",
"Workflow",
".",
"id_",
"==",
"workflow_uuid",
")",
".",
"first",
"(",
")"... | Get Workflow with UUIDv4.
:param workflow_uuid: UUIDv4 of a Workflow.
:type workflow_uuid: String representing a valid UUIDv4.
:rtype: reana-db.models.Workflow | [
"Get",
"Workflow",
"with",
"UUIDv4",
"."
] | python | train | 34.473684 |
brocade/pynos | pynos/versions/ver_7/ver_7_1_0/yang/brocade_ntp.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_ntp.py#L85-L99 | def ntp_server_key(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ntp = ET.SubElement(config, "ntp", xmlns="urn:brocade.com:mgmt:brocade-ntp")
server = ET.SubElement(ntp, "server")
ip_key = ET.SubElement(server, "ip")
ip_key.text = kwarg... | [
"def",
"ntp_server_key",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"ntp",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"ntp\"",
",",
"xmlns",
"=",
"\"urn:brocade.com:mgmt:brocade-ntp... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 39.466667 |
newville/wxmplot | wxmplot/plotpanel.py | https://github.com/newville/wxmplot/blob/8e0dc037453e5cdf18c968dc5a3d29efd761edee/wxmplot/plotpanel.py#L682-L698 | def __onPickEvent(self, event=None):
"""pick events"""
legline = event.artist
trace = self.conf.legend_map.get(legline, None)
visible = True
if trace is not None and self.conf.hidewith_legend:
line, legline, legtext = trace
visible = not line.get_visible()... | [
"def",
"__onPickEvent",
"(",
"self",
",",
"event",
"=",
"None",
")",
":",
"legline",
"=",
"event",
".",
"artist",
"trace",
"=",
"self",
".",
"conf",
".",
"legend_map",
".",
"get",
"(",
"legline",
",",
"None",
")",
"visible",
"=",
"True",
"if",
"trace... | pick events | [
"pick",
"events"
] | python | train | 36.941176 |
collectiveacuity/labPack | labpack/platforms/localhost.py | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/platforms/localhost.py#L392-L464 | def list(self, filter_function=None, list_root='', max_results=1, reverse_order=False, previous_file=''):
''' a method to list files on localhost from walk of directories
:param filter_function: (keyword arguments) function used to filter results
:param list_root: string with localhost pa... | [
"def",
"list",
"(",
"self",
",",
"filter_function",
"=",
"None",
",",
"list_root",
"=",
"''",
",",
"max_results",
"=",
"1",
",",
"reverse_order",
"=",
"False",
",",
"previous_file",
"=",
"''",
")",
":",
"__name__",
"=",
"'%s.list(...)'",
"%",
"self",
"."... | a method to list files on localhost from walk of directories
:param filter_function: (keyword arguments) function used to filter results
:param list_root: string with localhost path from which to root list of files
:param max_results: integer with maximum number of results to return
... | [
"a",
"method",
"to",
"list",
"files",
"on",
"localhost",
"from",
"walk",
"of",
"directories",
":",
"param",
"filter_function",
":",
"(",
"keyword",
"arguments",
")",
"function",
"used",
"to",
"filter",
"results",
":",
"param",
"list_root",
":",
"string",
"wi... | python | train | 42.767123 |
liftoff/pyminifier | pyminifier/obfuscate.py | https://github.com/liftoff/pyminifier/blob/087ea7b0c8c964f1f907c3f350f5ce281798db86/pyminifier/obfuscate.py#L533-L572 | def obfuscate_builtins(module, tokens, name_generator, table=None):
"""
Inserts an assignment, '<obfuscated identifier> = <builtin function>' at
the beginning of *tokens* (after the shebang and encoding if present) for
every Python built-in function that is used inside *tokens*. Also, replaces
all... | [
"def",
"obfuscate_builtins",
"(",
"module",
",",
"tokens",
",",
"name_generator",
",",
"table",
"=",
"None",
")",
":",
"used_builtins",
"=",
"analyze",
".",
"enumerate_builtins",
"(",
"tokens",
")",
"obfuscated_assignments",
"=",
"remap_name",
"(",
"name_generator... | Inserts an assignment, '<obfuscated identifier> = <builtin function>' at
the beginning of *tokens* (after the shebang and encoding if present) for
every Python built-in function that is used inside *tokens*. Also, replaces
all of said builti-in functions in *tokens* with each respective obfuscated
ide... | [
"Inserts",
"an",
"assignment",
"<obfuscated",
"identifier",
">",
"=",
"<builtin",
"function",
">",
"at",
"the",
"beginning",
"of",
"*",
"tokens",
"*",
"(",
"after",
"the",
"shebang",
"and",
"encoding",
"if",
"present",
")",
"for",
"every",
"Python",
"built",... | python | train | 45.025 |
locationlabs/mockredis | mockredis/client.py | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L424-L446 | def msetnx(self, *args, **kwargs):
"""
Sets key/values based on a mapping if none of the keys are already set.
Mapping can be supplied as a single dictionary argument or as kwargs.
Returns a boolean indicating if the operation was successful.
"""
if args:
if l... | [
"def",
"msetnx",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"args",
":",
"if",
"len",
"(",
"args",
")",
"!=",
"1",
"or",
"not",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"dict",
")",
":",
"raise",
"RedisError",... | Sets key/values based on a mapping if none of the keys are already set.
Mapping can be supplied as a single dictionary argument or as kwargs.
Returns a boolean indicating if the operation was successful. | [
"Sets",
"key",
"/",
"values",
"based",
"on",
"a",
"mapping",
"if",
"none",
"of",
"the",
"keys",
"are",
"already",
"set",
".",
"Mapping",
"can",
"be",
"supplied",
"as",
"a",
"single",
"dictionary",
"argument",
"or",
"as",
"kwargs",
".",
"Returns",
"a",
... | python | train | 35.782609 |
saltstack/salt | salt/pillar/s3.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/s3.py#L398-L432 | def _get_file_from_s3(creds, metadata, saltenv, bucket, path,
cached_file_path):
'''
Checks the local cache for the file, if it's old or missing go grab the
file from S3 and update the cache
'''
# check the local cache...
if os.path.isfile(cached_file_path):
file_m... | [
"def",
"_get_file_from_s3",
"(",
"creds",
",",
"metadata",
",",
"saltenv",
",",
"bucket",
",",
"path",
",",
"cached_file_path",
")",
":",
"# check the local cache...",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"cached_file_path",
")",
":",
"file_meta",
"=",... | Checks the local cache for the file, if it's old or missing go grab the
file from S3 and update the cache | [
"Checks",
"the",
"local",
"cache",
"for",
"the",
"file",
"if",
"it",
"s",
"old",
"or",
"missing",
"go",
"grab",
"the",
"file",
"from",
"S3",
"and",
"update",
"the",
"cache"
] | python | train | 33.371429 |
saltstack/salt | salt/cloud/clouds/vultrpy.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vultrpy.py#L265-L474 | def create(vm_):
'''
Create a single VM from a data dict
'''
if 'driver' not in vm_:
vm_['driver'] = vm_['provider']
private_networking = config.get_cloud_config_value(
'enable_private_network', vm_, __opts__, search_global=False, default=False,
)
startup_script = config.ge... | [
"def",
"create",
"(",
"vm_",
")",
":",
"if",
"'driver'",
"not",
"in",
"vm_",
":",
"vm_",
"[",
"'driver'",
"]",
"=",
"vm_",
"[",
"'provider'",
"]",
"private_networking",
"=",
"config",
".",
"get_cloud_config_value",
"(",
"'enable_private_network'",
",",
"vm_"... | Create a single VM from a data dict | [
"Create",
"a",
"single",
"VM",
"from",
"a",
"data",
"dict"
] | python | train | 32.961905 |
getsenic/gatt-python | gatt/gatt_linux.py | https://github.com/getsenic/gatt-python/blob/e1b147d54ff199571b6c0b43bdd3a9e1ce03850c/gatt/gatt_linux.py#L626-L631 | def _write_value_failed(self, dbus_error):
"""
Called when the write request has failed.
"""
error = _error_from_dbus_error(dbus_error)
self.service.device.characteristic_write_value_failed(characteristic=self, error=error) | [
"def",
"_write_value_failed",
"(",
"self",
",",
"dbus_error",
")",
":",
"error",
"=",
"_error_from_dbus_error",
"(",
"dbus_error",
")",
"self",
".",
"service",
".",
"device",
".",
"characteristic_write_value_failed",
"(",
"characteristic",
"=",
"self",
",",
"error... | Called when the write request has failed. | [
"Called",
"when",
"the",
"write",
"request",
"has",
"failed",
"."
] | python | train | 43 |
tipsi/aiozk | aiozk/recipes/allocator.py | https://github.com/tipsi/aiozk/blob/96d2f543de248c6d993b5bfe6621167dd1eb8223/aiozk/recipes/allocator.py#L121-L134 | def round_robin(members, items):
"""
Default allocator with a round robin approach.
In this algorithm, each member of the group is cycled over and given an
item until there are no items left. This assumes roughly equal capacity
for each member and aims for even distribution of item counts.
"""... | [
"def",
"round_robin",
"(",
"members",
",",
"items",
")",
":",
"allocation",
"=",
"collections",
".",
"defaultdict",
"(",
"set",
")",
"for",
"member",
",",
"item",
"in",
"zip",
"(",
"itertools",
".",
"cycle",
"(",
"members",
")",
",",
"items",
")",
":",... | Default allocator with a round robin approach.
In this algorithm, each member of the group is cycled over and given an
item until there are no items left. This assumes roughly equal capacity
for each member and aims for even distribution of item counts. | [
"Default",
"allocator",
"with",
"a",
"round",
"robin",
"approach",
"."
] | python | train | 34 |
santoshphilip/eppy | eppy/useful_scripts/loopdiagram.py | https://github.com/santoshphilip/eppy/blob/55410ff7c11722f35bc4331ff5e00a0b86f787e1/eppy/useful_scripts/loopdiagram.py#L206-L494 | def makeairplantloop(data, commdct):
"""make the edges for the airloop and the plantloop"""
anode = "epnode"
endnode = "EndNode"
# in plantloop get:
# demand inlet, outlet, branchlist
# supply inlet, outlet, branchlist
plantloops = loops.plantloopfields(data, commdct)
# splitter... | [
"def",
"makeairplantloop",
"(",
"data",
",",
"commdct",
")",
":",
"anode",
"=",
"\"epnode\"",
"endnode",
"=",
"\"EndNode\"",
"# in plantloop get:",
"# demand inlet, outlet, branchlist",
"# supply inlet, outlet, branchlist",
"plantloops",
"=",
"loops",
".",
"plantloo... | make the edges for the airloop and the plantloop | [
"make",
"the",
"edges",
"for",
"the",
"airloop",
"and",
"the",
"plantloop"
] | python | train | 38.705882 |
phn/lineid_plot | lineid_plot/lineid_plot.py | https://github.com/phn/lineid_plot/blob/7c7a1af53fe439b3a7c5a57f01680575837fb978/lineid_plot/lineid_plot.py#L16-L37 | def _convert_to_array(x, size, name):
"""Check length of array or convert scalar to array.
Check to see is `x` has the given length `size`. If this is true
then return Numpy array equivalent of `x`. If not then raise
ValueError, using `name` as an idnetification. If len(x) returns
TypeError, then a... | [
"def",
"_convert_to_array",
"(",
"x",
",",
"size",
",",
"name",
")",
":",
"try",
":",
"l",
"=",
"len",
"(",
"x",
")",
"if",
"l",
"!=",
"size",
":",
"raise",
"ValueError",
"(",
"\"{0} must be scalar or of length {1}\"",
".",
"format",
"(",
"name",
",",
... | Check length of array or convert scalar to array.
Check to see is `x` has the given length `size`. If this is true
then return Numpy array equivalent of `x`. If not then raise
ValueError, using `name` as an idnetification. If len(x) returns
TypeError, then assume it is a scalar and create a Numpy array... | [
"Check",
"length",
"of",
"array",
"or",
"convert",
"scalar",
"to",
"array",
"."
] | python | train | 34.681818 |
apache/spark | python/pyspark/rdd.py | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L2316-L2331 | def sumApprox(self, timeout, confidence=0.95):
"""
.. note:: Experimental
Approximate operation to return the sum within a timeout
or meet the confidence.
>>> rdd = sc.parallelize(range(1000), 10)
>>> r = sum(range(1000))
>>> abs(rdd.sumApprox(1000) - r) / r < 0... | [
"def",
"sumApprox",
"(",
"self",
",",
"timeout",
",",
"confidence",
"=",
"0.95",
")",
":",
"jrdd",
"=",
"self",
".",
"mapPartitions",
"(",
"lambda",
"it",
":",
"[",
"float",
"(",
"sum",
"(",
"it",
")",
")",
"]",
")",
".",
"_to_java_object_rdd",
"(",
... | .. note:: Experimental
Approximate operation to return the sum within a timeout
or meet the confidence.
>>> rdd = sc.parallelize(range(1000), 10)
>>> r = sum(range(1000))
>>> abs(rdd.sumApprox(1000) - r) / r < 0.05
True | [
"..",
"note",
"::",
"Experimental"
] | python | train | 38.75 |
eaton-lab/toytree | toytree/etemini.py | https://github.com/eaton-lab/toytree/blob/0347ed2098acc5f707fadf52a0ecd411a6d1859c/toytree/etemini.py#L675-L686 | def _iter_descendants_preorder(self, is_leaf_fn=None):
""" Iterator over all descendant nodes. """
to_visit = deque()
node = self
while node is not None:
yield node
if not is_leaf_fn or not is_leaf_fn(node):
to_visit.extendleft(reversed(node.childr... | [
"def",
"_iter_descendants_preorder",
"(",
"self",
",",
"is_leaf_fn",
"=",
"None",
")",
":",
"to_visit",
"=",
"deque",
"(",
")",
"node",
"=",
"self",
"while",
"node",
"is",
"not",
"None",
":",
"yield",
"node",
"if",
"not",
"is_leaf_fn",
"or",
"not",
"is_l... | Iterator over all descendant nodes. | [
"Iterator",
"over",
"all",
"descendant",
"nodes",
"."
] | python | train | 35 |
xgvargas/smartside | smartside/signal.py | https://github.com/xgvargas/smartside/blob/c63acb7d628b161f438e877eca12d550647de34d/smartside/signal.py#L98-L109 | def print_signals_and_slots(self):
"""
List all active Slots and Signal.
Credits to: http://visitusers.org/index.php?title=PySide_Recipes#Debugging
"""
for i in xrange(self.metaObject().methodCount()):
m = self.metaObject().method(i)
if m.methodType() =... | [
"def",
"print_signals_and_slots",
"(",
"self",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"self",
".",
"metaObject",
"(",
")",
".",
"methodCount",
"(",
")",
")",
":",
"m",
"=",
"self",
".",
"metaObject",
"(",
")",
".",
"method",
"(",
"i",
")",
"if"... | List all active Slots and Signal.
Credits to: http://visitusers.org/index.php?title=PySide_Recipes#Debugging | [
"List",
"all",
"active",
"Slots",
"and",
"Signal",
"."
] | python | train | 47.666667 |
nickmckay/LiPD-utilities | Python/lipd/doi_resolver.py | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/doi_resolver.py#L214-L236 | def find_doi(self, curr_dict):
"""
Recursively search the file for the DOI id. More taxing, but more flexible when dictionary structuring isn't absolute
:param dict curr_dict: Current dictionary being searched
:return dict bool: Recursive - Current dictionary, False flag that DOI was not... | [
"def",
"find_doi",
"(",
"self",
",",
"curr_dict",
")",
":",
"try",
":",
"if",
"'id'",
"in",
"curr_dict",
":",
"return",
"curr_dict",
"[",
"'id'",
"]",
",",
"True",
"elif",
"isinstance",
"(",
"curr_dict",
",",
"list",
")",
":",
"for",
"i",
"in",
"curr... | Recursively search the file for the DOI id. More taxing, but more flexible when dictionary structuring isn't absolute
:param dict curr_dict: Current dictionary being searched
:return dict bool: Recursive - Current dictionary, False flag that DOI was not found
:return str bool: Final - DOI id, Tr... | [
"Recursively",
"search",
"the",
"file",
"for",
"the",
"DOI",
"id",
".",
"More",
"taxing",
"but",
"more",
"flexible",
"when",
"dictionary",
"structuring",
"isn",
"t",
"absolute",
":",
"param",
"dict",
"curr_dict",
":",
"Current",
"dictionary",
"being",
"searche... | python | train | 44.73913 |
gem/oq-engine | openquake/commonlib/writers.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/writers.py#L74-L86 | def write(self, descrs):
"""
Convert descriptions into names
"""
# example: '(poe-[\d\.]+):float32' -> 'poe-[\d\.]+'
names = []
for descr in descrs:
mo = re.match(self.long_regex, descr)
if mo:
names.append(mo.group(mo.lastindex) + ... | [
"def",
"write",
"(",
"self",
",",
"descrs",
")",
":",
"# example: '(poe-[\\d\\.]+):float32' -> 'poe-[\\d\\.]+'",
"names",
"=",
"[",
"]",
"for",
"descr",
"in",
"descrs",
":",
"mo",
"=",
"re",
".",
"match",
"(",
"self",
".",
"long_regex",
",",
"descr",
")",
... | Convert descriptions into names | [
"Convert",
"descriptions",
"into",
"names"
] | python | train | 30.769231 |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_common_def.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_common_def.py#L475-L487 | def ip_hide_ext_community_list_holder_extcommunity_list_ext_community_expr(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip = ET.SubElement(config, "ip", xmlns="urn:brocade.com:mgmt:brocade-common-def")
hide_ext_community_list_holder = ET.SubElement(ip... | [
"def",
"ip_hide_ext_community_list_holder_extcommunity_list_ext_community_expr",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"ip",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"ip\"",
",",
... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 64 |
etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-SMI.py | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L860-L925 | def writeCommit(self, varBind, **context):
"""Commit new value of the Managed Object Instance.
Implements the second of the multi-step workflow of the SNMP SET
command processing (:RFC:`1905#section-4.2.5`).
The goal of the second phase is to actually modify the requested Managed
... | [
"def",
"writeCommit",
"(",
"self",
",",
"varBind",
",",
"*",
"*",
"context",
")",
":",
"name",
",",
"val",
"=",
"varBind",
"(",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_INS",
"and",
"debug",
".",
"logger",
"(",
"'%s: writeCommit(%s, %r)'",
"%",
... | Commit new value of the Managed Object Instance.
Implements the second of the multi-step workflow of the SNMP SET
command processing (:RFC:`1905#section-4.2.5`).
The goal of the second phase is to actually modify the requested Managed
Object Instance. When multiple Managed Objects Inst... | [
"Commit",
"new",
"value",
"of",
"the",
"Managed",
"Object",
"Instance",
"."
] | python | train | 37.393939 |
seleniumbase/SeleniumBase | seleniumbase/plugins/base_plugin.py | https://github.com/seleniumbase/SeleniumBase/blob/62e5b43ee1f90a9ed923841bdd53b1b38358f43a/seleniumbase/plugins/base_plugin.py#L184-L200 | def handleError(self, test, err, capt=None):
"""
If the database plugin is not present, we have to handle capturing
"errors" that shouldn't be reported as such in base.
"""
if not hasattr(test.test, "testcase_guid"):
if err[0] == errors.BlockedTest:
ra... | [
"def",
"handleError",
"(",
"self",
",",
"test",
",",
"err",
",",
"capt",
"=",
"None",
")",
":",
"if",
"not",
"hasattr",
"(",
"test",
".",
"test",
",",
"\"testcase_guid\"",
")",
":",
"if",
"err",
"[",
"0",
"]",
"==",
"errors",
".",
"BlockedTest",
":... | If the database plugin is not present, we have to handle capturing
"errors" that shouldn't be reported as such in base. | [
"If",
"the",
"database",
"plugin",
"is",
"not",
"present",
"we",
"have",
"to",
"handle",
"capturing",
"errors",
"that",
"shouldn",
"t",
"be",
"reported",
"as",
"such",
"in",
"base",
"."
] | python | train | 34.235294 |
ThreatConnect-Inc/tcex | tcex/tcex_session.py | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_session.py#L70-L74 | def request(self, method, url, **kwargs):
"""Override request method disabling verify on token renewal if disabled on session."""
if not url.startswith('https'):
url = '{}{}'.format(self.args.tc_api_path, url)
return super(TcExSession, self).request(method, url, **kwargs) | [
"def",
"request",
"(",
"self",
",",
"method",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"url",
".",
"startswith",
"(",
"'https'",
")",
":",
"url",
"=",
"'{}{}'",
".",
"format",
"(",
"self",
".",
"args",
".",
"tc_api_path",
",",
... | Override request method disabling verify on token renewal if disabled on session. | [
"Override",
"request",
"method",
"disabling",
"verify",
"on",
"token",
"renewal",
"if",
"disabled",
"on",
"session",
"."
] | python | train | 60.8 |
dereneaton/ipyrad | ipyrad/assemble/cluster_within.py | https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/cluster_within.py#L493-L618 | def build_clusters(data, sample, maxindels):
"""
Combines information from .utemp and .htemp files to create .clust files,
which contain un-aligned clusters. Hits to seeds are only kept in the
cluster if the number of internal indels is less than 'maxindels'.
By default, we set maxindels=6 for this ... | [
"def",
"build_clusters",
"(",
"data",
",",
"sample",
",",
"maxindels",
")",
":",
"## If reference assembly then here we're clustering the unmapped reads",
"if",
"\"reference\"",
"in",
"data",
".",
"paramsdict",
"[",
"\"assembly_method\"",
"]",
":",
"derepfile",
"=",
"os... | Combines information from .utemp and .htemp files to create .clust files,
which contain un-aligned clusters. Hits to seeds are only kept in the
cluster if the number of internal indels is less than 'maxindels'.
By default, we set maxindels=6 for this step (within-sample clustering). | [
"Combines",
"information",
"from",
".",
"utemp",
"and",
".",
"htemp",
"files",
"to",
"create",
".",
"clust",
"files",
"which",
"contain",
"un",
"-",
"aligned",
"clusters",
".",
"Hits",
"to",
"seeds",
"are",
"only",
"kept",
"in",
"the",
"cluster",
"if",
"... | python | valid | 39.095238 |
Stewori/pytypes | pytypes/util.py | https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/util.py#L94-L108 | def getargspecs(func):
"""Bridges inspect.getargspec and inspect.getfullargspec.
Automatically selects the proper one depending of current Python version.
Automatically bypasses wrappers from typechecked- and override-decorators.
"""
if func is None:
raise TypeError('None is not a Python fun... | [
"def",
"getargspecs",
"(",
"func",
")",
":",
"if",
"func",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"'None is not a Python function'",
")",
"if",
"hasattr",
"(",
"func",
",",
"'ch_func'",
")",
":",
"return",
"getargspecs",
"(",
"func",
".",
"ch_func",
... | Bridges inspect.getargspec and inspect.getfullargspec.
Automatically selects the proper one depending of current Python version.
Automatically bypasses wrappers from typechecked- and override-decorators. | [
"Bridges",
"inspect",
".",
"getargspec",
"and",
"inspect",
".",
"getfullargspec",
".",
"Automatically",
"selects",
"the",
"proper",
"one",
"depending",
"of",
"current",
"Python",
"version",
".",
"Automatically",
"bypasses",
"wrappers",
"from",
"typechecked",
"-",
... | python | train | 40.733333 |
ask/carrot | carrot/messaging.py | https://github.com/ask/carrot/blob/5889a25cd2e274642071c9bba39772f4b3e3d9da/carrot/messaging.py#L436-L449 | def wait(self, limit=None):
"""Go into consume mode.
Mostly for testing purposes and simple programs, you probably
want :meth:`iterconsume` or :meth:`iterqueue` instead.
This runs an infinite loop, processing all incoming messages
using :meth:`receive` to apply the message to a... | [
"def",
"wait",
"(",
"self",
",",
"limit",
"=",
"None",
")",
":",
"it",
"=",
"self",
".",
"iterconsume",
"(",
"limit",
")",
"while",
"True",
":",
"it",
".",
"next",
"(",
")"
] | Go into consume mode.
Mostly for testing purposes and simple programs, you probably
want :meth:`iterconsume` or :meth:`iterqueue` instead.
This runs an infinite loop, processing all incoming messages
using :meth:`receive` to apply the message to all registered
callbacks. | [
"Go",
"into",
"consume",
"mode",
"."
] | python | train | 30.785714 |
googledatalab/pydatalab | google/datalab/utils/_utils.py | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/_utils.py#L111-L125 | def is_http_running_on(port):
""" Check if an http server runs on a given port.
Args:
The port to check.
Returns:
True if it is used by an http server. False otherwise.
"""
try:
conn = httplib.HTTPConnection('127.0.0.1:' + str(port))
conn.connect()
conn.close()
return True
except Ex... | [
"def",
"is_http_running_on",
"(",
"port",
")",
":",
"try",
":",
"conn",
"=",
"httplib",
".",
"HTTPConnection",
"(",
"'127.0.0.1:'",
"+",
"str",
"(",
"port",
")",
")",
"conn",
".",
"connect",
"(",
")",
"conn",
".",
"close",
"(",
")",
"return",
"True",
... | Check if an http server runs on a given port.
Args:
The port to check.
Returns:
True if it is used by an http server. False otherwise. | [
"Check",
"if",
"an",
"http",
"server",
"runs",
"on",
"a",
"given",
"port",
"."
] | python | train | 22.066667 |
ChrisCummins/labm8 | lockfile.py | https://github.com/ChrisCummins/labm8/blob/dd10d67a757aefb180cb508f86696f99440c94f5/lockfile.py#L111-L152 | def acquire(self, replace_stale=False, force=False):
"""
Acquire the lock.
A lock can be claimed if any of these conditions are true:
1. The lock is unheld by anyone.
2. The lock is held but the 'force' argument is set.
3. The lock is held by the current proc... | [
"def",
"acquire",
"(",
"self",
",",
"replace_stale",
"=",
"False",
",",
"force",
"=",
"False",
")",
":",
"def",
"_create_lock",
"(",
")",
":",
"LockFile",
".",
"write",
"(",
"self",
".",
"path",
",",
"os",
".",
"getpid",
"(",
")",
",",
"time",
".",... | Acquire the lock.
A lock can be claimed if any of these conditions are true:
1. The lock is unheld by anyone.
2. The lock is held but the 'force' argument is set.
3. The lock is held by the current process.
Arguments:
replace_stale (bool, optional) If tr... | [
"Acquire",
"the",
"lock",
"."
] | python | train | 33.333333 |
sprockets/sprockets.mixins.statsd | sprockets/mixins/statsd/__init__.py | https://github.com/sprockets/sprockets.mixins.statsd/blob/98dcce37d275a3ab96ef618b4756d7c4618a550a/sprockets/mixins/statsd/__init__.py#L89-L130 | def on_finish(self):
"""Invoked once the request has been finished. Increments a counter
created in the format:
.. code::
<PREFIX>.counters.<host>.package[.module].Class.METHOD.STATUS
sprockets.counters.localhost.tornado.web.RequestHandler.GET.200
Adds a value ... | [
"def",
"on_finish",
"(",
"self",
")",
":",
"if",
"self",
".",
"statsd_prefix",
"!=",
"statsd",
".",
"STATSD_PREFIX",
":",
"statsd",
".",
"set_prefix",
"(",
"self",
".",
"statsd_prefix",
")",
"if",
"hasattr",
"(",
"self",
",",
"'request'",
")",
"and",
"se... | Invoked once the request has been finished. Increments a counter
created in the format:
.. code::
<PREFIX>.counters.<host>.package[.module].Class.METHOD.STATUS
sprockets.counters.localhost.tornado.web.RequestHandler.GET.200
Adds a value to a timer in the following form... | [
"Invoked",
"once",
"the",
"request",
"has",
"been",
"finished",
".",
"Increments",
"a",
"counter",
"created",
"in",
"the",
"format",
":"
] | python | train | 36.97619 |
majuss/lupupy | lupupy/devices/binary_sensor.py | https://github.com/majuss/lupupy/blob/71af6c397837ffc393c7b8122be175602638d3c6/lupupy/devices/binary_sensor.py#L11-L18 | def is_on(self):
"""
Get sensor state.
Assume offline or open (worst case).
"""
return self.status not in (CONST.STATUS_OFF, CONST.STATUS_OFFLINE,
CONST.STATUS_CLOSED, CONST.STATUS_OPEN) | [
"def",
"is_on",
"(",
"self",
")",
":",
"return",
"self",
".",
"status",
"not",
"in",
"(",
"CONST",
".",
"STATUS_OFF",
",",
"CONST",
".",
"STATUS_OFFLINE",
",",
"CONST",
".",
"STATUS_CLOSED",
",",
"CONST",
".",
"STATUS_OPEN",
")"
] | Get sensor state.
Assume offline or open (worst case). | [
"Get",
"sensor",
"state",
"."
] | python | train | 31.875 |
pymupdf/PyMuPDF | fitz/fitz.py | https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2293-L2298 | def _getOLRootNumber(self):
"""_getOLRootNumber(self) -> PyObject *"""
if self.isClosed or self.isEncrypted:
raise ValueError("operation illegal for closed / encrypted doc")
return _fitz.Document__getOLRootNumber(self) | [
"def",
"_getOLRootNumber",
"(",
"self",
")",
":",
"if",
"self",
".",
"isClosed",
"or",
"self",
".",
"isEncrypted",
":",
"raise",
"ValueError",
"(",
"\"operation illegal for closed / encrypted doc\"",
")",
"return",
"_fitz",
".",
"Document__getOLRootNumber",
"(",
"se... | _getOLRootNumber(self) -> PyObject * | [
"_getOLRootNumber",
"(",
"self",
")",
"-",
">",
"PyObject",
"*"
] | python | train | 41.666667 |
AkihikoITOH/capybara | capybara/virtualenv/lib/python2.7/site-packages/setuptools/command/easy_install.py | https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/setuptools/command/easy_install.py#L1223-L1257 | def install_site_py(self):
"""Make sure there's a site.py in the target dir, if needed"""
if self.sitepy_installed:
return # already did it, or don't need to
sitepy = os.path.join(self.install_dir, "site.py")
source = resource_string("setuptools", "site-patch.py")
... | [
"def",
"install_site_py",
"(",
"self",
")",
":",
"if",
"self",
".",
"sitepy_installed",
":",
"return",
"# already did it, or don't need to",
"sitepy",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"install_dir",
",",
"\"site.py\"",
")",
"source",
"=",... | Make sure there's a site.py in the target dir, if needed | [
"Make",
"sure",
"there",
"s",
"a",
"site",
".",
"py",
"in",
"the",
"target",
"dir",
"if",
"needed"
] | python | test | 32.8 |
RedHatInsights/insights-core | insights/contrib/ConfigParser.py | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/contrib/ConfigParser.py#L630-L660 | def items(self, section, raw=False, vars=None):
"""Return a list of tuples with (name, value) for each option
in the section.
All % interpolations are expanded in the return values, based on the
defaults passed into the constructor, unless the optional argument
`raw' is true. A... | [
"def",
"items",
"(",
"self",
",",
"section",
",",
"raw",
"=",
"False",
",",
"vars",
"=",
"None",
")",
":",
"d",
"=",
"self",
".",
"_defaults",
".",
"copy",
"(",
")",
"try",
":",
"d",
".",
"update",
"(",
"self",
".",
"_sections",
"[",
"section",
... | Return a list of tuples with (name, value) for each option
in the section.
All % interpolations are expanded in the return values, based on the
defaults passed into the constructor, unless the optional argument
`raw' is true. Additional substitutions may be provided using the
`... | [
"Return",
"a",
"list",
"of",
"tuples",
"with",
"(",
"name",
"value",
")",
"for",
"each",
"option",
"in",
"the",
"section",
"."
] | python | train | 38.806452 |
tensorlayer/tensorlayer | tensorlayer/visualize.py | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/visualize.py#L101-L145 | def save_images(images, size, image_path='_temp.png'):
"""Save multiple images into one single image.
Parameters
-----------
images : numpy array
(batch, w, h, c)
size : list of 2 ints
row and column number.
number of images should be equal or less than size[0] * size[1]
... | [
"def",
"save_images",
"(",
"images",
",",
"size",
",",
"image_path",
"=",
"'_temp.png'",
")",
":",
"if",
"len",
"(",
"images",
".",
"shape",
")",
"==",
"3",
":",
"# Greyscale [batch, h, w] --> [batch, h, w, 1]",
"images",
"=",
"images",
"[",
":",
",",
":",
... | Save multiple images into one single image.
Parameters
-----------
images : numpy array
(batch, w, h, c)
size : list of 2 ints
row and column number.
number of images should be equal or less than size[0] * size[1]
image_path : str
save path
Examples
--------... | [
"Save",
"multiple",
"images",
"into",
"one",
"single",
"image",
"."
] | python | valid | 33.688889 |
rikrd/inspire | inspirespeech/common.py | https://github.com/rikrd/inspire/blob/e281c0266a9a9633f34ab70f9c3ad58036c19b59/inspirespeech/common.py#L571-L615 | def create_flat_start_model(feature_filename,
state_stay_probabilities,
symbol_list,
output_model_directory,
output_prototype_filename,
htk_trace):
"""
Creates a flat start... | [
"def",
"create_flat_start_model",
"(",
"feature_filename",
",",
"state_stay_probabilities",
",",
"symbol_list",
",",
"output_model_directory",
",",
"output_prototype_filename",
",",
"htk_trace",
")",
":",
"# Create a prototype model",
"create_prototype_model",
"(",
"feature_fil... | Creates a flat start model by using HCompV to compute the global mean and variance.
Then uses these global mean and variance to create an N-state model for each symbol in the given list.
:param feature_filename: The filename containing the audio and feature file pairs
:param output_model_directory: The dir... | [
"Creates",
"a",
"flat",
"start",
"model",
"by",
"using",
"HCompV",
"to",
"compute",
"the",
"global",
"mean",
"and",
"variance",
".",
"Then",
"uses",
"these",
"global",
"mean",
"and",
"variance",
"to",
"create",
"an",
"N",
"-",
"state",
"model",
"for",
"e... | python | train | 47.933333 |
pysathq/pysat | examples/hitman.py | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/examples/hitman.py#L296-L315 | def get(self):
"""
This method computes and returns a hitting set. The hitting set is
obtained using the underlying oracle operating the MaxSAT problem
formulation. The computed solution is mapped back to objects of the
problem domain.
:rtype: list(ob... | [
"def",
"get",
"(",
"self",
")",
":",
"model",
"=",
"self",
".",
"oracle",
".",
"compute",
"(",
")",
"if",
"model",
":",
"if",
"self",
".",
"htype",
"==",
"'rc2'",
":",
"# extracting a hitting set",
"self",
".",
"hset",
"=",
"filter",
"(",
"lambda",
"... | This method computes and returns a hitting set. The hitting set is
obtained using the underlying oracle operating the MaxSAT problem
formulation. The computed solution is mapped back to objects of the
problem domain.
:rtype: list(obj) | [
"This",
"method",
"computes",
"and",
"returns",
"a",
"hitting",
"set",
".",
"The",
"hitting",
"set",
"is",
"obtained",
"using",
"the",
"underlying",
"oracle",
"operating",
"the",
"MaxSAT",
"problem",
"formulation",
".",
"The",
"computed",
"solution",
"is",
"ma... | python | train | 32.05 |
pingali/dgit | dgitcore/contrib/repomanagers/gitmanager.py | https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/contrib/repomanagers/gitmanager.py#L381-L405 | def drop(self, repo, args=[]):
"""
Cleanup the repo
"""
# Clean up the rootdir
rootdir = repo.rootdir
if os.path.exists(rootdir):
print("Cleaning repo directory: {}".format(rootdir))
shutil.rmtree(rootdir)
# Cleanup the local version of t... | [
"def",
"drop",
"(",
"self",
",",
"repo",
",",
"args",
"=",
"[",
"]",
")",
":",
"# Clean up the rootdir",
"rootdir",
"=",
"repo",
".",
"rootdir",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"rootdir",
")",
":",
"print",
"(",
"\"Cleaning repo directory: {... | Cleanup the repo | [
"Cleanup",
"the",
"repo"
] | python | valid | 32.04 |
AguaClara/aguaclara | aguaclara/design/sed_tank.py | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/sed_tank.py#L422-L440 | def q_diffuser(sed_inputs=sed_dict):
"""Return the flow through each diffuser.
Parameters
----------
sed_inputs : dict
A dictionary of all of the constant inputs needed for sedimentation tank
calculations can be found in sed.yaml
Returns
-------
float
Flow through eac... | [
"def",
"q_diffuser",
"(",
"sed_inputs",
"=",
"sed_dict",
")",
":",
"return",
"(",
"sed_inputs",
"[",
"'tank'",
"]",
"[",
"'vel_up'",
"]",
".",
"to",
"(",
"u",
".",
"m",
"/",
"u",
".",
"s",
")",
"*",
"sed_inputs",
"[",
"'tank'",
"]",
"[",
"'W'",
"... | Return the flow through each diffuser.
Parameters
----------
sed_inputs : dict
A dictionary of all of the constant inputs needed for sedimentation tank
calculations can be found in sed.yaml
Returns
-------
float
Flow through each diffuser in the sedimentation tank
Exa... | [
"Return",
"the",
"flow",
"through",
"each",
"diffuser",
".",
"Parameters",
"----------",
"sed_inputs",
":",
"dict",
"A",
"dictionary",
"of",
"all",
"of",
"the",
"constant",
"inputs",
"needed",
"for",
"sedimentation",
"tank",
"calculations",
"can",
"be",
"found",... | python | train | 30.157895 |
pmacosta/ptrie | ptrie/ptrie.py | https://github.com/pmacosta/ptrie/blob/c176d3ee810b7b5243c7ff2bbf2f1af0b0fff2a8/ptrie/ptrie.py#L1077-L1133 | def print_node(self, name): # noqa: D302
r"""
Print node information (parent, children and data).
:param name: Node name
:type name: :ref:`NodeName`
:raises:
* RuntimeError (Argument \`name\` is not valid)
* RuntimeError (Node *[name]* not in tree)
... | [
"def",
"print_node",
"(",
"self",
",",
"name",
")",
":",
"# noqa: D302",
"if",
"self",
".",
"_validate_node_name",
"(",
"name",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Argument `name` is not valid\"",
")",
"self",
".",
"_node_in_tree",
"(",
"name",
")",
"no... | r"""
Print node information (parent, children and data).
:param name: Node name
:type name: :ref:`NodeName`
:raises:
* RuntimeError (Argument \`name\` is not valid)
* RuntimeError (Node *[name]* not in tree)
Using the same example tree created in
:p... | [
"r",
"Print",
"node",
"information",
"(",
"parent",
"children",
"and",
"data",
")",
"."
] | python | train | 31.421053 |
saltstack/salt | salt/states/file.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/file.py#L1032-L1047 | def _set_symlink_ownership(path, user, group, win_owner):
'''
Set the ownership of a symlink and return a boolean indicating
success/failure
'''
if salt.utils.platform.is_windows():
try:
salt.utils.win_dacl.set_owner(path, win_owner)
except CommandExecutionError:
... | [
"def",
"_set_symlink_ownership",
"(",
"path",
",",
"user",
",",
"group",
",",
"win_owner",
")",
":",
"if",
"salt",
".",
"utils",
".",
"platform",
".",
"is_windows",
"(",
")",
":",
"try",
":",
"salt",
".",
"utils",
".",
"win_dacl",
".",
"set_owner",
"("... | Set the ownership of a symlink and return a boolean indicating
success/failure | [
"Set",
"the",
"ownership",
"of",
"a",
"symlink",
"and",
"return",
"a",
"boolean",
"indicating",
"success",
"/",
"failure"
] | python | train | 31.125 |
carljm/django-adminfiles | adminfiles/flickr.py | https://github.com/carljm/django-adminfiles/blob/b01dc7be266305d575c11d5ff9a37ccac04a78c2/adminfiles/flickr.py#L236-L254 | def getSizes(self):
"""
Get all the available sizes of the current image, and all available
data about them.
Returns: A list of dicts with the size data.
"""
method = 'flickr.photos.getSizes'
data = _doget(method, photo_id=self.id)
ret = []
# The g... | [
"def",
"getSizes",
"(",
"self",
")",
":",
"method",
"=",
"'flickr.photos.getSizes'",
"data",
"=",
"_doget",
"(",
"method",
",",
"photo_id",
"=",
"self",
".",
"id",
")",
"ret",
"=",
"[",
"]",
"# The given props are those that we return and the according types, since"... | Get all the available sizes of the current image, and all available
data about them.
Returns: A list of dicts with the size data. | [
"Get",
"all",
"the",
"available",
"sizes",
"of",
"the",
"current",
"image",
"and",
"all",
"available",
"data",
"about",
"them",
".",
"Returns",
":",
"A",
"list",
"of",
"dicts",
"with",
"the",
"size",
"data",
"."
] | python | train | 41.842105 |
gpoulter/python-ngram | scripts/csvjoin.py | https://github.com/gpoulter/python-ngram/blob/f8543bdc84a4d24ac60a48b36c4034f881664491/scripts/csvjoin.py#L16-L20 | def lowstrip(term):
"""Convert to lowercase and strip spaces"""
term = re.sub('\s+', ' ', term)
term = term.lower()
return term | [
"def",
"lowstrip",
"(",
"term",
")",
":",
"term",
"=",
"re",
".",
"sub",
"(",
"'\\s+'",
",",
"' '",
",",
"term",
")",
"term",
"=",
"term",
".",
"lower",
"(",
")",
"return",
"term"
] | Convert to lowercase and strip spaces | [
"Convert",
"to",
"lowercase",
"and",
"strip",
"spaces"
] | python | train | 27.8 |
SMTG-UCL/sumo | sumo/symmetry/seekpath_kpath.py | https://github.com/SMTG-UCL/sumo/blob/47aec6bbfa033a624435a65bd4edabd18bfb437f/sumo/symmetry/seekpath_kpath.py#L48-L96 | def kpath_from_seekpath(cls, seekpath, point_coords):
r"""Convert seekpath-formatted kpoints path to sumo-preferred format.
If 'GAMMA' is used as a label this will be replaced by '\Gamma'.
Args:
seekpath (list): A :obj:`list` of 2-tuples containing the labels at
eac... | [
"def",
"kpath_from_seekpath",
"(",
"cls",
",",
"seekpath",
",",
"point_coords",
")",
":",
"# convert from seekpath format e.g. [(l1, l2), (l2, l3), (l4, l5)]",
"# to our preferred representation [[l1, l2, l3], [l4, l5]]",
"path",
"=",
"[",
"[",
"seekpath",
"[",
"0",
"]",
"[",... | r"""Convert seekpath-formatted kpoints path to sumo-preferred format.
If 'GAMMA' is used as a label this will be replaced by '\Gamma'.
Args:
seekpath (list): A :obj:`list` of 2-tuples containing the labels at
each side of each segment of the k-point path::
... | [
"r",
"Convert",
"seekpath",
"-",
"formatted",
"kpoints",
"path",
"to",
"sumo",
"-",
"preferred",
"format",
"."
] | python | train | 37.816327 |
Robpol86/colorclass | colorclass/color.py | https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/color.py#L163-L172 | def bgmagenta(cls, string, auto=False):
"""Color-code entire string.
:param str string: String to colorize.
:param bool auto: Enable auto-color (dark/light terminal).
:return: Class instance for colorized string.
:rtype: Color
"""
return cls.colorize('bgmagenta'... | [
"def",
"bgmagenta",
"(",
"cls",
",",
"string",
",",
"auto",
"=",
"False",
")",
":",
"return",
"cls",
".",
"colorize",
"(",
"'bgmagenta'",
",",
"string",
",",
"auto",
"=",
"auto",
")"
] | Color-code entire string.
:param str string: String to colorize.
:param bool auto: Enable auto-color (dark/light terminal).
:return: Class instance for colorized string.
:rtype: Color | [
"Color",
"-",
"code",
"entire",
"string",
"."
] | python | train | 33.1 |
proofit404/service-factory | service_factory/validation.py | https://github.com/proofit404/service-factory/blob/a09d4e097e5599244564a2a7f0611e58efb4156a/service_factory/validation.py#L34-L40 | def validate_params(request):
"""Validate request params."""
if 'params' in request:
correct_params = isinstance(request['params'], (list, dict))
error = 'Incorrect parameter values'
assert correct_params, error | [
"def",
"validate_params",
"(",
"request",
")",
":",
"if",
"'params'",
"in",
"request",
":",
"correct_params",
"=",
"isinstance",
"(",
"request",
"[",
"'params'",
"]",
",",
"(",
"list",
",",
"dict",
")",
")",
"error",
"=",
"'Incorrect parameter values'",
"ass... | Validate request params. | [
"Validate",
"request",
"params",
"."
] | python | test | 34 |
timothyb0912/pylogit | pylogit/bootstrap_sampler.py | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap_sampler.py#L301-L360 | def create_bootstrap_dataframe(orig_df,
obs_id_col,
resampled_obs_ids_1d,
groupby_dict,
boot_id_col="bootstrap_id"):
"""
Will create the altered dataframe of data needed to estimate a choi... | [
"def",
"create_bootstrap_dataframe",
"(",
"orig_df",
",",
"obs_id_col",
",",
"resampled_obs_ids_1d",
",",
"groupby_dict",
",",
"boot_id_col",
"=",
"\"bootstrap_id\"",
")",
":",
"# Check the validity of the passed arguments.",
"check_column_existence",
"(",
"obs_id_col",
",",
... | Will create the altered dataframe of data needed to estimate a choice model
with the particular observations that belong to the current bootstrap
sample.
Parameters
----------
orig_df : pandas DataFrame.
Should be long-format dataframe containing the data used to estimate
the desire... | [
"Will",
"create",
"the",
"altered",
"dataframe",
"of",
"data",
"needed",
"to",
"estimate",
"a",
"choice",
"model",
"with",
"the",
"particular",
"observations",
"that",
"belong",
"to",
"the",
"current",
"bootstrap",
"sample",
"."
] | python | train | 41.916667 |
CI-WATER/gsshapy | gsshapy/orm/spn.py | https://github.com/CI-WATER/gsshapy/blob/00fd4af0fd65f1614d75a52fe950a04fb0867f4c/gsshapy/orm/spn.py#L138-L179 | def _createSlink(self, slinks):
"""
Create GSSHAPY SuperLink, Pipe, and SuperNode Objects Method
"""
for slink in slinks:
# Create GSSHAPY SuperLink object
superLink = SuperLink(slinkNumber=slink['slinkNumber'],
numPipes=slink['n... | [
"def",
"_createSlink",
"(",
"self",
",",
"slinks",
")",
":",
"for",
"slink",
"in",
"slinks",
":",
"# Create GSSHAPY SuperLink object",
"superLink",
"=",
"SuperLink",
"(",
"slinkNumber",
"=",
"slink",
"[",
"'slinkNumber'",
"]",
",",
"numPipes",
"=",
"slink",
"[... | Create GSSHAPY SuperLink, Pipe, and SuperNode Objects Method | [
"Create",
"GSSHAPY",
"SuperLink",
"Pipe",
"and",
"SuperNode",
"Objects",
"Method"
] | python | train | 45.02381 |
wglass/lighthouse | lighthouse/checks/tcp.py | https://github.com/wglass/lighthouse/blob/f4ce6550895acc31e433ede0c05d366718a3ffe5/lighthouse/checks/tcp.py#L54-L94 | def perform(self):
"""
Performs a straightforward TCP request and response.
Sends the TCP `query` to the proper host and port, and loops over the
socket, gathering response chunks until a full line is acquired.
If the response line matches the expected value, the check passes. ... | [
"def",
"perform",
"(",
"self",
")",
":",
"sock",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"sock",
".",
"connect",
"(",
"(",
"self",
".",
"host",
",",
"self",
".",
"port",
")",
")",
"# if n... | Performs a straightforward TCP request and response.
Sends the TCP `query` to the proper host and port, and loops over the
socket, gathering response chunks until a full line is acquired.
If the response line matches the expected value, the check passes. If
not, the check fails. The c... | [
"Performs",
"a",
"straightforward",
"TCP",
"request",
"and",
"response",
"."
] | python | train | 31.878049 |
pavoni/pyvera | pyvera/subscribe.py | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/subscribe.py#L55-L67 | def unregister(self, device, callback):
"""Remove a registered a callback.
device: device that has the subscription
callback: callback used in original registration
"""
if not device:
logger.error("Received an invalid device: %r", device)
return
... | [
"def",
"unregister",
"(",
"self",
",",
"device",
",",
"callback",
")",
":",
"if",
"not",
"device",
":",
"logger",
".",
"error",
"(",
"\"Received an invalid device: %r\"",
",",
"device",
")",
"return",
"logger",
".",
"debug",
"(",
"\"Removing subscription for {}\... | Remove a registered a callback.
device: device that has the subscription
callback: callback used in original registration | [
"Remove",
"a",
"registered",
"a",
"callback",
"."
] | python | train | 37 |
saltstack/salt | salt/log/setup.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/log/setup.py#L562-L739 | def setup_logfile_logger(log_path, log_level='error', log_format=None,
date_format=None, max_bytes=0, backup_count=0):
'''
Setup the logfile logger
Since version 0.10.6 we support logging to syslog, some examples:
tcp://localhost:514/LOG_USER
tcp://localhost/LOG_DA... | [
"def",
"setup_logfile_logger",
"(",
"log_path",
",",
"log_level",
"=",
"'error'",
",",
"log_format",
"=",
"None",
",",
"date_format",
"=",
"None",
",",
"max_bytes",
"=",
"0",
",",
"backup_count",
"=",
"0",
")",
":",
"if",
"is_logfile_configured",
"(",
")",
... | Setup the logfile logger
Since version 0.10.6 we support logging to syslog, some examples:
tcp://localhost:514/LOG_USER
tcp://localhost/LOG_DAEMON
udp://localhost:5145/LOG_KERN
udp://localhost
file:///dev/log
file:///dev/log/LOG_SYSLOG
file:///dev/log/LOG_DA... | [
"Setup",
"the",
"logfile",
"logger"
] | python | train | 38.764045 |
vaexio/vaex | packages/vaex-core/vaex/dataframe.py | https://github.com/vaexio/vaex/blob/a45b672f8287afca2ada8e36b74b604b9b28dd85/packages/vaex-core/vaex/dataframe.py#L1855-L1877 | def col(self):
"""Gives direct access to the columns only (useful for tab completion).
Convenient when working with ipython in combination with small DataFrames, since this gives tab-completion.
Columns can be accesed by there names, which are attributes. The attribues are currently expression... | [
"def",
"col",
"(",
"self",
")",
":",
"class",
"ColumnList",
"(",
"object",
")",
":",
"pass",
"data",
"=",
"ColumnList",
"(",
")",
"for",
"name",
"in",
"self",
".",
"get_column_names",
"(",
")",
":",
"expression",
"=",
"getattr",
"(",
"self",
",",
"na... | Gives direct access to the columns only (useful for tab completion).
Convenient when working with ipython in combination with small DataFrames, since this gives tab-completion.
Columns can be accesed by there names, which are attributes. The attribues are currently expressions, so you can
do c... | [
"Gives",
"direct",
"access",
"to",
"the",
"columns",
"only",
"(",
"useful",
"for",
"tab",
"completion",
")",
"."
] | python | test | 34.565217 |
Qiskit/qiskit-terra | qiskit/pulse/pulse_lib/discrete.py | https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/pulse/pulse_lib/discrete.py#L39-L46 | def zero(duration: int, name: str = None) -> SamplePulse:
"""Generates zero-sampled `SamplePulse`.
Args:
duration: Duration of pulse. Must be greater than zero.
name: Name of pulse.
"""
return _sampled_zero_pulse(duration, name=name) | [
"def",
"zero",
"(",
"duration",
":",
"int",
",",
"name",
":",
"str",
"=",
"None",
")",
"->",
"SamplePulse",
":",
"return",
"_sampled_zero_pulse",
"(",
"duration",
",",
"name",
"=",
"name",
")"
] | Generates zero-sampled `SamplePulse`.
Args:
duration: Duration of pulse. Must be greater than zero.
name: Name of pulse. | [
"Generates",
"zero",
"-",
"sampled",
"SamplePulse",
"."
] | python | test | 32.375 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.