text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def _configure_logger(cls, simple_name, log_dest, detail_level,
log_filename, connection, propagate):
# pylint: disable=line-too-long
"""
Configure the pywbem loggers and optionally activate WBEM connections
for logging and setting a log detail level.
P... | [
"def",
"_configure_logger",
"(",
"cls",
",",
"simple_name",
",",
"log_dest",
",",
"detail_level",
",",
"log_filename",
",",
"connection",
",",
"propagate",
")",
":",
"# pylint: disable=line-too-long",
"# noqa: E501",
"# pylint: enable=line-too-long",
"if",
"simple_name",
... | 43.764706 | 26.372549 |
def get_success_url(self):
"""Reverses the ``redis_metric_aggregate_detail`` URL using
``self.metric_slugs`` as an argument."""
slugs = '+'.join(self.metric_slugs)
url = reverse('redis_metric_aggregate_detail', args=[slugs])
# Django 1.6 quotes reversed URLs, which changes + into... | [
"def",
"get_success_url",
"(",
"self",
")",
":",
"slugs",
"=",
"'+'",
".",
"join",
"(",
"self",
".",
"metric_slugs",
")",
"url",
"=",
"reverse",
"(",
"'redis_metric_aggregate_detail'",
",",
"args",
"=",
"[",
"slugs",
"]",
")",
"# Django 1.6 quotes reversed URL... | 57.444444 | 17.111111 |
def parse_loops_file(self, contents, ignore_whitespace = True, ignore_errors = False):
'''This parser is forgiving and allows leading whitespace.'''
for l in [l for l in contents.strip().split('\n') if l]:
try:
if ignore_whitespace:
l = l.strip()
... | [
"def",
"parse_loops_file",
"(",
"self",
",",
"contents",
",",
"ignore_whitespace",
"=",
"True",
",",
"ignore_errors",
"=",
"False",
")",
":",
"for",
"l",
"in",
"[",
"l",
"for",
"l",
"in",
"contents",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'\\n'",
... | 44 | 18.705882 |
def add_user_to_group(iam_client, user, group, quiet = False):
"""
Add an IAM user to an IAM group
:param iam_client:
:param group:
:param user:
:param user_info:
:param dry_run:
:return:
"""
if not quiet:
printInfo('Adding user to group %s...' % group)
iam_client.ad... | [
"def",
"add_user_to_group",
"(",
"iam_client",
",",
"user",
",",
"group",
",",
"quiet",
"=",
"False",
")",
":",
"if",
"not",
"quiet",
":",
"printInfo",
"(",
"'Adding user to group %s...'",
"%",
"group",
")",
"iam_client",
".",
"add_user_to_group",
"(",
"GroupN... | 25.571429 | 19 |
def getDBusEnvEndpoints(reactor, client=True):
"""
Creates endpoints from the DBUS_SESSION_BUS_ADDRESS environment variable
@rtype: C{list} of L{twisted.internet.interfaces.IStreamServerEndpoint}
@returns: A list of endpoint instances
"""
env = os.environ.get('DBUS_SESSION_BUS_ADDRESS', None)
... | [
"def",
"getDBusEnvEndpoints",
"(",
"reactor",
",",
"client",
"=",
"True",
")",
":",
"env",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'DBUS_SESSION_BUS_ADDRESS'",
",",
"None",
")",
"if",
"env",
"is",
"None",
":",
"raise",
"Exception",
"(",
"'DBus Session... | 37.25 | 19.583333 |
def value(self):
""" Return the broadcasted value
"""
if not hasattr(self, "_value") and self._path is not None:
self._value = self._load(self._path)
return self._value | [
"def",
"value",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"_value\"",
")",
"and",
"self",
".",
"_path",
"is",
"not",
"None",
":",
"self",
".",
"_value",
"=",
"self",
".",
"_load",
"(",
"self",
".",
"_path",
")",
"return",
... | 34.5 | 12 |
def update(self, pbar):
"""Updates the widget with the current NIST/SI speed.
Basically, this calculates the average rate of update and figures out
how to make a "pretty" prefix unit"""
if pbar.seconds_elapsed < 2e-6 or pbar.currval < 2e-6:
scaled = bitmath.Byte()
else:
... | [
"def",
"update",
"(",
"self",
",",
"pbar",
")",
":",
"if",
"pbar",
".",
"seconds_elapsed",
"<",
"2e-6",
"or",
"pbar",
".",
"currval",
"<",
"2e-6",
":",
"scaled",
"=",
"bitmath",
".",
"Byte",
"(",
")",
"else",
":",
"speed",
"=",
"pbar",
".",
"currva... | 36 | 20.615385 |
def _GroupActions(action,group,alias,location):
"""Applies group level actions.
:param action: the server action url to exec against
:param group: group name
:param alias: short code for a particular account. If none will use account's default alias
:param location: datacenter location. If none will use ac... | [
"def",
"_GroupActions",
"(",
"action",
",",
"group",
",",
"alias",
",",
"location",
")",
":",
"if",
"alias",
"is",
"None",
":",
"alias",
"=",
"clc",
".",
"v1",
".",
"Account",
".",
"GetAlias",
"(",
")",
"if",
"location",
"is",
"None",
":",
"location"... | 45.357143 | 25.928571 |
def update_exc(exc, msg, before=True, separator="\n"):
"""
Adds additional text to an exception's error message.
The new text will be added before the existing text by default; to append
it after the original text, pass False to the `before` parameter.
By default the old and new text will be separ... | [
"def",
"update_exc",
"(",
"exc",
",",
"msg",
",",
"before",
"=",
"True",
",",
"separator",
"=",
"\"\\n\"",
")",
":",
"emsg",
"=",
"exc",
".",
"message",
"if",
"before",
":",
"parts",
"=",
"(",
"msg",
",",
"separator",
",",
"emsg",
")",
"else",
":",... | 33.85 | 19.85 |
def unique_email_validator(form, field):
""" Username must be unique. This validator may NOT be customized."""
user_manager = current_app.user_manager
if not user_manager.email_is_available(field.data):
raise ValidationError(_('This Email is already in use. Please try another one.')) | [
"def",
"unique_email_validator",
"(",
"form",
",",
"field",
")",
":",
"user_manager",
"=",
"current_app",
".",
"user_manager",
"if",
"not",
"user_manager",
".",
"email_is_available",
"(",
"field",
".",
"data",
")",
":",
"raise",
"ValidationError",
"(",
"_",
"(... | 60.2 | 13.6 |
def zmeshgrid(d):
"""
Returns a meshgrid like np.meshgrid but in z-order
:param d: you'll get 4**d nodes in meshgrid
:return: xx, yy in z-order
"""
lin = xfun(2, d)
one = ones(2, d)
xx = zkronv(lin, one)
yy = zkronv(one, lin)
return xx, yy | [
"def",
"zmeshgrid",
"(",
"d",
")",
":",
"lin",
"=",
"xfun",
"(",
"2",
",",
"d",
")",
"one",
"=",
"ones",
"(",
"2",
",",
"d",
")",
"xx",
"=",
"zkronv",
"(",
"lin",
",",
"one",
")",
"yy",
"=",
"zkronv",
"(",
"one",
",",
"lin",
")",
"return",
... | 20.692308 | 17.461538 |
def add_expect_string_healthcheck(self, expect_string):
"""Inserts a new healthckeck_expect with only expect_string.
:param expect_string: expect_string.
:return: Dictionary with the following structure:
::
{'healthcheck_expect': {'id': < id >}}
:raise InvalidPa... | [
"def",
"add_expect_string_healthcheck",
"(",
"self",
",",
"expect_string",
")",
":",
"healthcheck_map",
"=",
"dict",
"(",
")",
"healthcheck_map",
"[",
"'expect_string'",
"]",
"=",
"expect_string",
"url",
"=",
"'healthcheckexpect/add/expect_string/'",
"code",
",",
"xml... | 36.037037 | 28.555556 |
def export(self):
"""Returns requirements XML."""
top = self._top_element()
properties = self._properties_element(top)
self._fill_requirements(top)
self._fill_lookup_prop(properties)
return utils.prettify_xml(top) | [
"def",
"export",
"(",
"self",
")",
":",
"top",
"=",
"self",
".",
"_top_element",
"(",
")",
"properties",
"=",
"self",
".",
"_properties_element",
"(",
"top",
")",
"self",
".",
"_fill_requirements",
"(",
"top",
")",
"self",
".",
"_fill_lookup_prop",
"(",
... | 36.428571 | 6.857143 |
def setViewsFromUiAutomatorDump(self, received):
'''
Sets L{self.views} to the received value parsing the received XML.
@type received: str
@param received: the string received from the I{UI Automator}
'''
if not received or received == "":
raise ValueError(... | [
"def",
"setViewsFromUiAutomatorDump",
"(",
"self",
",",
"received",
")",
":",
"if",
"not",
"received",
"or",
"received",
"==",
"\"\"",
":",
"raise",
"ValueError",
"(",
"\"received is empty\"",
")",
"self",
".",
"views",
"=",
"[",
"]",
"''' The list of Views repr... | 44.466667 | 29.933333 |
def lonlat2xyz(lon, lat):
"""
Convert lon / lat (radians) for the spherical triangulation into x,y,z
on the unit sphere
"""
lons = np.array(lon)
lats = np.array(lat)
xs = np.cos(lats) * np.cos(lons)
ys = np.cos(lats) * np.sin(lons)
zs = np.sin(lats)
return xs, ys, zs | [
"def",
"lonlat2xyz",
"(",
"lon",
",",
"lat",
")",
":",
"lons",
"=",
"np",
".",
"array",
"(",
"lon",
")",
"lats",
"=",
"np",
".",
"array",
"(",
"lat",
")",
"xs",
"=",
"np",
".",
"cos",
"(",
"lats",
")",
"*",
"np",
".",
"cos",
"(",
"lons",
")... | 21.214286 | 18.928571 |
def sync_resources():
"""Sync the client's resources with the Lastuser server"""
print("Syncing resources with Lastuser...")
resources = manager.app.lastuser.sync_resources()['results']
for rname, resource in six.iteritems(resources):
if resource['status'] == 'error':
print("Error f... | [
"def",
"sync_resources",
"(",
")",
":",
"print",
"(",
"\"Syncing resources with Lastuser...\"",
")",
"resources",
"=",
"manager",
".",
"app",
".",
"lastuser",
".",
"sync_resources",
"(",
")",
"[",
"'results'",
"]",
"for",
"rname",
",",
"resource",
"in",
"six",... | 48.25 | 21 |
def last_activity_time(self):
"""获取用户最后一次活动的时间
:return: 用户最后一次活动的时间,返回值为 unix 时间戳
:rtype: int
"""
self._make_soup()
act = self.soup.find(
'div', class_='zm-profile-section-item zm-item clearfix')
return int(act['data-time']) if act is not None else -1 | [
"def",
"last_activity_time",
"(",
"self",
")",
":",
"self",
".",
"_make_soup",
"(",
")",
"act",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'div'",
",",
"class_",
"=",
"'zm-profile-section-item zm-item clearfix'",
")",
"return",
"int",
"(",
"act",
"[",
"'... | 31.1 | 15.2 |
def load_preseed():
""" Update JobPriority information from preseed.json
The preseed data has these fields: buildtype, testtype, platform, priority, expiration_date
The expiration_date field defaults to 2 weeks when inserted in the table
The expiration_date field has the format "YYYY-MM-DD", however, i... | [
"def",
"load_preseed",
"(",
")",
":",
"if",
"not",
"JobPriority",
".",
"objects",
".",
"exists",
"(",
")",
":",
"return",
"preseed",
"=",
"preseed_data",
"(",
")",
"for",
"job",
"in",
"preseed",
":",
"queryset",
"=",
"JobPriority",
".",
"objects",
".",
... | 43.357143 | 25.535714 |
def clear_further_steps(self):
"""Clear all further steps in order to properly calculate the prev step
"""
self.parent.step_kw_layermode.lstLayerModes.clear()
self.parent.step_kw_unit.lstUnits.clear()
self.parent.step_kw_field.lstFields.clear()
self.parent.step_kw_classif... | [
"def",
"clear_further_steps",
"(",
"self",
")",
":",
"self",
".",
"parent",
".",
"step_kw_layermode",
".",
"lstLayerModes",
".",
"clear",
"(",
")",
"self",
".",
"parent",
".",
"step_kw_unit",
".",
"lstUnits",
".",
"clear",
"(",
")",
"self",
".",
"parent",
... | 49.714286 | 11.142857 |
def stepfun(n, d=None, center=1, direction=1):
""" Create TT-vector for Heaviside step function :math:`\chi(x - x_0)`.
Heaviside step function is defined as
.. math::
\chi(x) = \\left\{ \\begin{array}{l} 1 \mbox{ when } x \ge 0, \\\\ 0 \mbox{ when } x < 0. \\end{array} \\right.
For negative ... | [
"def",
"stepfun",
"(",
"n",
",",
"d",
"=",
"None",
",",
"center",
"=",
"1",
",",
"direction",
"=",
"1",
")",
":",
"if",
"isinstance",
"(",
"n",
",",
"six",
".",
"integer_types",
")",
":",
"n",
"=",
"[",
"n",
"]",
"if",
"d",
"is",
"None",
":",... | 29.688172 | 17.548387 |
def send_vdp_port_event_internal(self, port_uuid, mac, net_uuid,
segmentation_id, status, oui):
"""Send vNIC UP/Down event to VDP.
:param port_uuid: a ovslib.VifPort object.
:mac: MAC address of the VNIC
:param net_uuid: the net_uuid this port is to ... | [
"def",
"send_vdp_port_event_internal",
"(",
"self",
",",
"port_uuid",
",",
"mac",
",",
"net_uuid",
",",
"segmentation_id",
",",
"status",
",",
"oui",
")",
":",
"lldpad_port",
"=",
"self",
".",
"lldpad_info",
"if",
"not",
"lldpad_port",
":",
"fail_reason",
"=",... | 51.361111 | 21.888889 |
def single_random_manipulation_low(molecule, manipulations):
"""Return a randomized copy of the molecule, without the nonbond check."""
manipulation = sample(manipulations, 1)[0]
coordinates = molecule.coordinates.copy()
transformation = manipulation.apply(coordinates)
return molecule.copy_with(coo... | [
"def",
"single_random_manipulation_low",
"(",
"molecule",
",",
"manipulations",
")",
":",
"manipulation",
"=",
"sample",
"(",
"manipulations",
",",
"1",
")",
"[",
"0",
"]",
"coordinates",
"=",
"molecule",
".",
"coordinates",
".",
"copy",
"(",
")",
"transformat... | 50.142857 | 16.142857 |
def _query_filter(search, urlkwargs, definitions):
"""Ingest query filter in query."""
filters, urlkwargs = _create_filter_dsl(urlkwargs, definitions)
for filter_ in filters:
search = search.filter(filter_)
return (search, urlkwargs) | [
"def",
"_query_filter",
"(",
"search",
",",
"urlkwargs",
",",
"definitions",
")",
":",
"filters",
",",
"urlkwargs",
"=",
"_create_filter_dsl",
"(",
"urlkwargs",
",",
"definitions",
")",
"for",
"filter_",
"in",
"filters",
":",
"search",
"=",
"search",
".",
"f... | 31.5 | 17.625 |
def snapshots_to_send(source_snaps, dest_snaps):
"""return pair of snapshots"""
if len(source_snaps) == 0:
raise AssertionError("No snapshots exist locally!")
if len(dest_snaps) == 0:
# nothing on the remote side, send everything
return None, source_snaps[-1]
last_remote = dest_s... | [
"def",
"snapshots_to_send",
"(",
"source_snaps",
",",
"dest_snaps",
")",
":",
"if",
"len",
"(",
"source_snaps",
")",
"==",
"0",
":",
"raise",
"AssertionError",
"(",
"\"No snapshots exist locally!\"",
")",
"if",
"len",
"(",
"dest_snaps",
")",
"==",
"0",
":",
... | 45.714286 | 12.714286 |
def delete(self):
"""
Removes a container that was created earlier.
"""
if not self.is_created():
LOG.debug("Container was not created. Skipping deletion")
return
try:
self.docker_client.containers\
.get(self.id)\
... | [
"def",
"delete",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_created",
"(",
")",
":",
"LOG",
".",
"debug",
"(",
"\"Container was not created. Skipping deletion\"",
")",
"return",
"try",
":",
"self",
".",
"docker_client",
".",
"containers",
".",
"get... | 36.76 | 20.44 |
def follow_topic(kafka_class, name, retry_interval=1, **kafka_init):
"""Dump each message from kafka topic to stdio."""
while True:
try:
client = kafka_class(**kafka_init)
topic = client.topics[name]
consumer = topic.get_simple_consumer(reset_offset_on_start=True)
... | [
"def",
"follow_topic",
"(",
"kafka_class",
",",
"name",
",",
"retry_interval",
"=",
"1",
",",
"*",
"*",
"kafka_init",
")",
":",
"while",
"True",
":",
"try",
":",
"client",
"=",
"kafka_class",
"(",
"*",
"*",
"kafka_init",
")",
"topic",
"=",
"client",
".... | 34.653846 | 14.961538 |
def convertPossibleValues(val, possibleValues, invalidDefault, emptyValue=''):
'''
convertPossibleValues - Convert input value to one of several possible values,
with a default for invalid entries
@param val <None/str> - The input value
... | [
"def",
"convertPossibleValues",
"(",
"val",
",",
"possibleValues",
",",
"invalidDefault",
",",
"emptyValue",
"=",
"''",
")",
":",
"from",
".",
"utils",
"import",
"tostr",
"# If null, retain null",
"if",
"val",
"is",
"None",
":",
"if",
"emptyValue",
"is",
"EMPT... | 32.844444 | 28.711111 |
def f_get_range(self, copy=True):
"""Returns a python iterable containing the exploration range.
:param copy:
If the range should be copied before handed over to avoid tempering with data
Example usage:
>>> param = Parameter('groupA.groupB.myparam',data=22, comment='I am ... | [
"def",
"f_get_range",
"(",
"self",
",",
"copy",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"f_has_range",
"(",
")",
":",
"raise",
"TypeError",
"(",
"'Your parameter `%s` is not array, so cannot return array.'",
"%",
"self",
".",
"v_full_name",
")",
"elif",... | 31.75 | 22.875 |
def update_asset(self, asset_form=None):
"""Updates an existing asset.
:param asset_form: the form containing the elements to be updated
:type asset_form: ``osid.repository.AssetForm``
:raise: ``IllegalState`` -- ``asset_form`` already used in anupdate transaction
:raise: ``Inva... | [
"def",
"update_asset",
"(",
"self",
",",
"asset_form",
"=",
"None",
")",
":",
"if",
"asset_form",
"is",
"None",
":",
"raise",
"NullArgument",
"(",
")",
"if",
"not",
"isinstance",
"(",
"asset_form",
",",
"abc_repository_objects",
".",
"AssetForm",
")",
":",
... | 48.216216 | 23.891892 |
def button_with_label(self, description, assistants=None):
"""
Function creates a button with lave.
If assistant is specified then text is aligned
"""
btn = self.create_button()
label = self.create_label(description)
if assistants is not None:
... | [
"def",
"button_with_label",
"(",
"self",
",",
"description",
",",
"assistants",
"=",
"None",
")",
":",
"btn",
"=",
"self",
".",
"create_button",
"(",
")",
"label",
"=",
"self",
".",
"create_label",
"(",
"description",
")",
"if",
"assistants",
"is",
"not",
... | 37.842105 | 13.105263 |
def retry(time_unit, multiplier, backoff_coefficient, max_delay, max_attempts, expiration_duration, enable_jitter):
"""
The retry function will keep retrying `task_to_try` until either:
(1) it returns None, then retry() finishes
(2) `max_attempts` is reached, then retry() raises an exception.
(3) if... | [
"def",
"retry",
"(",
"time_unit",
",",
"multiplier",
",",
"backoff_coefficient",
",",
"max_delay",
",",
"max_attempts",
",",
"expiration_duration",
",",
"enable_jitter",
")",
":",
"def",
"deco_retry",
"(",
"task_to_try",
")",
":",
"@",
"wraps",
"(",
"task_to_try... | 45.928571 | 29.128571 |
def xi2_from_mass1_mass2_spin2x_spin2y(mass1, mass2, spin2x, spin2y):
"""Returns the effective precession spin argument for the smaller mass.
This function assumes it's given spins of the secondary mass.
"""
q = q_from_mass1_mass2(mass1, mass2)
a1 = 2 + 3 * q / 2
a2 = 2 + 3 / (2 * q)
return ... | [
"def",
"xi2_from_mass1_mass2_spin2x_spin2y",
"(",
"mass1",
",",
"mass2",
",",
"spin2x",
",",
"spin2y",
")",
":",
"q",
"=",
"q_from_mass1_mass2",
"(",
"mass1",
",",
"mass2",
")",
"a1",
"=",
"2",
"+",
"3",
"*",
"q",
"/",
"2",
"a2",
"=",
"2",
"+",
"3",
... | 46.625 | 14.875 |
def list_all_free_shippings(cls, **kwargs):
"""List FreeShippings
Return a list of FreeShippings
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_free_shippings(async=True)
>>>... | [
"def",
"list_all_free_shippings",
"(",
"cls",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_list_all_free_shippings_with_http_info",
... | 37.869565 | 15 |
def run_cmake(arg=""):
"""
Forcing to run cmake
"""
if ds.find_executable('cmake') is None:
print "CMake is required to build zql"
print "Please install cmake version >= 2.8 and re-run setup"
sys.exit(-1)
print "Configuring zql build with CMake.... "
cmake_args = arg
... | [
"def",
"run_cmake",
"(",
"arg",
"=",
"\"\"",
")",
":",
"if",
"ds",
".",
"find_executable",
"(",
"'cmake'",
")",
"is",
"None",
":",
"print",
"\"CMake is required to build zql\"",
"print",
"\"Please install cmake version >= 2.8 and re-run setup\"",
"sys",
".",
"exit",
... | 34 | 16.5 |
def _extract_spi_args(self, **kwargs):
"""
Given a set of keyword arguments, splits it into those relevant to SPI
implementations and all the rest. SPI arguments are augmented with
defaults and converted into the pin format (from the port/device
format) if necessary.
Ret... | [
"def",
"_extract_spi_args",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"dev_defaults",
"=",
"{",
"'port'",
":",
"0",
",",
"'device'",
":",
"0",
",",
"}",
"default_hw",
"=",
"SPI_HARDWARE_PINS",
"[",
"dev_defaults",
"[",
"'port'",
"]",
"]",
"pin_defa... | 39.803279 | 18.590164 |
def get_annotation_data_between_times(self, id_tier, start, end):
"""Gives the annotations within the times.
When the tier contains reference annotations this will be returned,
check :func:`get_ref_annotation_data_between_times` for the format.
:param str id_tier: Name of the tier.
... | [
"def",
"get_annotation_data_between_times",
"(",
"self",
",",
"id_tier",
",",
"start",
",",
"end",
")",
":",
"if",
"self",
".",
"tiers",
"[",
"id_tier",
"]",
"[",
"1",
"]",
":",
"return",
"self",
".",
"get_ref_annotation_data_between_times",
"(",
"id_tier",
... | 50.705882 | 17.705882 |
def rm_rf(path):
"""
Recursively (if needed) delete path.
"""
if os.path.isdir(path) and not os.path.islink(path):
shutil.rmtree(path)
elif os.path.lexists(path):
os.remove(path) | [
"def",
"rm_rf",
"(",
"path",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
"and",
"not",
"os",
".",
"path",
".",
"islink",
"(",
"path",
")",
":",
"shutil",
".",
"rmtree",
"(",
"path",
")",
"elif",
"os",
".",
"path",
".",
... | 25.875 | 9.875 |
def build_filtered_queryset(self, query, **kwargs):
"""
Build and return the fully-filtered queryset
"""
# Take the basic queryset
qs = self.get_queryset()
# filter it via the query conditions
qs = qs.filter(self.get_queryset_filters(query))
return self.bu... | [
"def",
"build_filtered_queryset",
"(",
"self",
",",
"query",
",",
"*",
"*",
"kwargs",
")",
":",
"# Take the basic queryset",
"qs",
"=",
"self",
".",
"get_queryset",
"(",
")",
"# filter it via the query conditions",
"qs",
"=",
"qs",
".",
"filter",
"(",
"self",
... | 39.222222 | 9 |
def send_direct_message_new(self, messageobject):
""" :reference: https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-event.html
"""
headers, post_data = API._buildmessageobject(messageobject)
return bind_api(
api=self,
pa... | [
"def",
"send_direct_message_new",
"(",
"self",
",",
"messageobject",
")",
":",
"headers",
",",
"post_data",
"=",
"API",
".",
"_buildmessageobject",
"(",
"messageobject",
")",
"return",
"bind_api",
"(",
"api",
"=",
"self",
",",
"path",
"=",
"'/direct_messages/eve... | 46 | 12.1 |
def predict_dims(self, q, dims_x, dims_y, dims_out, sigma=None, k=None):
"""Provide a prediction of q in the output space
@param xq an array of float of length dim_x
@param estimated_sigma if False (default), sigma_sq=self.sigma_sq, else it is estimated from the neighbor distances in self._we... | [
"def",
"predict_dims",
"(",
"self",
",",
"q",
",",
"dims_x",
",",
"dims_y",
",",
"dims_out",
",",
"sigma",
"=",
"None",
",",
"k",
"=",
"None",
")",
":",
"assert",
"len",
"(",
"q",
")",
"==",
"len",
"(",
"dims_x",
")",
"+",
"len",
"(",
"dims_y",
... | 40.107143 | 27.642857 |
def check_nearby_preprocessor(impact_function):
"""Checker for the nearby preprocessor.
:param impact_function: Impact function to check.
:type impact_function: ImpactFunction
:return: If the preprocessor can run.
:rtype: bool
"""
hazard_key = layer_purpose_hazard['key']
earthquake_key... | [
"def",
"check_nearby_preprocessor",
"(",
"impact_function",
")",
":",
"hazard_key",
"=",
"layer_purpose_hazard",
"[",
"'key'",
"]",
"earthquake_key",
"=",
"hazard_earthquake",
"[",
"'key'",
"]",
"exposure_key",
"=",
"layer_purpose_exposure",
"[",
"'key'",
"]",
"place_... | 35.882353 | 15.058824 |
def get_kwargs(**kwargs):
"""This method should be used in query functions where user can query on any number of fields
>>> def get_instances(entity_id=NOTSET, my_field=NOTSET):
>>> kwargs = CoyoteDb.get_kwargs(entity_id=entity_id, my_field=my_field)
"""
d = dict()
... | [
"def",
"get_kwargs",
"(",
"*",
"*",
"kwargs",
")",
":",
"d",
"=",
"dict",
"(",
")",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"iteritems",
"(",
")",
":",
"if",
"v",
"is",
"not",
"NOTSET",
":",
"d",
"[",
"k",
"]",
"=",
"v",
"return",
"d"
] | 38.363636 | 18.545455 |
def db(ctx):
"""[GROUP] Database management operations"""
from hfos import database
database.initialize(ctx.obj['dbhost'], ctx.obj['dbname'])
ctx.obj['db'] = database | [
"def",
"db",
"(",
"ctx",
")",
":",
"from",
"hfos",
"import",
"database",
"database",
".",
"initialize",
"(",
"ctx",
".",
"obj",
"[",
"'dbhost'",
"]",
",",
"ctx",
".",
"obj",
"[",
"'dbname'",
"]",
")",
"ctx",
".",
"obj",
"[",
"'db'",
"]",
"=",
"da... | 29.666667 | 18.666667 |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'classifier_id') and self.classifier_id is not None:
_dict['classifier_id'] = self.classifier_id
if hasattr(self, 'url') and self.url is not None:
_dict['url'] ... | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'classifier_id'",
")",
"and",
"self",
".",
"classifier_id",
"is",
"not",
"None",
":",
"_dict",
"[",
"'classifier_id'",
"]",
"=",
"self",
".",
"classif... | 48.8 | 20.1 |
def rename_document(self, old_path, new_path):
"""
Renames an already opened document (this will not rename the file,
just update the file path and tab title).
Use that function to update a file that has been renamed externally.
:param old_path: old path (path of the widget to ... | [
"def",
"rename_document",
"(",
"self",
",",
"old_path",
",",
"new_path",
")",
":",
"to_rename",
"=",
"[",
"]",
"title",
"=",
"os",
".",
"path",
".",
"split",
"(",
"new_path",
")",
"[",
"1",
"]",
"for",
"widget",
"in",
"self",
".",
"widgets",
"(",
"... | 41.727273 | 16.454545 |
def get_permissions_for_registration(self):
"""
Utilised by Wagtail's 'register_permissions' hook to allow permissions
for a model to be assigned to groups in settings. This is only required
if the model isn't a Page model, and isn't registered as a Snippet
"""
from wagta... | [
"def",
"get_permissions_for_registration",
"(",
"self",
")",
":",
"from",
"wagtail",
".",
"wagtailsnippets",
".",
"models",
"import",
"SNIPPET_MODELS",
"if",
"not",
"self",
".",
"is_pagemodel",
"and",
"self",
".",
"model",
"not",
"in",
"SNIPPET_MODELS",
":",
"re... | 54 | 19.8 |
def is_closed(self) -> Optional[bool]:
"""For Magnet Sensor; True if Closed, False if Open."""
if self._device_type is not None and self._device_type == DeviceType.DoorMagnet:
return bool(self._current_status & 0x01)
return None | [
"def",
"is_closed",
"(",
"self",
")",
"->",
"Optional",
"[",
"bool",
"]",
":",
"if",
"self",
".",
"_device_type",
"is",
"not",
"None",
"and",
"self",
".",
"_device_type",
"==",
"DeviceType",
".",
"DoorMagnet",
":",
"return",
"bool",
"(",
"self",
".",
"... | 52 | 16.6 |
def release(version):
"""Tags all submodules for a new release.
Ensures that git tags, as well as the version.py files in each submodule, agree and that the
new version is strictly greater than the current version. Will fail if the new version
is not an increment (following PEP 440). Creates a new git ... | [
"def",
"release",
"(",
"version",
")",
":",
"check_new_version",
"(",
"version",
")",
"set_new_version",
"(",
"version",
")",
"commit_new_version",
"(",
"version",
")",
"set_git_tag",
"(",
"version",
")"
] | 40.909091 | 22.727273 |
def MaskSolve(A, b, w=5, progress=True, niter=None):
'''
Finds the solution `x` to the linear problem
A x = b
for all contiguous `w`-sized masks applied to
the rows and columns of `A` and to the entries
of `b`.
Returns an array `X` of shape `(N - w + 1, N - w)`,
where t... | [
"def",
"MaskSolve",
"(",
"A",
",",
"b",
",",
"w",
"=",
"5",
",",
"progress",
"=",
"True",
",",
"niter",
"=",
"None",
")",
":",
"# Ensure we have choldate installed\r",
"if",
"cholupdate",
"is",
"None",
":",
"log",
".",
"info",
"(",
"\"Running the slow vers... | 28.076923 | 20.076923 |
def iterkeys(self, match=None, count=1):
"""Return an iterator over the db's keys.
``match`` allows for filtering the keys by pattern.
``count`` allows for hint the minimum number of returns.
>>> dc = Dictator()
>>> dc['1'] = 'abc'
>>> dc['2'] = 'def'
>>> dc['3']... | [
"def",
"iterkeys",
"(",
"self",
",",
"match",
"=",
"None",
",",
"count",
"=",
"1",
")",
":",
"logger",
".",
"debug",
"(",
"'call iterkeys %s'",
",",
"match",
")",
"if",
"match",
"is",
"None",
":",
"match",
"=",
"'*'",
"for",
"key",
"in",
"self",
".... | 31.642857 | 14.642857 |
def i2m(self, pkt, x):
"""Convert internal value to machine value"""
if x is None:
# Try to return zero if undefined
x = self.h2i(pkt, 0)
return x | [
"def",
"i2m",
"(",
"self",
",",
"pkt",
",",
"x",
")",
":",
"if",
"x",
"is",
"None",
":",
"# Try to return zero if undefined",
"x",
"=",
"self",
".",
"h2i",
"(",
"pkt",
",",
"0",
")",
"return",
"x"
] | 31.5 | 12.333333 |
def sample_batch_transitions(self, batch_size, forward_steps=1):
""" Return indexes of next sample"""
results = []
for i in range(self.num_envs):
results.append(self.sample_frame_single_env(batch_size, forward_steps=forward_steps))
return np.stack(results, axis=-1) | [
"def",
"sample_batch_transitions",
"(",
"self",
",",
"batch_size",
",",
"forward_steps",
"=",
"1",
")",
":",
"results",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"num_envs",
")",
":",
"results",
".",
"append",
"(",
"self",
".",
"sampl... | 38 | 23 |
def model_sizes(m:nn.Module, size:tuple=(64,64))->Tuple[Sizes,Tensor,Hooks]:
"Pass a dummy input through the model `m` to get the various sizes of activations."
with hook_outputs(m) as hooks:
x = dummy_eval(m, size)
return [o.stored.shape for o in hooks] | [
"def",
"model_sizes",
"(",
"m",
":",
"nn",
".",
"Module",
",",
"size",
":",
"tuple",
"=",
"(",
"64",
",",
"64",
")",
")",
"->",
"Tuple",
"[",
"Sizes",
",",
"Tensor",
",",
"Hooks",
"]",
":",
"with",
"hook_outputs",
"(",
"m",
")",
"as",
"hooks",
... | 54.8 | 20.8 |
def unsubscribe(topic, subscription_arn, region=None, key=None, keyid=None, profile=None):
'''
Unsubscribe a specific SubscriptionArn of a topic.
CLI Example:
.. code-block:: bash
salt myminion boto_sns.unsubscribe my_topic my_subscription_arn region=us-east-1
.. versionadded:: 2016.11.0... | [
"def",
"unsubscribe",
"(",
"topic",
",",
"subscription_arn",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=... | 30.038462 | 27.961538 |
def copy_session(session: requests.Session) -> requests.Session:
"""Duplicates a requests.Session."""
new = requests.Session()
new.cookies = requests.utils.cookiejar_from_dict(requests.utils.dict_from_cookiejar(session.cookies))
new.headers = session.headers.copy()
return new | [
"def",
"copy_session",
"(",
"session",
":",
"requests",
".",
"Session",
")",
"->",
"requests",
".",
"Session",
":",
"new",
"=",
"requests",
".",
"Session",
"(",
")",
"new",
".",
"cookies",
"=",
"requests",
".",
"utils",
".",
"cookiejar_from_dict",
"(",
"... | 48.5 | 21.166667 |
def count_in_category(x='call_type', filter_dict=None, model=DEFAULT_MODEL, app=DEFAULT_APP, sort=True, limit=1000):
"""
Count the number of records for each discrete (categorical) value of a field and return a dict of two lists, the field values and the counts.
>>> x, y = count_in_category(x='call_type', ... | [
"def",
"count_in_category",
"(",
"x",
"=",
"'call_type'",
",",
"filter_dict",
"=",
"None",
",",
"model",
"=",
"DEFAULT_MODEL",
",",
"app",
"=",
"DEFAULT_APP",
",",
"sort",
"=",
"True",
",",
"limit",
"=",
"1000",
")",
":",
"sort",
"=",
"sort_prefix",
"(",... | 40.612903 | 26.548387 |
def firsts(iterable, items=1, default=None):
# type: (Iterable[T], int, T) -> Iterable[T]
""" Lazily return the first x items from this iterable or default. """
try:
items = int(items)
except (ValueError, TypeError):
raise ValueError("items should be usable as an int but is currently "
... | [
"def",
"firsts",
"(",
"iterable",
",",
"items",
"=",
"1",
",",
"default",
"=",
"None",
")",
":",
"# type: (Iterable[T], int, T) -> Iterable[T]",
"try",
":",
"items",
"=",
"int",
"(",
"items",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"r... | 35.818182 | 22.454545 |
def CheckBlobsExist(self, blob_ids):
"""Checks if given blobs exit."""
result = {}
for blob_id in blob_ids:
result[blob_id] = blob_id in self.blobs
return result | [
"def",
"CheckBlobsExist",
"(",
"self",
",",
"blob_ids",
")",
":",
"result",
"=",
"{",
"}",
"for",
"blob_id",
"in",
"blob_ids",
":",
"result",
"[",
"blob_id",
"]",
"=",
"blob_id",
"in",
"self",
".",
"blobs",
"return",
"result"
] | 22.25 | 18.625 |
def split(patterns, flags):
"""Split patterns."""
if flags & SPLIT:
splitted = []
for pattern in ([patterns] if isinstance(patterns, (str, bytes)) else patterns):
splitted.extend(WcSplit(pattern, flags).split())
return splitted
else:
return patterns | [
"def",
"split",
"(",
"patterns",
",",
"flags",
")",
":",
"if",
"flags",
"&",
"SPLIT",
":",
"splitted",
"=",
"[",
"]",
"for",
"pattern",
"in",
"(",
"[",
"patterns",
"]",
"if",
"isinstance",
"(",
"patterns",
",",
"(",
"str",
",",
"bytes",
")",
")",
... | 29.7 | 22.4 |
def domain_delete(domain, logger):
"""libvirt domain undefinition.
@raise: libvirt.libvirtError.
"""
if domain is not None:
try:
if domain.isActive():
domain.destroy()
except libvirt.libvirtError:
logger.exception("Unable to destroy the domain.")... | [
"def",
"domain_delete",
"(",
"domain",
",",
"logger",
")",
":",
"if",
"domain",
"is",
"not",
"None",
":",
"try",
":",
"if",
"domain",
".",
"isActive",
"(",
")",
":",
"domain",
".",
"destroy",
"(",
")",
"except",
"libvirt",
".",
"libvirtError",
":",
"... | 32.473684 | 17.736842 |
def get_correspondance_dict(self, classA, classB,
restrict=None,
replace_numeric=True):
""" Returns a correspondance between classification A and B as dict
Parameters
----------
classA: str
Valid classification... | [
"def",
"get_correspondance_dict",
"(",
"self",
",",
"classA",
",",
"classB",
",",
"restrict",
"=",
"None",
",",
"replace_numeric",
"=",
"True",
")",
":",
"result",
"=",
"{",
"nn",
":",
"None",
"for",
"nn",
"in",
"self",
".",
"data",
"[",
"classA",
"]",... | 35.24 | 22.88 |
def obj_to_csv(self, file_path=None, quote_everything=False,
space_columns=True, quote_numbers=True):
"""
This will return a str of a csv text that is friendly to excel
:param file_path: str to the path
:param quote_everything: bool if True will quote everything... | [
"def",
"obj_to_csv",
"(",
"self",
",",
"file_path",
"=",
"None",
",",
"quote_everything",
"=",
"False",
",",
"space_columns",
"=",
"True",
",",
"quote_numbers",
"=",
"True",
")",
":",
"list_of_list",
",",
"column_widths",
"=",
"self",
".",
"get_data_and_shared... | 43.387097 | 19.193548 |
def buttonDown(self, button=mouse.LEFT):
""" Holds down the specified mouse button.
Use Mouse.LEFT, Mouse.MIDDLE, Mouse.RIGHT
"""
self._lock.acquire()
mouse.press(button)
self._lock.release() | [
"def",
"buttonDown",
"(",
"self",
",",
"button",
"=",
"mouse",
".",
"LEFT",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"mouse",
".",
"press",
"(",
"button",
")",
"self",
".",
"_lock",
".",
"release",
"(",
")"
] | 29.125 | 10.75 |
def err_write(self, msg, **kwargs):
r"""Print `msg` as an error message.
The message is buffered (won't display) until linefeed ("\n").
"""
if self._thread_invalid():
# special case: if a non-main thread writes to stderr
# i.e. due to an uncaught exception, pass ... | [
"def",
"err_write",
"(",
"self",
",",
"msg",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_thread_invalid",
"(",
")",
":",
"# special case: if a non-main thread writes to stderr",
"# i.e. due to an uncaught exception, pass it through",
"# without raising an additi... | 42.75 | 17 |
def main_hrun():
""" API test: parse command line options and run commands.
"""
import argparse
from httprunner import logger
from httprunner.__about__ import __description__, __version__
from httprunner.api import HttpRunner
from httprunner.compat import is_py2
from httprunner.validator... | [
"def",
"main_hrun",
"(",
")",
":",
"import",
"argparse",
"from",
"httprunner",
"import",
"logger",
"from",
"httprunner",
".",
"__about__",
"import",
"__description__",
",",
"__version__",
"from",
"httprunner",
".",
"api",
"import",
"HttpRunner",
"from",
"httprunne... | 32.476744 | 17.72093 |
def inline_inputs(self):
"""Inline all input latex files references by this document. The
inlining is accomplished recursively. The document is modified
in place.
"""
self.text = texutils.inline(self.text,
os.path.dirname(self._filepath))
... | [
"def",
"inline_inputs",
"(",
"self",
")",
":",
"self",
".",
"text",
"=",
"texutils",
".",
"inline",
"(",
"self",
".",
"text",
",",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"_filepath",
")",
")",
"# Remove children",
"self",
".",
"_children"... | 40 | 14.555556 |
def length_of_associated_transcript(effect):
"""
Length of spliced mRNA sequence of transcript associated with effect,
if there is one (otherwise return 0).
"""
return apply_to_transcript_if_exists(
effect=effect,
fn=lambda t: len(t.sequence),
default=0) | [
"def",
"length_of_associated_transcript",
"(",
"effect",
")",
":",
"return",
"apply_to_transcript_if_exists",
"(",
"effect",
"=",
"effect",
",",
"fn",
"=",
"lambda",
"t",
":",
"len",
"(",
"t",
".",
"sequence",
")",
",",
"default",
"=",
"0",
")"
] | 32.222222 | 9.111111 |
def getCert(certHost=vos.vos.SERVER, certfile=None,
certQuery="/cred/proxyCert?daysValid=",daysValid=2):
"""Access the cadc certificate server"""
if certfile is None:
certfile = os.path.join(os.getenv("HOME","/tmp"),".ssl/cadcproxy.pem")
dirname = os.path.dirname(certfile)
try:
... | [
"def",
"getCert",
"(",
"certHost",
"=",
"vos",
".",
"vos",
".",
"SERVER",
",",
"certfile",
"=",
"None",
",",
"certQuery",
"=",
"\"/cred/proxyCert?daysValid=\"",
",",
"daysValid",
"=",
"2",
")",
":",
"if",
"certfile",
"is",
"None",
":",
"certfile",
"=",
"... | 30.352941 | 20.235294 |
def _appendSegment(self, type=None, points=None, smooth=False, **kwargs):
"""
Subclasses may override this method.
"""
self._insertSegment(len(self), type=type, points=points,
smooth=smooth, **kwargs) | [
"def",
"_appendSegment",
"(",
"self",
",",
"type",
"=",
"None",
",",
"points",
"=",
"None",
",",
"smooth",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_insertSegment",
"(",
"len",
"(",
"self",
")",
",",
"type",
"=",
"type",
",",
... | 42.5 | 12.166667 |
def _to_key_ranges_by_shard(cls, app, namespaces, shard_count, query_spec):
"""Get a list of key_ranges.KeyRanges objects, one for each shard.
This method uses scatter index to split each namespace into pieces
and assign those pieces to shards.
Args:
app: app_id in str.
namespaces: a list ... | [
"def",
"_to_key_ranges_by_shard",
"(",
"cls",
",",
"app",
",",
"namespaces",
",",
"shard_count",
",",
"query_spec",
")",
":",
"key_ranges_by_ns",
"=",
"[",
"]",
"# Split each ns into n splits. If a ns doesn't have enough scatter to",
"# split into n, the last few splits are Non... | 35.045455 | 17.977273 |
def list_ipsecpolicies(self, retrieve_all=True, **_params):
"""Fetches a list of all configured IPsecPolicies for a project."""
return self.list('ipsecpolicies',
self.ipsecpolicies_path,
retrieve_all,
**_params) | [
"def",
"list_ipsecpolicies",
"(",
"self",
",",
"retrieve_all",
"=",
"True",
",",
"*",
"*",
"_params",
")",
":",
"return",
"self",
".",
"list",
"(",
"'ipsecpolicies'",
",",
"self",
".",
"ipsecpolicies_path",
",",
"retrieve_all",
",",
"*",
"*",
"_params",
")... | 49.5 | 6 |
def interpolate_delays(augmented_stop_times, dist_threshold,
delay_threshold=3600, delay_cols=None):
"""
Given an augment stop times DataFrame as output by the function
:func:`build_augmented_stop_times`, a distance threshold (float)
in the same units as the ``'shape_dist_traveled'`` column of
``a... | [
"def",
"interpolate_delays",
"(",
"augmented_stop_times",
",",
"dist_threshold",
",",
"delay_threshold",
"=",
"3600",
",",
"delay_cols",
"=",
"None",
")",
":",
"f",
"=",
"augmented_stop_times",
".",
"copy",
"(",
")",
"if",
"delay_cols",
"is",
"None",
"or",
"no... | 37.02439 | 20.463415 |
def reload_current_page(self, *args, **kwds):
'''重新载入当前页面.
所有的页面都应该实现reload()方法.
'''
index = self.notebook.get_current_page()
self.notebook.get_nth_page(index).reload() | [
"def",
"reload_current_page",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"index",
"=",
"self",
".",
"notebook",
".",
"get_current_page",
"(",
")",
"self",
".",
"notebook",
".",
"get_nth_page",
"(",
"index",
")",
".",
"reload",
"(",... | 30.142857 | 16.428571 |
def body(self):
""" Return body request parameter
:return: Body parameter
:rtype: Parameter or None
"""
body = self.get_parameters_by_location(['body'])
return self.root.schemas.get(body[0].type) if body else None | [
"def",
"body",
"(",
"self",
")",
":",
"body",
"=",
"self",
".",
"get_parameters_by_location",
"(",
"[",
"'body'",
"]",
")",
"return",
"self",
".",
"root",
".",
"schemas",
".",
"get",
"(",
"body",
"[",
"0",
"]",
".",
"type",
")",
"if",
"body",
"else... | 31.875 | 15.625 |
def parse_version(version):
"""Use parse_version from pkg_resources or distutils as available."""
global parse_version
try:
from pkg_resources import parse_version
except ImportError:
from distutils.version import LooseVersion as parse_version
return parse_version(version) | [
"def",
"parse_version",
"(",
"version",
")",
":",
"global",
"parse_version",
"try",
":",
"from",
"pkg_resources",
"import",
"parse_version",
"except",
"ImportError",
":",
"from",
"distutils",
".",
"version",
"import",
"LooseVersion",
"as",
"parse_version",
"return",... | 37.75 | 14.875 |
def send_url(amount, redirect_url, url, api):
'''
return payment gateway url to redirect user
to it for payment.
'''
values = {'api': api, 'amount': amount, 'redirect': redirect_url}
send_request = requests.post(SEND_URL_FINAL, data=values)
id_get = send_request.text
print(id_get)
if... | [
"def",
"send_url",
"(",
"amount",
",",
"redirect_url",
",",
"url",
",",
"api",
")",
":",
"values",
"=",
"{",
"'api'",
":",
"api",
",",
"'amount'",
":",
"amount",
",",
"'redirect'",
":",
"redirect_url",
"}",
"send_request",
"=",
"requests",
".",
"post",
... | 36.230769 | 20.769231 |
def paths(self):
"""
Sequence of closed paths, encoded by entity index.
Returns
---------
paths: (n,) sequence of (*,) int referencing self.entities
"""
paths = traversal.closed_paths(self.entities,
self.vertices)
re... | [
"def",
"paths",
"(",
"self",
")",
":",
"paths",
"=",
"traversal",
".",
"closed_paths",
"(",
"self",
".",
"entities",
",",
"self",
".",
"vertices",
")",
"return",
"paths"
] | 29.090909 | 18.363636 |
def walk_from_list(cls, files):
"""A function that mimics :func:`os.walk()` by simulating a directory with
the list of files passed as an argument.
:param files: A list of file paths
:return: A function that mimics :func:`os.walk()` walking a directory
containing only t... | [
"def",
"walk_from_list",
"(",
"cls",
",",
"files",
")",
":",
"tree",
"=",
"cls",
".",
"list_to_tree",
"(",
"files",
")",
"def",
"walk",
"(",
"directory",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"cls",
".",
"tree_walk",
"(",
"directory",
",",
"tr... | 35.714286 | 16.785714 |
def get_component(self, colour, tolerance=0, default=None):
"""
Get the component corresponding to a display colour. This is for
generating a Striplog object from a colour image of a striplog.
Args:
colour (str): The hex colour string to look up.
tolerance (float):... | [
"def",
"get_component",
"(",
"self",
",",
"colour",
",",
"tolerance",
"=",
"0",
",",
"default",
"=",
"None",
")",
":",
"if",
"not",
"(",
"0",
"<=",
"tolerance",
"<=",
"np",
".",
"sqrt",
"(",
"195075",
")",
")",
":",
"raise",
"LegendError",
"(",
"'T... | 38.673469 | 19.44898 |
def use_openssl(libcrypto_path, libssl_path, trust_list_path=None):
"""
Forces using OpenSSL dynamic libraries on OS X (.dylib) or Windows (.dll),
or using a specific dynamic library on Linux/BSD (.so).
This can also be used to configure oscrypto to use LibreSSL dynamic
libraries.
This method ... | [
"def",
"use_openssl",
"(",
"libcrypto_path",
",",
"libssl_path",
",",
"trust_list_path",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"libcrypto_path",
",",
"str_cls",
")",
":",
"raise",
"ValueError",
"(",
"'libcrypto_path must be a unicode string, not %s'",... | 43.491525 | 28.508475 |
def get_image_location(image, sdir, image_list, recurred=False):
"""Take a raw image name + directory and return the location of image.
:param: image (string): the name of the raw image from the TeX
:param: sdir (string): the directory where everything was unzipped to
:param: image_list ([string, strin... | [
"def",
"get_image_location",
"(",
"image",
",",
"sdir",
",",
"image_list",
",",
"recurred",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"image",
",",
"list",
")",
":",
"# image is a list, not good",
"return",
"None",
"image",
"=",
"image",
".",
"encode"... | 37.078431 | 21.068627 |
def nested_join(array, o_str= '{', c_str= '}'):
'''
Builds a string out of a given nested list.
Args :
array : An array retruned by pyparsing nestedExpr.
o_str : Opening str.
c_str : Closing str.
'''
result = ''
for x in array :
if typ... | [
"def",
"nested_join",
"(",
"array",
",",
"o_str",
"=",
"'{'",
",",
"c_str",
"=",
"'}'",
")",
":",
"result",
"=",
"''",
"for",
"x",
"in",
"array",
":",
"if",
"type",
"(",
"x",
")",
"==",
"type",
"(",
"[",
"]",
")",
":",
"result",
"+=",
"o_str",
... | 30.133333 | 16.8 |
def _run_info_from_yaml(dirs, run_info_yaml, config, sample_names=None,
is_cwl=False, integrations=None):
"""Read run information from a passed YAML file.
"""
validate_yaml(run_info_yaml, run_info_yaml)
with open(run_info_yaml) as in_handle:
loaded = yaml.safe_load(in_han... | [
"def",
"_run_info_from_yaml",
"(",
"dirs",
",",
"run_info_yaml",
",",
"config",
",",
"sample_names",
"=",
"None",
",",
"is_cwl",
"=",
"False",
",",
"integrations",
"=",
"None",
")",
":",
"validate_yaml",
"(",
"run_info_yaml",
",",
"run_info_yaml",
")",
"with",... | 50.023622 | 20.409449 |
def __reorganize_authors(authors):
"""
Separate the string of authors and put it into a BibJSON compliant list
:param str authors:
:return list: List of dictionaries of author names.
"""
# String SHOULD be semi-colon separated names.
l = []
s = authors.spl... | [
"def",
"__reorganize_authors",
"(",
"authors",
")",
":",
"# String SHOULD be semi-colon separated names.",
"l",
"=",
"[",
"]",
"s",
"=",
"authors",
".",
"split",
"(",
"\";\"",
")",
"for",
"author",
"in",
"s",
":",
"try",
":",
"l",
".",
"append",
"(",
"{",
... | 37.8 | 18.333333 |
def summarize_classes(self):
"""
Summary of classes: names, numeric labels and sizes
Returns
-------
tuple : class_set, label_set, class_sizes
class_set : list
List of names of all the classes
label_set : list
Label for each class in clas... | [
"def",
"summarize_classes",
"(",
"self",
")",
":",
"class_sizes",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"self",
".",
"class_set",
")",
")",
"for",
"idx",
",",
"cls",
"in",
"enumerate",
"(",
"self",
".",
"class_set",
")",
":",
"class_sizes",
"[",
... | 30.086957 | 19.391304 |
def run(self):
"""
Starts a development server for the zengine application
"""
print("Development server started on http://%s:%s. \n\nPress Ctrl+C to stop\n" % (
self.manager.args.addr,
self.manager.args.port)
)
if self.manager.args.server_ty... | [
"def",
"run",
"(",
"self",
")",
":",
"print",
"(",
"\"Development server started on http://%s:%s. \\n\\nPress Ctrl+C to stop\\n\"",
"%",
"(",
"self",
".",
"manager",
".",
"args",
".",
"addr",
",",
"self",
".",
"manager",
".",
"args",
".",
"port",
")",
")",
"if... | 37.666667 | 14.5 |
def clear(self) -> None:
"""Resets all headers and content for this response."""
self._headers = httputil.HTTPHeaders(
{
"Server": "TornadoServer/%s" % tornado.version,
"Content-Type": "text/html; charset=UTF-8",
"Date": httputil.format_timesta... | [
"def",
"clear",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"_headers",
"=",
"httputil",
".",
"HTTPHeaders",
"(",
"{",
"\"Server\"",
":",
"\"TornadoServer/%s\"",
"%",
"tornado",
".",
"version",
",",
"\"Content-Type\"",
":",
"\"text/html; charset=UTF-8\"",
... | 39.615385 | 15.692308 |
def wrap(text, width=70, **kwargs):
"""Wrap multiple paragraphs of text, returning a list of wrapped lines.
Reformat the multiple paragraphs 'text' so they fit in lines of no
more than 'width' columns, and return a list of wrapped lines. By
default, tabs in 'text' are expanded with string.expandtabs(... | [
"def",
"wrap",
"(",
"text",
",",
"width",
"=",
"70",
",",
"*",
"*",
"kwargs",
")",
":",
"w",
"=",
"ParagraphWrapper",
"(",
"width",
"=",
"width",
",",
"*",
"*",
"kwargs",
")",
"return",
"w",
".",
"wrap",
"(",
"text",
")"
] | 47.583333 | 20.583333 |
def _check_hyperedge_attributes_consistency(self):
"""Consistency Check 1: consider all hyperedge IDs listed in
_hyperedge_attributes
:raises: ValueError -- detected inconsistency among dictionaries
"""
# required_attrs are attributes that every hyperedge must have.
req... | [
"def",
"_check_hyperedge_attributes_consistency",
"(",
"self",
")",
":",
"# required_attrs are attributes that every hyperedge must have.",
"required_attrs",
"=",
"[",
"'weight'",
",",
"'tail'",
",",
"'head'",
",",
"'__frozen_tail'",
",",
"'__frozen_head'",
"]",
"# Get list o... | 49.623529 | 22.2 |
def CurrentNode(self):
"""Hacking interface allowing to get the xmlNodePtr
correponding to the current node being accessed by the
xmlTextReader. This is dangerous because the underlying
node may be destroyed on the next Reads. """
ret = libxml2mod.xmlTextReaderCurrentNode(... | [
"def",
"CurrentNode",
"(",
"self",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlTextReaderCurrentNode",
"(",
"self",
".",
"_o",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlTextReaderCurrentNode() failed'",
")",
"__tmp",
"=",
"xmlNode",... | 50.111111 | 16.333333 |
def maximum(attrs, inputs, proto_obj):
"""
Elementwise maximum of arrays.
MXNet maximum compares only two symbols at a time.
ONNX can send more than two to compare.
Breaking into multiple mxnet ops to compare two symbols at a time
"""
if len(inputs) > 1:
mxnet_op = symbol.maximum(inp... | [
"def",
"maximum",
"(",
"attrs",
",",
"inputs",
",",
"proto_obj",
")",
":",
"if",
"len",
"(",
"inputs",
")",
">",
"1",
":",
"mxnet_op",
"=",
"symbol",
".",
"maximum",
"(",
"inputs",
"[",
"0",
"]",
",",
"inputs",
"[",
"1",
"]",
")",
"for",
"op_inpu... | 37.142857 | 11.428571 |
def fast_roc(actuals, controls):
"""
approximates the area under the roc curve for sets of actuals and controls.
Uses all values appearing in actuals as thresholds and lower sum
interpolation. Also returns arrays of the true positive rate and the false
positive rate that can be used for plotting the... | [
"def",
"fast_roc",
"(",
"actuals",
",",
"controls",
")",
":",
"assert",
"(",
"type",
"(",
"actuals",
")",
"is",
"np",
".",
"ndarray",
")",
"assert",
"(",
"type",
"(",
"controls",
")",
"is",
"np",
".",
"ndarray",
")",
"actuals",
"=",
"np",
".",
"rav... | 40.589744 | 17.25641 |
def delta_hv(scatterer):
"""
Delta_hv for the current setup.
Args:
scatterer: a Scatterer instance.
Returns:
Delta_hv [rad].
"""
Z = scatterer.get_Z()
return np.arctan2(Z[2,3] - Z[3,2], -Z[2,2] - Z[3,3]) | [
"def",
"delta_hv",
"(",
"scatterer",
")",
":",
"Z",
"=",
"scatterer",
".",
"get_Z",
"(",
")",
"return",
"np",
".",
"arctan2",
"(",
"Z",
"[",
"2",
",",
"3",
"]",
"-",
"Z",
"[",
"3",
",",
"2",
"]",
",",
"-",
"Z",
"[",
"2",
",",
"2",
"]",
"-... | 19.833333 | 17.333333 |
def copy(self, repository=None, tag=None,
source_transport=None,
target_transport=SkopeoTransport.DOCKER,
source_path=None, target_path=None,
logs=True):
""" Copy this image
:param repository to be copied to
:param tag
:param source_tr... | [
"def",
"copy",
"(",
"self",
",",
"repository",
"=",
"None",
",",
"tag",
"=",
"None",
",",
"source_transport",
"=",
"None",
",",
"target_transport",
"=",
"SkopeoTransport",
".",
"DOCKER",
",",
"source_path",
"=",
"None",
",",
"target_path",
"=",
"None",
","... | 40.558824 | 16.970588 |
def dusk(self, date=None, local=True, use_elevation=True):
"""Calculates the dusk time (the time in the evening when the sun is a
certain number of degrees below the horizon. By default this is 6
degrees but can be changed by setting the
:attr:`solar_depression` property.)
:para... | [
"def",
"dusk",
"(",
"self",
",",
"date",
"=",
"None",
",",
"local",
"=",
"True",
",",
"use_elevation",
"=",
"True",
")",
":",
"if",
"local",
"and",
"self",
".",
"timezone",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Local time requested but Location... | 41.225 | 24.9 |
def get_translations(self, domain=None, locale=None):
"""Load translations for given or configuration domain.
:param domain: Messages domain (str)
:param locale: Locale object
"""
if locale is None:
if self.locale is None:
return support.NullTranslat... | [
"def",
"get_translations",
"(",
"self",
",",
"domain",
"=",
"None",
",",
"locale",
"=",
"None",
")",
":",
"if",
"locale",
"is",
"None",
":",
"if",
"self",
".",
"locale",
"is",
"None",
":",
"return",
"support",
".",
"NullTranslations",
"(",
")",
"locale... | 33.344828 | 18.724138 |
def reversebait(self, maskmiddle='f', k=19):
"""
Use the freshly-baited FASTQ files to bait out sequence from the original target files. This will reduce the
number of possibly targets against which the baited reads must be aligned
"""
logging.info('Performing reverse kmer baitin... | [
"def",
"reversebait",
"(",
"self",
",",
"maskmiddle",
"=",
"'f'",
",",
"k",
"=",
"19",
")",
":",
"logging",
".",
"info",
"(",
"'Performing reverse kmer baiting of targets with FASTQ files'",
")",
"if",
"self",
".",
"kmer_size",
"is",
"None",
":",
"kmer",
"=",
... | 62.842105 | 28.052632 |
def download_vault_folder(remote_path, local_path, dry_run=False, force=False):
"""Recursively downloads a folder in a vault to a local directory.
Only downloads files, not datasets."""
local_path = os.path.normpath(os.path.expanduser(local_path))
if not os.access(local_path, os.W_OK):
raise Ex... | [
"def",
"download_vault_folder",
"(",
"remote_path",
",",
"local_path",
",",
"dry_run",
"=",
"False",
",",
"force",
"=",
"False",
")",
":",
"local_path",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"local_path",
... | 38.058824 | 19 |
def _parametersToDefaults(self, parameters):
"""
Extract the defaults from C{parameters}, constructing a dictionary
mapping parameter names to default values, suitable for passing to
L{ListChangeParameter}.
@type parameters: C{list} of L{liveform.Parameter} or
L{liveform... | [
"def",
"_parametersToDefaults",
"(",
"self",
",",
"parameters",
")",
":",
"defaults",
"=",
"{",
"}",
"for",
"p",
"in",
"parameters",
":",
"if",
"isinstance",
"(",
"p",
",",
"liveform",
".",
"ChoiceParameter",
")",
":",
"selected",
"=",
"[",
"]",
"for",
... | 34.409091 | 14.590909 |
def set_fold_trigger(block, val):
"""
Set the block fold trigger flag (True means the block is a fold
trigger).
:param block: block to set
:param val: value to set
"""
if block is None:
return
state = block.userState()
if state == -1:
... | [
"def",
"set_fold_trigger",
"(",
"block",
",",
"val",
")",
":",
"if",
"block",
"is",
"None",
":",
"return",
"state",
"=",
"block",
".",
"userState",
"(",
")",
"if",
"state",
"==",
"-",
"1",
":",
"state",
"=",
"0",
"state",
"&=",
"0x7BFFFFFF",
"state",... | 26.25 | 14 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.