text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def missing_homology_models(self):
"""list: List of genes with no mapping to any homology models."""
return [x.id for x in self.genes if not self.genes_with_homology_models.has_id(x.id)] | [
"def",
"missing_homology_models",
"(",
"self",
")",
":",
"return",
"[",
"x",
".",
"id",
"for",
"x",
"in",
"self",
".",
"genes",
"if",
"not",
"self",
".",
"genes_with_homology_models",
".",
"has_id",
"(",
"x",
".",
"id",
")",
"]"
] | 66.666667 | 19.666667 |
def put_script(self, id, body, context=None, params=None):
"""
Create a script in given language with specified ID.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/modules-scripting.html>`_
:arg id: Script ID
:arg body: The document
"""
for param... | [
"def",
"put_script",
"(",
"self",
",",
"id",
",",
"body",
",",
"context",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"for",
"param",
"in",
"(",
"id",
",",
"body",
")",
":",
"if",
"param",
"in",
"SKIP_IN_PATH",
":",
"raise",
"ValueError",
"(... | 41.285714 | 20.428571 |
def _updateFrame(self):
"""
Updates the frame for the given sender.
"""
for col, mov in self._movies.items():
self.setIcon(col, QtGui.QIcon(mov.currentPixmap())) | [
"def",
"_updateFrame",
"(",
"self",
")",
":",
"for",
"col",
",",
"mov",
"in",
"self",
".",
"_movies",
".",
"items",
"(",
")",
":",
"self",
".",
"setIcon",
"(",
"col",
",",
"QtGui",
".",
"QIcon",
"(",
"mov",
".",
"currentPixmap",
"(",
")",
")",
")... | 34.166667 | 8.833333 |
def resume(self):
"""Resumes the pool and reindex all objects processed
"""
self.num_calls -= 1
if self.num_calls > 0:
return
logger.info("Resume actions for {} objects".format(len(self)))
# Fetch the objects from the pool
processed = list()
f... | [
"def",
"resume",
"(",
"self",
")",
":",
"self",
".",
"num_calls",
"-=",
"1",
"if",
"self",
".",
"num_calls",
">",
"0",
":",
"return",
"logger",
".",
"info",
"(",
"\"Resume actions for {} objects\"",
".",
"format",
"(",
"len",
"(",
"self",
")",
")",
")"... | 37.259259 | 16.814815 |
def load_request_microservices(plugin_path, plugins, internal_attributes, base_url):
"""
Loads request micro services (handling incoming requests).
:type plugin_path: list[str]
:type plugins: list[str]
:type internal_attributes: dict[string, dict[str, str | list[str]]]
:type base_url: str
:... | [
"def",
"load_request_microservices",
"(",
"plugin_path",
",",
"plugins",
",",
"internal_attributes",
",",
"base_url",
")",
":",
"request_services",
"=",
"_load_microservices",
"(",
"plugin_path",
",",
"plugins",
",",
"_request_micro_service_filter",
",",
"internal_attribu... | 45.736842 | 23.526316 |
def run_cron_with_cache_check(cron_class, force=False, silent=False):
"""
Checks the cache and runs the cron or not.
@cron_class - cron class to run.
@force - run job even if not scheduled
@silent - suppress notifications
"""
with CronJobManager(cron_class, silent) as manager:
... | [
"def",
"run_cron_with_cache_check",
"(",
"cron_class",
",",
"force",
"=",
"False",
",",
"silent",
"=",
"False",
")",
":",
"with",
"CronJobManager",
"(",
"cron_class",
",",
"silent",
")",
"as",
"manager",
":",
"manager",
".",
"run",
"(",
"force",
")"
] | 30.272727 | 14.090909 |
def validate_object(obj, field_validators=None, non_field_validators=None,
schema=None, context=None):
"""
Takes a mapping and applies a mapping of validator functions to it
collecting and reraising any validation errors that occur.
"""
if schema is None:
schema = {}
... | [
"def",
"validate_object",
"(",
"obj",
",",
"field_validators",
"=",
"None",
",",
"non_field_validators",
"=",
"None",
",",
"schema",
"=",
"None",
",",
"context",
"=",
"None",
")",
":",
"if",
"schema",
"is",
"None",
":",
"schema",
"=",
"{",
"}",
"if",
"... | 39.470588 | 18.176471 |
def draw(self):
""" Draw MV grid's graph using the geo data of nodes
Notes
-----
This method uses the coordinates stored in the nodes' geoms which
are usually conformal, not equidistant. Therefore, the plot might
be distorted and does not (fully) reflect the real positio... | [
"def",
"draw",
"(",
"self",
")",
":",
"# get nodes' positions",
"nodes_pos",
"=",
"{",
"}",
"for",
"node",
"in",
"self",
".",
"graph",
".",
"nodes",
"(",
")",
":",
"nodes_pos",
"[",
"node",
"]",
"=",
"(",
"node",
".",
"geom",
".",
"x",
",",
"node",... | 32.631579 | 22.368421 |
def add_freeform_sp(self, x, y, cx, cy):
"""Append a new freeform `p:sp` with specified position and size."""
shape_id = self._next_shape_id
name = 'Freeform %d' % (shape_id-1,)
sp = CT_Shape.new_freeform_sp(shape_id, name, x, y, cx, cy)
self.insert_element_before(sp, 'p:extLst')... | [
"def",
"add_freeform_sp",
"(",
"self",
",",
"x",
",",
"y",
",",
"cx",
",",
"cy",
")",
":",
"shape_id",
"=",
"self",
".",
"_next_shape_id",
"name",
"=",
"'Freeform %d'",
"%",
"(",
"shape_id",
"-",
"1",
",",
")",
"sp",
"=",
"CT_Shape",
".",
"new_freefo... | 47.428571 | 9.428571 |
def start_daemon():
"""
Start a thread to continuously read log files and append lines in DB.
Work in progress. Currently the thread doesn't append anything,
it only print the information parsed from each line read.
Returns:
thread: the started thread.
"""
... | [
"def",
"start_daemon",
"(",
")",
":",
"if",
"RequestLog",
".",
"daemon",
"is",
"None",
":",
"parser",
"=",
"get_nginx_parser",
"(",
")",
"RequestLog",
".",
"daemon",
"=",
"RequestLog",
".",
"ParseToDBThread",
"(",
"parser",
",",
"daemon",
"=",
"True",
")",... | 35.266667 | 18.466667 |
def extract(self, log, basis, name, function=None):
"""
'Extract' a log into the components of a striplog.
Args:
log (array_like). A log or other 1D data.
basis (array_like). The depths or elevations of the log samples.
name (str). The name of the attribute t... | [
"def",
"extract",
"(",
"self",
",",
"log",
",",
"basis",
",",
"name",
",",
"function",
"=",
"None",
")",
":",
"# Build a dict of {index: [log values]} to keep track.",
"intervals",
"=",
"{",
"}",
"previous_ix",
"=",
"-",
"1",
"for",
"i",
",",
"z",
"in",
"e... | 37.411765 | 17.647059 |
def list_tags():
"""Lists the available tags.
Returns:
Tuple of tuples. Child tuples are four items: ('opening tag', 'closing tag', main ansi value, closing ansi value).
"""
codes = _AutoCodes()
grouped = set([(k, '/{0}'.format(k), codes[k], codes['/{0}'.format(k)]) for k in codes if not k.star... | [
"def",
"list_tags",
"(",
")",
":",
"codes",
"=",
"_AutoCodes",
"(",
")",
"grouped",
"=",
"set",
"(",
"[",
"(",
"k",
",",
"'/{0}'",
".",
"format",
"(",
"k",
")",
",",
"codes",
"[",
"k",
"]",
",",
"codes",
"[",
"'/{0}'",
".",
"format",
"(",
"k",
... | 46.769231 | 32.346154 |
def format_info(raw):
"""Format a string representing the information
concerning the name.
"""
logging.debug(_('raw[0]: %s'), raw[0])
results, sense = raw
# A scenario where ORM really stands out.
new = '\n'.join(
'{} {} {} {}'.format(
i[0], sense.kind_id_to_name(i[1]),
... | [
"def",
"format_info",
"(",
"raw",
")",
":",
"logging",
".",
"debug",
"(",
"_",
"(",
"'raw[0]: %s'",
")",
",",
"raw",
"[",
"0",
"]",
")",
"results",
",",
"sense",
"=",
"raw",
"# A scenario where ORM really stands out.",
"new",
"=",
"'\\n'",
".",
"join",
"... | 31.642857 | 10.785714 |
def extend_back(self, missing_dts):
"""
Resizes the buffer to hold a new window with a new cap_multiple.
If cap_multiple is None, then the old cap_multiple is used.
"""
delta = len(missing_dts)
if not delta:
raise ValueError(
'missing_dts must... | [
"def",
"extend_back",
"(",
"self",
",",
"missing_dts",
")",
":",
"delta",
"=",
"len",
"(",
"missing_dts",
")",
"if",
"not",
"delta",
":",
"raise",
"ValueError",
"(",
"'missing_dts must be a non-empty index'",
",",
")",
"self",
".",
"_window",
"+=",
"delta",
... | 29.071429 | 18.642857 |
def update(self):
"""Update the battery range state."""
self._controller.update(self._id, wake_if_asleep=False)
data = self._controller.get_charging_params(self._id)
if data:
self.__battery_range = data['battery_range']
self.__est_battery_range = data['est_battery... | [
"def",
"update",
"(",
"self",
")",
":",
"self",
".",
"_controller",
".",
"update",
"(",
"self",
".",
"_id",
",",
"wake_if_asleep",
"=",
"False",
")",
"data",
"=",
"self",
".",
"_controller",
".",
"get_charging_params",
"(",
"self",
".",
"_id",
")",
"if... | 46.666667 | 18.866667 |
def __connect(host, port, username, password, private_key):
"""
Establish remote connection
:param host: Hostname or IP address to connect to
:param port: Port number to use for SSH
:param username: Username credentials for SSH access
:param password: Password credential... | [
"def",
"__connect",
"(",
"host",
",",
"port",
",",
"username",
",",
"password",
",",
"private_key",
")",
":",
"# Initialize the SSH connection",
"ssh",
"=",
"paramiko",
".",
"SSHClient",
"(",
")",
"ssh",
".",
"set_missing_host_key_policy",
"(",
"paramiko",
".",
... | 43.107143 | 20.75 |
def union(self, other):
"""Constructs an unminimized DFA recognizing the union of the languages of two given DFAs.
Args:
other (DFA): The other DFA that will be used
for the union operation
Returns:
DFA: The resulting DFA
"""
opera... | [
"def",
"union",
"(",
"self",
",",
"other",
")",
":",
"operation",
"=",
"bool",
".",
"__or__",
"self",
".",
"cross_product",
"(",
"other",
",",
"operation",
")",
"return",
"self"
] | 35.727273 | 12 |
def cleanse(self):
"""Clean up some terms, like ensuring that the name is a slug"""
from .util import slugify
self.ensure_identifier()
try:
self.update_name()
except MetatabError:
identifier = self['Root'].find_first('Root.Identifier')
name... | [
"def",
"cleanse",
"(",
"self",
")",
":",
"from",
".",
"util",
"import",
"slugify",
"self",
".",
"ensure_identifier",
"(",
")",
"try",
":",
"self",
".",
"update_name",
"(",
")",
"except",
"MetatabError",
":",
"identifier",
"=",
"self",
"[",
"'Root'",
"]",... | 30.7 | 22.4 |
def any_email_field(field, **kwargs):
"""
Return random value for EmailField
>>> result = any_field(models.EmailField())
>>> type(result)
<type 'str'>
>>> re.match(r"(?:^|\s)[-a-z0-9_.]+@(?:[-a-z0-9]+\.)+[a-z]{2,6}(?:\s|$)", result, re.IGNORECASE) is not None
True
"""
retu... | [
"def",
"any_email_field",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"\"%s@%s.%s\"",
"%",
"(",
"xunit",
".",
"any_string",
"(",
"max_length",
"=",
"10",
")",
",",
"xunit",
".",
"any_string",
"(",
"max_length",
"=",
"10",
")",
",",
"xuni... | 37.538462 | 20.153846 |
def disable_option(self):
"""The command-line option that disables this diagnostic."""
disable = _CXString()
conf.lib.clang_getDiagnosticOption(self, byref(disable))
return str(conf.lib.clang_getCString(disable)) | [
"def",
"disable_option",
"(",
"self",
")",
":",
"disable",
"=",
"_CXString",
"(",
")",
"conf",
".",
"lib",
".",
"clang_getDiagnosticOption",
"(",
"self",
",",
"byref",
"(",
"disable",
")",
")",
"return",
"str",
"(",
"conf",
".",
"lib",
".",
"clang_getCSt... | 40 | 17.333333 |
def create_process(cmd, root_helper=None, addl_env=None, log_output=True):
"""Create a process object for the given command.
The return value will be a tuple of the process object and the
list of command arguments used to create it.
"""
if root_helper:
cmd = shlex.split(root_helper) + cmd
... | [
"def",
"create_process",
"(",
"cmd",
",",
"root_helper",
"=",
"None",
",",
"addl_env",
"=",
"None",
",",
"log_output",
"=",
"True",
")",
":",
"if",
"root_helper",
":",
"cmd",
"=",
"shlex",
".",
"split",
"(",
"root_helper",
")",
"+",
"cmd",
"cmd",
"=",
... | 34.473684 | 20.052632 |
def get(self, path):
"""
Get a file from the filesystem. Returns a SimFile or None.
"""
mountpoint, chunks = self.get_mountpoint(path)
if mountpoint is None:
return self._files.get(self._join_chunks(chunks))
else:
return mountpoint.get(chunks) | [
"def",
"get",
"(",
"self",
",",
"path",
")",
":",
"mountpoint",
",",
"chunks",
"=",
"self",
".",
"get_mountpoint",
"(",
"path",
")",
"if",
"mountpoint",
"is",
"None",
":",
"return",
"self",
".",
"_files",
".",
"get",
"(",
"self",
".",
"_join_chunks",
... | 30.7 | 15.9 |
def api(endpoint, data=None, json=None, filename=None, save_to=None):
"""
Perform a REST API request to a previously connected server.
This function is mostly for internal purposes, but may occasionally be useful for direct access to
the backend H2O server. It has same parameters as :meth:`H2OConnectio... | [
"def",
"api",
"(",
"endpoint",
",",
"data",
"=",
"None",
",",
"json",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"save_to",
"=",
"None",
")",
":",
"# type checks are performed in H2OConnection class",
"_check_connection",
"(",
")",
"return",
"h2oconn",
".... | 54 | 32 |
def run_checks(self, b, compute, times=[], **kwargs):
"""
run any sanity checks to make sure the parameters and options are legal
for this backend. If they are not, raise an error here to avoid errors
within the workers.
Any physics-checks that are backend-independent should be... | [
"def",
"run_checks",
"(",
"self",
",",
"b",
",",
"compute",
",",
"times",
"=",
"[",
"]",
",",
"*",
"*",
"kwargs",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"run_checks is not implemented by the {} backend\"",
".",
"format",
"(",
"self",
".",
"__class__"... | 46.615385 | 27.384615 |
def grid_at_redshift_from_image_plane_grid_and_redshift(self, image_plane_grid, redshift):
"""For an input grid of (y,x) arc-second image-plane coordinates, ray-trace the coordinates to any redshift in \
the strong lens configuration.
This is performed using multi-plane ray-tracing and the exis... | [
"def",
"grid_at_redshift_from_image_plane_grid_and_redshift",
"(",
"self",
",",
"image_plane_grid",
",",
"redshift",
")",
":",
"# TODO : We need to come up with a better abstraction for multi-plane lensing 0_0",
"image_plane_grid_stack",
"=",
"grids",
".",
"GridStack",
"(",
"regula... | 50.480769 | 37.153846 |
def watch_files(self):
"""watch files for changes, if changed, rebuild blog. this thread
will quit if the main process ends"""
try:
while 1:
sleep(1) # check every 1s
try:
files_stat = self.get_files_stat()
except... | [
"def",
"watch_files",
"(",
"self",
")",
":",
"try",
":",
"while",
"1",
":",
"sleep",
"(",
"1",
")",
"# check every 1s",
"try",
":",
"files_stat",
"=",
"self",
".",
"get_files_stat",
"(",
")",
"except",
"SystemExit",
":",
"logger",
".",
"error",
"(",
"\... | 41.03125 | 20.09375 |
def remove_named_query(self, alias, afterwards=None):
"""
remove a named query from the notmuch database.
:param alias: name of shortcut
:type alias: str
:param afterwards: callback to trigger after adding the alias
:type afterwards: callable or None
"""
... | [
"def",
"remove_named_query",
"(",
"self",
",",
"alias",
",",
"afterwards",
"=",
"None",
")",
":",
"if",
"self",
".",
"ro",
":",
"raise",
"DatabaseROError",
"(",
")",
"self",
".",
"writequeue",
".",
"append",
"(",
"(",
"'setconfig'",
",",
"afterwards",
",... | 36.333333 | 15.166667 |
def _set_node_id(self, v, load=False):
"""
Setter method for node_id, mapped from YANG variable /node_id (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_node_id is considered as a private
method. Backends looking to populate this variable should
do so via ... | [
"def",
"_set_node_id",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",... | 105.181818 | 49.818182 |
def ts_bin_op(op_name, ts1, ts2, all=True, fill=None, name=None):
'''Entry point for any arithmetic type function performed on a timeseries
and/or a scalar.
op_name - name of the function to be performed
ts1, ts2 - timeseries or scalars that the function is to performed over
all - whether all d... | [
"def",
"ts_bin_op",
"(",
"op_name",
",",
"ts1",
",",
"ts2",
",",
"all",
"=",
"True",
",",
"fill",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"op",
"=",
"op_get",
"(",
"op_name",
")",
"fill",
"=",
"fill",
"if",
"fill",
"is",
"not",
"None",
... | 36.875 | 22.375 |
def get_data_table(filename):
"""Returns a DataTable instance built from either the filename, or STDIN if filename is None."""
with get_file_object(filename, "r") as rf:
return DataTable(list(csv.reader(rf))) | [
"def",
"get_data_table",
"(",
"filename",
")",
":",
"with",
"get_file_object",
"(",
"filename",
",",
"\"r\"",
")",
"as",
"rf",
":",
"return",
"DataTable",
"(",
"list",
"(",
"csv",
".",
"reader",
"(",
"rf",
")",
")",
")"
] | 53.25 | 4.25 |
def push(self, obj):
"""Pushes a new item to the stack"""
rv = getattr(self._local, "stack", None)
if rv is None:
self._local.stack = rv = []
rv.append(obj)
return rv | [
"def",
"push",
"(",
"self",
",",
"obj",
")",
":",
"rv",
"=",
"getattr",
"(",
"self",
".",
"_local",
",",
"\"stack\"",
",",
"None",
")",
"if",
"rv",
"is",
"None",
":",
"self",
".",
"_local",
".",
"stack",
"=",
"rv",
"=",
"[",
"]",
"rv",
".",
"... | 30.285714 | 12.571429 |
async def persist_checkpoint_async(self, checkpoint, event_processor_context=None):
"""
Persists the checkpoint, and - optionally - the state of the Event Processor.
:param checkpoint: The checkpoint to persist.
:type checkpoint: ~azure.eventprocessorhost.checkpoint.Checkpoint
:... | [
"async",
"def",
"persist_checkpoint_async",
"(",
"self",
",",
"checkpoint",
",",
"event_processor_context",
"=",
"None",
")",
":",
"_logger",
".",
"debug",
"(",
"\"PartitionPumpCheckpointStart %r %r %r %r\"",
",",
"self",
".",
"host",
".",
"guid",
",",
"checkpoint",... | 59.190476 | 31.428571 |
def auth(self, request):
"""
get the auth of the services
:param request: contains the current session
:type request: dict
:rtype: dict
"""
# create app
redirect_uris = '%s://%s%s' % (request.scheme, request.get_host(),
... | [
"def",
"auth",
"(",
"self",
",",
"request",
")",
":",
"# create app",
"redirect_uris",
"=",
"'%s://%s%s'",
"%",
"(",
"request",
".",
"scheme",
",",
"request",
".",
"get_host",
"(",
")",
",",
"reverse",
"(",
"'mastodon_callback'",
")",
")",
"us",
"=",
"Us... | 36.71875 | 15.40625 |
def parse_java_version(cls, version):
"""Parses the java version (given a string or Revision object).
Handles java version-isms, converting things like '7' -> '1.7' appropriately.
Truncates input versions down to just the major and minor numbers (eg, 1.6), ignoring extra
versioning information after t... | [
"def",
"parse_java_version",
"(",
"cls",
",",
"version",
")",
":",
"conversion",
"=",
"{",
"str",
"(",
"i",
")",
":",
"'1.{}'",
".",
"format",
"(",
"i",
")",
"for",
"i",
"in",
"cls",
".",
"SUPPORTED_CONVERSION_VERSIONS",
"}",
"if",
"str",
"(",
"version... | 42.142857 | 22.714286 |
def get_vm_size_completion_list(cmd, prefix, namespace, **kwargs): # pylint: disable=unused-argument
"""Return the intersection of the VM sizes allowed by the ACS SDK with those returned by the Compute Service."""
location = _get_location(cmd.cli_ctx, namespace)
result = get_vm_sizes(cmd.cli_ctx, location... | [
"def",
"get_vm_size_completion_list",
"(",
"cmd",
",",
"prefix",
",",
"namespace",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"location",
"=",
"_get_location",
"(",
"cmd",
".",
"cli_ctx",
",",
"namespace",
")",
"result",
"=",
"get_vm... | 67.833333 | 28.5 |
def et2utc(et, formatStr, prec, lenout=_default_len_out):
"""
Convert an input time from ephemeris seconds past J2000
to Calendar, Day-of-Year, or Julian Date format, UTC.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/et2utc_c.html
:param et: Input epoch, given in ephemeris seconds past ... | [
"def",
"et2utc",
"(",
"et",
",",
"formatStr",
",",
"prec",
",",
"lenout",
"=",
"_default_len_out",
")",
":",
"et",
"=",
"ctypes",
".",
"c_double",
"(",
"et",
")",
"prec",
"=",
"ctypes",
".",
"c_int",
"(",
"prec",
")",
"lenout",
"=",
"ctypes",
".",
... | 36.32 | 16.08 |
def get(self, name, default=None):
'''
Gets the object for "name", or None if there's no such object. If
"default" is provided, return it if no object is found.
'''
session = self.__get_session_from_db()
return session.get(name, default) | [
"def",
"get",
"(",
"self",
",",
"name",
",",
"default",
"=",
"None",
")",
":",
"session",
"=",
"self",
".",
"__get_session_from_db",
"(",
")",
"return",
"session",
".",
"get",
"(",
"name",
",",
"default",
")"
] | 31 | 23 |
def shortcut_update(self, shortcut_id, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/chat/shortcuts#update-shortcut"
api_path = "/api/v2/shortcuts/{shortcut_id}"
api_path = api_path.format(shortcut_id=shortcut_id)
return self.call(api_path, method="PUT", data=data, **kwar... | [
"def",
"shortcut_update",
"(",
"self",
",",
"shortcut_id",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/shortcuts/{shortcut_id}\"",
"api_path",
"=",
"api_path",
".",
"format",
"(",
"shortcut_id",
"=",
"shortcut_id",
")",
"return",
... | 63.8 | 23.8 |
def resize(img, width, height):
"""
更改图片大小,只能更改磁盘空间的大小。
:param img:
:param width:
:param height:
:return: 更改后的图片
"""
return img.resize((width, height), Image.ANTIALIAS) | [
"def",
"resize",
"(",
"img",
",",
"width",
",",
"height",
")",
":",
"return",
"img",
".",
"resize",
"(",
"(",
"width",
",",
"height",
")",
",",
"Image",
".",
"ANTIALIAS",
")"
] | 21.333333 | 14.666667 |
def setcontents(source, identifier, pointer):
"""Patch existing bibliographic record."""
record = Record.get_record(identifier)
Document(record, pointer).setcontents(source) | [
"def",
"setcontents",
"(",
"source",
",",
"identifier",
",",
"pointer",
")",
":",
"record",
"=",
"Record",
".",
"get_record",
"(",
"identifier",
")",
"Document",
"(",
"record",
",",
"pointer",
")",
".",
"setcontents",
"(",
"source",
")"
] | 45.5 | 4 |
def download(ctx):
"""Download blobs or files from Azure Storage"""
settings.add_cli_options(ctx.cli_options, settings.TransferAction.Download)
ctx.initialize(settings.TransferAction.Download)
specs = settings.create_download_specifications(
ctx.cli_options, ctx.config)
del ctx.cli_options
... | [
"def",
"download",
"(",
"ctx",
")",
":",
"settings",
".",
"add_cli_options",
"(",
"ctx",
".",
"cli_options",
",",
"settings",
".",
"TransferAction",
".",
"Download",
")",
"ctx",
".",
"initialize",
"(",
"settings",
".",
"TransferAction",
".",
"Download",
")",... | 39.727273 | 15.363636 |
def no_going_back(confirmation):
"""Show a confirmation to a user.
:param confirmation str: the string the user has to enter in order to
confirm their action.
"""
if not confirmation:
confirmation = 'yes'
prompt = ('This action cannot be undone! Type "%s" or pr... | [
"def",
"no_going_back",
"(",
"confirmation",
")",
":",
"if",
"not",
"confirmation",
":",
"confirmation",
"=",
"'yes'",
"prompt",
"=",
"(",
"'This action cannot be undone! Type \"%s\" or press Enter '",
"'to abort'",
"%",
"confirmation",
")",
"ans",
"=",
"click",
".",
... | 29.352941 | 19.823529 |
def get_object(self):
"""
Returns the row the view is displaying.
You may want to override this if you need to provide non-standard
queryset lookups. Eg if objects are referenced using multiple
keyword arguments in the url conf.
"""
dataframe = self.filter_dataf... | [
"def",
"get_object",
"(",
"self",
")",
":",
"dataframe",
"=",
"self",
".",
"filter_dataframe",
"(",
"self",
".",
"get_dataframe",
"(",
")",
")",
"assert",
"self",
".",
"lookup_url_kwarg",
"in",
"self",
".",
"kwargs",
",",
"(",
"'Expected view %s to be called w... | 34.461538 | 21 |
def visit_Call(self, node, **kwargs):
"""
Handles function calls within code.
Function calls in Python are used to represent interface implementations
in addition to their normal use. If a call appears to mark an
implementation, it gets labeled as such for Doxygen.
"""
... | [
"def",
"visit_Call",
"(",
"self",
",",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"lineNum",
"=",
"node",
".",
"lineno",
"-",
"1",
"# Function calls have one Doxygen-significant special case: interface",
"# implementations.",
"match",
"=",
"AstWalker",
".",
"__impl... | 47.428571 | 19.428571 |
def start_http_server(self, port, args):
"""Start the HTTPServer
:param int port: The port to run the HTTPServer on
:param dict args: Dictionary of arguments for HTTPServer
:rtype: tornado.httpserver.HTTPServer
"""
# Start the HTTP Server
LOGGER.info("Starting T... | [
"def",
"start_http_server",
"(",
"self",
",",
"port",
",",
"args",
")",
":",
"# Start the HTTP Server",
"LOGGER",
".",
"info",
"(",
"\"Starting Tornado v%s HTTPServer on port %i Args: %r\"",
",",
"tornado_version",
",",
"port",
",",
"args",
")",
"http_server",
"=",
... | 38 | 15.866667 |
def boolean_automatic(meshes, operation):
"""
Automatically pick an engine for booleans based on availability.
Parameters
--------------
meshes : list of Trimesh
Meshes to be booleaned
operation : str
Type of boolean, i.e. 'union', 'intersection', 'difference'
Returns
-----... | [
"def",
"boolean_automatic",
"(",
"meshes",
",",
"operation",
")",
":",
"if",
"interfaces",
".",
"blender",
".",
"exists",
":",
"result",
"=",
"interfaces",
".",
"blender",
".",
"boolean",
"(",
"meshes",
",",
"operation",
")",
"elif",
"interfaces",
".",
"sc... | 29.173913 | 19.086957 |
def before_request(request, tracer=None):
"""
Attempts to extract a tracing span from incoming request.
If no tracing context is passed in the headers, or the data
cannot be parsed, a new root span is started.
:param request: HTTP request with `.headers` property exposed
that satisfies a re... | [
"def",
"before_request",
"(",
"request",
",",
"tracer",
"=",
"None",
")",
":",
"if",
"tracer",
"is",
"None",
":",
"# pragma: no cover",
"tracer",
"=",
"opentracing",
".",
"tracer",
"# we need to prepare tags upfront, mainly because RPC_SERVER tag must be",
"# set when sta... | 31.730769 | 18.538462 |
def first_lookup(self, symbol, size=1):
"""
Returns a Grammar Definition with the first n terminal symbols
produced by the input symbol
"""
if isinstance(symbol, (TerminalSymbol, NullSymbol)):
return [symbol.gd]
result = []
for production in self.produ... | [
"def",
"first_lookup",
"(",
"self",
",",
"symbol",
",",
"size",
"=",
"1",
")",
":",
"if",
"isinstance",
"(",
"symbol",
",",
"(",
"TerminalSymbol",
",",
"NullSymbol",
")",
")",
":",
"return",
"[",
"symbol",
".",
"gd",
"]",
"result",
"=",
"[",
"]",
"... | 49.857143 | 20.571429 |
def tag(self, resource_id):
"""Update the request URI to include the Tag for specific retrieval.
Args:
resource_id (string): The tag name.
"""
self._request_uri = '{}/{}'.format(self._request_uri, self.tcex.safetag(resource_id)) | [
"def",
"tag",
"(",
"self",
",",
"resource_id",
")",
":",
"self",
".",
"_request_uri",
"=",
"'{}/{}'",
".",
"format",
"(",
"self",
".",
"_request_uri",
",",
"self",
".",
"tcex",
".",
"safetag",
"(",
"resource_id",
")",
")"
] | 38.142857 | 20 |
def check_coverage():
"""Checks if the coverage is 100%."""
with lcd(settings.LOCAL_COVERAGE_PATH):
total_line = local('grep -n Total index.html', capture=True)
match = re.search(r'^(\d+):', total_line)
total_line_number = int(match.groups()[0])
percentage_line_number = total_lin... | [
"def",
"check_coverage",
"(",
")",
":",
"with",
"lcd",
"(",
"settings",
".",
"LOCAL_COVERAGE_PATH",
")",
":",
"total_line",
"=",
"local",
"(",
"'grep -n Total index.html'",
",",
"capture",
"=",
"True",
")",
"match",
"=",
"re",
".",
"search",
"(",
"r'^(\\d+):... | 44.4 | 14.35 |
def get_node_annotation_layers(docgraph):
"""
WARNING: this is higly inefficient!
Fix this via Issue #36.
Returns
-------
all_layers : set or dict
the set of all annotation layers used for annotating nodes in the given
graph
"""
all_layers = set()
for node_id, node_a... | [
"def",
"get_node_annotation_layers",
"(",
"docgraph",
")",
":",
"all_layers",
"=",
"set",
"(",
")",
"for",
"node_id",
",",
"node_attribs",
"in",
"docgraph",
".",
"nodes_iter",
"(",
"data",
"=",
"True",
")",
":",
"for",
"layer",
"in",
"node_attribs",
"[",
"... | 27.9375 | 16.4375 |
def load_env_from_file(filename):
"""
Read an env file into a collection of (name, value) tuples.
"""
if not os.path.exists(filename):
raise FileNotFoundError("Environment file {} does not exist.".format(filename))
with open(filename) as f:
for lineno, line in enumerate(f):
... | [
"def",
"load_env_from_file",
"(",
"filename",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"raise",
"FileNotFoundError",
"(",
"\"Environment file {} does not exist.\"",
".",
"format",
"(",
"filename",
")",
")",
"with",
"o... | 34.555556 | 19 |
def create_http_method(logic: Callable, http_method: str,
handle_http: Callable, before: Callable = None,
after: Callable = None) -> Callable:
"""Create a handler method to be used in a handler class.
:param callable logic: The underlying function to execute with t... | [
"def",
"create_http_method",
"(",
"logic",
":",
"Callable",
",",
"http_method",
":",
"str",
",",
"handle_http",
":",
"Callable",
",",
"before",
":",
"Callable",
"=",
"None",
",",
"after",
":",
"Callable",
"=",
"None",
")",
"->",
"Callable",
":",
"@",
"fu... | 42.48 | 17.2 |
def item(text, level=0, options=None):
""" Print indented item. """
# Extra line before in each section (unless brief)
if level == 0 and not options.brief:
print('')
# Only top-level items displayed in brief mode
if level == 1 and options.brief:
return
# Four space for each level... | [
"def",
"item",
"(",
"text",
",",
"level",
"=",
"0",
",",
"options",
"=",
"None",
")",
":",
"# Extra line before in each section (unless brief)",
"if",
"level",
"==",
"0",
"and",
"not",
"options",
".",
"brief",
":",
"print",
"(",
"''",
")",
"# Only top-level ... | 42.866667 | 16.066667 |
def __has_language(self, bundleId, languageId):
"""Returns ``True`` if the bundle has the language, ``False`` otherwise
"""
return True if self.__get_language_data(bundleId=bundleId,
languageId=languageId) \
else False | [
"def",
"__has_language",
"(",
"self",
",",
"bundleId",
",",
"languageId",
")",
":",
"return",
"True",
"if",
"self",
".",
"__get_language_data",
"(",
"bundleId",
"=",
"bundleId",
",",
"languageId",
"=",
"languageId",
")",
"else",
"False"
] | 51.666667 | 13 |
def token_cache_pkgs(source=None, release=None):
"""Determine additional packages needed for token caching
@param source: source string for charm
@param release: release of OpenStack currently deployed
@returns List of package to enable token caching
"""
packages = []
if enable_memcache(sou... | [
"def",
"token_cache_pkgs",
"(",
"source",
"=",
"None",
",",
"release",
"=",
"None",
")",
":",
"packages",
"=",
"[",
"]",
"if",
"enable_memcache",
"(",
"source",
"=",
"source",
",",
"release",
"=",
"release",
")",
":",
"packages",
".",
"extend",
"(",
"[... | 37.909091 | 14.272727 |
def delete_refresh_token(self, refresh_token):
"""
Deletes a refresh token after use
:param refresh_token: The refresh token to delete.
"""
access_token = self.fetch_by_refresh_token(refresh_token)
self.mc.delete(self._generate_cache_key(access_token.token))
self.... | [
"def",
"delete_refresh_token",
"(",
"self",
",",
"refresh_token",
")",
":",
"access_token",
"=",
"self",
".",
"fetch_by_refresh_token",
"(",
"refresh_token",
")",
"self",
".",
"mc",
".",
"delete",
"(",
"self",
".",
"_generate_cache_key",
"(",
"access_token",
"."... | 45.375 | 12.625 |
def _validate_num_clusters(num_clusters, initial_centers, num_rows):
"""
Validate the combination of the `num_clusters` and `initial_centers`
parameters in the Kmeans model create function. If the combination is
valid, determine and return the correct number of clusters.
Parameters
----------
... | [
"def",
"_validate_num_clusters",
"(",
"num_clusters",
",",
"initial_centers",
",",
"num_rows",
")",
":",
"## Basic validation",
"if",
"num_clusters",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"num_clusters",
",",
"int",
")",
":",
"raise",
"_ToolkitErro... | 36.482759 | 24.551724 |
def _join_url_dir(self, url, *args):
"""
Join a URL with multiple directories
"""
for path in args:
url = url.rstrip('/') + '/'
url = urljoin(url, path.lstrip('/'))
return url | [
"def",
"_join_url_dir",
"(",
"self",
",",
"url",
",",
"*",
"args",
")",
":",
"for",
"path",
"in",
"args",
":",
"url",
"=",
"url",
".",
"rstrip",
"(",
"'/'",
")",
"+",
"'/'",
"url",
"=",
"urljoin",
"(",
"url",
",",
"path",
".",
"lstrip",
"(",
"'... | 25.777778 | 10.444444 |
def _controller(self):
"""Return the server controller."""
def server_controller(cmd_id, cmd_body, _):
"""Server controler."""
if not self.init_logginig:
# the reason put the codes here is because we cannot get
# kvstore.rank earlier
... | [
"def",
"_controller",
"(",
"self",
")",
":",
"def",
"server_controller",
"(",
"cmd_id",
",",
"cmd_body",
",",
"_",
")",
":",
"\"\"\"Server controler.\"\"\"",
"if",
"not",
"self",
".",
"init_logginig",
":",
"# the reason put the codes here is because we cannot get",
"#... | 40.454545 | 14.909091 |
def snow_partitioning(im, dt=None, r_max=4, sigma=0.4, return_all=False,
mask=True, randomize=True):
r"""
Partitions the void space into pore regions using a marker-based watershed
algorithm, with specially filtered peaks as markers.
The SNOW network extraction algorithm (Sub-Netw... | [
"def",
"snow_partitioning",
"(",
"im",
",",
"dt",
"=",
"None",
",",
"r_max",
"=",
"4",
",",
"sigma",
"=",
"0.4",
",",
"return_all",
"=",
"False",
",",
"mask",
"=",
"True",
",",
"randomize",
"=",
"True",
")",
":",
"tup",
"=",
"namedtuple",
"(",
"'re... | 39.481481 | 23.638889 |
def wait_till_change_set_complete(cfn_client, change_set_id, try_count=25,
sleep_time=.5, max_sleep=3):
""" Checks state of a changeset, returning when it is in a complete state.
Since changesets can take a little bit of time to get into a complete
state, we need to poll i... | [
"def",
"wait_till_change_set_complete",
"(",
"cfn_client",
",",
"change_set_id",
",",
"try_count",
"=",
"25",
",",
"sleep_time",
"=",
".5",
",",
"max_sleep",
"=",
"3",
")",
":",
"complete",
"=",
"False",
"response",
"=",
"None",
"for",
"i",
"in",
"range",
... | 39.5 | 22.477273 |
def _get_parent(self):
""":return: Remote origin as Proxy instance"""
_dir = os.path.dirname(self.path)
if is_repo(_dir):
return Local(_dir)
else:
return None | [
"def",
"_get_parent",
"(",
"self",
")",
":",
"_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"path",
")",
"if",
"is_repo",
"(",
"_dir",
")",
":",
"return",
"Local",
"(",
"_dir",
")",
"else",
":",
"return",
"None"
] | 29.714286 | 12.571429 |
def get_datastores(service_instance, reference, datastore_names=None,
backing_disk_ids=None, get_all_datastores=False):
'''
Returns a list of vim.Datastore objects representing the datastores visible
from a VMware object, filtered by their names, or the backing disk
cannonical name or... | [
"def",
"get_datastores",
"(",
"service_instance",
",",
"reference",
",",
"datastore_names",
"=",
"None",
",",
"backing_disk_ids",
"=",
"None",
",",
"get_all_datastores",
"=",
"False",
")",
":",
"obj_name",
"=",
"get_managed_object_name",
"(",
"reference",
")",
"if... | 44.335938 | 20.398438 |
def subgraph(self, nodelist):
"""Return a CouplingMap object for a subgraph of self.
nodelist (list): list of integer node labels
"""
subcoupling = CouplingMap()
subcoupling.graph = self.graph.subgraph(nodelist)
for node in nodelist:
if node not in subcouplin... | [
"def",
"subgraph",
"(",
"self",
",",
"nodelist",
")",
":",
"subcoupling",
"=",
"CouplingMap",
"(",
")",
"subcoupling",
".",
"graph",
"=",
"self",
".",
"graph",
".",
"subgraph",
"(",
"nodelist",
")",
"for",
"node",
"in",
"nodelist",
":",
"if",
"node",
"... | 37.090909 | 12.454545 |
def _observed_name(field, name):
"""Adjust field name to reflect `dump_to` and `load_from` attributes.
:param Field field: A marshmallow field.
:param str name: Field name
:rtype: str
"""
if MARSHMALLOW_VERSION_INFO[0] < 3:
# use getattr in case we're running... | [
"def",
"_observed_name",
"(",
"field",
",",
"name",
")",
":",
"if",
"MARSHMALLOW_VERSION_INFO",
"[",
"0",
"]",
"<",
"3",
":",
"# use getattr in case we're running against older versions of marshmallow.",
"dump_to",
"=",
"getattr",
"(",
"field",
",",
"\"dump_to\"",
","... | 41.923077 | 13.153846 |
def _ScheduleTasks(self, storage_writer):
"""Schedules tasks.
Args:
storage_writer (StorageWriter): storage writer for a session storage.
"""
logger.debug('Task scheduler started')
self._status = definitions.STATUS_INDICATOR_RUNNING
# TODO: make tasks persistent.
# TODO: protect ta... | [
"def",
"_ScheduleTasks",
"(",
"self",
",",
"storage_writer",
")",
":",
"logger",
".",
"debug",
"(",
"'Task scheduler started'",
")",
"self",
".",
"_status",
"=",
"definitions",
".",
"STATUS_INDICATOR_RUNNING",
"# TODO: make tasks persistent.",
"# TODO: protect task schedu... | 29.795181 | 22.228916 |
def getEditPerson(self, name):
"""
Get an L{EditPersonView} for editing the person named C{name}.
@param name: A person name.
@type name: C{unicode}
@rtype: L{EditPersonView}
"""
view = EditPersonView(self.organizer.personByName(name))
view.setFragmentPa... | [
"def",
"getEditPerson",
"(",
"self",
",",
"name",
")",
":",
"view",
"=",
"EditPersonView",
"(",
"self",
".",
"organizer",
".",
"personByName",
"(",
"name",
")",
")",
"view",
".",
"setFragmentParent",
"(",
"self",
")",
"return",
"view"
] | 28.25 | 15.916667 |
def get_http_rtt(
url: str,
samples: int = 3,
method: str = 'head',
timeout: int = 1,
) -> Optional[float]:
"""
Determine the average HTTP RTT to `url` over the number of `samples`.
Returns `None` if the server is unreachable.
"""
durations = []
for _ in range(sam... | [
"def",
"get_http_rtt",
"(",
"url",
":",
"str",
",",
"samples",
":",
"int",
"=",
"3",
",",
"method",
":",
"str",
"=",
"'head'",
",",
"timeout",
":",
"int",
"=",
"1",
",",
")",
"->",
"Optional",
"[",
"float",
"]",
":",
"durations",
"=",
"[",
"]",
... | 28.916667 | 16.166667 |
def file_transfer_protocol_send(self, target_network, target_system, target_component, payload, force_mavlink1=False):
'''
File transfer message
target_network : Network ID (0 for broadcast) (uint8_t)
target_system : System ID (0 fo... | [
"def",
"file_transfer_protocol_send",
"(",
"self",
",",
"target_network",
",",
"target_system",
",",
"target_component",
",",
"payload",
",",
"force_mavlink1",
"=",
"False",
")",
":",
"return",
"self",
".",
"send",
"(",
"self",
".",
"file_transfer_protocol_encode",
... | 91 | 73.727273 |
def create_feature_array(text, n_pad=21):
"""
Create feature array of character and surrounding characters
"""
n = len(text)
n_pad_2 = int((n_pad - 1)/2)
text_pad = [' '] * n_pad_2 + [t for t in text] + [' '] * n_pad_2
x_char, x_type = [], []
for i in range(n_pad_2, n_pad_2 + n):
... | [
"def",
"create_feature_array",
"(",
"text",
",",
"n_pad",
"=",
"21",
")",
":",
"n",
"=",
"len",
"(",
"text",
")",
"n_pad_2",
"=",
"int",
"(",
"(",
"n_pad",
"-",
"1",
")",
"/",
"2",
")",
"text_pad",
"=",
"[",
"' '",
"]",
"*",
"n_pad_2",
"+",
"["... | 40.25 | 11.85 |
def fill_boot(seqarr, newboot, newmap, spans, loci):
""" fills the new bootstrap resampled array """
## column index
cidx = 0
## resample each locus
for i in xrange(loci.shape[0]):
## grab a random locus's columns
x1 = spans[loci[i]][0]
x2 = spans[loci[i]][1]
... | [
"def",
"fill_boot",
"(",
"seqarr",
",",
"newboot",
",",
"newmap",
",",
"spans",
",",
"loci",
")",
":",
"## column index",
"cidx",
"=",
"0",
"## resample each locus",
"for",
"i",
"in",
"xrange",
"(",
"loci",
".",
"shape",
"[",
"0",
"]",
")",
":",
"## gr... | 29.689655 | 16.965517 |
def as_bin(self):
"""Return the block (or header) as binary."""
f = io.BytesIO()
self.stream(f)
return f.getvalue() | [
"def",
"as_bin",
"(",
"self",
")",
":",
"f",
"=",
"io",
".",
"BytesIO",
"(",
")",
"self",
".",
"stream",
"(",
"f",
")",
"return",
"f",
".",
"getvalue",
"(",
")"
] | 28.6 | 14 |
def _parse_json(self, page, exactly_one):
"""Returns location, (latitude, longitude) from json feed."""
if not page.get('success'):
return None
latitude = page['latitude']
longitude = page['longitude']
place = page.get('place')
address = ", ".join([place['c... | [
"def",
"_parse_json",
"(",
"self",
",",
"page",
",",
"exactly_one",
")",
":",
"if",
"not",
"page",
".",
"get",
"(",
"'success'",
")",
":",
"return",
"None",
"latitude",
"=",
"page",
"[",
"'latitude'",
"]",
"longitude",
"=",
"page",
"[",
"'longitude'",
... | 30.625 | 17.4375 |
def createFolder(self, name):
"""
Creates a folder in which items can be placed. Folders are only
visible to a user and solely used for organizing content within
that user's content space.
"""
url = "%s/createFolder" % self.root
params = {
"f" : "json"... | [
"def",
"createFolder",
"(",
"self",
",",
"name",
")",
":",
"url",
"=",
"\"%s/createFolder\"",
"%",
"self",
".",
"root",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"\"title\"",
":",
"name",
"}",
"self",
".",
"_folders",
"=",
"None",
"return",
"s... | 37.411765 | 14.588235 |
def _reorder(string, salt):
"""Reorders `string` according to `salt`."""
len_salt = len(salt)
if len_salt != 0:
string = list(string)
index, integer_sum = 0, 0
for i in range(len(string) - 1, 0, -1):
integer = ord(salt[index])
integer_sum += integer
... | [
"def",
"_reorder",
"(",
"string",
",",
"salt",
")",
":",
"len_salt",
"=",
"len",
"(",
"salt",
")",
"if",
"len_salt",
"!=",
"0",
":",
"string",
"=",
"list",
"(",
"string",
")",
"index",
",",
"integer_sum",
"=",
"0",
",",
"0",
"for",
"i",
"in",
"ra... | 31.125 | 13.75 |
def __exchange(self, output, timeout=None):
"""Write output to the port and wait for response"""
self.__writeln(output)
self._port.flush()
return self.__expect(timeout=timeout or self._timeout) | [
"def",
"__exchange",
"(",
"self",
",",
"output",
",",
"timeout",
"=",
"None",
")",
":",
"self",
".",
"__writeln",
"(",
"output",
")",
"self",
".",
"_port",
".",
"flush",
"(",
")",
"return",
"self",
".",
"__expect",
"(",
"timeout",
"=",
"timeout",
"or... | 44.2 | 9.8 |
def extract_tar (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a TAR archive with the tarfile Python module."""
try:
with tarfile.open(archive) as tfile:
tfile.extractall(path=outdir)
except Exception as err:
msg = "error extracting %s: %s" % (archive, er... | [
"def",
"extract_tar",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
",",
"outdir",
")",
":",
"try",
":",
"with",
"tarfile",
".",
"open",
"(",
"archive",
")",
"as",
"tfile",
":",
"tfile",
".",
"extractall",
"(",
"... | 40.666667 | 14.555556 |
def email_uncaught_exception(func):
"""
Function decorator for send email with uncaught exceptions to admins.
Email is sent to ``settings.DBBACKUP_FAILURE_RECIPIENTS``
(``settings.ADMINS`` if not defined). The message contains a traceback
of error.
"""
@wraps(func)
def wrapper(*args, **k... | [
"def",
"email_uncaught_exception",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
":",
"l... | 34.047619 | 17.47619 |
def select_qadapter(self, pconfs):
"""
Given a list of parallel configurations, pconfs, this method select an `optimal` configuration
according to some criterion as well as the :class:`QueueAdapter` to use.
Args:
pconfs: :class:`ParalHints` object with the list of parallel c... | [
"def",
"select_qadapter",
"(",
"self",
",",
"pconfs",
")",
":",
"# Order the list of configurations according to policy.",
"policy",
",",
"max_ncpus",
"=",
"self",
".",
"policy",
",",
"self",
".",
"max_cores",
"pconfs",
"=",
"pconfs",
".",
"get_ordered_with_policy",
... | 43.791667 | 27.541667 |
def validate_file_ownership(config):
"""Verify that configuration files are owned by the correct user/group."""
files = config.get('files', {})
for file_name, options in files.items():
for key in options.keys():
if key not in ["owner", "group", "mode"]:
raise RuntimeError... | [
"def",
"validate_file_ownership",
"(",
"config",
")",
":",
"files",
"=",
"config",
".",
"get",
"(",
"'files'",
",",
"{",
"}",
")",
"for",
"file_name",
",",
"options",
"in",
"files",
".",
"items",
"(",
")",
":",
"for",
"key",
"in",
"options",
".",
"ke... | 50.421053 | 14.631579 |
def _bot_identifier(self, message):
"""Return the identifier used to address this bot in this message.
If one is not found, return None.
:param message: a message dict from the slack api.
"""
text = message['text']
formatters = [
lambda identifier: "%s " % ... | [
"def",
"_bot_identifier",
"(",
"self",
",",
"message",
")",
":",
"text",
"=",
"message",
"[",
"'text'",
"]",
"formatters",
"=",
"[",
"lambda",
"identifier",
":",
"\"%s \"",
"%",
"identifier",
",",
"lambda",
"identifier",
":",
"\"%s:\"",
"%",
"identifier",
... | 33.952381 | 21.52381 |
def makeAudibleSong(self):
"""Use mass to render wav soundtrack.
"""
sound0=n.hstack((sy.render(220,d=1.5),
sy.render(220*(2**(7/12)),d=2.5),
sy.render(220*(2**(-5/12)),d=.5),
sy.render(220*(2**(0/12)),d=1.5),
... | [
"def",
"makeAudibleSong",
"(",
"self",
")",
":",
"sound0",
"=",
"n",
".",
"hstack",
"(",
"(",
"sy",
".",
"render",
"(",
"220",
",",
"d",
"=",
"1.5",
")",
",",
"sy",
".",
"render",
"(",
"220",
"*",
"(",
"2",
"**",
"(",
"7",
"/",
"12",
")",
"... | 48.956522 | 15.869565 |
def update_database(self, instance_id, database_id, ddl_statements,
project_id=None,
operation_id=None):
"""
Updates DDL of a database in Cloud Spanner.
:type project_id: str
:param instance_id: The ID of the Cloud Spanner instance.
... | [
"def",
"update_database",
"(",
"self",
",",
"instance_id",
",",
"database_id",
",",
"ddl_statements",
",",
"project_id",
"=",
"None",
",",
"operation_id",
"=",
"None",
")",
":",
"instance",
"=",
"self",
".",
"_get_client",
"(",
"project_id",
"=",
"project_id",... | 46.5 | 20.5 |
def smart_reroot(treefile, outgroupfile, outfile, format=0):
"""
simple function to reroot Newick format tree using ete2
Tree reading format options see here:
http://packages.python.org/ete2/tutorial/tutorial_trees.html#reading-newick-trees
"""
tree = Tree(treefile, format=format)
leaves = ... | [
"def",
"smart_reroot",
"(",
"treefile",
",",
"outgroupfile",
",",
"outfile",
",",
"format",
"=",
"0",
")",
":",
"tree",
"=",
"Tree",
"(",
"treefile",
",",
"format",
"=",
"format",
")",
"leaves",
"=",
"[",
"t",
".",
"name",
"for",
"t",
"in",
"tree",
... | 32.125 | 19 |
def initialize(self, action=None, comment=None, user=None,
restricted=None):
self.action = none_or(action, bool)
"""
Is the text of this revision deleted/suppressed? : `bool`
"""
self.comment = none_or(comment, bool)
"""
Is the comment of this ... | [
"def",
"initialize",
"(",
"self",
",",
"action",
"=",
"None",
",",
"comment",
"=",
"None",
",",
"user",
"=",
"None",
",",
"restricted",
"=",
"None",
")",
":",
"self",
".",
"action",
"=",
"none_or",
"(",
"action",
",",
"bool",
")",
"self",
".",
"com... | 28.666667 | 11.619048 |
def get_indexed_slices(self, column_parent, index_clause, column_predicate, consistency_level):
"""
Returns the subset of columns specified in SlicePredicate for the rows matching the IndexClause
@deprecated use get_range_slices instead with range.row_filter specified
Parameters:
- column_parent
... | [
"def",
"get_indexed_slices",
"(",
"self",
",",
"column_parent",
",",
"index_clause",
",",
"column_predicate",
",",
"consistency_level",
")",
":",
"self",
".",
"_seqid",
"+=",
"1",
"d",
"=",
"self",
".",
"_reqs",
"[",
"self",
".",
"_seqid",
"]",
"=",
"defer... | 37.666667 | 27 |
def compute_structure_environments(self,
excluded_atoms=None,
only_atoms=None,
only_cations=True,
only_indices=None,
maximum_... | [
"def",
"compute_structure_environments",
"(",
"self",
",",
"excluded_atoms",
"=",
"None",
",",
"only_atoms",
"=",
"None",
",",
"only_cations",
"=",
"True",
",",
"only_indices",
"=",
"None",
",",
"maximum_distance_factor",
"=",
"PRESETS",
"[",
"'DEFAULT'",
"]",
"... | 62.432234 | 30.959707 |
def validate_lv_districts(session, nw):
'''Validate if total load of a grid in a pkl file is what expected from LV districts
Parameters
----------
session : sqlalchemy.orm.session.Session
Database session
nw:
The network
Returns
-------
DataFrame
compare_by... | [
"def",
"validate_lv_districts",
"(",
"session",
",",
"nw",
")",
":",
"# config network intern variables",
"nw",
".",
"_config",
"=",
"nw",
".",
"import_config",
"(",
")",
"nw",
".",
"_pf_config",
"=",
"nw",
".",
"import_pf_config",
"(",
")",
"nw",
".",
"_sta... | 46.975207 | 23.520661 |
def _exact_match(response, matches, insensitive, fuzzy):
'''
returns an exact match, if it exists, given parameters
for the match
'''
for match in matches:
if response == match:
return match
elif insensitive and response.lower() == match.lower():
return match
... | [
"def",
"_exact_match",
"(",
"response",
",",
"matches",
",",
"insensitive",
",",
"fuzzy",
")",
":",
"for",
"match",
"in",
"matches",
":",
"if",
"response",
"==",
"match",
":",
"return",
"match",
"elif",
"insensitive",
"and",
"response",
".",
"lower",
"(",
... | 31 | 21.714286 |
def Cylinder(center=(0.,0.,0.), direction=(1.,0.,0.), radius=0.5, height=1.0,
resolution=100, **kwargs):
"""
Create the surface of a cylinder.
Parameters
----------
center : list or np.ndarray
Location of the centroid in [x, y, z]
direction : list or np.ndarray
Di... | [
"def",
"Cylinder",
"(",
"center",
"=",
"(",
"0.",
",",
"0.",
",",
"0.",
")",
",",
"direction",
"=",
"(",
"1.",
",",
"0.",
",",
"0.",
")",
",",
"radius",
"=",
"0.5",
",",
"height",
"=",
"1.0",
",",
"resolution",
"=",
"100",
",",
"*",
"*",
"kwa... | 25.84 | 19.56 |
def get_plugin_class(self, plugin_name):
"""Returns the class registered under the given plugin name."""
try:
return self.plugin_classes[plugin_name]
except KeyError:
raise RezPluginError("Unrecognised %s plugin: '%s'"
% (self.pretty_type_... | [
"def",
"get_plugin_class",
"(",
"self",
",",
"plugin_name",
")",
":",
"try",
":",
"return",
"self",
".",
"plugin_classes",
"[",
"plugin_name",
"]",
"except",
"KeyError",
":",
"raise",
"RezPluginError",
"(",
"\"Unrecognised %s plugin: '%s'\"",
"%",
"(",
"self",
"... | 47.571429 | 15.714286 |
def confirm(self, msg, default=False):
""" Convenience short-hand for self.debugger.intf[-1].confirm """
return self.debugger.intf[-1].confirm(msg, default) | [
"def",
"confirm",
"(",
"self",
",",
"msg",
",",
"default",
"=",
"False",
")",
":",
"return",
"self",
".",
"debugger",
".",
"intf",
"[",
"-",
"1",
"]",
".",
"confirm",
"(",
"msg",
",",
"default",
")"
] | 56.666667 | 7 |
def check_signature(signature, key, data):
"""Compute the HMAC signature and test against a given hash."""
if isinstance(key, type(u'')):
key = key.encode()
digest = 'sha1=' + hmac.new(key, data, hashlib.sha1).hexdigest()
# Covert everything to byte sequences
if isinstance(digest, type(u''... | [
"def",
"check_signature",
"(",
"signature",
",",
"key",
",",
"data",
")",
":",
"if",
"isinstance",
"(",
"key",
",",
"type",
"(",
"u''",
")",
")",
":",
"key",
"=",
"key",
".",
"encode",
"(",
")",
"digest",
"=",
"'sha1='",
"+",
"hmac",
".",
"new",
... | 34.642857 | 14.571429 |
def get_new_names_by_old():
"""Return dictionary, new label name indexed by old label name."""
newdict = {}
for label_type, label_names in Labels.LABEL_NAMES.items():
for oldname in label_names[1:]:
newdict[oldname] = Labels.LABEL_NAMES[label_type][0]
return ... | [
"def",
"get_new_names_by_old",
"(",
")",
":",
"newdict",
"=",
"{",
"}",
"for",
"label_type",
",",
"label_names",
"in",
"Labels",
".",
"LABEL_NAMES",
".",
"items",
"(",
")",
":",
"for",
"oldname",
"in",
"label_names",
"[",
"1",
":",
"]",
":",
"newdict",
... | 40 | 18.5 |
def loadModules(self, *modNames, **userCtx):
"""Load (optionally, compiling) pysnmp MIB modules"""
# Build a list of available modules
if not modNames:
modNames = {}
for mibSource in self._mibSources:
for modName in mibSource.listdir():
... | [
"def",
"loadModules",
"(",
"self",
",",
"*",
"modNames",
",",
"*",
"*",
"userCtx",
")",
":",
"# Build a list of available modules",
"if",
"not",
"modNames",
":",
"modNames",
"=",
"{",
"}",
"for",
"mibSource",
"in",
"self",
".",
"_mibSources",
":",
"for",
"... | 32.97619 | 20.142857 |
def _create_bvals(sorted_dicoms, bval_file):
"""
Write the bvals from the sorted dicom files to a bval file
"""
bvals = []
for index in range(0, len(sorted_dicoms)):
if type(sorted_dicoms[0]) is list:
dicom_headers = sorted_dicoms[index][0]
else:
dicom_headers... | [
"def",
"_create_bvals",
"(",
"sorted_dicoms",
",",
"bval_file",
")",
":",
"bvals",
"=",
"[",
"]",
"for",
"index",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"sorted_dicoms",
")",
")",
":",
"if",
"type",
"(",
"sorted_dicoms",
"[",
"0",
"]",
")",
"is",
... | 34.8 | 13.333333 |
def is_correct(self, question_id):
"""is the question answered correctly"""
response = self.get_response(question_id=question_id)
if response.is_answered():
item = self._get_item(response.get_item_id())
return item.is_response_correct(response)
raise errors.Illega... | [
"def",
"is_correct",
"(",
"self",
",",
"question_id",
")",
":",
"response",
"=",
"self",
".",
"get_response",
"(",
"question_id",
"=",
"question_id",
")",
"if",
"response",
".",
"is_answered",
"(",
")",
":",
"item",
"=",
"self",
".",
"_get_item",
"(",
"r... | 46 | 9.714286 |
def _init():
"""Initialize the furious context and registry.
NOTE: Do not directly run this method.
"""
# If there is a context and it is initialized to this request,
# return, otherwise reinitialize the _local_context.
if (hasattr(_local_context, '_initialized') and
_local_context.... | [
"def",
"_init",
"(",
")",
":",
"# If there is a context and it is initialized to this request,",
"# return, otherwise reinitialize the _local_context.",
"if",
"(",
"hasattr",
"(",
"_local_context",
",",
"'_initialized'",
")",
"and",
"_local_context",
".",
"_initialized",
"==",
... | 35.181818 | 21.363636 |
def write_status(self, new_status, num_bytes=2, set_non_volatile=False):
"""Write up to 24 bits (num_bytes) of new status register
num_bytes can be 1, 2 or 3.
Not all flash supports the additional commands to write the
second and third byte of the status register. When writing 2
... | [
"def",
"write_status",
"(",
"self",
",",
"new_status",
",",
"num_bytes",
"=",
"2",
",",
"set_non_volatile",
"=",
"False",
")",
":",
"SPIFLASH_WRSR",
"=",
"0x01",
"SPIFLASH_WRSR2",
"=",
"0x31",
"SPIFLASH_WRSR3",
"=",
"0x11",
"SPIFLASH_WEVSR",
"=",
"0x50",
"SPIF... | 40.666667 | 24.111111 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.