text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def create_all_recommendations(self, cores, ip_views=False):
"""Calculate the recommendations for all records."""
global _store
_store = self.store
_create_all_recommendations(cores, ip_views, self.config) | [
"def",
"create_all_recommendations",
"(",
"self",
",",
"cores",
",",
"ip_views",
"=",
"False",
")",
":",
"global",
"_store",
"_store",
"=",
"self",
".",
"store",
"_create_all_recommendations",
"(",
"cores",
",",
"ip_views",
",",
"self",
".",
"config",
")"
] | 46.6 | 15.4 |
def get_from_cache(self, org_id, id):
'''
Get an object from the cache
Use all cache folders available (primary first, then secondary in order) and look for the ID in the dir
if found unpickle and return the object, else return False
FIXME: Check for expiry of o... | [
"def",
"get_from_cache",
"(",
"self",
",",
"org_id",
",",
"id",
")",
":",
"current_time",
"=",
"datetime",
".",
"now",
"(",
")",
"# Check memory cache first",
"if",
"id",
"in",
"self",
".",
"memory_cache",
"[",
"org_id",
"]",
":",
"obj",
"=",
"self",
"."... | 39.02381 | 22.785714 |
def call_checkout_api(self, request_data, action, **kwargs):
"""This will call the checkout adyen api. xapi key merchant_account,
and platform are pulled from root module level and or self object.
AdyenResult will be returned on 200 response. Otherwise, an exception
is raised.
A... | [
"def",
"call_checkout_api",
"(",
"self",
",",
"request_data",
",",
"action",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"http_init",
":",
"self",
".",
"http_client",
"=",
"HTTPClient",
"(",
"self",
".",
"app_name",
",",
"self",
".",
"... | 43.25 | 21.319444 |
def get_target_list(self, scan_id):
""" Get a scan's target list. """
target_list = []
for target, _, _ in self.scans_table[scan_id]['targets']:
target_list.append(target)
return target_list | [
"def",
"get_target_list",
"(",
"self",
",",
"scan_id",
")",
":",
"target_list",
"=",
"[",
"]",
"for",
"target",
",",
"_",
",",
"_",
"in",
"self",
".",
"scans_table",
"[",
"scan_id",
"]",
"[",
"'targets'",
"]",
":",
"target_list",
".",
"append",
"(",
... | 32.714286 | 14.571429 |
def increase_counter(self, *path, **kwargs):
"""Increase a counter.
This method increases a counter within the application's
namespace. Each element of `path` is converted to a string
and normalized before joining the elements by periods. The
normalization process is little mo... | [
"def",
"increase_counter",
"(",
"self",
",",
"*",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"application",
".",
"statsd",
".",
"send",
"(",
"path",
",",
"kwargs",
".",
"get",
"(",
"'amount'",
",",
"'1'",
")",
",",
"'c'",
")"
] | 41.333333 | 22.6 |
def profile(event_type, extra_data=None):
"""Profile a span of time so that it appears in the timeline visualization.
Note that this only works in the raylet code path.
This function can be used as follows (both on the driver or within a task).
.. code-block:: python
with ray.profile("custom... | [
"def",
"profile",
"(",
"event_type",
",",
"extra_data",
"=",
"None",
")",
":",
"worker",
"=",
"ray",
".",
"worker",
".",
"global_worker",
"return",
"RayLogSpanRaylet",
"(",
"worker",
".",
"profiler",
",",
"event_type",
",",
"extra_data",
"=",
"extra_data",
"... | 44.40625 | 27.96875 |
def find_trigger_value(psd_var, idx, start, sample_rate):
""" Find the PSD variation value at a particular time
Parameters
----------
psd_var : TimeSeries
Time series of the varaibility in the PSD estimation
idx : numpy.ndarray
Time indices of the triggers
start : float
... | [
"def",
"find_trigger_value",
"(",
"psd_var",
",",
"idx",
",",
"start",
",",
"sample_rate",
")",
":",
"# Find gps time of the trigger",
"time",
"=",
"start",
"+",
"idx",
"/",
"sample_rate",
"# Find where in the psd variation time series the trigger belongs",
"ind",
"=",
... | 26.666667 | 19.111111 |
def ext_publish(self, instance, loop, *args, **kwargs):
"""If 'external_signaller' is defined, calls it's publish method to
notify external event systems.
This is for internal usage only, but it's doumented because it's part
of the interface with external notification systems.
"... | [
"def",
"ext_publish",
"(",
"self",
",",
"instance",
",",
"loop",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"external_signaller",
"is",
"not",
"None",
":",
"# Assumes that the loop is managed by the external handler",
"return",
"self... | 53 | 20.090909 |
def cmd_cammsg_old(self, args):
'''cammsg_old'''
print("Sent old DIGICAM_CONTROL")
self.master.mav.digicam_control_send(
self.settings.target_system, # target_system
0, # target_component
0, 0, 0, 0, 1, 0, 0, 0) | [
"def",
"cmd_cammsg_old",
"(",
"self",
",",
"args",
")",
":",
"print",
"(",
"\"Sent old DIGICAM_CONTROL\"",
")",
"self",
".",
"master",
".",
"mav",
".",
"digicam_control_send",
"(",
"self",
".",
"settings",
".",
"target_system",
",",
"# target_system",
"0",
","... | 33.25 | 12.5 |
def InsertIntArg(self, string='', **unused_kwargs):
"""Inserts an Integer argument."""
try:
int_value = int(string)
except (TypeError, ValueError):
raise errors.ParseError('{0:s} is not a valid integer.'.format(string))
return self.InsertArg(int_value) | [
"def",
"InsertIntArg",
"(",
"self",
",",
"string",
"=",
"''",
",",
"*",
"*",
"unused_kwargs",
")",
":",
"try",
":",
"int_value",
"=",
"int",
"(",
"string",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"raise",
"errors",
".",
"ParseErro... | 39.142857 | 14.285714 |
def _init_options(self, kwargs):
""" Initializes self.options """
self.options = self.task_config.options
if self.options is None:
self.options = {}
if kwargs:
self.options.update(kwargs)
# Handle dynamic lookup of project_config values via $project_confi... | [
"def",
"_init_options",
"(",
"self",
",",
"kwargs",
")",
":",
"self",
".",
"options",
"=",
"self",
".",
"task_config",
".",
"options",
"if",
"self",
".",
"options",
"is",
"None",
":",
"self",
".",
"options",
"=",
"{",
"}",
"if",
"kwargs",
":",
"self"... | 40.625 | 18.125 |
def get_account_certificate(self, account_id, cert_id, **kwargs): # noqa: E501
"""Get trusted certificate by ID. # noqa: E501
An endpoint for retrieving a trusted certificate by ID. **Example usage:** `curl https://api.us-east-1.mbedcloud.com/v3/accounts/{accountID}/trusted-certificates/{cert-id} -... | [
"def",
"get_account_certificate",
"(",
"self",
",",
"account_id",
",",
"cert_id",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'asynchronous'",
")",
":",
"re... | 58.818182 | 32.272727 |
def rm_fstab(name, device, config='/etc/fstab'):
'''
.. versionchanged:: 2016.3.2
Remove the mount point from the fstab
CLI Example:
.. code-block:: bash
salt '*' mount.rm_fstab /mnt/foo /dev/sdg
'''
modified = False
if __grains__['kernel'] == 'SunOS':
criteria = _vf... | [
"def",
"rm_fstab",
"(",
"name",
",",
"device",
",",
"config",
"=",
"'/etc/fstab'",
")",
":",
"modified",
"=",
"False",
"if",
"__grains__",
"[",
"'kernel'",
"]",
"==",
"'SunOS'",
":",
"criteria",
"=",
"_vfstab_entry",
"(",
"name",
"=",
"name",
",",
"devic... | 29.68 | 19.84 |
def register(self, collector):
"""Add a collector to the registry."""
with self._lock:
names = self._get_names(collector)
duplicates = set(self._names_to_collectors).intersection(names)
if duplicates:
raise ValueError(
'Duplicated t... | [
"def",
"register",
"(",
"self",
",",
"collector",
")",
":",
"with",
"self",
".",
"_lock",
":",
"names",
"=",
"self",
".",
"_get_names",
"(",
"collector",
")",
"duplicates",
"=",
"set",
"(",
"self",
".",
"_names_to_collectors",
")",
".",
"intersection",
"... | 44.75 | 14.416667 |
def query(self, area=None, date=None, raw=None, area_relation='Intersects',
order_by=None, limit=None, offset=0, **keywords):
"""Query the OpenSearch API with the coordinates of an area, a date interval
and any other search keywords accepted by the API.
Parameters
--------... | [
"def",
"query",
"(",
"self",
",",
"area",
"=",
"None",
",",
"date",
"=",
"None",
",",
"raw",
"=",
"None",
",",
"area_relation",
"=",
"'Intersects'",
",",
"order_by",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"offset",
"=",
"0",
",",
"*",
"*",
... | 50.027397 | 28.123288 |
def short_stack():
"""Return a string summarizing the call stack."""
stack = inspect.stack()[:0:-1]
return "\n".join(["%30s : %s @%d" % (t[3],t[1],t[2]) for t in stack]) | [
"def",
"short_stack",
"(",
")",
":",
"stack",
"=",
"inspect",
".",
"stack",
"(",
")",
"[",
":",
"0",
":",
"-",
"1",
"]",
"return",
"\"\\n\"",
".",
"join",
"(",
"[",
"\"%30s : %s @%d\"",
"%",
"(",
"t",
"[",
"3",
"]",
",",
"t",
"[",
"1",
"]",
"... | 44.5 | 15.25 |
def print_ldamodel_topic_words(topic_word_distrib, vocab, n_top=10, row_labels=DEFAULT_TOPIC_NAME_FMT):
"""Print `n_top` values from a LDA model's topic-word distributions."""
print_ldamodel_distribution(topic_word_distrib, row_labels=row_labels, val_labels=vocab,
top_n=n_top) | [
"def",
"print_ldamodel_topic_words",
"(",
"topic_word_distrib",
",",
"vocab",
",",
"n_top",
"=",
"10",
",",
"row_labels",
"=",
"DEFAULT_TOPIC_NAME_FMT",
")",
":",
"print_ldamodel_distribution",
"(",
"topic_word_distrib",
",",
"row_labels",
"=",
"row_labels",
",",
"val... | 78.5 | 29.75 |
def polling(self, system_code=0xffff, request_code=0, time_slots=0):
"""Aquire and identify a card.
The Polling command is used to detect the Type 3 Tags in the
field. It is also used for initialization and anti-collision.
The *system_code* identifies the card system to acquire. A
... | [
"def",
"polling",
"(",
"self",
",",
"system_code",
"=",
"0xffff",
",",
"request_code",
"=",
"0",
",",
"time_slots",
"=",
"0",
")",
":",
"log",
".",
"debug",
"(",
"\"polling for system 0x{0:04x}\"",
".",
"format",
"(",
"system_code",
")",
")",
"if",
"time_s... | 51.919355 | 25.83871 |
def predict_factors(self, counts_df, maxiter=10, ncores=1, random_seed=1, stop_thr=1e-3, return_all=False):
"""
Gets latent factors for a user given her item counts
This is similar to obtaining topics for a document in LDA.
Note
----
This function will NOT modify any of the item parameters.
Note
----... | [
"def",
"predict_factors",
"(",
"self",
",",
"counts_df",
",",
"maxiter",
"=",
"10",
",",
"ncores",
"=",
"1",
",",
"random_seed",
"=",
"1",
",",
"stop_thr",
"=",
"1e-3",
",",
"return_all",
"=",
"False",
")",
":",
"ncores",
",",
"random_seed",
",",
"stop... | 36.082192 | 26.90411 |
def centroids(self, instrument, min_abundance=1e-4, points_per_fwhm=25):
"""
Estimates centroided peaks for a given instrument model.
:param instrument: instrument model
:param min_abundance: minimum abundance for including a peak
:param points_per_fwhm: grid density used for en... | [
"def",
"centroids",
"(",
"self",
",",
"instrument",
",",
"min_abundance",
"=",
"1e-4",
",",
"points_per_fwhm",
"=",
"25",
")",
":",
"assert",
"self",
".",
"ptr",
"!=",
"ffi",
".",
"NULL",
"centroids",
"=",
"ims",
".",
"spectrum_envelope_centroids",
"(",
"s... | 49.142857 | 20.428571 |
def _read_stderr(self, encoding='utf-8'):
"""Reads self.proc.stderr.
Usually, this should be read in a thread, to prevent blocking
the read from stdout of the stderr buffer is filled, and this
function is not called becuase the program is busy in the
stderr reading loop.
... | [
"def",
"_read_stderr",
"(",
"self",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"for",
"line",
"in",
"self",
".",
"proc",
".",
"stderr",
":",
"err_line",
"=",
"line",
".",
"decode",
"(",
"encoding",
",",
"errors",
"=",
"'surrogateescape'",
")",
"if",
"s... | 47.72 | 21.76 |
def drop_namespaces(self):
"""Drop all namespaces."""
self.session.query(NamespaceEntry).delete()
self.session.query(Namespace).delete()
self.session.commit() | [
"def",
"drop_namespaces",
"(",
"self",
")",
":",
"self",
".",
"session",
".",
"query",
"(",
"NamespaceEntry",
")",
".",
"delete",
"(",
")",
"self",
".",
"session",
".",
"query",
"(",
"Namespace",
")",
".",
"delete",
"(",
")",
"self",
".",
"session",
... | 37.2 | 8.4 |
def from_list(cls, l):
"""Return a Point instance from a given list"""
if len(l) == 3:
x, y, z = map(float, l)
return cls(x, y, z)
elif len(l) == 2:
x, y = map(float, l)
return cls(x, y)
else:
raise AttributeError | [
"def",
"from_list",
"(",
"cls",
",",
"l",
")",
":",
"if",
"len",
"(",
"l",
")",
"==",
"3",
":",
"x",
",",
"y",
",",
"z",
"=",
"map",
"(",
"float",
",",
"l",
")",
"return",
"cls",
"(",
"x",
",",
"y",
",",
"z",
")",
"elif",
"len",
"(",
"l... | 30.4 | 11.1 |
def doStuff(ABFfolder,analyze=False,convert=False,index=True,overwrite=True,
launch=True):
"""Inelegant for now, but lets you manually analyze every ABF in a folder."""
IN=INDEX(ABFfolder)
if analyze:
IN.analyzeAll()
if convert:
IN.convertImages() | [
"def",
"doStuff",
"(",
"ABFfolder",
",",
"analyze",
"=",
"False",
",",
"convert",
"=",
"False",
",",
"index",
"=",
"True",
",",
"overwrite",
"=",
"True",
",",
"launch",
"=",
"True",
")",
":",
"IN",
"=",
"INDEX",
"(",
"ABFfolder",
")",
"if",
"analyze"... | 35.5 | 18.625 |
def _check_iso9660_filename(fullname, interchange_level):
# type: (bytes, int) -> None
'''
A function to check that a file identifier conforms to the ISO9660 rules
for a particular interchange level.
Parameters:
fullname - The name to check.
interchange_level - The interchange level to ch... | [
"def",
"_check_iso9660_filename",
"(",
"fullname",
",",
"interchange_level",
")",
":",
"# type: (bytes, int) -> None",
"# Check to ensure the name is a valid filename for the ISO according to",
"# Ecma-119 7.5.",
"(",
"name",
",",
"extension",
",",
"version",
")",
"=",
"_split_... | 46.711864 | 31.220339 |
def format_output(self, rendered_widgets):
"""
Render the ``icekit_events/recurrence_rule_widget/format_output.html``
template with the following context:
preset
A choice field for preset recurrence rules.
natural
An input field for natura... | [
"def",
"format_output",
"(",
"self",
",",
"rendered_widgets",
")",
":",
"template",
"=",
"loader",
".",
"get_template",
"(",
"'icekit_events/recurrence_rule_widget/format_output.html'",
")",
"preset",
",",
"natural",
",",
"rfc",
"=",
"rendered_widgets",
"context",
"="... | 35.541667 | 17.208333 |
def iter(self, keyed=False, extended=False, cast=True, relations=False):
"""https://github.com/frictionlessdata/tableschema-py#schema
"""
# Prepare unique checks
if cast:
unique_fields_cache = {}
if self.schema:
unique_fields_cache = _create_uniqu... | [
"def",
"iter",
"(",
"self",
",",
"keyed",
"=",
"False",
",",
"extended",
"=",
"False",
",",
"cast",
"=",
"True",
",",
"relations",
"=",
"False",
")",
":",
"# Prepare unique checks",
"if",
"cast",
":",
"unique_fields_cache",
"=",
"{",
"}",
"if",
"self",
... | 40.098361 | 20.868852 |
def query_entities(self, table_name, filter=None, select=None, num_results=None,
marker=None, accept=TablePayloadFormat.JSON_MINIMAL_METADATA,
property_resolver=None, timeout=None):
'''
Returns a generator to list the entities in the table specified. The
... | [
"def",
"query_entities",
"(",
"self",
",",
"table_name",
",",
"filter",
"=",
"None",
",",
"select",
"=",
"None",
",",
"num_results",
"=",
"None",
",",
"marker",
"=",
"None",
",",
"accept",
"=",
"TablePayloadFormat",
".",
"JSON_MINIMAL_METADATA",
",",
"proper... | 56.095238 | 30.349206 |
def create_new_sub_account(self, account_id, account_name, account_default_group_storage_quota_mb=None, account_default_storage_quota_mb=None, account_default_user_storage_quota_mb=None, account_sis_account_id=None):
"""
Create a new sub-account.
Add a new sub-account to a given account.
... | [
"def",
"create_new_sub_account",
"(",
"self",
",",
"account_id",
",",
"account_name",
",",
"account_default_group_storage_quota_mb",
"=",
"None",
",",
"account_default_storage_quota_mb",
"=",
"None",
",",
"account_default_user_storage_quota_mb",
"=",
"None",
",",
"account_s... | 51.7 | 28.6 |
def get_all():
'''
Return all installed services
CLI Example:
.. code-block:: bash
salt '*' service.get_all
'''
ret = set()
cmd = '/usr/bin/svcs -aH -o FMRI,STATE -s FMRI'
lines = __salt__['cmd.run'](cmd).splitlines()
for line in lines:
comps = line.split()
... | [
"def",
"get_all",
"(",
")",
":",
"ret",
"=",
"set",
"(",
")",
"cmd",
"=",
"'/usr/bin/svcs -aH -o FMRI,STATE -s FMRI'",
"lines",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
")",
".",
"splitlines",
"(",
")",
"for",
"line",
"in",
"lines",
":",
"comp... | 20.315789 | 21.789474 |
def get_pull_request(project, num, auth=False):
"""get pull request info by number
"""
url = "https://api.github.com/repos/{project}/pulls/{num}".format(project=project, num=num)
if auth:
header = make_auth_header()
else:
header = None
response = requests.get(url, headers=header... | [
"def",
"get_pull_request",
"(",
"project",
",",
"num",
",",
"auth",
"=",
"False",
")",
":",
"url",
"=",
"\"https://api.github.com/repos/{project}/pulls/{num}\"",
".",
"format",
"(",
"project",
"=",
"project",
",",
"num",
"=",
"num",
")",
"if",
"auth",
":",
"... | 36.090909 | 15.909091 |
def from_dir(cls, ID, datadir, parser, pattern='*.fcs', recursive=False,
readdata_kwargs={}, readmeta_kwargs={}, **ID_kwargs):
"""
Create a Collection of measurements from data files contained in a directory.
Parameters
----------
ID : hashable
Colle... | [
"def",
"from_dir",
"(",
"cls",
",",
"ID",
",",
"datadir",
",",
"parser",
",",
"pattern",
"=",
"'*.fcs'",
",",
"recursive",
"=",
"False",
",",
"readdata_kwargs",
"=",
"{",
"}",
",",
"readmeta_kwargs",
"=",
"{",
"}",
",",
"*",
"*",
"ID_kwargs",
")",
":... | 41.454545 | 21.727273 |
def density_angle(rho0: Density, rho1: Density) -> bk.BKTensor:
"""The Fubini-Study angle between density matrices"""
return fubini_study_angle(rho0.vec, rho1.vec) | [
"def",
"density_angle",
"(",
"rho0",
":",
"Density",
",",
"rho1",
":",
"Density",
")",
"->",
"bk",
".",
"BKTensor",
":",
"return",
"fubini_study_angle",
"(",
"rho0",
".",
"vec",
",",
"rho1",
".",
"vec",
")"
] | 56.333333 | 10.666667 |
def write(self, data):
"""
write data on the OUT endpoint associated to the HID interface
"""
for _ in range(64 - len(data)):
data.append(0)
#logging.debug("send: %s", data)
self.device.write(bytearray([0]) + data)
return | [
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"for",
"_",
"in",
"range",
"(",
"64",
"-",
"len",
"(",
"data",
")",
")",
":",
"data",
".",
"append",
"(",
"0",
")",
"#logging.debug(\"send: %s\", data)",
"self",
".",
"device",
".",
"write",
"(",
... | 31.222222 | 10.777778 |
def value_matrix(self):
"""Converted rows of tabular data.
Returns:
|list| or |tuple|: Table rows.
"""
if self.__value_matrix:
return self.__value_matrix
self.__value_matrix = [
[value_dp.data for value_dp in value_dp_list] for value_dp_list... | [
"def",
"value_matrix",
"(",
"self",
")",
":",
"if",
"self",
".",
"__value_matrix",
":",
"return",
"self",
".",
"__value_matrix",
"self",
".",
"__value_matrix",
"=",
"[",
"[",
"value_dp",
".",
"data",
"for",
"value_dp",
"in",
"value_dp_list",
"]",
"for",
"v... | 25.066667 | 21.266667 |
def response_hook(self, response, **kwargs) -> HTMLResponse:
""" Change response enconding and replace it by a HTMLResponse. """
if not response.encoding:
response.encoding = DEFAULT_ENCODING
return HTMLResponse._from_response(response, self) | [
"def",
"response_hook",
"(",
"self",
",",
"response",
",",
"*",
"*",
"kwargs",
")",
"->",
"HTMLResponse",
":",
"if",
"not",
"response",
".",
"encoding",
":",
"response",
".",
"encoding",
"=",
"DEFAULT_ENCODING",
"return",
"HTMLResponse",
".",
"_from_response",... | 54.8 | 10.6 |
def path(self, filename=None, ext='tsv', digest=False, shard=False, encoding='utf-8'):
"""
Return the path for this class with a certain set of parameters.
`ext` sets the extension of the file.
If `hash` is true, the filename (w/o extenstion) will be hashed.
If `shard` is true, t... | [
"def",
"path",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"ext",
"=",
"'tsv'",
",",
"digest",
"=",
"False",
",",
"shard",
"=",
"False",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"if",
"self",
".",
"BASE",
"is",
"NotImplemented",
":",
"raise",
... | 41.44 | 20.64 |
def protein_map_from_twg(twg):
"""Build map of entity texts to validate protein grounding.
Looks at the grounding of the entity texts extracted from the statements
and finds proteins where there is grounding to a human protein that maps to
an HGNC name that is an exact match to the entity text. Return... | [
"def",
"protein_map_from_twg",
"(",
"twg",
")",
":",
"protein_map",
"=",
"{",
"}",
"unmatched",
"=",
"0",
"matched",
"=",
"0",
"logger",
".",
"info",
"(",
"'Building grounding map for human proteins'",
")",
"for",
"agent_text",
",",
"grounding_list",
",",
"_",
... | 40.836364 | 21.072727 |
def lsl(hdfs_path, user=None, recursive=False):
"""
Return a list of dictionaries of file properties.
If ``hdfs_path`` is a file, there is only one item corresponding to
the file itself; if it is a directory and ``recursive`` is
:obj:`False`, each list item corresponds to a file or directory
co... | [
"def",
"lsl",
"(",
"hdfs_path",
",",
"user",
"=",
"None",
",",
"recursive",
"=",
"False",
")",
":",
"host",
",",
"port",
",",
"path_",
"=",
"path",
".",
"split",
"(",
"hdfs_path",
",",
"user",
")",
"fs",
"=",
"hdfs",
"(",
"host",
",",
"port",
","... | 35.5 | 15.666667 |
def cluster_info(ipyclient, spacer=""):
""" reports host and engine info for an ipyclient """
## get engine data, skips busy engines.
hosts = []
for eid in ipyclient.ids:
engine = ipyclient[eid]
if not engine.outstanding:
hosts.append(engine.apply(_socket.gethostname)... | [
"def",
"cluster_info",
"(",
"ipyclient",
",",
"spacer",
"=",
"\"\"",
")",
":",
"## get engine data, skips busy engines. ",
"hosts",
"=",
"[",
"]",
"for",
"eid",
"in",
"ipyclient",
".",
"ids",
":",
"engine",
"=",
"ipyclient",
"[",
"eid",
"]",
"if",
"not",
... | 35.125 | 14.8125 |
def add_logging_level(name, value, method_name=None):
''' Comprehensively adds a new logging level to the ``logging`` module and
the currently configured logging class.
Derived from: https://stackoverflow.com/a/35804945/450917
'''
if not method_name:
method_name = name.lower()
... | [
"def",
"add_logging_level",
"(",
"name",
",",
"value",
",",
"method_name",
"=",
"None",
")",
":",
"if",
"not",
"method_name",
":",
"method_name",
"=",
"name",
".",
"lower",
"(",
")",
"# set levels",
"logging",
".",
"addLevelName",
"(",
"value",
",",
"name"... | 37.866667 | 21 |
def handle_default_options(options):
"""
Pass in a Values instance from OptionParser. Handle settings and pythonpath
options - Values from OptionParser
"""
if options.settings:
#Set the percept_settings_module (picked up by settings in conf.base)
os.environ['PERCEPT_SETTINGS_MODULE'... | [
"def",
"handle_default_options",
"(",
"options",
")",
":",
"if",
"options",
".",
"settings",
":",
"#Set the percept_settings_module (picked up by settings in conf.base)",
"os",
".",
"environ",
"[",
"'PERCEPT_SETTINGS_MODULE'",
"]",
"=",
"options",
".",
"settings",
"if",
... | 44.875 | 21.75 |
def setup_contracts_or_exit(
config: Dict[str, Any],
network_id: int,
) -> Dict[str, Any]:
"""Sets the contract deployment data depending on the network id and environment type
If an invalid combination of network id and environment type is provided, exits
the program with an error
"""
... | [
"def",
"setup_contracts_or_exit",
"(",
"config",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"network_id",
":",
"int",
",",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"environment_type",
"=",
"config",
"[",
"'environment_type'",
"]",
"not_al... | 34.452381 | 23.785714 |
def iter_all_children(obj, skipContainers=False):
"""
Returns an iterator over all childen and nested children using
obj's get_children() method
if skipContainers is true, only childless objects are returned.
"""
if hasattr(obj, 'get_children') and len(obj.get_children()) > 0:
for child... | [
"def",
"iter_all_children",
"(",
"obj",
",",
"skipContainers",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"'get_children'",
")",
"and",
"len",
"(",
"obj",
".",
"get_children",
"(",
")",
")",
">",
"0",
":",
"for",
"child",
"in",
"obj",
... | 36 | 16.375 |
def search(self, index, query):
"""
Begin a map/reduce operation using a Search. This command will
return an error unless executed against a Riak Search cluster.
:param index: The Solr index used in the search
:type index: string
:param query: The search query
:t... | [
"def",
"search",
"(",
"self",
",",
"index",
",",
"query",
")",
":",
"self",
".",
"_input_mode",
"=",
"'query'",
"self",
".",
"_inputs",
"=",
"{",
"'bucket'",
":",
"index",
",",
"'index'",
":",
"index",
",",
"'query'",
":",
"query",
"}",
"return",
"se... | 34.3125 | 11.4375 |
def parse(self, xml_data):
""" Parse XML data """
# parse tree
try:
root = ET.fromstring(xml_data)
except StdlibParseError as e:
raise ParseError(str(e))
self.origin = root.attrib['origin']
for child in root:
component = Component()
... | [
"def",
"parse",
"(",
"self",
",",
"xml_data",
")",
":",
"# parse tree",
"try",
":",
"root",
"=",
"ET",
".",
"fromstring",
"(",
"xml_data",
")",
"except",
"StdlibParseError",
"as",
"e",
":",
"raise",
"ParseError",
"(",
"str",
"(",
"e",
")",
")",
"self",... | 26.266667 | 15.466667 |
def _getSortedString(o):
"""
Returns a string describing o, sorting the contents (case-insensitive on keys) if o is a dict.
"""
# todo: replace this with something like pprint on Python upgrade
# We assume here that any container type is either list or tuple which may not always hold
if isinstance(o, (dict)):
p... | [
"def",
"_getSortedString",
"(",
"o",
")",
":",
"# todo: replace this with something like pprint on Python upgrade",
"# We assume here that any container type is either list or tuple which may not always hold",
"if",
"isinstance",
"(",
"o",
",",
"(",
"dict",
")",
")",
":",
"pkeys"... | 34.714286 | 21.428571 |
def mkdir(self, directory, exists_okay=False):
"""Create the specified directory. Note this cannot create a recursive
hierarchy of directories, instead each one should be created separately.
"""
# Execute os.mkdir command on the board.
command = """
try:
... | [
"def",
"mkdir",
"(",
"self",
",",
"directory",
",",
"exists_okay",
"=",
"False",
")",
":",
"# Execute os.mkdir command on the board.",
"command",
"=",
"\"\"\"\n try:\n import os\n except ImportError:\n import uos as os\n os... | 38 | 15.481481 |
async def dump_tuple(self, elem, elem_type, params=None):
"""
Dumps tuple of elements to the writer.
:param elem:
:param elem_type:
:param params:
:return:
"""
if len(elem) != len(elem_type.f_specs()):
raise ValueError('Fixed size tuple has no... | [
"async",
"def",
"dump_tuple",
"(",
"self",
",",
"elem",
",",
"elem_type",
",",
"params",
"=",
"None",
")",
":",
"if",
"len",
"(",
"elem",
")",
"!=",
"len",
"(",
"elem_type",
".",
"f_specs",
"(",
")",
")",
":",
"raise",
"ValueError",
"(",
"'Fixed size... | 35.869565 | 19.434783 |
def AddDigitalShortIdRecord(site_service, tag, time_value, value,
status_string="OK ", warn=False, chattering=False,
unreliable=False, manual=False):
"""
This function will add a digital value to the specified eDNA service and
tag, including all default point status definitions.
:p... | [
"def",
"AddDigitalShortIdRecord",
"(",
"site_service",
",",
"tag",
",",
"time_value",
",",
"value",
",",
"status_string",
"=",
"\"OK \"",
",",
"warn",
"=",
"False",
",",
"chattering",
"=",
"False",
",",
"unreliable",
"=",
"False",
",",
"manual",
"... | 49.416667 | 18.972222 |
def delete(self, instance):
'''Delete an instance'''
flushdb(self.client) if flushdb else self.client.flushdb() | [
"def",
"delete",
"(",
"self",
",",
"instance",
")",
":",
"flushdb",
"(",
"self",
".",
"client",
")",
"if",
"flushdb",
"else",
"self",
".",
"client",
".",
"flushdb",
"(",
")"
] | 42.333333 | 15 |
def dice(edge=15, fn=32):
""" dice
"""
edge = float(edge)
# dice
c = ops.Cube(edge, center=True)
s = ops.Sphere(edge * 3 / 4, center=True)
dice = c & s
# points
c = ops.Circle(edge / 12, _fn=fn)
h = 0.7
point = c.linear_extrude(heig... | [
"def",
"dice",
"(",
"edge",
"=",
"15",
",",
"fn",
"=",
"32",
")",
":",
"edge",
"=",
"float",
"(",
"edge",
")",
"# dice",
"c",
"=",
"ops",
".",
"Cube",
"(",
"edge",
",",
"center",
"=",
"True",
")",
"s",
"=",
"ops",
".",
"Sphere",
"(",
"edge",
... | 45.833333 | 16.8 |
def group(self, index, chunked=False):
""" Returns a list of Word objects that match the given group.
With chunked=True, returns a list of Word + Chunk objects - see Match.constituents().
A group consists of consecutive constraints wrapped in { }, e.g.,
search("{JJ JJ} NN", S... | [
"def",
"group",
"(",
"self",
",",
"index",
",",
"chunked",
"=",
"False",
")",
":",
"if",
"index",
"<",
"0",
"or",
"index",
">",
"len",
"(",
"self",
".",
"pattern",
".",
"groups",
")",
":",
"raise",
"IndexError",
"(",
"\"no such group\"",
")",
"if",
... | 57.066667 | 21.8 |
def get_monitor_ping(request):
"""MNCore.ping() → Boolean."""
response = d1_gmn.app.views.util.http_response_with_boolean_true_type()
d1_gmn.app.views.headers.add_http_date_header(response)
return response | [
"def",
"get_monitor_ping",
"(",
"request",
")",
":",
"response",
"=",
"d1_gmn",
".",
"app",
".",
"views",
".",
"util",
".",
"http_response_with_boolean_true_type",
"(",
")",
"d1_gmn",
".",
"app",
".",
"views",
".",
"headers",
".",
"add_http_date_header",
"(",
... | 43.4 | 17 |
def _subclass_must_implement(self, fn):
"""
Returns a NotImplementedError for a function that should be implemented.
:param fn: name of the function
"""
m = "Missing function implementation in {}: {}".format(type(self), fn)
return NotImplementedError(m) | [
"def",
"_subclass_must_implement",
"(",
"self",
",",
"fn",
")",
":",
"m",
"=",
"\"Missing function implementation in {}: {}\"",
".",
"format",
"(",
"type",
"(",
"self",
")",
",",
"fn",
")",
"return",
"NotImplementedError",
"(",
"m",
")"
] | 42.142857 | 11.857143 |
def refreshCompositeOf(self, single_keywords, composite_keywords,
store=None, namespace=None):
"""Re-check sub-parts of this keyword.
This should be called after the whole RDF was processed, because
it is using a cache of single keywords and if that
one is inc... | [
"def",
"refreshCompositeOf",
"(",
"self",
",",
"single_keywords",
",",
"composite_keywords",
",",
"store",
"=",
"None",
",",
"namespace",
"=",
"None",
")",
":",
"def",
"_get_ckw_components",
"(",
"new_vals",
",",
"label",
")",
":",
"if",
"label",
"in",
"sing... | 48.926829 | 17.292683 |
def get_diff_str(self, element, length):
'''get_diff_str
High-level api: Produce a string that indicates the difference between
two models.
Parameters
----------
element : `Element`
A node in model tree.
length : `int`
String length tha... | [
"def",
"get_diff_str",
"(",
"self",
",",
"element",
",",
"length",
")",
":",
"spaces",
"=",
"' '",
"*",
"(",
"self",
".",
"get_width",
"(",
"element",
")",
"-",
"length",
")",
"return",
"spaces",
"+",
"element",
".",
"get",
"(",
"'diff'",
")"
] | 22.791667 | 25.125 |
def genes_with_peak(self, peaks, transform_func=None, split=False,
intersect_kwargs=None, id_attribute='ID', *args,
**kwargs):
"""
Returns a boolean index of genes that have a peak nearby.
Parameters
----------
peaks : string or py... | [
"def",
"genes_with_peak",
"(",
"self",
",",
"peaks",
",",
"transform_func",
"=",
"None",
",",
"split",
"=",
"False",
",",
"intersect_kwargs",
"=",
"None",
",",
"id_attribute",
"=",
"'ID'",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"_t... | 41.565217 | 21.623188 |
def add_arguments(self, parser):
"""
Entry point for subclassed commands to add custom arguments.
"""
subparsers = parser.add_subparsers(help='sub-command help',
dest='command')
add_parser = partial(_add_subparser, subparsers, parser)
... | [
"def",
"add_arguments",
"(",
"self",
",",
"parser",
")",
":",
"subparsers",
"=",
"parser",
".",
"add_subparsers",
"(",
"help",
"=",
"'sub-command help'",
",",
"dest",
"=",
"'command'",
")",
"add_parser",
"=",
"partial",
"(",
"_add_subparser",
",",
"subparsers"... | 40.166667 | 16.583333 |
def find_peaks(sig):
"""
Find hard peaks and soft peaks in a signal, defined as follows:
- Hard peak: a peak that is either /\ or \/
- Soft peak: a peak that is either /-*\ or \-*/
In this case we define the middle as the peak
Parameters
----------
sig : np array
The 1d signa... | [
"def",
"find_peaks",
"(",
"sig",
")",
":",
"if",
"len",
"(",
"sig",
")",
"==",
"0",
":",
"return",
"np",
".",
"empty",
"(",
"[",
"0",
"]",
")",
",",
"np",
".",
"empty",
"(",
"[",
"0",
"]",
")",
"tmp",
"=",
"sig",
"[",
"1",
":",
"]",
"tmp"... | 25.94 | 20.5 |
def _get_nsamps_samples_n(res):
""" Helper function for calculating the number of samples
Parameters
----------
res : :class:`~dynesty.results.Results` instance
The :class:`~dynesty.results.Results` instance taken from a previous
nested sampling run.
Returns
-------
nsamps:... | [
"def",
"_get_nsamps_samples_n",
"(",
"res",
")",
":",
"try",
":",
"# Check if the number of live points explicitly changes.",
"samples_n",
"=",
"res",
".",
"samples_n",
"nsamps",
"=",
"len",
"(",
"samples_n",
")",
"except",
":",
"# If the number of live points is constant... | 33.514286 | 20.657143 |
def QA_fetch_future_min(
code,
start, end,
format='numpy',
frequence='1min',
collections=DATABASE.future_min):
'获取股票分钟线'
if frequence in ['1min', '1m']:
frequence = '1min'
elif frequence in ['5min', '5m']:
frequence = '5min'
elif frequence in ['15m... | [
"def",
"QA_fetch_future_min",
"(",
"code",
",",
"start",
",",
"end",
",",
"format",
"=",
"'numpy'",
",",
"frequence",
"=",
"'1min'",
",",
"collections",
"=",
"DATABASE",
".",
"future_min",
")",
":",
"if",
"frequence",
"in",
"[",
"'1min'",
",",
"'1m'",
"]... | 38.090909 | 17.772727 |
def decode_response(client_message, to_object=None):
""" Decode response from client message"""
parameters = dict(response=None)
if not client_message.read_bool():
parameters['response'] = to_object(client_message.read_data())
return parameters | [
"def",
"decode_response",
"(",
"client_message",
",",
"to_object",
"=",
"None",
")",
":",
"parameters",
"=",
"dict",
"(",
"response",
"=",
"None",
")",
"if",
"not",
"client_message",
".",
"read_bool",
"(",
")",
":",
"parameters",
"[",
"'response'",
"]",
"=... | 43.833333 | 11.166667 |
def get_include_fields(request):
"""Retrieve include_fields values from the request
"""
include_fields = []
rif = request.get("include_fields", "")
if "include_fields" in request:
include_fields = [x.strip()
for x in rif.split(",")
if x.str... | [
"def",
"get_include_fields",
"(",
"request",
")",
":",
"include_fields",
"=",
"[",
"]",
"rif",
"=",
"request",
".",
"get",
"(",
"\"include_fields\"",
",",
"\"\"",
")",
"if",
"\"include_fields\"",
"in",
"request",
":",
"include_fields",
"=",
"[",
"x",
".",
... | 35.916667 | 6.5 |
def Reorder(x, params, output=None, **kwargs):
"""Reorder a tuple into another tuple.
For example, we can re-order (x, y) into (y, x) or even (y, (x, y), y).
The output argument specifies how to re-order, using integers that refer
to indices in the input tuple. For example, if
input = (x, y, z)
then
... | [
"def",
"Reorder",
"(",
"x",
",",
"params",
",",
"output",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"del",
"params",
",",
"kwargs",
"if",
"output",
"is",
"None",
":",
"return",
"x",
"return",
"base",
".",
"nested_map",
"(",
"output",
",",
"la... | 30.677419 | 22.258065 |
def automain(self, function):
"""
Decorator that defines *and runs* the main function of the experiment.
The decorated function is marked as the default command for this
experiment, and the command-line interface is automatically run when
the file is executed.
The metho... | [
"def",
"automain",
"(",
"self",
",",
"function",
")",
":",
"captured",
"=",
"self",
".",
"main",
"(",
"function",
")",
"if",
"function",
".",
"__module__",
"==",
"'__main__'",
":",
"# Ensure that automain is not used in interactive mode.",
"import",
"inspect",
"ma... | 35.545455 | 20.878788 |
def _expand_address(addy):
'''
Convert the libcloud GCEAddress object into something more serializable.
'''
ret = {}
ret.update(addy.__dict__)
ret['extra']['zone'] = addy.region.name
return ret | [
"def",
"_expand_address",
"(",
"addy",
")",
":",
"ret",
"=",
"{",
"}",
"ret",
".",
"update",
"(",
"addy",
".",
"__dict__",
")",
"ret",
"[",
"'extra'",
"]",
"[",
"'zone'",
"]",
"=",
"addy",
".",
"region",
".",
"name",
"return",
"ret"
] | 26.75 | 23 |
def flavor_create(self,
name, # pylint: disable=C0103
flavor_id=0, # pylint: disable=C0103
ram=0,
disk=0,
vcpus=1,
is_public=True):
'''
Create a flavor
... | [
"def",
"flavor_create",
"(",
"self",
",",
"name",
",",
"# pylint: disable=C0103",
"flavor_id",
"=",
"0",
",",
"# pylint: disable=C0103",
"ram",
"=",
"0",
",",
"disk",
"=",
"0",
",",
"vcpus",
"=",
"1",
",",
"is_public",
"=",
"True",
")",
":",
"nt_ks",
"="... | 33.6 | 16.5 |
def merge(self, other):
# type: (TentativeType) -> None
"""
Merge two TentativeType instances
"""
for hashables in other.types_hashable:
self.add(hashables)
for non_hashbles in other.types:
self.add(non_hashbles) | [
"def",
"merge",
"(",
"self",
",",
"other",
")",
":",
"# type: (TentativeType) -> None",
"for",
"hashables",
"in",
"other",
".",
"types_hashable",
":",
"self",
".",
"add",
"(",
"hashables",
")",
"for",
"non_hashbles",
"in",
"other",
".",
"types",
":",
"self",... | 30.666667 | 4.444444 |
def state_to_modelparams(self, state):
"""
Converts a QuTiP-represented state into a model parameter vector.
:param qutip.Qobj state: State to be converted.
:rtype: :class:`np.ndarray`
:return: The representation of the given state in this basis,
as a vector of real ... | [
"def",
"state_to_modelparams",
"(",
"self",
",",
"state",
")",
":",
"basis",
"=",
"self",
".",
"flat",
"(",
")",
"data",
"=",
"state",
".",
"data",
".",
"todense",
"(",
")",
".",
"view",
"(",
"np",
".",
"ndarray",
")",
".",
"flatten",
"(",
")",
"... | 37.285714 | 15.714286 |
def CreateAttachment(self, document_link, attachment, options=None):
"""Creates an attachment in a document.
:param str document_link:
The link to the document.
:param dict attachment:
The Azure Cosmos attachment to create.
:param dict options:
The re... | [
"def",
"CreateAttachment",
"(",
"self",
",",
"document_link",
",",
"attachment",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"document_id",
",",
"path",
"=",
"self",
".",
"_GetItemIdWithPathForAttachme... | 30.538462 | 16.153846 |
def recover_and_supervise(recovery_file):
""" Retrieve monitor data from recovery_file and resume monitoring """
try:
logging.info("Attempting to recover Supervisor data from " + recovery_file)
with open(recovery_file) as rf:
recovery_data = json.load(rf)
monitor_data = r... | [
"def",
"recover_and_supervise",
"(",
"recovery_file",
")",
":",
"try",
":",
"logging",
".",
"info",
"(",
"\"Attempting to recover Supervisor data from \"",
"+",
"recovery_file",
")",
"with",
"open",
"(",
"recovery_file",
")",
"as",
"rf",
":",
"recovery_data",
"=",
... | 42.125 | 20.75 |
def swap_buffers(self):
"""
Headless window currently don't support double buffering.
We only increment the frame counter here.
"""
self.frames += 1
if self.headless_frames and self.frames >= self.headless_frames:
self.close() | [
"def",
"swap_buffers",
"(",
"self",
")",
":",
"self",
".",
"frames",
"+=",
"1",
"if",
"self",
".",
"headless_frames",
"and",
"self",
".",
"frames",
">=",
"self",
".",
"headless_frames",
":",
"self",
".",
"close",
"(",
")"
] | 31 | 17.222222 |
def split_lines(tokenlist):
"""
Take a single list of (Token, text) tuples and yield one such list for each
line. Just like str.split, this will yield at least one item.
:param tokenlist: List of (token, text) or (token, text, mouse_handler)
tuples.
"""
line = []
for ... | [
"def",
"split_lines",
"(",
"tokenlist",
")",
":",
"line",
"=",
"[",
"]",
"for",
"item",
"in",
"tokenlist",
":",
"# For (token, text) tuples.",
"if",
"len",
"(",
"item",
")",
"==",
"2",
":",
"token",
",",
"string",
"=",
"item",
"parts",
"=",
"string",
"... | 34.847826 | 21.456522 |
def modify(self, fd, eventmask):
"""
Change the bit-mask of events associated with a previously-registered
descriptor.
:param fd:
The descriptor to modify.
:param eventmask:
New bit-mask of events that will be monitored.
:raises ValueError:
... | [
"def",
"modify",
"(",
"self",
",",
"fd",
",",
"eventmask",
")",
":",
"if",
"self",
".",
"_epfd",
"<",
"0",
":",
"_err_closed",
"(",
")",
"ev",
"=",
"epoll_event",
"(",
")",
"ev",
".",
"events",
"=",
"eventmask",
"ev",
".",
"data",
".",
"fd",
"=",... | 32.761905 | 15.52381 |
def ensure_topic(self):
"""Verify the pub/sub topic exists.
Returns the topic qualified name.
"""
client = self.session.client('pubsub', 'v1', 'projects.topics')
topic = self.get_topic_param()
try:
client.execute_command('get', {'topic': topic})
excep... | [
"def",
"ensure_topic",
"(",
"self",
")",
":",
"client",
"=",
"self",
".",
"session",
".",
"client",
"(",
"'pubsub'",
",",
"'v1'",
",",
"'projects.topics'",
")",
"topic",
"=",
"self",
".",
"get_topic_param",
"(",
")",
"try",
":",
"client",
".",
"execute_c... | 33.157895 | 18.526316 |
def Ctrl_W(self, delay=0):
"""Ctrl + W shortcut.
"""
self._delay(delay)
self.add(Command("KeyDown", 'KeyDown "%s", %s' % (BoardKey.Ctrl, 1)))
self.add(Command("KeyPress", 'KeyPress "%s", %s' % (BoardKey.W, 1)))
self.add(Command("KeyUp", 'KeyUp "%s", %s' % (BoardKey.Ctrl, ... | [
"def",
"Ctrl_W",
"(",
"self",
",",
"delay",
"=",
"0",
")",
":",
"self",
".",
"_delay",
"(",
"delay",
")",
"self",
".",
"add",
"(",
"Command",
"(",
"\"KeyDown\"",
",",
"'KeyDown \"%s\", %s'",
"%",
"(",
"BoardKey",
".",
"Ctrl",
",",
"1",
")",
")",
")... | 45.428571 | 19.142857 |
def create_effect(self, label: str, name: str, *args, **kwargs) -> Effect:
"""
Create an effect instance adding it to the internal effects dictionary using the label as key.
Args:
label (str): The unique label for the effect instance
name (str): Name or full python... | [
"def",
"create_effect",
"(",
"self",
",",
"label",
":",
"str",
",",
"name",
":",
"str",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"Effect",
":",
"effect_cls",
"=",
"effects",
".",
"find_effect_class",
"(",
"name",
")",
"effect",
"=",
"eff... | 38.26087 | 25.043478 |
def _log_to_file(self, etype, source, msg='', target='', hostmask='', params=''):
"""Override `log()` if bot is not initialized with a database
connection. Do not call this method directly.
"""
today = datetime.utcnow()
# TODO: Use self.locale['timezone'] for changing time
... | [
"def",
"_log_to_file",
"(",
"self",
",",
"etype",
",",
"source",
",",
"msg",
"=",
"''",
",",
"target",
"=",
"''",
",",
"hostmask",
"=",
"''",
",",
"params",
"=",
"''",
")",
":",
"today",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"# TODO: Use self.loc... | 45.391304 | 17.73913 |
def _inherit_parent_kwargs(self, kwargs):
"""Extract any necessary attributes from parent serializer to
propagate down to child serializer.
"""
if not self.parent or not self._is_dynamic:
return kwargs
if 'request_fields' not in kwargs:
# If 'request_fie... | [
"def",
"_inherit_parent_kwargs",
"(",
"self",
",",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"parent",
"or",
"not",
"self",
".",
"_is_dynamic",
":",
"return",
"kwargs",
"if",
"'request_fields'",
"not",
"in",
"kwargs",
":",
"# If 'request_fields' isn't explic... | 36.678571 | 17.178571 |
async def listen_notifications(self, fallback_callback=None):
"""Listen for notifications from the device forever.
Use :func:on_notification: to register what notifications to listen to.
"""
tasks = []
async def handle_notification(notification):
if type(notificatio... | [
"async",
"def",
"listen_notifications",
"(",
"self",
",",
"fallback_callback",
"=",
"None",
")",
":",
"tasks",
"=",
"[",
"]",
"async",
"def",
"handle_notification",
"(",
"notification",
")",
":",
"if",
"type",
"(",
"notification",
")",
"not",
"in",
"self",
... | 38.21875 | 20.375 |
def binary(self):
"""Returns the binary that builds the pex for this lambda."""
dependencies = self.dependencies
if len(dependencies) != 1:
raise TargetDefinitionException(self, 'An app must define exactly one binary '
'dependency, have: {}'.format(dependenc... | [
"def",
"binary",
"(",
"self",
")",
":",
"dependencies",
"=",
"self",
".",
"dependencies",
"if",
"len",
"(",
"dependencies",
")",
"!=",
"1",
":",
"raise",
"TargetDefinitionException",
"(",
"self",
",",
"'An app must define exactly one binary '",
"'dependency, have: {... | 52.909091 | 23.727273 |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'cell_id') and self.cell_id is not None:
_dict['cell_id'] = self.cell_id
if hasattr(self, 'location') and self.location is not None:
_dict['location'] = self.lo... | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'cell_id'",
")",
"and",
"self",
".",
"cell_id",
"is",
"not",
"None",
":",
"_dict",
"[",
"'cell_id'",
"]",
"=",
"self",
".",
"cell_id",
"if",
"hasa... | 48.681818 | 20.181818 |
def inherit_doc(cls):
"""
A decorator that makes a class inherit documentation from its parents.
"""
for name, func in vars(cls).items():
# only inherit docstring for public functions
if name.startswith("_"):
continue
if not func.__doc__:
for parent in cls... | [
"def",
"inherit_doc",
"(",
"cls",
")",
":",
"for",
"name",
",",
"func",
"in",
"vars",
"(",
"cls",
")",
".",
"items",
"(",
")",
":",
"# only inherit docstring for public functions",
"if",
"name",
".",
"startswith",
"(",
"\"_\"",
")",
":",
"continue",
"if",
... | 36.333333 | 14.066667 |
def read_core_state_eigen(self):
"""
Read the core state eigenenergies at each ionic step.
Returns:
A list of dict over the atom such as [{"AO":[core state eig]}].
The core state eigenenergie list for each AO is over all ionic
step.
Example:
... | [
"def",
"read_core_state_eigen",
"(",
"self",
")",
":",
"with",
"zopen",
"(",
"self",
".",
"filename",
",",
"\"rt\"",
")",
"as",
"foutcar",
":",
"line",
"=",
"foutcar",
".",
"readline",
"(",
")",
"while",
"line",
"!=",
"\"\"",
":",
"line",
"=",
"foutcar... | 44.75 | 19.25 |
def list_subadressen_by_huisnummer(self, huisnummer):
'''
List all `subadressen` for a :class:`Huisnummer`.
:param huisnummer: The :class:`Huisnummer` for which the \
`subadressen` are wanted. OR A huisnummer id.
:rtype: A :class:`list` of :class:`Gebouw`
'''
... | [
"def",
"list_subadressen_by_huisnummer",
"(",
"self",
",",
"huisnummer",
")",
":",
"try",
":",
"id",
"=",
"huisnummer",
".",
"id",
"except",
"AttributeError",
":",
"id",
"=",
"huisnummer",
"def",
"creator",
"(",
")",
":",
"res",
"=",
"crab_gateway_request",
... | 34.484848 | 17.636364 |
def _inclusiveNamespacePrefixes(node, context, unsuppressedPrefixes):
'''http://www.w3.org/TR/xml-exc-c14n/
InclusiveNamespaces PrefixList parameter, which lists namespace prefixes that
are handled in the manner described by the Canonical XML Recommendation'''
inclusive = []
if node.prefix:
... | [
"def",
"_inclusiveNamespacePrefixes",
"(",
"node",
",",
"context",
",",
"unsuppressedPrefixes",
")",
":",
"inclusive",
"=",
"[",
"]",
"if",
"node",
".",
"prefix",
":",
"usedPrefixes",
"=",
"[",
"'xmlns:%s'",
"%",
"node",
".",
"prefix",
"]",
"else",
":",
"u... | 37.965517 | 17.827586 |
def GET_AUTH(self, courseid, f=None, t=None): # pylint: disable=arguments-differ
""" GET request """
course, __ = self.get_course_and_check_rights(courseid)
tasks = course.get_tasks()
now = datetime.now().replace(minute=0, second=0, microsecond=0)
error = None
if f == N... | [
"def",
"GET_AUTH",
"(",
"self",
",",
"courseid",
",",
"f",
"=",
"None",
",",
"t",
"=",
"None",
")",
":",
"# pylint: disable=arguments-differ",
"course",
",",
"__",
"=",
"self",
".",
"get_course_and_check_rights",
"(",
"courseid",
")",
"tasks",
"=",
"course",... | 44.857143 | 26.809524 |
def end_date(self):
"""账户的交易结束日期(只在回测中使用)
Raises:
RuntimeWarning -- [description]
Returns:
[type] -- [description]
"""
if self.start_==None:
if len(self.time_index_max) > 0:
return str(max(self.time_index_max))[0:10]
... | [
"def",
"end_date",
"(",
"self",
")",
":",
"if",
"self",
".",
"start_",
"==",
"None",
":",
"if",
"len",
"(",
"self",
".",
"time_index_max",
")",
">",
"0",
":",
"return",
"str",
"(",
"max",
"(",
"self",
".",
"time_index_max",
")",
")",
"[",
"0",
":... | 26.2 | 17.5 |
def get_music_service_information(self, search_type, search, start=0,
max_items=100):
"""Search for music service information items.
:param search_type: The type of search to perform, possible values are:
'artists', 'albums', 'tracks' and 'playlists'
... | [
"def",
"get_music_service_information",
"(",
"self",
",",
"search_type",
",",
"search",
",",
"start",
"=",
"0",
",",
"max_items",
"=",
"100",
")",
":",
"# Check input",
"if",
"search_type",
"not",
"in",
"[",
"'artists'",
",",
"'albums'",
",",
"'tracks'",
","... | 41.734694 | 19.959184 |
def exchange(self, send_data, timeout):
"""Exchange data with an activated target (*send_data* is a command
frame) or as an activated target (*send_data* is a response
frame). Returns a target response frame (if data is send to an
activated target) or a next command frame (if data is sen... | [
"def",
"exchange",
"(",
"self",
",",
"send_data",
",",
"timeout",
")",
":",
"with",
"self",
".",
"lock",
":",
"if",
"self",
".",
"device",
"is",
"None",
":",
"raise",
"IOError",
"(",
"errno",
".",
"ENODEV",
",",
"os",
".",
"strerror",
"(",
"errno",
... | 45.212121 | 21.757576 |
def decrop_image(cropped_image, full_image):
"""
The inverse function for `ants.crop_image`
ANTsR function: `decropImage`
Arguments
---------
cropped_image : ANTsImage
cropped image
full_image : ANTsImage
image in which the cropped image will be put back
Returns
... | [
"def",
"decrop_image",
"(",
"cropped_image",
",",
"full_image",
")",
":",
"inpixeltype",
"=",
"'float'",
"if",
"cropped_image",
".",
"pixeltype",
"!=",
"'float'",
":",
"inpixeltype",
"=",
"cropped_image",
".",
"pixeltype",
"cropped_image",
"=",
"cropped_image",
".... | 30.190476 | 20.047619 |
def log(self, message, level=None):
"""Log message, optionally providing a logging level
It is compatible with StreamParse API.
:type message: str
:param message: the log message to send
:type level: str
:param level: the logging level,
one of: trace (=debug), debug, info, wa... | [
"def",
"log",
"(",
"self",
",",
"message",
",",
"level",
"=",
"None",
")",
":",
"if",
"level",
"is",
"None",
":",
"_log_level",
"=",
"logging",
".",
"INFO",
"else",
":",
"if",
"level",
"==",
"\"trace\"",
"or",
"level",
"==",
"\"debug\"",
":",
"_log_l... | 30.730769 | 15.692308 |
def _offset_from_spaces(dom, ran):
"""Return index offset corresponding to given spaces."""
affected = np.not_equal(dom.shape, ran.shape)
diff_l = np.abs(ran.grid.min() - dom.grid.min())
offset_float = diff_l / dom.cell_sides
offset = np.around(offset_float).astype(int)
for i in range(dom.ndim):... | [
"def",
"_offset_from_spaces",
"(",
"dom",
",",
"ran",
")",
":",
"affected",
"=",
"np",
".",
"not_equal",
"(",
"dom",
".",
"shape",
",",
"ran",
".",
"shape",
")",
"diff_l",
"=",
"np",
".",
"abs",
"(",
"ran",
".",
"grid",
".",
"min",
"(",
")",
"-",... | 49.846154 | 15.692308 |
def _draw_fold_indicator(self, top, mouse_over, collapsed, painter):
"""
Draw the fold indicator/trigger (arrow).
:param top: Top position
:param mouse_over: Whether the mouse is over the indicator
:param collapsed: Whether the trigger is collapsed or not.
:param painter... | [
"def",
"_draw_fold_indicator",
"(",
"self",
",",
"top",
",",
"mouse_over",
",",
"collapsed",
",",
"painter",
")",
":",
"rect",
"=",
"QRect",
"(",
"0",
",",
"top",
",",
"self",
".",
"sizeHint",
"(",
")",
".",
"width",
"(",
")",
",",
"self",
".",
"si... | 39.5 | 14.833333 |
def filter_report(self, filt=None, analytes=None, savedir=None, nbin=5):
"""
Visualise effect of data filters.
Parameters
----------
filt : str
Exact or partial name of filter to plot. Supports
partial matching. i.e. if 'cluster' is specified, all
... | [
"def",
"filter_report",
"(",
"self",
",",
"filt",
"=",
"None",
",",
"analytes",
"=",
"None",
",",
"savedir",
"=",
"None",
",",
"nbin",
"=",
"5",
")",
":",
"return",
"plot",
".",
"filter_report",
"(",
"self",
",",
"filt",
",",
"analytes",
",",
"savedi... | 30.761905 | 19.047619 |
def which_bin(exes):
'''
Decorator wrapper for salt.utils.path.which_bin
'''
def wrapper(function):
def wrapped(*args, **kwargs):
if salt.utils.path.which_bin(exes) is None:
raise CommandNotFoundError(
'None of provided binaries({0}) was not found ... | [
"def",
"which_bin",
"(",
"exes",
")",
":",
"def",
"wrapper",
"(",
"function",
")",
":",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"salt",
".",
"utils",
".",
"path",
".",
"which_bin",
"(",
"exes",
")",
"is",
"Non... | 36 | 17 |
def parse_hashes(self):
# type: () -> None
"""
Parse hashes from *self.line* and set them on the current object.
:returns: Nothing
:rtype: None
"""
line, hashes = self.split_hashes(self.line)
self.hashes = hashes
self.line = line | [
"def",
"parse_hashes",
"(",
"self",
")",
":",
"# type: () -> None",
"line",
",",
"hashes",
"=",
"self",
".",
"split_hashes",
"(",
"self",
".",
"line",
")",
"self",
".",
"hashes",
"=",
"hashes",
"self",
".",
"line",
"=",
"line"
] | 26.545455 | 16.181818 |
def replace(self, year=None, month=None, day=None, hour=None, minute=None,
second=None, microsecond=None, tzinfo=None):
"""
Returns a new datetime.datetime or asn1crypto.util.extended_datetime
object with the specified components replaced
:return:
A datetime.... | [
"def",
"replace",
"(",
"self",
",",
"year",
"=",
"None",
",",
"month",
"=",
"None",
",",
"day",
"=",
"None",
",",
"hour",
"=",
"None",
",",
"minute",
"=",
"None",
",",
"second",
"=",
"None",
",",
"microsecond",
"=",
"None",
",",
"tzinfo",
"=",
"N... | 26.214286 | 19.071429 |
def decode(vol, filename, content):
"""Decode content according to settings in a cloudvolume instance."""
bbox = Bbox.from_filename(filename)
content_len = len(content) if content is not None else 0
if not content:
if vol.fill_missing:
content = ''
else:
raise EmptyVolumeException(filename)... | [
"def",
"decode",
"(",
"vol",
",",
"filename",
",",
"content",
")",
":",
"bbox",
"=",
"Bbox",
".",
"from_filename",
"(",
"filename",
")",
"content_len",
"=",
"len",
"(",
"content",
")",
"if",
"content",
"is",
"not",
"None",
"else",
"0",
"if",
"not",
"... | 27.64 | 20.08 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.