text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def removeKeyButtonEvent(self, buttons= [] ):
"""!
\~english
Remove key button event callbacks
@param buttons: an array of button Ids. eg. [ 12,13,15, ...]
\~chinese
移除按键事件回调
@param buttons: 按钮ID数组。 例如: [12,13,15,...]
"""
for i in range( 0, len(bu... | [
"def",
"removeKeyButtonEvent",
"(",
"self",
",",
"buttons",
"=",
"[",
"]",
")",
":",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"buttons",
")",
"-",
"1",
")",
":",
"GPIO",
".",
"remove_event_detect",
"(",
"buttons",
"[",
"i",
"]",
")"
] | 30.916667 | 14 |
def error_pre(f, *args, **kwargs):
"""Automatically log progress on function entry. Logging value: error.
*Logging with values contained in the parameters of the decorated function*
Message (args[0]) may be a string to be formatted with parameters passed to
the decorated function. Each '{varname}' will... | [
"def",
"error_pre",
"(",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"update",
"(",
"{",
"'log'",
":",
"logging",
".",
"ERROR",
"}",
")",
"kwargs",
".",
"update",
"(",
"{",
"'prefix_only'",
":",
"True",
"}",
")",
"ret... | 40.944444 | 20.555556 |
def where_node_as_ldap(where, compiler, connection):
"""Parse a django.db.models.sql.where.WhereNode.
Returns:
(clause, [params]): the filter clause, with a list of unescaped parameters.
"""
bits, params = [], []
for item in where.children:
if isinstance(item, WhereNode):
... | [
"def",
"where_node_as_ldap",
"(",
"where",
",",
"compiler",
",",
"connection",
")",
":",
"bits",
",",
"params",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"item",
"in",
"where",
".",
"children",
":",
"if",
"isinstance",
"(",
"item",
",",
"WhereNode",
")",
... | 30.272727 | 21.272727 |
def minor_extent(self) -> complex:
"""Minimum deviation from null."""
return min((self.max() - self.null, self.null - self.min())) | [
"def",
"minor_extent",
"(",
"self",
")",
"->",
"complex",
":",
"return",
"min",
"(",
"(",
"self",
".",
"max",
"(",
")",
"-",
"self",
".",
"null",
",",
"self",
".",
"null",
"-",
"self",
".",
"min",
"(",
")",
")",
")"
] | 48 | 11.333333 |
def load_tf_weights_in_openai_gpt(model, openai_checkpoint_folder_path):
""" Load tf pre-trained weights in a pytorch model (from NumPy arrays here)
"""
import re
import numpy as np
print("Loading weights...")
names = json.load(open(openai_checkpoint_folder_path + '/parameters_names.json', "r", ... | [
"def",
"load_tf_weights_in_openai_gpt",
"(",
"model",
",",
"openai_checkpoint_folder_path",
")",
":",
"import",
"re",
"import",
"numpy",
"as",
"np",
"print",
"(",
"\"Loading weights...\"",
")",
"names",
"=",
"json",
".",
"load",
"(",
"open",
"(",
"openai_checkpoin... | 41.882353 | 21.647059 |
def calcNewEdges(wcs, shape):
"""
This method will compute sky coordinates for all the pixels around
the edge of an image AFTER applying the geometry model.
Parameters
----------
wcs : obj
HSTWCS object for image
shape : tuple
numpy shape tuple for size of image
Return... | [
"def",
"calcNewEdges",
"(",
"wcs",
",",
"shape",
")",
":",
"naxis1",
"=",
"shape",
"[",
"1",
"]",
"naxis2",
"=",
"shape",
"[",
"0",
"]",
"# build up arrays for pixel positions for the edges",
"# These arrays need to be: array([(x,y),(x1,y1),...])",
"numpix",
"=",
"nax... | 27.848485 | 19.878788 |
def release(self):
"""
Release the lock if acquired.
"""
# TODO: thread safety (currently the lock may be acquired for one more TTL length)
if self.token is not None:
try:
self.client.test_and_set(self.key, 0, self.token)
except (ValueError... | [
"def",
"release",
"(",
"self",
")",
":",
"# TODO: thread safety (currently the lock may be acquired for one more TTL length)",
"if",
"self",
".",
"token",
"is",
"not",
"None",
":",
"try",
":",
"self",
".",
"client",
".",
"test_and_set",
"(",
"self",
".",
"key",
",... | 41 | 19.5 |
def arr_select(value): # function factory
'''Selecting array elements by bitwise and comparison to a given value.
Parameters:
value : int
Value to which array elements are compared to.
Returns:
array : np.array
'''
def f_eq(arr):
return np.equal(np.bitwise_and(a... | [
"def",
"arr_select",
"(",
"value",
")",
":",
"# function factory\r",
"def",
"f_eq",
"(",
"arr",
")",
":",
"return",
"np",
".",
"equal",
"(",
"np",
".",
"bitwise_and",
"(",
"arr",
",",
"value",
")",
",",
"value",
")",
"f_eq",
".",
"__name__",
"=",
"\"... | 31.642857 | 27.357143 |
def process_view(self, request, view_func, view_args, view_kwargs):
"""Run the profiler on _view_func_."""
profiler = getattr(request, 'profiler', None)
if profiler:
# Make sure profiler variables don't get passed into view_func
original_get = request.GET
requ... | [
"def",
"process_view",
"(",
"self",
",",
"request",
",",
"view_func",
",",
"view_args",
",",
"view_kwargs",
")",
":",
"profiler",
"=",
"getattr",
"(",
"request",
",",
"'profiler'",
",",
"None",
")",
"if",
"profiler",
":",
"# Make sure profiler variables don't ge... | 42.6875 | 13.4375 |
def add_interaction(self, u, v, t=None, e=None):
"""Add an interaction between u and v at time t vanishing (optional) at time e.
The nodes u and v will be automatically added if they are
not already in the graph.
Parameters
----------
u, v : nodes
Nodes can ... | [
"def",
"add_interaction",
"(",
"self",
",",
"u",
",",
"v",
",",
"t",
"=",
"None",
",",
"e",
"=",
"None",
")",
":",
"if",
"t",
"is",
"None",
":",
"raise",
"nx",
".",
"NetworkXError",
"(",
"\"The t argument must be specified.\"",
")",
"if",
"u",
"not",
... | 36.740157 | 22.708661 |
def coords_almost_equals(self, other, max_distance=1e-6, points_per_edge=8):
"""
Compare this and another LineString's coordinates.
This is an approximate method based on pointwise distances and can
in rare corner cases produce wrong outputs.
Parameters
----------
... | [
"def",
"coords_almost_equals",
"(",
"self",
",",
"other",
",",
"max_distance",
"=",
"1e-6",
",",
"points_per_edge",
"=",
"8",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"LineString",
")",
":",
"pass",
"elif",
"isinstance",
"(",
"other",
",",
"tuple",... | 36.773585 | 20.886792 |
def recentProgress(self):
"""Returns an array of the most recent [[StreamingQueryProgress]] updates for this query.
The number of progress updates retained for each stream is configured by Spark session
configuration `spark.sql.streaming.numRecentProgressUpdates`.
"""
return [jso... | [
"def",
"recentProgress",
"(",
"self",
")",
":",
"return",
"[",
"json",
".",
"loads",
"(",
"p",
".",
"json",
"(",
")",
")",
"for",
"p",
"in",
"self",
".",
"_jsq",
".",
"recentProgress",
"(",
")",
"]"
] | 61.5 | 21.833333 |
def populate(publications):
"""
Load custom links and files from database and attach to publications.
"""
customlinks = CustomLink.objects.filter(publication__in=publications)
customfiles = CustomFile.objects.filter(publication__in=publications)
publications_ = {}
for publication in publications:
publication... | [
"def",
"populate",
"(",
"publications",
")",
":",
"customlinks",
"=",
"CustomLink",
".",
"objects",
".",
"filter",
"(",
"publication__in",
"=",
"publications",
")",
"customfiles",
"=",
"CustomFile",
".",
"objects",
".",
"filter",
"(",
"publication__in",
"=",
"... | 30.555556 | 19.333333 |
def upload_path(instance, filename):
'''
Sanitize the user-provided file name, add timestamp for uniqness.
'''
filename = filename.replace(" ", "_")
filename = unicodedata.normalize('NFKD', filename).lower()
return os.path.join(str(timezone.now().date().isoformat()), filename) | [
"def",
"upload_path",
"(",
"instance",
",",
"filename",
")",
":",
"filename",
"=",
"filename",
".",
"replace",
"(",
"\" \"",
",",
"\"_\"",
")",
"filename",
"=",
"unicodedata",
".",
"normalize",
"(",
"'NFKD'",
",",
"filename",
")",
".",
"lower",
"(",
")",... | 37.375 | 24.875 |
def _characterize_header(self, header, hgroups):
"""Characterize header groups into different data types.
"""
out = []
for h in [header[g[0]] for g in hgroups]:
this_ctype = None
for ctype, names in self._col_types.items():
if h.startswith(names):
... | [
"def",
"_characterize_header",
"(",
"self",
",",
"header",
",",
"hgroups",
")",
":",
"out",
"=",
"[",
"]",
"for",
"h",
"in",
"[",
"header",
"[",
"g",
"[",
"0",
"]",
"]",
"for",
"g",
"in",
"hgroups",
"]",
":",
"this_ctype",
"=",
"None",
"for",
"ct... | 35.583333 | 9.5 |
def get_default_view_path(resource):
"Returns the dotted path to the default view class."
parts = [a.member_name for a in resource.ancestors] +\
[resource.collection_name or resource.member_name]
if resource.prefix:
parts.insert(-1, resource.prefix)
view_file = '%s' % '_'.join(par... | [
"def",
"get_default_view_path",
"(",
"resource",
")",
":",
"parts",
"=",
"[",
"a",
".",
"member_name",
"for",
"a",
"in",
"resource",
".",
"ancestors",
"]",
"+",
"[",
"resource",
".",
"collection_name",
"or",
"resource",
".",
"member_name",
"]",
"if",
"reso... | 34.642857 | 20.785714 |
def verify_integrity(self):
"""Verifies that all required functions been injected."""
if not self.__integrity_check:
if not self.__appid:
raise Exception('U2F_APPID was not defined! Please define it in configuration file.')
if self.__facets_enabled and not len(se... | [
"def",
"verify_integrity",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"__integrity_check",
":",
"if",
"not",
"self",
".",
"__appid",
":",
"raise",
"Exception",
"(",
"'U2F_APPID was not defined! Please define it in configuration file.'",
")",
"if",
"self",
".",... | 44.9375 | 30.84375 |
def db_dp996(self, value=None):
""" Corresponds to IDD Field `db_dp996`
mean coincident drybulb temperature corresponding to
Dew-point temperature corresponding to 99.6% annual cumulative
frequency of occurrence (cold conditions)
Args:
value (float): value for IDD F... | [
"def",
"db_dp996",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"try",
":",
"value",
"=",
"float",
"(",
"value",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'value {} need to be of type float... | 36.826087 | 20.086957 |
def qc_curve_group(self, tests, alias=None):
"""
Run tests on a cohort of curves.
Args:
alias (dict): an alias dictionary, mapping mnemonics to lists of
mnemonics.
Returns:
dict.
"""
keys = [k for k, v in self.data.items() if isin... | [
"def",
"qc_curve_group",
"(",
"self",
",",
"tests",
",",
"alias",
"=",
"None",
")",
":",
"keys",
"=",
"[",
"k",
"for",
"k",
",",
"v",
"in",
"self",
".",
"data",
".",
"items",
"(",
")",
"if",
"isinstance",
"(",
"v",
",",
"Curve",
")",
"]",
"if",... | 29.4 | 20.28 |
def reboot_instances(self, instance_ids=None):
"""
Reboot the specified instances.
:type instance_ids: list
:param instance_ids: The instances to terminate and reboot
"""
params = {}
if instance_ids:
self.build_list_params(params, instance_ids, 'Insta... | [
"def",
"reboot_instances",
"(",
"self",
",",
"instance_ids",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"if",
"instance_ids",
":",
"self",
".",
"build_list_params",
"(",
"params",
",",
"instance_ids",
",",
"'InstanceId'",
")",
"return",
"self",
".",
"... | 34.090909 | 15 |
def resource_path(package_name: str, relative_path: typing.Union[str, Path]) -> Path:
""" Get absolute path to resource, works for dev and for PyInstaller """
relative_path = Path(relative_path)
methods = [
_get_from_dev,
_get_from_package,
_get_from_sys,
]
for method in meth... | [
"def",
"resource_path",
"(",
"package_name",
":",
"str",
",",
"relative_path",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"Path",
"]",
")",
"->",
"Path",
":",
"relative_path",
"=",
"Path",
"(",
"relative_path",
")",
"methods",
"=",
"[",
"_get_from_dev",... | 32.571429 | 18.142857 |
def generic_export(request, model_name=None):
"""
Generic view configured through settings.TABLIB_MODELS
Usage:
1. Add the view to ``urlpatterns`` in ``urls.py``::
url(r'export/(?P<model_name>[^/]+)/$',
"django_tablib.views.generic_export"),
2. Create the ``setti... | [
"def",
"generic_export",
"(",
"request",
",",
"model_name",
"=",
"None",
")",
":",
"if",
"model_name",
"not",
"in",
"settings",
".",
"TABLIB_MODELS",
":",
"raise",
"Http404",
"(",
")",
"model",
"=",
"get_model",
"(",
"*",
"model_name",
".",
"split",
"(",
... | 32.75 | 19.516667 |
def recalculate_estimate(recalculate_total=False):
""" Recalculate price of consumables that were used by resource until now.
Regular task. It is too expensive to calculate consumed price on each
request, so we store cached price each hour.
If recalculate_total is True - task also recalcula... | [
"def",
"recalculate_estimate",
"(",
"recalculate_total",
"=",
"False",
")",
":",
"# Celery does not import server.urls and does not discover cost tracking modules.",
"# So they should be discovered implicitly.",
"CostTrackingRegister",
".",
"autodiscover",
"(",
")",
"# Step 1. Recalcul... | 54 | 19.318182 |
def _parse(self, roi=None, filenames=None):
"""
Parse catalog FITS files into recarray.
Parameters:
-----------
roi : The region of interest; if 'roi=None', read all catalog files
Returns:
--------
None
"""
if (roi is not None) an... | [
"def",
"_parse",
"(",
"self",
",",
"roi",
"=",
"None",
",",
"filenames",
"=",
"None",
")",
":",
"if",
"(",
"roi",
"is",
"not",
"None",
")",
"and",
"(",
"filenames",
"is",
"not",
"None",
")",
":",
"msg",
"=",
"\"Cannot take both roi and filenames\"",
"r... | 29.361111 | 18.972222 |
def setnx(self, name, value):
"""
Set the value as a string in the key only if the key doesn't exist.
:param name: str the name of the redis key
:param value:
:return: Future()
"""
with self.pipe as pipe:
return pipe.setnx(self.redis_key(name),
... | [
"def",
"setnx",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"with",
"self",
".",
"pipe",
"as",
"pipe",
":",
"return",
"pipe",
".",
"setnx",
"(",
"self",
".",
"redis_key",
"(",
"name",
")",
",",
"self",
".",
"valueparse",
".",
"encode",
"(",
... | 33.454545 | 15.818182 |
def l2_norm(x, filters=None, epsilon=1e-6, name=None, reuse=None):
"""Layer normalization with l2 norm."""
if filters is None:
filters = shape_list(x)[-1]
with tf.variable_scope(name, default_name="l2_norm", values=[x], reuse=reuse):
scale = tf.get_variable(
"l2_norm_scale", [filters], initializer... | [
"def",
"l2_norm",
"(",
"x",
",",
"filters",
"=",
"None",
",",
"epsilon",
"=",
"1e-6",
",",
"name",
"=",
"None",
",",
"reuse",
"=",
"None",
")",
":",
"if",
"filters",
"is",
"None",
":",
"filters",
"=",
"shape_list",
"(",
"x",
")",
"[",
"-",
"1",
... | 49.333333 | 19.133333 |
def fill_with_circles_path(size, radius=100):
"""
Covers an image with a set of overlapping circles of the given radius.
:param size: The size of the image
:param radius: The radius of the circles in question
:return: Yields a set of filled circles that cover the whole image.
Each circle is made... | [
"def",
"fill_with_circles_path",
"(",
"size",
",",
"radius",
"=",
"100",
")",
":",
"width",
",",
"height",
"=",
"size",
"radius",
"=",
"int",
"(",
"radius",
")",
"dx",
"=",
"dy",
"=",
"int",
"(",
"2",
"*",
"radius",
"/",
"sqrt",
"(",
"2",
")",
")... | 44.642857 | 14.357143 |
def _get_authorization_headers(self, context):
"""Gets the authorization headers for a request.
Returns:
Sequence[Tuple[str, str]]: A list of request headers (key, value)
to add to the request.
"""
headers = {}
self._credentials.before_request(
... | [
"def",
"_get_authorization_headers",
"(",
"self",
",",
"context",
")",
":",
"headers",
"=",
"{",
"}",
"self",
".",
"_credentials",
".",
"before_request",
"(",
"self",
".",
"_request",
",",
"context",
".",
"method_name",
",",
"context",
".",
"service_url",
",... | 30.533333 | 14.866667 |
def command(self, cmd, retries=None, timeout_cmd=None):
"""
Args:
cmd - command to execute via http
timeout_cmd - timeout, default 3sec
retries - maximum number of retries each connection should attempt
"""
retries = retries or self._retries_default
... | [
"def",
"command",
"(",
"self",
",",
"cmd",
",",
"retries",
"=",
"None",
",",
"timeout_cmd",
"=",
"None",
")",
":",
"retries",
"=",
"retries",
"or",
"self",
".",
"_retries_default",
"timeout",
"=",
"timeout_cmd",
"or",
"self",
".",
"_timeout_default",
"sess... | 37.757576 | 16.060606 |
def set_threshold(self, fpr=None, threshold=None):
"""Set motif scanning threshold based on background sequences.
Parameters
----------
fpr : float, optional
Desired FPR, between 0.0 and 1.0.
threshold : float or str, optional
Desired motif threshold, ex... | [
"def",
"set_threshold",
"(",
"self",
",",
"fpr",
"=",
"None",
",",
"threshold",
"=",
"None",
")",
":",
"if",
"threshold",
"and",
"fpr",
":",
"raise",
"ValueError",
"(",
"\"Need either fpr or threshold.\"",
")",
"if",
"fpr",
":",
"fpr",
"=",
"float",
"(",
... | 39.271429 | 19.914286 |
def delete_message(chat_id, message_id, **kwargs):
"""
Use this method to delete a message, including service messages, with the following limitations:
- A message can only be deleted if it was sent less than 48 hours ago.
- Bots can delete outgoing messages in groups and supergroups.
- Bots granted... | [
"def",
"delete_message",
"(",
"chat_id",
",",
"message_id",
",",
"*",
"*",
"kwargs",
")",
":",
"# required args",
"params",
"=",
"dict",
"(",
"chat_id",
"=",
"chat_id",
",",
"message_id",
"=",
"message_id",
")",
"return",
"TelegramBotRPCRequest",
"(",
"'delete... | 47.304348 | 33.478261 |
def _write_container_output(output_itr, stdout=None, stderr=None):
"""
Based on the data returned from the Container output, via the iterator, write it to the appropriate streams
Parameters
----------
output_itr: Iterator
Iterator returned by the Docker Attach comman... | [
"def",
"_write_container_output",
"(",
"output_itr",
",",
"stdout",
"=",
"None",
",",
"stderr",
"=",
"None",
")",
":",
"# Iterator returns a tuple of (frame_type, data) where the frame type determines which stream we write output",
"# to",
"for",
"frame_type",
",",
"data",
"i... | 45.133333 | 28.333333 |
def list_qos_policies(self, retrieve_all=True, **_params):
"""Fetches a list of all qos policies for a project."""
# Pass filters in "params" argument to do_request
return self.list('policies', self.qos_policies_path,
retrieve_all, **_params) | [
"def",
"list_qos_policies",
"(",
"self",
",",
"retrieve_all",
"=",
"True",
",",
"*",
"*",
"_params",
")",
":",
"# Pass filters in \"params\" argument to do_request",
"return",
"self",
".",
"list",
"(",
"'policies'",
",",
"self",
".",
"qos_policies_path",
",",
"ret... | 57.4 | 12.8 |
async def _send_loop(self):
"""
This loop is responsible for popping items off the send
queue, encrypting them, and sending them over the network.
Besides `connect`, only this method ever sends data.
"""
while self._user_connected and not self._reconnecting:
... | [
"async",
"def",
"_send_loop",
"(",
"self",
")",
":",
"while",
"self",
".",
"_user_connected",
"and",
"not",
"self",
".",
"_reconnecting",
":",
"if",
"self",
".",
"_pending_ack",
":",
"ack",
"=",
"RequestState",
"(",
"MsgsAck",
"(",
"list",
"(",
"self",
"... | 40.068182 | 20.25 |
def _realGetLoader(n, default=_marker):
"""
Search all themes for a template named C{n}, returning a loader
for it if found. If not found and a default is passed, the default
will be returned. Otherwise C{RuntimeError} will be raised.
This function is deprecated in favor of using a L{ThemedElement}... | [
"def",
"_realGetLoader",
"(",
"n",
",",
"default",
"=",
"_marker",
")",
":",
"for",
"t",
"in",
"getAllThemes",
"(",
")",
":",
"fact",
"=",
"t",
".",
"getDocFactory",
"(",
"n",
",",
"None",
")",
"if",
"fact",
"is",
"not",
"None",
":",
"return",
"fac... | 37.058824 | 15.647059 |
def MapParamNames(params, request_type):
"""Reverse parameter remappings for URL construction."""
return [encoding.GetCustomJsonFieldMapping(request_type, json_name=p) or p
for p in params] | [
"def",
"MapParamNames",
"(",
"params",
",",
"request_type",
")",
":",
"return",
"[",
"encoding",
".",
"GetCustomJsonFieldMapping",
"(",
"request_type",
",",
"json_name",
"=",
"p",
")",
"or",
"p",
"for",
"p",
"in",
"params",
"]"
] | 51.5 | 12.5 |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'classifiers') and self.classifiers is not None:
_dict['classifiers'] = [x._to_dict() for x in self.classifiers]
return _dict | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'classifiers'",
")",
"and",
"self",
".",
"classifiers",
"is",
"not",
"None",
":",
"_dict",
"[",
"'classifiers'",
"]",
"=",
"[",
"x",
".",
"_to_dict"... | 44.666667 | 21.833333 |
def prices(self):
"""
TimeSeries of prices.
"""
# if accessing and stale - update first
if self._needupdate or self.now != self.parent.now:
self.update(self.root.now)
return self._prices.loc[:self.now] | [
"def",
"prices",
"(",
"self",
")",
":",
"# if accessing and stale - update first",
"if",
"self",
".",
"_needupdate",
"or",
"self",
".",
"now",
"!=",
"self",
".",
"parent",
".",
"now",
":",
"self",
".",
"update",
"(",
"self",
".",
"root",
".",
"now",
")",... | 31.75 | 8 |
def color_by_height(self, axis=1, threshold=None, color=DEFAULT_COLORMAP): # pylint: disable=unused-argument
'''
Color each vertex by its height above the floor point.
axis: The axis to use. 0 means x, 1 means y, 2 means z.
threshold: The top of the range. Points at and above this heigh... | [
"def",
"color_by_height",
"(",
"self",
",",
"axis",
"=",
"1",
",",
"threshold",
"=",
"None",
",",
"color",
"=",
"DEFAULT_COLORMAP",
")",
":",
"# pylint: disable=unused-argument",
"import",
"numpy",
"as",
"np",
"heights",
"=",
"self",
".",
"v",
"[",
":",
",... | 40 | 27.619048 |
def format_mtime(mtime):
"""
Format the date associated with a file to be displayed in directory listing.
"""
now = datetime.now()
dt = datetime.fromtimestamp(mtime)
return '%s %2d %5s' % (
dt.strftime('%b'), dt.day,
dt.year if dt.year != now.year else dt.strftime('%H:%M')) | [
"def",
"format_mtime",
"(",
"mtime",
")",
":",
"now",
"=",
"datetime",
".",
"now",
"(",
")",
"dt",
"=",
"datetime",
".",
"fromtimestamp",
"(",
"mtime",
")",
"return",
"'%s %2d %5s'",
"%",
"(",
"dt",
".",
"strftime",
"(",
"'%b'",
")",
",",
"dt",
".",
... | 32.222222 | 13.555556 |
def _format_value_element(lines, element, spacer=""):
"""Formats a member or parameter for full documentation output."""
lines.append(spacer + element.definition())
_format_summary(lines, element)
_format_generic(lines, element, ["summary"]) | [
"def",
"_format_value_element",
"(",
"lines",
",",
"element",
",",
"spacer",
"=",
"\"\"",
")",
":",
"lines",
".",
"append",
"(",
"spacer",
"+",
"element",
".",
"definition",
"(",
")",
")",
"_format_summary",
"(",
"lines",
",",
"element",
")",
"_format_gene... | 50.6 | 6.6 |
def extract_paths_dead(self, paths, *args, **kwargs):
"""
Thin method that just uses the provider
"""
return self.provider.extract_paths_dead(paths, *args, **kwargs) | [
"def",
"extract_paths_dead",
"(",
"self",
",",
"paths",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"provider",
".",
"extract_paths_dead",
"(",
"paths",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 38.6 | 10.2 |
def iterfields(klass):
"""Iterate over the input class members and yield its TypedFields.
Args:
klass: A class (usually an Entity subclass).
Yields:
(class attribute name, TypedField instance) tuples.
"""
is_field = lambda x: isinstance(x, TypedField)
for name, field in inspec... | [
"def",
"iterfields",
"(",
"klass",
")",
":",
"is_field",
"=",
"lambda",
"x",
":",
"isinstance",
"(",
"x",
",",
"TypedField",
")",
"for",
"name",
",",
"field",
"in",
"inspect",
".",
"getmembers",
"(",
"klass",
",",
"predicate",
"=",
"is_field",
")",
":"... | 28.769231 | 21.769231 |
def get(name, import_str=False):
"""
Helper function to use inside the package.
"""
value = None
default_value = getattr(default_settings, name)
try:
value = getattr(settings, name)
except AttributeError:
if name in default_settings.required_attrs:
raise Exceptio... | [
"def",
"get",
"(",
"name",
",",
"import_str",
"=",
"False",
")",
":",
"value",
"=",
"None",
"default_value",
"=",
"getattr",
"(",
"default_settings",
",",
"name",
")",
"try",
":",
"value",
"=",
"getattr",
"(",
"settings",
",",
"name",
")",
"except",
"A... | 28 | 17.545455 |
def snapshot_get(repository, snapshot, ignore_unavailable=False, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Obtain snapshot residing in specified repository.
repository
Repository name
snapshot
Snapshot name, use _all to obtain all snapshots in specified repository
... | [
"def",
"snapshot_get",
"(",
"repository",
",",
"snapshot",
",",
"ignore_unavailable",
"=",
"False",
",",
"hosts",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"es",
"=",
"_get_instance",
"(",
"hosts",
",",
"profile",
")",
"try",
":",
"return",
"es... | 37.086957 | 34.130435 |
def cleanShutdown(self, quickMode=False, stopReactor=True, _reactor=reactor):
"""Shut down the entire process, once all currently-running builds are
complete.
quickMode will mark all builds as retry (except the ones that were triggered)
"""
if self.shuttingDown:
retur... | [
"def",
"cleanShutdown",
"(",
"self",
",",
"quickMode",
"=",
"False",
",",
"stopReactor",
"=",
"True",
",",
"_reactor",
"=",
"reactor",
")",
":",
"if",
"self",
".",
"shuttingDown",
":",
"return",
"log",
".",
"msg",
"(",
"\"Initiating clean shutdown\"",
")",
... | 46.414286 | 19.057143 |
def create(client, _type, **kwargs):
"""Create a suds object of the requested _type."""
obj = client.factory.create("ns0:%s" % _type)
for key, value in kwargs.items():
setattr(obj, key, value)
return obj | [
"def",
"create",
"(",
"client",
",",
"_type",
",",
"*",
"*",
"kwargs",
")",
":",
"obj",
"=",
"client",
".",
"factory",
".",
"create",
"(",
"\"ns0:%s\"",
"%",
"_type",
")",
"for",
"key",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"... | 37 | 8.333333 |
def plot(self, xmin, xmax, idx_input=0, idx_output=0, points=100,
**kwargs) -> None:
"""Plot the relationship between a certain input (`idx_input`) and a
certain output (`idx_output`) variable described by the actual
|anntools.ANN| object.
Define the lower and the upper bou... | [
"def",
"plot",
"(",
"self",
",",
"xmin",
",",
"xmax",
",",
"idx_input",
"=",
"0",
",",
"idx_output",
"=",
"0",
",",
"points",
"=",
"100",
",",
"*",
"*",
"kwargs",
")",
"->",
"None",
":",
"xs_",
"=",
"numpy",
".",
"linspace",
"(",
"xmin",
",",
"... | 46.222222 | 13.166667 |
def _clean(self):
"""
Method for cleaning according to object cleanup policy value
:return: None
"""
if K8sCleanupPolicy.NAMESPACES in self.cleanup:
self.cleanup_namespaces()
elif K8sCleanupPolicy.EVERYTHING in self.cleanup:
self.cleanup_pods()
... | [
"def",
"_clean",
"(",
"self",
")",
":",
"if",
"K8sCleanupPolicy",
".",
"NAMESPACES",
"in",
"self",
".",
"cleanup",
":",
"self",
".",
"cleanup_namespaces",
"(",
")",
"elif",
"K8sCleanupPolicy",
".",
"EVERYTHING",
"in",
"self",
".",
"cleanup",
":",
"self",
"... | 37.777778 | 11.444444 |
def join_channel(self, partner_address, partner_deposit):
"""Will be called, when we were selected as channel partner by another
node. It will fund the channel with up to the partners deposit, but
not more than remaining funds or the initial funding per channel.
If the connection manage... | [
"def",
"join_channel",
"(",
"self",
",",
"partner_address",
",",
"partner_deposit",
")",
":",
"# Consider this race condition:",
"#",
"# - Partner opens the channel and starts the deposit.",
"# - This nodes learns about the new channel, starts ConnectionManager's",
"# retry_connect, wh... | 38.810127 | 19.987342 |
def add_override(self, addr, key, value):
"""Register an attribute override for a device."""
address = Address(str(addr)).id
_LOGGER.debug('New override for %s %s is %s', address, key, value)
device_override = self._overrides.get(address, {})
device_override[key] = value
... | [
"def",
"add_override",
"(",
"self",
",",
"addr",
",",
"key",
",",
"value",
")",
":",
"address",
"=",
"Address",
"(",
"str",
"(",
"addr",
")",
")",
".",
"id",
"_LOGGER",
".",
"debug",
"(",
"'New override for %s %s is %s'",
",",
"address",
",",
"key",
",... | 50.857143 | 9.714286 |
def get_defined_srms(srm_file):
"""
Returns list of SRMS defined in the SRM database
"""
srms = read_table(srm_file)
return np.asanyarray(srms.index.unique()) | [
"def",
"get_defined_srms",
"(",
"srm_file",
")",
":",
"srms",
"=",
"read_table",
"(",
"srm_file",
")",
"return",
"np",
".",
"asanyarray",
"(",
"srms",
".",
"index",
".",
"unique",
"(",
")",
")"
] | 28.833333 | 5.833333 |
def update_calendar_event(self, id, calendar_event_child_event_data_X_context_code=None, calendar_event_child_event_data_X_end_at=None, calendar_event_child_event_data_X_start_at=None, calendar_event_context_code=None, calendar_event_description=None, calendar_event_end_at=None, calendar_event_location_address=None, ca... | [
"def",
"update_calendar_event",
"(",
"self",
",",
"id",
",",
"calendar_event_child_event_data_X_context_code",
"=",
"None",
",",
"calendar_event_child_event_data_X_end_at",
"=",
"None",
",",
"calendar_event_child_event_data_X_start_at",
"=",
"None",
",",
"calendar_event_context... | 54.710526 | 28.434211 |
def _not32(ins):
""" Negates top (Logical NOT) of the stack (32 bits in DEHL)
"""
output = _32bit_oper(ins.quad[2])
output.append('call __NOT32')
output.append('push af')
REQUIRES.add('not32.asm')
return output | [
"def",
"_not32",
"(",
"ins",
")",
":",
"output",
"=",
"_32bit_oper",
"(",
"ins",
".",
"quad",
"[",
"2",
"]",
")",
"output",
".",
"append",
"(",
"'call __NOT32'",
")",
"output",
".",
"append",
"(",
"'push af'",
")",
"REQUIRES",
".",
"add",
"(",
"'not3... | 28.875 | 10 |
def associate_public_ip(self, instance_id, public_ip_id, private_ip=None):
"""Associate a external IP"""
floating_ip = self.client.floating_ips.get(public_ip_id)
floating_ip = floating_ip.to_dict()
address = floating_ip.get('ip')
self.client.servers.add_floating_ip(instance_id, ... | [
"def",
"associate_public_ip",
"(",
"self",
",",
"instance_id",
",",
"public_ip_id",
",",
"private_ip",
"=",
"None",
")",
":",
"floating_ip",
"=",
"self",
".",
"client",
".",
"floating_ips",
".",
"get",
"(",
"public_ip_id",
")",
"floating_ip",
"=",
"floating_ip... | 39.222222 | 22.222222 |
def count(self):
"Return how many nodes this contains, including self."
if self._nodes is None:
return 1
return sum(i.count() for i in self._nodes) | [
"def",
"count",
"(",
"self",
")",
":",
"if",
"self",
".",
"_nodes",
"is",
"None",
":",
"return",
"1",
"return",
"sum",
"(",
"i",
".",
"count",
"(",
")",
"for",
"i",
"in",
"self",
".",
"_nodes",
")"
] | 35.8 | 17 |
def _bounds_to_array(bounds):
"""Create a CompositeArray to hold the bounds."""
elements = []
for value in bounds:
if all_elements_equal(value):
elements.append(Scalar(get_single_value(value), ctype='mot_float_type'))
else:
elements.append(Array(value, ctype='mot_floa... | [
"def",
"_bounds_to_array",
"(",
"bounds",
")",
":",
"elements",
"=",
"[",
"]",
"for",
"value",
"in",
"bounds",
":",
"if",
"all_elements_equal",
"(",
"value",
")",
":",
"elements",
".",
"append",
"(",
"Scalar",
"(",
"get_single_value",
"(",
"value",
")",
... | 46 | 22.333333 |
def create_shortlink(self, callback_uri=None,
description=None, serial_number=None):
"""Register new shortlink
Arguments:
callback_uri:
URI called by mCASH when user scans shortlink
description:
Shortlink description displ... | [
"def",
"create_shortlink",
"(",
"self",
",",
"callback_uri",
"=",
"None",
",",
"description",
"=",
"None",
",",
"serial_number",
"=",
"None",
")",
":",
"arguments",
"=",
"{",
"'callback_uri'",
":",
"callback_uri",
",",
"'description'",
":",
"description",
",",... | 43.777778 | 17.666667 |
def set_mode(self, gpio, mode):
"""
Sets the gpio mode.
gpio:= 0-53.
mode:= INPUT, OUTPUT, ALT0, ALT1, ALT2, ALT3, ALT4, ALT5.
...
pi.set_mode( 4, apigpio.INPUT) # gpio 4 as input
pi.set_mode(17, apigpio.OUTPUT) # gpio 17 as output
pi.set_mode(24, apig... | [
"def",
"set_mode",
"(",
"self",
",",
"gpio",
",",
"mode",
")",
":",
"res",
"=",
"yield",
"from",
"self",
".",
"_pigpio_aio_command",
"(",
"_PI_CMD_MODES",
",",
"gpio",
",",
"mode",
")",
"return",
"_u2i",
"(",
"res",
")"
] | 30.733333 | 20.733333 |
def get_stp_brief_info_input_request_type_getnext_request_last_rcvd_instance_instance_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
input = ET.SubElement(get_s... | [
"def",
"get_stp_brief_info_input_request_type_getnext_request_last_rcvd_instance_instance_id",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_stp_brief_info",
"=",
"ET",
".",
"Element",
"(",
"\"get_stp... | 50.6 | 20.8 |
def ecg_hrv_assessment(hrv, age=None, sex=None, position=None):
"""
Correct HRV features based on normative data from Voss et al. (2015).
Parameters
----------
hrv : dict
HRV features obtained by :function:`neurokit.ecg_hrv`.
age : float
Subject's age.
sex : str
Subj... | [
"def",
"ecg_hrv_assessment",
"(",
"hrv",
",",
"age",
"=",
"None",
",",
"sex",
"=",
"None",
",",
"position",
"=",
"None",
")",
":",
"hrv_adjusted",
"=",
"{",
"}",
"if",
"position",
"==",
"\"supine\"",
":",
"if",
"sex",
"==",
"\"m\"",
":",
"if",
"age",... | 43.345679 | 35.790123 |
def parse_tags(content, reference_id=None, canonicalize=True):
"""\
Returns the TAGS of a cable.
Acc. to the U.S. SD every cable needs at least one tag.
`content`
The content of the cable.
`reference_id`
The reference identifier of the cable.
`canonicalize`
Indicate... | [
"def",
"parse_tags",
"(",
"content",
",",
"reference_id",
"=",
"None",
",",
"canonicalize",
"=",
"True",
")",
":",
"max_idx",
"=",
"_MAX_HEADER_IDX",
"m",
"=",
"_SUBJECT_MAX_PATTERN",
".",
"search",
"(",
"content",
")",
"if",
"m",
":",
"max_idx",
"=",
"m",... | 39.98 | 21.16 |
def _GetSerializedAttributeContainerList(self, container_type):
"""Retrieves a serialized attribute container list.
Args:
container_type (str): attribute container type.
Returns:
SerializedAttributeContainerList: serialized attribute container list.
"""
container_list = self._serialize... | [
"def",
"_GetSerializedAttributeContainerList",
"(",
"self",
",",
"container_type",
")",
":",
"container_list",
"=",
"self",
".",
"_serialized_attribute_containers",
".",
"get",
"(",
"container_type",
",",
"None",
")",
"if",
"not",
"container_list",
":",
"container_lis... | 34.4375 | 22.9375 |
def project_onto_plane(strike, dip, plunge, bearing):
"""
Projects a linear feature(s) onto the surface of a plane. Returns a rake
angle(s) along the plane.
This is also useful for finding the rake angle of a feature that already
intersects the plane in question.
Parameters
----------
... | [
"def",
"project_onto_plane",
"(",
"strike",
",",
"dip",
",",
"plunge",
",",
"bearing",
")",
":",
"# Project the line onto the plane",
"norm",
"=",
"sph2cart",
"(",
"*",
"pole",
"(",
"strike",
",",
"dip",
")",
")",
"feature",
"=",
"sph2cart",
"(",
"*",
"lin... | 39.044444 | 19.977778 |
def paginator(context, page, leading=8, out=3, adjacent=3, sep='...'):
"""
Render paginator.
<<_1_2 3 4 5 6 7 8 9 ... 55 56 57 >> # leading=9 (1..9) out=3 (55..57)
<< 1 2 3 ... 23 24 25 26_27_28 29 30 31 ... 55 56 57 >> # adjacent = 4 (23..26, 28..31)
"""
leading_pages, out_left_pages, out_ri... | [
"def",
"paginator",
"(",
"context",
",",
"page",
",",
"leading",
"=",
"8",
",",
"out",
"=",
"3",
",",
"adjacent",
"=",
"3",
",",
"sep",
"=",
"'...'",
")",
":",
"leading_pages",
",",
"out_left_pages",
",",
"out_right_pages",
",",
"pages",
"=",
"[",
"]... | 45.351351 | 22.324324 |
def is_same_api(self, other):
"""Check if this implements the same API as another _ApiInfo instance."""
if not isinstance(other, _ApiInfo):
return False
# pylint: disable=protected-access
return self.__common_info is other.__common_info | [
"def",
"is_same_api",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"isinstance",
"(",
"other",
",",
"_ApiInfo",
")",
":",
"return",
"False",
"# pylint: disable=protected-access",
"return",
"self",
".",
"__common_info",
"is",
"other",
".",
"__common_info"
] | 42.166667 | 8 |
def user(self, **params):
"""Stream user
Accepted params found at:
https://dev.twitter.com/docs/api/1.1/get/user
"""
url = 'https://userstream.twitter.com/%s/user.json' \
% self.streamer.api_version
self.streamer._request(url, params=params) | [
"def",
"user",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"url",
"=",
"'https://userstream.twitter.com/%s/user.json'",
"%",
"self",
".",
"streamer",
".",
"api_version",
"self",
".",
"streamer",
".",
"_request",
"(",
"url",
",",
"params",
"=",
"params",
... | 32.888889 | 11.888889 |
def crude_stretch(self, ch_nb, min_stretch=None, max_stretch=None):
"""Perform simple linear stretching (without any cutoff) on the channel
*ch_nb* of the current image and normalize to the [0,1] range."""
if min_stretch is None:
min_stretch = self.channels[ch_nb].min()
if m... | [
"def",
"crude_stretch",
"(",
"self",
",",
"ch_nb",
",",
"min_stretch",
"=",
"None",
",",
"max_stretch",
"=",
"None",
")",
":",
"if",
"min_stretch",
"is",
"None",
":",
"min_stretch",
"=",
"self",
".",
"channels",
"[",
"ch_nb",
"]",
".",
"min",
"(",
")",... | 45.208333 | 16.291667 |
def on_service_modify(self, svc_ref, old_properties):
"""
Called when a service has been modified in the framework
:param svc_ref: A service reference
:param old_properties: Previous properties values
:return: A tuple (added, (service, reference)) if the dependency has
... | [
"def",
"on_service_modify",
"(",
"self",
",",
"svc_ref",
",",
"old_properties",
")",
":",
"with",
"self",
".",
"_lock",
":",
"try",
":",
"# Look for the service",
"service",
"=",
"self",
".",
"services",
"[",
"svc_ref",
"]",
"except",
"KeyError",
":",
"# A p... | 36.73913 | 16.391304 |
def preloop(self):
''' Keep persistent command history. '''
if not self.already_prelooped:
self.already_prelooped = True
open('.psiturk_history', 'a').close() # create file if it doesn't exist
readline.read_history_file('.psiturk_history')
for i in range(... | [
"def",
"preloop",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"already_prelooped",
":",
"self",
".",
"already_prelooped",
"=",
"True",
"open",
"(",
"'.psiturk_history'",
",",
"'a'",
")",
".",
"close",
"(",
")",
"# create file if it doesn't exist",
"readli... | 53.555556 | 18.888889 |
def go_enrichment(df, enrichment='function', organism='Homo sapiens', summary=True, fdr=0.05, ids_from=['Proteins','Protein IDs']):
"""
Calculate gene ontology (GO) enrichment for a specified set of indices, using the PantherDB GO enrichment service.
Provided with a processed data ``DataFrame`` will calcul... | [
"def",
"go_enrichment",
"(",
"df",
",",
"enrichment",
"=",
"'function'",
",",
"organism",
"=",
"'Homo sapiens'",
",",
"summary",
"=",
"True",
",",
"fdr",
"=",
"0.05",
",",
"ids_from",
"=",
"[",
"'Proteins'",
",",
"'Protein IDs'",
"]",
")",
":",
"if",
"is... | 48.530612 | 35.183673 |
def exist_partitions(self, prefix_spec=None):
"""
Check if partitions with provided conditions exist.
:param prefix_spec: prefix of partition
:return: whether partitions exist
"""
try:
next(self.partitions.iterate_partitions(spec=prefix_spec))
except ... | [
"def",
"exist_partitions",
"(",
"self",
",",
"prefix_spec",
"=",
"None",
")",
":",
"try",
":",
"next",
"(",
"self",
".",
"partitions",
".",
"iterate_partitions",
"(",
"spec",
"=",
"prefix_spec",
")",
")",
"except",
"StopIteration",
":",
"return",
"False",
... | 30.666667 | 14.833333 |
def eth_estimateGas(self, from_, to=None, gas=None,
gas_price=None, value=None, data=None):
"""https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_estimategas
:param from_: From account address
:type from_: str
:param to: To account address (optional)
:ty... | [
"def",
"eth_estimateGas",
"(",
"self",
",",
"from_",
",",
"to",
"=",
"None",
",",
"gas",
"=",
"None",
",",
"gas_price",
"=",
"None",
",",
"value",
"=",
"None",
",",
"data",
"=",
"None",
")",
":",
"obj",
"=",
"{",
"}",
"obj",
"[",
"'from'",
"]",
... | 30.230769 | 19.717949 |
def set_stop_chars_left(self, stop_chars):
"""
Set stop characters for text on left from TLD.
Stop characters are used when determining end of URL.
:param set stop_chars: set of characters
:raises: TypeError
"""
if not isinstance(stop_chars, set):
rai... | [
"def",
"set_stop_chars_left",
"(",
"self",
",",
"stop_chars",
")",
":",
"if",
"not",
"isinstance",
"(",
"stop_chars",
",",
"set",
")",
":",
"raise",
"TypeError",
"(",
"\"stop_chars should be type set \"",
"\"but {} was given\"",
".",
"format",
"(",
"type",
"(",
... | 38.785714 | 16.357143 |
def parse_url(self):
"""Parse a git/ssh/http(s) url."""
url = urlparse(self.url).path
# handle git
url = url.split('.git')[0]
if ':' in url:
url = url.split(':')[1]
# Ony capture last two list items
try:
project, repo = url.split('/')[-2... | [
"def",
"parse_url",
"(",
"self",
")",
":",
"url",
"=",
"urlparse",
"(",
"self",
".",
"url",
")",
".",
"path",
"# handle git",
"url",
"=",
"url",
".",
"split",
"(",
"'.git'",
")",
"[",
"0",
"]",
"if",
"':'",
"in",
"url",
":",
"url",
"=",
"url",
... | 26.411765 | 19.941176 |
def refresh_access_token(self,):
"""Refresh access token
"""
logger.debug("REFRESHING TOKEN")
self.token_time = time.time()
credentials = {
'token_time': self.token_time
}
if self.oauth_version == 'oauth1':
self.access_token, self.access_t... | [
"def",
"refresh_access_token",
"(",
"self",
",",
")",
":",
"logger",
".",
"debug",
"(",
"\"REFRESHING TOKEN\"",
")",
"self",
".",
"token_time",
"=",
"time",
".",
"time",
"(",
")",
"credentials",
"=",
"{",
"'token_time'",
":",
"self",
".",
"token_time",
"}"... | 44.25 | 27 |
def query(self,
query,
params=None,
bind_params=None,
epoch=None,
expected_response_code=200,
database=None,
raise_errors=True,
chunked=False,
chunk_size=0,
method="GET"):
... | [
"def",
"query",
"(",
"self",
",",
"query",
",",
"params",
"=",
"None",
",",
"bind_params",
"=",
"None",
",",
"epoch",
"=",
"None",
",",
"expected_response_code",
"=",
"200",
",",
"database",
"=",
"None",
",",
"raise_errors",
"=",
"True",
",",
"chunked",
... | 32.037037 | 21.75 |
def safe_chmod(path, mode):
"""Set the permissions mode on path, but only if it differs from the current mode.
"""
if stat.S_IMODE(os.stat(path).st_mode) != mode:
os.chmod(path, mode) | [
"def",
"safe_chmod",
"(",
"path",
",",
"mode",
")",
":",
"if",
"stat",
".",
"S_IMODE",
"(",
"os",
".",
"stat",
"(",
"path",
")",
".",
"st_mode",
")",
"!=",
"mode",
":",
"os",
".",
"chmod",
"(",
"path",
",",
"mode",
")"
] | 39.8 | 7.2 |
def over(expr, window):
"""
Turn an aggregation or full-sample analytic operation into a windowed
operation. See ibis.window for more details on window configuration
Parameters
----------
expr : value expression
window : ibis.Window
Returns
-------
expr : type of input
"""
... | [
"def",
"over",
"(",
"expr",
",",
"window",
")",
":",
"prior_op",
"=",
"expr",
".",
"op",
"(",
")",
"if",
"isinstance",
"(",
"prior_op",
",",
"ops",
".",
"WindowOp",
")",
":",
"op",
"=",
"prior_op",
".",
"over",
"(",
"window",
")",
"else",
":",
"o... | 20 | 22.129032 |
def exit():
"""
shuts down user interface without cleaning up.
Use a :class:`alot.commands.globals.ExitCommand` for a clean shutdown.
"""
exit_msg = None
try:
loop = asyncio.get_event_loop()
loop.stop()
except Exception as e:
lo... | [
"def",
"exit",
"(",
")",
":",
"exit_msg",
"=",
"None",
"try",
":",
"loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
"loop",
".",
"stop",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"logging",
".",
"error",
"(",
"'Could not stop loop: %s\\nSh... | 33.75 | 16.583333 |
def format_currency(number, currency, format, locale=babel.numbers.LC_NUMERIC,
force_frac=None, format_type='standard'):
"""Same as ``babel.numbers.format_currency``, but has ``force_frac``
argument instead of ``currency_digits``.
If the ``force_frac`` argument is given, the argument is... | [
"def",
"format_currency",
"(",
"number",
",",
"currency",
",",
"format",
",",
"locale",
"=",
"babel",
".",
"numbers",
".",
"LC_NUMERIC",
",",
"force_frac",
"=",
"None",
",",
"format_type",
"=",
"'standard'",
")",
":",
"locale",
"=",
"babel",
".",
"core",
... | 39.111111 | 19.296296 |
def indexbox(msg="Shall I continue?", title=" ",
choices=("Yes", "No"), image=None,
default_choice='Yes', cancel_choice='No'):
"""
Display a buttonbox with the specified choices.
:param str msg: the msg to be displayed
:param str title: the window title
:param list choices... | [
"def",
"indexbox",
"(",
"msg",
"=",
"\"Shall I continue?\"",
",",
"title",
"=",
"\" \"",
",",
"choices",
"=",
"(",
"\"Yes\"",
",",
"\"No\"",
")",
",",
"image",
"=",
"None",
",",
"default_choice",
"=",
"'Yes'",
",",
"cancel_choice",
"=",
"'No'",
")",
":",... | 39.741935 | 12.580645 |
def as_dict(self, verbosity=0):
"""
Json-serializable dict representation of PeriodicSite.
Args:
verbosity (int): Verbosity level. Default of 0 only includes the
matrix representation. Set to 1 for more details such as
cartesian coordinates, etc.
... | [
"def",
"as_dict",
"(",
"self",
",",
"verbosity",
"=",
"0",
")",
":",
"species_list",
"=",
"[",
"]",
"for",
"spec",
",",
"occu",
"in",
"self",
".",
"_species",
".",
"items",
"(",
")",
":",
"d",
"=",
"spec",
".",
"as_dict",
"(",
")",
"del",
"d",
... | 33.724138 | 16.827586 |
def join_(self, channel, key=None, process_only=False):
"""
Joins a channel.
Returns a tuple of information regarding the channel.
Channel Information:
* [0] - A tuple containing /NAMES.
* [1] - Channel topic.
* [2] - Tuple containing information regarding of whom... | [
"def",
"join_",
"(",
"self",
",",
"channel",
",",
"key",
"=",
"None",
",",
"process_only",
"=",
"False",
")",
":",
"with",
"self",
".",
"lock",
":",
"topic",
"=",
"''",
"users",
"=",
"[",
"]",
"set_by",
"=",
"''",
"time_set",
"=",
"''",
"self",
"... | 39.692308 | 13.205128 |
def patch(nml_path, nml_patch, out_path=None):
"""Create a new namelist based on an input namelist and reference dict.
>>> f90nml.patch('data.nml', nml_patch, 'patched_data.nml')
This function is equivalent to the ``read`` function of the ``Parser``
object with the patch output arguments.
>>> par... | [
"def",
"patch",
"(",
"nml_path",
",",
"nml_patch",
",",
"out_path",
"=",
"None",
")",
":",
"parser",
"=",
"Parser",
"(",
")",
"return",
"parser",
".",
"read",
"(",
"nml_path",
",",
"nml_patch",
",",
"out_path",
")"
] | 37.555556 | 22.666667 |
def parse(name, content, releases, get_head_fn):
"""
Parses the given content for a valid changelog
:param name: str, package name
:param content: str, content
:param releases: list, releases
:param get_head_fn: function
:return: dict, changelog
"""
changelog = {}
releases = froz... | [
"def",
"parse",
"(",
"name",
",",
"content",
",",
"releases",
",",
"get_head_fn",
")",
":",
"changelog",
"=",
"{",
"}",
"releases",
"=",
"frozenset",
"(",
"releases",
")",
"head",
"=",
"False",
"date_line",
"=",
"None",
"for",
"line",
"in",
"content",
... | 28.8 | 11.4 |
def _check_init(self, node):
"""check that the __init__ method call super or ancestors'__init__
method
"""
if not self.linter.is_message_enabled(
"super-init-not-called"
) and not self.linter.is_message_enabled("non-parent-init-called"):
return
kla... | [
"def",
"_check_init",
"(",
"self",
",",
"node",
")",
":",
"if",
"not",
"self",
".",
"linter",
".",
"is_message_enabled",
"(",
"\"super-init-not-called\"",
")",
"and",
"not",
"self",
".",
"linter",
".",
"is_message_enabled",
"(",
"\"non-parent-init-called\"",
")"... | 41.946429 | 15.285714 |
def setOutputHandler(self, outputhandler):
"""
Sets a new output handler.
Args:
outputhandler: The function handling the AMPL output derived from
interpreting user commands.
"""
class OutputHandlerInternal(amplpython.OutputHandler):
def output... | [
"def",
"setOutputHandler",
"(",
"self",
",",
"outputhandler",
")",
":",
"class",
"OutputHandlerInternal",
"(",
"amplpython",
".",
"OutputHandler",
")",
":",
"def",
"output",
"(",
"self",
",",
"kind",
",",
"msg",
")",
":",
"outputhandler",
".",
"output",
"(",... | 32 | 15.6 |
def create_default_config(schema):
"""Create a configuration dictionary from a schema dictionary.
The schema defines the valid configuration keys and their default
values. Each element of ``schema`` should be a tuple/list
containing (default value,docstring,type) or a dict containing a
nested schem... | [
"def",
"create_default_config",
"(",
"schema",
")",
":",
"o",
"=",
"{",
"}",
"for",
"key",
",",
"item",
"in",
"schema",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"item",
",",
"dict",
")",
":",
"o",
"[",
"key",
"]",
"=",
"create_default_... | 31.645161 | 21.032258 |
def parse_member_from_rsvp(data):
"""
Parse a ``MeetupMember`` from the given RSVP response data.
Returns
-------
A ``pythonkc_meetups.types.MeetupMember``.
"""
return MeetupMember(
id=data['member'].get('member_id', None),
name=data['member'].get('name', None),
pho... | [
"def",
"parse_member_from_rsvp",
"(",
"data",
")",
":",
"return",
"MeetupMember",
"(",
"id",
"=",
"data",
"[",
"'member'",
"]",
".",
"get",
"(",
"'member_id'",
",",
"None",
")",
",",
"name",
"=",
"data",
"[",
"'member'",
"]",
".",
"get",
"(",
"'name'",... | 26.733333 | 17.266667 |
def call_handlers(self, msg):
""" Reimplemented to emit signals instead of making callbacks.
"""
# Emit the generic signal.
self.message_received.emit(msg)
# Emit signals for specialized message types.
msg_type = msg['header']['msg_type']
signal = getattr(self, m... | [
"def",
"call_handlers",
"(",
"self",
",",
"msg",
")",
":",
"# Emit the generic signal.",
"self",
".",
"message_received",
".",
"emit",
"(",
"msg",
")",
"# Emit signals for specialized message types.",
"msg_type",
"=",
"msg",
"[",
"'header'",
"]",
"[",
"'msg_type'",
... | 32.266667 | 10.866667 |
def p_modules(self, p):
"""modules : modules module
| module"""
n = len(p)
if n == 3:
p[0] = p[1] + [p[2]]
elif n == 2:
p[0] = [p[1]] | [
"def",
"p_modules",
"(",
"self",
",",
"p",
")",
":",
"n",
"=",
"len",
"(",
"p",
")",
"if",
"n",
"==",
"3",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"+",
"[",
"p",
"[",
"2",
"]",
"]",
"elif",
"n",
"==",
"2",
":",
"p",
"[",
"... | 25.125 | 13 |
def get_registration_fields(xmlstream,
timeout=60,
):
"""
A query is sent to the server to obtain the fields that need to be
filled to register with the server.
:param xmlstream: Specifies the stream connected to the server where
... | [
"def",
"get_registration_fields",
"(",
"xmlstream",
",",
"timeout",
"=",
"60",
",",
")",
":",
"iq",
"=",
"aioxmpp",
".",
"IQ",
"(",
"to",
"=",
"aioxmpp",
".",
"JID",
".",
"fromstr",
"(",
"xmlstream",
".",
"_to",
")",
",",
"type_",
"=",
"aioxmpp",
"."... | 35.666667 | 20.6 |
def make_nd_vec(v, nd=None, t=None, norm=False):
""" Coerce input to np.array() and validate dimensionality.
Ensure dimensionality 'n' if passed.
Cast to type 't' if passed
Normalize output if norm=True
.. todo:: Complete make_nd_vec docstring
"""
# Imports
import numpy as np
fro... | [
"def",
"make_nd_vec",
"(",
"v",
",",
"nd",
"=",
"None",
",",
"t",
"=",
"None",
",",
"norm",
"=",
"False",
")",
":",
"# Imports",
"import",
"numpy",
"as",
"np",
"from",
"scipy",
"import",
"linalg",
"as",
"spla",
"# Reduce the input to the extent possible",
... | 24.472222 | 19.138889 |
def _req(self, req):
"""Send command and wait for response.
The command will be repeated 3 times at most in case data loss of serial port.
Args:
req (str): Command to send, please do not include new line in the end.
Returns:
[str]: The output lines
"""
... | [
"def",
"_req",
"(",
"self",
",",
"req",
")",
":",
"logger",
".",
"debug",
"(",
"'DUT> %s'",
",",
"req",
")",
"self",
".",
"_log",
"and",
"self",
".",
"pause",
"(",
")",
"times",
"=",
"3",
"res",
"=",
"None",
"while",
"times",
":",
"times",
"=",
... | 24.72093 | 20.418605 |
def get_broadcast_shape(*tensors):
"""Get broadcast shape as a Python list of integers (preferred) or `Tensor`.
Args:
*tensors: One or more `Tensor` objects (already converted!).
Returns:
broadcast shape: Python list (if shapes determined statically), otherwise
an `int32` `Tensor`.
"""
# Try... | [
"def",
"get_broadcast_shape",
"(",
"*",
"tensors",
")",
":",
"# Try static.",
"s_shape",
"=",
"tensors",
"[",
"0",
"]",
".",
"shape",
"for",
"t",
"in",
"tensors",
"[",
"1",
":",
"]",
":",
"s_shape",
"=",
"tf",
".",
"broadcast_static_shape",
"(",
"s_shape... | 31.227273 | 19.818182 |
def supports_tagging(obj):
"""
:param obj: a class or instance
"""
if isinstance(obj, type):
return issubclass(obj, SupportTagging)
if not isinstance(obj, SupportTagging):
return False
if obj.id is None:
return False
return True | [
"def",
"supports_tagging",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"type",
")",
":",
"return",
"issubclass",
"(",
"obj",
",",
"SupportTagging",
")",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"SupportTagging",
")",
":",
"return",
"Fal... | 19.285714 | 17.285714 |
def fold_xor(bloomfilter, # type: bitarray
folds # type: int
):
# type: (...) -> bitarray
""" Performs XOR folding on a Bloom filter.
If the length of the original Bloom filter is n and we perform
r folds, then the length of the resulting filter is n / 2 ** r.... | [
"def",
"fold_xor",
"(",
"bloomfilter",
",",
"# type: bitarray",
"folds",
"# type: int",
")",
":",
"# type: (...) -> bitarray",
"if",
"len",
"(",
"bloomfilter",
")",
"%",
"2",
"**",
"folds",
"!=",
"0",
":",
"msg",
"=",
"(",
"'The length of the bloom filter is {leng... | 31.689655 | 19.758621 |
def center_image(self, no_reset=True):
"""Pan to the center of the image.
Parameters
----------
no_reset : bool
See :meth:`set_pan`.
"""
try:
xy_mn, xy_mx = self.get_limits()
data_x = float(xy_mn[0] + xy_mx[0]) / 2.0
data_... | [
"def",
"center_image",
"(",
"self",
",",
"no_reset",
"=",
"True",
")",
":",
"try",
":",
"xy_mn",
",",
"xy_mx",
"=",
"self",
".",
"get_limits",
"(",
")",
"data_x",
"=",
"float",
"(",
"xy_mn",
"[",
"0",
"]",
"+",
"xy_mx",
"[",
"0",
"]",
")",
"/",
... | 29.785714 | 18.821429 |
def info(name):
'''
Return information about a certificate
.. note::
Will output tls.cert_info if that's available, or OpenSSL text if not
:param name: CommonName of cert
CLI example:
.. code-block:: bash
salt 'gitlab.example.com' acme.info dev.example.com
'''
cert_f... | [
"def",
"info",
"(",
"name",
")",
":",
"cert_file",
"=",
"_cert_file",
"(",
"name",
",",
"'cert'",
")",
"# Use the salt module if available",
"if",
"'tls.cert_info'",
"in",
"__salt__",
":",
"cert_info",
"=",
"__salt__",
"[",
"'tls.cert_info'",
"]",
"(",
"cert_fil... | 32.962963 | 21.555556 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.